test: remove 79 low-value suites (#42564)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-14 17:33:48 -08:00
committed by GitHub
co-authored by OrcaWin
parent c89329aa18
commit 089887316f
83 changed files with 17 additions and 4409 deletions
File diff suppressed because one or more lines are too long
@@ -36,7 +36,6 @@
"config/scripts/static-analysis/repository-layout/check-root-directory-entries.test.mjs": 936,
"config/scripts/static-analysis/process-boundaries/check-runtime-electron-ratchet-graph.test.mjs": 160,
"config/scripts/static-analysis/process-boundaries/check-runtime-electron-ratchet.test.mjs": 3540,
"config/scripts/daemon-protocol/admission/check-runtime-launcher-protocol-ratchet.test.mjs": 212,
"config/scripts/ci/unit-selection/check-test-file-runners.test.mjs": 267,
"config/scripts/ci/workflow-contracts/ci-closed-pr-cancellation.test.mjs": 112,
"config/scripts/ci/workflow-contracts/ci-draft-pr-admission.test.mjs": 546,
@@ -57,7 +56,6 @@
"config/scripts/ci/sharding/ci-unit-timing-reporter.test.mjs": 374,
"config/scripts/ci/workflow-contracts/cloud-security-history-workflow.test.mjs": 357,
"config/scripts/runtime-verification/codex-account/codex-primary-home-tripwire.test.ts": 378,
"config/scripts/orcad-distribution/template/compact-packaged-orcad-ripgrep.test.mjs": 1153,
"config/scripts/desktop-build/output-contracts/dark-build-switches.test.mjs": 52,
"config/scripts/dependency-security/audit-tools/dependency-security-audit.test.mjs": 187,
"config/scripts/dependency-security/audit-tools/dependency-security-patches.test.mjs": 50,
@@ -584,7 +582,6 @@
"src/main/ai-vault/scanners/devin/session-scanner-devin-dedup.test.ts": 501,
"src/main/ai-vault/scanners/devin/session-scanner-devin-parser.test.ts": 283,
"src/main/ai-vault/session-scanner-discovery-pipeline.test.ts": 244,
"src/main/ai-vault/scanners/droid/session-scanner-droid-parser.test.ts": 166,
"src/main/ai-vault/session-scanner-first-user-prompt.test.ts": 60,
"src/main/ai-vault/scanners/session-scanner-graph-parsers.test.ts": 176,
"src/main/ai-vault/scanners/grok/session-scanner-grok-parser.test.ts": 199,
@@ -691,7 +688,6 @@
"src/main/automations/automation-zero-grace-tick-latency.test.ts": 2108,
"src/main/automations/dispatch/dispatch-refusal-wsl-move.test.ts": 577,
"src/main/automations/external-managers/external-automation-manager-cache.test.ts": 70,
"src/main/automations/external-managers/external-automation-probe-scheduler.test.ts": 97,
"src/main/automations/external-managers/scoped-external-automations.test.ts": 391,
"src/main/automations/run-terminal-retention.test.ts": 112,
"src/main/automations/automation-workspace-create.test.ts": 50,
@@ -1484,7 +1480,6 @@
"src/main/git/command-runner/git-admission-storm-measurement.test.ts": 264,
"src/main/git/command-runner/git-command-resolution-windows-checkout.test.ts": 133,
"src/main/git/command-runner/git-exec-admission-lifetime.test.ts": 718,
"src/main/git/command-runner/git-operation-executor.test.ts": 59,
"src/main/git/command-runner/git-spawn-wsl-admission.test.ts": 153,
"src/main/git/command-runner/missing-git-spawn-cwd.test.ts": 218,
"src/main/git/command-runner/spawned-command-tree-kill.test.ts": 81,
@@ -1719,7 +1714,6 @@
"src/main/host/deferred-secret-protection-report.test.ts": 81,
"src/main/host/electron-http-client.test.ts": 496,
"src/main/host/electron-manual-redirect-fetch.test.ts": 52,
"src/main/host/safe-storage-availability.test.ts": 51,
"src/main/host/secret-protection-report.test.ts": 59,
"src/main/i18n/main-i18n-lazy-locale.test.ts": 518,
"src/shared/image-file-signature.test.ts": 47,
@@ -1785,7 +1779,6 @@
"src/main/ipc/filesystem/filesystem-wsl-stopped-distro-reads.test.ts": 1284,
"src/main/ipc/filesystem/filesystem.test.ts": 2043,
"src/main/ipc/filesystem/local-disk-write-precondition.test.ts": 8407,
"src/main/ipc/filesystem/local-file-range-read.test.ts": 56,
"src/main/ipc/filesystem/local-regular-file-read.test.ts": 78,
"src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-child-registry.test.ts": 93,
"src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse.test.ts": 54,
@@ -1909,7 +1902,6 @@
"src/main/ipc/ssh/ssh-host-user-disconnect.test.ts": 4734,
"src/main/ipc/ssh/ssh-passphrase.test.ts": 135,
"src/main/ipc/ssh/ssh.test.ts": 6905,
"src/main/ipc/terminal-preview-output-stream.test.ts": 53,
"src/main/ipc/terminal-render-desync-evidence.test.ts": 78,
"src/main/ipc/terminal-startup-color-query-replies.test.ts": 265,
"src/main/ipc/filesystem/watcher-process/root-paths/watcher-event-root-path-rewrite.test.ts": 48,
@@ -2075,7 +2067,6 @@
"src/main/native-chat/agent-session-journal/store-lifecycle/journal-settlement-contracts.test.ts": 3953,
"src/main/native-chat/agent-session-journal/durable-rows/journal-storage-admission.test.ts": 1276,
"src/main/native-chat/agent-session-journal/replay/journal-streaming-replay.test.ts": 1394,
"src/main/native-chat/agent-session-journal/queued-messages/queued-message-context-clear.test.ts": 60,
"src/main/native-chat/agent-session-journal/queued-messages/queued-message-edit-leases.test.ts": 79,
"src/main/native-chat/agent-session-timeline/provider-timeline-assembler-earlier-turn-end.test.ts": 686,
"src/main/native-chat/agent-session-timeline/provider-timeline-assembler-held-rows.test.ts": 799,
@@ -2194,7 +2185,6 @@
"src/main/node-runtime/runtime-archive-download.test.ts": 149,
"src/main/notebook/notebook-kernel.test.ts": 151,
"src/main/observability/bundle.test.ts": 696,
"src/main/observability/diagnostic-upload-http.test.ts": 56,
"src/main/observability/local-file-sink.test.ts": 1124,
"src/main/observability/redactor-environment-lines.test.ts": 46,
"src/main/observability/redactor.test.ts": 80,
@@ -2656,12 +2646,10 @@
"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts": 140,
"src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts": 136,
"src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts": 184,
"src/main/runtime/browser-host/reconciliation/browser-host-page-placement-replacement.test.ts": 159,
"src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts": 169,
"src/main/runtime/browser-host/reconciliation/browser-host-page-reconciliation-preconditions.test.ts": 129,
"src/main/runtime/browser-host/reconciliation/browser-host-page-retirement.test.ts": 59,
"src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts": 5293,
"src/main/runtime/browser/screencast/browser-screencast-driver-attribution.test.ts": 5015,
"src/main/runtime/browser/screencast/browser-screencast-renderer-throttle-lease.test.ts": 5665,
"src/main/runtime/browser/tabs/browser-session-tab-selection-snapshot.test.ts": 45,
"src/main/runtime/browser/screencast/browser-screencasts.test.ts": 632,
@@ -2673,7 +2661,6 @@
"src/main/runtime/agent-session/lifecycle/claude-structured-failed-start-resume.test.ts": 2454,
"src/main/runtime/agent-session/lifecycle/claude-structured-resumed-start-failure.test.ts": 4153,
"src/main/runtime/agent-session/lifecycle/claude-structured-startup-fault-is-not-an-exit.test.ts": 2741,
"src/main/runtime/terminal/wait/claude-worker-start-readiness.test.ts": 4076,
"src/main/runtime/browser/client-pages/client-hosted-browser-page-persistence.integration.test.ts": 4022,
"src/main/runtime/browser/client-pages/client-hosted-browser-page-persistence.test.ts": 315,
"src/main/runtime/browser/client-pages/client-hosted-browser-row-publication.test.ts": 73,
@@ -2919,7 +2906,6 @@
"src/main/runtime/terminal/launch/qoder-mobile-resume-adoption.test.ts": 22896,
"src/main/runtime/terminal/identity/quarter-circle-title-send-authorization.test.ts": 25181,
"src/main/runtime/terminal/lifecycle/queued-terminal-graph-exit.test.ts": 4008,
"src/main/runtime/terminal/output/recent-pty-output-retention.test.ts": 114,
"src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts": 7614,
"src/main/runtime/browser/screencast/remote-browser-screencast-frame-admission.test.ts": 316,
"src/main/runtime/terminal/driver/remote-desktop-driver.test.ts": 4334,
@@ -3397,7 +3383,6 @@
"src/main/pty/shell-startup/shell-startup-identity-scanner.test.ts": 39,
"src/main/pty/shell-startup/shell-startup-output-scanner.test.ts": 58,
"src/main/pty/shell-startup/shell-wrapper-content-address.test.ts": 49,
"src/main/filesystem/sidecar-snapshot-file.test.ts": 65,
"src/main/source-control/hosted-review-azure-devops.integration.test.ts": 818,
"src/main/source-control/hosted-review-base-ref-suffix.test.ts": 474,
"src/main/source-control/hosted-review-bitbucket.integration.test.ts": 1172,
@@ -3719,7 +3704,6 @@
"src/main/window/dropped-path-preparation-ipc.test.ts": 129,
"src/main/window/dropped-path-preparation.test.ts": 602,
"src/main/window/foreground-activation-policy.test.ts": 61,
"src/main/window/history-gc-worktree-ids.test.ts": 384,
"src/main/window/host-frame-navigation-guard.test.ts": 105,
"src/main/window/host-frame-permission-policy.test.ts": 100,
"src/main/window/mac-app-paste-input.test.ts": 85,
@@ -3956,7 +3940,6 @@
"src/renderer/src/components/browser-pane/annotate/browser-grab-toast-owner-cleanup.test.tsx": 1007,
"src/renderer/src/components/browser-pane/annotate/markup-gesture.test.ts": 95,
"src/renderer/src/components/browser-pane/annotate/markup-shape-hit-test.test.ts": 76,
"src/renderer/src/components/browser-pane/annotate/markup-shape-render.test.ts": 64,
"src/renderer/src/components/browser-pane/annotate/use-browser-page-annotation-send.test.tsx": 1485,
"src/renderer/src/components/browser-pane/annotate/useMarkupPointerHandlers.test.ts": 280,
"src/renderer/src/components/browser-pane/assemble-chrome/BrowserPane.webview-preferences.test.ts": 1920,
@@ -4111,8 +4094,6 @@
"src/renderer/src/components/editor/markdown-export-html.test.ts": 47,
"src/renderer/src/components/editor/markdown/navigation/markdown-navigation-details.test.ts": 626,
"src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-client.test.ts": 65,
"src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-search-budget.test.ts": 400,
"src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-search-cache.test.ts": 588,
"src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document.test.ts": 1670,
"src/renderer/src/components/editor/markdown-preview/links/markdown-preview-local-images.test.ts": 1639,
"src/renderer/src/components/editor/markdown-preview/review/markdown-preview-review-frame-lifecycle.test.tsx": 642,
@@ -4317,7 +4298,6 @@
"src/renderer/src/components/native-chat/viewport/rail/native-chat-active-rail-item.test.ts": 62,
"src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-host.test.tsx": 8140,
"src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-identity.test.tsx": 1880,
"src/renderer/src/components/native-chat/appearance/native-chat-appearance-write.test.ts": 329,
"src/renderer/src/components/native-chat/attachments/uploads/native-chat-attachment-upload.test.ts": 1614,
"src/renderer/src/components/native-chat/conversation/slots/native-chat-compaction-visibility.test.ts": 363,
"src/renderer/src/components/native-chat/composer/editor/native-chat-composer-composition.test.tsx": 2961,
@@ -4350,7 +4330,6 @@
"src/renderer/src/components/native-chat/queue/editing/native-chat-queued-edit-draft.test.ts": 649,
"src/renderer/src/components/native-chat/viewport/rail/native-chat-rail-outline-parity.test.ts": 497,
"src/renderer/src/components/native-chat/attachments/uploads/native-chat-resolved-path-ownership.test.ts": 1749,
"src/renderer/src/components/native-chat/drafts/native-chat-sent-prompt-history.test.ts": 217,
"src/renderer/src/components/native-chat/session/terminal/assembly/native-chat-session-assembler.test.ts": 221,
"src/renderer/src/components/native-chat/session/options/catalog/native-chat-session-option-enrichment.test.ts": 2042,
"src/renderer/src/components/native-chat/session/terminal/read/native-chat-session-transport.test.ts": 381,
@@ -4390,7 +4369,6 @@
"src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session.test.ts": 2218,
"src/renderer/src/components/native-chat/composer/pickers/use-native-chat-mention-files.test.tsx": 2162,
"src/renderer/src/components/native-chat/viewport/rail/use-native-chat-message-rail.test.ts": 655,
"src/renderer/src/components/native-chat/markdown/use-native-chat-paced-text.remount.test.tsx": 327,
"src/renderer/src/components/native-chat/paste/use-native-chat-paste-lifetime.test.tsx": 567,
"src/renderer/src/components/native-chat/paste/use-native-chat-pasted-text-file.test.tsx": 2385,
"src/renderer/src/components/native-chat/session/terminal/delivery/use-native-chat-pending-delivery.test.tsx": 457,
@@ -4431,7 +4409,6 @@
"src/renderer/src/components/plugins/page/PluginAddsSection.test.tsx": 2043,
"src/renderer/src/components/plugins/page/PluginCommandReplacementRow.test.tsx": 1926,
"src/renderer/src/components/plugins/page/PluginDetailPage.test.tsx": 3367,
"src/renderer/src/components/plugins/state/use-plugin-contribution-source.test.tsx": 1935,
"src/renderer/src/components/plugins/state/use-plugin-install-link.test.tsx": 518,
"src/renderer/src/components/plugins/view/plugin-view-acts.test.tsx": 3241,
"src/renderer/src/components/plugins/view/plugin-view-data-acts.test.tsx": 3002,
@@ -4640,7 +4617,6 @@
"src/renderer/src/components/sidebar/workspace-board/projection/workspace-board-task-status-sync.test.ts": 378,
"src/renderer/src/components/sidebar/workspace-actions/deletion/workspace-delete-lineage.test.ts": 51,
"src/renderer/src/components/sidebar/workspace-board/search/workspace-kanban-search.test.ts": 176,
"src/renderer/src/components/sidebar/workspace-actions/context-menu/workspace-lineage-menu-actions.test.ts": 235,
"src/renderer/src/components/sidebar/workspace-card/review/workspace-reference-detail-read.test.ts": 662,
"src/renderer/src/components/sidebar/workspace-card/review/workspace-reference-refresh-targets.test.ts": 945,
"src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-activity-summary.test.ts": 577,
@@ -4729,7 +4705,6 @@
"src/renderer/src/components/task-page/jira/task-page-jira-linked-issues.test.ts": 204,
"src/renderer/src/components/task-page/jira/filters/use-task-page-jira-project-scope.test.tsx": 2642,
"src/renderer/src/components/task-page/jira/filters/use-task-page-jira-quick-filters.test.tsx": 1466,
"src/renderer/src/components/task-page/jira/filters/use-task-page-jira-saved-filters.test.tsx": 1501,
"src/renderer/src/components/task-page/jira/creation/use-task-page-jira-summary-generation.test.tsx": 571,
"src/renderer/src/components/task-page/linear/task-page-linear-creation-lifetime.test.tsx": 3315,
"src/renderer/src/components/task-page/linear/issues/task-page-linear-in-orca-issues.test.ts": 430,
@@ -4809,7 +4784,6 @@
"src/renderer/src/components/terminal-pane/pty-connection/spawn/main-pane-start-wait.test.ts": 76,
"src/renderer/src/components/terminal-pane/pty-connection/serialization/pane-serializer-register.test.ts": 123,
"src/renderer/src/components/terminal-pane/pty-connection/output-restore/snapshot-covered-terminal-queries.test.ts": 150,
"src/renderer/src/components/terminal-pane/pty-connection/output/terminal-input-echo-delay.test.ts": 132,
"src/renderer/src/components/terminal-pane/pty-connection/host-ownership/unserved-ssh-pane-bridge.test.ts": 70,
"src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-delivery-resync.test.ts": 85,
"src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-pi-routing.test.ts": 1362,
@@ -4913,7 +4887,6 @@
"src/renderer/src/components/terminal-pane/links/files/terminal-link-provider-markdown.test.ts": 1480,
"src/renderer/src/components/terminal-pane/links/gestures/terminal-link-pty-mouse-suppression.test.ts": 574,
"src/renderer/src/components/terminal-pane/links/files/terminal-link-same-id-ssh-file-host.test.ts": 879,
"src/renderer/src/components/terminal-pane/layout/reconciliation/terminal-live-layout-reconciliation.test.ts": 74,
"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts": 52,
"src/renderer/src/components/terminal-pane/input/file-drop/terminal-pane-element-file-drop.test.tsx": 1748,
"src/renderer/src/components/terminal-pane/layout/reconciliation/terminal-pane-frame-reconciliation.test.ts": 903,
@@ -4921,7 +4894,6 @@
"src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-commit.test.ts": 2090,
"src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-move.test.ts": 2147,
"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts": 473,
"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-registry.test.ts": 245,
"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-sleep-preserved-exit.test.ts": 399,
"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-sole-newborn-exit.test.ts": 402,
"src/renderer/src/components/terminal-pane/emulation/terminal-parser-handler-guard.test.ts": 55,
@@ -5160,10 +5132,8 @@
"src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-setup.test.tsx": 3435,
"src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.test.ts": 99,
"src/renderer/src/lib/work-items/linked-work-item-context.test.ts": 64,
"src/renderer/src/lib/editor/monaco/monaco-editor-gutter-disposal.test.ts": 295,
"src/renderer/src/lib/monaco-languages/monarch-embed-entry-recursion.test.ts": 697,
"src/renderer/src/lib/monaco-languages/plugin-grammar-worker-client.test.ts": 198,
"src/renderer/src/lib/monaco-languages/plugin-syntax-slot-pool.test.ts": 65,
"src/renderer/src/lib/monaco-languages/register-astro.test.ts": 267,
"src/renderer/src/lib/monaco-languages/register-jsonl.test.ts": 259,
"src/renderer/src/lib/monaco-languages/register-svelte.test.ts": 319,
@@ -5184,7 +5154,6 @@
"src/renderer/src/lib/text-input/paste/paste-payload-metadata.test.ts": 53,
"src/renderer/src/lib/path.test.ts": 55,
"src/renderer/src/lib/plugin-icons/plugin-icon-svg.test.ts": 231,
"src/renderer/src/lib/source-control/review/pr-bot-author-overrides.test.ts": 349,
"src/renderer/src/lib/source-control/review/comments/pr-comment-thread-resolution.test.ts": 48,
"src/renderer/src/lib/editor/file-operations/remap-open-editor-tabs-for-path-change.test.ts": 2178,
"src/renderer/src/lib/renderer-agent-status-observation-ingress.test.ts": 81,
@@ -5231,7 +5200,6 @@
"src/renderer/src/lib/workspace/ownership/worktree-live-terminal-surface-owners.test.ts": 266,
"src/renderer/src/lib/workspace/ownership/worktree-operation-route.test.ts": 342,
"src/renderer/src/lib/workspace/search/worktrees/worktree-palette-comment-snippet.test.ts": 53,
"src/renderer/src/lib/workspace/search/worktrees/worktree-palette-task-url-match.test.ts": 165,
"src/renderer/src/lib/workspace/activation/worktree-reactivation-preserved-pane-replacement.test.ts": 2268,
"src/renderer/src/lib/workspace/activation/worktree-reactivation-tab-forkbomb.test.ts": 4131,
"src/renderer/src/lib/workspace/ownership/worktree-runtime-owner-index.detected.test.ts": 121,
@@ -5698,7 +5666,6 @@
"src/shared/ai-vault/search/ai-vault-search-status-fallback.test.ts": 175,
"src/shared/ai-vault/scanning/ai-vault-session-depth.test.ts": 78,
"src/shared/ai-vault/session-display/ai-vault-session-filters.test.ts": 176,
"src/shared/ai-vault/resume/ai-vault-ssh-resume-target.test.ts": 84,
"src/shared/ansi-escape-sequences-consumers.test.ts": 140,
"src/shared/antigravity-generation-plan.test.ts": 122,
"src/shared/automatic-work-run-marker.test.ts": 93,
@@ -5801,7 +5768,6 @@
"src/shared/git/remotes/git-remote-error.test.ts": 88,
"src/shared/git/remotes/git-remote-identity.test.ts": 56,
"src/shared/git/remotes/git-remote-url-index.test.ts": 47,
"src/shared/git/compatibility/git-resolution-config-snapshot.test.ts": 72,
"src/shared/git/commands/git-ssh-policy-env.test.ts": 221,
"src/shared/git/status/git-status-branch-line-total-cache.test.ts": 82,
"src/shared/git/status/git-status-conflict-entries.test.ts": 56,
@@ -5868,12 +5834,10 @@
"src/shared/managed-orcad-execution-host.test.ts": 170,
"src/shared/managed-orcad-ssh-owner.test.ts": 42,
"src/shared/manual-repo-order.test.ts": 44,
"src/shared/map-settled-with-concurrency.test.ts": 61,
"src/shared/map-with-concurrency.test.ts": 50,
"src/shared/markdown-document-listing-limits.test.ts": 44,
"src/shared/markdown-document-paths.test.ts": 51,
"src/shared/mcp-config.test.ts": 92,
"src/shared/mermaid-flowchart-contrast.test.ts": 180,
"src/shared/remote-runtime/e2ee/mobile-e2ee-v2-contract.test.ts": 56,
"src/shared/remote-runtime/e2ee/mobile-e2ee-v2-framing.test.ts": 48,
"src/shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule.test.ts": 125,
@@ -5922,7 +5886,6 @@
"src/shared/native-chat/transcript/native-chat-text-reveal.test.ts": 48,
"src/shared/native-chat/transcript/native-chat-transcript-contracts.test.ts": 715,
"src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts": 182,
"src/shared/native-chat/transcript/native-chat-transcript-retention.test.ts": 58,
"src/shared/native-chat/transcript/native-chat-turn-activity.test.ts": 119,
"src/shared/native-chat/transcript/native-chat-turn-fold.test.ts": 192,
"src/shared/native-chat/transcript/native-chat-turn-status.test.ts": 69,
@@ -5933,7 +5896,6 @@
"src/shared/network-proxy.test.ts": 44,
"src/shared/network/manual-address.test.ts": 68,
"src/shared/new-workspace-dialog-repo.test.ts": 50,
"src/shared/new-workspace/smart-workspace-linear-intent.test.ts": 64,
"src/shared/new-workspace/smart-workspace-url-source-results.test.ts": 67,
"src/shared/new-workspace/work-item-lookup-text.test.ts": 56,
"src/shared/new-workspace/workspace-source.test.ts": 68,
@@ -5962,7 +5924,6 @@
"src/shared/opencode-plugin-permissions.test.ts": 121,
"src/shared/opencode-tui-config-registration.test.ts": 91,
"src/shared/opencode-tui-plugin-install.test.ts": 82,
"src/shared/openssh-default-shell.test.ts": 54,
"src/shared/orca-hook-setup-config.test.ts": 38,
"src/shared/orca-session-address.test.ts": 154,
"src/shared/orca-yaml-alias-bounds.test.ts": 425,
@@ -5991,7 +5952,6 @@
"src/shared/palette-match/palette-match-core.test.ts": 104,
"src/shared/palette-match/palette-ranking.test.ts": 46,
"src/shared/pan-zoom-view.test.ts": 39,
"src/shared/physical-exit-tracker.test.ts": 46,
"src/shared/plugin-theme-settings.test.ts": 55,
"src/shared/plugins/approval/plugin-consent-fingerprint.test.ts": 197,
"src/shared/plugins/approval/plugin-update-access-growth.test.ts": 189,
@@ -6030,11 +5990,9 @@
"src/shared/plugins/manifest/plugin-manifest.test.ts": 234,
"src/shared/plugins/view/plugin-editor-shot-acts.test.ts": 112,
"src/shared/plugins/workers/plugin-hook-chain.test.ts": 182,
"src/shared/portuguese-ui-language-migration.test.ts": 264,
"src/shared/posix-wait-status.test.ts": 40,
"src/shared/powershell-native-argument.test.ts": 34,
"src/shared/powershell-native-argument.windows.test.ts": 67,
"src/shared/source-control/review-comments/pr-bot-author-overrides.test.ts": 76,
"src/shared/source-control/checks/pr-checks-fix-prompt.test.ts": 93,
"src/shared/preferred-git-remote.test.ts": 42,
"src/shared/priority-semaphore.test.ts": 43,
@@ -6146,7 +6104,6 @@
"src/shared/secure-file-fsync-flags.test.ts": 81,
"src/shared/secure-file-windows.test.ts": 190,
"src/shared/secure-file.test.ts": 69,
"src/shared/secure-path-hardening-retry-budget.test.ts": 63,
"src/shared/secure-path-windows-acl.win32.test.ts": 67,
"src/shared/session-tab-placement.test.ts": 53,
"src/shared/session-tabs-tab-delta.test.ts": 59,
@@ -6167,12 +6124,10 @@
"src/shared/sidebar-list/stamp-order.test.ts": 86,
"src/shared/sidebar-list/text-order.test.ts": 59,
"src/shared/sidebar-list/workspace-review-facts.test.ts": 191,
"src/shared/skill-metadata.test.ts": 41,
"src/shared/skill-package-manifest.test.ts": 188,
"src/shared/skill-path-containment.test.ts": 49,
"src/shared/sleeping-record-legacy-pane-key.test.ts": 59,
"src/shared/source-control/listing/source-control-discard-all-sequence.test.ts": 50,
"src/shared/source-control/recovery/source-control-push-failure.test.ts": 51,
"src/shared/source-scan/source-tree-scan.test.ts": 50,
"src/shared/source-scan/source-tree-walk.test.ts": 62,
"src/shared/ssh-pending-pty-kill.test.ts": 43,
@@ -6200,7 +6155,6 @@
"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-tail-retention.test.ts": 220,
"src/shared/terminal/links/terminal-links-cjk.test.ts": 116,
"src/shared/terminal/links/terminal-links.test.ts": 299,
"src/shared/terminal/links/terminal-markdown-file-links.test.ts": 67,
"src/shared/terminal/output/terminal-mode-2031-final-state.test.ts": 96,
"src/shared/terminal/protocol/input-modes/terminal-mode-reset-profiles.test.ts": 79,
"src/shared/terminal/protocol/input-modes/terminal-mouse-encoding.test.ts": 63,
@@ -6212,7 +6166,6 @@
"src/shared/terminal/protocol/escape/terminal-partial-escape-tail-ground-scan.test.ts": 59,
"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts": 79,
"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts": 65,
"src/shared/file-links/file-link-path-normalization.test.ts": 50,
"src/shared/terminal/protocol/queries/terminal-query-reply.test.ts": 94,
"src/shared/terminal/protocol/queries/terminal-reply-query-extraction.test.ts": 46,
"src/shared/terminal/protocol/queries/terminal-reply-query-scan.test.ts": 51,
@@ -6231,7 +6184,6 @@
"src/shared/tmux-agent-hook-owner.test.ts": 423,
"src/shared/tmux-client-attachment.test.ts": 50,
"src/shared/tmux-hook-refresh-retirement.test.ts": 608,
"src/shared/tmux-host-attachment-probe.test.ts": 69,
"src/shared/agent-launch/permissions/tui-agent-auto-permissions.test.ts": 293,
"src/shared/agent-launch/startup/tui-agent-launch-command-argument-values.test.ts": 266,
"src/shared/agent-launch/startup/tui-agent-launch-command-override.test.ts": 63,
@@ -6376,16 +6328,12 @@
"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/alt-screen-frame.unit.test.ts": 100,
"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-launch-args.unit.test.ts": 58,
"tests/e2e/helpers/electron-main-evaluate-retry.unit.test.ts": 49,
"tests/e2e/helpers/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-runtime-environment.unit.test.ts": 67,
"tests/e2e/helpers/paired-client-window-reveal.unit.test.ts": 57,
"tests/e2e/helpers/persisted-profile-state.unit.test.ts": 402,
"tests/e2e/helpers/wsl-terminate-retry.unit.test.ts": 60,
@@ -6429,13 +6377,10 @@
"tests/tools/omp-config-root-relay-shell.test.mjs": 297,
"tests/tools/relay-bench/phone-e2ee-desktop-parity.test.mjs": 111,
"tests/tools/relay-bench/region-probe-replay.test.mjs": 79,
"tests/tools/relay-bench/relay-bench-invocation.test.mjs": 85,
"tests/tools/relay-bench/relay-bench-state-file.test.mjs": 60,
"tests/tools/relay-bench/relay-phone-connect-bench.test.mjs": 93,
"tests/tools/win-update-e2e/app-shutdown.test.mjs": 726,
"tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-oracle.test.mjs": 52,
"tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-probe.test.mjs": 261,
"tests/tools/windows-pty-native-capability-smoke/run.test.mjs": 49,
"src/main/skills/sharing/agent-skill-selection.test.ts": 103,
"src/main/skills/bundled-skill-install/bundled-skill-auto-update-eligibility.test.ts": 400,
"src/main/skills/bundled-skill-install/bundled-skill-backup-permissions.test.ts": 246,
@@ -6461,7 +6406,6 @@
"src/main/skills/skill-delete/skill-delete-plan.test.ts": 239,
"src/main/skills/skill-delete/skill-delete-recovery.test.ts": 178,
"src/main/skills/skill-delete/skill-deletion.test.ts": 524,
"src/main/skills/filesystem/skill-transaction-staging-visibility.test.ts": 48,
"src/main/skills/filesystem/skill-wsl-enumeration-protocol.test.ts": 52,
"src/main/skills/discovery/skill-discovery-wsl-bash-filter.test.ts": 2105,
"src/main/skills/discovery/skill-discovery-wsl-script-roundtrip.test.ts": 136,
@@ -1,108 +0,0 @@
import { execFileSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
RUNTIME_PROTOCOL_OVERRIDE_ENV,
checkRuntimeLauncherProtocolRatchet
} from './check-runtime-launcher-protocol-ratchet.mjs'
import { DAEMON_PROTOCOL_SOURCE_PATH } from '../schema-facts/daemon-protocol-facts.mjs'
const repos = []
const LAUNCHER = 'src/main/managed-server/install/orcad-remote-runtime.ts'
function git(repo, args) {
return execFileSync('git', args, {
cwd: repo,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe']
})
}
function write(repo, path, contents) {
const file = join(repo, path)
mkdirSync(dirname(file), { recursive: true })
writeFileSync(file, contents)
}
function writeProtocol(repo, current) {
const previous = Array.from({ length: current - 1 }, (_, index) => index + 1)
write(
repo,
DAEMON_PROTOCOL_SOURCE_PATH,
`export const PROTOCOL_VERSION = ${current}\nexport const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [${previous.join(', ')}] as const\n`
)
}
function commit(repo, message) {
git(repo, ['add', '.'])
git(repo, [
'-c',
'user.name=test',
'-c',
'user.email=test@example.com',
'commit',
'-q',
'--no-gpg-sign',
'-m',
message
])
return git(repo, ['rev-parse', 'HEAD']).trim()
}
/** A base commit at protocol 3, then a candidate commit shaped by `change`. */
function repoWithCandidate(change) {
const repo = mkdtempSync(join(tmpdir(), 'runtime-launcher-ratchet-'))
repos.push(repo)
git(repo, ['init', '-q'])
writeProtocol(repo, 3)
write(repo, LAUNCHER, 'export const launcher = 1\n')
write(repo, 'src/unrelated.ts', 'export const unrelated = 1\n')
const base = commit(repo, 'base')
change(repo)
commit(repo, 'candidate')
return { repo, base }
}
afterEach(() => {
for (const repo of repos.splice(0)) {
rmSync(repo, { recursive: true, force: true })
}
})
describe('checkRuntimeLauncherProtocolRatchet against git history', () => {
it('fails when the diff from the base both edits a launcher and bumps PROTOCOL_VERSION', () => {
const { repo, base } = repoWithCandidate((candidate) => {
writeProtocol(candidate, 4)
write(candidate, LAUNCHER, 'export const launcher = 2\n')
})
expect(checkRuntimeLauncherProtocolRatchet({ repoRoot: repo, base, env: {} }).ok).toBe(false)
expect(
checkRuntimeLauncherProtocolRatchet({
repoRoot: repo,
base,
env: { [RUNTIME_PROTOCOL_OVERRIDE_ENV]: 'true' }
}).ok
).toBe(true)
})
it('passes a bump next to unrelated edits', () => {
const { repo, base } = repoWithCandidate((candidate) => {
writeProtocol(candidate, 4)
write(candidate, 'src/unrelated.ts', 'export const unrelated = 2\n')
})
expect(checkRuntimeLauncherProtocolRatchet({ repoRoot: repo, base, env: {} }).ok).toBe(true)
})
it('ignores edits to the protocol file that keep PROTOCOL_VERSION', () => {
const { repo, base } = repoWithCandidate((candidate) => {
write(
candidate,
DAEMON_PROTOCOL_SOURCE_PATH,
'// comment\nexport const PROTOCOL_VERSION = 3\nexport const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [1, 2] as const\n'
)
write(candidate, LAUNCHER, 'export const launcher = 2\n')
})
expect(checkRuntimeLauncherProtocolRatchet({ repoRoot: repo, base, env: {} }).ok).toBe(true)
})
})
@@ -1,81 +0,0 @@
import { createHash } from 'node:crypto'
import 'node:fs'
import { copyFile, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import '../../../../src/main/orcad/artifact-slots/orcad-artifact-materializer.ts'
import '../../../../src/main/orcad/artifact-slots/orcad-artifact-identity.ts'
import {
ORCAD_TEMPLATE_MANIFEST_FILENAME,
orcadRipgrepArtifact
} from '../../../../src/shared/orcad-artifacts.ts'
import { writeOrcadTemplateTestFixture } from './orcad-template-test-fixture.mjs'
const require = createRequire(import.meta.url)
const { compactPackagedOrcadRipgrep } = require('./compact-packaged-orcad-ripgrep.cjs')
const { resealSignedWindowsApp } = require('./packaged-orcad-template.cjs')
const roots = []
const hash = (bytes) => createHash('sha256').update(bytes).digest('hex')
afterEach(async () => {
vi.restoreAllMocks()
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
async function fixture() {
vi.spyOn(console, 'log').mockImplementation(() => {})
const appDir = await mkdtemp(join(tmpdir(), 'orca-compact-ripgrep-'))
roots.push(appDir)
const resourcesDir = join(appDir, 'resources')
const templateDir = await writeOrcadTemplateTestFixture(resourcesDir, { compat: true })
const manifestPath = join(templateDir, ORCAD_TEMPLATE_MANIFEST_FILENAME)
const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
for (const [target, entry] of Object.entries(manifest.targets)) {
const filename = orcadRipgrepArtifact(target)
const desktop = join(resourcesDir, filename)
await mkdir(dirname(desktop), { recursive: true })
const bytes = Buffer.from(`${filename}:static binary`)
await writeFile(desktop, bytes)
await writeFile(join(templateDir, 'targets', target, filename), bytes)
entry.files[filename] = hash(bytes)
}
await writeFile(manifestPath, JSON.stringify(manifest))
return { appDir, resourcesDir, templateDir, manifest, manifestPath }
}
describe('packaged ripgrep storage', () => {
it('does not launder corrupted target bytes while removing duplicates', async () => {
const f = await fixture()
await writeFile(join(f.templateDir, 'targets/linux-x64-glibc/ripgrep/linux-x64/rg'), 'tampered')
expect(() => compactPackagedOrcadRipgrep(f.resourcesDir)).toThrow('checksum mismatch')
})
it.skipIf(process.platform === 'win32')('rejects a shared symlink', async () => {
const f = await fixture()
const shared = join(f.resourcesDir, 'ripgrep/linux-x64/rg')
const other = `${shared}.other`
await copyFile(shared, other)
await rm(shared)
await symlink(other, shared)
expect(() => compactPackagedOrcadRipgrep(f.resourcesDir)).toThrow('must be a regular file')
})
it('reseals only shared Windows binaries explicitly returned by SignPath', async () => {
const f = await fixture()
compactPackagedOrcadRipgrep(f.resourcesDir)
const filename = 'ripgrep/win32-x64/rg.exe'
const shared = join(f.resourcesDir, filename)
await writeFile(shared, 'authenticode-signed binary')
const list = join(f.appDir, 'inner-signing-list.txt')
await writeFile(list, 'Orca.exe\r\n')
expect(() => resealSignedWindowsApp(f.appDir, list)).toThrow('checksum mismatch')
await writeFile(list, 'Orca.exe\r\nresources\\ripgrep\\win32-x64\\rg.exe\r\n')
resealSignedWindowsApp(f.appDir, list)
const manifest = JSON.parse(await readFile(f.manifestPath, 'utf8'))
expect(manifest.targets['win32-x64'].files[filename]).toBe(hash(await readFile(shared)))
await writeFile(join(f.resourcesDir, 'ripgrep/linux-x64/rg'), 'unrelated change')
expect(() => resealSignedWindowsApp(f.appDir, list)).toThrow('checksum mismatch')
})
})
@@ -1,78 +0,0 @@
import { afterEach, describe, expect, it } from 'vitest'
import { BRIDGE_PROTOCOL_VERSION } from '../protocol/bridge-frame-fields'
import { createFakeBridgePortPair as createPair } from '../test-support/bridge-port-pair-test-harness'
import type { BridgePortPair } from '../test-support/bridge-port-pair-contract'
import type { FakeRpcClient } from '../../test-support/bridge-host-test-fakes'
const resources = new Set<ReturnType<typeof createPair>>()
function createFakeBridgePortPair(
...args: Parameters<typeof createPair>
): ReturnType<typeof createPair> {
const resource = createPair(...args)
resources.add(resource)
return resource
}
function closeResources(): void {
for (const resource of resources) {
resource.client.close()
resource.host.dispose()
}
resources.clear()
}
async function opened(): Promise<BridgePortPair<FakeRpcClient>> {
const pair = createFakeBridgePortPair()
await pair.flush()
return pair
}
// Use both bridge endpoints: the page’s claim and shell’s Back press travel in opposite directions, so testing either alone misses their coordination.
describe('a Back press crossing from the shell to the page', () => {
it('tells the shell when the last consumer lets go, so the key goes back to the navigator', async () => {
const pair = await opened()
const release = pair.client.claimBack(() => true)
await pair.flush()
release()
await pair.flush()
expect(pair.backClaims).toEqual([true, false])
})
// A sheet can close between claim and press; hand an unclaimed press back to native navigation instead of swallowing it.
it('hands a press nothing took back as a navigate-back, and says so on the page', async () => {
const pair = await opened()
const release = pair.client.claimBack(() => true)
await pair.flush()
release()
await pair.flush()
pair.host.receive(JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, type: 'ready' }))
await pair.flush()
expect(pair.host.sendBack()).toBe(true)
await pair.flush()
expect(pair.backPops).toEqual(['popped'])
expect(pair.diagnostics).toContainEqual({ kind: 'back-unclaimed' })
})
// Reassert the page’s current claim on init because readReady clears the shell’s claim; otherwise Back can pop a screen beneath an open sheet.
it('says the claim again on the init that answers a re-asked ready', async () => {
const pair = await opened()
pair.client.claimBack(() => true)
await pair.flush()
expect(pair.backClaims).toEqual([true])
// A stale state causes another ready/init; reassert the claim after the shell clears it.
pair.host.receive(JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, type: 'ready' }))
await pair.flush()
expect(pair.backClaims).toEqual([true, false, true])
})
it('gives the key back when the page client closes', async () => {
const pair = await opened()
pair.client.claimBack(() => true)
await pair.flush()
pair.client.close()
await pair.flush()
expect(pair.backClaims).toEqual([true, false])
})
})
afterEach(closeResources)
@@ -1,70 +0,0 @@
import { describe, expect, it } from 'vitest'
import { createFakeBridgePortPair } from '../test-support/bridge-port-pair-test-harness'
import type { BridgeInitRoute } from '../protocol/bridge-init-route'
const SESSION = '/h/host-a/session/wt-1'
function sessionRoute(paneKey?: string): BridgeInitRoute {
return {
pathname: SESSION,
params: { name: 'my worktree', ...(paneKey === undefined ? {} : { paneKey }) }
}
}
async function openedOnTheSession(): Promise<ReturnType<typeof createFakeBridgePortPair>> {
const pair = createFakeBridgePortPair({
route: sessionRoute(),
storage: { 'orca:hostDockWidth': '320' }
})
await pair.flush()
return pair
}
function recordRouteUpdates(pair: ReturnType<typeof createFakeBridgePortPair>): string[] {
const seen: string[] = []
pair.client.onRouteUpdate((route) => {
seen.push(route?.params?.paneKey ?? '')
})
return seen
}
// Deliver pane taps through same-session init updates so the mounted page keeps its state; remount keys exclude pane params (ruling 33.1).
describe('a route update over a re-sent init', () => {
it('reaches the page twice for a repeat tap on the same pane', async () => {
const pair = await openedOnTheSession()
const seen = recordRouteUpdates(pair)
pair.host.publishRoute(sessionRoute('pane-1'))
await pair.flush()
pair.host.publishRoute(sessionRoute())
await pair.flush()
pair.host.publishRoute(sessionRoute('pane-1'))
await pair.flush()
expect(seen).toEqual(['pane-1', '', 'pane-1'])
})
// Repeated ready repairs state but is not another pane request; notify listeners only when route params move.
it('publishes nothing for a re-asked ready that carries the route the page holds', async () => {
const pair = await openedOnTheSession()
const seen = recordRouteUpdates(pair)
pair.host.receive(JSON.stringify({ v: 1, type: 'ready' }))
await pair.flush()
expect(seen).toEqual([])
pair.host.publishRoute(sessionRoute('pane-1'))
await pair.flush()
pair.host.receive(JSON.stringify({ v: 1, type: 'ready' }))
await pair.flush()
expect(seen).toEqual(['pane-1'])
})
it('leaves a request pending across the update still resolving', async () => {
const pair = await openedOnTheSession()
const pending = pair.client.sendRequest('worktree.list')
await pair.flush()
pair.host.publishRoute(sessionRoute('pane-1'))
await pair.flush()
const sent = pair.rpc.requests.find((request) => request.method === 'worktree.list')
sent?.resolve({ id: 'r1', ok: true, result: { worktrees: [] } })
await pair.flush()
await expect(pending).resolves.toMatchObject({ ok: true })
})
})
@@ -1,105 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { createPageBackConsumers } from './page-back-consumers'
function consumers() {
const claims: boolean[] = []
const unclaimed = vi.fn()
return {
claims,
unclaimed,
stack: createPageBackConsumers({
publishClaim: (claimed) => claims.push(claimed),
onUnclaimed: unclaimed
})
}
}
describe('who in the page is holding the device Back key', () => {
it('tells the shell on the edges only, so one sheet over another does not flicker the key', () => {
const { claims, stack } = consumers()
const first = stack.claim(() => true)
const second = stack.claim(() => true)
expect(claims).toEqual([true])
second()
expect(claims).toEqual([true])
first()
expect(claims).toEqual([true, false])
})
it('offers a press newest first, and stops at the one that takes it', () => {
const { stack } = consumers()
const order: string[] = []
stack.claim(() => {
order.push('bottom')
return true
})
stack.claim(() => {
order.push('top')
return true
})
stack.press()
expect(order).toEqual(['top'])
})
it('falls through a consumer that says the press was not its own', () => {
const { stack, unclaimed } = consumers()
const order: string[] = []
stack.claim(() => {
order.push('bottom')
return true
})
stack.claim(() => {
order.push('top')
return false
})
stack.press()
expect(order).toEqual(['top', 'bottom'])
expect(unclaimed).not.toHaveBeenCalled()
})
it('survives a consumer that disposes itself from inside its own answer', () => {
const { stack } = consumers()
const order: string[] = []
stack.claim(() => {
order.push('bottom')
return true
})
const release = stack.claim(() => {
order.push('top')
release()
return false
})
stack.press()
// A copied stack must still visit the lower consumer after the upper one disposes itself.
expect(order).toEqual(['top', 'bottom'])
})
it('ignores a release called twice, so a remounting claim cannot free another one', () => {
const { claims, stack } = consumers()
const release = stack.claim(() => true)
release()
const other = stack.claim(() => true)
release()
expect(claims).toEqual([true, false, true])
other()
expect(claims).toEqual([true, false, true, false])
})
// Every ready/init clears the host claim; reassert current page state even without a new consumer edge.
it('says again what it is holding when the shell asks, without a second edge', () => {
const { claims, stack } = consumers()
stack.claim(() => true)
stack.reassert()
expect(claims).toEqual([true, true])
})
it('gives the key back when the client closes, whoever was still holding it', () => {
const { claims, stack } = consumers()
stack.claim(() => true)
stack.claim(() => true)
stack.clear()
expect(claims).toEqual([true, false])
stack.clear()
expect(claims).toEqual([true, false])
})
})
@@ -1,76 +0,0 @@
import { describe, expect, it } from 'vitest'
import { clientFrame } from '../test-support/bridge-host-test-fakes'
import { harness } from '../test-support/bridge-host-test-harness'
import { BRIDGE_BACK_CLAIM_NOTIFY } from '../bridge/page-lifecycle/bridge-page-back'
function ready(): string {
return clientFrame({ type: 'ready' })
}
function claim(claimed: boolean): string {
return clientFrame({ type: 'notify', name: BRIDGE_BACK_CLAIM_NOTIFY, claimed })
}
// Clear Back claims on every document-ending path; a stale claim hands the key to an unrelated page and swallows navigation.
describe('the claim a host holds on the device Back key', () => {
it('carries the page taking the key and letting it go, and says neither twice', () => {
const bridge = harness()
bridge.host.receive(ready())
bridge.host.receive(claim(true))
bridge.host.receive(claim(true))
bridge.host.receive(claim(false))
expect(bridge.backClaims).toEqual([true, false])
})
it('drops it on the next document saying ready, which is the one that has to claim again', () => {
const bridge = harness()
bridge.host.receive(ready())
bridge.host.receive(claim(true))
bridge.host.receive(ready())
expect(bridge.backClaims).toEqual([true, false])
})
it('drops it when the page closes, which is the document saying it is going', () => {
const bridge = harness()
bridge.host.receive(ready())
bridge.host.receive(claim(true))
bridge.host.receive(clientFrame({ type: 'close' }))
expect(bridge.backClaims).toEqual([true, false])
})
// Host replacement preserves the live document and its Back claim; only leaving ready ends the session (shell-page-back-claim.ts).
it('reports nothing when the host itself ends: the claim belongs to the session', () => {
const bridge = harness()
bridge.host.receive(ready())
bridge.host.receive(claim(true))
bridge.host.dispose()
expect(bridge.backClaims).toEqual([true])
expect(bridge.host.readSessionBack()).toEqual({ claimed: true })
})
it('lets the next document reset a carried claim, so the seed is not a latch', () => {
const rebuilt = harness({
sessionBack: { claimed: true },
sessionEstablished: true
})
rebuilt.host.receive(ready())
expect(rebuilt.backClaims).toEqual([false])
})
})
describe('handing one press to the page', () => {
// Older pages drop unknown Back frames; return false without sending so the navigator retains the press.
it('sends nothing between documents, when the view belongs to no page', () => {
const bridge = harness()
bridge.host.receive(ready())
bridge.host.receive(clientFrame({ type: 'close' }))
expect(bridge.host.sendBack()).toBe(false)
})
it('sends nothing once the host is disposed', () => {
const bridge = harness()
bridge.host.receive(ready())
bridge.host.dispose()
expect(bridge.host.sendBack()).toBe(false)
})
})
@@ -1,69 +0,0 @@
import { describe, expect, it } from 'vitest'
import { harness, ID, OTHER, subscribeFrame } from '../test-support/bridge-host-test-harness'
import { BRIDGE_MAX_UNACKED_FRAMES } from '../host-streams/bridge-host-subscriptions'
import {
clientFrame,
createFakeRpcClient,
flushBridge,
rpcSuccess
} from '../test-support/bridge-host-test-fakes'
describe('requests', () => {
it('answers a synchronous throw from the client and frees the slot', () => {
const client = createFakeRpcClient()
const bridge = harness({
ready: true,
client: {
...client,
sendRequest: () => {
throw new Error('no socket')
}
}
})
bridge.host.receive(clientFrame({ type: 'request', id: ID, method: 'status.get' }))
bridge.host.receive(clientFrame({ type: 'request', id: ID, method: 'status.get' }))
const errors = bridge.frames().filter((frame) => frame.type === 'error')
expect(errors).toHaveLength(2)
expect(
errors.every((frame) => frame.type === 'error' && frame.error.category === 'Error')
).toBe(true)
})
it('stops answering a cancelled request without pretending the desktop stopped running it', async () => {
const bridge = harness({ ready: true })
bridge.host.receive(clientFrame({ type: 'request', id: ID, method: 'status.get' }))
bridge.host.receive(clientFrame({ type: 'cancel', id: ID, target: 'request' }))
bridge.client.requests[0]?.resolve(rpcSuccess('wire-1', 'ok'))
await flushBridge()
expect(bridge.frames().filter((frame) => frame.type !== 'init')).toEqual([])
})
})
describe('backpressure', () => {
// Use a nonterminal stream to test the byte window; terminal.subscribe now holds/coalesces output and tests that exception separately.
const WINDOWED = 'session.tabs.subscribe'
it('keeps each stream on its own window', () => {
const bridge = harness({ ready: true })
bridge.host.receive(subscribeFrame(ID, WINDOWED))
bridge.host.receive(subscribeFrame(OTHER, WINDOWED))
for (let index = 0; index <= BRIDGE_MAX_UNACKED_FRAMES; index += 1) {
bridge.client.streams[0]?.emit({ n: index })
}
bridge.client.streams[1]?.emit({ n: 0 })
expect(bridge.last()).toEqual({ v: 1, type: 'event', id: OTHER, seq: 1, payload: { n: 0 } })
})
})
describe('teardown', () => {
it('posts nothing into a view that belongs to no document yet', () => {
const bridge = harness()
bridge.host.receive(clientFrame({ type: 'close' }))
// Client state fan-out continues between documents; do not post it into the replacement before init.
bridge.client.pushState('reconnecting')
bridge.client.pushState('connected')
expect(bridge.posted).toHaveLength(0)
expect(bridge.diagnostics).toEqual([])
})
})
@@ -1,86 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
BrowserScreencastOpcode,
type BrowserScreencastFrame
} from '../../browser/screencast/browser-screencast-protocol'
import { clientFrame } from '../test-support/bridge-host-test-fakes'
import { harness, ID } from '../test-support/bridge-host-test-harness'
const SCREENCAST = 'browser.screencast'
function screencastSubscribe(id: string, wantsBinary?: boolean): string {
return clientFrame({
type: 'subscribe',
id,
method: SCREENCAST,
params: { worktree: 'id:w', page: 'p' },
...(wantsBinary === undefined ? {} : { wantsBinary })
})
}
function frame(seq: number, image: Uint8Array): BrowserScreencastFrame {
return {
opcode: BrowserScreencastOpcode.Frame,
seq,
format: 'jpeg',
metadata: { deviceWidth: 390, deviceHeight: 712, imageWidth: 975, imageHeight: 609 },
image
}
}
const IMAGE = Uint8Array.from({ length: 512 }, (_, index) => (index * 31 + 7) & 0xff)
describe('a binary frame crosses as the event the page decodes', () => {
// JSON and binary share sequence numbers because the page acknowledges one event ledger.
it('shares one seq sequence with the JSON events of the same stream', () => {
const bridge = harness({ ready: true })
bridge.host.receive(screencastSubscribe(ID, true))
bridge.client.streams[0]?.emit({ type: 'ready' })
bridge.client.streams[0]?.emitBinary?.(frame(0, IMAGE))
bridge.client.streams[0]?.emit({ type: 'ready' })
expect(
bridge
.frames()
.filter((message) => message.type === 'event')
.map((m) => m.seq)
).toEqual([1, 2, 3])
})
it('delivers nothing for a stream the page already cancelled', () => {
const bridge = harness({ ready: true })
bridge.host.receive(screencastSubscribe(ID, true))
const emitBinary = bridge.client.streams[0]?.emitBinary
bridge.host.receive(clientFrame({ type: 'cancel', id: ID, target: 'subscription' }))
if (emitBinary === undefined || emitBinary === null) {
throw new Error('binary listener never installed')
}
emitBinary(frame(1, IMAGE))
expect(bridge.frames().filter((message) => message.type === 'event')).toEqual([])
})
})
// Oversized JSON must end the stream because invisible gaps corrupt state; screencast may drop a frame and retain the last picture until the next.
describe('an over-cap frame drops on the binary lane and ends the stream on the JSON one', () => {
// 500,000 raw bytes encode to 666,668 base64 characters, exceeding the message cap.
const OVERSIZED = new Uint8Array(500_000)
function openBinary(): ReturnType<typeof harness> {
const bridge = harness({ ready: true })
bridge.host.receive(screencastSubscribe(ID, true))
return bridge
}
// Dropped frames must not consume a sequence number that the page could acknowledge as sent.
it('does not spend a seq on a frame it dropped', () => {
const bridge = openBinary()
bridge.client.streams[0]?.emitBinary?.(frame(1, IMAGE))
bridge.client.streams[0]?.emitBinary?.(frame(2, OVERSIZED))
bridge.client.streams[0]?.emitBinary?.(frame(3, IMAGE))
expect(
bridge
.frames()
.filter((message) => message.type === 'event')
.map((message) => message.seq)
).toEqual([1, 2])
})
})
@@ -1,108 +0,0 @@
import { createElement, useEffect } from 'react'
import { act, create } from 'react-test-renderer'
import { beforeEach, expect, it, vi } from 'vitest'
import { useShellPageStorageRefresh } from './use-shell-page-storage-refresh'
import {
hydrateMirroredStorage,
readMirroredStorage,
retainMirroredStorage,
writeMirroredStorage
} from '../../storage/mirrored-storage-keys'
import { createFakeBridgePortPair } from '../bridge/test-support/bridge-port-pair-test-harness'
const store = vi.hoisted(() => ({
values: new Map<string, string>(),
pending: new Array<() => void>()
}))
vi.mock('@react-native-async-storage/async-storage', () => ({
default: {
setItem: (key: string, value: string) =>
new Promise<void>((resolve) =>
store.pending.push(() => {
store.values.set(key, value)
resolve()
})
),
getItem: async (key: string) => store.values.get(key) ?? null,
multiGet: async (keys: string[]) => keys.map((key) => [key, store.values.get(key) ?? null])
}
}))
const focus = vi.hoisted(() => ({ active: true }))
const app = vi.hoisted(() => ({ listener: (_state: string) => {}, remove: vi.fn() }))
vi.mock('expo-router', () => ({
useFocusEffect: (effect: () => void | (() => void)) =>
useEffect(() => (focus.active ? effect() : undefined), [effect, focus.active])
}))
vi.mock('react-native', () => ({
AppState: {
addEventListener: (_event: string, listener: (state: string) => void) => {
app.listener = listener
return { remove: app.remove }
}
}
}))
beforeEach(() => {
focus.active = true
app.remove.mockClear()
store.values.clear()
store.pending.length = 0
})
it('republishes an accepted page zoom after an older native snapshot crosses the pinch', async () => {
const key = 'orca:terminalTextScale'
store.values.set(key, '1')
const releaseKeys = retainMirroredStorage([key])
const storage = { [key]: '1' }
let hold = false
const held: string[] = []
const pair = createFakeBridgePortPair({
route: { pathname: '/h/host-a/session/wt-1' },
storage,
holdToPage: (json) => {
if (hold) {
held.push(json)
}
return hold
},
onStorageWrite: writeMirroredStorage
})
await pair.flush()
let displayedScale = 1
pair.client.onStorageUpdate(() => {
displayedScale = Number(pair.client.getShellSession()!.storage[key])
})
const refresh = () => hydrateMirroredStorage([key])
const publish = () => {
Object.assign(storage, readMirroredStorage([key]))
pair.host.publishStorage()
}
function Harness() {
useShellPageStorageRefresh(refresh, publish)
return null
}
let renderer!: ReturnType<typeof create>
await act(async () => {
renderer = create(createElement(Harness))
await pair.flush()
})
hold = true
pair.host.publishStorage()
displayedScale = 1.5
expect(pair.client.notifyStorageWrite(key, '1.5')).toBe(true)
await act(async () => pair.flush())
pair.deliverToPage(held.shift()!)
expect(displayedScale).toBe(1)
for (const frame of held) {
pair.deliverToPage(frame)
}
await act(async () => store.pending.shift()!())
expect(store.values.get(key)).toBe('1.5')
expect(displayedScale).toBe(1.5)
act(() => renderer.unmount())
pair.client.close()
pair.host.dispose()
releaseKeys()
})
@@ -1,80 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it } from 'vitest'
import { FakeSession } from '../../../transport/connection/mobile-endpoint-supervisor-test-fakes'
import type { RpcClient } from '../../../transport/rpc/rpc-client-contract'
import { useNewWorkspaceExecutionTarget } from './use-new-workspace-execution-target'
const mounted: ReactTestRenderer[] = []
afterEach(() => {
for (const renderer of mounted.splice(0)) {
act(() => renderer.unmount())
}
})
describe('New Workspace agent detection', () => {
it('targets the picked repo and clears the previous repo agents while switching', async () => {
const client = new FakeSession('connected')
let resolveNext: ((response: { id: string; ok: true; result: string[] }) => void) | undefined
client.sendRequest.mockImplementation(async (_method: string, params?: unknown) => {
if (JSON.stringify(params) === JSON.stringify({ repoId: 'wsl-repo' })) {
return { id: 'reply', ok: true, result: ['claude'] }
}
return new Promise((resolve) => {
resolveNext = resolve
})
})
let detected: Set<string> | null = null
function Harness({
repoId,
selectedClient = client
}: {
repoId: string
selectedClient?: RpcClient
}) {
detected = useNewWorkspaceExecutionTarget({
client: selectedClient,
repoId,
connectionId: null,
visible: true
}).detectedAgentIds
return null
}
let renderer: ReactTestRenderer | undefined
await act(async () => {
renderer = create(createElement(Harness, { repoId: 'wsl-repo' }))
mounted.push(renderer)
})
expect(client.sendRequest).toHaveBeenCalledWith('preflight.detectAgents', {
repoId: 'wsl-repo'
})
expect(detected).toEqual(new Set(['claude']))
await act(async () => {
renderer?.update(createElement(Harness, { repoId: 'host-repo' }))
})
expect(detected).toBeNull()
expect(client.sendRequest).toHaveBeenLastCalledWith('preflight.detectAgents', {
repoId: 'host-repo'
})
await act(async () => {
resolveNext?.({ id: 'reply', ok: true, result: ['codex'] })
})
expect(detected).toEqual(new Set(['codex']))
const otherHost = new FakeSession('connected')
otherHost.sendRequest.mockImplementation(
() =>
new Promise((resolve) => {
resolveNext = resolve
})
)
await act(async () => {
renderer?.update(createElement(Harness, { repoId: 'host-repo', selectedClient: otherHost }))
})
expect(detected).toBeNull()
await act(async () => {
resolveNext?.({ id: 'reply', ok: true, result: ['gemini'] })
})
expect(detected).toEqual(new Set(['gemini']))
})
})
@@ -1,118 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useMobileNativeChatTerminalStream } from './use-mobile-native-chat-terminal-stream'
describe('useMobileNativeChatTerminalStream', () => {
let renderer: ReactTestRenderer | null = null
const subscriptionsRef = { current: new Map<string, () => void>() }
const subscribingRef = { current: new Set<string>() }
const leaseOnlyRef = { current: new Set<string>() }
const webReadyRef = { current: new Set(['terminal-1']) }
const registerSubscription = (handle: string): boolean => {
subscriptionsRef.current.set(handle, () => {})
leaseOnlyRef.current.delete(handle)
return true
}
const subscribe = vi.fn(registerSubscription)
const unsubscribe = vi.fn((handle: string) => {
subscriptionsRef.current.delete(handle)
leaseOnlyRef.current.delete(handle)
})
const notifyListedHandlesRef = { current: (_liveHandles: ReadonlySet<string>): void => {} }
const hasTabsRecoveryNeedRef = { current: (): boolean => false }
beforeEach(() => {
subscriptionsRef.current = new Map([['terminal-1', () => {}]])
subscribingRef.current = new Set()
leaseOnlyRef.current = new Set()
webReadyRef.current = new Set(['terminal-1'])
subscribe.mockClear()
unsubscribe.mockClear()
})
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
})
function Harness({
showNativeChat,
activeHandle = 'terminal-1',
leaseReady = true,
streamRevision = 0
}: {
showNativeChat: boolean
activeHandle?: string
leaseReady?: boolean
streamRevision?: number
}): null {
const stream = useMobileNativeChatTerminalStream({
showNativeChat,
activeHandle,
activeTabType: 'terminal',
leaseReady,
streamRevision,
subscriptionsRef,
subscribingRef,
leaseOnlyRef,
webReadyRef,
subscribe,
unsubscribe
})
notifyListedHandlesRef.current = stream.notifyListedHandles
hasTabsRecoveryNeedRef.current = stream.hasTabsRecoveryNeed
return null
}
// Model subscribed then end in one dead-PTY round trip; testing end alone misses a self-refilling rearm loop.
async function playDeadPtyRoundTrip(revision: number): Promise<void> {
subscriptionsRef.current.delete('terminal-1')
await act(async () => {
renderer?.update(
createElement(Harness, {
showNativeChat: true,
leaseReady: false,
streamRevision: revision
})
)
})
await act(async () => {
renderer?.update(
createElement(Harness, { showNativeChat: true, leaseReady: true, streamRevision: revision })
)
})
}
it('keeps asking until a tab snapshot replaces the exhausted handle', async () => {
await act(async () => {
renderer = create(createElement(Harness, { showNativeChat: true }))
})
for (let revision = 1; revision <= 3; revision += 1) {
await playDeadPtyRoundTrip(revision)
}
await act(async () => {
notifyListedHandlesRef.current(new Set(['terminal-1']))
})
expect(hasTabsRecoveryNeedRef.current()).toBe(false)
// Exhaustion plus absence needs a fresh tab snapshot to find the reminted handle.
await act(async () => {
notifyListedHandlesRef.current(new Set(['terminal-2']))
})
expect(hasTabsRecoveryNeedRef.current()).toBe(true)
expect(hasTabsRecoveryNeedRef.current()).toBe(true)
await act(async () => {
renderer?.update(
createElement(Harness, {
showNativeChat: true,
activeHandle: 'terminal-2',
leaseReady: false,
streamRevision: 4
})
)
})
expect(hasTabsRecoveryNeedRef.current()).toBe(false)
})
})
@@ -1,96 +0,0 @@
import { useContext } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { NativeChatMessage } from '../../../../../../src/shared/native-chat/native-chat-types'
import { MobileNativeChatRowOverlaysHost } from './MobileNativeChatRowOverlaysHost'
import {
MobileNativeChatRowOverlaysContext,
type MobileNativeChatRowOverlays
} from './mobile-native-chat-row-overlays'
import type { MobileNativeChatConversation } from '../../conversation/use-mobile-native-chat-conversation-state'
vi.mock('react-native', async () => ({
...(await import('../../../../test-support/react-native-motion-stub')).reactNativeMotionStub(),
Image: 'Image',
Modal: 'Modal',
Platform: { OS: 'ios' },
Pressable: 'Pressable',
ScrollView: 'ScrollView',
View: 'View',
StyleSheet: { create: (styles: unknown) => styles }
}))
vi.mock('react-native-safe-area-context', () => ({
useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 })
}))
vi.mock('lucide-react-native', () => ({ X: 'X' }))
vi.mock('../../../../platform/haptics/haptics', () => ({ triggerMediumImpact: vi.fn() }))
vi.mock('./MobileNativeChatRewindDialog', () => ({ MobileNativeChatRewindDialog: () => null }))
vi.mock('./MobileNativeChatMessageActionsSheet', () => ({
MobileNativeChatMessageActionsSheet: 'MessageActionsSheet'
}))
vi.mock('./MobileLinkActionSheet', () => ({ MobileLinkActionSheet: 'LinkActionSheet' }))
vi.mock('../../visual/MobileImageViewerActions', () => ({
MobileImageViewerActions: 'ImageViewerActions'
}))
let overlays: MobileNativeChatRowOverlays | null = null
function Row(): null {
overlays = useContext(MobileNativeChatRowOverlaysContext)
return null
}
const chat = (conversation: MobileNativeChatConversation) => (
<MobileNativeChatRowOverlaysHost conversation={conversation}>
<Row />
</MobileNativeChatRowOverlaysHost>
)
const message: NativeChatMessage = {
id: 'a1',
role: 'assistant',
blocks: [{ type: 'text', text: 'Done.' }],
timestamp: null,
source: 'transcript'
}
let renderer: ReactTestRenderer | null = null
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
})
describe("a row's actions sheet", () => {
function shownAcross(conversations: MobileNativeChatConversation[]): boolean[] {
const [first, ...rest] = conversations
act(() => {
renderer = create(chat(first!))
})
act(() => overlays!.openActions(message))
const shown = () =>
renderer!.root.findAll((node) => String(node.type) === 'MessageActionsSheet').length === 1
return [shown()].concat(
rest.map((conversation) => {
act(() => renderer!.update(chat(conversation)))
return shown()
})
)
}
it('closes when a notification switches the tab, and does not reopen', () => {
expect(
shownAcross([
{ surfaceId: 'tab-a', sessionId: 's1' },
{ surfaceId: 'tab-b', sessionId: 's1' },
{ surfaceId: 'tab-a', sessionId: 's1' }
])
).toEqual([true, false, false])
})
it("stays open when the tab's first session id arrives, then closes on a replacement", () => {
expect(
shownAcross([
{ surfaceId: 'tab-a', sessionId: null },
{ surfaceId: 'tab-a', sessionId: 's1' },
{ surfaceId: 'tab-a', sessionId: 's2' }
])
).toEqual([true, true, false])
})
})
@@ -1,101 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { NativeChatMessage } from '../../../../../../src/shared/native-chat/native-chat-types'
import { useMobileNativeChatTurnDisclosure } from './use-mobile-native-chat-turn-disclosure'
import { Harness, Result, userMessage } from './use-mobile-native-chat-turn-disclosure.test-fixture'
describe('useMobileNativeChatTurnDisclosure', () => {
let renderer: ReactTestRenderer | null = null
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
})
it('keeps the live bar on every render until it settles in place', () => {
vi.useFakeTimers()
try {
vi.setSystemTime(1_000)
const messages = [userMessage('u1')]
const seen: unknown[] = []
function Recorder({ isWorking }: { isWorking: boolean }): React.JSX.Element {
const disclosure = useMobileNativeChatTurnDisclosure({
messages,
enabled: true,
isWorking,
scopeKey: 'host\0worktree\0tab-a'
})
seen.push(disclosure.resolveRow(0, messages[0]).turnStatus)
return createElement('result', { disclosure })
}
act(() => {
renderer = create(createElement(Recorder, { isWorking: true }))
})
vi.setSystemTime(6_000)
seen.length = 0
act(() => {
renderer?.update(createElement(Recorder, { isWorking: false }))
})
expect(seen).not.toContain(null)
expect(seen.at(-1)).toEqual({ startedAt: 1_000, thinking: false, workedSeconds: 5 })
} finally {
vi.useRealTimers()
}
})
})
describe('the open reasoning block the live line discloses', () => {
let renderer: ReactTestRenderer | null = null
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
})
const block = (id: string, state: 'running' | 'completed'): NativeChatMessage => ({
id,
role: 'reasoning',
blocks: [{ type: 'text', text: `${id} weighs two approaches` }],
timestamp: null,
source: 'transcript',
state
})
const show = (
messages: NativeChatMessage[],
props: { thinking?: boolean; lineYields?: boolean }
) =>
act(() => {
const element = createElement(Harness, { messages, enabled: true, ...props })
if (renderer) {
renderer.update(element)
} else {
renderer = create(element)
}
})
const latest = () => renderer!.root.findByType(Result).props.disclosure
it('hides only that block, and lands it open once it ends if the reader opened it live', () => {
const prompt = userMessage('u1')
show([prompt, block('r-1', 'running')], { thinking: true })
expect(latest().liveLine).toMatchObject({
reasoning: { message: { id: 'r-1' } },
reasoningExpanded: false
})
expect(latest().resolveRow(1, block('r-1', 'running')).reasoningIsLive).toBe(true)
act(() => latest().onToggleReasoning('reasoning:r-1'))
expect(latest().liveLine.reasoningExpanded).toBe(true)
show([prompt, block('r-1', 'completed')], { thinking: false })
expect(latest().liveLine).toMatchObject({ reasoning: null })
const row = latest().resolveRow(1, block('r-1', 'completed'))
expect(row).toMatchObject({ reasoningIsLive: false, reasoningExpanded: true })
show([prompt, block('r-1', 'completed'), block('r-2', 'running')], { thinking: true })
expect(latest().liveLine).toMatchObject({
reasoning: { message: { id: 'r-2' } },
reasoningExpanded: false
})
})
})
@@ -1,90 +0,0 @@
import { createElement, type ReactNode } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, expect, it, vi } from 'vitest'
const hosts = vi.hoisted(() => {
const make = (name: string) => {
const Host = (props: {
children?: ReactNode
accessibilityLabel?: string
name?: string
}): ReactNode => props.children ?? null
Host.displayName = name
return Host
}
return { Title: make('Title'), MarkedName: make('MarkedName') }
})
vi.mock('react-native', () => ({}))
// The sheet's chrome is not under test: keep only the title and its spoken label.
vi.mock('../../components/sheets/ActionSheetModal', () => ({
ActionSheetModal: (props: { title?: ReactNode; titleAccessibilityLabel?: string }) =>
createElement(hosts.Title, { accessibilityLabel: props.titleAccessibilityLabel }, props.title)
}))
vi.mock('../fork/MobileForkMarkedName', () => ({
MobileForkMarkedName: (props: { name: string }) => createElement(hosts.MarkedName, props)
}))
vi.mock('../fork/mobile-fork-marked-name', () => ({
mobileForkAccessibleName: (name: string) => `fork-label(${name})`
}))
vi.mock('../../i18n/use-mobile-translation', () => ({
useMobileTranslation: () => (_key: string, fallback: string) => fallback
}))
vi.mock('../native-chat/mobile-native-chat-cli-fork', () => ({
getMobileNativeChatCliForkActions: () => []
}))
vi.mock('./mobile-worker-auto-close', () => ({
useMobileAllowAutoCloseActions: () => [],
workerSubjectOf: () => undefined
}))
const { MobileAgentSessionTabActionSheet } = await import('./MobileAgentSessionTabActionSheet')
let renderer: ReactTestRenderer | undefined
afterEach(() => {
act(() => renderer?.unmount())
renderer = undefined
})
function renderSheet(forked: boolean): ReactTestRenderer {
const tab = {
type: 'agent-session' as const,
id: 'tab',
title: 'Plan',
sessionId: 'chat',
agent: 'claude' as const,
isActive: true,
...(forked ? { forked: true as const } : {})
}
const controller = {
agentSessionActionTarget: tab,
setAgentSessionActionTarget: () => {},
closeWithBulkActions: () => [],
client: null
}
act(() => {
renderer = create(
createElement(MobileAgentSessionTabActionSheet, {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the sheet reads only these controller members.
controller: controller as never,
workspaceOnPairedHost: true
})
)
})
return renderer!
}
it("titles a fork tab's sheet with the fork-marked name and its spoken label", () => {
const sheet = renderSheet(true)
const title = sheet.root.findByType(hosts.Title)
expect(sheet.root.findByType(hosts.MarkedName).props.name).toBe('Plan')
expect(title.props.accessibilityLabel).toBe('fork-label(Plan)')
})
it("titles an original chat tab's sheet with its plain name", () => {
const sheet = renderSheet(false)
const title = sheet.root.findByType(hosts.Title)
expect(sheet.root.findAllByType(hosts.MarkedName)).toHaveLength(0)
expect(title.props.children).toBe('Plan')
expect(title.props.accessibilityLabel).toBeUndefined()
})
@@ -1,40 +0,0 @@
import { describe, expect, it } from 'vitest'
import { runRecording } from '../run-recording'
import { vitestRecordingScheduler } from './vitest-recording-scheduler'
import type { RecordingScenario } from '../scenarios/recording-scenario'
// No corpus golden has detached rejections; pin capture and recording integration directly.
describe('recordUnhandledRejections', () => {
it('reaches a checkpoint and the cleanup checkpoint through a real recording', async () => {
const scenario: RecordingScenario = {
id: 'detached',
operation: 'op',
family: 'op',
sites: [],
schedules: [],
steps: [{ action: 'fire', id: 'fire' }, { checkpoint: 'after-fire' }]
}
const recording = await runRecording(
scenario,
() => ({
action: () => {
void Promise.reject(new TypeError('detached in an action'))
},
state: () => ({}),
dispose: () => {
void Promise.reject(new Error('detached in cleanup'))
}
}),
vitestRecordingScheduler()
)
const effects = (id: string) =>
recording.checkpoints.find((checkpoint) => checkpoint.id === id)!.observation.effects
expect(effects('after-fire')).toMatchObject([
{ name: 'unhandled-rejection', value: { message: 'detached in an action' } }
])
expect(effects('cleanup')).toMatchObject([
{ name: 'unhandled-rejection', value: { message: 'detached in an action' } },
{ name: 'unhandled-rejection', value: { message: 'detached in cleanup' } }
])
})
})
@@ -1,72 +0,0 @@
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, describe, expect, it } from 'vitest'
import { operationModuleLoader } from './operation-module-loader'
// Use synthetic trees so loader properties do not depend on current product imports.
const roots: string[] = []
function sourceTree(files: Record<string, string>): string {
const root = mkdtempSync(join(tmpdir(), 'pr-31602-rpc-loader-'))
roots.push(root)
for (const [name, source] of Object.entries(files)) {
mkdirSync(join(root, 'mobile/src'), { recursive: true })
writeFileSync(join(root, 'mobile/src', name), source)
}
return root
}
function loaderOver(files: Record<string, string>): ReturnType<typeof operationModuleLoader> {
return operationModuleLoader(sourceTree(files))
}
afterAll(() => {
for (const root of roots) {
rmSync(root, { recursive: true, force: true })
}
roots.length = 0
})
describe('the mounted module loader', () => {
it('follows named reexports reached through the task foundation barrel', () => {
const modules = loaderOver({
'mobile-tasks-legacy-foundation.tsx': `export * from './mapping'`,
'mapping.ts': `export { run as search } from './operation'; export type { Missing } from './missing'`,
'operation.ts': `export const run = (query: string) => 'is:pr ' + query`
})
const foundation = modules.load<{ search: (query: string) => string }>(
'mobile/src/mobile-tasks-legacy-foundation.tsx'
)
expect(foundation.search('is:open')).toBe('is:pr is:open')
expect(() => modules.load('mobile/src/mobile-tasks-legacy-foundation.tsx').Missing).toThrow(
'Unmapped barrel export: Missing'
)
})
// Preserve proxy interop so refusal occurs on actual member use rather than merely importing the package.
it('lets a default import of an unlisted package load, and refuses the member it uses', () => {
const modules = loaderOver({
'uses-default.ts': `
import Animated from 'react-native-not-substituted'
export const read = () => Animated.createAnimatedComponent
`
})
const { read } = modules.load<{ read: () => unknown }>('mobile/src/uses-default.ts')
expect(() => read()).toThrow(
'Unspecified native mounting dependency: react-native-not-substituted.default'
)
})
// Default dependencies may reference native members before an adapter overrides them; import alone must remain possible.
it('lets a namespace import of an unlisted package load, and refuses the member it reads', () => {
const modules = loaderOver({
'uses-namespace.ts': `
import * as Haptics from 'expo-not-substituted'
export const read = () => Haptics.selectionAsync
`
})
const { read } = modules.load<{ read: () => unknown }>('mobile/src/uses-namespace.ts')
expect(() => read()).toThrow(
'Unspecified native mounting dependency: expo-not-substituted.selectionAsync'
)
})
})
@@ -1,33 +0,0 @@
import { describe, expect, it } from 'vitest'
import { ScriptedRpcTransport } from './scripted-rpc-transport'
import { vitestRecordingScheduler } from '../execution/vitest-recording-scheduler'
describe('a transparent wrapper between the operation and the scripted transport', () => {
it('keeps the sibling identity and still rejects a swallowed invocation', async () => {
const clock = vitestRecordingScheduler()
await clock.start()
const transport = new ScriptedRpcTransport(clock.elapsed, undefined, (client) => ({
...client,
sendRequest: (...args) =>
args[0] === 'alpha.one'
? Promise.reject(new Error('the wrapper kept this one'))
: client.sendRequest(...args)
}))
try {
const swallowed = transport.client.sendRequest('alpha.one').catch(() => undefined)
const sibling = transport.client.sendRequest('beta.two')
await clock.flush()
expect(transport.payloads.map(({ name }) => name)).toEqual(['beta.two#1'])
transport.complete('beta.two#1', undefined, { ok: true, result: 'B' })
await Promise.all([swallowed, sibling])
await transport.dispose()
await clock.flush()
expect(() => transport.causality.assertTransparentCalls()).toThrow('swallowed alpha.one#1')
} finally {
await transport.dispose()
await clock.flush()
transport.causality.close()
clock.stop()
}
})
})
@@ -1,118 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
dependencies,
FakeLogicalClient,
FakeRelaySession,
host,
relay
} from './mobile-endpoint-supervisor-test-fakes'
import { MobileEndpointSupervisor } from './mobile-endpoint-supervisor'
import { RelayOuterError } from '../encryption/mobile-relay-e2ee-link'
import { RelayDirectorResolveTimeoutError } from '../relay/mobile-relay-resume-director'
import type { MobileEndpointSupervisorDependencies } from './mobile-endpoint-supervisor-contract'
import type { ConnectionLogEntry } from '../../diagnostics/connection/connection-log-types'
vi.mock('react-native', () => ({ Platform: { OS: 'ios' } }))
vi.mock('expo-secure-store', () => ({ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'when-unlocked' }))
vi.mock('expo-crypto', () => ({ getRandomBytes: (length: number) => new Uint8Array(length) }))
const hostOfflineSession = () =>
new FakeRelaySession('disconnected', new RelayOuterError(4404, false, ''))
async function startOffLan(overrides: Partial<MobileEndpointSupervisorDependencies>) {
const logical = new FakeLogicalClient('disconnected', 'lan')
const logs: ConnectionLogEntry[] = []
const deps = dependencies({
openRelay: vi.fn(hostOfflineSession),
onLog: (entry) => logs.push(entry),
// Full-width jitter: 4404 retries wait the full 15s.
randomBytes: () => new Uint8Array([255, 255]),
...overrides
})
const supervisor = new MobileEndpointSupervisor(logical, host.id, relay, deps)
await supervisor.start()
await vi.advanceTimersByTimeAsync(0)
return { logical, deps, logs, supervisor }
}
describe('mobile endpoint supervisor on persistent host-offline', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-11-13T12:00:00Z'))
vi.spyOn(console, 'log').mockImplementation(() => {})
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
it('asks the director on the second 4404 and adopts the cell it names', async () => {
const moved = { ...relay, cellUrl: 'https://relay-hk.onorca.dev' }
const openRelay = vi
.fn()
.mockImplementationOnce(hostOfflineSession)
.mockImplementationOnce(hostOfflineSession)
.mockImplementation(() => new FakeRelaySession('connected'))
const resolveRelay = vi.fn(async () => moved)
const { logical, deps, supervisor } = await startOffLan({ openRelay, resolveRelay })
expect(openRelay).toHaveBeenCalledTimes(1)
expect(resolveRelay).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(15_000)
expect(resolveRelay).toHaveBeenCalledOnce()
expect(resolveRelay).toHaveBeenCalledWith(expect.objectContaining({ timeoutMs: 5_000 }))
expect(deps.setRelayRouting).toHaveBeenCalledWith(host.id, moved)
expect(openRelay).toHaveBeenLastCalledWith(
moved,
expect.anything(),
expect.any(String),
expect.any(Function)
)
expect(logical.getActivePath()).toBe('relay')
supervisor.stop()
})
it('gives the next resolve 10s after one times out', async () => {
const resolveRelay = vi.fn(async (_input: { timeoutMs?: number }) => {
throw new RelayDirectorResolveTimeoutError(5_000)
})
const { supervisor } = await startOffLan({ resolveRelay })
// Resolves are at least 5 minutes apart within an offline episode.
await vi.advanceTimersByTimeAsync(12 * 60_000)
const budgets = resolveRelay.mock.calls.map(([input]) => input.timeoutMs)
expect(budgets.length).toBeGreaterThanOrEqual(2)
expect(budgets[0]).toBe(5_000)
expect(budgets.slice(1).every((timeoutMs) => timeoutMs === 10_000)).toBe(true)
supervisor.stop()
})
it('asks the director only a few times while a laptop sleeps for two hours', async () => {
// The director keeps naming the same cell; the edge keeps answering 4404.
const resolveRelay = vi.fn(async ({ relay: current }: { relay: typeof relay }) => current)
const { deps, supervisor } = await startOffLan({ resolveRelay })
await vi.advanceTimersByTimeAsync(2 * 60 * 60_000)
// Gaps of 5, 10, 20, 40 min: resolves near 0, 5, 15, 35 and 75 min.
expect(resolveRelay.mock.calls.length).toBeGreaterThanOrEqual(5)
expect(resolveRelay.mock.calls.length).toBeLessThanOrEqual(6)
// Unchanged answers neither re-route nor add an immediate redial: 4404 pacing alone (5-15s).
expect(deps.setRelayRouting).not.toHaveBeenCalled()
expect(vi.mocked(deps.openRelay).mock.calls.length).toBeLessThanOrEqual(120 * 4 + 1)
supervisor.stop()
})
it('logs cooldown deferrals with their remaining time, at most once per window', async () => {
const { logical, logs, supervisor } = await startOffLan({})
// An unroutable LAN address fails fast; each direct state flap re-enters relay recovery.
for (let i = 0; i < 10; i++) {
logical.publishState('reconnecting')
logical.publishState('disconnected')
await vi.advanceTimersByTimeAsync(1_000)
}
const deferrals = logs.filter((entry) => entry.message.startsWith('Relay: recovery deferred'))
expect(deferrals).toHaveLength(1)
expect(deferrals[0].message).toBe('Relay: recovery deferred by cooldown')
expect(deferrals[0].detail).toMatch(/^retryInMs=\d+$/)
supervisor.stop()
})
})
@@ -1,75 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { dialRelayThroughDirectorFallback } from './mobile-relay-director-fallback'
import { RelayHostOfflineStreak } from './relay-host-offline-streak'
import { RelayOuterError } from '../encryption/mobile-relay-e2ee-link'
const relay = {
v: 1 as const,
directorUrl: 'https://relay.onorca.dev',
cellUrl: 'https://relay-edge.onorca.dev',
assignmentEpoch: 7,
relayHostId: 'AbCdEf0123_-xyZ9',
e2eeFraming: 2 as const
}
const hostOffline = { ok: false as const, error: new RelayOuterError(4404) }
const attachTimeout = {
ok: false as const,
error: new RelayOuterError(4404, false, 'attach-timeout')
}
function dialer(
results: { ok: boolean; error?: Error }[],
resolved: typeof relay = { ...relay, cellUrl: 'https://relay-hk.onorca.dev', assignmentEpoch: 8 }
) {
const streak = new RelayHostOfflineStreak(() => null)
const resolveRelay = vi.fn(async () => resolved)
const persistResolvedRelay = vi.fn(async () => {})
const queue = [...results]
const dial = vi.fn(async () => {
const next = queue.shift() ?? { ok: true }
return next.ok ? { ok: true as const } : { ok: false as const, error: next.error! }
})
const attempt = () =>
dialRelayThroughDirectorFallback({
resumeToken: 'A'.repeat(43),
hostOfflineStreak: streak,
relay: () => relay,
dial,
resolveRelay,
persistResolvedRelay
})
return { attempt, dial, resolveRelay, persistResolvedRelay }
}
describe('dialRelayThroughDirectorFallback on host-offline', () => {
it('resolves on the second consecutive 4404 and redials the moved cell once', async () => {
const { attempt, dial, resolveRelay } = dialer([hostOffline, hostOffline, { ok: true }])
await expect(attempt()).resolves.toEqual(hostOffline)
expect(resolveRelay).not.toHaveBeenCalled()
await expect(attempt()).resolves.toEqual({ ok: true })
expect(resolveRelay).toHaveBeenCalledOnce()
expect(dial).toHaveBeenCalledTimes(3)
})
it('does not redial when the director still names the same cell', async () => {
const { attempt, dial, resolveRelay, persistResolvedRelay } = dialer(
[hostOffline, hostOffline],
relay
)
await attempt()
await expect(attempt()).resolves.toEqual(hostOffline)
expect(resolveRelay).toHaveBeenCalledOnce()
expect(persistResolvedRelay).not.toHaveBeenCalled()
expect(dial).toHaveBeenCalledTimes(2)
})
it('never resolves on attach timeouts, which prove the desktop is seated on this cell', async () => {
const { attempt, resolveRelay } = dialer([attachTimeout, attachTimeout, attachTimeout])
for (let i = 0; i < 3; i++) {
await attempt()
}
expect(resolveRelay).not.toHaveBeenCalled()
})
})
@@ -1,32 +0,0 @@
import { expect, it } from 'vitest'
import { createDroidSessionResumeState } from './session-scanner-droid-parser'
import type { TranscriptMessage } from '../../transcripts/session-transcript-consumers'
it.each([413, 256 * 1024 + 1])(
'publishes %i-character Droid content before preview limits',
async (length) => {
const messages: TranscriptMessage[] = []
const state = createDroidSessionResumeState(
{ path: 'droid-session.jsonl', mtimeMs: 1, modifiedAt: '2026-05-01T00:00:00.000Z' },
{ active: true, push: (message) => messages.push(message) }
)
const text = 'x'.repeat(length)
state.consumeLine(
JSON.stringify({
type: 'message',
message: { role: 'assistant', content: [{ type: 'text', text }] }
})
)
state.consumeLine(JSON.stringify({ type: 'message', role: 'user', text }))
expect(messages).toEqual(
['assistant', 'user'].map((role) => ({
role,
text: text.slice(0, 256 * 1024),
timestamp: null,
...(length > 256 * 1024 ? { textTruncated: true } : {})
}))
)
const session = await state.finalize('linux')
expect(session?.previewMessages.map((message) => message.text.length)).toEqual([220, 220])
}
)
@@ -1,32 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import {
ExternalAutomationProbeCancelledError,
ExternalAutomationProbeScheduler
} from './external-automation-probe-scheduler'
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
let resolve!: (value: T) => void
const promise = new Promise<T>((res) => {
resolve = res
})
return { promise, resolve }
}
describe('ExternalAutomationProbeScheduler', () => {
it('does not start a duplicate key while cancelled provider work is still settling', async () => {
const scheduler = new ExternalAutomationProbeScheduler({ concurrency: 2 })
const never = deferred<string>()
const run = vi.fn(() => never.promise)
const first = scheduler.schedule({ key: 'openclaw@self', scopeKey: 'self', run })
scheduler.cancelAll()
const second = scheduler.schedule({ key: 'openclaw@self', scopeKey: 'self', run })
await expect(first).rejects.toBeInstanceOf(ExternalAutomationProbeCancelledError)
await expect(second).rejects.toBeInstanceOf(ExternalAutomationProbeCancelledError)
expect(run).toHaveBeenCalledTimes(1)
never.resolve('ignored')
await vi.waitFor(() => expect(scheduler.inFlight).toBe(0))
})
})
@@ -1,33 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
_getSidecarSnapshotPendingFileCountForTests,
withSidecarSnapshotQueue
} from './sidecar-snapshot-file'
describe('sidecar snapshot queues', () => {
it('releases completed per-file queue entries', async () => {
const gate = Promise.withResolvers<void>()
let started = 0
const tasks = Array.from({ length: 600 }, (_, index) =>
withSidecarSnapshotQueue(`snapshot-${index}`, async () => {
started += 1
await gate.promise
return `result-${index}`
})
)
try {
await Promise.resolve()
expect(started).toBe(600)
expect(_getSidecarSnapshotPendingFileCountForTests()).toBe(600)
} finally {
gate.resolve()
}
expect(await Promise.all(tasks)).toEqual(
Array.from({ length: 600 }, (_, index) => `result-${index}`)
)
await Promise.resolve()
expect(_getSidecarSnapshotPendingFileCountForTests()).toBe(0)
})
})
@@ -1,33 +0,0 @@
import { afterEach, describe, expect, it } from 'vitest'
import { resolveGitAdmissionTier } from './git-operation-executor'
import { _resetGitAdmissionForTests } from './git-subprocess-admission'
import {
worktreeCreateGit,
worktreePreparationGit
} from '../../worktrees/creation/worktree-create-git-executor'
afterEach(() => _resetGitAdmissionForTests())
describe('Git operation execution policy', () => {
it('isolates concurrent callers and restores the create policy after nested work', async () => {
const entered = Promise.withResolvers<void>()
const finish = Promise.withResolvers<void>()
const create = worktreeCreateGit.run(async () => {
expect(resolveGitAdmissionTier()).toBe('interactive')
await worktreePreparationGit.run(async () => {
await Promise.resolve()
expect(resolveGitAdmissionTier()).toBe('status')
})
entered.resolve()
await finish.promise
expect(resolveGitAdmissionTier()).toBe('interactive')
expect(resolveGitAdmissionTier('background')).toBe('background')
})
await entered.promise
expect(resolveGitAdmissionTier()).toBe('status')
finish.resolve()
await create
expect(resolveGitAdmissionTier()).toBe('status')
})
})
@@ -1,34 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
const safeStorageMock = vi.hoisted(() => ({
isEncryptionAvailable: vi.fn(() => true),
encryptString: vi.fn((value: string) => Buffer.from(`sealed:${value}`)),
decryptString: vi.fn((cipher: Buffer) => cipher.toString().replace('sealed:', ''))
}))
vi.mock('electron', () => ({ safeStorage: safeStorageMock }))
const {
guardedSafeStorage,
resetSafeStorageWithholdForTests,
safeStorageWithheldReason,
withholdSafeStorage
} = await import('./safe-storage-availability')
describe('guardedSafeStorage', () => {
afterEach(() => {
resetSafeStorageWithholdForTests()
vi.clearAllMocks()
})
it('never reaches the native keychain once withheld', () => {
withholdSafeStorage('no default keychain')
withholdSafeStorage('a later reason')
expect(safeStorageWithheldReason()).toBe('no default keychain')
expect(guardedSafeStorage.isEncryptionAvailable()).toBe(false)
expect(() => guardedSafeStorage.encryptString('token')).toThrow('secrets_unavailable')
expect(() => guardedSafeStorage.decryptString(Buffer.from('x'))).toThrow('secrets_unavailable')
expect(safeStorageMock.isEncryptionAvailable).not.toHaveBeenCalled()
expect(safeStorageMock.encryptString).not.toHaveBeenCalled()
})
})
@@ -1,33 +0,0 @@
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, expect, it } from 'vitest'
import { readLocalFileRange } from './local-file-range-read'
let folder: string
beforeEach(async () => {
folder = await mkdtemp(join(tmpdir(), 'orca-file-range-'))
})
afterEach(async () => {
await rm(folder, { recursive: true, force: true })
})
it('reads only the requested bytes and reports partial and past-EOF ranges', async () => {
const file = join(folder, 'records.csv')
await writeFile(file, '0123456789')
await expect(readLocalFileRange(file, 3, 4)).resolves.toEqual({
contentBase64: Buffer.from('3456').toString('base64'),
bytesRead: 4,
eof: false
})
await expect(readLocalFileRange(file, 8, 4)).resolves.toEqual({
contentBase64: Buffer.from('89').toString('base64'),
bytesRead: 2,
eof: true
})
await expect(readLocalFileRange(file, 12, 4)).resolves.toEqual({
contentBase64: '',
bytesRead: 0,
eof: true
})
})
@@ -1,33 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type { WebContents } from 'electron'
import { TerminalPreviewOutputStream } from './terminal-preview-output-stream'
function makeStream(): TerminalPreviewOutputStream {
const contents = {
id: 1,
isDestroyed: () => false,
send: vi.fn()
} as unknown as WebContents
return new TerminalPreviewOutputStream(
contents,
'p1',
() => undefined,
() => undefined
)
}
// Preserve chunk mode: replaying post-snapshot kitty pushes as redelivery corrupts the later pop.
describe('TerminalPreviewOutputStream.completeSnapshot', () => {
it('slices a partially covered chunk and keeps the suffix live', () => {
const stream = makeStream()
stream.append('abc', { seq: 7, rawLength: 3 })
expect(stream.completeSnapshot(6)).toEqual([{ data: 'c', mode: 'live' }])
})
it('falls back to replay mode for an unsliceable transformed overlap', () => {
const stream = makeStream()
// Transformed bytes cannot be split by raw offsets; preserve uncertain redelivery.
stream.append('abc', { seq: 7, rawLength: 3, transformed: true })
expect(stream.completeSnapshot(6)).toEqual([{ data: 'abc', mode: 'replay' }])
})
})
@@ -1,32 +0,0 @@
import { describe, expect, it } from 'vitest'
import { deriveQueuePauses, journalQueuePauseRestatement } from './queued-message-pause'
import { createJournalQueuePauseMarks } from './queued-message-pause-marks'
const card = (messageId: string) => ({
messageId,
state: 'waiting',
holdReason: null,
queuedAt: { epoch: 'epoch', sequence: 2 }
})
const marks = () => ({
...createJournalQueuePauseMarks(),
cleared: { sequence: 5, operationId: 'clear', messageIds: ['before-one', 'before-two'] }
})
const pauses = (cards = [card('before-one'), card('before-two')], m = marks(), accepted = 0) =>
deriveQueuePauses({
epoch: 'epoch',
marks: m,
latestAcceptedTurnSequence: accepted,
cards,
reopenFloor: null
})
describe('exact waiting-card membership after context clear', () => {
it('restates an explicit lift when rewind retires the accepted turn', () => {
const prior = marks()
const cards = [card('before-one'), card('before-two')]
const restated = journalQueuePauseRestatement(prior, 6, pauses(cards, prior, 6)).cleared!
expect(restated.lifted).toBe(true)
expect(pauses(cards, { ...prior, cleared: { ...restated, sequence: 10 } }, 0)).toEqual([])
})
})
@@ -1,32 +0,0 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { forkTestSource } from './structured-agent-session-fork.test-fixture'
import {
createRestTestRig,
type RestTestRig
} from '../../host/testing/structured-agent-session-rest-test-rig.test-fixture'
import { setStructuredAgentSessionHost } from '../../host/structured-agent-session-registry'
let rig: RestTestRig
beforeEach(async () => {
rig = await createRestTestRig({ idleSweep: { intervalMs: 60_000 } })
})
afterEach(async () => {
setStructuredAgentSessionHost(null)
await rig.dispose()
vi.restoreAllMocks()
})
it('saves a fork under its source name, with no " fork" suffix', async () => {
const test = forkTestSource(rig)
test.record.conversationName = 'Annotate capabilities'
const params = await test.prepare()
expect(test.copy.mock.calls[0]![0].title).toBe('Annotate capabilities')
expect(params.adopt?.conversationName).toBe('Annotate capabilities')
})
it('saves a fork of an unnamed chat under the agent default label', async () => {
const test = forkTestSource(rig)
test.record.conversationName = undefined
await test.prepare()
expect(test.copy.mock.calls[0]![0].title).toBe('Codex Chat')
})
@@ -1,33 +0,0 @@
import { EventEmitter } from 'node:events'
import { describe, expect, it, vi } from 'vitest'
const { httpRequestMock, httpsRequestMock } = vi.hoisted(() => ({
httpRequestMock: vi.fn(),
httpsRequestMock: vi.fn()
}))
vi.mock('node:http', () => ({ request: httpRequestMock }))
vi.mock('node:https', () => ({ request: httpsRequestMock }))
import { postJsonForJson } from './diagnostic-upload-http'
class FakeRequest extends EventEmitter {
destroy = vi.fn()
end = vi.fn()
write = vi.fn()
}
describe('diagnostic upload HTTP', () => {
it('handles the asynchronous socket error after a request timeout until close', async () => {
const request = new FakeRequest()
httpRequestMock.mockReturnValueOnce(request)
const result = postJsonForJson('http://diagnostics.example/upload', {}, 1000)
request.emit('timeout')
await expect(result).rejects.toThrow('diagnostic network request timed out')
expect(request.destroy).toHaveBeenCalledOnce()
expect(() => request.emit('error', new Error('socket hang up'))).not.toThrow()
request.emit('close')
expect(request.eventNames()).toEqual([])
})
})
@@ -1,33 +0,0 @@
/** An incomplete GC live set deletes owned history; regressions here caused the #14863 revert (#14975). */
import { describe, expect, it } from 'vitest'
import { getKnownWorktreeIdsForHistoryGc } from './history-gc-worktree-ids'
const noOtherProfiles = () => ({ ids: new Set<string>(), unreadableProfiles: 0 })
const store = (worktreeIds: string[], folderIds: string[]) =>
({
getAllWorktreeMeta: () => Object.fromEntries(worktreeIds.map((id) => [id, {}])),
getFolderWorkspaces: () => folderIds.map((id) => ({ id }))
}) as never
describe('getKnownWorktreeIdsForHistoryGc', () => {
it('includes git worktrees', () => {
expect(
getKnownWorktreeIdsForHistoryGc(store(['repo-1::/path/wt'], []), noOtherProfiles)
).toEqual(new Set(['repo-1::/path/wt']))
})
// Folder PTYs mint history under folder:<id>; omitting their separate store collection falsely marks live history orphaned.
// History is not profile-scoped, so other profiles must remain in the live set.
// Unreadable profiles make ownership unknown; empty means prune nothing, while partial IDs would delete live history.
it('reports nothing live when a profile could not be read', () => {
const live = getKnownWorktreeIdsForHistoryGc(store(['repo-1::/b'], ['fw-b']), () => ({
ids: new Set(['repo-1::/a']),
unreadableProfiles: 1
}))
expect(live.size).toBe(0)
})
})
@@ -1,32 +0,0 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { HeadlessEmulator } from '../../daemon/emulation/headless-emulator'
import { visibleNonBlankTerminalLines } from '../terminal/output/tail/terminal-tail-read'
import { evaluateAgentStateRules } from './agent-state-rules-engine'
async function verdictFor(fixture: string) {
const emulator = new HeadlessEmulator({ cols: 120, rows: 40 })
await emulator.write(
readFileSync(join(__dirname, '..', '__fixtures__', `${fixture}.txt`), 'utf8')
)
const lines = visibleNonBlankTerminalLines(emulator.getVisibleLines())
emulator.dispose()
return evaluateAgentStateRules('antigravity', { readScreenLines: () => lines })
}
describe('antigravity composer with background task rows', () => {
it.each([
'antigravity-1-4-11-ready-background-task',
'antigravity-1-4-11-ready-two-background-tasks'
])('reads %s as a strong idle composer', async (fixture) => {
expect(await verdictFor(fixture)).toMatchObject({ state: 'idle', strength: 'strong' })
})
it.each([
'antigravity-1-4-11-busy-with-background-task',
'antigravity-1-4-11-draft-with-background-task'
])('holds %s', async (fixture) => {
expect(await verdictFor(fixture)).toMatchObject({ state: 'hold' })
})
})
@@ -1,33 +0,0 @@
import { describe, expect, it } from 'vitest'
import { BrowserHostPagePlacementRegistry } from './browser-host-page-placement'
const host = {
browserHostClientId: 'host-a',
browserHostGeneration: 1
}
const registry = (maxPagePlacements = 256): BrowserHostPagePlacementRegistry =>
new BrowserHostPagePlacementRegistry(
{ authorityRuntimeId: 'runtime-a', authorityEpoch: 'epoch-a' },
{ maxPagePlacements }
)
describe('browser page placement replacement barrier', () => {
it('keeps capacity occupied until exact retirement and preserves generations', () => {
const pages = registry(1)
const original = pages.placeClientPage('page-a', host)
expect(() => pages.placeClientPage('page-a', host)).toThrow(
'browser_page_replacement_requires_retirement'
)
expect(() => pages.placeServerPage('page-b')).toThrow('browser_page_placement_capacity')
const retirement = pages.beginPageRetirement('page-a', original)
expect(pages.completePageRetirement(retirement)).toBe(true)
const replacement = pages.placeClientPage('page-a', host)
expect(replacement.pageHostGeneration).toBe(original.pageHostGeneration + 1)
expect(pages.completePageRetirement(retirement)).toBe(false)
expect(() => pages.placeServerPage('page-b')).toThrow('browser_page_placement_capacity')
expect(pages.getPlacement('page-a')).toBe(replacement)
})
})
@@ -1,33 +0,0 @@
/** Shared screencast subscriptions must not give desktop/web/CLI viewers a phone's input lock. */
import { describe, expect, it, vi } from 'vitest'
import {
createScreencastHarness,
HARNESS_PAGE_ID as PAGE
} from './browser-screencast-subscriber-test-harness'
vi.mock('electron', () => ({
ipcMain: { on: vi.fn(), removeListener: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() },
webContents: { fromId: vi.fn() }
}))
describe('browser screencast driver attribution', () => {
it('take-back cancels the phone stream and leaves a desktop viewer streaming', async () => {
const { runtime, subscribe, driver } = createScreencastHarness()
const phone = subscribe({ connectionId: 'conn-phone', clientKind: 'mobile' })
await phone.streaming()
expect(driver()).toEqual({ kind: 'mobile', clientId: 'conn-phone' })
const desktop = subscribe({ connectionId: 'conn-desktop', clientKind: 'runtime' })
await desktop.streaming()
runtime.reclaimBrowserForDesktop(PAGE)
await phone.done
expect(driver()).toEqual({ kind: 'desktop' })
expect(phone.stops()).toBe(1)
expect(desktop.stops()).toBe(0)
desktop.stop()
await desktop.done
// Prove the counter can move; zero alone could be a vacuous assertion.
expect(desktop.stops()).toBeGreaterThan(0)
})
})
@@ -1,31 +0,0 @@
import { describe, expect, it } from 'vitest'
import { RECENT_PTY_OUTPUT_LIMIT, RecentPtyOutputBuffer } from './recent-pty-output-buffer'
function heapAfterGc(): number {
if (!('gc' in globalThis) || typeof globalThis.gc !== 'function') {
throw new Error('The test runner must enable --expose-gc')
}
globalThis.gc()
globalThis.gc()
return process.memoryUsage().heapUsed
}
describe('recent PTY output retention', () => {
it('releases oversized parent strings', () => {
const count = 8
const before = heapAfterGc()
const buffers = Array.from({ length: count }, (_value, index) => {
const buffer = new RecentPtyOutputBuffer()
buffer.append(`${index}:${'x'.repeat(4 * 1024 * 1024)}`)
return buffer
})
const growth = heapAfterGc() - before
expect(growth).toBeLessThan(count * RECENT_PTY_OUTPUT_LIMIT * 4)
for (const buffer of buffers) {
expect(buffer.read()).toBe('x'.repeat(RECENT_PTY_OUTPUT_LIMIT))
buffer.append('next')
expect(buffer.read()).toBe(`${'x'.repeat(RECENT_PTY_OUTPUT_LIMIT - 4)}next`)
}
})
})
@@ -1,33 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { createDraftPasteReadyScanner } from '../../../../shared/draft-paste-ready-scanner'
import { readRuntimeFixture } from './agent-transcript-replay-test-harness'
vi.mock('electron', () => ({
BrowserWindow: { fromId: vi.fn(() => null) },
webContents: { fromId: vi.fn(() => null) },
ipcMain: { on: vi.fn(), removeListener: vi.fn() },
app: { getPath: vi.fn(() => '/tmp') }
}))
describe('the Claude composer marker', () => {
const firesOn = (fixture: string): boolean => {
const scanner = createDraftPasteReadyScanner('claude-composer-prompt')
return scanner.observe(readRuntimeFixture(fixture)).ready
}
it('does not fire on the workspace-trust menu, which draws the same pointer', () => {
expect(readRuntimeFixture('claude-dialog-trust-workspace')).toContain('❯')
expect(firesOn('claude-dialog-trust-workspace')).toBe(false)
})
// A powerlevel10k/starship prompt draws the same `❯` + NBSP after the shell's own DECSET 2004.
const SHELL_PROMPT = '\x1b[?2004h~/repo \x1b[32m❯ \x1b[0m'
it('does not fire on a shell prompt that draws the same glyph', () => {
// Presence precondition: the shell turns bracketed paste on just as Claude does.
expect(readRuntimeFixture('zsh-prompt-runs-command')).toContain('\x1b[?2004h')
const scanner = createDraftPasteReadyScanner('claude-composer-prompt')
expect(scanner.observe(readRuntimeFixture('zsh-prompt-runs-command')).ready).toBe(false)
expect(scanner.observe(SHELL_PROMPT).ready).toBe(false)
})
})
@@ -1,31 +0,0 @@
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { findSkillFiles } from '../discovery/skill-root-file-walk'
import { skillDeleteStagedName } from '../skill-delete/skill-delete-staging-names'
const roots: string[] = []
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
async function stagedRoot(stagedName: string): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-staging-visibility-'))
roots.push(root)
const staged = join(root, stagedName)
await mkdir(staged, { recursive: true })
await writeFile(join(staged, 'SKILL.md'), '---\nname: demo\n---\n')
return root
}
describe('native walker', () => {
it('still finds an ordinary skill beside a staged one', async () => {
const root = await stagedRoot(skillDeleteStagedName('demo', 'id'))
const real = join(root, 'demo')
await mkdir(real)
await writeFile(join(real, 'SKILL.md'), '---\nname: demo\n---\n')
expect(await findSkillFiles(root, 4)).toEqual([join(real, 'SKILL.md')])
})
})
@@ -1,67 +0,0 @@
import { describe, expect, it } from 'vitest'
import { textInkBox } from './markup-shape-render'
// Record the context subset drawShape uses without requiring a real canvas.
function makeRecordingCtx() {
const calls: { method: string; args: unknown[] }[] = []
const record =
(method: string) =>
(...args: unknown[]) => {
calls.push({ method, args })
}
const ctx = {
save: record('save'),
restore: record('restore'),
beginPath: record('beginPath'),
moveTo: record('moveTo'),
lineTo: record('lineTo'),
arc: record('arc'),
ellipse: record('ellipse'),
stroke: record('stroke'),
fill: record('fill'),
strokeRect: record('strokeRect'),
fillText: record('fillText'),
strokeText: record('strokeText'),
// Records the style in force when measuring, and returns fixed ink metrics.
measureText: () => {
calls.push({ method: 'measureText', args: [ctx.font, ctx.textBaseline] })
return {
actualBoundingBoxLeft: 1,
actualBoundingBoxRight: 40,
actualBoundingBoxAscent: -2,
actualBoundingBoxDescent: 20
}
},
lineCap: '',
lineJoin: '',
strokeStyle: '',
fillStyle: '',
lineWidth: 0,
globalAlpha: 1,
font: '',
textBaseline: ''
}
const methods = (name: string) => calls.filter((c) => c.method === name)
return { ctx: ctx as unknown as CanvasRenderingContext2D, calls, methods }
}
describe('textInkBox', () => {
it('covers the measured glyphs plus the halo, measured in the style text is drawn with', () => {
const { ctx, methods } = makeRecordingCtx()
const box = textInkBox(ctx, {
id: 't',
kind: 'text',
color: '#111827',
at: { x: 100, y: 200 },
text: 'gy',
fontSize: 18
})
const [font, textBaseline] = methods('measureText')[0].args
expect(font).toContain('18px')
expect(textBaseline).toBe('top')
// The halo is 3px wide at 18px type, so it adds 1.5px on every side.
expect(box).toEqual({ x: 97.5, y: 200.5, width: 44, height: 21 })
})
})
@@ -1,21 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { MarkdownPreviewDocumentEngine } from './markdown-preview-document-engine'
import type * as DocumentTypes from './markdown-preview-document-types'
vi.mock('./markdown-preview-document-types', async () => ({
...(await vi.importActual<typeof DocumentTypes>('./markdown-preview-document-types')),
MARKDOWN_PREVIEW_SEARCH_TEXT_MAX_BYTES: 32,
MARKDOWN_PREVIEW_SEARCH_TEXT_MAX_NODES: 3
}))
describe('large preview search index budgets', () => {
it('bounds retained text bytes, leaves viewport rendering available, and resets on replacement', async () => {
const engine = new MarkdownPreviewDocumentEngine()
engine.load('12345678\n\nabcdefgh\n\nexhaust')
await expect(engine.search('missing')).rejects.toThrow('search limit')
await expect(engine.search('123')).rejects.toThrow('search limit')
expect(engine.blocks([2])[0].oversized).toBe(false)
engine.load('# New')
expect((await engine.search('New'))?.matches).toHaveLength(1)
})
})
@@ -1,15 +0,0 @@
import { describe, expect, it } from 'vitest'
import { MarkdownPreviewDocumentEngine } from './markdown-preview-document-engine'
describe('large preview searchable text ownership', () => {
it('cancels indexing, retains completed text, and clears it on document replacement', async () => {
const engine = new MarkdownPreviewDocumentEngine()
engine.load('needle\n\n'.repeat(100))
const pending = engine.search('needle')
engine.cancelSearch()
expect(await pending).toBeNull()
expect((await engine.search('needle'))?.matches).toHaveLength(100)
engine.load('needle replacement')
expect((await engine.search('replacement'))?.matches).toHaveLength(1)
})
})
@@ -1,58 +0,0 @@
import type { GlobalSettings } from '../../../../../shared/global-settings-types'
import { getDefaultSettings } from '../../../../../shared/constants'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const mock = vi.hoisted(
(): {
state: {
settings: GlobalSettings | null
updateSettings: (updates: Partial<GlobalSettings>) => Promise<void>
}
} => ({ state: { settings: null, updateSettings: async () => {} } })
)
vi.mock('../../../store/index', () => ({ useAppStore: { getState: () => mock.state } }))
import { writeNativeChatAppearance } from './native-chat-appearance-write'
import { writeNativeChatFontSize } from './native-chat-font-size-write'
beforeEach(() => {
mock.state.settings = getDefaultSettings('/tmp')
})
describe('chat appearance write queue', () => {
it('serializes card and zoom changes against the latest published settings', async () => {
let releaseFirst: () => void = () => {}
const firstWrite = new Promise<void>((resolve) => {
releaseFirst = resolve
})
let calls = 0
const updateSettings = vi.fn(async (updates: Partial<GlobalSettings>) => {
calls += 1
if (calls === 1) {
await firstWrite
}
mock.state.settings = { ...mock.state.settings!, ...updates }
})
mock.state.updateSettings = updateSettings
const fromNewerVersion = { fontSize: 14, contrast: 151, futureSetting: 'keep' }
mock.state.settings = {
...getDefaultSettings('/tmp'),
nativeChatAppearance: fromNewerVersion
}
const cardWrite = writeNativeChatAppearance((current) => ({ ...current, codeFontSize: 16 }))
const zoomWrite = writeNativeChatFontSize('increase')
await vi.waitFor(() => expect(updateSettings).toHaveBeenCalledTimes(1))
releaseFirst()
await Promise.all([cardWrite, zoomWrite])
expect(updateSettings).toHaveBeenCalledTimes(2)
expect(mock.state.settings?.nativeChatAppearance).toEqual({
contrast: 150,
futureSetting: 'keep',
codeFontSize: 16,
fontSize: 15
})
})
})
@@ -1,65 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types'
import {
nativeChatSentPrompts,
stepNativeChatPromptRecall
} from './native-chat-sent-prompt-history'
function message(
id: string,
role: NativeChatMessage['role'],
text: string,
extra: Partial<NativeChatMessage> = {}
): NativeChatMessage {
return {
id,
role,
blocks: text ? [{ type: 'text', text }] : [],
timestamp: null,
source: 'transcript',
...extra
}
}
describe('nativeChatSentPrompts', () => {
it('recalls a structured prompt without the markers of images recall cannot bring back', () => {
const image = { type: 'image-ref' as const, path: '/tmp/a.png' }
const messages = [
message('1', 'user', '', { blocks: [image, { type: 'text', text: '[Image #1] ' }] }),
message('2', 'user', '', { blocks: [image, { type: 'text', text: 'fix [Image #1]' }] })
]
expect(nativeChatSentPrompts({ messages, withoutImageMarkers: true })).toEqual([
{ id: '2', prompt: 'fix' }
])
const typed = [
message('3', 'user', '[Image #1]'),
message('4', 'user', '', { blocks: [image, { type: 'text', text: 'not [Image #2]' }] })
]
expect(nativeChatSentPrompts({ messages: typed, withoutImageMarkers: true })).toEqual([
{ id: '3', prompt: '[Image #1]' },
{ id: '4', prompt: 'not [Image #2]' }
])
// A terminal chat's transcript text is the agent's own, markers included.
expect(nativeChatSentPrompts({ messages }).map(({ prompt }) => prompt)).toEqual([
'[Image #1]',
'fix [Image #1]'
])
})
})
describe('stepNativeChatPromptRecall', () => {
const prompts = [
{ id: '1', prompt: 'one' },
{ id: '2', prompt: 'two' }
]
it('keeps its place when the recalled echo is replaced by its transcript turn', () => {
const step = stepNativeChatPromptRecall({
direction: 'back',
prompts,
position: { id: 'pending:9', recalled: 'two' },
draft: 'two'
})
expect(step?.draft).toBe('one')
})
})
@@ -1,67 +0,0 @@
// @vitest-environment happy-dom
import { act, cleanup, renderHook } from '@testing-library/react'
import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { NativeChatReplyRevealsContext } from './native-chat-reply-reveals'
import type { NativeChatReplyReveals } from '../../../../../shared/native-chat/transcript/row-content/native-chat-reply-reveals'
import { useNativeChatPacedText } from './use-native-chat-paced-text'
const motion = vi.hoisted(() => ({ reduced: false }))
vi.mock('@/hooks/usePrefersReducedMotion', () => ({
usePrefersReducedMotion: () => motion.reduced
}))
function transcript(): NativeChatReplyReveals {
return { begun: new Set(['reply']), drawn: new Map() }
}
function within(reveals = transcript()) {
return function Transcript({ children }: { children: ReactNode }) {
return (
<NativeChatReplyRevealsContext.Provider value={reveals}>
{children}
</NativeChatReplyRevealsContext.Provider>
)
}
}
function advance(ms: number): void {
act(() => vi.advanceTimersByTime(ms))
}
beforeEach(() => {
motion.reduced = false
vi.useFakeTimers({
toFake: [
'setTimeout',
'clearTimeout',
'requestAnimationFrame',
'cancelAnimationFrame',
'performance'
]
})
})
afterEach(() => {
cleanup()
vi.useRealTimers()
})
describe('fixed latency text reveal', () => {
it('keeps the original deadline through a reconnect and remount', () => {
const wrapper = within()
const row = renderHook(() => useNativeChatPacedText('reply', 'a '.repeat(1000), true), {
wrapper
})
advance(100)
const shown = row.result.current.text.length
expect(shown).toBeGreaterThan(0)
expect(shown).toBeLessThan(2000)
row.unmount()
advance(200)
const returned = renderHook(() => useNativeChatPacedText('reply', 'a '.repeat(1000), true), {
wrapper
})
expect(returned.result.current.text.length).toBeGreaterThan(shown)
advance(50)
expect(returned.result.current.text).toHaveLength(2000)
})
})
@@ -1,53 +0,0 @@
// @vitest-environment happy-dom
import { cleanup, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { WorkspaceSetupChoice } from './WorkspaceSetupChoice'
afterEach(() => {
cleanup()
vi.useRealTimers()
})
describe('WorkspaceSetupChoice', () => {
it('brings the choice into view and focuses it on each reveal request', () => {
vi.useFakeTimers()
const scrollIntoView = vi.fn()
Element.prototype.scrollIntoView = scrollIntoView
const onRevealed = vi.fn()
const props = {
decision: null,
onChange: vi.fn(),
runLabel: 'Run',
skipLabel: 'Skip',
onRevealed
}
const { rerender } = render(<WorkspaceSetupChoice {...props} revealRequest={0} />)
vi.runAllTimers()
expect(scrollIntoView).not.toHaveBeenCalled()
// A second request matters too: Advanced may already be open from the first.
for (const revealRequest of [1, 2]) {
rerender(<WorkspaceSetupChoice {...props} revealRequest={revealRequest} />)
vi.runAllTimers()
expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Run' }))
}
expect(scrollIntoView).toHaveBeenCalledTimes(2)
// Each handled request is cleared so a remount after a project switch cannot replay it.
expect(onRevealed).toHaveBeenCalledTimes(2)
})
it('does not move focus onto Run when the user chose before the reveal fired', () => {
vi.useFakeTimers()
Element.prototype.scrollIntoView = vi.fn()
const onRevealed = vi.fn()
const props = { onChange: vi.fn(), runLabel: 'Run', skipLabel: 'Skip', onRevealed }
const { rerender } = render(
<WorkspaceSetupChoice {...props} decision={null} revealRequest={1} />
)
rerender(<WorkspaceSetupChoice {...props} decision="skip" revealRequest={1} />)
vi.runAllTimers()
expect(document.activeElement).not.toBe(screen.getByRole('button', { name: 'Run' }))
expect(onRevealed).toHaveBeenCalledTimes(1)
})
})
@@ -1,58 +0,0 @@
// @vitest-environment happy-dom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { pluginManifestSchema } from '../../../../../shared/plugins/manifest/plugin-manifest'
import { useInstalledPluginManifest } from './use-plugin-contribution-source'
const base = {
manifestVersion: 1,
id: 'notes',
publisher: 'acme',
name: 'Notes',
engines: { orca: '>=1.0.0' },
pluginApi: 1
}
const before = pluginManifestSchema.parse({ ...base, version: '1.0.0' })
const after = pluginManifestSchema.parse({ ...base, version: '2.0.0' })
let root: Root | null = null
afterEach(() => {
act(() => root?.unmount())
root = null
})
describe('useInstalledPluginManifest', () => {
it('forgets the old manifest when a same-key update changes the installed revision', async () => {
let resolveNext: (manifest: typeof after) => void = () => {}
const getInstalledManifest = vi
.fn()
.mockResolvedValueOnce(before)
.mockReturnValueOnce(new Promise((resolve) => (resolveNext = resolve)))
Object.defineProperty(window, 'api', {
configurable: true,
value: { plugins: { getInstalledManifest } }
})
const seen: unknown[] = []
function Probe({ revision }: { revision: string }): null {
seen.push(
useInstalledPluginManifest({
pluginKey: 'acme.notes',
consentFingerprint: revision,
source: undefined
})?.version
)
return null
}
root = createRoot(document.createElement('div'))
await act(async () => root?.render(<Probe revision="sha256-one" />))
expect(seen.at(-1)).toBe('1.0.0')
// Why undefined first: pairing 1.0.0's contents with the new fingerprint would misreport trust.
await act(async () => root?.render(<Probe revision="sha256-two" />))
expect(seen.at(-1)).toBeUndefined()
await act(async () => resolveNext(after))
expect(seen.at(-1)).toBe('2.0.0')
})
})
@@ -1,70 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types'
import type { Worktree } from '../../../../../../shared/worktree/types'
import { getWorkspaceLineageMenuActions } from './workspace-lineage-menu-actions'
function makeWorktree(id: string): Worktree {
return {
id,
instanceId: `${id}-instance`,
repoId: 'repo-1',
path: `/workspaces/${id}`,
head: 'abc123',
branch: id,
isBare: false,
isMainWorktree: false,
displayName: id,
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 1
}
}
function makeLineage(child: Worktree, parent: Worktree): WorktreeLineage {
return {
worktreeId: child.id,
worktreeInstanceId: child.instanceId ?? '',
parentWorktreeId: parent.id,
parentWorktreeInstanceId: parent.instanceId ?? '',
origin: 'manual',
capture: { source: 'manual-action', confidence: 'explicit' },
createdAt: 1
}
}
describe('workspace lineage menu actions', () => {
it('does not expose stale descendants through the recursive action scope', () => {
const parent = makeWorktree('parent')
const child = makeWorktree('child')
const actions = getWorkspaceLineageMenuActions({
parent,
worktrees: [parent, child],
lineageById: {
[child.id]: {
...makeLineage(child, parent),
parentWorktreeInstanceId: 'stale-parent-instance'
}
},
activity: {
tabsByWorktree: { [child.id]: [{ id: 'child-tab' }] },
ptyIdsByTabId: { 'child-tab': ['child-pty'] },
browserTabsByWorktree: {},
unifiedTabsByWorktree: {},
agentStatusByPaneKey: {},
structuredChatSleptAtByPaneKey: {}
}
})
expect(actions.descendants).toEqual([])
expect(actions.sleepableTargets).toEqual([])
})
})
@@ -1,68 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { DndContext } from '@dnd-kit/core'
import { cleanup, render, screen } from '@testing-library/react'
import { afterEach, expect, it } from 'vitest'
import { TooltipProvider } from '@/components/ui/tooltip'
import SortableTab from './SortableTab'
afterEach(cleanup)
const noop = (): void => {}
function renderChatTab(fork: boolean): void {
render(
<DndContext>
<TooltipProvider>
<SortableTab
tab={{ id: 'chat', worktreeId: 'w', title: 'Annotate', customTitle: null, color: null }}
agent="claude"
unifiedTabId="chat"
groupId="g"
tabCount={1}
hasTabsToRight={false}
hasTabsToLeft={false}
isActive
isPinned={false}
isExpanded={false}
onActivate={noop}
onClose={noop}
onCloseOthers={noop}
onCloseToRight={noop}
onCloseToLeft={noop}
onSetCustomTitle={noop}
onSetTabColor={noop}
onTogglePin={noop}
onToggleExpand={noop}
dragData={{
kind: 'tab',
worktreeId: 'w',
groupId: 'g',
unifiedTabId: 'chat',
visibleTabId: 'chat',
tabType: 'agent-session',
label: 'Annotate',
color: null
}}
canSplitTerminal={false}
fork={
fork
? { describeSource: () => 'Fork of Annotate', markedTitle: 'Fork · Annotate' }
: undefined
}
/>
</TooltipProvider>
</DndContext>
)
}
it("names a fork tab's close button after its marked title", () => {
renderChatTab(true)
expect(screen.getByRole('button', { name: 'Close tab Fork · Annotate' })).toBeInTheDocument()
expect(screen.getByText('Fork: Annotate')).toBeInTheDocument()
})
it('keeps the plain title on an original chat tab', () => {
renderChatTab(false)
expect(screen.getByRole('button', { name: 'Close tab Annotate' })).toBeInTheDocument()
})
@@ -1,58 +0,0 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
import { useTaskPageJiraSavedFilters } from './use-task-page-jira-saved-filters'
import { toRuntimeExecutionHostId } from '../../../../../../shared/execution-host'
const { read, mutate } = vi.hoisted(() => ({ read: vi.fn(), mutate: vi.fn() }))
vi.mock('@/runtime/jira/runtime-jira-saved-filter-state', () => ({
readJiraSavedFilterState: read,
mutateJiraSavedFilters: mutate
}))
afterEach(cleanup)
beforeEach(() => {
vi.resetAllMocks()
})
const filter = { id: 'mine', name: 'My work', jql: 'project = APP' }
const initial = { filters: [filter], activeFilterId: filter.id }
function model(
host: string | null,
accountHost = 'account-owner'
): Parameters<typeof useTaskPageJiraSavedFilters>[0] {
return {
taskSource: 'jira',
taskResumeApplied: true,
accountBackedTaskSourceHostId: toRuntimeExecutionHostId(accountHost),
jiraTaskSourceContext: host
? {
kind: 'task-source',
provider: 'jira',
projectId: 'project',
hostId: toRuntimeExecutionHostId(host)
}
: null
}
}
it('ignores an old host read that completes after switching execution hosts', async () => {
let resolveOld: (value: typeof initial) => void = () => {}
read
.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveOld = resolve
})
)
.mockResolvedValueOnce({ filters: [], activeFilterId: null })
const setQuery = vi.fn()
const { result, rerender } = renderHook(
({ host }) => useTaskPageJiraSavedFilters(model(host), setQuery),
{ initialProps: { host: 'host-a' } }
)
rerender({ host: 'host-b' })
await waitFor(() => expect(result.current.jiraSavedFiltersReady).toBe(true))
await act(async () => {
resolveOld(initial)
})
expect(result.current.jiraSavedFilters).toEqual([])
expect(setQuery).not.toHaveBeenCalledWith(filter.jql)
})
@@ -1,67 +0,0 @@
import { describe, expect, it } from 'vitest'
import { planTerminalLiveLayoutInsertions } from './terminal-live-layout-reconciliation'
import type { TerminalPaneLayoutNode } from '../../../../../../shared/workspace-layout/terminal-tab-types'
describe('planTerminalLiveLayoutInsertions', () => {
it('bridges a missing parent second subtree before filling the first subtree', () => {
const layout: TerminalPaneLayoutNode = {
type: 'split',
direction: 'vertical',
first: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', leafId: 'leaf-a' },
second: { type: 'leaf', leafId: 'leaf-b' }
},
second: { type: 'leaf', leafId: 'leaf-c' }
}
expect(planTerminalLiveLayoutInsertions(layout, ['leaf-a'])).toEqual([
{
sourceLeafId: 'leaf-a',
sourceLeafIds: ['leaf-a'],
newLeafId: 'leaf-c',
direction: 'vertical',
placement: 'after'
},
{
sourceLeafId: 'leaf-a',
sourceLeafIds: ['leaf-a'],
newLeafId: 'leaf-b',
direction: 'horizontal',
placement: 'after'
}
])
})
it('plans nested missing first subtrees from an anchor in the second subtree', () => {
const layout: TerminalPaneLayoutNode = {
type: 'split',
direction: 'vertical',
first: { type: 'leaf', leafId: 'leaf-a' },
second: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', leafId: 'leaf-b' },
second: { type: 'leaf', leafId: 'leaf-c' }
}
}
expect(planTerminalLiveLayoutInsertions(layout, ['leaf-c'])).toEqual([
{
sourceLeafId: 'leaf-c',
sourceLeafIds: ['leaf-c'],
newLeafId: 'leaf-a',
direction: 'vertical',
placement: 'before'
},
{
sourceLeafId: 'leaf-c',
sourceLeafIds: ['leaf-c'],
newLeafId: 'leaf-b',
direction: 'horizontal',
placement: 'before'
}
])
})
})
@@ -1,59 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
bufferPreHandlerPtyData,
bufferPreHandlerPtyExit,
clearPreHandlerPtyState,
drainPreHandlerPtyData,
drainPreHandlerPtyExit,
hasPreHandlerPtyExit
} from '../../pty-transport/delivery/pty-pre-handler-buffer'
import {
capturedPanesByTabId,
parkedWatchersByTabId,
pruneParkedTerminalWatchers
} from './terminal-parked-watcher-registry'
const TAB_ID = 'removed-parked-tab'
const PTY_ID = 'removed-worktree@@parked-pty'
const FLOATING_TAB_ID = 'floating-parked-tab'
describe('terminal parked watcher registry removal', () => {
afterEach(() => {
parkedWatchersByTabId.delete(TAB_ID)
parkedWatchersByTabId.delete(FLOATING_TAB_ID)
capturedPanesByTabId.delete(TAB_ID)
capturedPanesByTabId.delete(FLOATING_TAB_ID)
clearPreHandlerPtyState(PTY_ID)
})
it('consumes retained state and suppresses a delayed exit for a removed worktree', () => {
const dispose = vi.fn()
parkedWatchersByTabId.set(TAB_ID, {
worktreeId: 'removed-worktree',
tabPtyId: PTY_ID,
paneIdByPtyId: new Map([[PTY_ID, 1]]),
disposersByPtyId: new Map([[PTY_ID, dispose]])
})
bufferPreHandlerPtyData(PTY_ID, 'final frame')
bufferPreHandlerPtyExit(PTY_ID, 17)
pruneParkedTerminalWatchers(new Set())
expect(dispose).toHaveBeenCalledTimes(1)
expect(parkedWatchersByTabId.has(TAB_ID)).toBe(false)
expect(hasPreHandlerPtyExit(PTY_ID)).toBe(false)
const data = vi.fn()
drainPreHandlerPtyData(PTY_ID, data)
expect(data).not.toHaveBeenCalled()
// Why: the actual kill exit can arrive after sidecar disposal and prune.
bufferPreHandlerPtyExit(PTY_ID, 18)
bufferPreHandlerPtyData(PTY_ID, 'delayed final frame')
const exit = vi.fn()
const delayedData = vi.fn()
drainPreHandlerPtyExit(PTY_ID, exit)
drainPreHandlerPtyData(PTY_ID, delayedData)
expect(exit).not.toHaveBeenCalled()
expect(delayedData).not.toHaveBeenCalled()
})
})
@@ -1,55 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
INPUT_ECHO_DELAY_MAX_ALLOWANCE_MS,
createTerminalInputEchoDelay,
noteTerminalInputAwaitingEcho,
noteTerminalOutputAfterInput,
terminalInputEchoAllowanceMs
} from './terminal-input-echo-delay'
describe('terminal input echo delay', () => {
it('measures the round trip from the oldest unanswered input', () => {
const delay = createTerminalInputEchoDelay()
noteTerminalInputAwaitingEcho(delay, 1000)
noteTerminalInputAwaitingEcho(delay, 1040)
noteTerminalOutputAfterInput(delay, 1200)
expect(terminalInputEchoAllowanceMs(delay)).toBe(200)
})
it('stays at zero with no input, so output alone never widens the windows', () => {
const delay = createTerminalInputEchoDelay()
noteTerminalOutputAfterInput(delay, 5000)
expect(terminalInputEchoAllowanceMs(delay)).toBe(0)
})
it('takes the recent minimum so one slow frame cannot inflate it', () => {
const delay = createTerminalInputEchoDelay()
for (const [input, output] of [
[0, 210],
[1000, 1900],
[2000, 2205]
]) {
noteTerminalInputAwaitingEcho(delay, input)
noteTerminalOutputAfterInput(delay, output)
}
expect(terminalInputEchoAllowanceMs(delay)).toBe(205)
})
it('ignores output that cannot be the echo and clamps the allowance', () => {
const delay = createTerminalInputEchoDelay()
noteTerminalInputAwaitingEcho(delay, 0)
noteTerminalOutputAfterInput(delay, 5000)
expect(terminalInputEchoAllowanceMs(delay)).toBe(0)
noteTerminalInputAwaitingEcho(delay, 6000)
noteTerminalOutputAfterInput(delay, 6900)
expect(terminalInputEchoAllowanceMs(delay)).toBe(INPUT_ECHO_DELAY_MAX_ALLOWANCE_MS)
})
it('restarts a pending input that went unanswered past the sample limit', () => {
const delay = createTerminalInputEchoDelay()
noteTerminalInputAwaitingEcho(delay, 0)
noteTerminalInputAwaitingEcho(delay, 3000)
noteTerminalOutputAfterInput(delay, 3180)
expect(terminalInputEchoAllowanceMs(delay)).toBe(180)
})
})
@@ -1,61 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { DiscoveredSkill } from '../../../../../shared/skills'
import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, hasInstalledAgentSkill } from './useInstalledAgentSkills'
function makeSkill(
overrides: Partial<DiscoveredSkill> & Pick<DiscoveredSkill, 'name'>
): DiscoveredSkill {
return {
id: overrides.name,
description: '',
sourceKind: 'home',
sourceLabel: 'Claude',
installed: true,
updatedAt: null,
providers: ['claude'],
rootPath: '/Users/test/.claude/skills',
directoryPath: `/Users/test/.claude/skills/${overrides.name}`,
skillFilePath: `/Users/test/.claude/skills/${overrides.name}/SKILL.md`,
...overrides
}
}
describe('hasInstalledAgentSkill synced-folder exclusion', () => {
it('does not count Claude desktop synced skills as installs', () => {
const synced = [
makeSkill({
name: 'computer-use',
providers: ['claude'],
rootPath: '/Users/test/.claude/skills',
directoryPath: '/Users/test/.claude/skills/synced/org_bucket/computer-use'
}),
makeSkill({
name: 'computer-use',
providers: ['claude'],
rootPath: 'C:\\Users\\test\\.claude\\skills',
directoryPath: 'C:\\Users\\test\\.claude\\skills\\synced\\org_bucket\\computer-use'
})
]
expect(
hasInstalledAgentSkill(synced, 'computer-use', {
sourceKinds: GLOBAL_AGENT_SKILL_SOURCE_KINDS
})
).toBe(false)
})
it('still counts synced folder installs outside Claude home', () => {
const options = { sourceKinds: GLOBAL_AGENT_SKILL_SOURCE_KINDS }
for (const directoryPath of [
'/Users/test/.hermes/skills/synced/computer-use',
'/Users/test/.hermes/skills/synced/team/computer-use'
]) {
const installed = makeSkill({
name: 'computer-use',
providers: ['codex'],
rootPath: '/Users/test/.hermes/skills',
directoryPath
})
expect(hasInstalledAgentSkill([installed], 'computer-use', options)).toBe(true)
}
})
})
@@ -1,52 +0,0 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { EditorGutter } from 'monaco-editor/esm/vs/editor/browser/widget/diffEditor/utils/editorGutter.js'
// Guard the Monaco 0.55.1 patch: visible gutter views must dispose their global MenuRegistry toolbar entries.
class FakeResizeObserver {
observe(): void {}
disconnect(): void {}
}
const noEvent = (): { dispose(): void } => ({ dispose: () => undefined })
function createGutter(): { gutter: EditorGutter; viewDispose: () => void; domNode: HTMLElement } {
const editor = {
onDidScrollChange: noEvent,
onDidChangeModel: noEvent,
onDidChangeViewZones: noEvent,
onDidContentSizeChange: noEvent,
getScrollTop: () => 0,
hasModel: () => true,
getModel: () => ({ getLineCount: () => 10 }),
getVisibleRanges: () => [{ startLineNumber: 1, endLineNumber: 10 }],
getTopForLineNumber: (line: number) => (line - 1) * 20,
getBottomForLineNumber: (line: number) => line * 20
}
const domNode = document.createElement('div')
Object.defineProperty(domNode, 'clientHeight', { value: 200 })
const viewDispose = vi.fn()
const range = { startLineNumber: 2, endLineNumberExclusive: 4, intersect: () => range }
const gutter = new EditorGutter(editor, domNode, {
getIntersectingGutterItems: () => [{ id: 'hunk-1', range }],
createView: () => ({ layout: () => undefined, dispose: viewDispose })
})
return { gutter, viewDispose, domNode }
}
afterEach(() => {
vi.unstubAllGlobals()
})
describe('monaco-editor EditorGutter disposal patch', () => {
it('disposes gutter item views that are still on screen when the gutter is disposed', () => {
vi.stubGlobal('ResizeObserver', FakeResizeObserver)
const { gutter, viewDispose, domNode } = createGutter()
expect(domNode.childElementCount).toBeGreaterThan(1)
expect(viewDispose).not.toHaveBeenCalled()
gutter.dispose()
expect(viewDispose).toHaveBeenCalledTimes(1)
})
})
@@ -1,64 +0,0 @@
import { describe, expect, it } from 'vitest'
import { PluginSyntaxSlotPool } from './plugin-syntax-slot-pool'
function pool(limit?: number) {
const registered: string[] = []
const live = new Set<string>()
const released: string[] = []
const instance = new PluginSyntaxSlotPool({
limit,
register: (languageId) => registered.push(languageId),
create: (languageId, key) => {
const id = `${languageId}:${key}`
live.add(id)
return {
dispose: () => {
live.delete(id)
},
releaseModels: () => {
released.push(id)
}
}
}
})
return { instance, registered, live, released }
}
describe('PluginSyntaxSlotPool', () => {
it('evicts the least recently used idle language, and only falls back when all are open', () => {
const { instance, live } = pool(2)
const a = instance.acquire('a@1')
const b = instance.acquire('b@1')
a?.release()
b?.release()
// `a` is older, so it is evicted first.
const c = instance.acquire('c@1')
expect(c?.languageId).toBe(a?.languageId)
expect([...live].some((id) => id.endsWith(':a@1'))).toBe(false)
const d = instance.acquire('d@1')
expect(d?.languageId).toBe(b?.languageId)
expect(instance.acquire('e@1')).toBeNull()
c?.release()
expect(instance.acquire('e@1')?.languageId).toBe(c?.languageId)
})
it('ignores a second release of the same lease', () => {
const { instance } = pool(1)
const first = instance.acquire('a@1')
const second = instance.acquire('a@1')
first?.release()
first?.release()
expect(instance.acquire('b@1')).toBeNull()
second?.release()
})
it('moves models off a language once no editor uses it', () => {
const { instance, released } = pool()
const first = instance.acquire('a@1')
const second = instance.acquire('a@1')
first?.release()
expect(released).toEqual([])
second?.release()
expect(released).toEqual([`${second?.languageId}:a@1`])
})
})
@@ -1,62 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { applyPRBotAuthorOverride } from '../../../../../shared/source-control/review-comments/pr-bot-author-overrides'
const store = vi.hoisted(() => ({
settings: { prBotAuthorOverrides: [] as string[] },
pending: [] as (() => void)[],
apiUpdate: vi.fn(),
warning: vi.fn()
}))
vi.mock('sonner', () => ({ toast: { warning: store.warning } }))
vi.mock('@/store/index', () => ({
useAppStore: Object.assign(vi.fn(), {
getState: () => ({ settings: store.settings }),
setState: (next: { settings: typeof store.settings }) => {
store.settings = next.settings
}
})
}))
import { setPRBotAuthorOverride } from './pr-bot-author-overrides'
describe('PR bot author override updates', () => {
beforeEach(() => {
store.settings = { prBotAuthorOverrides: [] }
store.pending = []
store.apiUpdate.mockReset()
store.warning.mockReset()
store.apiUpdate.mockImplementation(
(args: { author: string; isBot: boolean }) =>
new Promise((resolve) => {
store.pending.push(() => {
store.settings = {
prBotAuthorOverrides: applyPRBotAuthorOverride(
store.settings.prBotAuthorOverrides,
args.author,
args.isBot
)
}
resolve(store.settings)
})
})
)
Object.defineProperty(globalThis, 'window', {
configurable: true,
value: { api: { settings: { updatePRBotAuthorOverride: store.apiUpdate } } }
})
})
it('continues processing updates after an atomic settings write fails', async () => {
store.apiUpdate
.mockRejectedValueOnce(new Error('settings unavailable'))
.mockResolvedValueOnce({ prBotAuthorOverrides: ['bob'] })
setPRBotAuthorOverride('alice', true)
setPRBotAuthorOverride('bob', true)
await vi.waitFor(() => expect(store.apiUpdate).toHaveBeenCalledTimes(2))
expect(store.settings.prBotAuthorOverrides).toEqual(['bob'])
})
})
@@ -1,74 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { Worktree } from '../../../../../../shared/worktree/types'
import {
matchWorktreePaletteTaskUrl,
parseCmdJTaskSourceUrl
} from './worktree-palette-task-url-match'
function makeWorktree(overrides: Partial<Worktree> = {}): Worktree {
return {
id: 'wt-1',
repoId: 'repo-1',
path: '/tmp/wt-1',
head: 'abc123',
branch: 'refs/heads/feature/url-match',
isBare: false,
isMainWorktree: false,
displayName: 'URL match',
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 0,
...overrides
}
}
describe('matchWorktreePaletteTaskUrl', () => {
// Jira issue keys repeat across tenants sharing a project key.
it('rejects a Jira issue URL from a different tenant with the same issue key', () => {
const intent = parseCmdJTaskSourceUrl('https://acme.atlassian.net/browse/PROJ-123')
expect(
matchWorktreePaletteTaskUrl({
worktree: makeWorktree({
linkedWorkItem: {
provider: 'jira',
type: 'issue',
number: 0,
title: 'Other tenant',
jiraIdentifier: 'PROJ-123',
url: 'https://other.atlassian.net/browse/PROJ-123'
}
}),
intent: intent!
})
).toBeNull()
})
// Same host, different site path: Jira Server installs are commonly path-scoped.
it('rejects a Jira issue URL from a different site path on the same host', () => {
const intent = parseCmdJTaskSourceUrl('https://jira.acme.test/one/browse/PROJ-123')
expect(
matchWorktreePaletteTaskUrl({
worktree: makeWorktree({
linkedWorkItem: {
provider: 'jira',
type: 'issue',
number: 0,
title: 'Other site',
jiraIdentifier: 'PROJ-123',
url: 'https://jira.acme.test/two/browse/PROJ-123'
}
}),
intent: intent!
})
).toBeNull()
})
})
@@ -1,25 +0,0 @@
import { expect, it } from 'vitest'
import {
AgentJournalSubmissionSchema,
isAdmissibleAgentJournalSubmission
} from './agent-session-journal-submission-schema'
it('admits newer fields without replacing or mutating the submission', () => {
const value = {
clientMessageId: 'client-1',
fence: 1,
payloadFingerprint: 'fingerprint',
dispatchState: 'future-dispatch-state',
providerItemId: null,
reason: null,
submittedAt: 1,
resolvedAt: null,
source: { kind: 'future-source', sender: 'retained-by-guard' },
future: { retained: true }
}
const original = structuredClone(value)
expect(isAdmissibleAgentJournalSubmission(value)).toBe(true)
expect(value).toEqual(original)
expect(AgentJournalSubmissionSchema.parse(value).source).toEqual({ kind: 'future-source' })
})
@@ -1,32 +0,0 @@
import { describe, expect, it } from 'vitest'
import { canResumeAiVaultSessionOnSshHost } from './ai-vault-ssh-resume-target'
describe('canResumeAiVaultSessionOnSshHost', () => {
it('keeps a transcript-referencing Antigravity resume on the transcript host', () => {
const wslReference =
'//wsl.localhost/Ubuntu/home/ada/.gemini/antigravity-ide/brain/id/transcript_full.jsonl'
const sshReference = '/home/ada/.gemini/antigravity-ide/brain/id/transcript_full.jsonl'
expect(
canResumeAiVaultSessionOnSshHost({
sessionFilePath: wslReference,
sessionExecutionHostId: 'local',
targetExecutionHostId: 'ssh:builder'
})
).toBe(false)
expect(
canResumeAiVaultSessionOnSshHost({
sessionFilePath: sshReference,
sessionExecutionHostId: 'ssh:builder',
targetExecutionHostId: 'ssh:builder'
})
).toBe(true)
// The CLI resumes by ID, so it keeps the WSL exception.
expect(
canResumeAiVaultSessionOnSshHost({
sessionFilePath: wslReference.replace('antigravity-ide', 'antigravity-cli'),
sessionExecutionHostId: 'local',
targetExecutionHostId: 'ssh:builder'
})
).toBe(true)
})
})
@@ -1,32 +0,0 @@
import { describe, expect, it } from 'vitest'
import { joinAbsolutePath } from './file-link-path-normalization'
describe('joinAbsolutePath', () => {
it.each([
['/repo', '../sibling/readme.md', '/sibling/readme.md'],
['/repo/worktree', '../../sibling/readme.md', '/sibling/readme.md'],
['/repo/worktree', 'src/../../readme.md', '/repo/readme.md'],
['/repo/./worktree/..', '../sibling/readme.md', '/sibling/readme.md'],
['/repo', '../../../readme.md', '/readme.md'],
['/repo', '..', '/'],
['/', '../../readme.md', '/readme.md'],
['/', '', '/'],
['/', '/readme.md', '/readme.md'],
[String.raw`c:\repo\worktree`, String.raw`..\sibling\readme.md`, 'C:/repo/sibling/readme.md'],
['C:/repo/worktree', '../../../readme.md', 'C:/readme.md'],
['C:/repo', '..', 'C:/'],
['C:/', '../readme.md', 'C:/readme.md'],
['C:/', '', 'C:/'],
[
String.raw`\\server\share\repo`,
String.raw`..\sibling\readme.md`,
'//server/share/sibling/readme.md'
],
['//server/share/repo', '../../../readme.md', '//server/share/readme.md'],
['//server/share/repo', '..', '//server/share'],
['//server/share', '../../readme.md', '//server/share/readme.md'],
['//server/share', '', '//server/share']
])('joins %j and %j without escaping its filesystem root', (base, relative, expected) => {
expect(joinAbsolutePath(base, relative)).toBe(expected)
})
})
@@ -1,34 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { resolveConfiguredGitPushTarget } from '../remotes/git-push-target-resolution'
function createRunner(config = new Map<string, string>()) {
return vi.fn(async (args: string[]) => {
if (args[0] === 'symbolic-ref') {
return { stdout: 'refs/heads/feature\n' }
}
if (args[0] === 'config' && args[1] === '--list') {
return { stdout: Array.from(config, ([key, value]) => `${key}\n${value}\0`).join('') }
}
throw new Error(`unexpected Git command: ${args.join(' ')}`)
})
}
describe('resolution config snapshots', () => {
it('reads a fresh push snapshot after branch config changes', async () => {
const config = new Map([
['branch.feature.remote', 'fork'],
['branch.feature.merge', 'refs/heads/feature']
])
const runGit = createRunner(config)
await expect(resolveConfiguredGitPushTarget(runGit)).resolves.toEqual({
remote: 'fork',
refspec: 'HEAD:feature'
})
config.set('remote.pushdefault', 'other-fork')
await expect(resolveConfiguredGitPushTarget(runGit)).resolves.toEqual({
remote: 'other-fork',
refspec: 'HEAD:feature'
})
})
})
@@ -1,34 +0,0 @@
import { describe, expect, it } from 'vitest'
import { mapSettledWithConcurrency } from './map-with-concurrency'
describe('mapSettledWithConcurrency', () => {
it('preserves all-settled results and order while bounding a large fanout', async () => {
const limit = 7
const items = Array.from({ length: 1_000 }, (_, index) => index)
let inFlight = 0
let peak = 0
const results = await mapSettledWithConcurrency(items, limit, async (item) => {
inFlight += 1
peak = Math.max(peak, inFlight)
await Promise.resolve()
for (let turn = 0; turn < item % 5; turn += 1) {
await Promise.resolve()
}
inFlight -= 1
if (item % 97 === 0) {
throw `rejected-${item}`
}
return `fulfilled-${item}`
})
expect(peak).toBe(limit)
expect(results).toEqual(
items.map((item): PromiseSettledResult<string> =>
item % 97 === 0
? { status: 'rejected', reason: `rejected-${item}` }
: { status: 'fulfilled', value: `fulfilled-${item}` }
)
)
})
})
@@ -1,34 +0,0 @@
// @vitest-environment happy-dom
import { describe, expect, it } from 'vitest'
import { readableMermaidFlowchartSvg } from './mermaid-flowchart-contrast'
function flowchart(fill: string, label: string): string {
return (
'<svg aria-roledescription="flowchart-v2"><g class="node">' +
`<rect class="label-container" style="fill:${fill}"></rect>` +
`<g class="label"><text style="fill:${label}">Node</text></g>` +
'</g></svg>'
)
}
function labelFill(svg: string): string {
const host = document.createElement('div')
host.innerHTML = svg
return host.querySelector('text')!.style.getPropertyValue('fill')
}
describe('readableMermaidFlowchartSvg', () => {
it('recolours a light theme label on a pale custom fill', () => {
const svg = readableMermaidFlowchartSvg(flowchart('#fde68a', '#e0e0e0'), '#e0e0e0', '#111111')
expect(labelFill(svg)).toBe('#111111')
})
it('reads the painted path when the label container is a group', () => {
const stadium = flowchart('#1e3a8a', '#e0e0e0').replace(
'<rect class="label-container" style="fill:#1e3a8a"></rect>',
// The group inherits the diagram's text colour; only its path is painted.
'<g class="label-container" style="fill:#e0e0e0"><path style="fill:#1e3a8a"></path></g>'
)
expect(labelFill(readableMermaidFlowchartSvg(stadium, '#e0e0e0', '#111111'))).toBe('#e0e0e0')
})
})
@@ -1,32 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { NativeChatMessage } from '../../native-chat-types'
import { createNativeChatTranscriptRetention } from './native-chat-transcript-retention'
function message(id: string): NativeChatMessage {
return { id, role: 'assistant', blocks: [], timestamp: 0, source: 'transcript' }
}
describe('native chat transcript retention', () => {
it('holds only the latest settled transcript for the same identity while unsettled', () => {
const retention = createNativeChatTranscriptRetention()
const first = [message('first')]
const second = [message('second')]
retention.capture('source-a', first)
expect(retention.visible({ identity: 'source-a', messages: [], settled: false })).toBe(first)
expect(retention.visible({ identity: 'source-b', messages: [], settled: false })).toEqual([])
retention.capture('source-b', second)
expect(retention.visible({ identity: 'source-a', messages: [], settled: false })).toEqual([])
expect(retention.visible({ identity: 'source-b', messages: [], settled: false })).toBe(second)
})
it('never substitutes retained history for a settled read', () => {
const retention = createNativeChatTranscriptRetention()
const retained = [message('retained')]
const fresh = [message('fresh')]
retention.capture('source', retained)
expect(retention.visible({ identity: 'source', messages: fresh, settled: true })).toBe(fresh)
})
})
@@ -1,32 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
getSmartWorkspaceLinearSearchQuery,
parseBoundedSmartWorkspaceLinearIssueInput,
parseBoundedSmartWorkspaceLinearIssueUrlIntent
} from './smart-workspace-linear-intent'
describe('numeric-leading Linear workspace source input', () => {
it.each(['2eng-123', '1pass-42', '3d-15'])('recognizes %s as an issue identifier', (input) => {
const identifier = input.toUpperCase()
const url = `https://linear.app/acme/issue/${input}/notes`
const intent = { identifier, organizationUrlKey: 'acme' }
expect(parseBoundedSmartWorkspaceLinearIssueInput(` ${input} `)).toEqual({ identifier })
expect(getSmartWorkspaceLinearSearchQuery(input)).toBe(identifier)
expect(parseBoundedSmartWorkspaceLinearIssueInput(url)).toEqual(intent)
expect(parseBoundedSmartWorkspaceLinearIssueUrlIntent(url)).toEqual(intent)
expect(getSmartWorkspaceLinearSearchQuery(url)).toBe(identifier)
})
it.each(['2026-09', '555-1234', '8080-8090', '1_2-3'])(
'keeps %s as search text without issue intent',
(input) => {
const url = `https://linear.app/acme/issue/${input}/notes`
expect(parseBoundedSmartWorkspaceLinearIssueInput(input)).toBeNull()
expect(getSmartWorkspaceLinearSearchQuery(input)).toBe(input)
expect(parseBoundedSmartWorkspaceLinearIssueInput(url)).toBeNull()
expect(parseBoundedSmartWorkspaceLinearIssueUrlIntent(url)).toBeNull()
}
)
})
-33
View File
@@ -1,33 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { runProcessSyncMock } = vi.hoisted(() => ({ runProcessSyncMock: vi.fn() }))
vi.mock('@orca/process-host', () => ({ runProcessSync: runProcessSyncMock }))
function regResult(stdout: string, code = 0) {
return { code, signal: null, stdout, stderr: '', timedOut: false }
}
async function loadReader() {
return (await import('./openssh-default-shell.js')).readOpenSshDefaultShell
}
describe('readOpenSshDefaultShell', () => {
beforeEach(() => {
vi.resetModules()
runProcessSyncMock.mockReset()
})
it('treats malformed output as empty', async () => {
runProcessSyncMock.mockReturnValue(
regResult(
[
'HKEY_LOCAL_MACHINE\\SOFTWARE\\OpenSSH',
' DefaultShellCommandOption REG_SZ /c'
].join('\r\n')
)
)
expect((await loadReader())()).toBe('')
})
})
-34
View File
@@ -1,34 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { PhysicalExitTracker } from './physical-exit-tracker'
describe('PhysicalExitTracker', () => {
afterEach(() => vi.useRealTimers())
it('lets a later retry observe exit after an earlier wait times out', async () => {
vi.useFakeTimers()
const tracker = new PhysicalExitTracker()
const first = tracker.waitForExit(10, () => new Error('first deadline'))
const firstRejection = expect(first).rejects.toThrow('first deadline')
await vi.advanceTimersByTimeAsync(10)
await firstRejection
const retry = tracker.waitForExit(10, () => new Error('retry deadline'))
tracker.markExited()
await expect(retry).resolves.toBeUndefined()
await expect(tracker.exitedPromise).resolves.toBeUndefined()
})
it('settles every active waiter once and resolves later waits immediately', async () => {
const tracker = new PhysicalExitTracker()
const first = tracker.waitForExit(100, () => new Error('deadline'))
const second = tracker.waitForExit(100, () => new Error('deadline'))
tracker.markExited()
tracker.markExited()
await expect(Promise.all([first, second])).resolves.toEqual([undefined, undefined])
await expect(tracker.waitForExit(1, () => new Error('deadline'))).resolves.toBeUndefined()
})
})
@@ -1,34 +0,0 @@
import { describe, expect, it } from 'vitest'
import { getDefaultSettings } from './constants'
import { migratePortugueseUiLanguageOnLoad } from './portuguese-ui-language-migration'
import { normalizeUiLanguage } from './ui-language'
const plugin = 'plugin:stablyai.orca-portuguese/pt-BR'
describe('Portuguese UI language load migration', () => {
it.each([undefined, false, null, 'true', 1, {}])(
'converts only the exact legacy preference with marker %j',
(marker) => {
const stored = JSON.parse(
JSON.stringify({ uiLanguage: plugin, uiLanguagePortugueseMigrationApplied: marker })
)
const migrated = migratePortugueseUiLanguageOnLoad(stored)
expect(migrated).toEqual({ uiLanguage: 'pt', uiLanguagePortugueseMigrationApplied: true })
expect(migratePortugueseUiLanguageOnLoad(migrated)).toEqual(migrated)
}
)
it('preserves explicit plugin selection in stamped and fresh stores', () => {
expect(normalizeUiLanguage(plugin)).toBe(plugin)
expect(
migratePortugueseUiLanguageOnLoad({
...getDefaultSettings('~'),
uiLanguage: plugin
})
).toEqual({ uiLanguage: plugin, uiLanguagePortugueseMigrationApplied: true })
expect(migratePortugueseUiLanguageOnLoad(undefined)).toEqual({
uiLanguage: 'system',
uiLanguagePortugueseMigrationApplied: true
})
})
})
@@ -1,31 +0,0 @@
import { describe, expect, it } from 'vitest'
import { createProgramStatusProjector } from './agent-status-projector'
const osc = (body: string): string => `\x1b]7501;${body}\x1b\\`
function lastRootStates(data: string[]) {
const projector = createProgramStatusProjector(() => 1000)
return data.map((chunk) => {
const payloads = projector.process(chunk).payloads
const last = payloads.at(-1)?.payload
return last && { state: last.state, sessionBoundary: last.sessionBoundary }
})
}
describe('createProgramStatusProjector', () => {
it('ends an OpenCode turn on idle but not its startup', () => {
// Captured from OpenCode 2.2.5, which never reports done.
const session = 'ses_e57cc6093ffeU9dbfhOFmwKNgt'
expect(
lastRootStates([
osc('state=idle:app=opencode'),
osc('state=working:app=opencode') + osc(`state=working:id=${session}:app=opencode`),
osc(`state=clear:id=${session}`) + osc('state=idle:app=opencode')
])
).toEqual([
{ state: 'done', sessionBoundary: true },
{ state: 'working', sessionBoundary: undefined },
{ state: 'done', sessionBoundary: undefined }
])
})
})
@@ -1,31 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { configureHardeningRetryBudget } from './secure-path-hardening-retry-budget'
const PATH = 'C:\\Users\\me\\.orca\\secret.json'
const OTHER = 'C:\\Users\\me\\.orca\\other.json'
describe('secure path hardening retry budget', () => {
beforeEach(() => {
configureHardeningRetryBudget({
maxEntries: 64,
maxKeyBytes: 4096,
maxTotalKeyBytes: 65_536
})
})
afterEach(() => {
vi.restoreAllMocks()
})
/** A second importer may have no configuration; throwing there made async hardening crash main.
* Import only the budget so secure-file cannot hide the missing defaults. */
it('defaults its bounds when nothing configured it', async () => {
vi.resetModules()
const budget = await import('./secure-path-hardening-retry-budget.js')
expect(budget.mayAttemptHardening(PATH)).toBe(true)
expect(() => budget.recordHardeningOutcome(PATH, false)).not.toThrow()
expect(budget.mayAttemptHardening(PATH)).toBe(false)
expect(budget.mayAttemptHardening(OTHER)).toBe(true)
})
})
-34
View File
@@ -1,34 +0,0 @@
import { describe, expect, it } from 'vitest'
import { summarizeSkillMarkdown } from './skill-metadata'
describe('summarizeSkillMarkdown', () => {
it('reads name and folded description from YAML frontmatter', () => {
const summary = summarizeSkillMarkdown(`---
name: orca-cli
description: >-
Use the orca CLI to drive a running editor;
keep worktree comments current.
---
# Orca CLI
`)
expect(summary).toEqual({
name: 'orca-cli',
description: 'Use the orca CLI to drive a running editor; keep worktree comments current.'
})
})
})
it.each(['', '\uFEFF'])('preserves the last CRLF frontmatter field with BOM %j', (bom) => {
for (const fields of [
['name: actual-name', 'description: actual description'],
['description: actual description', 'name: actual-name']
]) {
const markdown = `${bom}${['---', ...fields, '---', '# Fallback heading', '', 'Fallback paragraph'].join('\r\n')}`
expect(summarizeSkillMarkdown(markdown)).toEqual({
name: 'actual-name',
description: 'actual description'
})
}
})
@@ -1,33 +0,0 @@
import { describe, expect, it } from 'vitest'
import { isPushHookFailure, summarizePushFailure } from './source-control-push-failure'
describe('push failure detection and summary', () => {
it('detects explicit pre-push hook failures', () => {
const raw =
"error: failed to push some refs to 'origin'\nhusky - pre-push hook exited with code 1"
expect(isPushHookFailure(raw)).toBe(true)
expect(summarizePushFailure(raw)).toBe('Pre-push hook failed.')
})
it('does not treat auth failures as push hook failures', () => {
const raw =
'git push failed: Command failed: git push origin main\nremote: Repository not found.\nfatal: Authentication failed'
expect(isPushHookFailure(raw)).toBe(false)
})
it('does not treat protected, pre-receive, non-fast-forward, transport, or submodule failures as push hooks', () => {
const negatives = [
'git push failed: Command failed: git push origin main\nremote: error: GH006: Protected branch update failed for refs/heads/main.\nremote: lint status check is required',
'git push failed: Command failed: git push origin main\nremote: pre-receive hook declined\nremote: eslint failed in hosted checks',
'git push failed: Command failed: git push origin main\n! [rejected] main -> main (non-fast-forward)\nerror: failed to push some refs',
'git push failed: Command failed: git push origin main\nfatal: unable to access https://example.com/repo.git: Could not resolve host',
"git push failed: Command failed: git push --recurse-submodules\nUnable to push submodule 'vendor/lib'\nfatal: failed to push all needed submodules"
]
for (const raw of negatives) {
expect(isPushHookFailure(raw)).toBe(false)
}
})
})
@@ -3,5 +3,4 @@ import './agent-session/requests/structured-agent-session-send-mutation.spec'
import './agent-session/structured-agent-session-unknown-item.spec'
import './structured-session-foreground-commands.spec'
import './agent-session/requests/structured-agent-session-first-prompt.spec'
import './agent-session/journal/agent-session-journal-submission-schema.spec'
import './agent-session/requests/structured-agent-session-projection-sender.spec'
@@ -1,32 +0,0 @@
import { describe, expect, it } from 'vitest'
import { extractTerminalFileLinks } from './terminal-links'
describe('extractTerminalFileLinks', () => {
it('preserves bare percent filenames and route punctuation beside Markdown', () => {
expect(
extractTerminalFileLinks(
'/tmp/literal%20/file.pdf [PDF](/tmp/report.pdf) app/(shop)/[id]/page.tsx'
).map((link) => link.pathText)
).toEqual(['/tmp/literal%20/file.pdf', '/tmp/report.pdf', 'app/(shop)/[id]/page.tsx'])
})
it('does not turn an external link label into a local file target', () => {
expect(
extractTerminalFileLinks('[/tmp/misleading.pdf](https://example.com/report.pdf)')
).toEqual([])
})
it('preserves adjacent route bracket and parenthesis segments in bare paths', () => {
expect(
extractTerminalFileLinks('/tmp/[id](group)/page.tsx').map((link) => link.pathText)
).toEqual(['/tmp/[id](group)/page.tsx'])
})
it('finds adjacent Markdown destinations independently', () => {
expect(
extractTerminalFileLinks('[one](/tmp/one.pdf)[two](/tmp/two.pdf)').map(
(link) => link.pathText
)
).toEqual(['/tmp/one.pdf', '/tmp/two.pdf'])
})
})
@@ -1,33 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { readTmuxPaneBridge } from './tmux-host-attachment-probe'
const run = vi.hoisted(() => vi.fn())
vi.mock('@orca/process-host', () => ({ runProcess: run }))
vi.mock('node:fs/promises', () => ({
stat: async () => ({ isSocket: () => true, uid: process.getuid?.() })
}))
vi.mock('./agent-status/process/agent-process-presence-probe', () => ({
readAgentProcess: async (pid: number) => ({ verdict: 'live', startTime: `birth-${pid}` })
}))
describe('a tmux pane this terminal does not show', () => {
const start = process.platform === 'darwin' ? 'Fri Oct 2 03:00:00 2026' : '100'
// This pane's shell (pts/1), and a client attached in another app's terminal (pts/2).
const table: Record<number, string> = {
100: `100 1 100 100 S pts/1 ${start} /bin/bash`,
300: `300 1 300 301 S pts/2 ${start} -zsh`,
301: `301 300 301 301 S+ pts/2 ${start} /usr/bin/tmux attach`
}
it.each([
['refuses it once the other client’s lineage is read', [100, 300, 301], 'elsewhere'],
['leaves it unverified when that lineage is unread', [100, 301], null]
])('%s', async (_name, readable, expected) => {
run.mockImplementation(async (options: { program: string; args: string[] }) => {
const pid = Number(options.args[1])
const stdout =
options.program === 'tmux' ? '301:%1' : readable.includes(pid) ? `${table[pid]}\n` : ''
return { code: 0, timedOut: false, stdout }
})
expect(await readTmuxPaneBridge('/tmp/fixture.sock', 100, '%1')).toBe(expected)
})
})
@@ -1,80 +0,0 @@
// Pin viewport-only reveal reads; normal-buffer scrollback in serialize() can masquerade as a live alt frame (STA-5208).
import '../../../src/main/daemon/emulation/xterm-env-polyfill'
import { describe, expect, it } from 'vitest'
import { Terminal } from '@xterm/headless'
import { SerializeAddon } from '@xterm/addon-serialize'
import type { Page } from '@stablyai/playwright-test'
import { readActiveScreen, readRenderedAltScreenFrame } from './alt-screen-frame'
const MARKER = 'DUPLICATE_PTY_REVEAL_TEST'
const TAB_ID = 'tab-under-test'
type Harness = { page: Page; terminal: Terminal; serialize: () => string }
// Matches the streaming TUI fixture in terminal-duplicate-pty-renderer-reveal.spec.ts.
function frameLine(frame: number): string {
return `${MARKER} frame ${String(frame).padStart(6, '0')}`
}
function write(terminal: Terminal, data: string): Promise<void> {
return new Promise((resolve) => terminal.write(data, () => resolve()))
}
// Run the real serialized browser closure against a headless terminal, not a copied implementation.
function createHarness(rows: number): Harness {
const terminal = new Terminal({ cols: 80, rows, scrollback: 100, allowProposedApi: true })
const serializeAddon = new SerializeAddon()
terminal.loadAddon(serializeAddon)
const pane = { terminal, serializeAddon }
;(globalThis as Record<string, unknown>).__paneManagers = new Map([
[TAB_ID, { getPanes: () => [pane] }]
])
const page = {
evaluate: <Arg, Result>(fn: (arg: Arg) => Result, arg: Arg): Promise<Result> =>
Promise.resolve(fn(arg))
} as unknown as Page
return { page, terminal, serialize: () => serializeAddon.serialize() }
}
// The oracle this replaces: a positional scan over every buffer serialize() emits.
function parseSerializedFrame(content: string, pick: 'first' | 'last'): number | null {
const prefix = `${MARKER} frame `
const start = pick === 'first' ? content.indexOf(prefix) : content.lastIndexOf(prefix)
if (start < 0) {
return null
}
const digits = content.slice(start + prefix.length).match(/^\d+/)?.[0]
return digits ? Number(digits) : null
}
describe('readRenderedAltScreenFrame', () => {
it('reads the live alt frame, not the stale copy left in the normal buffer', async () => {
const harness = createHarness(8)
await write(harness.terminal, `${frameLine(390)}\r\n`)
await write(harness.terminal, `\x1b[?1049h\x1b[H${frameLine(400)}\x1b[J`)
const serialized = harness.serialize()
expect(parseSerializedFrame(serialized, 'first')).toBe(390)
expect(parseSerializedFrame(serialized, 'last')).toBe(400)
await expect(readActiveScreen(harness.page, TAB_ID)).resolves.toMatchObject({
bufferType: 'alternate'
})
await expect(readRenderedAltScreenFrame(harness.page, TAB_ID, MARKER)).resolves.toBe(400)
})
it('reports no frame when the freshest marker scrolled off the visible rows', async () => {
const harness = createHarness(8)
await write(harness.terminal, `${frameLine(400)}\r\n`)
for (let row = 0; row < 12; row += 1) {
await write(harness.terminal, `filler row ${row}\r\n`)
}
// serialize() still sees off-screen history; only the viewport proves the marker is absent.
expect(parseSerializedFrame(harness.serialize(), 'last')).toBe(400)
await expect(readActiveScreen(harness.page, TAB_ID)).resolves.toMatchObject({
bufferType: 'normal'
})
await expect(readRenderedAltScreenFrame(harness.page, TAB_ID, MARKER)).resolves.toBeNull()
})
})
@@ -1,61 +0,0 @@
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { getElectronIsolatedKeychainArgs, getOrcaElectronLaunchArgs } from './electron-launch-args'
describe('getOrcaElectronLaunchArgs', () => {
afterEach(() => vi.unstubAllGlobals())
it.each(['darwin', 'linux', 'win32'])(
'isolates packaged and source test keychains on %s',
(platform) => {
vi.stubGlobal('process', { ...process, platform })
const args = getElectronIsolatedKeychainArgs()
expect(args).toEqual(
platform === 'darwin' ? ['--password-store=basic', '--use-mock-keychain'] : []
)
expect(getOrcaElectronLaunchArgs(join('orca', 'out', 'main', 'index.js'), false)).toEqual(
expect.arrayContaining(args)
)
}
)
it.each([
['linux', 'true', true, true],
['linux', undefined, true, false],
['linux', 'true', false, false],
['darwin', 'true', true, false],
['win32', 'true', true, false]
] as const)(
'scopes software WebGL to Linux CI headful launches: %s/%s/%s',
(platform, ci, headful, enabled) => {
vi.stubGlobal('process', { ...process, platform, env: { ...process.env, CI: ci } })
const args = getOrcaElectronLaunchArgs(join('orca', 'out', 'main', 'index.js'), headful)
expect(args.includes('--use-gl=angle')).toBe(enabled)
expect(args.includes('--use-angle=swiftshader')).toBe(enabled)
expect(args.includes('--enable-unsafe-swiftshader')).toBe(enabled)
if (enabled) {
expect(args).toContain('--disable-gpu-sandbox')
expect(args).not.toContain('--disable-gpu')
}
}
)
it('launches the package root that owns the compiled main entry', () => {
const root = join('workspace', 'orca')
const mainPath = join(root, 'out', 'main', 'index.js')
const args = getOrcaElectronLaunchArgs(mainPath, true)
if (process.platform === 'darwin') {
expect(args).toEqual([
'--password-store=basic',
'--use-mock-keychain',
root,
'-ApplePersistenceIgnoreState',
'YES'
])
} else {
expect(args.at(-1)).toBe(root)
}
expect(getOrcaElectronLaunchArgs(mainPath, false)).toContain(root)
})
})
@@ -1,71 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { retryTransientMainEvaluate } from './electron-main-evaluate-retry'
const transientMessages = [
'Execution context was destroyed, most likely because of a navigation.',
'electronApplication.evaluate: Resulting promise was garbage collected.'
]
afterEach(() => vi.useRealTimers())
describe('retryTransientMainEvaluate', () => {
it.each(transientMessages)('retries a transient startup failure: %s', async (message) => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
let calls = 0
const outcome = expect(
retryTransientMainEvaluate(async () => {
calls += 1
if (calls < 3) {
throw new Error(message)
}
return '/isolated/home'
})
).resolves.toBe('/isolated/home')
void outcome.catch(() => undefined)
await vi.advanceTimersByTimeAsync(400)
await outcome
expect(calls).toBe(3)
})
it('rethrows a real failure immediately instead of masking it behind retries', async () => {
let calls = 0
await expect(
retryTransientMainEvaluate(async () => {
calls += 1
throw new Error('Electron E2E HOME escaped the disposable profile boundary')
})
).rejects.toThrow(/escaped the disposable profile/)
expect(calls).toBe(1)
})
it.each(transientMessages)(
'bounds retries when evaluation keeps failing: %s',
async (message) => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
let calls = 0
const outcome = expect(
retryTransientMainEvaluate(async () => {
calls += 1
throw new Error(message)
})
).rejects.toThrow(message)
void outcome.catch(() => undefined)
await vi.advanceTimersByTimeAsync(800)
await outcome
expect(calls).toBe(5)
}
)
it('does not retry a closed application', async () => {
let calls = 0
await expect(
retryTransientMainEvaluate(async () => {
calls += 1
throw new Error(
'electronApplication.evaluate: Target page, context or browser has been closed'
)
})
).rejects.toThrow(/has been closed/)
expect(calls).toBe(1)
})
})
@@ -1,74 +0,0 @@
import { afterEach, expect, it, vi } from 'vitest'
import { rePairPairedElectronClient } from './paired-client-runtime-environment'
import type { PairedElectronClient } from './paired-electron-client'
afterEach(() => {
vi.unstubAllGlobals()
vi.unstubAllEnvs()
})
function fixture(canSelectLocal: boolean) {
let selected: string | null = 'old-hub'
const remove = vi.fn(async () => {
if (selected !== null) {
throw new Error('Cannot remove the selected runtime')
}
})
const state = {
setActiveRuntimeEnvironmentPreference: vi.fn(async (id: string | null) => {
if (id === null && !canSelectLocal) {
return false
}
selected = id
return true
}),
setRuntimeEnvironments: vi.fn(),
refreshRuntimeEnvironmentStatus: vi.fn(async () => true)
}
vi.stubGlobal('window', {
__store: { getState: () => state },
api: {
runtimeEnvironments: {
remove,
addFromPairingCode: vi.fn(async () => ({ environment: { id: 'new-hub' } })),
list: vi.fn(async () => [{ id: 'new-hub' }])
}
}
})
const nativeEvaluate = vi.fn()
const reload = vi.fn(async () => undefined)
const client = {
environmentId: 'old-hub',
captureDirectSshAttempts: vi.fn(async () => undefined),
installDirectSshAttemptProbe: vi.fn(async () => undefined),
app: { evaluate: nativeEvaluate },
page: {
evaluate: async (callback: (args: unknown) => unknown, args: unknown) => callback(args),
reload,
waitForFunction: vi.fn(async () => undefined)
}
} as unknown as PairedElectronClient
return { client, remove, reload, nativeEvaluate }
}
it('keeps the old pairing when selecting local fails', async () => {
const { client, remove, reload } = fixture(false)
await expect(rePairPairedElectronClient(client, { pairingUrl: 'code' }, 'HUB')).rejects.toThrow(
'could not select local'
)
expect(remove).not.toHaveBeenCalled()
expect(reload).not.toHaveBeenCalled()
expect(client.environmentId).toBe('old-hub')
})
it('replaces the active pairing without touching native windows in background mode', async () => {
vi.stubEnv('ORCA_BACKGROUND_LAUNCH', '1')
vi.stubEnv('GITHUB_ACTIONS', 'true')
vi.stubEnv('DISPLAY', ':99')
const { client, remove, reload, nativeEvaluate } = fixture(true)
await rePairPairedElectronClient(client, { pairingUrl: 'code' }, 'HUB')
expect(remove).toHaveBeenCalledWith({ selector: 'old-hub' })
expect(client.environmentId).toBe('new-hub')
expect(reload).toHaveBeenCalledOnce()
expect(nativeEvaluate).not.toHaveBeenCalled()
})
+3 -5
View File
@@ -13,9 +13,8 @@ session so it runs outside the React Native bundle.
`phone-e2ee-desktop-parity.test.mjs` pins that port to the desktop responder
in `src/main/runtime/rpc/mobile/e2ee/mobile-e2ee-v2-desktop-session.ts`. It runs in the normal unit suite, so
a change to the transcript encoding, key schedule, or frame layout fails there instead of leaving
a bench that quietly measures a handshake nobody ships. The four other `*.test.mjs` files in this
directory cover the invocation guards, the state file, the region verdicts, and pairing-link
decoding, and none of them opens a socket.
a bench that quietly measures a handshake nobody ships. The other `*.test.mjs` files in this directory cover the state file, region verdicts, and
pairing-link decoding. The region tests use an owned loopback listener.
## Security rules
@@ -33,8 +32,7 @@ No script here has a production default. Every one of them refuses to open a soc
`--director=<origin>` or `ORCA_RELAY_BENCH_DIRECTOR`. Without those, they print usage and exit 2.
That keeps an accidental or automated invocation inert instead of live traffic.
The guards are in `relay-bench-invocation.mjs` and `relay-bench-state-file.mjs`, and
`relay-bench-invocation.test.mjs` / `relay-bench-state-file.test.mjs` pin them:
The guards are in `relay-bench-invocation.mjs` and `relay-bench-state-file.mjs`:
| Guard | What it stops |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
@@ -1,118 +0,0 @@
// Pin numeric and destination guards against operator typos/hostile director URLs that would create unintended live traffic.
import { describe, expect, it, vi } from 'vitest'
import {
classifyPublicHttpsOrigin,
isPublicIpAddress,
parseBoundedInteger,
parsePort,
requireOrigin,
resolvesToPublicAddress
} from './relay-bench-invocation.mjs'
/** refuse() exits the process; make that observable instead of killing the test worker. */
describe('parseBoundedInteger', () => {
// 'Infinity' is the one that mattered: Number('Infinity') made the run loops never terminate.
it.each(['Infinity', '-Infinity', 'NaN', '', ' ', 'abc', '1e3', '-1', '1.5', '0x10', '+2'])(
'rejects %j',
(value) => {
expect(parseBoundedInteger(value, { min: 0, max: 10 })).toBeNull()
}
)
it('rejects values outside the bounds', () => {
expect(parseBoundedInteger('11', { min: 0, max: 10 })).toBeNull()
expect(parseBoundedInteger('0', { min: 1, max: 10 })).toBeNull()
})
})
describe('parsePort', () => {
// WHATWG URL reads '80@attacker.example' as userinfo, so the fetch would leave loopback.
it.each(['80@attacker.example', '0', '65536', '9222 9223', 'Infinity', ''])(
'rejects %j',
(value) => {
expect(parsePort(value)).toBeNull()
}
)
})
describe('isPublicIpAddress', () => {
it.each([
'127.0.0.1',
'127.1.2.3',
'0.0.0.0',
'10.0.0.1',
'172.16.0.1',
'172.31.255.255',
'192.168.1.1',
'169.254.169.254',
'100.64.0.1',
'224.0.0.1',
'255.255.255.255',
'::1',
'::',
'::ffff:127.0.0.1',
'fe80::1',
'fc00::1',
'fd12:3456::1',
'ff02::1'
])('refuses %s', (host) => {
expect(isPublicIpAddress(host)).toBe(false)
})
it.each(['8.8.8.8', '172.32.0.1', '172.15.0.1', '1.1.1.1', '2001:db8::1', '::ffff:8.8.8.8'])(
'allows %s',
(host) => {
expect(isPublicIpAddress(host)).toBe(true)
}
)
})
describe('classifyPublicHttpsOrigin', () => {
it.each([
['http://relay.example', 'must be an https origin'],
['wss://relay.example', 'must be an https origin'],
['https://user:pass@relay.example', 'must not carry credentials'],
['https://localhost:9222', 'loopback'],
['https://app.localhost', 'loopback'],
['https://127.0.0.1:8080', 'loopback, link-local, or private'],
['https://[::1]/', 'loopback, link-local, or private'],
['https://[::ffff:127.0.0.1]/', 'loopback, link-local, or private'],
['https://169.254.169.254/latest/meta-data', 'loopback, link-local, or private'],
['https://10.1.2.3', 'loopback, link-local, or private'],
['not a url', 'not a URL'],
['', 'missing origin']
])('refuses %s', (value, reason) => {
const verdict = classifyPublicHttpsOrigin(value)
expect(verdict.ok).toBe(false)
expect(verdict.reason).toContain(reason)
})
})
describe('resolvesToPublicAddress', () => {
it('refuses when any resolved address is private', async () => {
const lookup = vi.fn().mockResolvedValue([
{ address: '8.8.8.8', family: 4 },
{ address: '10.0.0.5', family: 4 }
])
expect((await resolvesToPublicAddress('https://relay.example', { lookup })).ok).toBe(false)
})
it('accepts a name that resolves publicly', async () => {
const lookup = vi.fn().mockResolvedValue([{ address: '8.8.8.8', family: 4 }])
expect(await resolvesToPublicAddress('https://relay.example', { lookup })).toEqual({ ok: true })
})
it('refuses when resolution fails', async () => {
const lookup = vi.fn().mockRejectedValue(new Error('ENOTFOUND'))
expect((await resolvesToPublicAddress('https://relay.example', { lookup })).ok).toBe(false)
})
})
describe('requireOrigin and requireDirector', () => {
it('returns the origin for an https target', () => {
expect(requireOrigin('https://relay.example/x', 'cell origin', 'usage')).toBe(
'https://relay.example'
)
})
})
@@ -1,98 +0,0 @@
import { describe, expect, it } from 'vitest'
import { evaluatePackagedNodePtyCapability } from './packaged-node-pty-capability-oracle.mjs'
const fixtureToken = 'a'.repeat(64)
const channel = `\\\\.\\pipe\\orca-pty-native-capability-${fixtureToken}`
function observation(pid, role) {
return { pid, fixtureToken, role, channel }
}
function closure(role) {
return { fixtureToken, role, channel }
}
function passingEvidence() {
const shell = observation(4100, 'target-shell')
const launcherExited = observation(4101, 'target-launcher-exited')
const grandchild = observation(4102, 'target-grandchild')
const canary = observation(5100, 'canary-shell')
return {
patchedExports: ['assignCurrentProcessToJob', 'listJobProcessIds', 'terminateJob'],
fixtureToken,
channel,
target: {
terminalHandle: 'pty-job:7:4100',
shell,
launcherExited,
grandchild,
jobProcessIds: [shell.pid, grandchild.pid]
},
canary: {
terminalHandle: 'pty-job:8:5100',
process: canary,
connectedAfterTargetClose: true,
jobProcessIdsAfterTargetClose: [canary.pid],
exit: { terminalHandle: 'pty-job:8:5100', exitCode: 1, signal: 0 },
socketClosed: closure('canary-shell')
},
close: {
method: 'terminate-job',
requestedHandle: 'pty-job:7:4100',
completedHandle: 'pty-job:7:4100',
targetExit: { terminalHandle: 'pty-job:7:4100', exitCode: 1, signal: 0 },
targetShellClosed: closure('target-shell'),
targetGrandchildClosed: closure('target-grandchild')
}
}
}
describe('packaged node-pty native capability oracle', () => {
it('accepts exact target teardown while the unrelated canary remains live', () => {
expect(evaluatePackagedNodePtyCapability(passingEvidence())).toEqual({
pass: true,
failures: []
})
})
it.each([
['missing patched export', (evidence) => evidence.patchedExports.pop()],
['launcher exit absent', (evidence) => delete evidence.target.launcherExited],
['empty job membership', (evidence) => (evidence.target.jobProcessIds = [])],
[
'target shell outside membership',
(evidence) => (evidence.target.jobProcessIds = [evidence.target.grandchild.pid])
],
[
'launcher-surviving grandchild outside membership',
(evidence) => (evidence.target.jobProcessIds = [evidence.target.shell.pid])
],
['target exit absent', (evidence) => delete evidence.close.targetExit],
['canary connection loss', (evidence) => (evidence.canary.connectedAfterTargetClose = false)]
])('rejects %s', (_name, mutate) => {
const evidence = passingEvidence()
mutate(evidence)
expect(evaluatePackagedNodePtyCapability(evidence).pass).toBe(false)
})
it.each([
['guessable token', (evidence) => (evidence.fixtureToken = 'run-1')],
[
'grandchild from another channel',
(evidence) => (evidence.target.grandchild.channel = '\\\\.\\pipe\\other')
],
['wrong completed handle', (evidence) => (evidence.close.completedHandle = 'pty-job:9:9999')],
[
'launcher still in target job',
(evidence) => evidence.target.jobProcessIds.push(evidence.target.launcherExited.pid)
],
['canary outside its job', (evidence) => (evidence.canary.jobProcessIdsAfterTargetClose = [])],
['canary teardown absent', (evidence) => delete evidence.canary.socketClosed]
])('rejects scope violation: %s', (_name, mutate) => {
const evidence = passingEvidence()
mutate(evidence)
expect(evaluatePackagedNodePtyCapability(evidence).pass).toBe(false)
})
})
@@ -1,18 +0,0 @@
import { describe, expect, it } from 'vitest'
import { formatProbeFailure } from './run.mjs'
describe('packaged Windows native smoke runner boundary', () => {
it('keeps timeout evidence bounded and preserves both output channels', () => {
const failure = formatProbeFailure({
code: null,
timedOut: true,
stdout: `old-${'x'.repeat(9_000)}-stdout-tail`,
stderr: 'stage=target-spawn:start'
})
expect(failure).toContain('code=null, timedOut=true')
expect(failure).not.toContain('old-')
expect(failure).toContain('stdout-tail')
expect(failure).toContain('stage=target-spawn:start')
})
})