mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
test: remove 47 low-value test suites (#42648)
Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
@@ -474,7 +474,6 @@
|
||||
1 test-no-wall-clock:src/renderer/src/components/activity/activity-auto-mark-read-loop.react185.test.tsx
|
||||
2 test-no-wall-clock:src/renderer/src/components/artifacts/ArtifactCollection.test.tsx
|
||||
1 test-no-wall-clock:src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx
|
||||
2 test-no-wall-clock:src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx
|
||||
1 test-no-wall-clock:src/renderer/src/components/sidebar/workspace-card/review/use-workspace-reference-details.test.tsx
|
||||
1 test-no-wall-clock:src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx
|
||||
2 test-no-wall-clock:src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -51,7 +51,6 @@
|
||||
"config/scripts/ci/unit-selection/ci-unit-selection-review.test.mjs": 51,
|
||||
"config/scripts/ci/unit-selection/ci-unit-selection.test.mjs": 271,
|
||||
"config/scripts/ci/sharding/ci-unit-sequencer.test.mjs": 296,
|
||||
"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/desktop-build/output-contracts/dark-build-switches.test.mjs": 52,
|
||||
@@ -397,7 +396,6 @@
|
||||
"src/main/acp/history/acp-history-scaling.test.ts": 24879,
|
||||
"src/main/persistence/preferences/active-view-persistence-boundary.test.ts": 2119,
|
||||
"src/main/persistence/preferences/active-view-preference-sync-flush-veto.test.ts": 781,
|
||||
"src/main/persistence/preferences/active-view-preference.test.ts": 61,
|
||||
"src/main/providers/accounts/agent-auth-restart-preservation.test.ts": 55,
|
||||
"src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.test.ts": 202,
|
||||
"src/main/agent-hooks/installation/scripts/cursor-replay-guard.test.ts": 403,
|
||||
@@ -1597,7 +1595,6 @@
|
||||
"src/main/filesystem/host-checkout-removal.test.ts": 52,
|
||||
"src/main/filesystem/host-tree-removal-asar.electron.test.ts": 308,
|
||||
"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/secret-protection-report.test.ts": 59,
|
||||
"src/main/i18n/main-i18n-lazy-locale.test.ts": 518,
|
||||
@@ -1612,7 +1609,6 @@
|
||||
"src/main/ipc/ai-vault/ai-vault-scan-coalescing.test.ts": 2230,
|
||||
"src/main/ipc/ai-vault/ai-vault-search-all-hosts-real-index.test.ts": 1852,
|
||||
"src/main/ipc/ai-vault/ai-vault-search-all-hosts.test.ts": 123,
|
||||
"src/main/ipc/ai-vault/ai-vault-search.test.ts": 1424,
|
||||
"src/main/ipc/ai-vault/ai-vault-unresolved-owner.test.ts": 1436,
|
||||
"src/main/ipc/app.test.ts": 319,
|
||||
"src/main/ipc/automations-external-scope.test.ts": 359,
|
||||
@@ -1625,7 +1621,6 @@
|
||||
"src/main/ipc/crash-reporting/crash-reporting-replay-guard-wedge-burst.test.ts": 82,
|
||||
"src/main/ipc/created-worktree-root-prune.test.ts": 494,
|
||||
"src/main/ipc/developer-permissions.test.ts": 147,
|
||||
"src/main/ipc/diagnostics.test.ts": 124,
|
||||
"src/main/ipc/dropped-path-resolution.test.ts": 92,
|
||||
"src/main/ipc/emulator-frame-stream-socket-lifetime.test.ts": 166,
|
||||
"src/main/ipc/emulator-renderer-lifetime.test.ts": 116,
|
||||
@@ -1652,12 +1647,10 @@
|
||||
"src/main/ipc/filesystem/filesystem-list-files.test.ts": 796,
|
||||
"src/main/ipc/filesystem/filesystem-listing-cancel-admission.test.ts": 157,
|
||||
"src/main/ipc/filesystem/filesystem-mutations.test.ts": 1189,
|
||||
"src/main/ipc/filesystem/access/filesystem-path-containment-remote-enoent.test.ts": 45,
|
||||
"src/main/ipc/filesystem/access/filesystem-path-containment-unicode-normalization.test.ts": 505,
|
||||
"src/main/ipc/filesystem/filesystem-pull-request-linked-issue-lifetime.test.ts": 2532,
|
||||
"src/main/ipc/filesystem/filesystem-quick-open-options.integration.test.ts": 1350,
|
||||
"src/main/ipc/filesystem/filesystem-runtime-upload-staging.test.ts": 106,
|
||||
"src/main/ipc/filesystem/filesystem-search-file-paths.test.ts": 443,
|
||||
"src/main/ipc/filesystem/filesystem-symlink-directory-entries.test.ts": 56,
|
||||
"src/main/ipc/filesystem/filesystem-write-bytes.test.ts": 147,
|
||||
"src/main/ipc/filesystem/filesystem-wsl-stopped-distro-git.test.ts": 1163,
|
||||
@@ -1762,7 +1755,6 @@
|
||||
"src/main/ipc/runtime-environments/runtime-environments-repair.test.ts": 4122,
|
||||
"src/main/ipc/runtime-environments/runtime-environments-subscription-lifecycle.test.ts": 5098,
|
||||
"src/main/ipc/runtime-upload-file-stream.test.ts": 144,
|
||||
"src/main/ipc/runtime.test.ts": 3323,
|
||||
"src/main/ipc/sender-scoped-request-cancellation.test.ts": 80,
|
||||
"src/main/ipc/session-window-view-save.test.ts": 1998,
|
||||
"src/main/ipc/settings-delayed-response.test.ts": 2804,
|
||||
@@ -1774,7 +1766,6 @@
|
||||
"src/main/ipc/ssh/ssh-credential-cancel.test.ts": 4604,
|
||||
"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-render-desync-evidence.test.ts": 78,
|
||||
"src/main/ipc/terminal-startup-color-query-replies.test.ts": 265,
|
||||
"src/main/workspaces/removal/watcher-removal-gate.test.ts": 384,
|
||||
@@ -1788,7 +1779,6 @@
|
||||
"src/main/ipc/worktrees/git/worktree-git-common-native-upgrade-poll.test.ts": 57,
|
||||
"src/main/ipc/worktrees/git/worktree-git-common-watch-reconciliation.test.ts": 121,
|
||||
"src/main/ipc/worktrees/git/worktree-git-status-attribution-real-git.test.ts": 1963,
|
||||
"src/main/ipc/worktrees/git/worktree-git-status-ref-watch.test.ts": 59,
|
||||
"src/main/ipc/worktrees/creation/worktree-head-identity-reader-incremental.test.ts": 144,
|
||||
"src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts": 74,
|
||||
"src/main/ipc/worktree-logic.test.ts": 323,
|
||||
@@ -1803,7 +1793,6 @@
|
||||
"src/main/ipc/worktrees-removal-recovery.test.ts": 1971,
|
||||
"src/main/ipc/worktrees-remove-preflight.test.ts": 1415,
|
||||
"src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts": 650,
|
||||
"src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts": 105,
|
||||
"src/main/ipc/worktrees/listing/detected-worktree-scan-listing-distro.test.ts": 880,
|
||||
"src/main/ipc/worktrees/listing/detected-worktree-scan-superseded.test.ts": 110,
|
||||
"src/main/ipc/wsl-guest-native-program.test.ts": 107,
|
||||
@@ -1884,7 +1873,6 @@
|
||||
"src/main/managed-server/install/orcad-remote-shell-commands.integration.test.ts": 9000,
|
||||
"src/main/managed-server/install/orcad-remote-windows-scripts.test.ts": 3474,
|
||||
"src/main/managed-server/install/remote-install-lock-exited-owner.test.ts": 380,
|
||||
"src/main/managed-server/install/remote-install-lock-termination.test.ts": 215,
|
||||
"src/main/managed-server/install/remote-install-model.test.ts": 164,
|
||||
"src/main/managed-server/install/remote-install-noisy-sftp-wire.test.ts": 520,
|
||||
"src/main/managed-server/install/remote-node-runtime-store-gc.test.ts": 2254,
|
||||
@@ -1897,7 +1885,6 @@
|
||||
"src/main/managed-server/lifecycle/orcad-managed-tunnel-peer-restart.test.ts": 494,
|
||||
"src/main/managed-server/lifecycle/orcad-managed-tunnel-transport-real-openssh.test.ts": 360,
|
||||
"src/main/managed-server/lifecycle/orcad-managed-update-deferrals.test.ts": 44,
|
||||
"src/main/managed-server/lifecycle/orcad-runtime-forget.test.ts": 857,
|
||||
"src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.test.ts": 595,
|
||||
"src/main/media/media-preview-protocol.test.ts": 1027,
|
||||
"src/main/media/preview-grant-range-read.test.ts": 691,
|
||||
@@ -1936,7 +1923,6 @@
|
||||
"src/main/native-chat/agent-session-timeline/provider-timeline-assembler-held-rows.test.ts": 799,
|
||||
"src/main/native-chat/agent-session-timeline/provider-timeline-assembler-refusal.test.ts": 1225,
|
||||
"src/main/native-chat/agent-session-timeline/provider-timeline-assembler-restart.test.ts": 576,
|
||||
"src/main/native-chat/agent-session-timeline/provider-timeline-assembler-rows.test.ts": 1710,
|
||||
"src/main/native-chat/agent-session-timeline/provider-timeline-assembler-streams.test.ts": 757,
|
||||
"src/main/native-chat/agent-session-timeline/provider-timeline-assembler-turns.test.ts": 809,
|
||||
"src/main/native-chat/agent-session-timeline/provider-timeline-identity.test.ts": 52,
|
||||
@@ -2168,7 +2154,6 @@
|
||||
"src/main/persistence/profile-state/database/profile-state-write-transaction.test.ts": 94,
|
||||
"src/main/persistence/profile-state/writer/profile-state-writer-worker.test.ts": 1458,
|
||||
"src/main/persistence/restoring-sessions/pane-alias-normalization.test.ts": 847,
|
||||
"src/main/persistence/restoring-sessions/session-worktree-ownership.test.ts": 490,
|
||||
"src/main/persistence/restoring-sessions/tab-terminal-pane-binding-repair.test.ts": 348,
|
||||
"src/main/persistence/restoring-sessions/terminal-layout-normalization.test.ts": 73,
|
||||
"src/main/persistence/restoring-sessions/unattached-terminal-row-sweep.test.ts": 347,
|
||||
@@ -2197,7 +2182,6 @@
|
||||
"src/main/persistence/loading-store/workspace-sessions/terminal-sleep-quit-resume.test.ts": 1766,
|
||||
"src/main/persistence/terminal-topology/pane-moves/terminal-window-pane-detach.test.ts": 1941,
|
||||
"src/main/persistence/restoring-sessions/windowless-restart-lost-binding.test.ts": 1626,
|
||||
"src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts": 544,
|
||||
"src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts": 619,
|
||||
"src/main/persistence/tracking-repos/persistence-deregistered-repo-residue.test.ts": 2374,
|
||||
"src/main/persistence/tracking-repos/persistence-duplicate-repo-id-host-scope.test.ts": 2045,
|
||||
@@ -2205,7 +2189,6 @@
|
||||
"src/main/persistence/tracking-repos/persistence-folder-workspace-notes.test.ts": 2124,
|
||||
"src/main/persistence/tracking-repos/persistence-invalid-workspace-layout-purge.test.ts": 2151,
|
||||
"src/main/persistence/tracking-repos/persistence-update-repo.test.ts": 2213,
|
||||
"src/main/persistence/tracking-repos/persistence-workspace-attachments.test.ts": 2030,
|
||||
"src/main/persistence/tracking-repos/persistence-workspace-pinned-automation-fence.test.ts": 2412,
|
||||
"src/main/persistence/tracking-repos/persistence-workspace-repin-automation-owner.test.ts": 2205,
|
||||
"src/main/persistence/tracking-repos/persistence-workspace-session-scrollback.test.ts": 1952,
|
||||
@@ -2219,7 +2202,6 @@
|
||||
"src/main/persistence/tracking-repos/project-group-session-batch.test.ts": 496,
|
||||
"src/main/persistence/tracking-repos/repo-update-host-guard.test.ts": 478,
|
||||
"src/main/persistence/tracking-repos/worktree-identity-migration-field-coverage.test.ts": 505,
|
||||
"src/main/persistence/tracking-repos/worktree-metadata-normalization.test.ts": 372,
|
||||
"src/main/persistence/window-save-sleep-records.test.ts": 60,
|
||||
"src/main/pi/managed-extensions/agent-status/agent-status-extension-nested-run-settlement.test.ts": 335,
|
||||
"src/main/pi/managed-extensions/agent-status/agent-status-extension-session-change.test.ts": 613,
|
||||
@@ -2233,7 +2215,6 @@
|
||||
"src/main/plugins/catalog/plugin-catalog-monorepo-images.test.ts": 216,
|
||||
"src/main/plugins/catalog/plugin-install-stats-service.test.ts": 196,
|
||||
"src/main/plugins/catalog/plugin-kill-list-content-revocation.test.ts": 3680,
|
||||
"src/main/plugins/catalog/plugin-kill-list-service.test.ts": 289,
|
||||
"src/main/plugins/catalog/plugin-marketplace-installer.test.ts": 859,
|
||||
"src/main/plugins/catalog/plugin-marketplace-store.test.ts": 250,
|
||||
"src/main/plugins/catalog/plugin-private-marketplace.integration.test.ts": 978,
|
||||
@@ -2288,7 +2269,6 @@
|
||||
"src/main/plugins/plugin-vm-recipe-registry.test.ts": 349,
|
||||
"src/main/plugins/view/plugin-view-editor-shot.test.ts": 194,
|
||||
"src/main/plugins/view/plugin-view-replay-shot.test.ts": 256,
|
||||
"src/main/plugins/view/plugin-view-target.test.ts": 143,
|
||||
"src/main/plugins/workers/plugin-host-panel-methods.test.ts": 304,
|
||||
"src/main/plugins/workers/plugin-host-runtime.test.ts": 274,
|
||||
"src/main/plugins/workers/plugin-worker-controller.test.ts": 394,
|
||||
@@ -3585,7 +3565,6 @@
|
||||
"src/renderer/src/components/agent-tab-shortcut-launch.test.ts": 369,
|
||||
"src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx": 2090,
|
||||
"src/renderer/src/components/artifacts/ArtifactCollection.test.tsx": 1833,
|
||||
"src/renderer/src/components/artifacts/ArtifactPreview.test.tsx": 474,
|
||||
"src/renderer/src/components/artifacts/ArtifactPublishButton.test.tsx": 706,
|
||||
"src/renderer/src/components/artifacts/ArtifactsPage.test.tsx": 2052,
|
||||
"src/renderer/src/components/artifacts/artifact-publish-flow.test.ts": 114,
|
||||
@@ -3884,7 +3863,6 @@
|
||||
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.host-outage.test.tsx": 3552,
|
||||
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.refusal-notices.test.tsx": 3014,
|
||||
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test.tsx": 4459,
|
||||
"src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx": 583,
|
||||
"src/renderer/src/components/native-chat/tools/lines/NativeChatToolLine.test.tsx": 3544,
|
||||
"src/renderer/src/components/native-chat/tools/lines/NativeChatToolOutput.test.tsx": 410,
|
||||
"src/renderer/src/components/native-chat/tools/runs/NativeChatToolRun.identity.test.tsx": 3269,
|
||||
@@ -3916,7 +3894,6 @@
|
||||
"src/renderer/src/components/native-chat/attachments/intake/native-chat-external-attachments-destination.test.tsx": 951,
|
||||
"src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts": 1937,
|
||||
"src/renderer/src/components/native-chat/links/actions/native-chat-host-file-open.test.ts": 895,
|
||||
"src/renderer/src/components/native-chat/links/previews/native-chat-hover-preview-cache.test.ts": 49,
|
||||
"src/renderer/src/components/native-chat/attachments/chips/native-chat-image-references.test.tsx": 2485,
|
||||
"src/renderer/src/components/native-chat/session/terminal/assembly/native-chat-live-message-preparation.test.ts": 252,
|
||||
"src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-projection.test.ts": 207,
|
||||
@@ -3950,7 +3927,6 @@
|
||||
"src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.test.tsx": 2467,
|
||||
"src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-preview-lifetime.test.tsx": 1926,
|
||||
"src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.test.tsx": 797,
|
||||
"src/renderer/src/components/native-chat/session/status/use-native-chat-hook-status.test.ts": 1927,
|
||||
"src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage.test.tsx": 2131,
|
||||
"src/renderer/src/components/native-chat/drafts/use-native-chat-launch-draft-adoption.test.tsx": 319,
|
||||
"src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-live-session-pending.test.ts": 2063,
|
||||
@@ -3962,7 +3938,6 @@
|
||||
"src/renderer/src/components/native-chat/session/terminal/delivery/use-native-chat-pending-delivery.test.tsx": 457,
|
||||
"src/renderer/src/components/native-chat/composer/pickers/use-native-chat-picker-state.test.tsx": 315,
|
||||
"src/renderer/src/components/native-chat/use-native-chat-rail-history-jump.test.ts": 572,
|
||||
"src/renderer/src/components/native-chat/session/terminal/read/use-native-chat-retained-session.test.ts": 229,
|
||||
"src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind.test.tsx": 686,
|
||||
"src/renderer/src/components/native-chat/session/terminal/send/use-native-chat-send-lifecycle.test.tsx": 281,
|
||||
"src/renderer/src/components/native-chat/session/options/terminal/use-native-chat-session-options.test.ts": 1068,
|
||||
@@ -4003,7 +3978,6 @@
|
||||
"src/renderer/src/components/quick-open-file-list.test.ts": 54,
|
||||
"src/renderer/src/components/quick-open-recent-validation.test.ts": 213,
|
||||
"src/renderer/src/components/render-phase-adjustment-discarded-render.test.tsx": 2577,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/scanning/AiVaultScanProgressStrip.test.tsx": 893,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/session-list/AiVaultSessionHistoryDialog.test.tsx": 2796,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/session-list/AiVaultSessionVirtualList.measurement.test.tsx": 3117,
|
||||
"src/renderer/src/components/right-sidebar/FolderWorkspaceWorktreesPanel.test.tsx": 461,
|
||||
@@ -4011,7 +3985,6 @@
|
||||
"src/renderer/src/components/right-sidebar/PortsPanel.test.tsx": 1618,
|
||||
"src/renderer/src/components/right-sidebar/source-control/ai/SourceControlAgentActionDialog.test.tsx": 2772,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-account-native.test.tsx": 2785,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-account-peer.test.tsx": 2516,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-original-pane.test.ts": 64,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-panel-session-list-request.test.tsx": 3044,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/session-list/ai-vault-session-filters.test.ts": 105,
|
||||
@@ -4022,7 +3995,6 @@
|
||||
"src/renderer/src/components/right-sidebar/checks-panel/checks-list-expanded-details.test.tsx": 1549,
|
||||
"src/renderer/src/components/right-sidebar/checks-panel/comments/review-comment-markdown.test.tsx": 2171,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-delete-undo-precondition.test.tsx": 2023,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-dir-pages.test.ts": 1767,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-expanded-dirs-refresh.test.ts": 1962,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-inline-input-ime-enter.test.tsx": 479,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-linked-recovery.test.tsx": 2158,
|
||||
@@ -4041,14 +4013,12 @@
|
||||
"src/renderer/src/components/right-sidebar/source-control/review/create-pr-intent-operation-target.test.ts": 1735,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.test.tsx": 688,
|
||||
"src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-terminal-worktree.test.ts": 2116,
|
||||
"src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-jira-review-title.test.tsx": 1979,
|
||||
"src/renderer/src/components/right-sidebar/source-control/sync/use-source-control-git-history.test.tsx": 1951,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileDeletion.save-refusal.test.tsx": 840,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileDeletion.trash-failure.test.tsx": 774,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileExplorerImport.committed-scope.test.tsx": 588,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerTree.stale-dirs.test.tsx": 1958,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchPanel.lifecycle.test.tsx": 2249,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/content-search/useFileSearchRunner.test.tsx": 742,
|
||||
"src/renderer/src/components/right-sidebar/source-control/listing/useSourceControlSubmoduleStatus.test.tsx": 2076,
|
||||
"src/renderer/src/components/settings/accounts/AccountsPane.owner-scope.test.tsx": 4057,
|
||||
"src/renderer/src/components/settings/agents/AgentsPane.test.tsx": 3230,
|
||||
@@ -4092,7 +4062,6 @@
|
||||
"src/renderer/src/components/session-search/use-session-search-status.test.tsx": 477,
|
||||
"src/renderer/src/components/settings/accounts/usage/use-zcode-plan-credentials.test.tsx": 880,
|
||||
"src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts": 1925,
|
||||
"src/renderer/src/components/shared/useDaemonActions.test.tsx": 332,
|
||||
"src/renderer/src/components/sidebar/host-admission/ssh/AddRemoteHostDialog.config-picker.test.tsx": 1178,
|
||||
"src/renderer/src/components/sidebar/project-admission/dialog/AddRepoDialogChrome.test.tsx": 714,
|
||||
"src/renderer/src/components/sidebar/workspace-card/identity/AutoRenameFailedDialog.test.tsx": 2254,
|
||||
@@ -4110,7 +4079,6 @@
|
||||
"src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCard.single-reference-details.test.tsx": 2032,
|
||||
"src/renderer/src/components/sidebar/workspace-actions/context-menu/WorktreeContextMenu.closed-menu-work.test.tsx": 1753,
|
||||
"src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx": 5388,
|
||||
"src/renderer/src/components/sidebar/workspace-card/metadata/WorktreeMetaDialog.host-scope.test.tsx": 2215,
|
||||
"src/renderer/src/components/sidebar/workspace-card/metadata/WorktreeMetaDialog.test.tsx": 7694,
|
||||
"src/renderer/src/components/sidebar/workspace-visibility/dialog/WorktreeVisibilityDialog.test.tsx": 2602,
|
||||
"src/renderer/src/components/sidebar/chat-markdown-math-typeset.test.ts": 1336,
|
||||
@@ -4267,7 +4235,6 @@
|
||||
"src/renderer/src/components/terminal-pane/pty-connection/reattach/deferred-session-reattach-startup-snapshot.test.ts": 1830,
|
||||
"src/renderer/src/components/terminal-pane/pty-connection/reattach/deferred-session-reattach-wsl-distro-stopped-hold.test.ts": 2517,
|
||||
"src/shared/terminal/protocol/escape/terminal-synchronized-output-socket-splits.test.ts": 92,
|
||||
"src/renderer/src/components/terminal-pane/pty-connection/spawn/hidden-agent-resume-deferral.test.ts": 55,
|
||||
"src/renderer/src/components/terminal-pane/pty-connection/startup/main-pane-resume-banner.test.ts": 59,
|
||||
"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,
|
||||
@@ -4538,8 +4505,6 @@
|
||||
"src/shared/agent-status/contracts/agent-status-evidence-clock.test.ts": 88,
|
||||
"src/shared/agent-status/title/agent-title-tracker.test.ts": 172,
|
||||
"src/renderer/src/lib/agent-session/resume/history/ai-vault-antigravity-reference-host.test.ts": 678,
|
||||
"src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.drop-repin.test.ts": 541,
|
||||
"src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-target.test.ts": 92,
|
||||
"src/renderer/src/lib/agent-session/resume/history/ai-vault-session-drag.test.ts": 68,
|
||||
"src/renderer/src/lib/agent-session/resume/history/ai-vault-session-resume-preparation.test.ts": 408,
|
||||
"src/renderer/src/lib/agent-session/history/title-sync/ai-vault-tab-title-sync-inputs.test.ts": 476,
|
||||
@@ -4620,7 +4585,6 @@
|
||||
"src/renderer/src/lib/workspace/search/tabs/workspace-tab-palette-activation.store.test.ts": 1994,
|
||||
"src/renderer/src/lib/workspace/ownership/workspace-terminal-host-authority.test.ts": 2066,
|
||||
"src/renderer/src/lib/workspace/activation/worktree-activation-created-agent.test.ts": 2295,
|
||||
"src/renderer/src/lib/workspace/activation/worktree-activation-launch-awaiting-host.test.ts": 2161,
|
||||
"src/renderer/src/lib/workspace/activation/worktree-activation-structured-chat-surface.test.ts": 2043,
|
||||
"src/renderer/src/lib/workspace/activation/worktree-activation-web-runtime.test.ts": 2768,
|
||||
"src/renderer/src/lib/workspace/creation/worktree-creation-initial-surface.test.ts": 5258,
|
||||
@@ -4674,7 +4638,6 @@
|
||||
"src/renderer/src/runtime/browser/creation/web-runtime-browser-link-open.test.ts": 2217,
|
||||
"src/renderer/src/runtime/web-session-tabs-sync/tracking/web-session-tabs-removed-frame-retires-live-publisher.test.ts": 854,
|
||||
"src/renderer/src/runtime/web-session-tabs-sync/subscriptions/web-session-tabs-stream-end-resubscribe.test.tsx": 2282,
|
||||
"src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-editor-ownership.test.ts": 1902,
|
||||
"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts": 892,
|
||||
"src/renderer/src/runtime/web-session-tabs-sync/agent-status/web-session-tabs-sync-host-tab-retraction-ghost-rows.test.ts": 1956,
|
||||
"src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-mirrored-draft-close.test.ts": 1833,
|
||||
@@ -4722,7 +4685,6 @@
|
||||
"src/renderer/src/store/slices/browser/cleanup/browser-mount-admission-removal.test.ts": 1982,
|
||||
"src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts": 1777,
|
||||
"src/renderer/src/store/slices/browser/hosts/browser-session-host-selection.test.ts": 988,
|
||||
"src/renderer/src/store/slices/browser/profiles/browser-session-profiles.test.ts": 792,
|
||||
"src/renderer/src/store/slices/browser/tabs/browser-tab-creation-placement.test.ts": 1886,
|
||||
"src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts": 2007,
|
||||
"src/renderer/src/store/slices/browser/browser.test.ts": 2001,
|
||||
@@ -4740,7 +4702,6 @@
|
||||
"src/renderer/src/store/slices/editor/markdown/editor-markdown-link-activation.test.ts": 953,
|
||||
"src/renderer/src/store/slices/editor/tabs/editor-preview-tab-setting.test.ts": 1952,
|
||||
"src/renderer/src/store/slices/editor/opening/editor-read-only-tabs.test.ts": 901,
|
||||
"src/renderer/src/store/slices/editor/closing/editor-recently-closed-tabs.test.ts": 1948,
|
||||
"src/renderer/src/store/slices/editor/focus/editor-set-active-file-guard.test.ts": 895,
|
||||
"src/renderer/src/store/slices/editor/buffers/editor-buffer-reconcile-identity.test.ts": 1775,
|
||||
"src/renderer/src/store/slices/editor/buffers/editor-buffer-reconcile-joins.test.ts": 1766,
|
||||
@@ -4816,7 +4777,6 @@
|
||||
"src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-stale-catalog-version.test.ts": 1337,
|
||||
"src/renderer/src/store/slices/worktrees/metadata/worktrees-git-identity-branch-title.test.ts": 1181,
|
||||
"src/renderer/src/store/slices/worktrees/listing/worktrees-hydration-purge.test.ts": 1274,
|
||||
"src/renderer/src/store/slices/worktrees/create/worktrees-pending-creation-state.test.ts": 1132,
|
||||
"src/renderer/src/store/slices/worktrees/listing/worktrees-runtime-connection-generation-fence.test.ts": 1240,
|
||||
"src/renderer/src/store/slices/worktrees/session/worktrees-terminal-reference-source-race.test.ts": 1063,
|
||||
"src/renderer/src/store/slices/worktrees/host-scoped-row-merges.test.ts": 1805,
|
||||
@@ -4872,7 +4832,6 @@
|
||||
"src/shared/agent-session/options/agent-cli-flag-detection.test.ts": 56,
|
||||
"src/shared/agent-cli-install-dir-fallback.test.ts": 130,
|
||||
"src/shared/agent-launch/startup/agent-command-line-intent.test.ts": 95,
|
||||
"src/shared/agent-status/title/agent-detection.test.ts": 188,
|
||||
"src/shared/agent-hook-listener/transport/agent-hook-endpoint-temp-cleanup.test.ts": 55,
|
||||
"src/shared/agent-hook-listener/normalization/agent-hook-listener-claude-elicitation.test.ts": 229,
|
||||
"src/shared/agent-hook-listener/normalization/agent-hook-listener-codex-approval-ownership.test.ts": 258,
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import UnitTimingReporter from './ci-unit-timing-reporter.mjs'
|
||||
|
||||
const phaseDiagnostic = (overrides = {}) => ({
|
||||
environmentSetupDuration: 1.5,
|
||||
prepareDuration: 2.5,
|
||||
collectDuration: 30.25,
|
||||
setupDuration: 4.5,
|
||||
duration: 5.25,
|
||||
workerId: 7,
|
||||
concurrencyId: 2,
|
||||
importDurations: {},
|
||||
...overrides
|
||||
})
|
||||
const phaseModule = (file, diagnostic = phaseDiagnostic(), project = 'bun') => ({
|
||||
moduleId: resolve(file),
|
||||
project: { name: project },
|
||||
state: () => 'passed',
|
||||
diagnostic: () => diagnostic
|
||||
})
|
||||
const phaseContext = (state) => ({
|
||||
config: { root: process.cwd(), shard: { index: 1, count: 5 } },
|
||||
version: '5.0.3',
|
||||
state
|
||||
})
|
||||
|
||||
function withReporterOutputs(run) {
|
||||
const directory = mkdtempSync(join(tmpdir(), 'orca-unit-phases-'))
|
||||
const timingPath = join(directory, 'unit-timings.json')
|
||||
const phasePath = join(directory, 'unit-phase-diagnostics.json')
|
||||
vi.stubEnv('ORCA_UNIT_TIMING_REPORT', timingPath)
|
||||
vi.stubEnv('ORCA_UNIT_PHASE_REPORT', undefined)
|
||||
vi.stubEnv('ORCA_UNIT_SELECTION_PLAN', join(directory, 'missing-selection.json'))
|
||||
vi.stubEnv('ORCA_SHARD_SOURCE_SHA', 'phase-source')
|
||||
vi.stubEnv('GITHUB_RUN_ID', 'phase-run')
|
||||
vi.stubEnv('GITHUB_RUN_ATTEMPT', '3')
|
||||
try {
|
||||
run({ timingPath, phasePath })
|
||||
} finally {
|
||||
vi.unstubAllEnvs()
|
||||
rmSync(directory, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
describe('optional unit phase diagnostics', () => {
|
||||
it('preserves timing evidence when optional output targets the timing file', () => {
|
||||
withReporterOutputs(({ timingPath }) => {
|
||||
const reporter = new UnitTimingReporter()
|
||||
reporter.onInit(phaseContext())
|
||||
const modules = [phaseModule('src/example.test.ts')]
|
||||
reporter.onTestRunEnd(modules, [], 'passed')
|
||||
const timing = readFileSync(timingPath, 'utf8')
|
||||
vi.stubEnv('ORCA_UNIT_PHASE_REPORT', timingPath)
|
||||
expect(() => reporter.onTestRunEnd(modules, [], 'passed')).not.toThrow()
|
||||
expect(readFileSync(timingPath, 'utf8')).toBe(timing)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -19,7 +19,6 @@ const NODE_RUNTIME_INCLUDE = [
|
||||
// The forced-probe handoff race opens only under V8's promise scheduling, which Electron main uses.
|
||||
'src/main/github/api/rate-limit.test.ts',
|
||||
// Electron main bridges streams with Node's implementation.
|
||||
'src/main/host/electron-http-client.test.ts',
|
||||
'src/main/browser/extensions/native-messaging/browser-extension-native-host-process-backpressure.test.ts',
|
||||
'src/main/daemon/providers/lifecycle/testing/daemon-init-provider-installation.test.ts',
|
||||
'src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts',
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
// Use the real page adapter: its resolved refusals must not put rejected values into the next shell init’s mirror.
|
||||
vi.mock('@react-native-async-storage/async-storage', async () => ({
|
||||
default: (await import('../mobile-web-shell/bridge/page-storage/page-async-storage')).default
|
||||
}))
|
||||
|
||||
const { publishPageStorage } =
|
||||
await import('../mobile-web-shell/bridge/page-storage/page-async-storage')
|
||||
const { pageStorageKeysForRoute } =
|
||||
await import('../mobile-web-shell/page-storage/page-storage-keys')
|
||||
const { persistMirrored, readMirroredStorage, retainMirroredStorage } =
|
||||
await import('./mirrored-storage-keys')
|
||||
|
||||
const HOST_ID = 'host-1'
|
||||
const ROUTE = '/h/host-1/session/wt-1'
|
||||
const DOCK_WIDTH = 'orca:hostDockWidth'
|
||||
const OTHER_HOST_PIN = 'orca:pins:host-2'
|
||||
let releaseStorage = () => {}
|
||||
|
||||
afterEach(() => releaseStorage())
|
||||
|
||||
beforeEach(() => {
|
||||
releaseStorage = retainMirroredStorage(pageStorageKeysForRoute(HOST_ID, ROUTE))
|
||||
publishPageStorage({ [DOCK_WIDTH]: '320' }, () => true, HOST_ID, ROUTE)
|
||||
return persistMirrored(DOCK_WIDTH, '320')
|
||||
})
|
||||
|
||||
describe('the mirrored write path', () => {
|
||||
it('leaves them alone for a key this route was never given, and logs the drop', async () => {
|
||||
const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
// Unlisted-key writes resolve because page callers may await them without a catch.
|
||||
await expect(persistMirrored(OTHER_HOST_PIN, '["a"]')).resolves.toBeUndefined()
|
||||
expect(readMirroredStorage([OTHER_HOST_PIN])[OTHER_HOST_PIN]).toBeUndefined()
|
||||
expect(warned).toHaveBeenCalledWith(
|
||||
'[page-bridge] storage-write-dropped',
|
||||
expect.objectContaining({ key: OTHER_HOST_PIN, refusal: 'not-allowed' })
|
||||
)
|
||||
warned.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -1,70 +0,0 @@
|
||||
import { createElement } from 'react'
|
||||
import { act, create } from 'react-test-renderer'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { RpcClient } from '../../transport/rpc/rpc-client-contract'
|
||||
import {
|
||||
EMPTY_RETIRED_NAME_REGISTRY,
|
||||
type RetiredNameRegistry
|
||||
} from '../../../../src/shared/worktree/naming/retired-name-registry'
|
||||
import { useRetiredWorktreeNames } from './use-retired-worktree-names'
|
||||
|
||||
type Pending = { resolve: (response: unknown) => void }
|
||||
|
||||
// Defer RPC replies to control both their repo and arrival order.
|
||||
function mountNames() {
|
||||
const pending: Pending[] = []
|
||||
let latest: RetiredNameRegistry = EMPTY_RETIRED_NAME_REGISTRY
|
||||
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The hook only calls this fixture's deferred sendRequest method.
|
||||
const client = {
|
||||
sendRequest: () => new Promise<unknown>((resolve) => pending.push({ resolve }))
|
||||
} as unknown as RpcClient
|
||||
|
||||
function Probe({ repoId, refreshKey }: { repoId: string | null; refreshKey: string }) {
|
||||
latest = useRetiredWorktreeNames(client, repoId, refreshKey)
|
||||
return null
|
||||
}
|
||||
|
||||
let renderer!: ReturnType<typeof create>
|
||||
act(() => {
|
||||
renderer = create(createElement(Probe, { repoId: 'repo-1', refreshKey: 'a' }))
|
||||
})
|
||||
return {
|
||||
get names(): readonly string[] {
|
||||
return latest.names
|
||||
},
|
||||
rerender(props: { repoId: string | null; refreshKey: string }) {
|
||||
act(() => {
|
||||
renderer.update(createElement(Probe, props))
|
||||
})
|
||||
},
|
||||
async settle(
|
||||
index: number,
|
||||
retiredNamesByRepo: Record<string, unknown>,
|
||||
retiredNameTiersByRepo: Record<string, unknown> = {}
|
||||
) {
|
||||
await act(async () => {
|
||||
// Include the real host’s ok field so acceptance exercises success rather than refusal.
|
||||
pending[index]!.resolve({
|
||||
ok: true,
|
||||
result: { retiredNamesByRepo, retiredNameTiersByRepo }
|
||||
})
|
||||
await Promise.resolve()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('useRetiredWorktreeNames', () => {
|
||||
it('drops names when the repo changes rather than showing another repo pool', async () => {
|
||||
const probe = mountNames()
|
||||
await probe.settle(0, { 'repo-1': ['nautilus'] })
|
||||
|
||||
probe.rerender({ repoId: 'repo-1', refreshKey: 'b' })
|
||||
probe.rerender({ repoId: 'repo-2', refreshKey: 'a' })
|
||||
expect(probe.names).toEqual([])
|
||||
await probe.settle(2, { 'repo-2': ['seahorse'] })
|
||||
await probe.settle(1, { 'repo-1': ['nautilus', 'marlin'] })
|
||||
expect(probe.names).toEqual(['seahorse'])
|
||||
})
|
||||
})
|
||||
@@ -1,131 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { AgentJournalToolCallItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import type { PRInfo } from '../../../shared/github/pull-requests/pull-request-types'
|
||||
import {
|
||||
finishedShellCall,
|
||||
pushedPullRequestHead,
|
||||
pushUpdatesByCall
|
||||
} from './pr-chat-action-recorder'
|
||||
import { prInfoFixture } from './pr-watch-test-fixtures'
|
||||
|
||||
type ToolCallRow = { itemId: string; revision: number; body: AgentJournalToolCallItem }
|
||||
|
||||
function toolCallRow(
|
||||
call: Omit<AgentJournalToolCallItem, 'kind' | 'state' | 'output'> & { output: string }
|
||||
): ToolCallRow {
|
||||
const head = call.output
|
||||
return {
|
||||
itemId: 'claude:session:toolu_01',
|
||||
revision: 2,
|
||||
body: {
|
||||
...call,
|
||||
kind: 'tool-call',
|
||||
state: 'completed',
|
||||
output: { head, byteLength: head.length, digest: 'd', truncated: false }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function pushedBranches(row: ToolCallRow): unknown[] {
|
||||
const call = finishedShellCall('chat-1', row, 0)
|
||||
return (call ? pushUpdatesByCall(call) : []).map(({ branch, newSha }) => ({ branch, newSha }))
|
||||
}
|
||||
|
||||
const TO_ORIGIN = 'To github.com:acme/repo.git\n'
|
||||
const REVIEW_PUSHED =
|
||||
"To github.com:acme/repo.git\n 8d5f74b..c512e75 HEAD -> review\nbranch 'review' set up to track 'origin/review'.\n"
|
||||
const REVIEW_UPDATE = { branch: 'review', newSha: 'c512e75' }
|
||||
|
||||
function pushBy(command: string, output: string): unknown[] {
|
||||
return pushedBranches(toolCallRow({ name: 'Bash', input: { command }, output }))
|
||||
}
|
||||
|
||||
describe('push updates from recorded tool calls', () => {
|
||||
it("reads Claude's Bash push and Codex's shell push", () => {
|
||||
// Claude's Bash tool: git writes its update lines to stderr, which the tool merges.
|
||||
const claude = toolCallRow({
|
||||
name: 'Bash',
|
||||
input: { command: 'git push -u origin HEAD', description: 'Push the branch' },
|
||||
output:
|
||||
"To github.com:stablyai/orca.git\n 8d5f74b..c512e75 HEAD -> brennanb2025/ci-lines\nbranch 'brennanb2025/ci-lines' set up to track 'origin/brennanb2025/ci-lines'."
|
||||
})
|
||||
// Codex app-server: one string through a login shell, with its cwd and exit code.
|
||||
const codex = toolCallRow({
|
||||
name: 'shell',
|
||||
input: {
|
||||
command: "/bin/zsh -lc 'git add -A && git commit -m wip && git push --force-with-lease'",
|
||||
cwd: '/Users/me/orca/workspaces/orca/ci-lines'
|
||||
},
|
||||
exitCode: 0,
|
||||
output:
|
||||
'[ci-lines 5d6e7f8] wip\n 1 file changed, 2 insertions(+)\nTo github.com:stablyai/orca.git\n + 1a2b3c4...5d6e7f8 ci-lines -> ci-lines (forced update)\n'
|
||||
})
|
||||
expect(pushedBranches(claude)).toEqual([{ branch: 'brennanb2025/ci-lines', newSha: 'c512e75' }])
|
||||
expect(pushedBranches(codex)).toEqual([{ branch: 'ci-lines', newSha: '5d6e7f8' }])
|
||||
})
|
||||
|
||||
it("reads a push after a heredoc's declaration, past `;`", () => {
|
||||
const command = "cat <<'EOF' > notes.md; git push -u origin HEAD 2>&1\nnotes\nEOF"
|
||||
expect(pushBy(command, REVIEW_PUSHED)).toEqual([REVIEW_UPDATE])
|
||||
})
|
||||
|
||||
it('takes nothing from a heredoc that prints a push and its update lines', () => {
|
||||
const printed =
|
||||
'git push -u origin HEAD 2>&1\nTo github.com:acme/repo.git\n 1234567..89abcde HEAD -> review\n'
|
||||
for (const opener of ["<<'EOF'", '<<EOF', '<<"EOF"']) {
|
||||
expect(pushBy(`cat ${opener}\n${printed}EOF`, printed)).toEqual([])
|
||||
}
|
||||
const indented = printed.replace(/^/gmu, '\t').replace(/\t$/u, '')
|
||||
expect(pushBy(`cat <<-EOF\n${indented}\tEOF`, printed)).toEqual([])
|
||||
})
|
||||
|
||||
it("doesn't let an escaped `>` before a real pipe hide the push after it", () => {
|
||||
expect(pushBy('printf x \\>|git push origin HEAD', REVIEW_PUSHED)).toEqual([REVIEW_UPDATE])
|
||||
})
|
||||
})
|
||||
|
||||
describe('pushedPullRequestHead', () => {
|
||||
const updateOf = (output: string) =>
|
||||
pushUpdatesByCall({
|
||||
chatId: 'chat-1',
|
||||
anchor: { itemId: 'item', revision: 1 },
|
||||
script: 'git push',
|
||||
output,
|
||||
finishedAt: 0
|
||||
})[0]!
|
||||
// The remote as resolved through the checkout's config; here, what the `To` line parsed to.
|
||||
const match = (output: string, pr: PRInfo) => {
|
||||
const update = updateOf(output)
|
||||
return pushedPullRequestHead(update, update.remote, pr)
|
||||
}
|
||||
const pr = (fields: Partial<PRInfo>): PRInfo =>
|
||||
prInfoFixture({
|
||||
number: 20,
|
||||
headRefName: 'review',
|
||||
headSha: '89abcde0123',
|
||||
headRepo: { owner: 'acme', repo: 'repo' },
|
||||
...fields
|
||||
})
|
||||
|
||||
it('binds a push to the branch, repository and forge host its own update line names', () => {
|
||||
// `git push origin work:review` updated review, not the checked-out branch.
|
||||
const workToReview = `${TO_ORIGIN} 1234567..89abcde work -> review\n`
|
||||
expect(match(workToReview, pr({}))).toEqual({ headSha: '89abcde0123', superseded: false })
|
||||
// A new branch in another repository is not this fork PR's head.
|
||||
expect(
|
||||
match('To github.com:parent/repo.git\n * [new branch] HEAD -> review\n', pr({}))
|
||||
).toBeNull()
|
||||
// The same commit pushed to the same owner/repo on another forge host is another repository.
|
||||
expect(
|
||||
match(
|
||||
'To https://github.enterprise.example/acme/repo.git\n 1234567..89abcde work -> review\n',
|
||||
pr({})
|
||||
)
|
||||
).toBeNull()
|
||||
// Another push moved the PR on before the read: the proven head is kept, marked superseded.
|
||||
expect(match(workToReview, pr({ headSha: 'ffff0000aaaa' }))).toEqual({
|
||||
headSha: '89abcde',
|
||||
superseded: true
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,173 +0,0 @@
|
||||
import { Readable, Writable } from 'node:stream'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
type LoginCallback = (username?: string, password?: string) => void
|
||||
type ProxyChallenge = { isProxy: boolean; host: string; port: number }
|
||||
|
||||
class FakeClientRequest extends Writable {
|
||||
readonly body: Buffer[] = []
|
||||
readonly headers = new Map<string, string>()
|
||||
readonly abort = vi.fn()
|
||||
ended = false
|
||||
|
||||
override _write(chunk: Buffer, _encoding: BufferEncoding, callback: () => void): void {
|
||||
this.body.push(chunk)
|
||||
callback()
|
||||
}
|
||||
|
||||
override _final(callback: () => void): void {
|
||||
this.ended = true
|
||||
callback()
|
||||
}
|
||||
|
||||
setHeader(key: string, value: string): void {
|
||||
this.headers.set(key, value)
|
||||
}
|
||||
|
||||
challenge(authInfo: ProxyChallenge): LoginCallback {
|
||||
const callback = vi.fn<LoginCallback>()
|
||||
this.emit('login', authInfo, callback)
|
||||
return callback
|
||||
}
|
||||
|
||||
respond(status: number, text: string | null): Readable {
|
||||
// null leaves the body stalled after headers.
|
||||
const stream = text === null ? new Readable({ read() {} }) : Readable.from([Buffer.from(text)])
|
||||
const response = Object.assign(stream, {
|
||||
statusCode: status,
|
||||
statusMessage: 'OK',
|
||||
headers: { 'content-type': 'text/plain', 'set-cookie': ['a=1', 'b=2'] }
|
||||
})
|
||||
this.emit('response', response)
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
defaultSession: {
|
||||
resolveProxy: async (): Promise<string> => 'DIRECT',
|
||||
setProxy: async (): Promise<void> => {}
|
||||
},
|
||||
netFetch: vi.fn(),
|
||||
netRequest: vi.fn(),
|
||||
readiness: vi.fn<() => boolean | Promise<boolean>>(() => true)
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
net: { fetch: mocks.netFetch, request: mocks.netRequest },
|
||||
session: { defaultSession: mocks.defaultSession }
|
||||
}))
|
||||
|
||||
vi.mock('../network/proxy-settings', () => ({
|
||||
getProxySessionApplicationReadiness: mocks.readiness
|
||||
}))
|
||||
|
||||
import {
|
||||
resetElectronProxyCredentialsForTests,
|
||||
setElectronProxyCredentialsForSession
|
||||
} from '../network/electron-proxy-credentials'
|
||||
import { electronHttpClient } from './electron-http-client'
|
||||
|
||||
const PROXY = { host: 'proxy.corp', port: 8080, username: 'user', password: 'secret' }
|
||||
let native: FakeClientRequest
|
||||
|
||||
// Wrapped so awaiting the request start does not also await its response.
|
||||
async function startRequest(init?: RequestInit): Promise<{ pending: Promise<Response> }> {
|
||||
const pending = electronHttpClient.fetch('https://api.example.com/v1', init)
|
||||
await vi.waitFor(() => expect(mocks.netRequest).toHaveBeenCalled())
|
||||
return { pending }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
native = new FakeClientRequest()
|
||||
mocks.netRequest.mockReturnValue(native)
|
||||
mocks.netFetch.mockResolvedValue(new Response('direct'))
|
||||
mocks.readiness.mockReturnValue(true)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetElectronProxyCredentialsForTests()
|
||||
})
|
||||
|
||||
describe('electronHttpClient proxy authentication', () => {
|
||||
it('answers the configured proxy challenge on a cold request', async () => {
|
||||
setElectronProxyCredentialsForSession(mocks.defaultSession, PROXY)
|
||||
const { pending } = await startRequest({ method: 'POST', body: 'payload', headers: { a: 'b' } })
|
||||
|
||||
const login = native.challenge({ isProxy: true, host: 'PROXY.corp', port: 8080 })
|
||||
await vi.waitFor(() => expect(native.ended).toBe(true))
|
||||
native.respond(200, 'ok')
|
||||
const response = await pending
|
||||
|
||||
expect(login).toHaveBeenCalledWith('user', 'secret')
|
||||
expect(mocks.netRequest).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ session: mocks.defaultSession, method: 'POST' })
|
||||
)
|
||||
expect(native.headers.get('a')).toBe('b')
|
||||
expect(Buffer.concat(native.body).toString()).toBe('payload')
|
||||
expect(response.headers.get('set-cookie')).toBe('a=1, b=2')
|
||||
expect(await response.text()).toBe('ok')
|
||||
expect(mocks.netFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('cancels unrelated, origin, and repeated challenges', async () => {
|
||||
setElectronProxyCredentialsForSession(mocks.defaultSession, PROXY)
|
||||
await startRequest()
|
||||
|
||||
expect(native.challenge({ isProxy: true, host: 'other', port: 8080 })).toHaveBeenCalledWith()
|
||||
|
||||
native = new FakeClientRequest()
|
||||
mocks.netRequest.mockReturnValue(native)
|
||||
void electronHttpClient.fetch('https://api.example.com/v1')
|
||||
await vi.waitFor(() => expect(mocks.netRequest).toHaveBeenCalledTimes(2))
|
||||
expect(
|
||||
native.challenge({ isProxy: false, host: 'proxy.corp', port: 8080 })
|
||||
).toHaveBeenCalledWith()
|
||||
|
||||
native = new FakeClientRequest()
|
||||
mocks.netRequest.mockReturnValue(native)
|
||||
void electronHttpClient.fetch('https://api.example.com/v1')
|
||||
await vi.waitFor(() => expect(mocks.netRequest).toHaveBeenCalledTimes(3))
|
||||
const challenge = { isProxy: true, host: 'proxy.corp', port: 8080 }
|
||||
expect(native.challenge(challenge)).toHaveBeenCalledWith('user', 'secret')
|
||||
expect(native.challenge(challenge)).toHaveBeenCalledWith()
|
||||
})
|
||||
|
||||
it('waits for a pending proxy policy to install its credentials', async () => {
|
||||
let settle: (ready: boolean) => void = () => {}
|
||||
mocks.readiness.mockReturnValue(new Promise((resolve) => (settle = resolve)))
|
||||
const pending = electronHttpClient.fetch('https://api.example.com/v1')
|
||||
|
||||
setElectronProxyCredentialsForSession(mocks.defaultSession, PROXY)
|
||||
settle(true)
|
||||
await vi.waitFor(() => expect(mocks.netRequest).toHaveBeenCalled())
|
||||
native.respond(204, '')
|
||||
|
||||
expect((await pending).body).toBeNull()
|
||||
expect(mocks.netFetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects with the caller abort reason and aborts the native request', async () => {
|
||||
setElectronProxyCredentialsForSession(mocks.defaultSession, PROXY)
|
||||
const controller = new AbortController()
|
||||
const { pending } = await startRequest({ signal: controller.signal })
|
||||
|
||||
const reason = new Error('stop')
|
||||
controller.abort(reason)
|
||||
|
||||
await expect(pending).rejects.toBe(reason)
|
||||
expect(native.abort).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('cancels a stalled response body without waiting for more data', async () => {
|
||||
setElectronProxyCredentialsForSession(mocks.defaultSession, PROXY)
|
||||
const { pending } = await startRequest()
|
||||
const stalled = native.respond(503, null)
|
||||
const response = await pending
|
||||
|
||||
await response.body?.cancel()
|
||||
|
||||
expect(stalled.destroyed).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,120 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { clearSearch, handlers, sshSearch, sshHostInfos, runtimeSearch } = vi.hoisted(() => ({
|
||||
clearSearch: vi.fn(),
|
||||
handlers: new Map<string, (...args: unknown[]) => Promise<unknown>>(),
|
||||
sshSearch: vi.fn(),
|
||||
sshHostInfos: vi.fn<() => { targetId: string }[]>(() => []),
|
||||
runtimeSearch: vi.fn()
|
||||
}))
|
||||
vi.mock('../../ai-vault/scan-service/session-scanner-service-spawn', () => ({
|
||||
clearSessionSearchInService: clearSearch
|
||||
}))
|
||||
vi.mock('electron', () => ({
|
||||
ipcMain: {
|
||||
handle: (name: string, handler: (...args: unknown[]) => Promise<unknown>) =>
|
||||
handlers.set(name, handler)
|
||||
},
|
||||
ipcRenderer: { invoke: (name: string, ...args: unknown[]) => handlers.get(name)!(null, ...args) }
|
||||
}))
|
||||
vi.mock('../ssh/ssh', () => ({
|
||||
requestActiveSshSessionSearch: sshSearch,
|
||||
getActiveSshAiVaultHostInfos: sshHostInfos
|
||||
}))
|
||||
|
||||
import { createChildSessionSearchService } from '../../ai-vault-search/session-search-child-service'
|
||||
import { registerAiVaultSearchHandlers } from './ai-vault-search'
|
||||
import { aiVaultApi } from '../../../preload/api/ai-vault/ai-vault-bridge'
|
||||
import { setSessionSearchService } from '../../ai-vault-search/session-search-service-registry'
|
||||
import { fakeSearchService } from '../../../shared/ai-vault/search/ai-vault-search-test-fixture'
|
||||
import { setStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry'
|
||||
beforeEach(() => {
|
||||
handlers.clear()
|
||||
sshSearch.mockReset()
|
||||
sshHostInfos.mockReset()
|
||||
sshHostInfos.mockReturnValue([])
|
||||
runtimeSearch.mockReset()
|
||||
clearSearch.mockReset()
|
||||
registerAiVaultSearchHandlers({
|
||||
callRuntimeSearch: runtimeSearch
|
||||
})
|
||||
})
|
||||
afterEach(() => {
|
||||
setSessionSearchService(null)
|
||||
setStructuredAgentSessionHost(null)
|
||||
})
|
||||
|
||||
describe('desktop IPC and preload search boundary', () => {
|
||||
it('maps a runtime unknown-method refusal to unavailable and keeps transport errors', async () => {
|
||||
runtimeSearch.mockRejectedValue(
|
||||
Object.assign(new Error('unknown method'), { code: 'method_not_found' })
|
||||
)
|
||||
expect(await aiVaultApi.searchSessions({ query: 'needle' }, 'runtime:env-1')).toEqual({
|
||||
kind: 'unavailable',
|
||||
reason: 'no-service'
|
||||
})
|
||||
// Status is the one read where "no such method" must not collapse into "off".
|
||||
await expect(aiVaultApi.searchStatus('runtime:env-1')).rejects.toThrow('host-too-old')
|
||||
runtimeSearch.mockRejectedValue(
|
||||
Object.assign(new Error('runtime disconnected'), { code: 'connection_lost' })
|
||||
)
|
||||
await expect(aiVaultApi.searchSessions({ query: 'needle' }, 'runtime:env-1')).rejects.toThrow(
|
||||
'runtime disconnected'
|
||||
)
|
||||
})
|
||||
|
||||
it('refuses an unroutable host instead of widening it to every host', async () => {
|
||||
const local = fakeSearchService()
|
||||
setSessionSearchService(local)
|
||||
for (const scope of ['nope', 'ssh:', 'runtime:a|b']) {
|
||||
await expect(
|
||||
handlers.get('aiVault:searchSessions')!(null, { query: 'needle' }, scope)
|
||||
).rejects.toThrow('not available for this execution host')
|
||||
await expect(handlers.get('aiVault:searchStatus')!(null, scope)).rejects.toThrow(
|
||||
'not available for this execution host'
|
||||
)
|
||||
}
|
||||
expect(local.search).not.toHaveBeenCalled()
|
||||
expect(local.status).not.toHaveBeenCalled()
|
||||
expect(sshSearch).not.toHaveBeenCalled()
|
||||
expect(runtimeSearch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('maps an unknown-method refusal to host-too-old and keeps every other failure', async () => {
|
||||
runtimeSearch.mockRejectedValue(
|
||||
Object.assign(new Error('Unknown method: aiVault.setSearchEnabled'), { code: -32601 })
|
||||
)
|
||||
await expect(aiVaultApi.setSearchEnabled('runtime:env-1', true)).rejects.toThrow('host-too-old')
|
||||
|
||||
runtimeSearch.mockRejectedValue(Object.assign(new Error('not paired'), { code: 'forbidden' }))
|
||||
await expect(aiVaultApi.setSearchEnabled('runtime:env-1', true)).rejects.toThrow('not paired')
|
||||
})
|
||||
|
||||
it('refuses local, SSH, unroutable hosts and a non-boolean', async () => {
|
||||
await expect(aiVaultApi.setSearchEnabled('local', true)).rejects.toThrow('through Settings')
|
||||
await expect(aiVaultApi.setSearchEnabled('ssh:box', true)).rejects.toThrow('unsupported')
|
||||
await expect(handlers.get('aiVault:setSearchEnabled')!(null, 'nope', true)).rejects.toThrow(
|
||||
'not available for this execution host'
|
||||
)
|
||||
await expect(
|
||||
handlers.get('aiVault:setSearchEnabled')!(null, 'runtime:env-1', 'yes')
|
||||
).rejects.toThrow()
|
||||
expect(runtimeSearch).not.toHaveBeenCalled()
|
||||
expect(sshSearch).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves a child reader failure through registry, IPC and preload', async () => {
|
||||
const service = fakeSearchService()
|
||||
service.search.mockRejectedValue(new Error('reader deadline exceeded'))
|
||||
setSessionSearchService(
|
||||
createChildSessionSearchService({
|
||||
search: service.search,
|
||||
status: service.status,
|
||||
reconcile: service.reconcile
|
||||
})
|
||||
)
|
||||
await expect(aiVaultApi.searchSessions({ query: 'needle' }, 'local')).rejects.toThrow(
|
||||
'reader deadline exceeded'
|
||||
)
|
||||
})
|
||||
@@ -1,173 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { CollectedBundle } from '../observability/bundle'
|
||||
import type * as NodeFs from 'node:fs'
|
||||
|
||||
const handlers = new Map<string, (_event: unknown, ...args: unknown[]) => unknown>()
|
||||
|
||||
const {
|
||||
handleMock,
|
||||
mkdirSyncMock,
|
||||
readFileSyncMock,
|
||||
writeFileSyncMock,
|
||||
showMessageBoxMock,
|
||||
openPathMock,
|
||||
collectDiagnosticBundleMock,
|
||||
deleteDiagnosticBundleMock,
|
||||
getDiagnosticsStatusMock,
|
||||
uploadDiagnosticBundleMock
|
||||
} = vi.hoisted(() => ({
|
||||
handleMock: vi.fn(),
|
||||
mkdirSyncMock: vi.fn(),
|
||||
readFileSyncMock: vi.fn(),
|
||||
writeFileSyncMock: vi.fn(),
|
||||
showMessageBoxMock: vi.fn(),
|
||||
openPathMock: vi.fn(),
|
||||
collectDiagnosticBundleMock: vi.fn(),
|
||||
deleteDiagnosticBundleMock: vi.fn(),
|
||||
getDiagnosticsStatusMock: vi.fn(),
|
||||
uploadDiagnosticBundleMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('node:fs', async () => {
|
||||
const actual = await vi.importActual<typeof NodeFs>('node:fs')
|
||||
return {
|
||||
...actual,
|
||||
mkdirSync: mkdirSyncMock,
|
||||
readFileSync: readFileSyncMock,
|
||||
writeFileSync: writeFileSyncMock
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => '/tmp', getVersion: () => '1.2.3-test' },
|
||||
dialog: { showMessageBox: showMessageBoxMock },
|
||||
ipcMain: { handle: handleMock },
|
||||
shell: { openPath: openPathMock }
|
||||
}))
|
||||
|
||||
vi.mock('../observability', () => ({
|
||||
collectDiagnosticBundle: collectDiagnosticBundleMock,
|
||||
deleteDiagnosticBundle: deleteDiagnosticBundleMock,
|
||||
getDiagnosticsStatus: getDiagnosticsStatusMock,
|
||||
uploadDiagnosticBundle: uploadDiagnosticBundleMock
|
||||
}))
|
||||
|
||||
import { registerDiagnosticsHandlers } from './diagnostics'
|
||||
|
||||
function captureHandlers(): void {
|
||||
handlers.clear()
|
||||
for (const call of handleMock.mock.calls) {
|
||||
const [channel, handler] = call as [
|
||||
string,
|
||||
typeof handlers extends Map<string, infer V> ? V : never
|
||||
]
|
||||
handlers.set(channel, handler)
|
||||
}
|
||||
}
|
||||
|
||||
function makeBundle(overrides: Partial<CollectedBundle> = {}): CollectedBundle {
|
||||
return {
|
||||
bundleSubmissionId: 'abcdefghijklmnopqrstuv',
|
||||
payload: '{"type":"bundle-header"}\n',
|
||||
bytes: 25,
|
||||
spanCount: 0,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('diagnostics IPC handlers', () => {
|
||||
beforeEach(() => {
|
||||
handleMock.mockReset()
|
||||
mkdirSyncMock.mockReset()
|
||||
readFileSyncMock.mockReset()
|
||||
writeFileSyncMock.mockReset()
|
||||
showMessageBoxMock.mockReset()
|
||||
showMessageBoxMock.mockResolvedValue({ response: 0 })
|
||||
openPathMock.mockReset()
|
||||
openPathMock.mockResolvedValue('')
|
||||
collectDiagnosticBundleMock.mockReset()
|
||||
deleteDiagnosticBundleMock.mockReset()
|
||||
getDiagnosticsStatusMock.mockReset()
|
||||
uploadDiagnosticBundleMock.mockReset()
|
||||
delete (globalThis as { ORCA_BUILD_IDENTITY?: unknown }).ORCA_BUILD_IDENTITY
|
||||
delete (globalThis as { ORCA_DIAGNOSTICS_TOKEN_URL?: unknown }).ORCA_DIAGNOSTICS_TOKEN_URL
|
||||
process.env.ORCA_DIAGNOSTICS_TOKEN_URL = 'https://diagnostics.example.com/diagnostics/token'
|
||||
getDiagnosticsStatusMock.mockReturnValue({
|
||||
localFileEnabled: true,
|
||||
bundleEnabled: true,
|
||||
traceFilePath: '/tmp/main.trace.ndjson',
|
||||
traceFamilySize: 0
|
||||
})
|
||||
collectDiagnosticBundleMock.mockReturnValue(makeBundle())
|
||||
readFileSyncMock.mockReturnValue(makeBundle().payload)
|
||||
uploadDiagnosticBundleMock.mockResolvedValue({ ticketId: 'ticketabcdefghijklmnop' })
|
||||
deleteDiagnosticBundleMock.mockResolvedValue(undefined)
|
||||
registerDiagnosticsHandlers()
|
||||
captureHandlers()
|
||||
})
|
||||
|
||||
it('rejects upload without a main-collected bundle preview', async () => {
|
||||
const upload = handlers.get('diagnostics:uploadBundle')!
|
||||
await expect(upload({}, 'rendererMintedBundleId')).rejects.toThrow(/expired/)
|
||||
expect(uploadDiagnosticBundleMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rechecks the retained preview after upload confirmation', async () => {
|
||||
const bundle = makeBundle({ bundleSubmissionId: 'bundleabcdefghijklmnop' })
|
||||
collectDiagnosticBundleMock.mockReturnValue(bundle)
|
||||
const collect = handlers.get('diagnostics:collectBundle')!
|
||||
const openPreview = handlers.get('diagnostics:openBundlePreview')!
|
||||
const discard = handlers.get('diagnostics:discardBundlePreview')!
|
||||
const upload = handlers.get('diagnostics:uploadBundle')!
|
||||
showMessageBoxMock.mockImplementation(async () => {
|
||||
await discard({}, bundle.bundleSubmissionId)
|
||||
return { response: 0 }
|
||||
})
|
||||
|
||||
await collect({}, 30)
|
||||
await openPreview({}, bundle.bundleSubmissionId)
|
||||
await expect(upload({}, bundle.bundleSubmissionId)).rejects.toThrow(/expired/)
|
||||
|
||||
expect(uploadDiagnosticBundleMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requires opening the retained review file before sending', async () => {
|
||||
const bundle = makeBundle({ bundleSubmissionId: 'bundleabcdefghijklmnop' })
|
||||
collectDiagnosticBundleMock.mockReturnValue(bundle)
|
||||
const collect = handlers.get('diagnostics:collectBundle')!
|
||||
const upload = handlers.get('diagnostics:uploadBundle')!
|
||||
|
||||
await collect({}, 30)
|
||||
await expect(upload({}, bundle.bundleSubmissionId)).rejects.toThrow(/open.*review file/)
|
||||
expect(uploadDiagnosticBundleMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('expires retained bundle previews without another diagnostics call', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const bundle = makeBundle({ bundleSubmissionId: 'bundleabcdefghijklmnop' })
|
||||
collectDiagnosticBundleMock.mockReturnValue(bundle)
|
||||
const collect = handlers.get('diagnostics:collectBundle')!
|
||||
const upload = handlers.get('diagnostics:uploadBundle')!
|
||||
|
||||
await collect({}, 30)
|
||||
await vi.advanceTimersByTimeAsync(15 * 60 * 1000 + 1)
|
||||
|
||||
await expect(upload({}, bundle.bundleSubmissionId)).rejects.toThrow(/expired/)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not expose retained bundle payloads through collection IPC', async () => {
|
||||
const bundle = makeBundle({
|
||||
bundleSubmissionId: 'bundleabcdefghijklmnop',
|
||||
payload: '{"secret":"retained in main"}\n'
|
||||
})
|
||||
collectDiagnosticBundleMock.mockReturnValue(bundle)
|
||||
const collect = handlers.get('diagnostics:collectBundle')!
|
||||
|
||||
const preview = await collect({}, 30)
|
||||
expect(JSON.stringify(preview)).not.toContain('retained in main')
|
||||
})
|
||||
})
|
||||
@@ -1,54 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { isENOENT, isPathAbsentError } from './filesystem-path-containment'
|
||||
|
||||
/** Relay JSON-RPC preserves Node ENOENT messages but replaces string codes; remote creation must still recognize expected absence. */
|
||||
describe('isENOENT across the SSH relay boundary', () => {
|
||||
it('recognises an error rebuilt from the relay with a numeric transport code', () => {
|
||||
// Relay response reconstruction preserves the message and replaces the code.
|
||||
const fromRelay = new Error(
|
||||
"ENOENT: no such file or directory, lstat '/home/neil/projects/orca-test1234'"
|
||||
)
|
||||
Object.defineProperty(fromRelay, 'code', { value: -32000 })
|
||||
|
||||
expect(isENOENT(fromRelay), 'a remote missing path must read as absent, not as a failure').toBe(
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
it('recognises it through the IPC wrapper the renderer sees', () => {
|
||||
const throughIpc = new Error(
|
||||
"Error invoking remote method 'worktrees:create': Error: ENOENT: no such file or directory, lstat '/home/neil/projects/orca-test1234-3'"
|
||||
)
|
||||
|
||||
expect(isENOENT(throughIpc)).toBe(true)
|
||||
})
|
||||
|
||||
it('does not treat a different errno as absent', () => {
|
||||
const denied = new Error("EACCES: permission denied, lstat '/root/x'") as NodeJS.ErrnoException
|
||||
denied.code = 'EACCES'
|
||||
|
||||
expect(isENOENT(denied)).toBe(false)
|
||||
})
|
||||
|
||||
it('does not match a message that merely mentions the word', () => {
|
||||
// Match the canonical phrase so unrelated ENOENT mentions cannot bypass collision checks.
|
||||
expect(isENOENT(new Error('fix: handle ENOENT better'))).toBe(false)
|
||||
expect(isENOENT(new Error('branch enoent-handling created'))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isPathAbsentError', () => {
|
||||
it('treats a path under a file as absent, but not a denied one', () => {
|
||||
// Terminal hard-wrap guesses may probe a child under a file (#32128).
|
||||
const underFile = Object.assign(new Error("ENOTDIR: not a directory, stat '/r/a.txt/b.txt'"), {
|
||||
code: 'ENOTDIR'
|
||||
})
|
||||
const denied = Object.assign(new Error("EACCES: permission denied, stat '/root/x'"), {
|
||||
code: 'EACCES'
|
||||
})
|
||||
|
||||
expect(isPathAbsentError(underFile)).toBe(true)
|
||||
expect(isPathAbsentError(denied)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,176 +0,0 @@
|
||||
import { EventEmitter } from 'node:events'
|
||||
import type { ChildProcess } from 'node:child_process'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Store } from '../../persistence/loading-store/store'
|
||||
import type * as GitRunner from '../../git/command-runner/host-routing/wsl-aware-spawn'
|
||||
import type * as BundledRipgrepPath from '../../ripgrep/bundled-ripgrep-path'
|
||||
|
||||
const {
|
||||
bundledRipgrepCommandMock,
|
||||
getLocalGitOptionsForRegisteredWorktreeMock,
|
||||
resolveAuthorizedPathMock,
|
||||
wslAwareSpawnMock
|
||||
} = vi.hoisted(() => ({
|
||||
bundledRipgrepCommandMock: vi.fn(),
|
||||
getLocalGitOptionsForRegisteredWorktreeMock: vi.fn(),
|
||||
resolveAuthorizedPathMock: vi.fn(),
|
||||
wslAwareSpawnMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../git/command-runner/host-routing/wsl-aware-spawn', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof GitRunner>()),
|
||||
wslAwareSpawn: wslAwareSpawnMock
|
||||
}))
|
||||
|
||||
vi.mock('./access/filesystem-auth', () => ({
|
||||
resolveAuthorizedPath: resolveAuthorizedPathMock
|
||||
}))
|
||||
|
||||
vi.mock('../../ripgrep/bundled-ripgrep-path', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof BundledRipgrepPath>()),
|
||||
bundledRipgrepCommand: bundledRipgrepCommandMock
|
||||
}))
|
||||
|
||||
vi.mock('../local-worktree-runtime-options', () => ({
|
||||
getLocalGitOptionsForRegisteredWorktree: getLocalGitOptionsForRegisteredWorktreeMock
|
||||
}))
|
||||
|
||||
import { searchQuickOpenFilePaths } from './filesystem-search-file-paths'
|
||||
|
||||
function createMockProcess(spawned = true): ChildProcess {
|
||||
const child = new EventEmitter() as ChildProcess
|
||||
;(child as unknown as Record<string, unknown>).stdout = new EventEmitter()
|
||||
;(
|
||||
(child as unknown as Record<string, unknown>).stdout as EventEmitter & {
|
||||
setEncoding: () => void
|
||||
}
|
||||
).setEncoding = vi.fn()
|
||||
;(child as unknown as Record<string, unknown>).stderr = new EventEmitter()
|
||||
;(child as unknown as Record<string, unknown>).kill = vi.fn()
|
||||
;(child as unknown as Record<string, unknown>).exitCode = null
|
||||
;(child as unknown as Record<string, unknown>).signalCode = null
|
||||
Object.defineProperty(child, 'pid', { configurable: true, value: spawned ? 1 : undefined })
|
||||
return child
|
||||
}
|
||||
|
||||
const UNUSED_STORE: Store = Object.create(null)
|
||||
|
||||
function createSpawnError(code: string): NodeJS.ErrnoException {
|
||||
return Object.assign(new Error(`spawn rg ${code}`), { code })
|
||||
}
|
||||
|
||||
async function flushMicrotasks(): Promise<void> {
|
||||
for (let index = 0; index < 8; index++) {
|
||||
await Promise.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
describe('searchQuickOpenFilePaths', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resolveAuthorizedPathMock.mockImplementation(async (path) => path)
|
||||
getLocalGitOptionsForRegisteredWorktreeMock.mockReturnValue({})
|
||||
bundledRipgrepCommandMock.mockImplementation((options?: { wsl?: boolean }) =>
|
||||
options?.wsl ? '/bundled/linux/rg' : '/bundled/rg'
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves control characters within ranked paths', async () => {
|
||||
const child = createMockProcess()
|
||||
wslAwareSpawnMock.mockReturnValue(child)
|
||||
const promise = searchQuickOpenFilePaths('/repo', UNUSED_STORE, {
|
||||
query: 'target',
|
||||
limit: 2
|
||||
})
|
||||
await flushMicrotasks()
|
||||
child.stdout?.emit('data', 'first\ntarget.ts\0target.ts\r\0')
|
||||
child.emit('close', 0, null)
|
||||
expect((await promise).paths.sort()).toEqual(['first\ntarget.ts', 'target.ts\r'].sort())
|
||||
})
|
||||
|
||||
it('rejects and stops an oversized path rather than ranking a truncated suffix', async () => {
|
||||
const child = createMockProcess()
|
||||
wslAwareSpawnMock.mockReturnValue(child)
|
||||
const promise = searchQuickOpenFilePaths('/repo', UNUSED_STORE, {
|
||||
query: 'target',
|
||||
limit: 2
|
||||
})
|
||||
await flushMicrotasks()
|
||||
child.stdout?.emit('data', 'x'.repeat(64 * 1024 + 1))
|
||||
await expect(promise).rejects.toThrow('file path exceeds the listing limit')
|
||||
expect(child.kill).toHaveBeenCalledTimes(1)
|
||||
child.stdout?.emit('data', 'target.ts\0')
|
||||
child.emit('close', 0, null)
|
||||
})
|
||||
|
||||
it('finds fuzzy matches after 100k paths without returning excluded worktrees', async () => {
|
||||
const child = createMockProcess()
|
||||
wslAwareSpawnMock.mockReturnValue(child)
|
||||
const promise = searchQuickOpenFilePaths('/repo', {} as Store, {
|
||||
query: 's4354tgt',
|
||||
limit: 2,
|
||||
excludePaths: ['/repo/nested']
|
||||
})
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(wslAwareSpawnMock).toHaveBeenCalledTimes(1)
|
||||
expect(wslAwareSpawnMock.mock.calls[0][0]).toBe('/bundled/rg')
|
||||
expect(wslAwareSpawnMock.mock.calls[0][1]).toContain('--no-ignore-vcs')
|
||||
child.stdout?.emit(
|
||||
'data',
|
||||
`${Array.from({ length: 100_100 }, (_, index) => `data/payload-${index}.bin`).join('\0')}\0`
|
||||
)
|
||||
child.stdout?.emit('data', 'nested/src/sta-4354-target.ts\0src/sta-4354-target.ts\0')
|
||||
child.emit('close', 0, null)
|
||||
|
||||
await expect(promise).resolves.toEqual({
|
||||
paths: ['src/sta-4354-target.ts'],
|
||||
totalCount: 1,
|
||||
truncated: false
|
||||
})
|
||||
})
|
||||
|
||||
it('retries a transient rg spawn failure instead of reporting the bundled rg broken', async () => {
|
||||
const failed = createMockProcess(false)
|
||||
const succeeded = createMockProcess()
|
||||
wslAwareSpawnMock.mockReturnValueOnce(failed).mockReturnValueOnce(succeeded)
|
||||
const promise = searchQuickOpenFilePaths('/repo', {} as Store, {
|
||||
query: 'sta4354gitignored',
|
||||
limit: 32
|
||||
})
|
||||
await flushMicrotasks()
|
||||
|
||||
failed.emit('error', createSpawnError('EAGAIN'))
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(wslAwareSpawnMock).toHaveBeenCalledTimes(2)
|
||||
succeeded.stdout?.emit('data', 'data/chunk-077568/sta-4354-gitignored-target.bin\0')
|
||||
succeeded.emit('close', 0, null)
|
||||
|
||||
await expect(promise).resolves.toEqual({
|
||||
paths: ['data/chunk-077568/sta-4354-gitignored-target.bin'],
|
||||
totalCount: 1,
|
||||
truncated: false
|
||||
})
|
||||
})
|
||||
|
||||
// Model error then negative close so the async cwd check faces the real spawn ordering.
|
||||
|
||||
// Classify WSL cd failure 97 before generic unavailable checks for codes above rg's 0/1/2.
|
||||
|
||||
it('names the unreachable root when the workspace is gone, not the bundled binary', async () => {
|
||||
const child = createMockProcess(false)
|
||||
wslAwareSpawnMock.mockReturnValue(child)
|
||||
resolveAuthorizedPathMock.mockImplementation(async () => '/definitely/not/here')
|
||||
const promise = searchQuickOpenFilePaths('/repo', {} as Store, {
|
||||
query: 'target',
|
||||
limit: 32
|
||||
})
|
||||
await flushMicrotasks()
|
||||
|
||||
child.emit('error', createSpawnError('ENOENT'))
|
||||
child.emit('close', -2, null)
|
||||
|
||||
await expect(promise).rejects.toThrow('Search root is not reachable: /definitely/not/here')
|
||||
})
|
||||
})
|
||||
@@ -1,160 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { handleMock, onMock, removeAllListenersMock, removeHandlerMock, fromWebContentsMock } =
|
||||
vi.hoisted(() => ({
|
||||
handleMock: vi.fn(),
|
||||
onMock: vi.fn(),
|
||||
removeAllListenersMock: vi.fn(),
|
||||
removeHandlerMock: vi.fn(),
|
||||
fromWebContentsMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
BrowserWindow: {
|
||||
fromWebContents: fromWebContentsMock
|
||||
},
|
||||
ipcMain: {
|
||||
handle: handleMock,
|
||||
on: onMock,
|
||||
removeAllListeners: removeAllListenersMock,
|
||||
removeHandler: removeHandlerMock
|
||||
}
|
||||
}))
|
||||
import { registerRuntimeHandlers } from './runtime'
|
||||
import { EphemeralVmFailureError } from '../../shared/remote-runtime/ephemeral-vm-recipes/ephemeral-vm-failure-copy'
|
||||
|
||||
describe('registerRuntimeHandlers', () => {
|
||||
beforeEach(() => {
|
||||
handleMock.mockReset()
|
||||
onMock.mockReset()
|
||||
removeAllListenersMock.mockReset()
|
||||
removeHandlerMock.mockReset()
|
||||
fromWebContentsMock.mockReset()
|
||||
})
|
||||
|
||||
it("passes the orchestration contract fence for the window's own mutations", async () => {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fence answers before any other runtime member is read.
|
||||
registerRuntimeHandlers({ getRuntimeId: () => 'runtime-1' } as never)
|
||||
const registration = handleMock.mock.calls.find(([channel]) => channel === 'runtime:call')
|
||||
const frame = {}
|
||||
const response = await registration, on: vi.fn() } },
|
||||
{
|
||||
method: 'orchestration.approvalAnswer',
|
||||
params: { dispatch: 'ctx_1', prompt: 'apr_1', decision: 'deny', reason: 'no' }
|
||||
}
|
||||
)
|
||||
expect(response.error?.code).not.toBe('orchestration_migration_required')
|
||||
})
|
||||
|
||||
// #36923: the window's wake shares the runtime's one VM wake path with its sleep's suspend.
|
||||
it("routes the window's recipe VM wake through the runtime", async () => {
|
||||
const record = { id: 'vm-1', status: 'running' }
|
||||
const runtime = { wakeWorkspaceVm: vi.fn().mockResolvedValue(record) }
|
||||
|
||||
registerRuntimeHandlers(runtime as never)
|
||||
|
||||
const registration = handleMock.mock.calls.find(
|
||||
([channel]) => channel === 'ephemeralVm:resumeWorkspace'
|
||||
)
|
||||
await expect(registration).resolves.toEqual({
|
||||
ok: true,
|
||||
runtime: record
|
||||
})
|
||||
expect(runtime.wakeWorkspaceVm).toHaveBeenCalledWith('repo::/vm')
|
||||
})
|
||||
|
||||
it('returns coded VM wake and suspend failures as values so the code reaches the window', async () => {
|
||||
const failure = {
|
||||
error: 'Resume exited with code 3.',
|
||||
errorCode: 'resumeExited',
|
||||
errorParams: { exitCode: 3 }
|
||||
}
|
||||
const runtime = {
|
||||
wakeWorkspaceVm: vi.fn().mockRejectedValue(new EphemeralVmFailureError(failure)),
|
||||
suspendWorkspaceVm: vi.fn().mockRejectedValue(new Error('Suspend failed.'))
|
||||
}
|
||||
registerRuntimeHandlers(runtime as never)
|
||||
const handler = (channel: string) =>
|
||||
handleMock.mock.calls.find(([registered]) => registered === channel)![1]
|
||||
|
||||
await expect(
|
||||
handler('ephemeralVm:resumeWorkspace')({}, { workspaceId: 'repo::/vm' })
|
||||
).resolves.toEqual({ ok: false, ...failure })
|
||||
await expect(
|
||||
handler('ephemeralVm:suspendWorkspace')({}, { workspaceId: 'repo::/vm' })
|
||||
).resolves.toEqual({ ok: false, error: 'Suspend failed.' })
|
||||
expect(runtime.suspendWorkspaceVm).toHaveBeenCalledWith('repo::/vm')
|
||||
})
|
||||
|
||||
// #37067: a phone's re-read on the add's reposChanged came before this publish.
|
||||
|
||||
it('rejects a graph publication queued by a superseded main frame', () => {
|
||||
const runtime = {
|
||||
syncWindowGraph: vi.fn(),
|
||||
getStatus: vi.fn(),
|
||||
getRuntimeId: vi.fn()
|
||||
}
|
||||
registerRuntimeHandlers(runtime as never)
|
||||
const handler = handleMock.mock.calls.find(
|
||||
([channel]) => channel === 'runtime:syncWindowGraph'
|
||||
)![1]
|
||||
const sender = { mainFrame: { generation: 2 } }
|
||||
fromWebContentsMock.mockReturnValue({ id: 17 })
|
||||
|
||||
expect(() =>
|
||||
handler({ sender, senderFrame: { generation: 1 } }, { tabs: [], leaves: [] })
|
||||
).toThrow('Runtime graph sync must originate from the current main frame')
|
||||
expect(runtime.syncWindowGraph).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('cancels the GitHub host handler through the existing local subscription boundary', async () => {
|
||||
handleMock.mockClear()
|
||||
onMock.mockClear()
|
||||
const entered = Promise.withResolvers<AbortSignal>()
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The fixture supplies every runtime method reached by this upload subscription.
|
||||
registerRuntimeHandlers({
|
||||
getRuntimeId: () => 'local',
|
||||
uploadGitHubAttachment: (_params: unknown, _bytes: Buffer, signal: AbortSignal) => {
|
||||
entered.resolve(signal)
|
||||
return new Promise((_resolve, reject) =>
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
|
||||
)
|
||||
}
|
||||
} as never)
|
||||
const frame = {}
|
||||
const sender = {
|
||||
mainFrame: frame,
|
||||
id: 14237,
|
||||
once: vi.fn(),
|
||||
on: vi.fn(),
|
||||
send: vi.fn(),
|
||||
isDestroyed: () => false
|
||||
}
|
||||
const event = { senderFrame: frame, sender }
|
||||
const handler = (channel: string) => handleMock.mock.calls.find(([name]) => name === channel)![1]
|
||||
const started = await handler('runtime:call')(event, {
|
||||
method: 'clipboard.startImageUpload',
|
||||
params: { expectedBase64Length: 8, fileName: 'image.png' }
|
||||
})
|
||||
expect(started.ok).toBe(true)
|
||||
await handler('runtime:call')(event, {
|
||||
method: 'clipboard.appendImageUploadChunk',
|
||||
params: { uploadId: started.result.uploadId, offset: 0, contentBase64: 'aW1hZ2U=' }
|
||||
})
|
||||
handler('runtime:subscribe')(event, {
|
||||
subscriptionId: 'image-cancel',
|
||||
method: 'github.uploadAttachment',
|
||||
params: {
|
||||
uploadId: started.result.uploadId,
|
||||
target: { kind: 'repo', repo: 'repo', source: 'origin' },
|
||||
fileName: 'image.png',
|
||||
contentType: 'image/png'
|
||||
}
|
||||
})
|
||||
const signal = await entered.promise
|
||||
const unsubscribe = onMock.mock.calls.find(([name]) => name === 'runtime:unsubscribe')![1]
|
||||
unsubscribe(event, { subscriptionId: 'image-cancel' })
|
||||
expect(signal.aborted).toBe(true)
|
||||
})
|
||||
@@ -1,171 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = await vi.hoisted(async () => {
|
||||
const { createSshIpcMocks } = await import('./ssh-ipc-module-mocks')
|
||||
return createSshIpcMocks()
|
||||
})
|
||||
|
||||
vi.mock('../../ssh/config/ssh-config-host-picker', () => mocks.sshConfigHostPicker)
|
||||
vi.mock('electron', () => mocks.electron)
|
||||
vi.mock('../../ssh/targets/ssh-connection-store', () => mocks.sshConnectionStore)
|
||||
vi.mock('./ssh-host-server-connect', () => mocks.hostServerConnect)
|
||||
vi.mock('../../ssh/connection/ssh-connection-manager', () => mocks.sshConnectionManager)
|
||||
vi.mock('../../ssh/protocol/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer)
|
||||
vi.mock('../../ssh/port-forwarding/ssh-port-forward', () => mocks.sshPortForward)
|
||||
vi.mock('../ssh/ssh-port-scanner', () => mocks.sshPortScanner)
|
||||
|
||||
import type { SshConnectionState, SshTarget } from '../../../shared/remote-runtime/ssh/ssh-types'
|
||||
import { createSshIpcHarness } from './ssh-ipc-test-harness'
|
||||
import { decideHostServer, publishUnservedHostServer } from './ssh-host-server-connect'
|
||||
import {
|
||||
beginSshHostCensus,
|
||||
recordSshConnectionOpened
|
||||
} from '../../ssh/connection/ssh-connection-attribution'
|
||||
import type { SshConnection } from '../../ssh/connection/ssh-connection'
|
||||
import {
|
||||
clearSshHostServerStatus,
|
||||
setSshHostServerStatus
|
||||
} from '../../ssh/host-server/ssh-host-server-status'
|
||||
|
||||
const { mockSshStore, mockConnectionManager } = mocks
|
||||
|
||||
const target: SshTarget = {
|
||||
id: 'ssh-1',
|
||||
label: 'Server',
|
||||
host: 'example.com',
|
||||
port: 22,
|
||||
username: 'deploy'
|
||||
}
|
||||
|
||||
function asTransport(value: { id: string }): SshConnection {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: attribution keys on identity only.
|
||||
return value as unknown as SshConnection
|
||||
}
|
||||
|
||||
describe('SSH IPC handlers', () => {
|
||||
const harness = createSshIpcHarness(mocks)
|
||||
const { handlers, mockWindow } = harness
|
||||
|
||||
beforeEach(harness.reset)
|
||||
|
||||
it('fails a host the managed server does not serve, with no fallback', async () => {
|
||||
const decision = {
|
||||
route: 'unserved' as const,
|
||||
reason: 'orcad_unavailable' as const,
|
||||
detail: 'unsupported_host'
|
||||
}
|
||||
const opened = { id: 'decision-transport' }
|
||||
mockSshStore.getTarget.mockReturnValue(target)
|
||||
vi.mocked(decideHostServer).mockImplementationOnce(async () => {
|
||||
recordSshConnectionOpened(asTransport(opened))
|
||||
mockConnectionManager.getConnection.mockReturnValue(opened)
|
||||
return decision
|
||||
})
|
||||
|
||||
await expect(handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' })).rejects.toThrow(
|
||||
'This SSH host isn’t supported'
|
||||
)
|
||||
expect(publishUnservedHostServer).toHaveBeenCalledWith(target, decision)
|
||||
expect(mockConnectionManager.disconnectConnection).toHaveBeenCalledWith('ssh-1', opened)
|
||||
expect(mockConnectionManager.connect).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('holds a raw connected the server decision causes', async () => {
|
||||
const conn = { hasCachedCredential: () => false }
|
||||
mockSshStore.getTarget.mockReturnValue(target)
|
||||
mockConnectionManager.getConnection.mockReturnValue(conn)
|
||||
let broadcastsDuringDecision: unknown[] = []
|
||||
vi.mocked(decideHostServer).mockImplementationOnce(async () => {
|
||||
await Promise.resolve()
|
||||
const callbacks = mockConnectionManager.callbacksRef.current as {
|
||||
onStateChange: (targetId: string, state: SshConnectionState) => void
|
||||
}
|
||||
callbacks.onStateChange('ssh-1', {
|
||||
targetId: 'ssh-1',
|
||||
status: 'connected',
|
||||
error: null,
|
||||
reconnectAttempt: 0
|
||||
})
|
||||
broadcastsDuringDecision = mockWindow.webContents.send.mock.calls
|
||||
.filter(([channel]) => channel === 'ssh:state-changed')
|
||||
.map(([, payload]) => payload)
|
||||
return { route: 'managed', environmentId: 'env-test' }
|
||||
})
|
||||
|
||||
await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' })
|
||||
expect(broadcastsDuringDecision).not.toContainEqual(
|
||||
expect.objectContaining({ state: expect.objectContaining({ status: 'connected' }) })
|
||||
)
|
||||
expect(broadcastsDuringDecision.at(-1)).toMatchObject({ state: { status: 'connecting' } })
|
||||
})
|
||||
|
||||
it("holds a census's raw 'connected' outside any connect", () => {
|
||||
const end = beginSshHostCensus('ssh-1')
|
||||
try {
|
||||
const callbacks = mockConnectionManager.callbacksRef.current as {
|
||||
onStateChange: (targetId: string, state: SshConnectionState) => void
|
||||
}
|
||||
mockWindow.webContents.send.mockClear()
|
||||
callbacks.onStateChange('ssh-1', {
|
||||
targetId: 'ssh-1',
|
||||
status: 'connected',
|
||||
error: null,
|
||||
reconnectAttempt: 0
|
||||
})
|
||||
expect(mockWindow.webContents.send).toHaveBeenCalledWith(
|
||||
'ssh:state-changed',
|
||||
expect.objectContaining({ state: expect.objectContaining({ status: 'connecting' }) })
|
||||
)
|
||||
} finally {
|
||||
end()
|
||||
}
|
||||
})
|
||||
|
||||
// Tunnel startup can serve a host without an SSH connect, so connect-only restoration left saved forwards off (#32484).
|
||||
it.each([
|
||||
{ kind: 'managed', environmentId: 'env-test' } as const,
|
||||
{ kind: 'relay', reason: 'orcad_unavailable', bridged: true } as const
|
||||
])('restores saved forwards whenever a $kind status is published', async (status) => {
|
||||
const conn = { id: 'conn-1', getConnectGeneration: () => 1 }
|
||||
mockSshStore.getTarget.mockReturnValue({
|
||||
...target,
|
||||
portForwards: [{ localPort: 8080, remoteHost: '127.0.0.1', remotePort: 3000 }]
|
||||
})
|
||||
mockConnectionManager.getConnection.mockReturnValue(conn)
|
||||
clearSshHostServerStatus('ssh-1')
|
||||
try {
|
||||
setSshHostServerStatus('ssh-1', status)
|
||||
await vi.waitFor(() =>
|
||||
expect(mocks.mockPortForwardManager.addForward).toHaveBeenCalledWith(
|
||||
'ssh-1',
|
||||
conn,
|
||||
8080,
|
||||
'127.0.0.1',
|
||||
3000,
|
||||
undefined
|
||||
)
|
||||
)
|
||||
} finally {
|
||||
clearSshHostServerStatus('ssh-1')
|
||||
}
|
||||
})
|
||||
|
||||
it('leaves saved forwards alone while the server decision is unsettled', async () => {
|
||||
mockSshStore.getTarget.mockReturnValue({
|
||||
...target,
|
||||
portForwards: [{ localPort: 8080, remoteHost: '127.0.0.1', remotePort: 3000 }]
|
||||
})
|
||||
mockConnectionManager.getConnection.mockReturnValue({
|
||||
id: 'conn-1',
|
||||
getConnectGeneration: () => 1
|
||||
})
|
||||
try {
|
||||
setSshHostServerStatus('ssh-1', { kind: 'setting-up', phase: 'deploying' })
|
||||
setSshHostServerStatus('ssh-1', { kind: 'relay', reason: 'orcad_unavailable' })
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
expect(mocks.mockPortForwardManager.addForward).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
clearSshHostServerStatus('ssh-1')
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,107 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
clearActiveGitStatusRefBinding,
|
||||
updateActiveGitStatusRefBinding,
|
||||
type GitStatusRefBindingRequest,
|
||||
type GitStatusRefWatchTarget
|
||||
} from './worktree-git-status-ref-watch'
|
||||
|
||||
function makeTarget(): GitStatusRefWatchTarget {
|
||||
return {
|
||||
kind: 'git-common',
|
||||
path: 'C:\\repo\\.git',
|
||||
repos: new Map([['repo-1', { repoId: 'repo-1', repoName: 'repo', nestWorkspaces: false }]]),
|
||||
gitStatusRefPaths: new Set()
|
||||
}
|
||||
}
|
||||
|
||||
describe('worktree git status ref watch binding', () => {
|
||||
afterEach(() => clearActiveGitStatusRefBinding())
|
||||
|
||||
function request(overrides: Partial<GitStatusRefBindingRequest> = {}) {
|
||||
return {
|
||||
worktreeId: 'repo-1::C:\\repo',
|
||||
worktreePath: 'C:\\repo',
|
||||
executionHostId: 'local',
|
||||
branch: 'refs/heads/feature/main',
|
||||
upstreamName: 'origin/feature/main',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
it('binds a custom refspec destination exactly', async () => {
|
||||
const target = makeTarget()
|
||||
await updateActiveGitStatusRefBinding(
|
||||
request(),
|
||||
() => [target],
|
||||
async () => 'refs/custom/origin/main'
|
||||
)
|
||||
|
||||
expect([...target.gitStatusRefPaths]).toEqual(['C:/repo/.git/refs/custom/origin/main'])
|
||||
})
|
||||
|
||||
it('does not spend the dynamic ref stat on a slash-named local upstream', async () => {
|
||||
const target = makeTarget()
|
||||
await updateActiveGitStatusRefBinding(
|
||||
request(),
|
||||
() => [target],
|
||||
async () => 'refs/heads/feature/base'
|
||||
)
|
||||
|
||||
expect(target.gitStatusRefPaths).toEqual(new Set())
|
||||
})
|
||||
|
||||
it('keeps a slash-containing remote name exact', async () => {
|
||||
const target = makeTarget()
|
||||
await updateActiveGitStatusRefBinding(
|
||||
request(),
|
||||
() => [target],
|
||||
async () => 'refs/remotes/team/fork/feature/main'
|
||||
)
|
||||
|
||||
expect([...target.gitStatusRefPaths]).toEqual([
|
||||
'C:/repo/.git/refs/remotes/team/fork/feature/main'
|
||||
])
|
||||
})
|
||||
|
||||
it('does not resolve the exact ref again on unchanged status ticks', async () => {
|
||||
const target = makeTarget()
|
||||
const resolve = vi.fn(async () => 'refs/remotes/origin/feature/main')
|
||||
|
||||
await updateActiveGitStatusRefBinding(request(), () => [target], resolve)
|
||||
await updateActiveGitStatusRefBinding(request(), () => [target], resolve)
|
||||
|
||||
expect(resolve).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('applies an in-flight resolution to a replacement watch', async () => {
|
||||
const first = makeTarget()
|
||||
const replacement = makeTarget()
|
||||
let current = [first]
|
||||
let finish: (ref: string) => void = () => {}
|
||||
const pending = new Promise<string>((resolve) => {
|
||||
finish = resolve
|
||||
})
|
||||
|
||||
const update = updateActiveGitStatusRefBinding(
|
||||
request(),
|
||||
() => current,
|
||||
() => pending
|
||||
)
|
||||
current = [replacement]
|
||||
finish('refs/remotes/origin/feature/main')
|
||||
await update
|
||||
|
||||
expect(first.gitStatusRefPaths).toEqual(new Set())
|
||||
expect([...replacement.gitStatusRefPaths]).toEqual([
|
||||
'C:/repo/.git/refs/remotes/origin/feature/main'
|
||||
])
|
||||
|
||||
const latest = makeTarget()
|
||||
current = [latest]
|
||||
const resolve = vi.fn(async () => 'refs/remotes/origin/feature/main')
|
||||
await updateActiveGitStatusRefBinding(request(), () => current, resolve)
|
||||
expect(resolve).not.toHaveBeenCalled()
|
||||
expect([...latest.gitStatusRefPaths]).toEqual(['C:/repo/.git/refs/remotes/origin/feature/main'])
|
||||
})
|
||||
})
|
||||
@@ -1,152 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Repo } from '../../../../shared/repo-types'
|
||||
import type { GitWorktreeInfo } from '../../../../shared/worktree/types'
|
||||
|
||||
const { listRepoWorktreesMock, pruneLineageMock, pruneMetadataMock, registerWorktreeRootsMock } =
|
||||
vi.hoisted(() => ({
|
||||
listRepoWorktreesMock: vi.fn(),
|
||||
pruneLineageMock: vi.fn(),
|
||||
pruneMetadataMock: vi.fn(),
|
||||
registerWorktreeRootsMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../../workspaces/catalog/repo-worktrees', () => ({
|
||||
listRepoWorktreesForDetectedScan: listRepoWorktreesMock
|
||||
}))
|
||||
vi.mock('../../../workspaces/execution-host/project-runtime-git-options', () => ({
|
||||
getLocalProjectWorktreeGitOptions: () => ({})
|
||||
}))
|
||||
vi.mock('../removal/registered-worktree-roots-cache', () => ({
|
||||
getRegisteredWorktreeRootsRevision: () => 1,
|
||||
registerWorktreeRootsForRepo: registerWorktreeRootsMock
|
||||
}))
|
||||
vi.mock('../../../workspaces/catalog/worktree-lineage-pruning', () => ({
|
||||
pruneLineageForMissingRepoWorktrees: pruneLineageMock
|
||||
}))
|
||||
vi.mock('./authoritative-local-worktree-metadata-pruning', () => ({
|
||||
pruneMetadataMissingFromAuthoritativeLocalScan: pruneMetadataMock
|
||||
}))
|
||||
|
||||
const {
|
||||
DETECTED_WORKTREE_SCAN_CACHE_TTL_MS,
|
||||
__resetDetectedWorktreeScanCacheForTests,
|
||||
applyFreshDetectedWorktreeScanSideEffects,
|
||||
invalidateDetectedWorktreeScanCache,
|
||||
listDetectedGitWorktrees
|
||||
} = await import('./detected-worktree-scan-cache')
|
||||
const { setWorktreeCatalogRouteResolver } =
|
||||
await import('../../../workspaces/catalog/repo-worktree-catalog-route')
|
||||
const { invalidateLocalWorktreeMetadataPruneInputs } =
|
||||
await import('../../../workspaces/catalog/local-worktree-metadata-prune-gate')
|
||||
|
||||
const repo = { id: 'repo-1', path: '/repos/one', displayName: 'one' } as Repo
|
||||
|
||||
function worktreeAt(path: string): GitWorktreeInfo {
|
||||
return { path, head: 'abc', branch: 'main', isBare: false, isMainWorktree: path === repo.path }
|
||||
}
|
||||
|
||||
const captureExpectation = vi.fn(() => ({ repo: { id: repo.id }, metadata: [] }))
|
||||
const store = { captureNativeLocalWorktreeMetadataScanExpectation: captureExpectation } as never
|
||||
|
||||
function advancePastListingTtl(): void {
|
||||
vi.setSystemTime(Date.now() + DETECTED_WORKTREE_SCAN_CACHE_TTL_MS + 1)
|
||||
}
|
||||
|
||||
describe('detected worktree scan hygiene gate', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(1_000_000)
|
||||
listRepoWorktreesMock.mockReset().mockResolvedValue([worktreeAt(repo.path)])
|
||||
captureExpectation.mockClear()
|
||||
pruneLineageMock.mockReset()
|
||||
pruneMetadataMock
|
||||
.mockReset()
|
||||
.mockResolvedValue({ scanGenerationCurrent: true, preservedMetadataCandidateIds: new Set() })
|
||||
registerWorktreeRootsMock.mockReset()
|
||||
__resetDetectedWorktreeScanCacheForTests()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('runs hygiene once and then never again while nothing changes', async () => {
|
||||
const first = await listDetectedGitWorktrees(store, repo)
|
||||
expect(first.hygieneDue).toBe(true)
|
||||
expect(first.metadataPrune).toBeDefined()
|
||||
|
||||
for (let poll = 0; poll < 20; poll += 1) {
|
||||
advancePastListingTtl()
|
||||
const scan = await listDetectedGitWorktrees(store, repo)
|
||||
expect(scan.fresh).toBe(true)
|
||||
expect(scan.hygieneDue).toBe(false)
|
||||
expect(scan.metadataPrune).toBeUndefined()
|
||||
}
|
||||
expect(captureExpectation).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('re-runs hygiene after a worktree lifecycle event', async () => {
|
||||
await listDetectedGitWorktrees(store, repo)
|
||||
invalidateDetectedWorktreeScanCache(repo.id)
|
||||
|
||||
expect((await listDetectedGitWorktrees(store, repo)).hygieneDue).toBe(true)
|
||||
expect(captureExpectation).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('re-runs hygiene when ownership state may have released a row', async () => {
|
||||
await listDetectedGitWorktrees(store, repo)
|
||||
advancePastListingTtl()
|
||||
expect((await listDetectedGitWorktrees(store, repo)).hygieneDue).toBe(false)
|
||||
|
||||
invalidateLocalWorktreeMetadataPruneInputs()
|
||||
|
||||
advancePastListingTtl()
|
||||
expect((await listDetectedGitWorktrees(store, repo)).hygieneDue).toBe(true)
|
||||
expect(captureExpectation).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('re-runs hygiene when the listing changes with no event to report it', async () => {
|
||||
await listDetectedGitWorktrees(store, repo)
|
||||
advancePastListingTtl()
|
||||
expect((await listDetectedGitWorktrees(store, repo)).hygieneDue).toBe(false)
|
||||
|
||||
// Model an external removal with no change notification.
|
||||
listRepoWorktreesMock.mockResolvedValue([worktreeAt(repo.path), worktreeAt('/repos/one-wt')])
|
||||
advancePastListingTtl()
|
||||
await listDetectedGitWorktrees(store, repo)
|
||||
|
||||
advancePastListingTtl()
|
||||
expect((await listDetectedGitWorktrees(store, repo)).hygieneDue).toBe(true)
|
||||
})
|
||||
|
||||
it('stops deleting once the owner retires the route during the prune helper', async () => {
|
||||
let live = true
|
||||
setWorktreeCatalogRouteResolver(() =>
|
||||
live ? { repoPath: repo.path, runtimeKey: 'local:default' } : null
|
||||
)
|
||||
try {
|
||||
const scan = await listDetectedGitWorktrees(store, repo)
|
||||
let helperSawCurrent: boolean | undefined
|
||||
pruneMetadataMock.mockImplementation(async (args: { isCallerCurrent: () => boolean }) => {
|
||||
live = false
|
||||
helperSawCurrent = args.isCallerCurrent()
|
||||
return { scanGenerationCurrent: true, preservedMetadataCandidateIds: new Set() }
|
||||
})
|
||||
|
||||
const applied = await applyFreshDetectedWorktreeScanSideEffects(
|
||||
store,
|
||||
repo,
|
||||
scan.gitWorktrees,
|
||||
scan.metadataPrune,
|
||||
{ sideEffectToken: scan.sideEffectToken, hygieneDue: scan.hygieneDue }
|
||||
)
|
||||
|
||||
expect(helperSawCurrent).toBe(false)
|
||||
expect(applied).toBe(false)
|
||||
expect(pruneLineageMock).not.toHaveBeenCalled()
|
||||
expect(scan.authorityCurrent?.()).toBe(false)
|
||||
} finally {
|
||||
setWorktreeCatalogRouteResolver(null)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,141 +0,0 @@
|
||||
import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof ExecCommandModule>()),
|
||||
execCommand: vi.fn()
|
||||
}))
|
||||
|
||||
import { execCommand } from '../../ssh/remote-exec/remote-exec-command'
|
||||
import { acquireInstallLock, isRelayInstallLockStale } from './remote-install-lock'
|
||||
import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform'
|
||||
import { unusedSshConnection } from '../testing/managed-host-transport.test-fixture'
|
||||
|
||||
const conn = unusedSshConnection()
|
||||
const mockExec = vi.mocked(execCommand)
|
||||
const nextAcquisition = ['OPEN', '', 'OK', 'OPEN']
|
||||
|
||||
const lockFailureStages = [
|
||||
{
|
||||
stage: 'claim probe after acquisition',
|
||||
replies: ['OPEN', '', 'OK'],
|
||||
recovery: ['', 'OK', 'OPEN']
|
||||
},
|
||||
{
|
||||
stage: 'release after acquisition',
|
||||
replies: ['OPEN', '', 'OK', 'LOCKED'],
|
||||
recovery: ['OK', 'OPEN']
|
||||
},
|
||||
{
|
||||
stage: 'stale lock takeover',
|
||||
replies: ['OPEN', '', 'BUSY'],
|
||||
recovery: nextAcquisition
|
||||
},
|
||||
{
|
||||
stage: 'claim probe after stale takeover',
|
||||
replies: ['OPEN', '', 'BUSY', 'OK'],
|
||||
recovery: ['', ...nextAcquisition]
|
||||
},
|
||||
{
|
||||
stage: 'release after stale takeover',
|
||||
replies: ['OPEN', '', 'BUSY', 'OK', 'LOCKED'],
|
||||
recovery: nextAcquisition
|
||||
}
|
||||
]
|
||||
|
||||
beforeEach(() => {
|
||||
mockExec.mockReset()
|
||||
mockExec.mockResolvedValue('OPEN')
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
vi.spyOn(console, 'info').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe.each([
|
||||
{ platform: 'linux-x64' as const, remoteDir: '/relay/version' },
|
||||
{ platform: 'win32-x64' as const, remoteDir: 'C:/relay/version' }
|
||||
])('install lock termination on $platform', ({ platform, remoteDir }) => {
|
||||
const host = getRemoteHostPlatform(platform)
|
||||
|
||||
it.each(lockFailureStages)('stops after unconfirmed $stage', async ({ replies }) => {
|
||||
const error = Object.assign(new Error('SSH teardown not confirmed'), {
|
||||
sshChannelCloseConfirmed: false
|
||||
})
|
||||
for (const reply of replies) {
|
||||
mockExec.mockResolvedValueOnce(reply)
|
||||
}
|
||||
mockExec.mockRejectedValueOnce(error)
|
||||
|
||||
await expect(acquireInstallLock(conn, remoteDir, host)).rejects.toBe(error)
|
||||
expect(mockExec).toHaveBeenCalledTimes(replies.length + 1)
|
||||
})
|
||||
|
||||
it.each(lockFailureStages)(
|
||||
'keeps recovery after confirmed $stage failure',
|
||||
async ({ replies, recovery }) => {
|
||||
vi.useFakeTimers()
|
||||
for (const reply of replies) {
|
||||
mockExec.mockResolvedValueOnce(reply)
|
||||
}
|
||||
mockExec.mockRejectedValueOnce(
|
||||
Object.assign(new Error('SSH command failed after closing'), {
|
||||
sshChannelCloseConfirmed: true
|
||||
})
|
||||
)
|
||||
for (const reply of recovery) {
|
||||
mockExec.mockResolvedValueOnce(reply)
|
||||
}
|
||||
|
||||
const acquiring = acquireInstallLock(conn, remoteDir, host)
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
|
||||
await expect(acquiring).resolves.toBeUndefined()
|
||||
expect(mockExec).toHaveBeenCalledTimes(replies.length + recovery.length + 1)
|
||||
}
|
||||
)
|
||||
|
||||
it('preserves takeover uncertainty when the caller also aborts', async () => {
|
||||
const controller = new AbortController()
|
||||
const error = Object.assign(new Error('SSH teardown not confirmed'), {
|
||||
sshChannelCloseConfirmed: false
|
||||
})
|
||||
mockExec
|
||||
.mockResolvedValueOnce('OPEN')
|
||||
.mockResolvedValueOnce('')
|
||||
.mockResolvedValueOnce('BUSY')
|
||||
.mockImplementationOnce(async () => {
|
||||
controller.abort(new Error('deploy aborted'))
|
||||
throw error
|
||||
})
|
||||
|
||||
await expect(
|
||||
acquireInstallLock(conn, remoteDir, host, { signal: controller.signal })
|
||||
).rejects.toBe(error)
|
||||
expect(mockExec).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('preserves uncertainty from the stale lock age probe', async () => {
|
||||
const error = Object.assign(new Error('SSH teardown not confirmed'), {
|
||||
sshChannelCloseConfirmed: false
|
||||
})
|
||||
mockExec.mockRejectedValueOnce(error)
|
||||
|
||||
await expect(isRelayInstallLockStale(conn, remoteDir, host)).rejects.toBe(error)
|
||||
expect(mockExec).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps a confirmed stale age probe failure as not stale', async () => {
|
||||
mockExec.mockRejectedValueOnce(
|
||||
Object.assign(new Error('SSH command failed after closing'), {
|
||||
sshChannelCloseConfirmed: true
|
||||
})
|
||||
)
|
||||
|
||||
await expect(isRelayInstallLockStale(conn, remoteDir, host)).resolves.toBe(false)
|
||||
expect(mockExec).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -1,158 +0,0 @@
|
||||
import { rmSync } from 'node:fs'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { getManagedOrcadFenceEnvironmentId } from '../../../shared/remote-runtime/ssh/managed-orcad-ssh-owner'
|
||||
import { listEnvironments } from '../../../shared/remote-runtime/host-store/runtime-environment-store'
|
||||
import {
|
||||
listOrcadMigrationSourceCutovers,
|
||||
writeOrcadMigrationSourceCutover
|
||||
} from '../../persistence/migrating-orcad-catalog/cutover-journals/orcad-migration-cutover-journal'
|
||||
import { orcadMigrationCutoverFixture } from '../migration/cutover/testing/orcad-migration-cutover-fixture'
|
||||
import { createManagedLifecycleHarness } from './orcad-managed-lifecycle-test-fixture'
|
||||
import { isManagedOrcadSshTarget } from '../../ssh/targets/ssh-target-runtime-ownership'
|
||||
import { addManagedOrcadEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store'
|
||||
import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing'
|
||||
import { PAIRING_OFFER_VERSION } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer'
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const state: { store: unknown } = { store: null }
|
||||
return {
|
||||
state,
|
||||
connect: vi.fn(),
|
||||
resolveContext: vi.fn(),
|
||||
closeTunnel: vi.fn(),
|
||||
retire: vi.fn(),
|
||||
releaseHost: vi.fn()
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../ssh/targets/ssh-target-registry', () => ({
|
||||
getSshConnectionManager: () => ({ connect: mocks.connect }),
|
||||
getSshTargetRegistryStore: () => mocks.state.store
|
||||
}))
|
||||
vi.mock('../install/orcad-remote-context', () => ({
|
||||
resolveOrcadRemoteContext: mocks.resolveContext
|
||||
}))
|
||||
vi.mock('./orcad-managed-tunnel', () => ({
|
||||
closeOrcadManagedTunnel: mocks.closeTunnel,
|
||||
ensureOrcadManagedTunnel: vi.fn()
|
||||
}))
|
||||
|
||||
const {
|
||||
forgetManagedOrcadEnvironment,
|
||||
forgetRedundantManagedOrcadEnvironment,
|
||||
stopManagedOrcadEnvironment
|
||||
} = await import('./orcad-runtime-decommission')
|
||||
|
||||
let harness: ReturnType<typeof createManagedLifecycleHarness>
|
||||
|
||||
const policy = (isActive = false) => ({
|
||||
isActiveEnvironment: () => isActive,
|
||||
retireLocalState: mocks.retire,
|
||||
releaseHostTransport: mocks.releaseHost
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
harness = createManagedLifecycleHarness()
|
||||
mocks.state.store = harness.targetStore
|
||||
mocks.connect.mockRejectedValue(new Error('connect ECONNREFUSED 127.0.0.1:2841'))
|
||||
mocks.resolveContext.mockRejectedValue(new Error('connect ECONNREFUSED 127.0.0.1:2841'))
|
||||
})
|
||||
|
||||
afterEach(() => rmSync(harness.userDataPath, { recursive: true, force: true }))
|
||||
|
||||
describe('a managed server whose host is gone (P1-E)', () => {
|
||||
it('cannot be stopped, since the host can never prove orcad exited', async () => {
|
||||
await expect(
|
||||
stopManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }, policy())
|
||||
).rejects.toThrow('ECONNREFUSED')
|
||||
expect(listEnvironments(harness.userDataPath)).toHaveLength(1)
|
||||
expect(isManagedOrcadSshTarget(harness.current())).toBe(true)
|
||||
})
|
||||
|
||||
it('is forgotten locally without contacting the host, which frees its SSH target', async () => {
|
||||
writeOrcadMigrationSourceCutover(harness.userDataPath, {
|
||||
...orcadMigrationCutoverFixture('migration-1', 'ssh-1', { environmentId: 'environment-1' }),
|
||||
phase: 'destination-committed',
|
||||
sourceRetainedAt: '2026-10-01T00:00:00.000Z'
|
||||
})
|
||||
await expect(
|
||||
forgetManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }, policy())
|
||||
).resolves.toEqual({
|
||||
outcome: 'forgotten',
|
||||
// No host observation means local forgetting cannot report proven exit.
|
||||
verdict: 'unverifiable',
|
||||
environmentId: 'environment-1',
|
||||
sshTargetId: 'ssh-1'
|
||||
})
|
||||
expect(mocks.connect).not.toHaveBeenCalled()
|
||||
expect(mocks.resolveContext).not.toHaveBeenCalled()
|
||||
expect(listEnvironments(harness.userDataPath)).toEqual([])
|
||||
expect(getManagedOrcadFenceEnvironmentId(harness.current())).toBeNull()
|
||||
expect(isManagedOrcadSshTarget(harness.current())).toBe(false)
|
||||
expect(harness.flushes).toHaveLength(1)
|
||||
expect(mocks.retire).toHaveBeenCalledWith('environment-1')
|
||||
expect(mocks.closeTunnel).toHaveBeenCalledWith('environment-1')
|
||||
// An unserved host never stays connected, so Set location can't offer it (#37767).
|
||||
expect(mocks.releaseHost).toHaveBeenCalledWith('ssh-1')
|
||||
expect(listOrcadMigrationSourceCutovers(harness.userDataPath)).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses to forget the Active Server and keeps every link', async () => {
|
||||
await expect(
|
||||
forgetManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }, policy(true))
|
||||
).resolves.toMatchObject({ outcome: 'refused', code: 'orcad_forget_active_environment' })
|
||||
expect(listEnvironments(harness.userDataPath)).toHaveLength(1)
|
||||
expect(getManagedOrcadFenceEnvironmentId(harness.current())).toBe('environment-1')
|
||||
expect(mocks.retire).not.toHaveBeenCalled()
|
||||
expect(mocks.closeTunnel).not.toHaveBeenCalled()
|
||||
expect(mocks.releaseHost).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('a managed server saved under a second SSH alias', () => {
|
||||
// Same host key in its padded spelling, reached through its own SSH target.
|
||||
const addTwin = () =>
|
||||
addManagedOrcadEnvironment(harness.userDataPath, {
|
||||
id: 'environment-2',
|
||||
name: 'Managed alias',
|
||||
pairingCode: encodePairingOffer({
|
||||
v: PAIRING_OFFER_VERSION,
|
||||
endpoint: 'ws://127.0.0.1:46769/',
|
||||
deviceToken: 'alias-device-token',
|
||||
publicKeyB64: 'public-key='
|
||||
}),
|
||||
orcadDeployment: {
|
||||
sshTargetId: 'ssh-2',
|
||||
sshTargetGeneration: 1,
|
||||
localPort: 46_769,
|
||||
remotePort: 6_768
|
||||
}
|
||||
})
|
||||
|
||||
it('forgets the redundant entry and leaves the other one managing the server', async () => {
|
||||
addTwin()
|
||||
await expect(
|
||||
forgetRedundantManagedOrcadEnvironment(
|
||||
harness.userDataPath,
|
||||
{ selector: 'Managed' },
|
||||
policy()
|
||||
)
|
||||
).resolves.toMatchObject({ outcome: 'forgotten', environmentId: 'environment-1' })
|
||||
expect(mocks.connect).not.toHaveBeenCalled()
|
||||
expect(listEnvironments(harness.userDataPath).map(({ id }) => id)).toEqual(['environment-2'])
|
||||
})
|
||||
|
||||
it('refuses when the other entry is gone by the time the removal runs', async () => {
|
||||
await expect(
|
||||
forgetRedundantManagedOrcadEnvironment(
|
||||
harness.userDataPath,
|
||||
{ selector: 'Managed' },
|
||||
policy()
|
||||
)
|
||||
).resolves.toMatchObject({ outcome: 'refused', code: 'orcad_forget_no_managed_twin' })
|
||||
expect(listEnvironments(harness.userDataPath)).toHaveLength(1)
|
||||
expect(getManagedOrcadFenceEnvironmentId(harness.current())).toBe('environment-1')
|
||||
expect(mocks.closeTunnel).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,163 +0,0 @@
|
||||
// Refused events must consume no keys, rows or admission budget.
|
||||
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { parseAgentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import {
|
||||
backgroundTask,
|
||||
closeProviderTimelineRigs,
|
||||
messageText,
|
||||
openProviderTimelineRig,
|
||||
pendingApproval,
|
||||
providerItemId,
|
||||
providerTurnItemId,
|
||||
refusingSink
|
||||
} from './provider-timeline-assembler-test-support'
|
||||
|
||||
afterEach(closeProviderTimelineRigs)
|
||||
|
||||
const messages = async (rig: Awaited<ReturnType<typeof openProviderTimelineRig>>) =>
|
||||
(await rig.rows()).filter((row) => row.body.kind === 'message')
|
||||
|
||||
describe('a refused event takes nothing', () => {
|
||||
it('allocates no key and no request row, and its retry lands once', async () => {
|
||||
const rig = await openProviderTimelineRig()
|
||||
let refusing = false
|
||||
const assembler = rig.assemble({ sink: refusingSink(rig.sink, () => refusing) })
|
||||
const refused = { accepted: false, reason: 'backpressure' }
|
||||
const turnOpen = { type: 'turn.open', at: 1_000 } as const
|
||||
const frame = { type: 'provider.frame', frameKind: 'mystery', payload: { a: 1 } } as const
|
||||
const request = { type: 'request.open', request: 'p1', body: pendingApproval } as const
|
||||
refusing = true
|
||||
expect(assembler.apply(turnOpen).admission).toEqual(refused)
|
||||
expect(assembler.openTurnId).toBeNull()
|
||||
refusing = false
|
||||
expect(assembler.apply(turnOpen).admission).toEqual({ accepted: true })
|
||||
expect(assembler.openTurnId).toBe('m:gen-1%3At1')
|
||||
refusing = true
|
||||
expect(assembler.apply(frame).admission).toEqual(refused)
|
||||
expect(assembler.apply(request).admission).toEqual(refused)
|
||||
refusing = false
|
||||
expect(assembler.apply(frame).admission).toEqual({ accepted: true })
|
||||
expect(assembler.apply(request).admission).toEqual({ accepted: true })
|
||||
assembler.apply({
|
||||
type: 'text.delta',
|
||||
item: { stream: 'reply' },
|
||||
channel: 'assistant',
|
||||
text: 'Hi'
|
||||
})
|
||||
assembler.flush()
|
||||
|
||||
const rows = (await rig.rows()).filter((row) => row.body.kind !== 'turn')
|
||||
expect(rows.map((row) => row.itemId)).toEqual([
|
||||
expect.stringContaining('frame%3Am%3Agen-1%253Af2'),
|
||||
providerItemId('request', 'p1'),
|
||||
expect.stringContaining('item%3Am%3Agen-1%253As3')
|
||||
])
|
||||
expect(messageText(rows[2]?.body)).toBe('Hi')
|
||||
})
|
||||
})
|
||||
|
||||
describe('a row keeps the turn it opened in', () => {
|
||||
it('takes a background task update in the turn it opened in, after that turn ended', async () => {
|
||||
const rig = await openProviderTimelineRig()
|
||||
rig.assembler.apply({ type: 'turn.open', turn: 't1', at: 1_000 })
|
||||
rig.assembler.apply({
|
||||
type: 'item.open',
|
||||
item: 'background-tool',
|
||||
body: backgroundTask('background-tool', 'working')
|
||||
})
|
||||
rig.assembler.apply({ type: 'turn.end', turn: 't1', at: 2_000, state: 'completed' })
|
||||
// Completed turns still own later updates to their existing rows.
|
||||
rig.assembler.apply({
|
||||
type: 'item.update',
|
||||
item: 'background-tool',
|
||||
body: backgroundTask('background-tool', 'done')
|
||||
})
|
||||
expect(await rig.row(providerItemId('item', 'background-tool'))).toMatchObject({
|
||||
turnScope: { kind: 'turn', turnItemId: providerTurnItemId('t1') },
|
||||
body: backgroundTask('background-tool', 'done')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('streamed text has the same lifecycle as the item it streams into', () => {
|
||||
it('keeps interleaved same-id streams on separate threads apart', async () => {
|
||||
const rig = await openProviderTimelineRig({ ownThread: () => 'root' })
|
||||
rig.assembler.apply({ type: 'turn.open', turn: 't1', at: 1_000 })
|
||||
rig.assembler.apply({
|
||||
type: 'text.delta',
|
||||
item: { id: 'm1' },
|
||||
channel: 'assistant',
|
||||
text: 'Root',
|
||||
join: { thread: 'root', turn: 't1' }
|
||||
})
|
||||
rig.assembler.apply({
|
||||
type: 'text.delta',
|
||||
item: { id: 'm1' },
|
||||
channel: 'assistant',
|
||||
text: 'Child',
|
||||
join: { thread: 'child', turn: 'child-turn' }
|
||||
})
|
||||
rig.assembler.apply({ type: 'turn.end', turn: 't1', at: 2_000, state: 'completed' })
|
||||
|
||||
expect((await messages(rig)).map((row) => [row.itemId, messageText(row.body)])).toEqual([
|
||||
[providerItemId('item', 'm1', { thread: 'root' }), 'Root'],
|
||||
[providerItemId('item', 'm1', { thread: 'child' }), 'Child']
|
||||
])
|
||||
})
|
||||
|
||||
it('settles a message on text.close, so a late delta cannot erase what it said', async () => {
|
||||
const rig = await openProviderTimelineRig()
|
||||
rig.assembler.apply({
|
||||
type: 'text.delta',
|
||||
item: { id: 'm1' },
|
||||
channel: 'assistant',
|
||||
text: 'Prefix'
|
||||
})
|
||||
rig.assembler.apply({ type: 'text.close', item: { id: 'm1' } })
|
||||
expect(
|
||||
rig.assembler.apply({
|
||||
type: 'text.delta',
|
||||
item: { id: 'm1' },
|
||||
channel: 'assistant',
|
||||
text: 'Suffix'
|
||||
}).dropped
|
||||
).toBe('item-settled')
|
||||
rig.assembler.flush()
|
||||
|
||||
expect(messageText((await rig.row(providerItemId('item', 'm1')))?.body)).toBe('Prefix')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the budget counts the work actually open', () => {
|
||||
it('frees an answered request incarnation without waiting for its turn to end', async () => {
|
||||
const rig = await openProviderTimelineRig()
|
||||
rig.assembler.apply({ type: 'turn.open', turn: 't1', at: 1_000 })
|
||||
for (let incarnation = 1; incarnation <= 129; incarnation += 1) {
|
||||
expect(
|
||||
rig.assembler.apply({ type: 'request.open', request: 'approval', body: pendingApproval })
|
||||
.admission
|
||||
).toEqual({ accepted: true })
|
||||
await rig.rows()
|
||||
const identity = parseAgentJournalItemKey(
|
||||
providerItemId('request', 'approval', { incarnation })
|
||||
)
|
||||
if (!identity) {
|
||||
throw new Error('the request has a journal key')
|
||||
}
|
||||
await rig.journal.appendItem(
|
||||
identity,
|
||||
{
|
||||
...pendingApproval,
|
||||
resolution: {
|
||||
state: 'resolved',
|
||||
selectedOptionId: 'allow',
|
||||
resolvedBy: 'phone',
|
||||
resolvedAt: 1_100
|
||||
}
|
||||
},
|
||||
{ fence: 1, turnScope: { kind: 'turn', turnItemId: providerTurnItemId('t1') } }
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,89 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { ActiveViewPreference, getActiveViewPreferenceFile } from './active-view-preference'
|
||||
|
||||
describe('ActiveViewPreference', () => {
|
||||
let dir: string
|
||||
let dataFile: string
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'orca-active-view-'))
|
||||
dataFile = join(dir, 'orca-data.json')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('migrates the legacy durable-state value into the profile sidecar', async () => {
|
||||
vi.useFakeTimers()
|
||||
const preference = new ActiveViewPreference(dataFile, 'tasks')
|
||||
|
||||
expect(preference.get()).toBe('tasks')
|
||||
expect(existsSync(getActiveViewPreferenceFile(dataFile))).toBe(false)
|
||||
|
||||
expect(preference.set('tasks')).toBe(false)
|
||||
vi.advanceTimersByTime(100)
|
||||
await preference.waitForPendingWrite()
|
||||
|
||||
expect(JSON.parse(readFileSync(getActiveViewPreferenceFile(dataFile), 'utf-8'))).toEqual({
|
||||
activeView: 'tasks'
|
||||
})
|
||||
})
|
||||
|
||||
it('coalesces rapid switches into one tiny preference write', async () => {
|
||||
vi.useFakeTimers()
|
||||
const preference = new ActiveViewPreference(dataFile, 'terminal')
|
||||
|
||||
preference.set('settings')
|
||||
vi.advanceTimersByTime(50)
|
||||
preference.set('automations')
|
||||
vi.advanceTimersByTime(50)
|
||||
expect(existsSync(getActiveViewPreferenceFile(dataFile))).toBe(false)
|
||||
|
||||
vi.advanceTimersByTime(50)
|
||||
await preference.waitForPendingWrite()
|
||||
|
||||
expect(JSON.parse(readFileSync(getActiveViewPreferenceFile(dataFile), 'utf-8'))).toEqual({
|
||||
activeView: 'automations'
|
||||
})
|
||||
})
|
||||
|
||||
it('flushes synchronously for an immediate graceful exit', () => {
|
||||
vi.useFakeTimers()
|
||||
const preference = new ActiveViewPreference(dataFile, 'terminal')
|
||||
|
||||
preference.set('settings')
|
||||
preference.flushOrThrow()
|
||||
|
||||
expect(JSON.parse(readFileSync(getActiveViewPreferenceFile(dataFile), 'utf-8'))).toEqual({
|
||||
activeView: 'settings'
|
||||
})
|
||||
vi.advanceTimersByTime(100)
|
||||
expect(JSON.parse(readFileSync(getActiveViewPreferenceFile(dataFile), 'utf-8'))).toEqual({
|
||||
activeView: 'settings'
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores an invalid sidecar and invalid updates', () => {
|
||||
writeFileSync(getActiveViewPreferenceFile(dataFile), '{"activeView":"unknown"}', 'utf-8')
|
||||
const preference = new ActiveViewPreference(dataFile, 'not-a-view')
|
||||
|
||||
expect(preference.get()).toBe('terminal')
|
||||
expect(preference.set('also-not-a-view')).toBe(false)
|
||||
expect(preference.get()).toBe('terminal')
|
||||
})
|
||||
|
||||
it('rejects inherited object keys from a corrupt sidecar', () => {
|
||||
// Inherited keys pass `in` checks but are invalid views.
|
||||
writeFileSync(getActiveViewPreferenceFile(dataFile), '{"activeView":"constructor"}', 'utf-8')
|
||||
const preference = new ActiveViewPreference(dataFile, 'tasks')
|
||||
|
||||
expect(preference.get()).toBe('tasks')
|
||||
expect(preference.set('__proto__')).toBe(false)
|
||||
expect(preference.get()).toBe('tasks')
|
||||
})
|
||||
})
|
||||
@@ -1,58 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getDefaultWorkspaceSession } from '../../../shared/constants'
|
||||
import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types'
|
||||
|
||||
import { collectWorkspaceSessionWorktreeOwners } from './session-worktree-ownership'
|
||||
|
||||
function sessionWith(field: keyof WorkspaceSessionState, value: unknown): WorkspaceSessionState {
|
||||
return { ...getDefaultWorkspaceSession(), [field]: value } as WorkspaceSessionState
|
||||
}
|
||||
|
||||
describe('workspace session worktree ownership', () => {
|
||||
it('prefers an exact candidate id over workspace-key prefix parsing', () => {
|
||||
const prefixedId = 'folder::/workspace/target'
|
||||
const session = sessionWith('tabsByWorktree', { [prefixedId]: [] })
|
||||
|
||||
expect([...collectWorkspaceSessionWorktreeOwners(session, new Set([prefixedId]))]).toEqual([
|
||||
prefixedId
|
||||
])
|
||||
})
|
||||
|
||||
it('matches canonically equivalent Unicode worktree owners', () => {
|
||||
const candidateId = 'repo-1::/workspace/Café'.normalize('NFC')
|
||||
const ownerId = candidateId.normalize('NFD')
|
||||
const session = sessionWith('activeWorktreeId', ownerId)
|
||||
|
||||
expect([...collectWorkspaceSessionWorktreeOwners(session, new Set([candidateId]))]).toEqual([
|
||||
candidateId
|
||||
])
|
||||
})
|
||||
|
||||
it('matches Windows worktree owners across drive case and slash spelling', () => {
|
||||
const candidateId = 'repo-1::D:/Agentic/game2'
|
||||
const session = sessionWith('activeWorktreeId', 'repo-1::d:\\agentic\\game2')
|
||||
|
||||
expect([...collectWorkspaceSessionWorktreeOwners(session, new Set([candidateId]))]).toEqual([
|
||||
candidateId
|
||||
])
|
||||
})
|
||||
|
||||
it('matches macOS /private/tmp session owners to /tmp metadata', () => {
|
||||
const candidateId = 'repo-1::/private/tmp/orca/target'
|
||||
const session = sessionWith('activeWorktreeId', 'repo-1::/tmp/orca/target')
|
||||
|
||||
expect([
|
||||
...collectWorkspaceSessionWorktreeOwners(session, new Set([candidateId]), 'darwin')
|
||||
]).toEqual([candidateId])
|
||||
})
|
||||
|
||||
it('preserves every candidate that shares an owner comparison key', () => {
|
||||
const nfcId = 'repo-1::/workspace/Café'.normalize('NFC')
|
||||
const nfdId = nfcId.normalize('NFD')
|
||||
const session = sessionWith('activeWorktreeId', nfcId)
|
||||
|
||||
expect(
|
||||
[...collectWorkspaceSessionWorktreeOwners(session, new Set([nfcId, nfdId]))].sort()
|
||||
).toEqual([nfcId, nfdId].sort())
|
||||
})
|
||||
})
|
||||
@@ -1,131 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getDefaultPersistedState } from '../../../shared/constants'
|
||||
import type { PersistedState } from '../../../shared/persisted-state-types'
|
||||
import type { Repo } from '../../../shared/repo-types'
|
||||
import type { WorktreeMeta } from '../../../shared/worktree/meta-types'
|
||||
import {
|
||||
captureNativeLocalWorktreeMetadataScanExpectation,
|
||||
pruneSessionlessMissingLocalWorktreeMetadataForRepo
|
||||
} from './missing-local-worktree-metadata-pruning'
|
||||
|
||||
const REPO_ID = 'repo-1'
|
||||
const WORKTREE_ID = `${REPO_ID}::/workspace/stale`
|
||||
const LOCAL_ALIAS = `local|${WORKTREE_ID}`
|
||||
const IDENTITY_KEY = 'local-identity'
|
||||
|
||||
function makeRepo(id = REPO_ID): Repo {
|
||||
return {
|
||||
id,
|
||||
path: `/workspace/${id}`,
|
||||
displayName: id,
|
||||
badgeColor: '#000',
|
||||
addedAt: 0
|
||||
}
|
||||
}
|
||||
|
||||
function makeMeta(worktreeId = WORKTREE_ID): WorktreeMeta {
|
||||
return {
|
||||
instanceId: `instance-${worktreeId}`,
|
||||
hostId: 'local',
|
||||
displayName: worktreeId,
|
||||
comment: '',
|
||||
linkedIssue: null,
|
||||
linkedPR: null,
|
||||
linkedLinearIssue: null,
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 0
|
||||
}
|
||||
}
|
||||
|
||||
function makeState(): PersistedState {
|
||||
const state = getDefaultPersistedState('/home/test')
|
||||
state.repos = [makeRepo()]
|
||||
return state
|
||||
}
|
||||
|
||||
function makeCanonicalOnlyState(): {
|
||||
state: PersistedState
|
||||
meta: WorktreeMeta
|
||||
} {
|
||||
const state = makeState()
|
||||
const meta = makeMeta()
|
||||
state.worktreeMetaByIdentity = { [IDENTITY_KEY]: meta }
|
||||
state.worktreeIdentityAliases = { [LOCAL_ALIAS]: [IDENTITY_KEY] }
|
||||
return { state, meta }
|
||||
}
|
||||
|
||||
function pruneCaptured(state: PersistedState): string[] {
|
||||
const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!)
|
||||
return pruneSessionlessMissingLocalWorktreeMetadataForRepo(state, scan, scan.metadata)
|
||||
}
|
||||
|
||||
describe('local worktree metadata scan expectations', () => {
|
||||
it('captures canonical-only local metadata and removes its orphaned identity row', () => {
|
||||
const { state } = makeCanonicalOnlyState()
|
||||
|
||||
expect(pruneCaptured(state)).toEqual([WORKTREE_ID])
|
||||
expect(state.worktreeMeta[WORKTREE_ID]).toBeUndefined()
|
||||
expect(state.worktreeIdentityAliases?.[LOCAL_ALIAS]).toBeUndefined()
|
||||
expect(state.worktreeMetaByIdentity?.[IDENTITY_KEY]).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not sweep an unrelated unaliased canonical row during pruning', () => {
|
||||
const { state, meta } = makeCanonicalOnlyState()
|
||||
const unrelated = makeMeta(`${REPO_ID}::/workspace/unrelated`)
|
||||
state.worktreeMetaByIdentity!.unrelated = unrelated
|
||||
|
||||
expect(pruneCaptured(state)).toEqual([WORKTREE_ID])
|
||||
expect(state.worktreeMetaByIdentity).toEqual({ unrelated })
|
||||
expect(state.worktreeMetaByIdentity?.[IDENTITY_KEY]).not.toBeDefined()
|
||||
expect(meta).not.toBe(unrelated)
|
||||
})
|
||||
|
||||
it('preserves metadata when an alias array is replaced with identical contents', () => {
|
||||
const { state } = makeCanonicalOnlyState()
|
||||
const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!)
|
||||
state.worktreeIdentityAliases![LOCAL_ALIAS] = [IDENTITY_KEY]
|
||||
|
||||
expect(pruneSessionlessMissingLocalWorktreeMetadataForRepo(state, scan, scan.metadata)).toEqual(
|
||||
[]
|
||||
)
|
||||
expect(state.worktreeMetaByIdentity?.[IDENTITY_KEY]).toBeDefined()
|
||||
})
|
||||
|
||||
it.each([
|
||||
[
|
||||
'added',
|
||||
(state: PersistedState) => {
|
||||
state.worktreeIdentityAliases![`ssh:builder|${WORKTREE_ID}`] = [IDENTITY_KEY]
|
||||
}
|
||||
],
|
||||
[
|
||||
'removed',
|
||||
(state: PersistedState) => {
|
||||
delete state.worktreeIdentityAliases![LOCAL_ALIAS]
|
||||
}
|
||||
]
|
||||
] as const)('preserves metadata when an alias is %s during the scan', (_label, mutate) => {
|
||||
const { state } = makeCanonicalOnlyState()
|
||||
const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!)
|
||||
mutate(state)
|
||||
|
||||
expect(pruneSessionlessMissingLocalWorktreeMetadataForRepo(state, scan, scan.metadata)).toEqual(
|
||||
[]
|
||||
)
|
||||
expect(state.worktreeMetaByIdentity?.[IDENTITY_KEY]).toBeDefined()
|
||||
})
|
||||
|
||||
it('preserves a legacy row created after a canonical-only scan capture', () => {
|
||||
const { state } = makeCanonicalOnlyState()
|
||||
const scan = captureNativeLocalWorktreeMetadataScanExpectation(state, state.repos[0]!)
|
||||
state.worktreeMeta[WORKTREE_ID] = makeMeta()
|
||||
|
||||
expect(pruneSessionlessMissingLocalWorktreeMetadataForRepo(state, scan, scan.metadata)).toEqual(
|
||||
[]
|
||||
)
|
||||
expect(state.worktreeMeta[WORKTREE_ID]).toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -1,164 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
import {
|
||||
closeTestStores,
|
||||
createStore,
|
||||
makeRepo,
|
||||
testState,
|
||||
writeDataFile
|
||||
} from '../persistence-test-harness'
|
||||
import { getWorkspaceAttachments } from '../../../shared/workspace-attachments/workspace-attachments'
|
||||
import type { WorkspaceAttachment } from '../../../shared/worktree/types'
|
||||
import { mergeWorktree } from '../../ipc/worktree-metadata-merge'
|
||||
import { hostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity'
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => testState.dir },
|
||||
safeStorage: {
|
||||
isEncryptionAvailable: () => false
|
||||
}
|
||||
}))
|
||||
vi.mock('../../telemetry/client', () => ({ track: vi.fn() }))
|
||||
vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() }))
|
||||
const pr = (number: number): WorkspaceAttachment => ({ provider: 'github', type: 'pr', number })
|
||||
|
||||
describe('workspace attachment persistence', () => {
|
||||
beforeEach(() => {
|
||||
testState.dir = mkdtempSync(join(tmpdir(), 'orca-attachments-'))
|
||||
})
|
||||
afterEach(async () => {
|
||||
await closeTestStores()
|
||||
rmSync(testState.dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('round-trips collections and active selection through host-qualified metadata and git projections', async () => {
|
||||
writeDataFile({ repos: [makeRepo({ id: 'repo', path: '/work', connectionId: 'test' })] })
|
||||
const store = await createStore()
|
||||
store.setWorktreeMeta(hostWorktreeTarget({ id: 'repo::/work', hostId: 'ssh:test' }), {
|
||||
linkedPR: 7
|
||||
})
|
||||
store.setWorktreeMeta(hostWorktreeTarget({ id: 'repo::/work', hostId: 'ssh:test' }), {
|
||||
linkedPR: 8
|
||||
})
|
||||
store.flush()
|
||||
const restored = await createStore()
|
||||
const meta = restored.getWorktreeMetaForHost('repo::/work', 'ssh:test')
|
||||
expect(meta?.linkedItems).toEqual([pr(7), pr(8)])
|
||||
expect(meta?.linkedPR).toBe(8)
|
||||
const projected = mergeWorktree(
|
||||
'repo',
|
||||
{ path: '/work', head: 'abc', branch: 'feature', isBare: false, isMainWorktree: false },
|
||||
meta
|
||||
)
|
||||
expect(projected.linkedItems).toEqual([pr(7), pr(8)])
|
||||
expect(
|
||||
restored.setWorktreeMeta(hostWorktreeTarget({ id: 'repo::/work', hostId: 'ssh:test' }), {
|
||||
linkedItems: [pr(7)]
|
||||
}).linkedPR
|
||||
).toBe(7)
|
||||
restored.flush()
|
||||
expect(
|
||||
(await createStore()).getWorktreeMetaForHost('repo::/work', 'ssh:test')?.linkedItems
|
||||
).toEqual([pr(7)])
|
||||
})
|
||||
|
||||
it('loads scalar-only metadata and repairs malformed duplicate collection entries', async () => {
|
||||
writeDataFile({
|
||||
worktreeMeta: {
|
||||
legacy: { linkedPR: 7 },
|
||||
repaired: { linkedPR: 7, linkedItems: [pr(7), null, {}, pr(7), pr(8)] }
|
||||
}
|
||||
})
|
||||
const store = await createStore()
|
||||
expect(getWorkspaceAttachments(store.getWorktreeMeta('legacy'))).toEqual([pr(7)])
|
||||
expect(store.getWorktreeMeta('repaired')?.linkedItems).toEqual([pr(7), pr(8)])
|
||||
store.setWorktreeMeta(hostWorktreeTarget({ id: 'legacy', hostId: 'local' }), { linkedPR: 8 })
|
||||
expect(store.getWorktreeMeta('legacy')?.linkedItems).toEqual([pr(7), pr(8)])
|
||||
})
|
||||
|
||||
it('retains multiple repo-less folder tasks and clears the active task when its collection is emptied', async () => {
|
||||
const store = await createStore()
|
||||
const group = store.createProjectGroup({
|
||||
name: 'Docs',
|
||||
parentPath: '/docs',
|
||||
createdFrom: 'folder-scan'
|
||||
})
|
||||
const task = (number: number) => ({
|
||||
provider: 'github' as const,
|
||||
type: 'issue' as const,
|
||||
number,
|
||||
title: `Issue ${number}`,
|
||||
url: `https://github.com/a/docs/issues/${number}`
|
||||
})
|
||||
const workspace = store.createFolderWorkspace({ projectGroupId: group.id, linkedTask: task(7) })
|
||||
store.updateFolderWorkspace(workspace.id, { linkedTask: task(8) })
|
||||
expect(workspace.linkedItems).toHaveLength(2)
|
||||
store.flush()
|
||||
const restored = await createStore()
|
||||
expect(restored.getFolderWorkspace(workspace.id)?.linkedItems).toHaveLength(2)
|
||||
expect(restored.updateFolderWorkspace(workspace.id, { linkedItems: [] })?.linkedTask).toBeNull()
|
||||
restored.flush()
|
||||
expect((await createStore()).getFolderWorkspace(workspace.id)?.linkedItems).toEqual([])
|
||||
})
|
||||
it('applies stale client add/remove deltas atomically for worktrees and folders', async () => {
|
||||
const store = await createStore()
|
||||
store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt', hostId: 'local' }), {
|
||||
linkedItems: [pr(1)]
|
||||
})
|
||||
const firstClient = { linkedItemsBase: [pr(1)], linkedItems: [pr(1), pr(2)] }
|
||||
const secondClient = { linkedItemsBase: [pr(1)], linkedItems: [pr(3)] }
|
||||
store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt', hostId: 'local' }), firstClient)
|
||||
store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt', hostId: 'local' }), secondClient)
|
||||
expect(store.getWorktreeMeta('wt')?.linkedItems).toEqual([pr(2), pr(3)])
|
||||
expect(store.getWorktreeMeta('wt')).not.toHaveProperty('linkedItemsBase')
|
||||
const group = store.createProjectGroup({
|
||||
name: 'Folder',
|
||||
parentPath: '/docs',
|
||||
createdFrom: 'folder-scan'
|
||||
})
|
||||
const folder = store.createFolderWorkspace({ projectGroupId: group.id, linkedItems: [pr(1)] })
|
||||
store.updateFolderWorkspace(folder.id, firstClient)
|
||||
store.updateFolderWorkspace(folder.id, secondClient)
|
||||
expect(folder.linkedItems).toEqual([pr(2), pr(3)])
|
||||
expect(folder).not.toHaveProperty('linkedItemsBase')
|
||||
store.flush()
|
||||
const restored = await createStore()
|
||||
expect(restored.getWorktreeMeta('wt')?.linkedItems).toEqual([pr(2), pr(3)])
|
||||
expect(restored.getFolderWorkspace(folder.id)?.linkedItems).toEqual([pr(2), pr(3)])
|
||||
})
|
||||
|
||||
it('keeps the current review target when a stale collection edit resolved another review', async () => {
|
||||
const store = await createStore()
|
||||
const currentTarget = { remoteName: 'origin', branchName: 'pr-2' }
|
||||
store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt', hostId: 'local' }), {
|
||||
linkedItems: [pr(2)],
|
||||
linkedPR: 2,
|
||||
pushTarget: currentTarget
|
||||
})
|
||||
store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt', hostId: 'local' }), {
|
||||
linkedItemsBase: [],
|
||||
linkedItems: [pr(1)],
|
||||
linkedPR: 1,
|
||||
linkedItemsSelectionChanged: false,
|
||||
pushTarget: { remoteName: 'origin', branchName: 'pr-1' }
|
||||
})
|
||||
expect(store.getWorktreeMeta('wt')).toMatchObject({
|
||||
linkedPR: 2,
|
||||
linkedItems: [pr(2), pr(1)],
|
||||
pushTarget: currentTarget
|
||||
})
|
||||
store.setWorktreeMeta(hostWorktreeTarget({ id: 'wt', hostId: 'local' }), {
|
||||
linkedItemsBase: [pr(2), pr(1)],
|
||||
linkedItems: [pr(2), pr(1)],
|
||||
linkedPR: 1,
|
||||
linkedItemsSelectionChanged: true,
|
||||
pushTarget: { remoteName: 'origin', branchName: 'pr-1' }
|
||||
})
|
||||
expect(store.getWorktreeMeta('wt')).toMatchObject({
|
||||
linkedPR: 1,
|
||||
pushTarget: { remoteName: 'origin', branchName: 'pr-1' }
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,111 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { WorktreeMeta } from '../../../shared/worktree/meta-types'
|
||||
import { WORKTREE_META_PERSISTED_DEFAULTS } from '../../../shared/worktree/metadata/meta-persisted-defaults'
|
||||
import type { PersistedState } from '../../../shared/persisted-state-types'
|
||||
import {
|
||||
gcStaleWorktreeMeta,
|
||||
normalizeWorktreeLinkedItemMetadata
|
||||
} from './worktree-metadata-normalization'
|
||||
|
||||
// Surviving rows must restore the defaults omitted by serialization.
|
||||
function makeMeta(): WorktreeMeta {
|
||||
return { createdAt: 1, ...WORKTREE_META_PERSISTED_DEFAULTS } as WorktreeMeta
|
||||
}
|
||||
|
||||
function makeState(overrides: Partial<PersistedState>): PersistedState {
|
||||
return {
|
||||
worktreeMeta: {},
|
||||
worktreeLineageById: {},
|
||||
workspaceLineageByChildKey: {},
|
||||
...overrides
|
||||
} as PersistedState
|
||||
}
|
||||
|
||||
describe('normalizeWorktreeLinkedItemMetadata', () => {
|
||||
it('drops malformed canonical metadata entries', () => {
|
||||
const state = makeState({
|
||||
worktreeMetaByIdentity: {
|
||||
valid: makeMeta(),
|
||||
malformed: null
|
||||
} as unknown as PersistedState['worktreeMetaByIdentity'],
|
||||
worktreeIdentityAliases: { 'local|r1::/tmp/wt': ['valid', 'malformed'] }
|
||||
})
|
||||
|
||||
expect(normalizeWorktreeLinkedItemMetadata(state)).toBe(true)
|
||||
expect(state.worktreeIdentityAliases).toEqual({ 'local|r1::/tmp/wt': ['valid'] })
|
||||
})
|
||||
|
||||
it('preserves every host canonical row when one legacy locator row is malformed', () => {
|
||||
const localKey = 'wt2:local:local-instance'
|
||||
const remoteKey = 'wt2:ssh%3Abuilder:remote-instance'
|
||||
const worktreeId = 'r1::/tmp/wt'
|
||||
const state = makeState({
|
||||
worktreeMeta: { [worktreeId]: null } as unknown as PersistedState['worktreeMeta'],
|
||||
worktreeMetaByIdentity: { [localKey]: makeMeta(), [remoteKey]: makeMeta() },
|
||||
worktreeIdentityAliases: {
|
||||
[`local|${worktreeId}`]: [localKey],
|
||||
[`ssh:builder|${worktreeId}`]: [remoteKey]
|
||||
}
|
||||
})
|
||||
|
||||
expect(normalizeWorktreeLinkedItemMetadata(state)).toBe(true)
|
||||
expect(state.worktreeMeta).toEqual({})
|
||||
expect(state.worktreeIdentityAliases).toEqual({
|
||||
[`local|${worktreeId}`]: [localKey],
|
||||
[`ssh:builder|${worktreeId}`]: [remoteKey]
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves valid canonical state when the whole legacy projection is malformed', () => {
|
||||
const identityKey = 'wt2:ssh%3Abuilder:remote-instance'
|
||||
const alias = 'ssh:builder|r1::/tmp/wt'
|
||||
const state = makeState({
|
||||
worktreeMeta: null as unknown as PersistedState['worktreeMeta'],
|
||||
worktreeMetaByIdentity: { [identityKey]: makeMeta() },
|
||||
worktreeIdentityAliases: { [alias]: [identityKey] }
|
||||
})
|
||||
|
||||
expect(normalizeWorktreeLinkedItemMetadata(state)).toBe(true)
|
||||
expect(state.worktreeMeta).toEqual({})
|
||||
expect(state.worktreeIdentityAliases).toEqual({ [alias]: [identityKey] })
|
||||
})
|
||||
|
||||
it('prunes canonical metadata left unreachable by dangling-alias cleanup', () => {
|
||||
const liveKey = 'wt2:local:live'
|
||||
const orphanKey = 'wt2:local:orphan'
|
||||
const state = makeState({
|
||||
worktreeMetaByIdentity: { [liveKey]: makeMeta(), [orphanKey]: makeMeta() },
|
||||
worktreeIdentityAliases: {
|
||||
'local|r1::/tmp/live': [liveKey],
|
||||
'local|r1::/tmp/dangling': ['missing-key']
|
||||
}
|
||||
})
|
||||
|
||||
expect(normalizeWorktreeLinkedItemMetadata(state)).toBe(true)
|
||||
expect(state.worktreeIdentityAliases).toEqual({ 'local|r1::/tmp/live': [liveKey] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('gcStaleWorktreeMeta', () => {
|
||||
it('keeps an archived workspace whose checkout was deleted on purpose', () => {
|
||||
const worktreeId = 'r1::/definitely/missing/orca/archived'
|
||||
const state = makeState({
|
||||
repos: [],
|
||||
projects: [],
|
||||
worktreeMeta: {
|
||||
[worktreeId]: {
|
||||
...makeMeta(),
|
||||
hostId: 'local',
|
||||
comment: 'resume after review',
|
||||
isArchived: true,
|
||||
archivedCheckout: { branch: 'feature/archived', archivedAt: 1 },
|
||||
// Epoch-start activity is past any grace period, so only the archive mark keeps it.
|
||||
lastActivityAt: 1
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
expect(gcStaleWorktreeMeta(state)).toBe(0)
|
||||
expect(state.worktreeMeta[worktreeId]?.comment).toBe('resume after review')
|
||||
})
|
||||
})
|
||||
@@ -1,139 +0,0 @@
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { PluginKillList } from '../../../shared/plugins/catalog/plugin-kill-list'
|
||||
import { PLUGIN_KILL_LIST_RETRY_MS, PluginKillListService } from './plugin-kill-list-service'
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
async function tempRoot(): Promise<string> {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-plugin-kill-list-'))
|
||||
roots.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
function killList(date = '2026-07-12T20:00:00Z'): PluginKillList {
|
||||
return {
|
||||
version: 1,
|
||||
generatedAt: date,
|
||||
plugins: [{ pluginKey: 'community.unsafe', reason: 'Malware advisory' }]
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers()
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
|
||||
})
|
||||
|
||||
describe('PluginKillListService', () => {
|
||||
it('loads cached revocations before any network refresh', async () => {
|
||||
const root = await tempRoot()
|
||||
const first = new PluginKillListService({
|
||||
pluginsDataDir: root,
|
||||
fetcher: async () => killList()
|
||||
})
|
||||
await first.refresh()
|
||||
const fetcher = vi.fn(async () => killList())
|
||||
const restarted = new PluginKillListService({ pluginsDataDir: root, fetcher })
|
||||
|
||||
await restarted.initialize()
|
||||
|
||||
expect(restarted.reason('community.unsafe')).toBe('Malware advisory')
|
||||
expect(fetcher).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps accepting genuine lists after a far-future snapshot is published', async () => {
|
||||
const root = await tempRoot()
|
||||
const fetcher = vi
|
||||
.fn<() => Promise<PluginKillList>>()
|
||||
.mockResolvedValueOnce(killList('9999-12-31T23:59:59Z'))
|
||||
.mockResolvedValueOnce(killList('2026-07-12T20:00:00Z'))
|
||||
const service = new PluginKillListService({ pluginsDataDir: root, fetcher })
|
||||
|
||||
await expect(service.refresh()).rejects.toThrow()
|
||||
await expect(service.refresh()).resolves.toMatchObject({
|
||||
generatedAt: '2026-07-12T20:00:00Z'
|
||||
})
|
||||
expect(service.reason('community.unsafe')).toBe('Malware advisory')
|
||||
const restarted = new PluginKillListService({ pluginsDataDir: root, fetcher })
|
||||
await restarted.initialize()
|
||||
expect(restarted.snapshot()?.generatedAt).toBe('2026-07-12T20:00:00Z')
|
||||
})
|
||||
|
||||
it('keeps cached revocations live when the device clock runs far behind', async () => {
|
||||
const root = await tempRoot()
|
||||
const generatedAt = new Date().toISOString()
|
||||
const published = new PluginKillListService({
|
||||
pluginsDataDir: root,
|
||||
fetcher: async () => killList(generatedAt)
|
||||
})
|
||||
await published.refresh()
|
||||
// A skewed RTC/restored VM clock must not undo cached revocation.
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date(Date.parse(generatedAt) - 30 * 24 * 60 * 60 * 1000))
|
||||
const restarted = new PluginKillListService({
|
||||
pluginsDataDir: root,
|
||||
fetcher: async () => killList(generatedAt)
|
||||
})
|
||||
|
||||
await restarted.initialize()
|
||||
|
||||
expect(restarted.snapshot()?.generatedAt).toBe(generatedAt)
|
||||
expect(restarted.reason('community.unsafe')).toBe('Malware advisory')
|
||||
// Refused refreshes must preserve existing revocation.
|
||||
await expect(restarted.refresh()).rejects.toThrow()
|
||||
expect(restarted.reason('community.unsafe')).toBe('Malware advisory')
|
||||
})
|
||||
|
||||
it('refreshes periodically while plugins are on so long sessions see revocations', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] })
|
||||
let revoked = false
|
||||
const service = new PluginKillListService({
|
||||
pluginsDataDir: await tempRoot(),
|
||||
fetcher: async () =>
|
||||
revoked
|
||||
? killList('2026-07-13T20:00:00Z')
|
||||
: { version: 1, generatedAt: '2026-07-12T20:00:00Z', plugins: [] }
|
||||
})
|
||||
await service.refresh()
|
||||
const changed = vi.fn()
|
||||
service.onChanged(changed)
|
||||
service.syncPeriodicRefresh(true, 1000)
|
||||
service.syncPeriodicRefresh(true, 1000)
|
||||
revoked = true
|
||||
|
||||
vi.advanceTimersByTime(1000)
|
||||
await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(1))
|
||||
expect(service.reason('community.unsafe')).toBe('Malware advisory')
|
||||
|
||||
service.syncPeriodicRefresh(false)
|
||||
vi.advanceTimersByTime(5000)
|
||||
await Promise.resolve()
|
||||
expect(changed).toHaveBeenCalledTimes(1)
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PluginKillListService retry', () => {
|
||||
it('retries 15 minutes after a failed refresh instead of waiting a full interval', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'setTimeout', 'clearTimeout'] })
|
||||
let online = false
|
||||
const service = new PluginKillListService({
|
||||
pluginsDataDir: await tempRoot(),
|
||||
fetcher: async () => {
|
||||
if (!online) {
|
||||
throw new Error('offline')
|
||||
}
|
||||
return killList()
|
||||
}
|
||||
})
|
||||
service.syncPeriodicRefresh(true)
|
||||
await expect(service.refresh()).rejects.toThrow('offline')
|
||||
online = true
|
||||
await vi.advanceTimersByTimeAsync(PLUGIN_KILL_LIST_RETRY_MS)
|
||||
await vi.waitFor(() => expect(service.reason('community.unsafe')).toBe('Malware advisory'))
|
||||
service.dispose()
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -1,102 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type {
|
||||
PluginHostListEntry,
|
||||
PluginHostStatus
|
||||
} from '../../../shared/plugins/plugin-list-entry'
|
||||
import type { ValidDiscoveredPlugin } from '../discovery/plugin-discovery'
|
||||
import {
|
||||
resolvePluginViewEditor,
|
||||
resolvePluginViewPanel,
|
||||
type PluginViewSource
|
||||
} from './plugin-view-target'
|
||||
|
||||
const KEY = 'acme.todos'
|
||||
|
||||
function source(
|
||||
status: PluginHostStatus,
|
||||
contributes: { panels?: unknown[]; customEditors?: unknown[] } = {}
|
||||
): PluginViewSource {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the resolver reads only pluginKey, status and error.
|
||||
const entry = { pluginKey: KEY, status, error: 'boom' } as PluginHostListEntry
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the resolver reads only rootDir, contentHash and these contributions.
|
||||
const plugin = {
|
||||
pluginKey: KEY,
|
||||
rootDir: '/plugins/acme.todos',
|
||||
contentHash: `sha256-${'a'.repeat(64)}`,
|
||||
manifest: {
|
||||
contributes: {
|
||||
panels: contributes.panels ?? [],
|
||||
customEditors: contributes.customEditors ?? []
|
||||
}
|
||||
}
|
||||
} as unknown as ValidDiscoveredPlugin
|
||||
return {
|
||||
list: async () => [entry],
|
||||
findValidPlugin: (key) => (key === KEY ? plugin : null)
|
||||
}
|
||||
}
|
||||
|
||||
const PANELS = [
|
||||
{ id: 'todos', title: 'Todos', entry: 'src/panel.tsx', ui: 'components' },
|
||||
{ id: 'stats', title: 'Stats', entry: 'stats.html' }
|
||||
]
|
||||
|
||||
describe('resolvePluginViewPanel', () => {
|
||||
it('defaults to the first panel and stamps the guest revision', async () => {
|
||||
await expect(
|
||||
resolvePluginViewPanel(source('idle', { panels: PANELS }), KEY, undefined)
|
||||
).resolves.toEqual({
|
||||
pluginKey: KEY,
|
||||
panelId: 'todos',
|
||||
title: 'Todos',
|
||||
ui: 'components',
|
||||
guestRevision: 'sha256-aaaaaaaaa'
|
||||
})
|
||||
await expect(
|
||||
resolvePluginViewPanel(source('running', { panels: PANELS }), KEY, 'stats')
|
||||
).resolves.toMatchObject({ panelId: 'stats', ui: 'html' })
|
||||
})
|
||||
|
||||
it('names the panels it has when the id is wrong', async () => {
|
||||
await expect(
|
||||
resolvePluginViewPanel(source('idle', { panels: PANELS }), KEY, 'nope')
|
||||
).rejects.toMatchObject({
|
||||
code: 'invalid_argument',
|
||||
data: { nextSteps: ['Its panels: todos, stats.'] }
|
||||
})
|
||||
await expect(resolvePluginViewPanel(source('idle'), KEY, undefined)).rejects.toThrow(
|
||||
/contributes no panels/
|
||||
)
|
||||
})
|
||||
|
||||
it('refuses an unknown plugin and one that is not running', async () => {
|
||||
await expect(
|
||||
resolvePluginViewPanel(source('idle', { panels: PANELS }), 'acme.other', undefined)
|
||||
).rejects.toMatchObject({ code: 'plugin_not_found' })
|
||||
await expect(
|
||||
resolvePluginViewPanel(source('pending', { panels: PANELS }), KEY, undefined)
|
||||
).rejects.toThrow(/waiting for approval/)
|
||||
await expect(
|
||||
resolvePluginViewPanel(source('errored', { panels: PANELS }), KEY, undefined)
|
||||
).rejects.toThrow(/is errored: boom/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolvePluginViewEditor', () => {
|
||||
const editors = [{ id: 'notes', title: 'Notes', extensions: ['.notes'], filenames: [] }]
|
||||
|
||||
it('picks the first editor that takes the file', async () => {
|
||||
await expect(
|
||||
resolvePluginViewEditor(source('idle', { customEditors: editors }), KEY, '/w/plan.notes')
|
||||
).resolves.toEqual({ pluginKey: KEY, editorId: 'notes', title: 'Notes' })
|
||||
})
|
||||
|
||||
it('says which files its editors open when none takes this one', async () => {
|
||||
await expect(
|
||||
resolvePluginViewEditor(source('idle', { customEditors: editors }), KEY, '/w/plan.md')
|
||||
).rejects.toMatchObject({ data: { nextSteps: ['notes opens *.notes.'] } })
|
||||
await expect(resolvePluginViewEditor(source('idle'), KEY, '/w/a.md')).rejects.toThrow(
|
||||
/no custom editors/
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,81 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ArtifactPreview } from './ArtifactPreview'
|
||||
|
||||
function dispatchLoadFailure(
|
||||
webview: Element,
|
||||
failure: { errorCode: number; isMainFrame: boolean }
|
||||
): void {
|
||||
const event = new Event('did-fail-load')
|
||||
Object.assign(event, {
|
||||
errorCode: failure.errorCode,
|
||||
errorDescription: 'failed',
|
||||
validatedURL: 'https://share.onorca.dev/a/report',
|
||||
isMainFrame: failure.isMainFrame
|
||||
})
|
||||
webview.dispatchEvent(event)
|
||||
}
|
||||
|
||||
describe('ArtifactPreview', () => {
|
||||
beforeEach(() => {
|
||||
Object.assign(window, {
|
||||
api: {
|
||||
browser: { sessionResolvePartition: vi.fn().mockResolvedValue('persist:orca-default') }
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
cleanup()
|
||||
})
|
||||
|
||||
it('ignores child-frame failures and aborted navigations', async () => {
|
||||
render(<ArtifactPreview shareUrl="https://share.onorca.dev/a/report" />)
|
||||
const webview = await waitFor(() => {
|
||||
const element = document.querySelector('webview')
|
||||
expect(element).not.toBeNull()
|
||||
if (!element) {
|
||||
throw new Error('preview webview not attached')
|
||||
}
|
||||
return element
|
||||
})
|
||||
|
||||
act(() => dispatchLoadFailure(webview, { errorCode: -105, isMainFrame: false }))
|
||||
expect(screen.queryByText('Preview unavailable')).not.toBeInTheDocument()
|
||||
act(() => dispatchLoadFailure(webview, { errorCode: -3, isMainFrame: true }))
|
||||
expect(screen.queryByText('Preview unavailable')).not.toBeInTheDocument()
|
||||
act(() => webview.dispatchEvent(new Event('did-stop-loading')))
|
||||
expect(screen.queryByText('Preview unavailable')).not.toBeInTheDocument()
|
||||
|
||||
act(() => dispatchLoadFailure(webview, { errorCode: -105, isMainFrame: true }))
|
||||
expect(screen.getByText('Preview unavailable')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('stops waiting when navigation stalls', async () => {
|
||||
vi.useFakeTimers()
|
||||
render(<ArtifactPreview shareUrl="https://share.onorca.dev/a/report" />)
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
expect(document.querySelector('webview')).not.toBeNull()
|
||||
|
||||
act(() => vi.advanceTimersByTime(20_000))
|
||||
|
||||
expect(screen.getByText('Preview unavailable')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('stops waiting when preview-session resolution stalls', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.mocked(window.api.browser.sessionResolvePartition).mockReturnValue(new Promise(() => {}))
|
||||
render(<ArtifactPreview shareUrl="https://share.onorca.dev/a/report" />)
|
||||
|
||||
act(() => vi.advanceTimersByTime(20_000))
|
||||
|
||||
expect(screen.getByText('Preview unavailable')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createHoverPreviewCache } from './native-chat-hover-preview-cache'
|
||||
|
||||
describe('createHoverPreviewCache', () => {
|
||||
it('starts a fresh request after the pending binding retires and preserves its replacement', async () => {
|
||||
const cache = createHoverPreviewCache<string>({ freshMs: 60_000, maxEntries: 100 })
|
||||
let live = true
|
||||
let finish: (value: string) => void = () => {}
|
||||
const old = cache.load(
|
||||
'a',
|
||||
() => new Promise((resolve) => (finish = resolve)),
|
||||
() => live
|
||||
)
|
||||
live = false
|
||||
let finishNew: (value: string) => void = () => {}
|
||||
const current = cache.load('a', () => new Promise((resolve) => (finishNew = resolve)))
|
||||
finish('old')
|
||||
expect(await old).toBeNull()
|
||||
const joined = cache.load('a', async () => 'unexpected')
|
||||
finishNew('new')
|
||||
expect(await current).toBe('new')
|
||||
expect(await joined).toBe('new')
|
||||
expect(cache.read('a')).toBe('new')
|
||||
})
|
||||
|
||||
it('coalesces pending requests while their binding remains live', async () => {
|
||||
const cache = createHoverPreviewCache<string>({ freshMs: 60_000, maxEntries: 100 })
|
||||
let finish: (value: string) => void = () => {}
|
||||
const first = cache.load(
|
||||
'a',
|
||||
() => new Promise((resolve) => (finish = resolve)),
|
||||
() => true
|
||||
)
|
||||
const second = cache.load(
|
||||
'a',
|
||||
async () => 'unexpected',
|
||||
() => true
|
||||
)
|
||||
finish('result')
|
||||
expect(await first).toBe('result')
|
||||
expect(await second).toBe('result')
|
||||
})
|
||||
|
||||
it('does not publish a response whose owner rejects it at cache commit', async () => {
|
||||
const cache = createHoverPreviewCache<string>({ freshMs: 60_000, maxEntries: 100 })
|
||||
const response = Promise.withResolvers<string>()
|
||||
let current = true
|
||||
const pending = cache.load(
|
||||
'alice',
|
||||
() => response.promise,
|
||||
() => current
|
||||
)
|
||||
response.resolve('bob response')
|
||||
current = false
|
||||
await expect(pending).resolves.toBeNull()
|
||||
expect(cache.read('alice')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the last answer through a reread that fails, and rereads past one started earlier', async () => {
|
||||
const cache = createHoverPreviewCache<string>({ freshMs: 60_000, maxEntries: 100 })
|
||||
await cache.load('pr', async () => 'closed')
|
||||
let finishEarly: (value: string) => void = () => {}
|
||||
cache.expire('pr')
|
||||
const early = cache.load('pr', () => new Promise((resolve) => (finishEarly = resolve)))
|
||||
expect(cache.read('pr')).toBe('closed')
|
||||
|
||||
// The chat reopened the pull request while that read was out.
|
||||
cache.expire('pr')
|
||||
const after = cache.load('pr', async () => 'open')
|
||||
finishEarly('closed')
|
||||
await early
|
||||
expect(await after).toBe('open')
|
||||
expect(cache.read('pr')).toBe('open')
|
||||
|
||||
cache.expire('pr')
|
||||
await cache.load('pr', async () => null)
|
||||
expect(cache.read('pr')).toBe('open')
|
||||
})
|
||||
})
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
import type * as RuntimeCapabilityProofModule from '@/runtime/rpc/compatibility/runtime-capability-proof'
|
||||
// @vitest-environment happy-dom
|
||||
import {
|
||||
answer,
|
||||
mutateWith,
|
||||
renderOptions,
|
||||
REOPENED,
|
||||
currentValue
|
||||
} from './use-structured-agent-session-options.test-fixture'
|
||||
import { forgetStructuredSessionSelection } from '@/lib/agent-session/options/structured-agent-session-selection-controller'
|
||||
|
||||
import { act, waitFor } from '@testing-library/react'
|
||||
import { expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof RuntimeCapabilityProofModule>()),
|
||||
runtimeEnvironmentSupportsCapability: async () => true
|
||||
}))
|
||||
|
||||
it('projects transmitted mode admission to the optimistic exit control and recovers after settlement', async () => {
|
||||
const sessionId = 'mode-admission-projection'
|
||||
forgetStructuredSessionSelection(sessionId)
|
||||
let interactionMode: 'default' | 'plan' = 'default'
|
||||
const reply = Promise.withResolvers<{
|
||||
key: string
|
||||
value: string
|
||||
options: Record<string, string>
|
||||
}>()
|
||||
answer({
|
||||
options: async () => ({
|
||||
models: [],
|
||||
current: { interactionMode, acceptedInputSources: { interactionMode: 'saved' } }
|
||||
})
|
||||
})
|
||||
const { mutate } = mutateWith(async (_method, _fingerprint, fields) => {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the option writer sends the fixture its key/value fields.
|
||||
const pick = fields as { key: string; value: string }
|
||||
return pick.key === 'interactionMode' ? reply.promise : { key: pick.key, value: pick.value }
|
||||
})
|
||||
const hook = renderOptions({ ...REOPENED, sessionId }, mutate)
|
||||
try {
|
||||
await waitFor(() =>
|
||||
expect(hook.result.current.optionSurface.admits?.('interactionMode', 'plan')).toBe(true)
|
||||
)
|
||||
let pending: Promise<boolean> | undefined
|
||||
act(() => {
|
||||
pending = hook.result.current.setStructuredOption('interactionMode', 'plan')
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(currentValue(hook.result.current.optionSnapshot, 'interactionMode')).toBe('plan')
|
||||
)
|
||||
expect(
|
||||
hook.result.current.optionSnapshot.find((entry) => entry.id === 'interactionMode')?.settable
|
||||
).toBe(false)
|
||||
await act(async () => {
|
||||
await hook.result.current.setStructuredOption('effort', 'high')
|
||||
})
|
||||
expect(
|
||||
hook.result.current.optionSnapshot.find((entry) => entry.id === 'interactionMode')?.settable
|
||||
).toBe(false)
|
||||
interactionMode = 'plan'
|
||||
await act(async () => {
|
||||
reply.resolve({ key: 'interactionMode', value: 'plan', options: { interactionMode: 'plan' } })
|
||||
await pending
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
hook.result.current.optionSnapshot.find((entry) => entry.id === 'interactionMode')?.settable
|
||||
).toBe(true)
|
||||
)
|
||||
} finally {
|
||||
hook.unmount()
|
||||
forgetStructuredSessionSelection(sessionId)
|
||||
}
|
||||
})
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, cleanup, renderHook } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../../shared/agent-status/contracts/agent-status-freshness'
|
||||
import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types'
|
||||
|
||||
vi.mock('@/store', async () => {
|
||||
const { createTestStore } = await import('@/store/testing/app-store-test-fixture')
|
||||
return { useAppStore: createTestStore() }
|
||||
})
|
||||
|
||||
import { useAppStore } from '@/store'
|
||||
import { useNativeChatHookStatus } from './use-native-chat-hook-status'
|
||||
import { useNativeChatTerminalTurnTiming } from '../../conversation/turns/use-native-chat-terminal-turn-timing'
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
for (const key of Object.keys(useAppStore.getState().agentStatusByPaneKey)) {
|
||||
useAppStore.getState().removeAgentStatus(key)
|
||||
}
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('preserves its pane status across another pane update and observes its own status and expiry', async () => {
|
||||
vi.useFakeTimers()
|
||||
const start = AGENT_STATUS_STALE_AFTER_MS * 10
|
||||
vi.setSystemTime(start)
|
||||
const messages: NativeChatMessage[] = [
|
||||
{ id: 'turn', role: 'user', blocks: [], timestamp: start, source: 'transcript' }
|
||||
]
|
||||
const store = useAppStore.getState()
|
||||
for (const paneKey of ['own:1', 'other:1']) {
|
||||
store.setAgentStatus(
|
||||
paneKey,
|
||||
{ state: 'working', prompt: 'task', agentType: 'claude' },
|
||||
undefined,
|
||||
{ updatedAt: start, evidenceObservedAt: start, turnStartedAt: start }
|
||||
)
|
||||
}
|
||||
const status = renderHook(() => useNativeChatHookStatus('own:1'))
|
||||
const timing = renderHook(() => useNativeChatTerminalTurnTiming('own:1', messages, false))
|
||||
act(() => {
|
||||
store.setAgentStatus('other:1', { state: 'done', prompt: 'task' })
|
||||
useAppStore.setState((state) => ({ agentStatusEpoch: state.agentStatusEpoch + 1 }))
|
||||
})
|
||||
expect(status.result.current[0]).toBe('working')
|
||||
act(() => {
|
||||
vi.setSystemTime(start + 5_000)
|
||||
store.setAgentStatus('own:1', { state: 'done', prompt: 'task' }, undefined, {
|
||||
turnStartedAt: start
|
||||
})
|
||||
})
|
||||
expect(status.result.current[0]).toBe('done')
|
||||
expect(timing.result.current.settledTurns.get('turn')).toEqual({
|
||||
startedAt: start,
|
||||
workedSeconds: 5
|
||||
})
|
||||
act(() => store.setAgentStatus('own:1', { state: 'working', prompt: 'next task' }))
|
||||
const entry = useAppStore.getState().agentStatusByPaneKey['own:1']
|
||||
await act(async () => {
|
||||
await new Promise<void>((resolve) => queueMicrotask(resolve))
|
||||
vi.advanceTimersByTime(AGENT_STATUS_STALE_AFTER_MS + 1)
|
||||
})
|
||||
expect(useAppStore.getState().agentStatusByPaneKey['own:1']).toBe(entry)
|
||||
expect(status.result.current[0]).toBeNull()
|
||||
expect(timing.result.current.settledTurns.get('turn')).toBeNull()
|
||||
})
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, createElement } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { NativeChatMessage } from '../../../../../../../shared/native-chat/native-chat-types'
|
||||
import type {
|
||||
NativeChatLiveSession,
|
||||
UseNativeChatLiveSessionArgs
|
||||
} from './native-chat-live-session-contract'
|
||||
|
||||
const { liveSession } = vi.hoisted(() => ({ liveSession: vi.fn() }))
|
||||
|
||||
vi.mock('./use-native-chat-live-session', () => ({ useNativeChatLiveSession: liveSession }))
|
||||
|
||||
import { useNativeChatRetainedSession } from './use-native-chat-retained-session'
|
||||
|
||||
const ARGS: UseNativeChatLiveSessionArgs = {
|
||||
paneKey: 'tab:leaf',
|
||||
agent: 'claude',
|
||||
sessionId: 'session',
|
||||
runtimeEnvironmentId: 'owner-a'
|
||||
}
|
||||
|
||||
function message(id: string): NativeChatMessage {
|
||||
return { id, role: 'assistant', blocks: [], timestamp: 0, source: 'transcript' }
|
||||
}
|
||||
|
||||
function session(
|
||||
readPhase: NativeChatLiveSession['readPhase'],
|
||||
messages: NativeChatMessage[],
|
||||
sessionId: string | null = 'session'
|
||||
): NativeChatLiveSession {
|
||||
return {
|
||||
agent: 'claude',
|
||||
sessionId,
|
||||
messages,
|
||||
status: readPhase === 'loading' ? 'loading' : 'ready',
|
||||
hasMore: false,
|
||||
loadingEarlier: false,
|
||||
olderHistoryGeneration: 0,
|
||||
loadEarlier: vi.fn(),
|
||||
readPhase
|
||||
}
|
||||
}
|
||||
|
||||
describe('useNativeChatRetainedSession', () => {
|
||||
let root: Root | null = null
|
||||
let latest: NativeChatLiveSession | null = null
|
||||
|
||||
function Probe(props: UseNativeChatLiveSessionArgs): null {
|
||||
latest = useNativeChatRetainedSession(props)
|
||||
return null
|
||||
}
|
||||
|
||||
async function render(props: UseNativeChatLiveSessionArgs): Promise<void> {
|
||||
if (!root) {
|
||||
root = createRoot(document.createElement('div'))
|
||||
}
|
||||
await act(async () => root?.render(createElement(Probe, props)))
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount())
|
||||
root = null
|
||||
latest = null
|
||||
liveSession.mockReset()
|
||||
})
|
||||
it.each(['loading', 'error'] as const)(
|
||||
'releases expanded fallback rows during %s',
|
||||
async (phase) => {
|
||||
const rows = Array.from({ length: 800 }, (_, index) => message(`row-${index}`))
|
||||
liveSession.mockReturnValue(session('ready', rows))
|
||||
await render(ARGS)
|
||||
const trimHistory = vi.fn()
|
||||
liveSession.mockReturnValue({ ...session(phase, []), trimHistory })
|
||||
await render(ARGS)
|
||||
expect(latest?.messages).toHaveLength(800)
|
||||
act(() => latest?.trimHistory?.())
|
||||
liveSession.mockReturnValue({ ...session(phase, []), trimHistory, olderHistoryGeneration: 1 })
|
||||
await render(ARGS)
|
||||
expect(latest?.messages).toHaveLength(300)
|
||||
expect(latest?.messages[0]?.id).toBe('row-500')
|
||||
expect(latest?.messages.at(-1)?.id).toBe('row-799')
|
||||
expect(trimHistory).toHaveBeenCalledOnce()
|
||||
}
|
||||
)
|
||||
})
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
|
||||
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AgentSessionCancelResult } from '../../../../../../shared/agent-session/agent-session-wire'
|
||||
import type { AgentChildWorkView } from '../../../../../../shared/agent-status/child-work/agent-status-child-work-view'
|
||||
import { structuredSessionBackgroundTasksView } from '../../../../../../shared/structured-session-background-tasks-view'
|
||||
import { NativeChatStructuredSessionStatus } from './NativeChatStructuredSessionStatus'
|
||||
import { useStructuredSessionTaskStop } from './use-structured-session-task-stop'
|
||||
|
||||
vi.mock('./use-structured-session-child-row-context', () => ({
|
||||
useStructuredSessionChildRowContext: () => undefined
|
||||
}))
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
function Strip(props: { tasks: Parameters<typeof useStructuredSessionTaskStop>[1] }) {
|
||||
const stop = useStructuredSessionTaskStop('session-1', props.tasks)
|
||||
return (
|
||||
<NativeChatStructuredSessionStatus
|
||||
sessionId="session-1"
|
||||
paneKey="pane-1"
|
||||
isVisible
|
||||
backgroundTasks={props.tasks.backgroundTasks}
|
||||
stop={stop}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function helper(invocation: AgentChildWorkView['invocation']): AgentChildWorkView {
|
||||
return {
|
||||
id: 'helper',
|
||||
providerId: 'thread-helper',
|
||||
kind: 'agent',
|
||||
description: 'audit_build',
|
||||
state: 'working',
|
||||
membership: 'live',
|
||||
firstObservedAt: Date.now() - 65_000,
|
||||
observedAt: Date.now() - 1_000,
|
||||
stoppable: true,
|
||||
invocation
|
||||
}
|
||||
}
|
||||
|
||||
describe('NativeChatStructuredSessionStatus', () => {
|
||||
it("offers Stop again on a helper's next run, which reuses the stopped run's row id", async () => {
|
||||
let finish: (result: AgentSessionCancelResult) => void = () => {}
|
||||
const stopBackgroundTask = vi.fn(
|
||||
() => new Promise<AgentSessionCancelResult>((resolve) => (finish = resolve))
|
||||
)
|
||||
const strip = (children: AgentChildWorkView[]) => (
|
||||
<Strip
|
||||
tasks={{
|
||||
backgroundTasks: structuredSessionBackgroundTasksView(
|
||||
{ state: 'monitoring', supportsTaskStop: true, children },
|
||||
null
|
||||
),
|
||||
stopBackgroundTask
|
||||
}}
|
||||
/>
|
||||
)
|
||||
const { rerender } = render(strip([helper({ invocationId: 'turn-1', generation: 1 })]))
|
||||
fireEvent.click(screen.getByRole('button', { expanded: false }))
|
||||
fireEvent.click(screen.getByLabelText('Stop audit_build'))
|
||||
await act(async () => finish({ cancelled: true }))
|
||||
expect(screen.getByLabelText('Stop audit_build')).toBeDisabled()
|
||||
|
||||
// The helper's next run, with no render between: same provider id, a new invocation.
|
||||
rerender(strip([helper({ invocationId: 'turn-2', generation: 2 })]))
|
||||
expect(screen.getByLabelText('Stop audit_build')).toBeEnabled()
|
||||
})
|
||||
})
|
||||
@@ -1,82 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { useAppStore } from '@/store'
|
||||
import { showWorkspaceForFile } from './plugin-view-editor-workspace'
|
||||
import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture'
|
||||
|
||||
const activation = vi.hoisted(() => ({ activateAndRevealWorkspace: vi.fn() }))
|
||||
vi.mock('@/lib/workspace/activation/worktree-activation', () => activation)
|
||||
const initialState = useAppStore.getState()
|
||||
afterEach(() => {
|
||||
useAppStore.setState(initialState, true)
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('refuses a retired file owner without registering its deleting directory as a folder', async () => {
|
||||
const addRepoPath = vi.fn()
|
||||
const row = makeWorktree({
|
||||
id: 'r::/work/feature',
|
||||
repoId: 'r',
|
||||
path: '/work/feature',
|
||||
hostId: 'local',
|
||||
removing: true,
|
||||
removalRecorded: true
|
||||
})
|
||||
useAppStore.setState({
|
||||
worktreesByRepo: { r: [row] },
|
||||
folderWorkspaces: [],
|
||||
activeWorktreeId: null,
|
||||
addRepoPath
|
||||
})
|
||||
await expect(
|
||||
showWorkspaceForFile(['/work/feature/document.ext'], '/work/feature')
|
||||
).resolves.toBeNull()
|
||||
expect(addRepoPath).not.toHaveBeenCalled()
|
||||
expect(activation.activateAndRevealWorkspace).not.toHaveBeenCalled()
|
||||
|
||||
useAppStore.setState({ worktreesByRepo: { r: [{ ...row, removalRecorded: undefined }] } })
|
||||
await expect(
|
||||
showWorkspaceForFile(['/work/feature/document.ext'], '/work/feature')
|
||||
).resolves.toMatchObject({ worktreeId: row.id })
|
||||
expect(addRepoPath).not.toHaveBeenCalled()
|
||||
expect(activation.activateAndRevealWorkspace).toHaveBeenCalledWith(row.id, {
|
||||
providesInitialSurface: true,
|
||||
executionHostId: 'local'
|
||||
})
|
||||
})
|
||||
|
||||
it('still registers a genuinely unowned file folder and opens it', async () => {
|
||||
const row = makeWorktree({
|
||||
id: 'added::/new/folder',
|
||||
repoId: 'added',
|
||||
path: '/new/folder',
|
||||
hostId: 'local'
|
||||
})
|
||||
const addRepoPath = vi.fn<typeof initialState.addRepoPath>(async () => {
|
||||
useAppStore.setState({ worktreesByRepo: { added: [row] } })
|
||||
return {
|
||||
id: 'added',
|
||||
path: '/new/folder',
|
||||
displayName: 'added',
|
||||
badgeColor: 'blue',
|
||||
addedAt: 1
|
||||
}
|
||||
})
|
||||
const fetchWorktrees = vi.fn().mockResolvedValue(true)
|
||||
useAppStore.setState({
|
||||
worktreesByRepo: {},
|
||||
folderWorkspaces: [],
|
||||
activeWorktreeId: null,
|
||||
addRepoPath,
|
||||
fetchWorktrees
|
||||
})
|
||||
await expect(
|
||||
showWorkspaceForFile(['/new/folder/document.ext'], '/new/folder')
|
||||
).resolves.toMatchObject({ worktreeId: row.id, addedRepoId: 'added' })
|
||||
expect(addRepoPath).toHaveBeenCalledWith('/new/folder', 'folder', { runtimeEnvironmentId: null })
|
||||
expect(fetchWorktrees).toHaveBeenCalledWith('added')
|
||||
expect(activation.activateAndRevealWorkspace).toHaveBeenCalledWith(row.id, {
|
||||
providesInitialSurface: true,
|
||||
executionHostId: 'local'
|
||||
})
|
||||
})
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import type * as I18n from '@/i18n/i18n'
|
||||
import { expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
NativeAccountInputs,
|
||||
NativeAccountEvidence,
|
||||
nativeEvidenceCovers
|
||||
} from './ai-vault-native-account-index'
|
||||
import { accountSettings, installAccountFixture } from './ai-vault-account-test-fixture'
|
||||
|
||||
vi.mock('@/i18n/i18n', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof I18n>()),
|
||||
translate: (_key: string, fallback: string) => fallback
|
||||
}))
|
||||
installAccountFixture()
|
||||
|
||||
it('compares real coverage under the same evidence across ordered candidates and A/B/A roots', () => {
|
||||
const settings = accountSettings(4)
|
||||
const saved = settings.claudeManagedAccounts[0]!
|
||||
const candidates = [
|
||||
{ ...saved },
|
||||
{ ...saved, managedAuthPath: '/other', email: 'other@example.com' }
|
||||
]
|
||||
const a = new NativeAccountInputs({ ...settings, claudeManagedAccounts: candidates })
|
||||
const evidence = new NativeAccountEvidence(a, {
|
||||
claude: {
|
||||
accounts: [
|
||||
{ ...saved, email: 'old-first@example.com' },
|
||||
{ ...saved, email: 'old-second@example.com' }
|
||||
],
|
||||
activeAccountId: null
|
||||
}
|
||||
})
|
||||
const binding = { kind: 'claude' as const, path: saved.managedAuthPath, scope: 'host' }
|
||||
const b = new NativeAccountInputs({
|
||||
...settings,
|
||||
claudeManagedAccounts: candidates.toReversed()
|
||||
})
|
||||
expect(nativeEvidenceCovers(binding, b, evidence)).toBe(false)
|
||||
const again = new NativeAccountInputs(
|
||||
{ ...settings, claudeManagedAccounts: candidates.map((account) => ({ ...account })) },
|
||||
b
|
||||
)
|
||||
expect(nativeEvidenceCovers(binding, again, evidence)).toBe(true)
|
||||
const orderOnly = new NativeAccountInputs({
|
||||
...settings,
|
||||
claudeManagedAccounts: candidates.map((account, i) => ({ ...account, updatedAt: i + 2 }))
|
||||
})
|
||||
expect(nativeEvidenceCovers(binding, orderOnly, evidence)).toBe(false)
|
||||
const modern = new NativeAccountEvidence(a, {
|
||||
claude: {
|
||||
accounts: [
|
||||
{ ...saved, home: '/routed' },
|
||||
{ ...candidates[1]!, id: 'other', home: '/routed' }
|
||||
],
|
||||
activeAccountId: null
|
||||
}
|
||||
})
|
||||
const routed = { ...binding, path: '/routed' }
|
||||
expect(nativeEvidenceCovers(routed, orderOnly, modern)).toBe(false)
|
||||
const codex = settings.codexManagedAccounts[0]!
|
||||
const firstPath = [codex, { ...codex, id: 'other', email: 'other@example.com' }]
|
||||
const paths = new NativeAccountInputs({ ...settings, codexManagedAccounts: firstPath })
|
||||
const pathEvidence = new NativeAccountEvidence(paths, {
|
||||
codex: { accounts: firstPath, activeAccountId: null }
|
||||
})
|
||||
const swapped = new NativeAccountInputs({
|
||||
...settings,
|
||||
codexManagedAccounts: firstPath.toReversed()
|
||||
})
|
||||
expect(
|
||||
nativeEvidenceCovers(
|
||||
{ kind: 'codex', scope: 'host', path: codex.managedHomePath },
|
||||
swapped,
|
||||
pathEvidence
|
||||
)
|
||||
).toBe(false)
|
||||
})
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import type { AiVaultScanProgress } from '../../../../../../shared/ai-vault/scanning/ai-vault-scan-progress'
|
||||
import { aiVaultLocalScanKey } from '../../../../../../shared/ai-vault/scanning/ai-vault-local-scan-key'
|
||||
|
||||
import { resetAiVaultSessionResultCacheForTest } from './ai-vault-session-result-cache'
|
||||
import {
|
||||
resetAiVaultScanProgressStoreForTests,
|
||||
useAiVaultScanProgress
|
||||
} from './ai-vault-scan-progress-store'
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
resetAiVaultScanProgressStoreForTests()
|
||||
resetAiVaultSessionResultCacheForTest()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
const FINISHED: AiVaultScanProgress = {
|
||||
scanId: 'scan-a',
|
||||
stage: 'finished',
|
||||
agents: [
|
||||
{ agent: 'claude', files: 24_968, databases: 0, walking: false },
|
||||
{ agent: 'codex', files: 77_483, databases: 0, walking: false },
|
||||
{ agent: 'opencode', files: 0, databases: 1, walking: false }
|
||||
],
|
||||
read: { done: 2_000, total: 2_000 },
|
||||
startedAt: 0,
|
||||
settledAt: 90_000
|
||||
}
|
||||
|
||||
it('keeps a narrower cached panel off the broader key while a late matching panel loads it', async () => {
|
||||
const lowerDepth = { scopePaths: ['/project'], includeAntigravityIdeSessions: true, limit: 100 }
|
||||
const broader = aiVaultLocalScanKey({ ...lowerDepth, limit: 1000 })
|
||||
const narrower = aiVaultLocalScanKey(lowerDepth)
|
||||
expect(broader).not.toBe(narrower)
|
||||
const cachedProgress = FINISHED
|
||||
let push: (update: { scanKey: string; progress: AiVaultScanProgress | null }) => void = () =>
|
||||
undefined
|
||||
vi.stubGlobal('api', {
|
||||
aiVault: {
|
||||
getScanProgress: (scanKey: string) =>
|
||||
Promise.resolve(scanKey === broader ? cachedProgress : null),
|
||||
onScanProgress: (callback: typeof push) => {
|
||||
push = callback
|
||||
return () => undefined
|
||||
}
|
||||
}
|
||||
})
|
||||
const local = renderHook(() => useAiVaultScanProgress('local', broader))
|
||||
const narrowerPanel = renderHook(() => useAiVaultScanProgress('local', narrower))
|
||||
const remote = renderHook(() => useAiVaultScanProgress('runtime:server-1', broader))
|
||||
const allHosts = renderHook(() => useAiVaultScanProgress('all', broader))
|
||||
await waitFor(() => expect(local.result.current?.progress).toBe(cachedProgress))
|
||||
act(() => push({ scanKey: broader, progress: cachedProgress }))
|
||||
|
||||
expect(local.result.current?.progress).toBe(cachedProgress)
|
||||
expect(narrowerPanel.result.current).toBeNull()
|
||||
act(() =>
|
||||
push({ scanKey: broader, progress: { ...cachedProgress, scanId: 'later', stage: 'finding' } })
|
||||
)
|
||||
expect(narrowerPanel.result.current).toBeNull()
|
||||
// Without remote progress evidence, retain the existing spinner/error presentation.
|
||||
expect(remote.result.current).toBeNull()
|
||||
expect(allHosts.result.current).toBeNull()
|
||||
})
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { SearchResult } from '../../../../../../shared/file-search/code-search-types'
|
||||
import { useFileSearchRunner } from './useFileSearchRunner'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getConnectionId: vi.fn(),
|
||||
getState: vi.fn(),
|
||||
searchRuntimeFiles: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/workspace/ownership/connection-context', () => ({
|
||||
getConnectionId: mocks.getConnectionId
|
||||
}))
|
||||
|
||||
vi.mock('@/runtime/files/search/runtime-file-search-client', () => ({
|
||||
searchRuntimeFiles: mocks.searchRuntimeFiles
|
||||
}))
|
||||
|
||||
vi.mock('@/store/index', () => ({
|
||||
useAppStore: Object.assign(
|
||||
vi.fn((selector: (state: ReturnType<typeof mocks.getState>) => unknown) =>
|
||||
selector(mocks.getState())
|
||||
),
|
||||
{ getState: mocks.getState }
|
||||
)
|
||||
}))
|
||||
|
||||
const RESULTS: SearchResult = {
|
||||
files: [],
|
||||
totalMatches: 0,
|
||||
truncated: false
|
||||
}
|
||||
|
||||
function renderSearchRunner(state: Record<string, unknown>, worktreeId: string) {
|
||||
const updates: Record<string, unknown>[] = []
|
||||
mocks.getState.mockImplementation(() => state)
|
||||
mocks.searchRuntimeFiles.mockResolvedValue(RESULTS)
|
||||
|
||||
const hook = renderHook(() =>
|
||||
useFileSearchRunner({
|
||||
activeWorktreeId: worktreeId,
|
||||
worktreePath: '/repo',
|
||||
updateActiveSearchState: (update) => updates.push(update)
|
||||
})
|
||||
)
|
||||
|
||||
return { hook, updates }
|
||||
}
|
||||
|
||||
async function finishSearch(executeSearch: (query: string) => void): Promise<void> {
|
||||
await act(async () => {
|
||||
executeSearch('owner')
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
})
|
||||
}
|
||||
|
||||
describe('useFileSearchRunner result ownership', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
mocks.getConnectionId.mockReturnValue(null)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('ignores an older rejection after a newer search has succeeded', async () => {
|
||||
const { hook, updates } = renderSearchRunner(
|
||||
{ settings: {}, repos: [], worktreesByRepo: {}, fileSearchStateByWorktree: {} },
|
||||
'missing-repo::/repo'
|
||||
)
|
||||
const log = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
let rejectOldSearch: (reason: Error) => void = () => {}
|
||||
mocks.searchRuntimeFiles.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((_resolve, reject) => {
|
||||
rejectOldSearch = reject
|
||||
})
|
||||
)
|
||||
await finishSearch(hook.result.current.executeSearch)
|
||||
await finishSearch(hook.result.current.executeSearch)
|
||||
await act(async () => rejectOldSearch(new Error('old failure')))
|
||||
expect(Object.assign({}, ...updates)).toMatchObject({
|
||||
error: null,
|
||||
results: RESULTS,
|
||||
loading: false
|
||||
})
|
||||
expect(updates.some((update) => update.error === 'old failure')).toBe(false)
|
||||
log.mockRestore()
|
||||
})
|
||||
})
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { DirEntry } from '../../../../../../shared/file-listing/directory-entry'
|
||||
|
||||
const readRuntimeDirectoryPage = vi.fn()
|
||||
const readRuntimeDirectory = vi.fn()
|
||||
let hostPages = true
|
||||
vi.mock('@/runtime/files/reads/runtime-directory-page-client', () => ({
|
||||
readRuntimeDirectoryPage: (...args: unknown[]) => readRuntimeDirectoryPage(...args),
|
||||
runtimeDirectoryPagesSupported: () => hostPages
|
||||
}))
|
||||
vi.mock('@/runtime/files/reads/runtime-directory-read', () => ({
|
||||
readRuntimeDirectory: (...args: unknown[]) => readRuntimeDirectory(...args)
|
||||
}))
|
||||
vi.mock('../navigation/file-explorer-operation-owner', () => ({
|
||||
getFileExplorerOperationOwner: () => ({ kind: 'local' }),
|
||||
getFileExplorerOperationRoute: () => ({ target: { kind: 'local' }, connectionId: null }),
|
||||
getFileExplorerOwnerUnresolvedMessage: () => 'unresolved'
|
||||
}))
|
||||
|
||||
import { appendFileExplorerDirPage } from './file-explorer-dir-pages'
|
||||
|
||||
import type { DirCache } from './file-explorer-types'
|
||||
|
||||
const file = (name: string): DirEntry => ({ name, isDirectory: false, isSymlink: false })
|
||||
const names = (count: number, from = 0): DirEntry[] =>
|
||||
Array.from({ length: count }, (_, index) => file(`f${String(from + index).padStart(5, '0')}`))
|
||||
|
||||
/** A host folder of `total` sorted files: refused whole past `wholeLimit`, served in pages. */
|
||||
|
||||
beforeEach(() => {
|
||||
readRuntimeDirectoryPage.mockReset()
|
||||
readRuntimeDirectory.mockReset()
|
||||
hostPages = true
|
||||
})
|
||||
|
||||
describe('paged folder listing', () => {
|
||||
it('appends a page in order, keeping a row the watcher already added once', () => {
|
||||
const owner = { kind: 'local' as const }
|
||||
const cache: DirCache = {
|
||||
children: [
|
||||
{ name: 'f00000', path: '/w/f00000', relativePath: 'f00000', isDirectory: false, depth: 0 },
|
||||
{ name: 'f00003', path: '/w/f00003', relativePath: 'f00003', isDirectory: false, depth: 0 }
|
||||
],
|
||||
operationOwner: owner,
|
||||
more: { after: { name: 'f00000', isDirectory: false } }
|
||||
}
|
||||
const appended = appendFileExplorerDirPage(
|
||||
cache,
|
||||
{ entries: names(3, 1), operationOwner: owner },
|
||||
'/w',
|
||||
-1,
|
||||
'/w'
|
||||
)
|
||||
expect(appended.children.map((child) => child.name)).toEqual([
|
||||
'f00000',
|
||||
'f00001',
|
||||
'f00002',
|
||||
'f00003'
|
||||
])
|
||||
expect(appended.more).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not extend rows with a page from another host', () => {
|
||||
const cache: DirCache = {
|
||||
children: [],
|
||||
operationOwner: { kind: 'local' },
|
||||
more: { after: { name: 'f00000', isDirectory: false } }
|
||||
}
|
||||
const appended = appendFileExplorerDirPage(
|
||||
cache,
|
||||
{ entries: names(1), operationOwner: { kind: 'ssh', connectionId: 'c' } },
|
||||
'/w',
|
||||
-1,
|
||||
'/w'
|
||||
)
|
||||
expect(appended).toEqual({ children: [], operationOwner: { kind: 'local' } })
|
||||
})
|
||||
})
|
||||
-83
@@ -1,83 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, cleanup, renderHook } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { useCreatePullRequestDialogFields } from './useCreatePullRequestDialogFields'
|
||||
import type { HostedReviewCreationEligibility } from '../../../../../../shared/source-control/hosted-review/hosted-review-contracts'
|
||||
import type { WorkspaceAttachmentMetadata } from '../../../../../../shared/workspace-attachments/workspace-attachment-legacy'
|
||||
|
||||
const workspace: WorkspaceAttachmentMetadata = {
|
||||
linkedWorkItem: {
|
||||
provider: 'jira',
|
||||
type: 'issue',
|
||||
number: 0,
|
||||
jiraIdentifier: 'team_alpha9-7',
|
||||
title: 'Restore login',
|
||||
url: 'https://jira.example.com/jira/browse/team_alpha9-7'
|
||||
}
|
||||
}
|
||||
const fields = {
|
||||
base: 'main',
|
||||
title: 'team_alpha9-7 TEAM_ALPHA9-7 Restore login',
|
||||
body: 'Generated body',
|
||||
draft: false
|
||||
}
|
||||
const revisions = { base: 0, title: 0, body: 0, draft: 0 }
|
||||
|
||||
function options(provider: 'github' | 'gitlab') {
|
||||
const eligibility: HostedReviewCreationEligibility = {
|
||||
provider,
|
||||
review: null,
|
||||
canCreate: true,
|
||||
blockedReason: null,
|
||||
nextAction: null,
|
||||
reviewLookupOutcome: 'not_found',
|
||||
defaultBaseRef: 'main',
|
||||
title: 'Restore login',
|
||||
body: 'Details'
|
||||
}
|
||||
return {
|
||||
open: true,
|
||||
repoId: 'repo-1',
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/repo/wt',
|
||||
branch: 'user/team_alpha9-7-restore-login',
|
||||
eligibility,
|
||||
settings: null,
|
||||
target: { kind: 'local' as const },
|
||||
submitting: false,
|
||||
workspace
|
||||
}
|
||||
}
|
||||
afterEach(cleanup)
|
||||
|
||||
describe('Jira review title ownership', () => {
|
||||
it('keeps a title edited during or before regeneration', () => {
|
||||
const { result } = renderHook(() => useCreatePullRequestDialogFields(options('gitlab')))
|
||||
act(() => {
|
||||
result.current.setTitle('My exact manual title')
|
||||
})
|
||||
act(() => {
|
||||
result.current.applyGeneratedFields(fields, revisions)
|
||||
})
|
||||
expect(result.current.title).toBe('My exact manual title')
|
||||
const laterRevisions = { ...result.current.fieldRevisions }
|
||||
act(() => {
|
||||
result.current.applyGeneratedFields(fields, laterRevisions)
|
||||
})
|
||||
expect(result.current.title).toBe('My exact manual title')
|
||||
expect(result.current.body).toBe('Generated body')
|
||||
})
|
||||
it('keeps a manual title when eligibility refreshes on the same branch', () => {
|
||||
const input = options('github')
|
||||
const { result, rerender } = renderHook(
|
||||
({ eligibility }) => useCreatePullRequestDialogFields({ ...input, eligibility }),
|
||||
{ initialProps: { eligibility: input.eligibility } }
|
||||
)
|
||||
act(() => {
|
||||
result.current.setTitle('Manual title')
|
||||
})
|
||||
rerender({ eligibility: { ...input.eligibility, title: 'Refreshed title' } })
|
||||
expect(result.current.title).toBe('Manual title')
|
||||
})
|
||||
})
|
||||
@@ -1,99 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { runCleanupMock, snapshotMock, toastErrorMock, toastInfoMock, toastSuccessMock } =
|
||||
vi.hoisted(() => ({
|
||||
runCleanupMock: vi.fn(),
|
||||
snapshotMock: vi.fn(),
|
||||
toastErrorMock: vi.fn(),
|
||||
toastInfoMock: vi.fn(),
|
||||
toastSuccessMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./kill-all-terminal-surfaces', () => ({
|
||||
runKillAllTerminalSurfaces: runCleanupMock,
|
||||
snapshotKillAllTerminalSurfaceIds: snapshotMock
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
error: toastErrorMock,
|
||||
info: toastInfoMock,
|
||||
success: toastSuccessMock,
|
||||
warning: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/i18n/i18n', () => ({
|
||||
translate: (_key: string, fallback: string) => fallback
|
||||
}))
|
||||
|
||||
import type { KillAllTerminalSurfacesSummary } from './kill-all-terminal-surfaces'
|
||||
import { useDaemonActions } from './useDaemonActions'
|
||||
|
||||
function rejectedSummary(): KillAllTerminalSurfacesSummary {
|
||||
return {
|
||||
targetCount: 1,
|
||||
closeAttemptCount: 1,
|
||||
absentTargetCount: 1,
|
||||
failedCloseAttemptCount: 0,
|
||||
exactKillAcceptedCount: 1,
|
||||
exactKillRejectedCount: 0,
|
||||
closeDurationMs: 1,
|
||||
maxCloseBatchDurationMs: 1,
|
||||
closeYieldCount: 0,
|
||||
closePhaseExceededLongTaskBudget: false,
|
||||
daemon: { status: 'rejected' }
|
||||
}
|
||||
}
|
||||
|
||||
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>((resolvePromise) => {
|
||||
resolve = resolvePromise
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
describe('useDaemonActions kill-all cleanup', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
snapshotMock.mockReturnValue(['confirmed-tab'])
|
||||
})
|
||||
|
||||
it('snapshots before start and does not revoke cleanup when the caller unmounts', async () => {
|
||||
const cleanup = deferred<KillAllTerminalSurfacesSummary>()
|
||||
const sequence: string[] = []
|
||||
const onKillAllStart = vi.fn(() => sequence.push('start'))
|
||||
const onKillAllError = vi.fn()
|
||||
const onKillAllSettled = vi.fn()
|
||||
snapshotMock.mockImplementation(() => {
|
||||
sequence.push('snapshot')
|
||||
return ['confirmed-tab']
|
||||
})
|
||||
runCleanupMock.mockImplementation(() => {
|
||||
sequence.push('cleanup')
|
||||
return cleanup.promise
|
||||
})
|
||||
const { result, unmount } = renderHook(() =>
|
||||
useDaemonActions({ onKillAllStart, onKillAllError, onKillAllSettled })
|
||||
)
|
||||
|
||||
let completion!: Promise<void>
|
||||
act(() => {
|
||||
completion = result.current.runKillAll()
|
||||
})
|
||||
|
||||
expect(sequence).toEqual(['snapshot', 'start', 'cleanup'])
|
||||
expect(runCleanupMock).toHaveBeenCalledWith(['confirmed-tab'])
|
||||
unmount()
|
||||
cleanup.resolve(rejectedSummary())
|
||||
await completion
|
||||
|
||||
expect(toastErrorMock).toHaveBeenCalledTimes(1)
|
||||
expect(onKillAllError).not.toHaveBeenCalled()
|
||||
expect(onKillAllSettled).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useAppStore } from '@/store'
|
||||
import type { Repo } from '../../../../../../shared/repo-types'
|
||||
import type { Worktree, WorkspaceAttachment } from '../../../../../../shared/worktree/types'
|
||||
|
||||
import WorktreeMetaDialog from './WorktreeMetaDialog'
|
||||
|
||||
vi.mock('./WorktreeDisplayNameField', () => ({ WorktreeDisplayNameField: () => null }))
|
||||
vi.mock('./WorktreeLinkedItemsField', () => ({
|
||||
WorktreeLinkedItemsField: ({ items, repo }: { items: WorkspaceAttachment[]; repo?: Repo }) => (
|
||||
<div>
|
||||
<span data-testid="owner-repo">{repo?.path ?? 'none'}</span>
|
||||
{items.map((item) => (
|
||||
<span key={item.number}>{item.title}</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}))
|
||||
|
||||
const initialState = useAppStore.getInitialState()
|
||||
const update = vi.fn(async () => ({ ok: true as const }))
|
||||
const localRepo: Repo = {
|
||||
id: 'repo',
|
||||
path: '/local',
|
||||
displayName: 'Local',
|
||||
badgeColor: '',
|
||||
addedAt: 1
|
||||
}
|
||||
const remoteRepo: Repo = { ...localRepo, path: '/remote', executionHostId: 'ssh:box' }
|
||||
function workspace(hostId?: Worktree['hostId']): Worktree {
|
||||
return {
|
||||
id: 'shared-id',
|
||||
repoId: 'repo',
|
||||
path: '/workspace',
|
||||
branch: 'feature',
|
||||
head: 'abc',
|
||||
isBare: false,
|
||||
isMainWorktree: false,
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 1,
|
||||
displayName: 'Workspace',
|
||||
comment: 'note',
|
||||
hostId,
|
||||
linkedPR: null,
|
||||
linkedIssue: null,
|
||||
linkedLinearIssue: null,
|
||||
linkedItems: [
|
||||
{
|
||||
provider: 'github',
|
||||
type: 'issue',
|
||||
number: hostId ? 2 : 1,
|
||||
title: hostId ? 'Remote task' : 'Local task'
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
function open(
|
||||
executionHostId: string,
|
||||
rows: Worktree[] = [workspace(), workspace('ssh:box')],
|
||||
repos: Repo[] = [localRepo, remoteRepo]
|
||||
): void {
|
||||
useAppStore.setState({
|
||||
repos,
|
||||
worktreesByRepo: { repo: rows },
|
||||
updateWorktreeMeta: update,
|
||||
activeModal: 'edit-meta',
|
||||
modalData: { worktreeId: 'shared-id', repoId: 'repo', executionHostId }
|
||||
})
|
||||
render(<WorktreeMetaDialog />)
|
||||
}
|
||||
|
||||
describe('workspace details exact host selection', () => {
|
||||
beforeEach(() => {
|
||||
useAppStore.setState(initialState, true)
|
||||
update.mockClear()
|
||||
})
|
||||
afterEach(cleanup)
|
||||
|
||||
it('does not fall back to another host when the requested workspace disappeared', () => {
|
||||
open('ssh:missing', [workspace()])
|
||||
expect(screen.getByTestId('owner-repo').textContent).toBe('none')
|
||||
expect(screen.queryByText('Local task')).toBeNull()
|
||||
const save = screen.getByRole('button', { name: 'Save' })
|
||||
expect(save.hasAttribute('disabled')).toBe(true)
|
||||
fireEvent.click(save)
|
||||
expect(update).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
deferHiddenAgentResume,
|
||||
noteHiddenAgentResumePtyEnded
|
||||
} from './hidden-agent-resume-deferral'
|
||||
import type { ColdRestoreAgentResumeStartup } from '../startup/fresh-spawn-types'
|
||||
import type { ConnectPanePtySession } from '../connect-pane-pty-session'
|
||||
|
||||
const wakeRequests = vi.hoisted(() => ({ take: vi.fn(() => false) }))
|
||||
vi.mock('@/lib/agent-session/resume/sleeping-agent-wake-requests', () => ({
|
||||
takeSleepingAgentWakeRequest: wakeRequests.take
|
||||
}))
|
||||
vi.mock('../reattach/deferred-session-reattach-connect', () => ({
|
||||
startDeferredSessionReattach: vi.fn()
|
||||
}))
|
||||
|
||||
function hiddenPaneSession(): ConnectPanePtySession {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deferHiddenAgentResume reads only these session members.
|
||||
return {
|
||||
disposed: false,
|
||||
cacheKey: 'tab-1:leaf-1',
|
||||
deps: { isVisibleRef: { current: false } },
|
||||
transport: { getPtyId: () => null },
|
||||
hibernatedWakeTarget: null,
|
||||
hibernatedWakeInFlightClaimKey: null,
|
||||
wakeHibernatedAgentPane: () => Promise.resolve('pty-1')
|
||||
} as unknown as ConnectPanePtySession
|
||||
}
|
||||
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deferHiddenAgentResume reads only the record entry.
|
||||
const startup = {
|
||||
sleepingRecordEntry: { paneKey: 'tab-1:leaf-1', record: { paneKey: 'tab-1:leaf-1' } }
|
||||
} as unknown as ColdRestoreAgentResumeStartup
|
||||
|
||||
describe('deferHiddenAgentResume', () => {
|
||||
it('holds again once a pane a background wake released has gone back to sleep', () => {
|
||||
const session = hiddenPaneSession()
|
||||
wakeRequests.take.mockReturnValueOnce(true)
|
||||
|
||||
expect(deferHiddenAgentResume(session, startup)).toBe(false)
|
||||
// A fallback in the same connect keeps the background wake's release.
|
||||
expect(deferHiddenAgentResume(session, startup)).toBe(false)
|
||||
|
||||
noteHiddenAgentResumePtyEnded(session)
|
||||
expect(deferHiddenAgentResume(session, startup)).toBe(true)
|
||||
})
|
||||
|
||||
it('releases the hold under a record key the pane no longer holds', async () => {
|
||||
const { isPaneSpawnDeferred } =
|
||||
await import('@/components/terminal-pane/session-restore/spawn-deferral/pane-spawn-deferral-registry')
|
||||
const session = hiddenPaneSession()
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deferHiddenAgentResume reads only the record entry.
|
||||
const legacyStartup = {
|
||||
sleepingRecordEntry: { paneKey: 'tab-1:2', record: { paneKey: 'tab-1:2' } }
|
||||
} as unknown as ColdRestoreAgentResumeStartup
|
||||
|
||||
expect(deferHiddenAgentResume(session, legacyStartup)).toBe(true)
|
||||
expect(isPaneSpawnDeferred('tab-1:2')).toBe(true)
|
||||
expect(deferHiddenAgentResume(session, startup)).toBe(true)
|
||||
|
||||
expect(isPaneSpawnDeferred('tab-1:2')).toBe(false)
|
||||
expect(isPaneSpawnDeferred('tab-1:leaf-1')).toBe(true)
|
||||
})
|
||||
})
|
||||
-87
@@ -1,87 +0,0 @@
|
||||
import type { AiVaultResumePlatformState } from './ai-vault-resume-platform'
|
||||
import { getDefaultSettings } from '../../../../../../shared/constants'
|
||||
import { TEST_REPO } from '../../../../store/repos/repo.test-fixture'
|
||||
import { makeWorktree } from '../../../../store/slices/worktrees/worktree.test-fixture'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { buildAiVaultDropRepinStartup } from './ai-vault-resume-command'
|
||||
|
||||
vi.mock('@/lib/workspace/creation/new-workspace', () => ({
|
||||
CLIENT_PLATFORM: 'darwin'
|
||||
}))
|
||||
|
||||
const RECORDED_HOME = '/tmp/orca/codex-accounts/aaaa/home'
|
||||
const SELECTED_HOME = '/tmp/orca/codex-accounts/bbbb/home'
|
||||
|
||||
function makeState(): AiVaultResumePlatformState {
|
||||
return {
|
||||
activeRepoId: 'repo-1',
|
||||
activeWorktreeId: 'repo-1::worktree-1',
|
||||
detectedWorktreesByRepo: {},
|
||||
sshConnectionStates: new Map(),
|
||||
sshStateByEnvironment: new Map(),
|
||||
runtimeStatusByEnvironmentId: new Map(),
|
||||
folderWorkspaces: [],
|
||||
projectGroups: [],
|
||||
repos: [{ ...TEST_REPO, id: 'repo-1', path: '/Users/ada/repo' }],
|
||||
projects: [
|
||||
{
|
||||
displayName: 'repo',
|
||||
badgeColor: '',
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
id: 'repo-1',
|
||||
sourceRepoIds: ['repo-1']
|
||||
}
|
||||
],
|
||||
settings: {
|
||||
...getDefaultSettings('/tmp'),
|
||||
agentDefaultArgs: { claude: '', codex: '' },
|
||||
agentDefaultEnv: { claude: {}, codex: {} }
|
||||
},
|
||||
worktreesByRepo: {
|
||||
'repo-1': [
|
||||
makeWorktree({ id: 'repo-1::worktree-1', repoId: 'repo-1', path: '/Users/ada/repo' })
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function payload(overrides: {
|
||||
sessionCwd?: string | null
|
||||
sessionFilePath?: string
|
||||
}): Parameters<typeof buildAiVaultDropRepinStartup>[0]['payload'] {
|
||||
return {
|
||||
agent: 'codex',
|
||||
sessionId: 'session-1',
|
||||
sessionExecutionHostId: 'local',
|
||||
sessionFilePath: `${RECORDED_HOME}/sessions/2026/07/20/rollout-x.jsonl`,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('buildAiVaultDropRepinStartup', () => {
|
||||
it('repins a payload whose session has no cwd instead of keeping the wrong-account command', () => {
|
||||
const startup = buildAiVaultDropRepinStartup({
|
||||
state: makeState(),
|
||||
payload: payload({ sessionCwd: null }),
|
||||
substituteCodexHome: SELECTED_HOME,
|
||||
worktreeId: 'repo-1::worktree-1'
|
||||
})
|
||||
|
||||
expect(startup).not.toBeNull()
|
||||
expect(startup?.command).toContain(`CODEX_HOME='${SELECTED_HOME}'`)
|
||||
expect(startup?.command).not.toContain(RECORDED_HOME)
|
||||
expect(startup?.command).not.toContain('cd ')
|
||||
})
|
||||
|
||||
it('declines a payload from an older serializer that never carried sessionCwd', () => {
|
||||
const startup = buildAiVaultDropRepinStartup({
|
||||
state: makeState(),
|
||||
payload: payload({}),
|
||||
substituteCodexHome: SELECTED_HOME,
|
||||
worktreeId: 'repo-1::worktree-1'
|
||||
})
|
||||
|
||||
expect(startup).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,93 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { AppState } from '@/store/types'
|
||||
import { getAiVaultResumeWorkspaceTargetStatus } from './ai-vault-resume-target'
|
||||
import { folderWorkspaceKey } from '../../../../../../shared/workspace-scope'
|
||||
|
||||
type ResumeTargetState = Pick<
|
||||
AppState,
|
||||
'folderWorkspaces' | 'projectGroups' | 'repos' | 'worktreesByRepo'
|
||||
>
|
||||
|
||||
function makeState(
|
||||
overrides: Partial<Record<keyof ResumeTargetState, unknown>>
|
||||
): ResumeTargetState {
|
||||
return {
|
||||
folderWorkspaces: [],
|
||||
projectGroups: [],
|
||||
repos: [],
|
||||
worktreesByRepo: {},
|
||||
...overrides
|
||||
} as unknown as ResumeTargetState
|
||||
}
|
||||
|
||||
describe('ai vault resume target ownership', () => {
|
||||
it('uses the composite worktree repo id when worktree discovery is incomplete', () => {
|
||||
expect(
|
||||
getAiVaultResumeWorkspaceTargetStatus(
|
||||
makeState({
|
||||
repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'runtime:env-1' }]
|
||||
}),
|
||||
'repo-1::/repo/orca'
|
||||
)
|
||||
).toBe('runtime')
|
||||
})
|
||||
|
||||
it('resolves explicit workspace keys through the target worktree host', () => {
|
||||
expect(
|
||||
getAiVaultResumeWorkspaceTargetStatus(
|
||||
makeState({
|
||||
worktreesByRepo: {
|
||||
'repo-1': [{ id: 'repo-1::/repo/orca', repoId: 'repo-1', hostId: 'runtime:env-1' }]
|
||||
},
|
||||
repos: [{ id: 'repo-1', connectionId: 'ssh-1', executionHostId: 'ssh:ssh-1' }]
|
||||
}),
|
||||
'worktree:repo-1::/repo/orca'
|
||||
)
|
||||
).toBe('runtime')
|
||||
})
|
||||
|
||||
it('prefers runtime project-group ownership over stale SSH folder connection ids', () => {
|
||||
expect(
|
||||
getAiVaultResumeWorkspaceTargetStatus(
|
||||
makeState({
|
||||
folderWorkspaces: [
|
||||
{
|
||||
id: 'folder-1',
|
||||
projectGroupId: 'group-1',
|
||||
name: 'Platform',
|
||||
folderPath: '/repo/platform',
|
||||
connectionId: 'ssh-1'
|
||||
}
|
||||
],
|
||||
projectGroups: [
|
||||
{ id: 'group-1', connectionId: 'ssh-1', executionHostId: 'runtime:env-1' }
|
||||
]
|
||||
}),
|
||||
folderWorkspaceKey('folder-1')
|
||||
)
|
||||
).toBe('runtime')
|
||||
})
|
||||
|
||||
it('treats mixed local and SSH folder workspace targets as unknown', () => {
|
||||
expect(
|
||||
getAiVaultResumeWorkspaceTargetStatus(
|
||||
makeState({
|
||||
folderWorkspaces: [
|
||||
{
|
||||
id: 'folder-1',
|
||||
projectGroupId: 'group-1',
|
||||
name: 'Platform',
|
||||
folderPath: '/repo/platform'
|
||||
}
|
||||
],
|
||||
projectGroups: [{ id: 'group-1' }],
|
||||
repos: [
|
||||
{ id: 'repo-local', path: '/repo/platform/web', connectionId: null },
|
||||
{ id: 'repo-ssh', path: '/repo/platform/api', connectionId: 'ssh-1' }
|
||||
]
|
||||
}),
|
||||
folderWorkspaceKey('folder-1')
|
||||
)
|
||||
).toBe('unknown')
|
||||
})
|
||||
})
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
|
||||
const admit = vi.hoisted(() => vi.fn())
|
||||
vi.mock('sonner', () => ({ toast: { info: vi.fn(), error: vi.fn() } }))
|
||||
vi.mock('@/lib/agent-session/launch/structured-agent-session-host-admission', () => ({
|
||||
admitStructuredLaunchOnHost: admit
|
||||
}))
|
||||
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { activateAndRevealWorktree } from './worktree-activation'
|
||||
import * as activationGate from './worktree-agent-activation-gate'
|
||||
import {
|
||||
makeCreatedAgentWorktree as makeWorktree,
|
||||
seedEmptyActivatableWorktree
|
||||
} from './worktree-activation-created-agent.test-fixture'
|
||||
import { registerWorktreeActivationReset } from './worktree-activation.test-fixture'
|
||||
import { beginHostAdmittedStructuredLaunch } from '../../agent-session/launch/structured-agent-session-launch-admission'
|
||||
import { adoptAgentSessionLaunchVerdict } from '../../agent-session/launch/routing/agent-session-launch-plan'
|
||||
import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host'
|
||||
|
||||
const initial = useAppStore.getState()
|
||||
registerWorktreeActivationReset()
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
useAppStore.setState(initial, true)
|
||||
})
|
||||
|
||||
// Clicking the still-empty workspace while its chat waits on this machine used to seed
|
||||
// "Terminal 1" beside the chat, through the activation's reseed rather than the watcher.
|
||||
it('does not seed a shell when the workspace is re-activated while its chat waits on its host', async () => {
|
||||
const worktree = makeWorktree()
|
||||
seedEmptyActivatableWorktree(worktree)
|
||||
vi.stubGlobal('window', { api: { runtime: { call: vi.fn() }, pty: { listSessions: vi.fn() } } })
|
||||
const gate = vi.spyOn(activationGate, 'gateWorktreeAgentActivation').mockResolvedValue('empty')
|
||||
let answer!: (admission: { kind: 'admitted' }) => void
|
||||
admit.mockReturnValue(new Promise((resolve) => (answer = resolve)))
|
||||
const openAdmitted = vi.fn(() => ({ settlement: new Promise<never>(() => {}), cancel: vi.fn() }))
|
||||
beginHostAdmittedStructuredLaunch({
|
||||
plan: {
|
||||
...adoptAgentSessionLaunchVerdict({
|
||||
route: 'structured-native-chat',
|
||||
requestId: 'request-1',
|
||||
agent: 'claude',
|
||||
worktreeId: worktree.id
|
||||
}),
|
||||
agent: 'claude'
|
||||
},
|
||||
hooks: {},
|
||||
worktreeId: worktree.id,
|
||||
executionHostId: LOCAL_EXECUTION_HOST_ID,
|
||||
target: { kind: 'local' },
|
||||
openAdmitted,
|
||||
onHostDeclined: () => ({ opened: true })
|
||||
})
|
||||
|
||||
activateAndRevealWorktree(worktree.id, { notifyHostRuntime: false })
|
||||
await gate.mock.results[0]?.value
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
expect(useAppStore.getState().tabsByWorktree[worktree.id] ?? []).toEqual([])
|
||||
|
||||
answer({ kind: 'admitted' })
|
||||
await vi.waitFor(() => expect(openAdmitted).toHaveBeenCalledOnce())
|
||||
expect(useAppStore.getState().tabsByWorktree[worktree.id] ?? []).toEqual([])
|
||||
})
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
TerminalStreamOpcode,
|
||||
decodeTerminalStreamFrame,
|
||||
decodeTerminalStreamJson
|
||||
} from '../../../../../shared/terminal/stream/terminal-stream-protocol'
|
||||
import {
|
||||
getRemoteRuntimeTerminalMultiplexer,
|
||||
resetRemoteRuntimeTerminalMultiplexersForTests
|
||||
} from './registry/remote-runtime-terminal-multiplexer-registry'
|
||||
import { replaceRuntimeEnvironmentRevisions } from '../../rpc/environment-revisions/runtime-environment-revision'
|
||||
import { stubRuntimeEnvironmentBridge } from '../../rpc/testing/runtime-environment-bridge-fixture'
|
||||
|
||||
type SubscribeCallbacks = { onResponse: (response: unknown) => void }
|
||||
|
||||
// Why: hosts that predate opcode 20 reject it, so the client may send it only after the capability echo.
|
||||
describe('remote terminal output cadence negotiation', () => {
|
||||
let hostCapabilities: Record<string, 1>
|
||||
let cadenceFrames: unknown[]
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetRemoteRuntimeTerminalMultiplexersForTests()
|
||||
replaceRuntimeEnvironmentRevisions([])
|
||||
cadenceFrames = []
|
||||
const subscribe = vi.fn(async (_args: unknown, next: SubscribeCallbacks) => {
|
||||
queueMicrotask(() => next.onResponse({ ok: true, result: { type: 'ready' } }))
|
||||
return {
|
||||
unsubscribe: vi.fn(),
|
||||
sendBinary: (bytes: Uint8Array<ArrayBufferLike>) => {
|
||||
const frame = decodeTerminalStreamFrame(bytes)
|
||||
if (frame?.opcode === TerminalStreamOpcode.Subscribe) {
|
||||
const payload = decodeTerminalStreamJson<{ streamId: number }>(frame.payload)
|
||||
next.onResponse({
|
||||
ok: true,
|
||||
result: {
|
||||
type: 'subscribed',
|
||||
streamId: payload?.streamId ?? 0,
|
||||
capabilities: hostCapabilities
|
||||
}
|
||||
})
|
||||
} else if (frame?.opcode === TerminalStreamOpcode.SetOutputCadence) {
|
||||
cadenceFrames.push(decodeTerminalStreamJson(frame.payload))
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
stubRuntimeEnvironmentBridge({ subscribe })
|
||||
})
|
||||
|
||||
async function subscribeAndBackground(): Promise<void> {
|
||||
const stream = await getRemoteRuntimeTerminalMultiplexer('env-1').subscribeTerminal({
|
||||
terminal: 'terminal-1',
|
||||
client: { id: 'desktop-1', type: 'desktop' },
|
||||
outputCadence: 'focused',
|
||||
callbacks: { onData: () => {}, onSnapshot: () => {} }
|
||||
})
|
||||
stream.setOutputCadence('background')
|
||||
}
|
||||
|
||||
it('never sends a cadence frame to a host that did not echo the capability', async () => {
|
||||
hostCapabilities = { outputPause: 1 }
|
||||
await subscribeAndBackground()
|
||||
expect(cadenceFrames).toEqual([])
|
||||
})
|
||||
|
||||
it('sends the cadence to a host that echoed the capability', async () => {
|
||||
hostCapabilities = { outputPause: 1, outputCadence: 1 }
|
||||
await subscribeAndBackground()
|
||||
expect(cadenceFrames).toEqual([{ cadence: 'background' }])
|
||||
})
|
||||
})
|
||||
-96
@@ -1,96 +0,0 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import type { RuntimeMobileSessionFileTab } from '../../../../../shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts'
|
||||
import type { OpenFile } from '../../../store/slices/editor/types/open-file'
|
||||
import { applyWebSessionTabsSnapshot } from '../snapshot-api'
|
||||
import {
|
||||
ENV,
|
||||
NOW,
|
||||
WT,
|
||||
makeSnapshot,
|
||||
makeState,
|
||||
resetWebSessionTabsSyncTestState
|
||||
} from '../testing/web-session-tabs-sync.test-fixture'
|
||||
|
||||
const filePath = '/repo/readme.txt'
|
||||
const hostTab: RuntimeMobileSessionFileTab = {
|
||||
type: 'file',
|
||||
id: 'retained-tab',
|
||||
title: 'readme.txt',
|
||||
filePath,
|
||||
relativePath: 'readme.txt',
|
||||
language: 'plaintext',
|
||||
isDirty: false,
|
||||
isActive: true
|
||||
}
|
||||
function file(overrides: Partial<OpenFile> = {}): OpenFile {
|
||||
return {
|
||||
id: filePath,
|
||||
filePath,
|
||||
relativePath: 'readme.txt',
|
||||
worktreeId: WT,
|
||||
language: 'plaintext',
|
||||
isDirty: false,
|
||||
runtimeEnvironmentId: null,
|
||||
mode: 'edit',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
function snapshot(tabs = [hostTab]) {
|
||||
return makeSnapshot(tabs, { activeTabId: hostTab.id, activeTabType: 'file' })
|
||||
}
|
||||
|
||||
describe('host editor file ownership', () => {
|
||||
beforeEach(resetWebSessionTabsSyncTestState)
|
||||
|
||||
it('shares a pending retained file with a newly published split listed first', () => {
|
||||
const retained = file({ isDirty: true, pendingOwnerMigration: true })
|
||||
const state = makeState({
|
||||
openFiles: [retained],
|
||||
unifiedTabsByWorktree: {
|
||||
[WT]: [
|
||||
{
|
||||
id: hostTab.id,
|
||||
entityId: retained.id,
|
||||
worktreeId: WT,
|
||||
groupId: 'legacy-group',
|
||||
executionHostId: 'ssh:legacy-target',
|
||||
contentType: 'editor',
|
||||
label: 'readme.txt',
|
||||
customLabel: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: NOW,
|
||||
isPreview: false
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
const patch = applyWebSessionTabsSnapshot(
|
||||
state,
|
||||
snapshot([{ ...hostTab, id: 'new-split', isActive: false }, hostTab]),
|
||||
ENV,
|
||||
NOW
|
||||
)
|
||||
expect(patch.openFiles ?? state.openFiles).toEqual([retained])
|
||||
expect(patch.unifiedTabsByWorktree?.[WT]?.map((tab) => tab.entityId)).toEqual([
|
||||
retained.id,
|
||||
retained.id
|
||||
])
|
||||
})
|
||||
|
||||
it('does not borrow another host’s disk signature or overwrite its file ID', () => {
|
||||
const other = file({ runtimeEnvironmentId: 'other-host', lastKnownDiskSignature: 'other-disk' })
|
||||
const patch = applyWebSessionTabsSnapshot(
|
||||
makeState({ openFiles: [other] }),
|
||||
snapshot(),
|
||||
ENV,
|
||||
NOW
|
||||
)
|
||||
expect(patch?.openFiles).toHaveLength(2)
|
||||
expect(patch?.openFiles?.[0]).toBe(other)
|
||||
expect(patch?.openFiles?.[1]).toMatchObject({
|
||||
runtimeEnvironmentId: ENV
|
||||
})
|
||||
expect(patch?.openFiles?.[1]?.lastKnownDiskSignature).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -1,79 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { getDefaultBrowserProfileForHost } from '../hosts/browser-host-state'
|
||||
import {
|
||||
createBrowserMockApi,
|
||||
createTestStore,
|
||||
resetBrowserRuntimeMocks
|
||||
} from '../browser-slice-test-harness'
|
||||
|
||||
const createWebRuntimeSessionBrowserTabMock = vi.hoisted(() => vi.fn())
|
||||
const runtimeEnvironmentCall = vi.fn()
|
||||
const runtimeEnvironmentTransportCall = vi.fn()
|
||||
|
||||
vi.mock('@/runtime/browser/creation/web-runtime-browser-creation', () => ({
|
||||
createWebRuntimeSessionBrowserTab: createWebRuntimeSessionBrowserTabMock
|
||||
}))
|
||||
|
||||
const mockApi = createBrowserMockApi(runtimeEnvironmentTransportCall)
|
||||
|
||||
// @ts-expect-error test window mock
|
||||
globalThis.window = { api: mockApi }
|
||||
|
||||
describe('createBrowserSlice runtime guard', () => {
|
||||
beforeEach(() => {
|
||||
resetBrowserRuntimeMocks({
|
||||
runtimeEnvironmentCall,
|
||||
runtimeEnvironmentTransportCall,
|
||||
createWebRuntimeSessionBrowserTabMock
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('drops the default profile pick once a refreshed list no longer has it', async () => {
|
||||
const store = createTestStore()
|
||||
const listed = (id: string) => ({
|
||||
id,
|
||||
scope: id === 'default' ? ('default' as const) : ('isolated' as const),
|
||||
partition: `persist:${id}`,
|
||||
label: id,
|
||||
source: null
|
||||
})
|
||||
await store.getState().setDefaultBrowserSessionProfileId('work')
|
||||
expect(store.getState().settings?.browserDefaultProfileIdByHostId).toEqual({ local: 'work' })
|
||||
mockApi.browser.sessionListProfiles
|
||||
.mockResolvedValueOnce([listed('default'), listed('work')])
|
||||
.mockResolvedValueOnce([listed('default')])
|
||||
|
||||
await store.getState().fetchBrowserSessionProfiles('local')
|
||||
expect(getDefaultBrowserProfileForHost(store.getState(), 'local')).toBe('work')
|
||||
|
||||
await store.getState().fetchBrowserSessionProfiles('local')
|
||||
expect(getDefaultBrowserProfileForHost(store.getState(), 'local')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the newest listing when an older one answers last', async () => {
|
||||
const store = createTestStore()
|
||||
const listed = (id: string) => ({
|
||||
id,
|
||||
scope: id === 'default' ? ('default' as const) : ('isolated' as const),
|
||||
partition: `persist:${id}`,
|
||||
label: id,
|
||||
source: null
|
||||
})
|
||||
const older = Promise.withResolvers<ReturnType<typeof listed>[]>()
|
||||
mockApi.browser.sessionListProfiles
|
||||
.mockReturnValueOnce(older.promise)
|
||||
.mockResolvedValueOnce([listed('default')])
|
||||
|
||||
const olderFetch = store.getState().fetchBrowserSessionProfiles('local')
|
||||
await store.getState().fetchBrowserSessionProfiles('local')
|
||||
older.resolve([listed('default'), listed('deleted')])
|
||||
await olderFetch
|
||||
|
||||
expect(store.getState().browserSessionProfilesByHostId.local).toEqual([listed('default')])
|
||||
})
|
||||
})
|
||||
@@ -1,78 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { createEditorTabsStore } from '../editor-slice-test-harness'
|
||||
|
||||
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) =>
|
||||
(
|
||||
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
|
||||
).runtimeRpcClientWithLayoutApply(await importOriginal())
|
||||
)
|
||||
vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) =>
|
||||
(
|
||||
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
|
||||
).runtimeLayoutClientWithTestFrames(await importOriginal())
|
||||
)
|
||||
|
||||
const { toastErrorMock } = vi.hoisted(() => ({
|
||||
toastErrorMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: { error: toastErrorMock }
|
||||
}))
|
||||
|
||||
const { notifyHostOfMirroredEditorCloseMock } = vi.hoisted(() => ({
|
||||
notifyHostOfMirroredEditorCloseMock: vi.fn()
|
||||
}))
|
||||
vi.mock('@/runtime/web-session-tabs-sync/closing/close-mirrored-editor-tab', () => ({
|
||||
notifyHostOfMirroredEditorClose: (...args: unknown[]) =>
|
||||
notifyHostOfMirroredEditorCloseMock(...args)
|
||||
}))
|
||||
|
||||
describe('createEditorSlice recently closed editor tabs', () => {
|
||||
it('restores the exact same-path owner instead of moving the local editor', () => {
|
||||
const store = createEditorTabsStore()
|
||||
const localId = store.getState().openFile({
|
||||
filePath: '/repo/notes.md',
|
||||
relativePath: 'notes.md',
|
||||
worktreeId: 'wt-1',
|
||||
language: 'markdown',
|
||||
mode: 'edit'
|
||||
})
|
||||
const remoteId = store.getState().openFile({
|
||||
filePath: '/repo/notes.md',
|
||||
relativePath: 'notes.md',
|
||||
worktreeId: 'wt-1',
|
||||
language: 'markdown',
|
||||
runtimeEnvironmentId: 'env-1',
|
||||
mode: 'edit'
|
||||
})
|
||||
store.getState().setTabBarOrder('wt-1', [localId, remoteId])
|
||||
|
||||
store.getState().closeFile(remoteId)
|
||||
expect(store.getState().reopenClosedEditorTab('wt-1')).toBe(true)
|
||||
|
||||
const openIds = store.getState().openFiles.map((file) => file.id)
|
||||
expect(openIds).toEqual([localId, remoteId])
|
||||
expect(store.getState().tabBarOrderByWorktree['wt-1']).toEqual([localId, remoteId])
|
||||
})
|
||||
|
||||
it('keeps same-path edit and diff tabs as separate entities on reopen', () => {
|
||||
const store = createEditorTabsStore()
|
||||
const editId = store.getState().openFile({
|
||||
filePath: '/repo/notes.md',
|
||||
relativePath: 'notes.md',
|
||||
worktreeId: 'wt-1',
|
||||
language: 'markdown',
|
||||
mode: 'edit'
|
||||
})
|
||||
store.getState().openDiff('wt-1', '/repo/notes.md', 'notes.md', 'markdown', false)
|
||||
const diffId = 'wt-1::diff::unstaged::notes.md'
|
||||
store.getState().setTabBarOrder('wt-1', [editId, diffId])
|
||||
|
||||
store.getState().closeFile(diffId)
|
||||
expect(store.getState().reopenClosedEditorTab('wt-1')).toBe(true)
|
||||
|
||||
expect(store.getState().openFiles.map((file) => file.id)).toEqual([editId, diffId])
|
||||
expect(store.getState().tabBarOrderByWorktree['wt-1']).toEqual([editId, diffId])
|
||||
})
|
||||
})
|
||||
-103
@@ -1,103 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation'
|
||||
import {
|
||||
createTestStore,
|
||||
resetRemoteRuntimeMocks,
|
||||
resetWorktreeSliceModuleMemory
|
||||
} from '../worktrees-slice-test-harness'
|
||||
|
||||
const requestWorktreeBaseFallbackNotice = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
dismiss: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/components/worktree-base-fallback-notice', () => ({
|
||||
requestWorktreeBaseFallbackNotice
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
resetWorktreeSliceModuleMemory()
|
||||
})
|
||||
|
||||
function makePendingCreation(
|
||||
creationId: string,
|
||||
overrides: Partial<PendingWorktreeCreation> = {}
|
||||
): PendingWorktreeCreation {
|
||||
return {
|
||||
creationId,
|
||||
phase: 'fetching',
|
||||
status: 'creating',
|
||||
startedAt: 1000,
|
||||
indeterminate: false,
|
||||
loaderVisible: false,
|
||||
request: {
|
||||
repoId: 'repo1',
|
||||
name: 'feature',
|
||||
setupDecision: 'inherit',
|
||||
agent: null,
|
||||
pendingFirstAgentMessageRename: false,
|
||||
note: '',
|
||||
startupPlan: null,
|
||||
quickPrompt: '',
|
||||
quickTelemetry: null
|
||||
},
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('pending worktree creation state', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetRemoteRuntimeMocks()
|
||||
})
|
||||
|
||||
it('keeps composer picks when stale preparation lands with prior chat options', () => {
|
||||
const store = createTestStore()
|
||||
const request = {
|
||||
...makePendingCreation('c1').request,
|
||||
agent: 'codex' as const,
|
||||
launchInputs: {
|
||||
sessionOptions: { effort: 'high', permissionMode: 'ask' },
|
||||
chatSessionOptions: { effort: 'high' }
|
||||
}
|
||||
}
|
||||
store.getState().beginPendingWorktreeCreation(makePendingCreation('c1', { request }))
|
||||
store.getState().updatePendingWorktreeCreation('c1', {
|
||||
chatSessionOptions: { effort: 'low' }
|
||||
})
|
||||
store.getState().updatePendingWorktreeCreation('c1', {
|
||||
chatSessionOptions: { fastMode: 'true' }
|
||||
})
|
||||
|
||||
store.getState().updatePendingWorktreeCreation('c1', {
|
||||
request: {
|
||||
...request,
|
||||
setupDecision: 'skip',
|
||||
hookPreparation: undefined,
|
||||
executionHostId: 'runtime:host-1',
|
||||
launchInputs: { ...request.launchInputs, agentArgs: '--sandbox workspace-write' }
|
||||
},
|
||||
phase: 'creating'
|
||||
})
|
||||
|
||||
const current = store.getState().pendingWorktreeCreations.c1
|
||||
expect(current?.request).toMatchObject({
|
||||
setupDecision: 'skip',
|
||||
executionHostId: 'runtime:host-1',
|
||||
launchInputs: {
|
||||
sessionOptions: { effort: 'high', permissionMode: 'ask' },
|
||||
agentArgs: '--sandbox workspace-write',
|
||||
chatSessionOptions: { effort: 'low', fastMode: 'true' }
|
||||
}
|
||||
})
|
||||
expect(current?.request.launchInputs?.chatSessionOptions?.model).toBeUndefined()
|
||||
expect(current?.phase).toBe('creating')
|
||||
})
|
||||
})
|
||||
@@ -1,11 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { extractAllOscTitles, extractLastOscTitle } from './osc-title-extraction'
|
||||
|
||||
describe('OSC title extraction', () => {
|
||||
it('recovers when an abandoned incomplete OSC title is followed by a fresh title', () => {
|
||||
const data = '\x1b]0;abandoned\x1b]0;Fresh title\x07'
|
||||
|
||||
expect(extractLastOscTitle(data)).toBe('Fresh title')
|
||||
expect(extractAllOscTitles(data)).toEqual(['Fresh title'])
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user