From 7ff5252b0373643152be254a37667a019b625dce Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sat, 14 Nov 2026 18:14:46 -0800 Subject: [PATCH] test: remove 48 low-value suites (#42573) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 37 --- .../ai-vault-scan-coordinator.test.ts | 169 ----------- .../daemon-preserved-endpoint-loss.test.ts | 77 ----- .../runner-wsl-network-ssh-policy.test.ts | 155 ---------- .../runner-wsl-login-shell-capture.test.ts | 155 ---------- .../runner-command-exec.test.ts | 175 ----------- .../local-git-object-quarantine.test.ts | 94 ------ .../resolution/repo-branch-conflict.test.ts | 85 ------ .../drive-checkout-suspect-paths.test.ts | 59 ---- .../files/pull-request-detail-context.test.ts | 138 --------- .../stacks/stacked-pr-creation.test.ts | 176 ------------ .../github-api-repository.test.ts | 129 --------- .../parcel-watcher-owned-children.test.ts | 120 -------- ...el-watcher-native-error-retirement.test.ts | 168 ----------- ...lesystem-watcher-document-lifetime.test.ts | 171 ----------- .../idle-exit/orcad-idle-exit-monitor.test.ts | 117 -------- .../hooks/plugin-agent-hook-sites.test.ts | 147 ---------- .../worker-start-terminal-target.spec.ts | 151 ---------- .../worker-run-dispatch-contracts.test.ts | 2 - .../ssh-keyboard-interactive.test.ts | 116 -------- .../agent-launch-picker-retirement.test.ts | 95 ------ ...automation-legacy-schedule-editing.test.ts | 73 ----- .../markdown-preview-local-images.test.ts | 99 ------- ...erve-section-during-external-edit.test.tsx | 90 ------ .../monaco-cursor-line-lifetime.test.ts | 63 ---- .../routing/native-chat-leaf-routing.test.ts | 78 ----- .../structured-agent-session-tabs.test.ts | 66 ----- .../native-chat-subagent-handoff.test.ts | 79 ----- .../tools/runs/native-chat-tool-fold.test.ts | 88 ------ .../SetProjectLocationDialog.test.tsx | 93 ------ .../use-hosted-review-eligibility.test.tsx | 77 ----- .../set-project-hidden.test.ts | 78 ----- .../deletion/folder-workspace-delete.test.ts | 69 ----- .../ssh-host-form/ssh-target-draft.test.ts | 106 ------- ...te-terminal-pane-menu-copy-actions.test.ts | 62 ---- ...se-workspace-cleanup-browse-state.test.tsx | 81 ------ .../workspace-cleanup-host-index.test.ts | 83 ------ ...ree-jump-palette-browser-ownership.test.ts | 82 ------ .../lib/keyboard/app-keyboard-router.test.ts | 82 ------ .../plugins/catalog/plugin-panels.test.ts | 75 ----- .../agent-hibernation-live-anchor-e2e.test.ts | 74 ----- .../worktrees-multiple-attachments.test.ts | 59 ---- .../pty/terminal-exited-pane-liveness.test.ts | 76 ----- .../pty/terminal-tab-recovery-remount.test.ts | 67 ----- ...ative-chat-session-option-snapshot.test.ts | 272 ------------------ .../native-chat-transcript-contracts.test.ts | 2 - .../native-chat-reasoning-row.spec.ts | 65 ----- .../native-chat-subagent-summary.test.ts | 156 ---------- .../turns/native-chat-turn-activity.test.ts | 113 -------- .../turns/native-chat-turn-grouping.spec.ts | 126 -------- .../tab-groups/tab-group-moves.test.ts | 96 ------- 51 files changed, 5166 deletions(-) delete mode 100644 src/main/ai-vault/scan-lifecycle/ai-vault-scan-coordinator.test.ts delete mode 100644 src/main/daemon/providers/adapter/testing/daemon-preserved-endpoint-loss.test.ts delete mode 100644 src/main/git/command-runner/git-environment/runner-wsl-network-ssh-policy.test.ts delete mode 100644 src/main/git/command-runner/host-routing/runner-wsl-login-shell-capture.test.ts delete mode 100644 src/main/git/command-runner/runner-command-exec.test.ts delete mode 100644 src/main/git/objects/local-git-object-quarantine.test.ts delete mode 100644 src/main/git/refs/resolution/repo-branch-conflict.test.ts delete mode 100644 src/main/git/source-control/drive-checkout/drive-checkout-suspect-paths.test.ts delete mode 100644 src/main/github/pull-requests/files/pull-request-detail-context.test.ts delete mode 100644 src/main/github/pull-requests/stacks/stacked-pr-creation.test.ts delete mode 100644 src/main/github/repositories/github-api-repository.test.ts delete mode 100644 src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-owned-children.test.ts delete mode 100644 src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-native-error-retirement.test.ts delete mode 100644 src/main/ipc/filesystem/watchers/filesystem-watcher-document-lifetime.test.ts delete mode 100644 src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts delete mode 100644 src/main/plugins/hooks/plugin-agent-hook-sites.test.ts delete mode 100644 src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-start-terminal-target.spec.ts delete mode 100644 src/main/ssh/authentication/ssh-keyboard-interactive.test.ts delete mode 100644 src/renderer/src/components/agent/agent-launch-picker-retirement.test.ts delete mode 100644 src/renderer/src/components/automations/authoring/automation-legacy-schedule-editing.test.ts delete mode 100644 src/renderer/src/components/editor/markdown-preview/links/markdown-preview-local-images.test.ts delete mode 100644 src/renderer/src/components/editor/markdown-preview/viewport/use-preserve-section-during-external-edit.test.tsx delete mode 100644 src/renderer/src/components/editor/monaco/monaco-cursor-line-lifetime.test.ts delete mode 100644 src/renderer/src/components/native-chat/pane/routing/native-chat-leaf-routing.test.ts delete mode 100644 src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.test.ts delete mode 100644 src/renderer/src/components/native-chat/subagents/native-chat-subagent-handoff.test.ts delete mode 100644 src/renderer/src/components/native-chat/tools/runs/native-chat-tool-fold.test.ts delete mode 100644 src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.test.tsx delete mode 100644 src/renderer/src/components/right-sidebar/source-control/review/use-hosted-review-eligibility.test.tsx delete mode 100644 src/renderer/src/components/sidebar/hidden-projects/set-project-hidden.test.ts delete mode 100644 src/renderer/src/components/sidebar/workspace-actions/deletion/folder-workspace-delete.test.ts delete mode 100644 src/renderer/src/components/ssh-host-form/ssh-target-draft.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/clipboard/create-terminal-pane-menu-copy-actions.test.ts delete mode 100644 src/renderer/src/components/workspace-cleanup/browse/use-workspace-cleanup-browse-state.test.tsx delete mode 100644 src/renderer/src/components/workspace-cleanup/candidate-evidence/workspace-cleanup-host-index.test.ts delete mode 100644 src/renderer/src/components/worktree-jump/tabs/use-worktree-jump-palette-browser-ownership.test.ts delete mode 100644 src/renderer/src/lib/keyboard/app-keyboard-router.test.ts delete mode 100644 src/renderer/src/store/plugins/catalog/plugin-panels.test.ts delete mode 100644 src/renderer/src/store/slices/agent-status/agent-hibernation-live-anchor-e2e.test.ts delete mode 100644 src/renderer/src/store/slices/worktrees/metadata/worktrees-multiple-attachments.test.ts delete mode 100644 src/renderer/src/store/terminals/pty/terminal-exited-pane-liveness.test.ts delete mode 100644 src/renderer/src/store/terminals/pty/terminal-tab-recovery-remount.test.ts delete mode 100644 src/shared/native-chat/input/session-options/native-chat-session-option-snapshot.test.ts delete mode 100644 src/shared/native-chat/transcript/row-content/native-chat-reasoning-row.spec.ts delete mode 100644 src/shared/native-chat/transcript/subagents/native-chat-subagent-summary.test.ts delete mode 100644 src/shared/native-chat/transcript/turns/native-chat-turn-activity.test.ts delete mode 100644 src/shared/native-chat/transcript/turns/native-chat-turn-grouping.spec.ts delete mode 100644 src/shared/workspace-layout/tab-groups/tab-group-moves.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 8b021ad8817..13bac691993 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -532,7 +532,6 @@ "src/main/ai-vault-search/query/session-search-typo-scope.test.ts": 195, "src/main/ai-vault-search/storage/session-search-write-buffer.test.ts": 197, "src/main/ai-vault-search/storage/session-search-write-lifetime.test.ts": 318, - "src/main/ai-vault/ai-vault-scan-coordinator.test.ts": 55, "src/main/ai-vault/ai-vault-scan-progress-flow.test.ts": 835, "src/main/ai-vault/ai-vault-scan-progress.test.ts": 475, "src/main/ai-vault/ai-vault-wsl-session-carryover.test.ts": 46, @@ -1497,7 +1496,6 @@ "src/main/git/command-runner/git-worktree-mutation-state.test.ts": 74, "src/main/git/remotes/hosted-remote-url.test.ts": 43, "src/main/git/source-control/ignores/huge-folder-ignore.test.ts": 58, - "src/main/git/objects/local-git-object-quarantine.test.ts": 108, "src/main/git/refs/maintenance/local-repo-ref-maintenance-wsl-stopped.test.ts": 271, "src/main/git/refs/maintenance/local-repo-ref-maintenance.test.ts": 339, "src/main/git/objects/merge-tree-object-quarantine-real-git.test.ts": 2561, @@ -1510,7 +1508,6 @@ "src/main/git/worktrees/removal/remove-worktree-clean-preflight.test.ts": 248, "src/main/git/worktrees/removal/remove-worktree.test.ts": 310, "src/main/git/refs/resolution/repo-branch-conflict-real-git.test.ts": 348, - "src/main/git/refs/resolution/repo-branch-conflict.test.ts": 308, "src/main/git/repositories/discovery/repo-detection-async.test.ts": 612, "src/main/git/repositories/discovery/repo-detection-batching.test.ts": 494, "src/main/git/repositories/discovery/repo-detection-command.test.ts": 49, @@ -1525,7 +1522,6 @@ "src/main/git/refs/resolution/repo.test.ts": 2318, "src/main/git/command-runner/runner-buffer-cancellation.test.ts": 318, "src/main/git/command-runner/runner-buffer-stdin.test.ts": 229, - "src/main/git/command-runner/runner-command-exec.test.ts": 764, "src/main/git/command-runner/hosted-cli/runner-gh-account-binding.test.ts": 246, "src/main/git/command-runner/hosted-cli/runner-gh-rate-limit-breaker.test.ts": 261, "src/main/git/command-runner/git-environment/runner-network-ssh-policy.test.ts": 283, @@ -1534,14 +1530,11 @@ "src/main/git/command-runner/hosted-cli/runner-wsl-gh-fallback.test.ts": 1093, "src/main/git/runner-wsl-linked-gitdir-timeout.test.ts": 266, "src/main/git/command-runner/host-routing/runner-wsl-linked-gitdir-windows.test.ts": 381, - "src/main/git/command-runner/host-routing/runner-wsl-login-shell-capture.test.ts": 222, - "src/main/git/command-runner/git-environment/runner-wsl-network-ssh-policy.test.ts": 260, "src/main/git/repositories/cloning/saved-clone-target.test.ts": 890, "src/main/git/source-control/diffs/blob-absence-real-git.test.ts": 629, "src/main/git/source-control/mutations/complete-merge-real-git.test.ts": 958, "src/main/git/source-control/diffs/diff-textconv-real-git.test.ts": 520, "src/main/git/source-control/diffs/diff-too-large-real-git.test.ts": 446, - "src/main/git/source-control/drive-checkout/drive-checkout-suspect-paths.test.ts": 49, "src/main/git/source-control/drive-checkout-suspect-real-git.test.ts": 406, "src/main/git/source-control/drive-checkout-suspect-writes-real-git.test.ts": 691, "src/main/git/source-control/mutations/stage-worktree-changes.test.ts": 1737, @@ -1641,7 +1634,6 @@ "src/main/github/gh-capability-state.test.ts": 48, "src/main/github/gh-utils-concurrency.test.ts": 530, "src/main/github/gh-utils.test.ts": 570, - "src/main/github/github-api-repository.test.ts": 566, "src/main/github/github-enterprise-repository.test.ts": 479, "src/main/github/github-pr-stack.test.ts": 495, "src/main/github/github-project-account.test.ts": 547, @@ -1669,11 +1661,9 @@ "src/main/github/project-view-host-auth.test.ts": 100, "src/main/github/project-view.test.ts": 560, "src/main/github/project-view/project-view-config.test.ts": 556, - "src/main/github/pull-request-detail-context.test.ts": 535, "src/main/github/pull-request-sidebar-query.test.ts": 492, "src/main/github/rate-limit.test.ts": 78, "src/main/github/repository-merge-metadata-reuse.test.ts": 546, - "src/main/github/stacked-pr-creation.test.ts": 490, "src/main/github/work-item-details-enterprise-host.test.ts": 574, "src/main/github/work-item-details-pr-files.test.ts": 591, "src/main/github/work-item-details-query-reuse.test.ts": 592, @@ -1782,14 +1772,11 @@ "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-crash-fuse.test.ts": 54, "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-disconnect-termination.test.ts": 145, "src/main/ipc/filesystem/watcher-process/event-delivery/parcel-watcher-event-delivery.test.ts": 162, - "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-native-error-retirement.test.ts": 120, - "src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-owned-children.test.ts": 59, "src/main/ipc/filesystem/watcher-process/parcel-watcher-process-dispose.test.ts": 51, "src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts": 519, "src/main/ipc/filesystem/watcher-process/root-paths/parcel-watcher-root-path-rewrite.test.ts": 135, "src/main/ipc/filesystem/watcher-process/native-subscriptions/parcel-watcher-shallow-subscription.test.ts": 241, "src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-supervisor-capacity.test.ts": 235, - "src/main/ipc/filesystem/watchers/filesystem-watcher-document-lifetime.test.ts": 557, "src/main/ipc/filesystem/watchers/filesystem-watcher-event-batch.test.ts": 59, "src/main/ipc/filesystem/watchers/filesystem-watcher-ignore-real.test.ts": 707, "src/main/ipc/filesystem/watchers/filesystem-watcher-large-batch.test.ts": 306, @@ -2221,7 +2208,6 @@ "src/main/orcad/serve-startup/orcad-cli-launcher.test.ts": 232, "src/main/orcad/orcad-cli-orchestration.integration.test.ts": 214, "src/main/orcad/serve-startup/orcad-help.integration.test.ts": 5016, - "src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts": 106, "src/main/orcad/instance-lock/orcad-instance-lock.test.ts": 315, "src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts": 617, "src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts": 407, @@ -2410,7 +2396,6 @@ "src/main/plugins/contributions/plugin-icon-theme-registry.test.ts": 268, "src/main/plugins/contributions/plugin-syntax-registry.test.ts": 221, "src/main/plugins/contributions/plugin-theme-registries.test.ts": 250, - "src/main/plugins/hooks/plugin-agent-hook-sites.test.ts": 279, "src/main/plugins/hooks/plugin-hook-warming.test.ts": 472, "src/main/plugins/installation/plugin-atomic-file-write.test.ts": 2051, "src/main/plugins/installation/plugin-catalog-install-guard.test.ts": 475, @@ -3516,7 +3501,6 @@ "src/main/ssh/host-server/ssh-host-server-on-connect.test.ts": 536, "src/main/ssh/host-server/ssh-host-server-telemetry.test.ts": 194, "src/main/ssh/authentication/ssh-identity-file-read.test.ts": 111, - "src/main/ssh/authentication/ssh-keyboard-interactive.test.ts": 54, "src/main/ssh/authentication/ssh-multi-factor-authentication.test.ts": 269, "src/main/ssh/authentication/ssh-multi-key-authentication.test.ts": 160, "src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts": 66, @@ -3905,7 +3889,6 @@ "src/renderer/src/components/automations/hosts/automation-host-list-rows.test.ts": 419, "src/renderer/src/components/automations/automation-host-scale-gates.test.ts": 638, "src/renderer/src/components/automations/hosts/automation-host-scheduler.test.ts": 439, - "src/renderer/src/components/automations/authoring/automation-legacy-schedule-editing.test.ts": 449, "src/renderer/src/components/automations/automation-list-view.test.ts": 257, "src/renderer/src/components/automations/automation-run-output-snapshot-equivalence.test.ts": 158, "src/renderer/src/components/automations/automation-run-output-snapshot.test.ts": 96, @@ -4080,7 +4063,6 @@ "src/renderer/src/components/editor/markdown/navigation/markdown-navigation-details.test.ts": 626, "src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document-client.test.ts": 65, "src/renderer/src/components/editor/markdown-preview/document-worker/markdown-preview-document.test.ts": 1670, - "src/renderer/src/components/editor/markdown-preview/links/markdown-preview-local-images.test.ts": 1639, "src/renderer/src/components/editor/markdown-preview/review/markdown-preview-review-frame-lifecycle.test.tsx": 642, "src/renderer/src/components/editor/markdown-preview/search/markdown-preview-search-crash.test.tsx": 255, "src/renderer/src/components/editor/markdown-preview/search/markdown-preview-search-offsets.test.ts": 92, @@ -4091,7 +4073,6 @@ "src/renderer/src/components/editor/markdown/render-mode/markdown-round-trip.test.ts": 2334, "src/renderer/src/components/editor/mermaid-sanitize.chromium.test.ts": 313, "src/renderer/src/components/editor/monaco-content-sync.undo-history.test.ts": 1108, - "src/renderer/src/components/editor/monaco-cursor-line-lifetime.test.ts": 1561, "src/renderer/src/components/editor/monaco-editor-input-bindings.paste-capture.test.ts": 342, "src/renderer/src/components/editor/monaco-large-text-paste.crlf.test.ts": 2297, "src/renderer/src/components/editor/markdown-source-tools/monaco/monaco-markdown-doc-completions-retention.test.ts": 1243, @@ -4159,7 +4140,6 @@ "src/renderer/src/components/editor/markdown-preview/search/use-markdown-preview-search-reveal.test.tsx": 390, "src/renderer/src/components/editor/use-monaco-editor-mount.cursor-owner.test.tsx": 1332, "src/renderer/src/components/editor/use-monaco-editor-mount.stale-cache.test.tsx": 877, - "src/renderer/src/components/editor/use-preserve-section-during-external-edit.test.tsx": 268, "src/renderer/src/components/editor/rich-markdown/tables/use-rich-markdown-table-context-menu.test.tsx": 2238, "src/renderer/src/components/editor/external-changes/useEditorPanelExternalContentEvents.test.tsx": 2018, "src/renderer/src/components/editor/useEditorPanelFloatingTabContentState.test.tsx": 889, @@ -4300,7 +4280,6 @@ "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/pane/routing/native-chat-leaf-routing.test.ts": 49, "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, "src/renderer/src/components/native-chat/composer/editor/native-chat-mounted-editor-view.test.ts": 222, @@ -4321,7 +4300,6 @@ "src/renderer/src/components/native-chat/subagents/native-chat-subagent-handoff-copy-budget.test.ts": 362, "src/renderer/src/components/native-chat/pane/routing/native-chat-tab-directory.test.ts": 304, "src/renderer/src/components/native-chat/native-chat-task-list-state.test.ts": 62, - "src/renderer/src/components/native-chat/tools/runs/native-chat-tool-fold.test.ts": 65, "src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts": 355, "src/renderer/src/components/native-chat/tools/diffs/native-chat-turn-diffs.test.ts": 340, "src/renderer/src/components/native-chat/session/options/terminal/serialized-screen-background-rows.test.ts": 131, @@ -4376,7 +4354,6 @@ "src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.test.tsx": 870, "src/renderer/src/components/new-workspace/RunTargetCombobox.host-identity.test.tsx": 856, "src/renderer/src/components/new-workspace/SetProjectLocationDialog.host-identity.test.tsx": 1094, - "src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.test.tsx": 1387, "src/renderer/src/components/new-workspace/SmartWorkspaceNameField-repo-slug-routing.test.ts": 342, "src/shared/new-workspace/smart-workspace-source-results.test.ts": 136, "src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.test.tsx": 278, @@ -4536,7 +4513,6 @@ "src/renderer/src/components/settings/navigation/settings-project-list.test.ts": 99, "src/renderer/src/components/settings/source-control/source-control-action-card-layout.test.tsx": 4551, "src/renderer/src/components/settings/source-control/source-control-action-permission-draft.test.tsx": 6938, - "src/renderer/src/components/ssh-host-form/ssh-target-draft.test.ts": 72, "src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx": 1414, "src/renderer/src/components/settings/repository/hooks/use-repository-hook-settings-draft.test.tsx": 586, "src/renderer/src/components/settings/repository/hooks/use-repository-issue-command-wsl-stopped.test.ts": 523, @@ -4926,12 +4902,10 @@ "src/renderer/src/components/virtualized-list.test.tsx": 446, "src/renderer/src/components/window-close-request-coordinator.test.ts": 361, "src/renderer/src/components/workspace-cleanup/dialog/WorkspaceCleanupDialog.stale-while-revalidate.test.tsx": 3269, - "src/renderer/src/components/workspace-cleanup/browse/use-workspace-cleanup-browse-state.test.tsx": 248, "src/renderer/src/components/workspace-cleanup/candidate-evidence/use-workspace-cleanup-git-evidence.test.tsx": 539, "src/renderer/src/components/workspace-cleanup/removal/use-workspace-cleanup-removal.agent-stop.test.tsx": 2285, "src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-background-removal-late-settlement.test.ts": 1880, "src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-background-removal.test.ts": 283, - "src/renderer/src/components/workspace-cleanup/candidate-evidence/workspace-cleanup-host-index.test.ts": 341, "src/renderer/src/components/workspace-cleanup/removal/workspace-cleanup-removal-candidates.test.ts": 206, "src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-removal-timeout-recovery.test.ts": 1817, "src/renderer/src/components/workspace-emoji/WorkspaceEmojiPickerButton.test.tsx": 1086, @@ -4939,7 +4913,6 @@ "src/renderer/src/components/worktree-creation/PendingNativeChatCreation.test.tsx": 4075, "src/renderer/src/components/worktree-jump/WorktreeJumpPalette.recent-tabs.behavior.test.tsx": 4445, "src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx": 4442, - "src/renderer/src/components/worktree-jump/use-worktree-jump-palette-browser-ownership.test.ts": 2096, "src/renderer/src/components/worktree-jump/use-worktree-jump-palette-task-search.test.tsx": 2140, "src/renderer/src/components/worktree-jump/worktree-jump-palette-browser-navigation.test.tsx": 4470, "src/renderer/src/components/wsl-move/wsl-move-dialog-store.test.ts": 2011, @@ -5074,7 +5047,6 @@ "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, - "src/renderer/src/lib/keyboard/app-keyboard-router.test.ts": 187, "src/renderer/src/lib/clipboard/menu/app-menu-paste.test.ts": 229, "src/renderer/src/lib/automation-session-reuse.test.ts": 70, "src/renderer/src/lib/automation-terminal-ownership.test.ts": 1795, @@ -5279,7 +5251,6 @@ "src/renderer/src/store/plugins/localization/plugin-language-packs-startup.test.ts": 435, "src/renderer/src/store/plugins/localization/plugin-language-packs.test.ts": 377, "src/renderer/src/store/plugins/catalog/plugin-panel-retry-timer-cleanup.test.ts": 5216, - "src/renderer/src/store/plugins/catalog/plugin-panels.test.ts": 2142, "src/renderer/src/store/projects/project-catalog-null-field-ingest.test.ts": 309, "src/renderer/src/store/repos/dropped-repo-worktree-rows.test.ts": 1738, "src/renderer/src/store/repos/repo-removal.test.ts": 799, @@ -5287,7 +5258,6 @@ "src/renderer/src/store/repos/wsl-moved-repo-ui-retention.test.ts": 2920, "src/renderer/src/store/slices/runtime-status/views/runtime-status-subscriptions.test.ts": 182, "src/renderer/src/store/slices/editor/focus/active-selection-owner-scoping.test.ts": 1909, - "src/renderer/src/store/slices/agent-status/agent-hibernation-live-anchor-e2e.test.ts": 1783, "src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts": 1756, "src/renderer/src/store/slices/agent-status/agent-status-pane-owner-reclaim.test.ts": 1899, "src/renderer/src/store/slices/agent-status/agent-status-ack-cleanup.test.ts": 1776, @@ -5429,7 +5399,6 @@ "src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts": 1751, "src/renderer/src/store/terminals/terminal-quick-command-hosts.test.ts": 1759, "src/renderer/src/store/terminals/terminal-tab-owner-index.test.ts": 50, - "src/renderer/src/store/terminals/terminal-tab-recovery-remount.test.ts": 1791, "src/renderer/src/store/terminals/terminals-hydration-canonical-pty-overlap.test.ts": 1946, "src/renderer/src/store/terminals/terminals-hydration-canonical-rows.test.ts": 1680, "src/renderer/src/store/slices/ui/ui-host-filter-sync.test.ts": 597, @@ -5467,7 +5436,6 @@ "src/renderer/src/store/slices/worktrees/listing/worktrees-hydration-purge.test.ts": 1274, "src/renderer/src/store/slices/worktrees/session/worktrees-identity-migration.test.ts": 1412, "src/renderer/src/store/slices/worktrees/metadata/worktrees-linked-review-push-target.test.ts": 1186, - "src/renderer/src/store/slices/worktrees/metadata/worktrees-multiple-attachments.test.ts": 1132, "src/renderer/src/store/slices/worktrees/create/worktrees-pending-creation-state.test.ts": 1132, "src/renderer/src/store/slices/worktrees/teardown/worktrees-removal-state-cleanup.test.ts": 1229, "src/renderer/src/store/slices/worktrees/listing/worktrees-runtime-connection-generation-fence.test.ts": 1240, @@ -5487,7 +5455,6 @@ "src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts": 67, "src/renderer/src/store/terminals/restored-relay-session-identity.test.ts": 2196, "src/renderer/src/store/terminals/structured-chat-tab-rename.test.ts": 3154, - "src/renderer/src/store/terminals/terminal-exited-pane-liveness.test.ts": 1721, "src/renderer/src/store/terminals/terminal-no-op-subscriber.test.ts": 1763, "src/renderer/src/store/terminals/terminal-startup-queue-restart.test.ts": 1895, "src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts": 1945, @@ -5827,7 +5794,6 @@ "src/shared/native-chat/input/native-chat-pty-session-options.test.ts": 519, "src/shared/native-chat/input/native-chat-ask.test.ts": 272, "src/shared/native-chat/input/native-chat-session-option-commands.test.ts": 216, - "src/shared/native-chat/input/native-chat-session-option-snapshot.test.ts": 224, "src/shared/native-chat/input/native-chat-session-option-state.test.ts": 55, "src/shared/native-chat/input/native-chat-slash-commands.test.ts": 49, "src/shared/native-chat/input/native-chat-task-list-history.test.ts": 49, @@ -5852,10 +5818,8 @@ "src/shared/native-chat/tools/native-chat-turn-membership-derived-tool-row.test.ts": 268, "src/shared/native-chat/transcript/native-chat-image-transcript-markers.test.ts": 94, "src/shared/native-chat/transcript/native-chat-subagent-items.test.ts": 188, - "src/shared/native-chat/transcript/native-chat-subagent-summary.test.ts": 62, "src/shared/native-chat/transcript/native-chat-transcript-contracts.test.ts": 715, "src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts": 182, - "src/shared/native-chat/transcript/native-chat-turn-activity.test.ts": 119, "src/shared/native-chat/transcript/native-chat-turn-fold.test.ts": 192, "src/shared/native-chat/transcript/native-chat-turn-status.test.ts": 69, "src/shared/native-chat/transcript/native-chat-unverifiable-turn-status.test.ts": 150, @@ -6186,7 +6150,6 @@ "src/shared/workspace-layout/old-client/old-client-pane-layout-translation.test.ts": 363, "src/shared/workspace-layout/old-client/old-client-session-tabs-projection-owned-editor.test.ts": 178, "src/shared/workspace-layout/old-client/old-client-session-tabs-projection.test.ts": 207, - "src/shared/workspace-layout/tab-groups/tab-group-moves.test.ts": 52, "src/shared/workspace-layout/tab-groups/tab-order-moves.test.ts": 44, "src/shared/workspace-layout/commands/workspace-layout-agent-session-tab.test.ts": 168, "src/shared/workspace-layout/commands/workspace-layout-browser-commands.test.ts": 177, diff --git a/src/main/ai-vault/scan-lifecycle/ai-vault-scan-coordinator.test.ts b/src/main/ai-vault/scan-lifecycle/ai-vault-scan-coordinator.test.ts deleted file mode 100644 index 904dfe51214..00000000000 --- a/src/main/ai-vault/scan-lifecycle/ai-vault-scan-coordinator.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { AiVaultScanCoordinator } from './ai-vault-scan-coordinator' -import { - localAiVaultScanProgress, - onLocalAiVaultScanProgress, - resetLocalAiVaultScanProgressForTests, - startLocalAiVaultScanProgress, - type LocalAiVaultScanProgressHandle -} from './ai-vault-local-scan-progress' - -const EMPTY_RESULT = { sessions: [], issues: [], scannedAt: '2026-07-27T00:00:00.000Z' } - -describe('AiVaultScanCoordinator', () => { - it('keeps the replacement finding while the old scan aborts before root preparation ends', async () => { - const coordinator = new AiVaultScanCoordinator() - const stages: (string | null)[] = [] - onLocalAiVaultScanProgress(({ progress }) => stages.push(progress?.stage ?? null)) - try { - const earlier = startLocalAiVaultScanProgress('scope', 'earlier', () => 500) - earlier.finish(null) - let old: LocalAiVaultScanProgressHandle | null = null - const first = coordinator.run({ - key: 'scope', - onCreate: (id) => { - old = startLocalAiVaultScanProgress('scope', id, () => 1_000) - }, - onError: () => old?.fail(), - start: (signal) => - new Promise((_resolve, reject) => { - signal.addEventListener('abort', () => reject(new Error('cancelled')), { once: true }) - }) - }) - await Promise.resolve() - let finishPreparation: ((result: typeof EMPTY_RESULT) => void) | undefined - const replacement = coordinator.run({ - key: 'scope', - force: true, - onCreate: (id) => { - startLocalAiVaultScanProgress('scope', id, () => 2_000) - }, - start: () => - new Promise((resolve) => { - finishPreparation = resolve - }) - }) - await Promise.resolve() - expect(localAiVaultScanProgress('scope')).toMatchObject({ - stage: 'finding', - startedAt: 2_000 - }) - expect(stages).not.toContain(null) - finishPreparation?.(EMPTY_RESULT) - await expect(Promise.all([first, replacement])).resolves.toEqual([EMPTY_RESULT, EMPTY_RESULT]) - } finally { - resetLocalAiVaultScanProgressForTests() - } - }) - - it('keeps a shared scan alive when only one caller cancels', async () => { - const coordinator = new AiVaultScanCoordinator() - let resolveScan: ((result: typeof EMPTY_RESULT) => void) | undefined - let sharedSignal: AbortSignal | undefined - const start = vi.fn( - (signal: AbortSignal) => - new Promise((resolve) => { - sharedSignal = signal - resolveScan = resolve - }) - ) - const controller = new AbortController() - const first = coordinator.run({ key: 'scope', signal: controller.signal, start }) - const second = coordinator.run({ key: 'scope', start }) - await Promise.resolve() - - controller.abort() - - await expect(first).rejects.toMatchObject({ name: 'AbortError' }) - expect(sharedSignal?.aborted).toBe(false) - resolveScan?.(EMPTY_RESULT) - await expect(second).resolves.toEqual(EMPTY_RESULT) - expect(start).toHaveBeenCalledTimes(1) - }) - - it('preempts a non-forced scan and re-joins its caller onto the forced scan', async () => { - const coordinator = new AiVaultScanCoordinator() - const signals: AbortSignal[] = [] - let resolveForced: ((result: typeof EMPTY_RESULT) => void) | undefined - const start = vi.fn((signal: AbortSignal) => { - signals.push(signal) - return new Promise((resolve) => { - if (signals.length === 1) { - signal.addEventListener('abort', () => resolve(EMPTY_RESULT), { once: true }) - } else { - resolveForced = resolve - } - }) - }) - const first = coordinator.run({ key: 'scope', start }) - await Promise.resolve() - - const forced = coordinator.run({ key: 'scope', force: true, start }) - const joined = coordinator.run({ key: 'scope', force: true, start }) - await Promise.resolve() - - expect(signals[0]?.aborted).toBe(true) - expect(start).toHaveBeenCalledTimes(2) - resolveForced?.(EMPTY_RESULT) - await expect(Promise.all([first, forced, joined])).resolves.toEqual([ - EMPTY_RESULT, - EMPTY_RESULT, - EMPTY_RESULT - ]) - }) - - it('lets a forced refresh preempt a forced scan that hung past the coalescing window', async () => { - vi.useFakeTimers() - try { - const coordinator = new AiVaultScanCoordinator() - const signals: AbortSignal[] = [] - let resolveSecond: ((result: typeof EMPTY_RESULT) => void) | undefined - const start = vi.fn((signal: AbortSignal) => { - signals.push(signal) - return new Promise((resolve) => { - if (signals.length > 1) { - resolveSecond = resolve - } - }) - }) - const stuck = coordinator.run({ key: 'scope', force: true, start }) - await Promise.resolve() - - vi.advanceTimersByTime(5_000) - const retry = coordinator.run({ key: 'scope', force: true, start }) - await Promise.resolve() - - expect(signals[0]?.aborted).toBe(true) - expect(start).toHaveBeenCalledTimes(2) - resolveSecond?.(EMPTY_RESULT) - await expect(Promise.all([stuck, retry])).resolves.toEqual([EMPTY_RESULT, EMPTY_RESULT]) - } finally { - vi.useRealTimers() - } - }) - - it('starts a fresh scan after every waiter cancels', async () => { - const coordinator = new AiVaultScanCoordinator() - const signals: AbortSignal[] = [] - const start = vi.fn((signal: AbortSignal) => { - signals.push(signal) - if (signals.length > 1) { - return Promise.resolve(EMPTY_RESULT) - } - return new Promise((resolve) => { - signal.addEventListener('abort', () => resolve(EMPTY_RESULT), { once: true }) - }) - }) - const controller = new AbortController() - const first = coordinator.run({ key: 'scope', signal: controller.signal, start }) - await Promise.resolve() - controller.abort() - await expect(first).rejects.toMatchObject({ name: 'AbortError' }) - - const second = coordinator.run({ key: 'scope', start }) - - await expect(second).resolves.toEqual(EMPTY_RESULT) - expect(start).toHaveBeenCalledTimes(2) - expect(signals[0]?.aborted).toBe(true) - }) -}) diff --git a/src/main/daemon/providers/adapter/testing/daemon-preserved-endpoint-loss.test.ts b/src/main/daemon/providers/adapter/testing/daemon-preserved-endpoint-loss.test.ts deleted file mode 100644 index 695a19e38e7..00000000000 --- a/src/main/daemon/providers/adapter/testing/daemon-preserved-endpoint-loss.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { confirmPreservedEndpointLoss } from '../daemon-preserved-endpoint-loss' -import { DaemonProtocolError } from '../../../protocol/daemon-errors' - -function connectError(code: string): Error { - return Object.assign(new Error(`connect ${code}`), { code, syscall: 'connect' }) -} - -const sleep = async (): Promise => {} - -/** Replays connect outcomes in order; once spent, the caller no longer needs a verdict. */ -function script(outcomes: (Error | 'ok')[]) { - let index = 0 - return { - connect: async () => { - const outcome = outcomes[index++] - if (outcome instanceof Error) { - throw outcome - } - }, - shouldContinue: () => index < outcomes.length - } -} - -describe('confirmPreservedEndpointLoss', () => { - it('is gone after three refused or missing attempts in a row with the process gone', async () => { - const run = script([ - connectError('ECONNREFUSED'), - connectError('ENOENT'), - connectError('ECONNREFUSED') - ]) - await expect( - confirmPreservedEndpointLoss({ ...run, processExited: () => true, delaysMs: [1], sleep }) - ).resolves.toBe('gone') - }) - - it('restarts the count on a timeout or other failure instead of reading it as death', async () => { - const run = script([ - connectError('ENOENT'), - connectError('ENOENT'), - new DaemonProtocolError('Connection timed out'), - connectError('EPERM'), - connectError('ENOENT'), - connectError('ENOENT') - ]) - await expect( - confirmPreservedEndpointLoss({ ...run, processExited: () => true, delaysMs: [1], sleep }) - ).resolves.toBe('abandoned') - }) - - it('keeps checking after an unproven attempt, so a host that dies later is still caught', async () => { - const run = script([ - new DaemonProtocolError('Connection timed out'), - connectError('ENOENT'), - connectError('ENOENT'), - connectError('ENOENT'), - connectError('ENOENT') - ]) - await expect( - confirmPreservedEndpointLoss({ ...run, processExited: () => true, delaysMs: [1], sleep }) - ).resolves.toBe('gone') - }) - - it('never declares loss while the daemon process may still be alive', async () => { - const run = script(Array.from({ length: 10 }, () => connectError('ECONNREFUSED'))) - await expect( - confirmPreservedEndpointLoss({ ...run, processExited: () => false, delaysMs: [1], sleep }) - ).resolves.toBe('abandoned') - }) - - it('stops when the host answers again', async () => { - const run = script([connectError('ECONNREFUSED'), 'ok', connectError('ECONNREFUSED')]) - await expect( - confirmPreservedEndpointLoss({ ...run, processExited: () => true, delaysMs: [1], sleep }) - ).resolves.toBe('reachable') - }) -}) diff --git a/src/main/git/command-runner/git-environment/runner-wsl-network-ssh-policy.test.ts b/src/main/git/command-runner/git-environment/runner-wsl-network-ssh-policy.test.ts deleted file mode 100644 index de82f09ab67..00000000000 --- a/src/main/git/command-runner/git-environment/runner-wsl-network-ssh-policy.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { execFileMock } = vi.hoisted(() => ({ execFileMock: vi.fn() })) -vi.mock('node:child_process', () => ({ - execFile: execFileMock, - execFileSync: vi.fn(), - spawn: vi.fn() -})) - -import { gitExecFileAsync } from '../git-exec-file' -import { GitAdmissionScheduler } from '../../../../shared/git/admission/git-admission-scheduler' -import { _resetGitAdmissionForTests } from '../admission/git-subprocess-admission' - -const originalPlatform = process.platform -const WSL_CWD = String.raw`\\wsl.localhost\Ubuntu\home\alice\repo` -const SSH_COMMAND = 'ssh -F /home/alice/.ssh/config' -const FETCH_ARGS = ['fetch', '--no-write-fetch-head', 'origin'] - -class ShellChild extends EventEmitter { - readonly pid = 0 - readonly stdout = new EventEmitter() - readonly stderr = new EventEmitter() - readonly kill = vi.fn() -} - -type ShellCall = { script: string; env: NodeJS.ProcessEnv; child: ShellChild } - -function installShell( - options: { delayMs?: number; variant?: string; configError?: Error } = {} -): ShellCall[] { - const calls: ShellCall[] = [] - execFileMock.mockImplementation((_program, args, spawnOptions, callback) => { - const child = new ShellChild() - const script = String(args.at(-1)) - calls.push({ script, env: spawnOptions.env, child }) - let closed = false - const close = () => { - if (closed) { - return - } - closed = true - child.emit('close', 0, null) - } - const reply = setTimeout(() => { - const isProbe = script.includes("'config'") - const payload = isProbe - ? `core.sshcommand\n${SSH_COMMAND}\0ssh.variant\n${options.variant ?? 'ssh'}\0` - : 'fetch-ok' - const nonce = /__ORCA_WSL_CAPTURE_BEGIN_ ([^_]+)__/.exec(script)?.[1] - const stdout = nonce - ? `profile banner\n__ORCA_WSL_CAPTURE_BEGIN_${nonce}__${payload}__ORCA_WSL_CAPTURE_END_${nonce}__` - : payload - callback(isProbe ? (options.configError ?? null) : null, stdout, '') - close() - }, options.delayMs ?? 3000) - child.kill.mockImplementation(() => { - clearTimeout(reply) - queueMicrotask(close) - return true - }) - return child - }) - return calls -} - -function fetch(options: { timeout?: number; signal?: AbortSignal; env?: NodeJS.ProcessEnv } = {}) { - return gitExecFileAsync(FETCH_ARGS, { - cwd: WSL_CWD, - wslDistro: 'Ubuntu', - env: {}, - ...options - }) -} - -function networkCalls(calls: ShellCall[]): ShellCall[] { - return calls.filter(({ script }) => script.includes("'fetch'")) -} - -beforeEach(() => { - vi.useFakeTimers() - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - execFileMock.mockReset() - _resetGitAdmissionForTests(new GitAdmissionScheduler({ generalCap: 1, generalHeadroom: 0 })) -}) - -afterEach(() => { - vi.useRealTimers() - Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) - _resetGitAdmissionForTests() -}) - -describe('WSL network Git SSH policy startup', () => { - it('honors an explicit shorter timeout before the network command starts', async () => { - const calls = installShell() - const pending = fetch({ timeout: 1000 }).catch((error) => error) - - await vi.advanceTimersByTimeAsync(1200) - expect(await pending).toMatchObject({ message: 'wsl.exe timed out.' }) - expect(calls).toHaveLength(1) - expect(calls[0].child.kill).toHaveBeenCalledOnce() - expect(networkCalls(calls)).toHaveLength(0) - }) - - it.each([30_000, 0])('keeps the probe bounded with explicit timeout %s', async (timeout) => { - const calls = installShell({ delayMs: 11_000 }) - const pending = fetch({ timeout }).catch((error) => error) - - await vi.advanceTimersByTimeAsync(10_500) - expect(await pending).toMatchObject({ message: 'wsl.exe timed out.' }) - expect(calls[0].child.kill).toHaveBeenCalledOnce() - expect(networkCalls(calls)).toHaveLength(0) - }) - - it.each([128, 'ETIMEDOUT', 'ENOBUFS'])( - 'keeps configuration failure %s closed after a slow startup', - async (code) => { - const configError = Object.assign(new Error('WSL configuration unavailable'), { code }) - const calls = installShell({ configError }) - const pending = fetch().catch((error) => error) - - await vi.advanceTimersByTimeAsync(3500) - expect(await pending).toBe(configError) - expect(calls).toHaveLength(1) - expect(networkCalls(calls)).toHaveLength(0) - } - ) - - it('aborts the slow probe and releases admission for the next attempt', async () => { - const calls = installShell() - const controller = new AbortController() - const pending = fetch({ signal: controller.signal }).catch((error) => error) - - await vi.advanceTimersByTimeAsync(1000) - controller.abort() - await vi.advanceTimersByTimeAsync(0) - expect(await pending).toMatchObject({ name: 'AbortError' }) - expect(calls[0].child.kill).toHaveBeenCalledOnce() - expect(networkCalls(calls)).toHaveLength(0) - - const retry = fetch() - await vi.advanceTimersByTimeAsync(6500) - await expect(retry).resolves.toMatchObject({ stdout: 'fetch-ok' }) - expect(networkCalls(calls)).toHaveLength(1) - }) - - it('does not spawn a probe for an already-aborted operation', async () => { - const calls = installShell() - const controller = new AbortController() - controller.abort() - - await expect(fetch({ signal: controller.signal })).rejects.toMatchObject({ name: 'AbortError' }) - expect(calls).toHaveLength(0) - }) -}) diff --git a/src/main/git/command-runner/host-routing/runner-wsl-login-shell-capture.test.ts b/src/main/git/command-runner/host-routing/runner-wsl-login-shell-capture.test.ts deleted file mode 100644 index a765136d01f..00000000000 --- a/src/main/git/command-runner/host-routing/runner-wsl-login-shell-capture.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { execFileMock, execFileSyncMock, spawnMock } = vi.hoisted(() => ({ - execFileMock: vi.fn(), - execFileSyncMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('node:child_process', () => ({ - execFile: execFileMock, - execFileSync: execFileSyncMock, - spawn: spawnMock -})) -vi.mock('../../../observability/instrumentation', () => ({ - withGitSpan: (_attributes: unknown, run: () => unknown) => run() -})) -vi.mock('../../../diagnostics/main-thread-churn-probe', () => ({ recordSubprocessSpawn: vi.fn() })) - -import { gitExecFileAsync, gitExecFileAsyncBuffer } from '../git-exec-file' -import { _resetGitAdmissionForTests } from '../admission/git-subprocess-admission' - -afterEach(() => _resetGitAdmissionForTests()) -import { resetWslGitReadEnvironmentForTests } from './wsl-git-read-environment' - -const originalPlatform = process.platform - -const DISTRO = 'Ubuntu' -const WSL_CWD = String.raw`\\wsl.localhost\Ubuntu\home\alice\repo` -const BANNER = 'To run a command as administrator (user "root"), use "sudo ".\n\n' - -function createMockChild(): EventEmitter & { stdout: EventEmitter; stderr: EventEmitter } { - const child = new EventEmitter() as EventEmitter & { - stdout: EventEmitter - stderr: EventEmitter - } - child.stdout = new EventEmitter() - child.stderr = new EventEmitter() - return child -} - -/** Stand in for the guest shell: banner first, then the payload inside the command's fence. */ -function respondWithFencedPayload(payload: Buffer | string, error: Error | null = null): void { - execFileMock.mockImplementation((_command, args, options, callback) => { - const nonce = /__ORCA_WSL_CAPTURE_BEGIN_ ([^_]+)__/.exec(String(args.at(-1)))?.[1] ?? '' - const body = typeof payload === 'string' ? Buffer.from(payload, 'utf8') : payload - const stdout = Buffer.concat([ - Buffer.from(BANNER, 'utf8'), - Buffer.from(`__ORCA_WSL_CAPTURE_BEGIN_${nonce}__`, 'utf8'), - body, - Buffer.from(`__ORCA_WSL_CAPTURE_END_${nonce}__`, 'utf8') - ]) - const asText = options?.encoding !== 'buffer' - queueMicrotask(() => - callback?.(error, asText ? stdout.toString('utf8') : stdout, asText ? '' : Buffer.alloc(0)) - ) - return createMockChild() - }) -} - -describe('WSL login-shell reads are fenced', () => { - beforeEach(() => { - execFileMock.mockReset() - execFileSyncMock.mockReset() - spawnMock.mockReset() - resetWslGitReadEnvironmentForTests() - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - }) - - afterEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) - resetWslGitReadEnvironmentForTests() - }) - - it('keeps binary blob bytes intact through the fence', async () => { - const binary = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff, 0xfe, 0x0a, 0x00, 0x1b]) - respondWithFencedPayload(binary) - - const { stdout } = await gitExecFileAsyncBuffer(['show', ':image.png'], { - cwd: WSL_CWD, - wslDistro: DISTRO - }) - - expect(Buffer.compare(stdout, binary)).toBe(0) - }) - - it('fences buffered text reads without a per-call opt-in', async () => { - respondWithFencedPayload('3\t1\ta.txt\0') - - const { stdout } = await gitExecFileAsync(['diff', '--numstat', '-z'], { - cwd: WSL_CWD, - wslDistro: DISTRO - }) - - expect(stdout).toBe('3\t1\ta.txt\0') - }) - - it('strips the fence from stdout of a non-zero exit', async () => { - respondWithFencedPayload('ignored.log\0', Object.assign(new Error('exit 1'), { code: 1 })) - - const failure = await gitExecFileAsync(['check-ignore', '-z', '--stdin'], { - cwd: WSL_CWD, - wslDistro: DISTRO, - stdin: 'ignored.log\0' - }).catch((error: unknown) => error) - - expect(failure).toMatchObject({ code: 1, stdout: 'ignored.log\0' }) - }) - - /** Answer the core.sshCommand probe with `configured`, and any other command with ok. */ - function respondToSshPolicyProbe(configured: string): void { - execFileMock.mockImplementation((_command, args, _options, callback) => { - const script = String(args.at(-1)) - const nonce = /__ORCA_WSL_CAPTURE_BEGIN_ ([^_]+)__/.exec(script)?.[1] ?? '' - const stdout = script.includes('sshcommand') - ? `${BANNER}__ORCA_WSL_CAPTURE_BEGIN_${nonce}__${configured}__ORCA_WSL_CAPTURE_END_${nonce}__` - : 'ok' - queueMicrotask(() => callback?.(null, stdout, '')) - return createMockChild() - }) - } - - function sshCommandFromLastGitCall(): string | undefined { - const gitCall = execFileMock.mock.calls.findLast( - (call) => !String(call[1]?.at(-1)).includes('sshcommand') - ) - return (gitCall?.[2] as { env?: NodeJS.ProcessEnv } | undefined)?.env?.GIT_SSH_COMMAND - } - - it('keeps the BatchMode guard when core.sshCommand is unset behind a banner', async () => { - // An unfenced banner could masquerade as core.sshCommand and drop the BatchMode guard. - respondToSshPolicyProbe('') - - await gitExecFileAsync(['fetch', 'origin'], { - cwd: WSL_CWD, - wslDistro: DISTRO, - useConfiguredSshCommandForNetwork: true - }) - - expect(sshCommandFromLastGitCall()).toBe('ssh -o BatchMode=yes') - }) - - it('still honors a genuinely configured core.sshCommand', async () => { - respondToSshPolicyProbe('core.sshcommand\nssh -i /home/alice/.ssh/id_ed25519\0') - - await gitExecFileAsync(['fetch', 'origin'], { - cwd: WSL_CWD, - wslDistro: DISTRO, - useConfiguredSshCommandForNetwork: true - }) - - expect(sshCommandFromLastGitCall()).toContain('/home/alice/.ssh/id_ed25519') - expect(sshCommandFromLastGitCall()).toContain('BatchMode=yes') - }) -}) diff --git a/src/main/git/command-runner/runner-command-exec.test.ts b/src/main/git/command-runner/runner-command-exec.test.ts deleted file mode 100644 index 5c04f221c3b..00000000000 --- a/src/main/git/command-runner/runner-command-exec.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createFakeSpawnedChild as createMockChildProcess } from '../../../shared/__fixtures__/fake-spawned-child' - -// Callback fixtures exercise native execFile; Mac spawn capture has real-child coverage. -const restorePlatform = vi.hoisted(() => { - const platform = process.platform - if (platform === 'darwin') { - Object.defineProperty(process, 'platform', { value: 'linux' }) - } - return () => Object.defineProperty(process, 'platform', { value: platform }) -}) -afterAll(restorePlatform) - -const { execFileMock, execFileSyncMock, spawnMock } = vi.hoisted(() => ({ - execFileMock: vi.fn(), - execFileSyncMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('node:child_process', () => ({ - execFile: execFileMock, - execFileSync: execFileSyncMock, - spawn: spawnMock -})) -import { commandExecFileAsync } from './process-capture/command-exec-file' -import { gitExecFileAsync } from './git-exec-file' -import { glabExecFileAsync } from './hosted-cli/glab-exec-file' -import { gitStreamStdout } from './git-stream-stdout' -import { _resetGitAdmissionForTests } from './admission/git-subprocess-admission' - -afterEach(() => _resetGitAdmissionForTests()) - -describe('runner execFile timeout handling', () => { - beforeEach(() => { - execFileMock.mockReset() - spawnMock.mockReset() - execFileSyncMock.mockReset() - vi.useFakeTimers() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('rejects command executions when execFile never calls back after timeout', async () => { - const child = createMockChildProcess(1234) - execFileMock.mockReturnValue(child) - - const promise = commandExecFileAsync('git', ['status'], { - cwd: '/repo', - timeout: 1000 - }) - const rejection = expect(promise).rejects.toThrow(/git(?:\.exe)? timed out\./i) - await vi.advanceTimersByTimeAsync(1000) - - await rejection - expect(child.kill).toHaveBeenCalled() - }) - - it.skipIf(process.platform === 'win32')( - 'keeps a barrier Git abort pending until the process group closes', - async () => { - const child = createMockChildProcess(1234) - spawnMock.mockImplementation((command: string) => { - if (command !== 'ps') { - return child - } - const probe = createMockChildProcess(4321) - queueMicrotask(() => probe.emit('close', 0, null)) - return probe - }) - const processKill = vi.spyOn(process, 'kill').mockImplementation(() => true) - const controller = new AbortController() - try { - const pending = gitExecFileAsync(['status'], { - cwd: '/repo', - signal: controller.signal, - terminationBarrier: true - }) - let settled = false - void pending.then( - () => { - settled = true - }, - () => { - settled = true - } - ) - - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalled()) - controller.abort() - child.emit('close', 0, null) - await vi.advanceTimersByTimeAsync(1_999) - expect(settled).toBe(false) - await vi.advanceTimersByTimeAsync(1) - expect(processKill).toHaveBeenCalledWith(-1234, 'SIGKILL') - - await expect(pending).rejects.toMatchObject({ name: 'AbortError' }) - } finally { - processKill.mockRestore() - } - } - ) - - // CLI shims have descendants; direct-child signals can leave them running beyond the deadline. - - it('aborts glab retry backoff instead of starting another attempt', async () => { - const controller = new AbortController() - const transient = Object.assign(new Error('glab failed'), { - stderr: 'HTTP 503 Service Unavailable' - }) - spawnMock.mockImplementationOnce(() => { - const child = createMockChildProcess(1234) - queueMicrotask(() => { - child.stderr.emit('data', Buffer.from(transient.stderr)) - child.emit('exit', 1, null) - child.emit('close', 1, null) - }) - return child - }) - - const promise = glabExecFileAsync(['api', 'projects'], { - cwd: '/repo', - signal: controller.signal - }) - const rejection = expect(promise).rejects.toMatchObject({ name: 'AbortError' }) - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledTimes(1)) - controller.abort() - - await rejection - expect(spawnMock).toHaveBeenCalledTimes(1) - }) -}) - -describe('gitStreamStdout', () => { - beforeEach(() => { - spawnMock.mockReset() - }) - - it('rejects (not crashes) when the onStdout callback throws', async () => { - const child = createMockChildProcess(1234) - spawnMock.mockReturnValue(child) - - const promise = gitStreamStdout(['status'], { - cwd: '/repo', - onStdout: () => { - throw new Error('parser blew up') - } - }) - const rejection = expect(promise).rejects.toThrow('parser blew up') - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledOnce()) - child.stdout.emit('data', Buffer.from('? a.txt\n')) - - await rejection - expect(child.kill).toHaveBeenCalled() - child.emit('close', null, 'SIGTERM') - }) - - it('handles a late spawn error after cancellation', async () => { - const child = createMockChildProcess(0) - spawnMock.mockReturnValue(child) - const controller = new AbortController() - - const promise = gitStreamStdout(['status'], { - cwd: '/repo', - signal: controller.signal, - onStdout: () => {} - }) - await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledOnce()) - controller.abort() - - await expect(promise).rejects.toMatchObject({ name: 'AbortError' }) - expect(() => child.emit('error', new Error('spawn ENOENT'))).not.toThrow() - }) -}) diff --git a/src/main/git/objects/local-git-object-quarantine.test.ts b/src/main/git/objects/local-git-object-quarantine.test.ts deleted file mode 100644 index 012fb699a97..00000000000 --- a/src/main/git/objects/local-git-object-quarantine.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type * as GitObjectQuarantineModule from '../../../shared/git/objects/git-object-quarantine' -import type { - GitObjectQuarantine, - GitObjectsDirectory -} from '../../../shared/git/objects/git-object-quarantine' -import { inheritedLocalObjectStore, localGitObjectsDirectory } from './local-git-object-quarantine' -import '../command-runner/host-routing/wsl-linked-worktree-git-routing' - -const { readRepoCommonDirFromGitMock } = vi.hoisted(() => ({ - readRepoCommonDirFromGitMock: vi.fn() -})) - -vi.mock('../worktrees/catalog/worktree-list-reader', () => ({ - readRepoCommonDirFromGit: readRepoCommonDirFromGitMock -})) -vi.mock('../../../shared/git/objects/git-object-quarantine', async (importOriginal) => ({ - ...(await importOriginal()), - createGitObjectQuarantine: ( - resolve: () => Promise - ): GitObjectQuarantine => ({ - run: async (command) => { - const objects = await resolve() - return command( - objects - ? { - GIT_OBJECT_DIRECTORY: `${objects.gitPath}/scratch`, - GIT_ALTERNATE_OBJECT_DIRECTORIES: objects.gitPath - } - : undefined - ) - } - }) -})) - -describe('localGitObjectsDirectory', () => { - it('translates a WSL Git common dir into a path the Windows host can open', () => { - expect(localGitObjectsDirectory('/home/me/repo/.git', 'Ubuntu')).toEqual({ - hostPath: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo\\.git\\objects', - gitPath: '/home/me/repo/.git/objects' - }) - }) - - it('hands WSL Git the drvfs spelling of a drive-path common dir (Git < 2.31 prints it relative)', () => { - expect(localGitObjectsDirectory('C:\\repo\\.git', 'Ubuntu')).toEqual({ - hostPath: 'C:\\repo\\.git\\objects', - gitPath: '/mnt/c/repo/.git/objects' - }) - expect(localGitObjectsDirectory('/mnt/c/repo/.git', 'Ubuntu')).toEqual({ - hostPath: 'C:\\repo\\.git\\objects', - gitPath: '/mnt/c/repo/.git/objects' - }) - }) -}) - -describe('inheritedLocalObjectStore', () => { - const ALTERNATES = { GIT_ALTERNATE_OBJECT_DIRECTORIES: '/shared/objects' } - - it('passes native Git’s inherited alternates on and refuses an inherited object dir', () => { - expect(inheritedLocalObjectStore(undefined, ALTERNATES, 'darwin')).toEqual({ - inheritedAlternates: '/shared/objects' - }) - expect( - inheritedLocalObjectStore(undefined, { GIT_OBJECT_DIRECTORY: 'C:\\objects' }, 'win32') - ).toBeUndefined() - }) - - it('ignores Windows values WSLENV does not forward, since WSL Git never saw them', () => { - expect(inheritedLocalObjectStore('Ubuntu', ALTERNATES, 'win32')).toEqual({}) - expect( - inheritedLocalObjectStore( - 'Ubuntu', - { WSLENV: 'GIT_OBJECT_DIRECTORY/p:GIT_ALTERNATE_OBJECT_DIRECTORIES' }, - 'win32' - ) - ).toEqual({}) - expect( - inheritedLocalObjectStore('Ubuntu', { GIT_OBJECT_DIRECTORY: 'C:\\objects' }, 'win32') - ).toEqual({}) - }) - - it.each(['GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_OBJECT_DIRECTORY/p'])( - 'runs unquarantined when WSLENV forwards %s to WSL Git', - (token) => { - const env = { - GIT_ALTERNATE_OBJECT_DIRECTORIES: 'C:\\shared', - GIT_OBJECT_DIRECTORY: 'C:\\objects', - WSLENV: `ORCA_X/u:${token}` - } - - expect(inheritedLocalObjectStore('Ubuntu', env, 'win32')).toBeUndefined() - } - ) -}) diff --git a/src/main/git/refs/resolution/repo-branch-conflict.test.ts b/src/main/git/refs/resolution/repo-branch-conflict.test.ts deleted file mode 100644 index 00140362044..00000000000 --- a/src/main/git/refs/resolution/repo-branch-conflict.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -import { - getBranchConflictKindStrictViaExec, - getBranchConflictKindViaExec -} from './repo-branch-conflict' - -describe('portable branch-name conflicts', () => { - function executor(refs = '') { - return vi.fn(async (argv: string[]) => { - if (argv[0] === 'rev-parse') { - throw Object.assign(new Error('missing'), { code: 1, stderr: '' }) - } - return { stdout: argv[0] === 'for-each-ref' ? refs : '' } - }) - } - - it('fails closed on unexpected stdout instead of treating it as an empty listing', async () => { - const exec = executor('Welcome to the host\n') - await expect(getBranchConflictKindViaExec(exec, 'Feature')).rejects.toThrow( - 'Cannot verify branch-name case conflicts' - ) - }) - - describe('strict probe for exact-name creates', () => { - const noMatch = () => Object.assign(new Error('missing'), { code: 1, stderr: '' }) - const transport = () => Object.assign(new Error('SSH disconnected'), { code: 255 }) - // origin is configured; each case breaks one probe boundary. - function strictExecutor(broken: 'local' | 'remote-names' | 'remote-ref', remoteHit = false) { - return vi.fn(async (argv: string[]) => { - if (argv[0] === 'rev-parse') { - throw broken === 'local' ? transport() : noMatch() - } - if (argv[0] === 'remote') { - if (broken === 'remote-names') { - throw transport() - } - return { stdout: 'origin\n' } - } - if (argv[0] === 'show-ref') { - if (remoteHit) { - return { stdout: '' } - } - throw broken === 'remote-ref' ? transport() : noMatch() - } - return { stdout: '' } - }) - } - - it.each(['local', 'remote-names', 'remote-ref'] as const)( - 'reports unknown when the %s probe cannot decide', - async (broken) => { - await expect( - getBranchConflictKindStrictViaExec(strictExecutor(broken), 'feature') - ).resolves.toBe('unknown') - } - ) - - it('keeps the lenient probe answering free where the strict one is unknown', async () => { - await expect(getBranchConflictKindViaExec(strictExecutor('local'), 'feature')).resolves.toBe( - null - ) - }) - - it('lets a known remote conflict win over an undecided local probe', async () => { - await expect( - getBranchConflictKindStrictViaExec(strictExecutor('local', true), 'feature') - ).resolves.toBe('remote') - }) - - it('reports unknown instead of throwing when the case-fold listing fails', async () => { - const exec = strictExecutor('remote-ref') - exec.mockImplementation(async (argv: string[]) => { - if (argv[0] === 'rev-parse') { - throw noMatch() - } - if (argv[0] === 'for-each-ref') { - throw transport() - } - return { stdout: '' } - }) - await expect(getBranchConflictKindStrictViaExec(exec, 'feature')).resolves.toBe('unknown') - }) - }) -}) diff --git a/src/main/git/source-control/drive-checkout/drive-checkout-suspect-paths.test.ts b/src/main/git/source-control/drive-checkout/drive-checkout-suspect-paths.test.ts deleted file mode 100644 index 1ce9ae395a5..00000000000 --- a/src/main/git/source-control/drive-checkout/drive-checkout-suspect-paths.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { DriveCheckoutSuspectPaths, repoRelativeWatcherPath } from './drive-checkout-suspect-paths' - -const REPO = String.raw`C:\Users\dev\My Repo` - -describe('repoRelativeWatcherPath', () => { - it('matches the root case- and Unicode-insensitively but keeps the tail spelling', () => { - const decomposed = 'Cafe\u0301' - const repo = String.raw`C:\Work\Café` - expect(repoRelativeWatcherPath(repo, `c:\\WORK\\${decomposed}\\Src\\Ünï.TS`)).toBe('Src/Ünï.TS') - }) -}) - -describe('DriveCheckoutSuspectPaths', () => { - const root = { rootPath: REPO } - const event = (relativePath: string, type = 'update'): { type: string; path: string } => ({ - type, - path: `${REPO}\\${relativePath.replace(/\//g, '\\')}` - }) - - it('treats a reinstalled watcher as a restart but keeps its own events', () => { - const tracker = new DriveCheckoutSuspectPaths(REPO) - tracker.recordEvents(root, [event('old.ts')]) - expect(tracker.beginPoll(root)?.size).toBe(1) - const reinstalled = { rootPath: REPO } - tracker.recordEvents(reinstalled, [event('new.ts')]) - expect([...(tracker.beginPoll(reinstalled)?.keys() ?? [])]).toEqual(['new.ts']) - }) - - it('keeps rechecked-dirty paths through overflow, interruption, restart, and a lost watcher', () => { - const tracker = new DriveCheckoutSuspectPaths(REPO, 3) - tracker.recordEvents(root, [event('hidden.ts')]) - tracker.confirmDirty('hidden.ts', tracker.beginPoll(root)?.get('hidden.ts') ?? 0) - tracker.recordEvents(root, [event('a'), event('b'), event('c')]) - tracker.recordInterruption(root) - const reinstalled = { rootPath: REPO } - expect([...(tracker.beginPoll(reinstalled)?.keys() ?? [])]).toEqual(['hidden.ts']) - expect([...(tracker.beginPoll(null)?.keys() ?? [])]).toEqual(['hidden.ts']) - }) - - it('keeps a dirty proof when the watcher was interrupted during the recheck', () => { - const tracker = new DriveCheckoutSuspectPaths(REPO) - tracker.recordEvents(root, [event('a.ts')]) - const snapshot = tracker.beginPoll(root) - tracker.recordInterruption(root) - tracker.confirmDirty('a.ts', snapshot?.get('a.ts') ?? 0) - expect([...(tracker.beginPoll(root)?.keys() ?? [])]).toEqual(['a.ts']) - }) - - it('drops only when no newer event re-armed the path', () => { - const tracker = new DriveCheckoutSuspectPaths(REPO) - tracker.recordEvents(root, [event('a.ts'), event('b.ts')]) - const snapshot = tracker.beginPoll(root)! - tracker.recordEvents(root, [event('b.ts')]) - tracker.drop('a.ts', snapshot.get('a.ts')!) - tracker.drop('b.ts', snapshot.get('b.ts')!) - expect([...(tracker.beginPoll(root)?.keys() ?? [])]).toEqual(['b.ts']) - }) -}) diff --git a/src/main/github/pull-requests/files/pull-request-detail-context.test.ts b/src/main/github/pull-requests/files/pull-request-detail-context.test.ts deleted file mode 100644 index ffa4ae31a1e..00000000000 --- a/src/main/github/pull-requests/files/pull-request-detail-context.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { LocalGitExecOptions } from '../../repositories/github-repository-identity' - -const { exec, guard, spend } = vi.hoisted(() => ({ exec: vi.fn(), guard: vi.fn(), spend: vi.fn() })) -vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ - ghExecFileAsync: exec -})) - -vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ - ...(await importOriginal()), - githubRepoContext: ( - repoPath: string, - connectionId: string | null, - options: LocalGitExecOptions - ) => ({ repoPath, connectionId, ...options }), - ghRepoExecOptions: ({ repoPath, ...options }: { repoPath: string }) => ({ - cwd: repoPath, - ...options - }) -})) -vi.mock('../../api/rate-limit', () => ({ - repositoryRateLimitGuard: guard, - noteRepositoryRateLimitSpend: spend -})) - -import { getPRDetailContext } from './pull-request-detail-context' - -const repository = { owner: 'acme', repo: 'widgets', host: 'github.com' } -const participant = { login: 'reviewer', name: null, avatarUrl: 'https://avatars/reviewer' } -const files = { - pageInfo: { hasNextPage: false, endCursor: null }, - nodes: [{ path: 'src/changed.ts', viewerViewedState: 'VIEWED' }] -} - -function response( - pullRequest: Record | null = { participants: { nodes: [participant] } }, - viewedPullRequest: Record | null = { id: 'PR_42', files }, - errors?: Record[] -) { - return { - stdout: JSON.stringify({ data: { repository: { pullRequest, viewedPullRequest } }, errors }) - } -} - -function mockReads(reads: ({ stdout: string } | Error | { code: number; stdout: string })[]) { - exec.mockImplementation(async (args: string[]) => { - if (args.includes('graphql')) { - const next = reads.shift() - if (!next) { - throw new Error('Unexpected GraphQL read') - } - if (next instanceof Error || 'code' in next) { - throw next - } - return next - } - throw new Error('Unexpected non-GraphQL read') - }) -} - -function graphqlCalls(): string[][] { - return exec.mock.calls.flatMap(([args]) => (args.includes('graphql') ? [args] : [])) -} - -beforeEach(() => { - vi.resetAllMocks() - guard.mockReturnValue({ blocked: false }) -}) - -describe('PR detail context requests', () => { - it('paginates only files after the first page and retains nullable viewer states', async () => { - mockReads([ - response(undefined, { - id: 'PR_42', - files: { ...files, pageInfo: { hasNextPage: true, endCursor: 'cursor-1' } } - }), - response(null, { - id: 'PR_42', - files: { ...files, nodes: [null, { path: 'src/unknown.ts', viewerViewedState: null }] } - }) - ]) - const result = await getPRDetailContext('/repo', 42, repository) - expect(result.viewedStates?.viewedStates).toEqual(new Map([['src/changed.ts', 'VIEWED']])) - expect(result.participants).toEqual([participant]) - expect(graphqlCalls()).toHaveLength(2) - expect(graphqlCalls()[1]).toContain('after=cursor-1') - expect(graphqlCalls()[1].join(' ')).not.toContain('participants') - }) - - it.each([ - { path: ['repository', 'pullRequest', 'participants'] }, - { path: ['repository', 'pullRequest'] } - ])('retains viewed files when an error nulls the participant PR at $path', async ({ path }) => { - mockReads([{ code: 1, ...response(null, { id: 'PR_42', files }, [{ path }]) }, response()]) - const result = await getPRDetailContext('/repo', 42, repository) - expect(result.participants).toEqual([participant]) - expect(result.viewedStates?.pullRequestId).toBe('PR_42') - expect(result.viewedStates?.viewedStates.get('src/changed.ts')).toBe('VIEWED') - expect(graphqlCalls()).toHaveLength(2) - expect(graphqlCalls()[1].join(' ')).not.toContain('viewerViewedState') - }) - - it('retains participants when the viewed PR alias is nulled', async () => { - mockReads([ - { - code: 1, - ...response(undefined, null, [{ path: ['repository', 'viewedPullRequest', 'id'] }]) - } - ]) - const result = await getPRDetailContext('/repo', 42, repository) - expect(result.participants).toEqual([participant]) - expect(result.viewedStates).toBeNull() - expect(graphqlCalls()).toHaveLength(1) - }) - - it('does not publish partially paginated viewed files after a later page fails', async () => { - mockReads([ - response(undefined, { - id: 'PR_42', - files: { ...files, pageInfo: { hasNextPage: true, endCursor: 'next' } } - }), - new Error('file page unavailable') - ]) - const result = await getPRDetailContext('/repo', 42, repository) - expect(result.participants).toEqual([participant]) - expect(result.viewedStates).toBeNull() - expect(graphqlCalls()).toHaveLength(2) - }) - - it('recovers participants after a failed query without retrying unavailable viewed state', async () => { - mockReads([new Error('Query failed'), response()]) - const result = await getPRDetailContext('/repo', 42, repository) - expect(result.participants).toEqual([participant]) - expect(result.viewedStates).toBeNull() - expect(graphqlCalls()).toHaveLength(2) - }) -}) diff --git a/src/main/github/pull-requests/stacks/stacked-pr-creation.test.ts b/src/main/github/pull-requests/stacks/stacked-pr-creation.test.ts deleted file mode 100644 index 138059d4e61..00000000000 --- a/src/main/github/pull-requests/stacks/stacked-pr-creation.test.ts +++ /dev/null @@ -1,176 +0,0 @@ -import type * as GithubRepositoryIdentityModule from '../../repositories/github-repository-identity' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { ghExecFileAsyncMock, repositoryMock } = vi.hoisted(() => ({ - ghExecFileAsyncMock: vi.fn(), - repositoryMock: vi.fn() -})) - -vi.mock('../../execution/github-operation-slots', () => ({ - acquire: vi.fn(), - release: vi.fn() -})) - -vi.mock('../../../git/command-runner/hosted-cli/gh-exec-file', () => ({ - ghExecFileAsync: ghExecFileAsyncMock -})) - -vi.mock('../../repositories/github-repository-identity', async (importOriginal) => ({ - ...(await importOriginal()), - ghRepoExecOptions: (context: { repoPath: string; connectionId?: string | null }) => - context.connectionId ? {} : { cwd: context.repoPath }, - githubRepoContext: ( - repoPath: string, - connectionId?: string | null, - localGitOptions?: Record - ) => ({ repoPath, connectionId, localGitOptions }) -})) - -vi.mock('../../repositories/github-api-repository-remote-probe', () => ({ - getOriginGitHubApiRepository: repositoryMock -})) - -vi.mock('../../repositories/github-repository-host', () => ({ - githubHostExecOptions: (repository: { host?: string }) => ({ host: repository.host }) -})) - -import { - prepareGitHubStackedPullRequest, - registerGitHubStackedPullRequest -} from './stacked-pr-creation' - -const repository = { owner: 'acme', repo: 'orca', host: 'github.com' } -const parentReview = { number: 41, url: 'https://github.com/acme/orca/pull/41' } -const currentReview = { number: 42, url: 'https://github.com/acme/orca/pull/42' } - -function pullRequest(number: number, head: string, base: string) { - return { - number, - html_url: `https://github.com/acme/orca/pull/${number}`, - head: { ref: head }, - base: { ref: base } - } -} - -function stack(number: number, pullRequests: number[]) { - return { - number, - open: true, - pull_requests: pullRequests.map((pullRequestNumber) => ({ number: pullRequestNumber })) - } -} - -beforeEach(() => { - ghExecFileAsyncMock.mockReset() - repositoryMock.mockReset() - repositoryMock.mockResolvedValue(repository) -}) - -describe('prepareGitHubStackedPullRequest', () => { - it('allows an idempotent retry after the child was already registered', async () => { - ghExecFileAsyncMock - .mockResolvedValueOnce({ stdout: JSON.stringify([pullRequest(41, 'stack/parent', 'main')]) }) - .mockResolvedValueOnce({ - stdout: JSON.stringify([pullRequest(42, 'stack/child', 'stack/parent')]) - }) - .mockResolvedValueOnce({ stdout: JSON.stringify([stack(50, [41, 42])]) }) - .mockResolvedValueOnce({ stdout: JSON.stringify([stack(50, [41, 42])]) }) - - const result = await prepareGitHubStackedPullRequest( - '/repo', - { - provider: 'github', - base: 'stack/parent', - head: 'stack/child', - title: 'Child' - }, - 'local' - ) - - expect(result).toMatchObject({ ok: true, currentReview: { number: 42 } }) - }) - - it('rejects a parent that is not the top of its stack', async () => { - ghExecFileAsyncMock - .mockResolvedValueOnce({ stdout: JSON.stringify([pullRequest(41, 'stack/parent', 'main')]) }) - .mockResolvedValueOnce({ stdout: '[]' }) - .mockResolvedValueOnce({ stdout: JSON.stringify([stack(50, [41, 45])]) }) - - const result = await prepareGitHubStackedPullRequest( - '/repo', - { - provider: 'github', - base: 'stack/parent', - head: 'stack/child', - title: 'Child' - }, - 'local' - ) - - expect(result).toMatchObject({ ok: false, code: 'validation' }) - if (!result.ok) { - expect(result.error).toContain('top pull request') - } - }) -}) - -describe('registerGitHubStackedPullRequest', () => { - it('treats an already registered parent-child pair as success', async () => { - ghExecFileAsyncMock - .mockResolvedValueOnce({ stdout: JSON.stringify([stack(50, [41, 42])]) }) - .mockResolvedValueOnce({ stdout: JSON.stringify([stack(50, [41, 42])]) }) - - const result = await registerGitHubStackedPullRequest({ - executionHostId: 'local', - repoPath: '/repo', - repository, - parentReview, - currentReview - }) - - expect(result).toMatchObject({ ok: true, stackNumber: 50 }) - expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) - }) - - it('does not claim registration when the stack no longer holds the parent', async () => { - // A missing parent gives -1; reading its successor would falsely identify the first entry as its child. - ghExecFileAsyncMock - .mockResolvedValueOnce({ stdout: JSON.stringify([stack(50, [42])]) }) - .mockResolvedValueOnce({ stdout: JSON.stringify([stack(50, [42])]) }) - - const result = await registerGitHubStackedPullRequest({ - executionHostId: 'local', - repoPath: '/repo', - repository, - parentReview, - currentReview - }) - - expect(result).toMatchObject({ - ok: false, - error: 'The pull request already belongs to a different GitHub stack.', - reason: 'stack_conflict', - createdReview: currentReview - }) - }) - - it('preserves the created PR when registration fails', async () => { - ghExecFileAsyncMock - .mockResolvedValueOnce({ stdout: '[]' }) - .mockResolvedValueOnce({ stdout: '[]' }) - .mockRejectedValueOnce(new Error('HTTP 422')) - - const result = await registerGitHubStackedPullRequest({ - executionHostId: 'local', - repoPath: '/repo', - repository, - parentReview, - currentReview - }) - - expect(result).toMatchObject({ - ok: false, - createdReview: currentReview - }) - }) -}) diff --git a/src/main/github/repositories/github-api-repository.test.ts b/src/main/github/repositories/github-api-repository.test.ts deleted file mode 100644 index 851e18cedd6..00000000000 --- a/src/main/github/repositories/github-api-repository.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import type * as GithubOwnerRepoSelectionModule from './github-owner-repo-selection' -import type * as GithubRepositoryIdentityModule from './github-repository-identity' -import type * as GithubEnterpriseRepositoryModule from './github-enterprise-repository' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { - getEnterpriseGitHubRepoSlugMock, - getOwnerRepoMock, - getOwnerRepoForRemoteMock, - isGitHubHostAuthenticatedMock, - shouldProbeGitRemoteMock -} = vi.hoisted(() => ({ - getEnterpriseGitHubRepoSlugMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - getOwnerRepoForRemoteMock: vi.fn(), - isGitHubHostAuthenticatedMock: vi.fn(), - shouldProbeGitRemoteMock: vi.fn(async () => true) -})) - -vi.mock('./github-owner-repo-selection', async (importOriginal) => ({ - ...(await importOriginal()), - getOwnerRepo: getOwnerRepoMock -})) - -vi.mock('./github-repository-identity', async (importOriginal) => ({ - ...(await importOriginal()), - getOwnerRepoForRemote: getOwnerRepoForRemoteMock -})) - -vi.mock('./github-enterprise-repository', async (importOriginal) => ({ - ...(await importOriginal()), - getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock, - isGitHubHostAuthenticated: isGitHubHostAuthenticatedMock -})) - -vi.mock('../../git/remotes/remote-name-listing', () => ({ - shouldProbeGitRemote: shouldProbeGitRemoteMock, - listCachedRemoteNames: async () => null -})) -import { - _resetOriginGitHubApiRepositoryCache, - getGitHubApiRepositoryForRemote -} from './github-api-repository-remote-probe' -import { resolveGitHubApiRepository, resolveGitHubRepoExecution } from './github-api-repository' - -beforeEach(() => { - _resetOriginGitHubApiRepositoryCache() - getEnterpriseGitHubRepoSlugMock.mockReset().mockResolvedValue(null) - getOwnerRepoMock.mockReset().mockResolvedValue(null) - getOwnerRepoForRemoteMock.mockReset().mockResolvedValue(null) - isGitHubHostAuthenticatedMock.mockReset().mockResolvedValue(false) - shouldProbeGitRemoteMock.mockReset().mockResolvedValue(true) -}) - -describe('resolveGitHubRepoExecution', () => { - it('rejects an explicit Enterprise host absent from the local gh auth inventory', async () => { - await expect( - resolveGitHubApiRepository( - '/remote/repo', - { - owner: 'acme', - repo: 'widgets', - host: 'evil.example.test' - }, - 'ssh-1' - ) - ).resolves.toBeNull() - - expect(isGitHubHostAuthenticatedMock).toHaveBeenCalledWith( - 'evil.example.test', - '/remote/repo', - 'ssh-1', - {} - ) - }) - - it.each([ - { owner: 'acme%2Fadmin', repo: 'widgets' }, - { owner: 'acme', repo: '..' } - ])('rejects repository overrides that could alter a gh REST path: %o', async (repository) => { - await expect( - resolveGitHubApiRepository('/repo', { - ...repository, - host: 'github.com' - }) - ).resolves.toBeNull() - - expect(isGitHubHostAuthenticatedMock).not.toHaveBeenCalled() - }) - - it('rejects a host-less caller-specific resolver for a connection-backed repository', async () => { - await expect( - resolveGitHubRepoExecution( - '/remote/repo', - async () => ({ owner: 'upstream', repo: 'widgets' }), - 'ssh-1' - ) - ).resolves.toEqual({ ownerRepo: null, ghOptions: {} }) - }) - - it('preserves an authoritative null from a caller-specific resolver', async () => { - getOwnerRepoMock.mockResolvedValue({ owner: 'origin', repo: 'widgets' }) - - await expect(resolveGitHubRepoExecution('/repo', async () => null)).resolves.toEqual({ - ownerRepo: null, - ghOptions: { cwd: '/repo' } - }) - - expect(getOwnerRepoMock).not.toHaveBeenCalled() - }) -}) - -describe('origin repository cache', () => { - it('keeps an indeterminate auth inventory unverifiable during candidate discovery', async () => { - getEnterpriseGitHubRepoSlugMock.mockResolvedValue(undefined) - - await expect( - getGitHubApiRepositoryForRemote( - '/remote/repo', - 'origin', - 'ssh-1', - {}, - { - requireVerifiedSshProbe: true - } - ) - ).rejects.toThrow('GitHub repository identity is unverifiable.') - }) -}) diff --git a/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-owned-children.test.ts b/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-owned-children.test.ts deleted file mode 100644 index eb85490c851..00000000000 --- a/src/main/ipc/filesystem/watcher-process/child-lifecycle/parcel-watcher-owned-children.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { EventEmitter } from 'node:events' -import type { ChildProcess } from 'node:child_process' -import { afterEach, expect, it, vi } from 'vitest' -import { WatcherOwnedChildren } from './parcel-watcher-owned-children' -import { - registerWatcherChildPhysicalExit, - signalWatcherChild, - WATCHER_PROCESS_HARD_KILL_DELAY_MS -} from './parcel-watcher-child-termination' -import { RUNTIME_FILE_WATCH_EXIT_DEADLINE_MS as WATCHER_PROCESS_EXIT_DEADLINE_MS } from '../../../../../shared/file-watch/runtime-file-watch-limits' - -afterEach(() => vi.useRealTimers()) - -function child() { - const exitState: { exitCode: number | null; signalCode: NodeJS.Signals | null } = { - exitCode: null, - signalCode: null - } - const events = Object.assign(new EventEmitter(), exitState, { kill: vi.fn(() => true) }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: termination reads only the exit fields, kill and events stubbed here. - const process = events as unknown as ChildProcess - const physicalExit = registerWatcherChildPhysicalExit(process) - events.on('exit', physicalExit) - events.on('close', physicalExit) - events.on('error', () => {}) - return { process, events, close: () => events.emit('close') } -} - -it('joins disposal and does not confuse disconnect/error with physical exit', async () => { - const owner = new WatcherOwnedChildren() - const c = child() - owner.track(c.process) - const logical = vi.fn() - const disposed = vi.fn() - const first = owner.disposeAndWait(logical) - expect(owner.disposeAndWait(logical)).toBe(first) - const result = first.then(disposed) - c.events.emit('disconnect') - c.events.emit('error', new Error('spawn or IPC failure')) - await new Promise((resolve) => setImmediate(resolve)) - expect(disposed).not.toHaveBeenCalled() - expect(logical).toHaveBeenCalledOnce() - c.close() - await result - expect(disposed).toHaveBeenCalledOnce() -}) - -it('includes children already signaled by synchronous or retired-owner disposal', async () => { - const owner = new WatcherOwnedChildren() - const old = child() - const replacement = child() - owner.track(old.process) - old.process.kill() - owner.track(replacement.process) - const disposed = vi.fn() - const result = owner.disposeAndWait(() => {}).then(disposed) - replacement.close() - await new Promise((resolve) => setImmediate(resolve)) - expect(disposed).not.toHaveBeenCalled() - old.close() - await result -}) - -it('retains a child after termination deadline failure and supports explicit retry', async () => { - vi.useFakeTimers() - const owner = new WatcherOwnedChildren() - const c = child() - owner.track(c.process) - const result = owner.disposeAndWait(() => {}).catch((error: unknown) => error) - await vi.advanceTimersByTimeAsync(WATCHER_PROCESS_EXIT_DEADLINE_MS) - expect(await result).toMatchObject({ message: 'watcher_owned_children_shutdown_incomplete' }) - const completed = vi.fn() - const retry = owner.disposeAndWait(() => {}).then(completed) - await vi.advanceTimersByTimeAsync(0) - expect(completed).not.toHaveBeenCalled() - c.close() - await retry -}) - -it('waits for other children even when logical disposal and one kill fail', async () => { - const owner = new WatcherOwnedChildren() - const failed = child() - const pending = child() - owner.track(failed.process) - owner.track(pending.process) - failed.events.kill.mockImplementationOnce(() => { - throw new Error('kill failed') - }) - const logicalFailure = new Error('logical cleanup failed') - const finished = vi.fn() - const result = owner - .disposeAndWait(() => { - throw logicalFailure - }) - .catch((error: unknown) => { - finished() - return error - }) - await new Promise((resolve) => setImmediate(resolve)) - expect(finished).not.toHaveBeenCalled() - pending.close() - expect(await result).toMatchObject({ errors: [logicalFailure, expect.any(Error)] }) - const retry = owner.disposeAndWait(() => {}) - failed.close() - await retry -}) - -it('skips a second graceful signal after the supervisor sent one but still escalates', async () => { - vi.useFakeTimers() - const owner = new WatcherOwnedChildren() - const c = child() - owner.track(c.process) - const disposal = owner.disposeAndWait(() => signalWatcherChild(c.process)) - expect(c.events.kill).toHaveBeenCalledTimes(1) - expect(c.events.kill).toHaveBeenCalledWith() - await vi.advanceTimersByTimeAsync(WATCHER_PROCESS_HARD_KILL_DELAY_MS) - expect(c.events.kill).toHaveBeenLastCalledWith('SIGKILL') - c.events.emit('exit', null, 'SIGKILL') - await expect(disposal).resolves.toBeUndefined() -}) diff --git a/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-native-error-retirement.test.ts b/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-native-error-retirement.test.ts deleted file mode 100644 index 88677d07b47..00000000000 --- a/src/main/ipc/filesystem/watcher-process/supervision/parcel-watcher-native-error-retirement.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - acknowledgeWatcherSubscribe, - currentWatcherChild, - FakeWatcherChild, - trackPromiseSettlement -} from './parcel-watcher-process-test-child' - -const { forkMock } = vi.hoisted(() => ({ forkMock: vi.fn() })) -vi.mock('node:child_process', () => ({ fork: forkMock })) -vi.mock('node:fs', () => ({ - existsSync: () => true, - mkdtempSync: () => '/tmp/orca-watcher-retirement-test', - rmSync: vi.fn() -})) - -import { WatcherProcessSupervisor } from './parcel-watcher-process-supervisor' -import { RUNTIME_FILE_WATCH_EXIT_DEADLINE_MS as WATCHER_PROCESS_EXIT_DEADLINE_MS } from '../../../../../shared/file-watch/runtime-file-watch-limits' - -describe('native watcher error retirement', () => { - let supervisor: WatcherProcessSupervisor - - beforeEach(() => { - forkMock.mockReset().mockImplementation(() => new FakeWatcherChild()) - supervisor = new WatcherProcessSupervisor({ useInProcessVitestFallback: false }) - }) - - afterEach(() => supervisor.dispose()) - - it('closes only the failed handle before recovery and joins concurrent unsubscribe', async () => { - const callback = vi.fn() - const onTerminalError = vi.fn() - const pending = supervisor.subscribe('/repo', callback, {}, { onTerminalError }) - const child = currentWatcherChild(forkMock) - const id = acknowledgeWatcherSubscribe(child) - const subscription = await pending - const keepAlive = supervisor.subscribe('/other', vi.fn(), {}) - const otherId = acknowledgeWatcherSubscribe(child) - await keepAlive - - child.emit('message', { op: 'watch-error', id, message: 'native watcher stopped' }) - expect(child.sent.at(-1)).toEqual({ op: 'unsubscribe', id }) - expect(onTerminalError).not.toHaveBeenCalled() - expect(callback).not.toHaveBeenCalled() - const closing = subscription.unsubscribe() - const closed = trackPromiseSettlement(closing) - child.emit('message', { op: 'watch-error', id, message: 'duplicate error' }) - child.emit('message', { op: 'events', id, events: [{ type: 'update', path: '/repo/stale' }] }) - await Promise.resolve() - expect(closed()).toBe(false) - expect(child.sent.filter((message) => message.op === 'unsubscribe')).toHaveLength(1) - - child.emit('message', { op: 'unsubscribed', id }) - await closing - await vi.waitFor(() => expect(onTerminalError).toHaveBeenCalledTimes(1)) - expect(onTerminalError).toHaveBeenCalledWith( - expect.objectContaining({ message: 'native watcher stopped' }) - ) - expect(callback).not.toHaveBeenCalled() - expect(child.kill).not.toHaveBeenCalled() - - child.connected = false - child.emit('exit', 1, null) - const replacement = currentWatcherChild(forkMock) - expect(replacement.sent).toEqual([ - expect.objectContaining({ op: 'subscribe', id: otherId, dir: '/other' }) - ]) - }) - - it('waits for physical exit before reporting the last failed subscription', async () => { - const callback = vi.fn() - const pending = supervisor.subscribe('/repo', callback, {}) - const child = currentWatcherChild(forkMock) - const id = acknowledgeWatcherSubscribe(child) - const subscription = await pending - - child.emit('message', { op: 'watch-error', id, message: 'root removed' }) - expect(child.kill).toHaveBeenCalledTimes(1) - expect(callback).not.toHaveBeenCalled() - const closing = subscription.unsubscribe() - const closed = trackPromiseSettlement(closing) - await Promise.resolve() - expect(closed()).toBe(false) - child.emit('exit', 0, null) - await closing - await vi.waitFor(() => expect(callback).toHaveBeenCalledTimes(1)) - expect(callback).toHaveBeenCalledWith(expect.objectContaining({ message: 'root removed' }), []) - expect(forkMock).toHaveBeenCalledTimes(1) - }) - - it('suppresses delayed recovery after supervisor disposal', async () => { - const onTerminalError = vi.fn() - const pending = supervisor.subscribe('/repo', vi.fn(), {}, { onTerminalError }) - const child = currentWatcherChild(forkMock) - const id = acknowledgeWatcherSubscribe(child) - await pending - const keepAlive = supervisor.subscribe('/other', vi.fn(), {}) - acknowledgeWatcherSubscribe(child) - await keepAlive - child.emit('message', { op: 'watch-error', id, message: 'native watcher stopped' }) - supervisor.dispose() - child.emit('message', { op: 'unsubscribed', id }) - await Promise.resolve() - await Promise.resolve() - expect(onTerminalError).not.toHaveBeenCalled() - }) - - it('fences replacement behind physical exit when termination misses its deadline', async () => { - vi.useFakeTimers() - try { - const onTerminalError = vi.fn() - const pending = supervisor.subscribe('/repo', vi.fn(), {}, { onTerminalError }) - const child = currentWatcherChild(forkMock) - const id = acknowledgeWatcherSubscribe(child) - const subscription = await pending - child.emit('message', { op: 'watch-error', id, message: 'native watcher stopped' }) - await vi.advanceTimersByTimeAsync(WATCHER_PROCESS_EXIT_DEADLINE_MS) - - expect(onTerminalError).toHaveBeenCalledTimes(1) - const error = onTerminalError.mock.calls[0]?.[0] - expect(error).toMatchObject({ scope: 'supervisor', physicalExit: expect.any(Promise) }) - let exited = false - void error.physicalExit.then(() => { - exited = true - }) - await expect(subscription.unsubscribe()).rejects.toBe(error) - expect(exited).toBe(false) - child.emit('exit', 0, null) - await error.physicalExit - expect(exited).toBe(true) - } finally { - vi.useRealTimers() - } - }) - - it('reports the removed owner when shared-child teardown misses its exit deadline', async () => { - vi.useFakeTimers() - try { - const onTerminalError = vi.fn() - const pending = supervisor.subscribe('/repo', vi.fn(), {}, { onTerminalError }) - const child = currentWatcherChild(forkMock) - const id = acknowledgeWatcherSubscribe(child) - const subscription = await pending - const otherTerminalError = vi.fn() - const other = supervisor.subscribe( - '/other', - vi.fn(), - {}, - { onTerminalError: otherTerminalError } - ) - acknowledgeWatcherSubscribe(child) - await other - child.emit('message', { op: 'watch-error', id, message: 'native watcher stopped' }) - child.emit('message', { op: 'unsubscribe-failed', id, message: 'native teardown failed' }) - await vi.advanceTimersByTimeAsync(WATCHER_PROCESS_EXIT_DEADLINE_MS) - - expect(onTerminalError).toHaveBeenCalledTimes(1) - expect(otherTerminalError).toHaveBeenCalledTimes(1) - const error = onTerminalError.mock.calls[0]?.[0] - expect(error).toMatchObject({ scope: 'supervisor', physicalExit: expect.any(Promise) }) - await expect(subscription.unsubscribe()).rejects.toBe(error) - child.emit('exit', 0, null) - await error.physicalExit - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-document-lifetime.test.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-document-lifetime.test.ts deleted file mode 100644 index 41b45da9f21..00000000000 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-document-lifetime.test.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { EventEmitter } from 'node:events' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createDebouncedBatch } from './filesystem-watcher-batch-control' - -type WatchArgs = { worktreePath: string; connectionId?: string } -class Sender extends EventEmitter { - constructor(readonly id: number) { - super() - } - isDestroyed = () => false - send = vi.fn() -} -const { handleMock, createLocal } = vi.hoisted(() => ({ - handleMock: vi.fn(), - createLocal: vi.fn() -})) -vi.mock('electron', () => ({ ipcMain: { handle: handleMock } })) -vi.mock('node:fs/promises', () => ({ stat: async () => ({ isDirectory: () => true }) })) -vi.mock('./filesystem-watcher-local-events', () => ({ - createLocalWatcher: createLocal, - scheduleLocalBatchFlush: vi.fn() -})) -vi.mock('../watcher-process/parcel-watcher-process', () => ({ - disposeWatcherProcess: vi.fn() -})) -import { watcherLifecycleState as state } from './filesystem-watcher-lifecycle-state' -import { getLocalWatcherRoot } from './filesystem-watcher-paths' -import { registerFilesystemWatcherHandlers } from './filesystem-watcher-handlers' -import { closeAllWatchers } from './filesystem-watcher-shutdown' -import { - closeLocalWatcherForWorktreePath, - restoreLocalWatcherAfterFailedRemoval -} from './filesystem-watcher-local-removal' - -const handlers = new Map Promise>() -function invoke(channel: string, sender: Sender, args: WatchArgs): Promise { - const handler = handlers.get(channel) - if (!handler) { - throw new Error(`Missing ${channel}`) - } - return handler({ sender }, args) -} -const watch = (sender: Sender, args: WatchArgs) => invoke('fs:watchWorktree', sender, args) -const unwatch = (sender: Sender, args: WatchArgs) => invoke('fs:unwatchWorktree', sender, args) -function deferred() { - let resolve!: (value: T) => void - const promise = new Promise((done) => { - resolve = done - }) - return { promise, resolve } -} -function localRoot(unsubscribe = vi.fn(async () => {})) { - return { - subscription: { unsubscribe }, - listeners: new Map(), - batch: createDebouncedBatch(), - rootPath: '/folder' - } -} - -beforeEach(async () => { - await closeAllWatchers() - vi.clearAllMocks() - createLocal.mockImplementation(async () => localRoot()) - handleMock.mockImplementation((channel, handler) => handlers.set(channel, handler)) - registerFilesystemWatcherHandlers() -}) -afterEach(async () => { - await closeAllWatchers() - vi.useRealTimers() -}) - -describe('filesystem watcher renderer document ownership', () => { - it.each(['did-navigate', 'render-process-gone'])( - 'releases installed local roots on %s without closing sibling owners', - async (event) => { - const sender = new Sender(1) - const sibling = new Sender(2) - const local = { worktreePath: '/folder' } - const root = localRoot() - createLocal.mockResolvedValue(root) - await watch(sender, local) - await watch(sibling, local) - sender.emit(event) - await Promise.resolve() - expect(root.subscription.unsubscribe).not.toHaveBeenCalled() - expect([...root.listeners.keys()]).toEqual([2]) - sibling.emit(event) - await Promise.resolve() - expect(root.subscription.unsubscribe).toHaveBeenCalledTimes(1) - expect(state.watchedRoots.size).toBe(0) - expect(sender.eventNames()).toEqual([]) - expect(sibling.eventNames()).toEqual([]) - } - ) - - it('keeps same-document and blocked navigations alive, and removes lifecycle listeners at shutdown', async () => { - const sender = new Sender(1) - for (let cycle = 0; cycle < 3; cycle++) { - await watch(sender, { worktreePath: '/folder' }) - sender.emit('did-start-navigation') - sender.emit('did-navigate-in-page') - expect(state.watchedRoots.size).toBe(1) - for (const event of ['destroyed', 'did-navigate', 'render-process-gone']) { - expect(sender.listenerCount(event)).toBe(1) - } - await closeAllWatchers() - expect(sender.eventNames()).toEqual([]) - } - }) - - it('does not revive a cancelled setup for a joiner whose document reloaded', async () => { - const sender = new Sender(1) - const joiner = new Sender(2) - const args = { worktreePath: '/folder' } - const install = deferred>() - createLocal.mockReturnValueOnce(install.promise) - const first = watch(sender, args) - await vi.waitFor(() => expect(createLocal).toHaveBeenCalledTimes(1)) - await unwatch(sender, args) - await Promise.resolve() - const key = getLocalWatcherRoot('/folder').key - expect(state.inFlightLocalInstalls.get(key)?.abortController.signal.aborted).toBe(true) - const pendingJoiner = watch(joiner, args) - joiner.emit('did-navigate') - const fresh = watch(joiner, { ...args, worktreePath: '/fresh' }) - const closeLate = vi.fn(async () => {}) - install.resolve(localRoot(closeLate)) - await Promise.all([first, pendingJoiner, fresh]) - expect(createLocal.mock.calls.filter(([path]) => path === '/folder')).toHaveLength(1) - expect(closeLate).toHaveBeenCalledTimes(1) - expect(state.watchedRoots.has(key)).toBe(false) - expect(createLocal).toHaveBeenCalledTimes(2) - }) - - it('aborts pending setup on renderer crash and discards late success', async () => { - const sender = new Sender(1) - const install = deferred>() - createLocal.mockReturnValueOnce(install.promise) - const pending = watch(sender, { worktreePath: '/folder' }) - await vi.waitFor(() => expect(createLocal).toHaveBeenCalledTimes(1)) - const token = [...state.inFlightLocalInstalls.values()][0] - sender.emit('render-process-gone') - await Promise.resolve() - expect(token.abortController.signal.aborted).toBe(true) - const closeLate = vi.fn(async () => {}) - install.resolve(localRoot(closeLate)) - await pending - expect(closeLate).toHaveBeenCalledTimes(1) - expect(state.watchedRoots.size).toBe(0) - }) - - it('does not restore a replaced sibling document after an awaited removal recovery', async () => { - const first = new Sender(1) - const sibling = new Sender(2) - const args = { worktreePath: '/folder' } - await watch(first, args) - await watch(sibling, args) - await closeLocalWatcherForWorktreePath('/folder') - const install = deferred>() - createLocal.mockReturnValueOnce(install.promise) - const restore = restoreLocalWatcherAfterFailedRemoval('/folder') - await vi.waitFor(() => expect(createLocal).toHaveBeenCalledTimes(2)) - sibling.emit('did-navigate') - install.resolve(localRoot()) - await restore - expect(sibling.send).not.toHaveBeenCalled() - expect(first.send).toHaveBeenCalledTimes(1) - expect([...state.watchedRoots.values()][0].listeners.size).toBe(1) - }) -}) diff --git a/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts deleted file mode 100644 index 0e30fcf132e..00000000000 --- a/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - OrcadIdleExitMonitor, - type OrcadIdleProbe, - type OrcadIdleVerdict -} from './orcad-idle-exit-monitor' - -function harness(options: { timeoutMs?: number; lastClientActivityAt?: number } = {}) { - let now = 1_000 - let lastActivity = options.lastClientActivityAt ?? 0 - const verdicts: Record = { clients: 'idle', terminals: 'idle' } - const probes: OrcadIdleProbe[] = Object.keys(verdicts).map((name) => ({ - name, - read: () => { - const verdict = verdicts[name] - if (verdict instanceof Error) { - throw verdict - } - return verdict - } - })) - const onIdle = vi.fn() - const monitor = new OrcadIdleExitMonitor({ - timeoutMs: options.timeoutMs ?? 100, - probes, - lastClientActivityAt: () => lastActivity, - onIdle, - now: () => now, - log: () => {} - }) - return { - monitor, - onIdle, - verdicts, - advance: (ms: number) => (now += ms), - touch: () => (lastActivity = now) - } -} - -describe('OrcadIdleExitMonitor', () => { - it('fires once every probe has stayed idle for the whole quiet period', async () => { - const h = harness() - expect(await h.monitor.check()).toBe(false) - h.advance(99) - expect(await h.monitor.check()).toBe(false) - h.advance(1) - expect(await h.monitor.check()).toBe(true) - expect(h.onIdle).toHaveBeenCalledWith({ quietSince: 1_000, stoppedAt: 1_100, timeoutMs: 100 }) - h.advance(1_000) - expect(await h.monitor.check()).toBe(false) - expect(h.onIdle).toHaveBeenCalledTimes(1) - }) - - it('restarts the quiet period whenever any probe is busy', async () => { - const h = harness() - await h.monitor.check() - h.advance(90) - h.verdicts.terminals = 'busy' - expect(await h.monitor.check()).toBe(false) - h.verdicts.terminals = 'idle' - h.advance(10) - expect(await h.monitor.check()).toBe(false) - h.advance(99) - expect(await h.monitor.check()).toBe(false) - h.advance(1) - expect(await h.monitor.check()).toBe(true) - }) - - it.each([ - ['unverifiable', 'unverifiable' as const], - ['throwing', new Error('daemon did not answer')] - ])('treats a %s probe as busy, never as idle', async (_label, verdict) => { - const h = harness() - h.verdicts.terminals = verdict - for (let i = 0; i < 5; i += 1) { - expect(await h.monitor.check()).toBe(false) - h.advance(100) - } - expect(h.onIdle).not.toHaveBeenCalled() - }) - - it('counts a request that came and went between checks as activity', async () => { - const h = harness() - await h.monitor.check() - h.advance(80) - h.touch() - h.advance(20) - expect(await h.monitor.check()).toBe(false) - h.advance(80) - expect(await h.monitor.check()).toBe(true) - }) - - it('does not fire after it was stopped', async () => { - const h = harness() - await h.monitor.check() - h.monitor.stop() - h.advance(1_000) - expect(await h.monitor.check()).toBe(false) - expect(h.onIdle).not.toHaveBeenCalled() - }) - - it('restarts the quiet period when the final idle stop declines after an asynchronous check', async () => { - const h = harness() - await h.monitor.check() - const decision = Promise.withResolvers() - h.onIdle.mockImplementationOnce(() => decision.promise) - h.advance(100) - const checking = h.monitor.check() - await vi.waitFor(() => expect(h.onIdle).toHaveBeenCalledOnce()) - decision.resolve(false) - expect(await checking).toBe(false) - h.advance(100) - expect(await h.monitor.check()).toBe(false) - h.advance(100) - expect(await h.monitor.check()).toBe(true) - }) -}) diff --git a/src/main/plugins/hooks/plugin-agent-hook-sites.test.ts b/src/main/plugins/hooks/plugin-agent-hook-sites.test.ts deleted file mode 100644 index 33aa5a09bc7..00000000000 --- a/src/main/plugins/hooks/plugin-agent-hook-sites.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { PluginHookName } from '../../../shared/plugins/contributions/plugin-hook-contribution' -import { runPluginHookChain } from '../../../shared/plugins/workers/plugin-hook-chain' -import type { PluginHookChainOutcome } from '../../../shared/plugins/workers/plugin-hook-chain' -import { applyAgentLaunchPluginHook } from '../../ipc/pty/spawn-agent-launch-plugin-hook' -import { - agentPromptHookApplies, - runAgentPromptPluginHook -} from '../../runtime/terminal/input/terminal-send-plugin-hook' -import { setPluginHookRunner } from './plugin-hook-dispatch' - -const { resumeCheck } = vi.hoisted(() => ({ - resumeCheck: vi.fn<(command: string, ensureHost: () => Promise) => Promise>() -})) -vi.mock('../../ai-vault/structured-sessions/structured-session-ownership', () => ({ - assertLegacyAiVaultResumeCommandAllowed: resumeCheck -})) - -const runtime = { ensureStructuredAgentSessionHost: vi.fn(async () => undefined) } - -type Decide = (event: PluginHookName, payload: unknown) => PluginHookChainOutcome - -function installRunner(decide: Decide, wanted: readonly PluginHookName[]) { - const run = vi.fn(async (event: PluginHookName, payload: unknown) => decide(event, payload)) - setPluginHookRunner({ wants: (event) => wanted.includes(event), run }) - return run -} - -const rewrite = - (changes: Record): Decide => - (_event, payload) => ({ kind: 'continue', payload: { ...Object(payload), ...changes } }) - -afterEach(() => { - setPluginHookRunner(null) - resumeCheck.mockReset() - vi.unstubAllGlobals() -}) - -describe('agent.launch.before at the spawn', () => { - const launch = { - launchAgent: 'claude' as const, - command: "claude 'fix the bug'", - env: { ORCA_TERMINAL_HANDLE: 'h', PATH: '/bin' }, - worktreeId: 'folder:notes', - preAllocatedHandle: 'term_1', - cols: 80 - } - - it('shows the agent, workspace and command but never the environment, and applies changes', async () => { - const run = installRunner(rewrite({ command: 'claude --verbose', env: { FOO: '1' } }), [ - 'agent.launch.before' - ]) - await expect(applyAgentLaunchPluginHook(launch, runtime)).resolves.toEqual({ - ...launch, - command: 'claude --verbose', - env: { ...launch.env, FOO: '1' } - }) - expect(run).toHaveBeenCalledWith('agent.launch.before', { - agent: 'claude', - workspaceId: 'folder:notes', - workspaceKind: 'folder', - terminalId: 'term_1', - command: "claude 'fix the bug'", - env: {} - }) - }) - - it('rechecks a rewritten command the way the caller checked its own', async () => { - installRunner(rewrite({ command: 'codex resume chat-owned' }), ['agent.launch.before']) - resumeCheck.mockRejectedValueOnce(new Error('owned by a chat')) - await expect(applyAgentLaunchPluginHook(launch, runtime)).rejects.toThrow('owned by a chat') - expect(resumeCheck).toHaveBeenCalledWith('codex resume chat-owned', expect.any(Function)) - installRunner(rewrite({}), ['agent.launch.before']) - await applyAgentLaunchPluginHook(launch, runtime) - expect(resumeCheck).toHaveBeenCalledOnce() - }) - - it('names added variables in WSLENV on Windows so WSL agents receive them', async () => { - vi.stubGlobal('process', { ...process, platform: 'win32', env: { WSLENV: 'USERPROFILE/p' } }) - installRunner(rewrite({ env: { FOO: '1' } }), ['agent.launch.before']) - const decided = await applyAgentLaunchPluginHook(launch, runtime) - expect(decided.env).toMatchObject({ FOO: '1', WSLENV: 'USERPROFILE/p:FOO' }) - }) - - it('keeps Orca’s own variables out of a plugin’s reach', async () => { - const outcome = await runPluginHookChain({ - event: 'agent.launch.before', - payload: { - agent: 'codex', - workspaceId: null, - workspaceKind: null, - command: 'codex', - env: {} - }, - participants: ['acme.env'], - invoke: async (_key, payload) => ({ - decision: 'continue', - payload: { ...Object(payload), env: { ORCA_AGENT_LAUNCH_TOKEN: 'stolen' } } - }), - log: vi.fn(), - now: () => 0 - }) - expect(outcome).toMatchObject({ kind: 'continue', payload: { env: {} } }) - }) -}) - -describe('agent.prompt.before', () => { - const allowed = vi.fn(async () => undefined) - const input = { - handle: 'term_1', - prompt: 'fix it', - inputKind: 'orchestration' as const, - agent: 'codex' - } - - it('rewrites the prompt with the agent named and rechecks the rewrite', async () => { - const run = installRunner(rewrite({ prompt: 'be brief: fix it' }), ['agent.prompt.before']) - await expect(runAgentPromptPluginHook(input, allowed)).resolves.toBe('be brief: fix it') - expect(run).toHaveBeenCalledWith('agent.prompt.before', { - agent: 'codex', - terminalId: 'term_1', - prompt: 'fix it', - inputKind: 'orchestration' - }) - expect(allowed).toHaveBeenCalledWith('be brief: fix it') - const refuse = vi.fn(async () => { - throw new Error('legacy writer refused') - }) - await expect(runAgentPromptPluginHook(input, refuse)).rejects.toThrow('legacy writer refused') - }) - - it('denies, and never holds a person’s own prompt', async () => { - installRunner( - () => ({ kind: 'deny', pluginKey: 'acme.p', reason: 'secret' }), - ['agent.prompt.before'] - ) - await expect(runAgentPromptPluginHook(input, allowed)).rejects.toThrow( - 'agent.prompt.before denied by plugin acme.p: secret' - ) - expect(agentPromptHookApplies({})).toBe(true) - expect(agentPromptHookApplies({ inputSource: 'programmatic' })).toBe(true) - expect(agentPromptHookApplies({ inputSource: 'desktop' })).toBe(false) - expect(agentPromptHookApplies({ inputSource: 'mobile' })).toBe(false) - setPluginHookRunner(null) - expect(agentPromptHookApplies({})).toBe(false) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-start-terminal-target.spec.ts b/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-start-terminal-target.spec.ts deleted file mode 100644 index cdee0a1657b..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/start/placement/worker-start-terminal-target.spec.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { createOrchestrationWorkerReleaseHarness } from '../../testing/worker-release.test-support' - -export function registerWorkerStartTerminalTargetTests(): void { - describe('worker-start --terminal target', () => { - const harness = createOrchestrationWorkerReleaseHarness() - beforeEach(() => harness.setup()) - afterEach(() => harness.cleanup()) - - it('refuses the coordinator terminal by handle', async () => { - const task = harness.db.createTask({ spec: 'self adoption', runId: harness.activeRunId }) - - await expect( - harness.call('orchestration.workerStart', { - task: task.id, - from: 'term_coord', - terminal: 'term_coord' - }) - ).rejects.toMatchObject({ - code: 'terminal_is_coordinator', - message: expect.stringContaining("coordinator's own terminal") - }) - expect(harness.db.getDispatchContext(task.id)).toBeUndefined() - }) - - it('refuses a different handle that resolves to the coordinator pane', async () => { - const task = harness.db.createTask({ - spec: 'self adoption alias', - runId: harness.activeRunId - }) - vi.spyOn(harness.runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === 'term_coord' || handle === 'term_coord_alias' ? harness.coordinatorPaneKey : null - ) - - await expect( - harness.call('orchestration.workerStart', { - task: task.id, - from: 'term_coord', - terminal: 'term_coord_alias' - }) - ).rejects.toMatchObject({ code: 'terminal_is_coordinator' }) - }) - }) - - // Manual inject is another self-adoption path; compare target with caller too. - describe('orchestration.dispatch --to the caller', () => { - const harness = createOrchestrationWorkerReleaseHarness() - beforeEach(() => harness.setup()) - afterEach(() => harness.cleanup()) - - it('refuses an injected dispatch aimed at the coordinator handle', async () => { - vi.spyOn(harness.runtime, 'getOrchestrationDispatchAuthority').mockImplementation( - (handle) => - ({ - terminalHandle: handle, - paneKey: harness.coordinatorPaneKey, - processIncarnation: 'runtime_test:term_coord:1' - }) as never - ) - const task = harness.db.createTask({ spec: 'self dispatch', runId: harness.activeRunId }) - - await expect( - harness.call('orchestration.dispatch', { - task: task.id, - from: 'term_coord', - to: 'term_coord', - inject: true - }) - ).rejects.toMatchObject({ code: 'terminal_is_coordinator' }) - expect(harness.db.getDispatchContext(task.id)).toBeUndefined() - expect(harness.runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() - }) - - it('refuses an injected dispatch to a different handle that resolves to the coordinator pane', async () => { - vi.spyOn(harness.runtime, 'getTerminalPaneKey').mockImplementation((handle) => - handle === 'term_coord' || handle === 'term_coord_alias' ? harness.coordinatorPaneKey : null - ) - vi.spyOn(harness.runtime, 'getOrchestrationDispatchAuthority').mockImplementation( - (handle) => - ({ - terminalHandle: handle, - paneKey: harness.coordinatorPaneKey, - processIncarnation: 'runtime_test:term_coord:1' - }) as never - ) - const task = harness.db.createTask({ - spec: 'self dispatch alias', - runId: harness.activeRunId - }) - - await expect( - harness.call('orchestration.dispatch', { - task: task.id, - from: 'term_coord', - to: 'term_coord_alias', - inject: true - }) - ).rejects.toMatchObject({ code: 'terminal_is_coordinator' }) - }) - - // Context-only self-dispatch writes no preamble and remains valid for low-level topologies. - it('still records a context-only dispatch aimed at the coordinator handle', async () => { - const task = harness.db.createTask({ spec: 'self context', runId: harness.activeRunId }) - - const result = (await harness.call('orchestration.dispatch', { - task: task.id, - from: 'term_coord', - to: 'term_coord' - })) as { dispatch: { id: string; status: string } } - - expect(result.dispatch.status).toBe('dispatched') - expect(harness.db.getDispatchContextById(result.dispatch.id)?.assignee_handle).toBe( - 'term_coord' - ) - expect(harness.runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() - }) - - // Self-injection must refuse regardless of agent detection; without-inject advice cannot authorize it. - it.each([ - ['the coordinator handle', 'term_coord'], - ['an alias of the coordinator pane', 'term_coord_alias'] - ])('refuses %s even when no agent is detected', async (_label, target) => { - vi.spyOn(harness.runtime, 'isTerminalRunningAgent').mockResolvedValue(false) - vi.spyOn(harness.runtime, 'getOrchestrationDispatchAuthority').mockImplementation( - (handle) => - (handle === 'term_coord_alias' - ? { - terminalHandle: handle, - paneKey: harness.coordinatorPaneKey, - processIncarnation: 'runtime_test:term_coord:1' - } - : null) as never - ) - const task = harness.db.createTask({ - spec: `self inject ${target}`, - runId: harness.activeRunId - }) - - await expect( - harness.call('orchestration.dispatch', { - task: task.id, - from: 'term_coord', - to: target, - inject: true - }) - ).rejects.toMatchObject({ code: 'terminal_is_coordinator' }) - expect(harness.db.getDispatchContext(task.id)).toBeUndefined() - }) - }) -} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/testing/worker-run-dispatch-contracts.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/testing/worker-run-dispatch-contracts.test.ts index 15743810727..c6064534297 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/testing/worker-run-dispatch-contracts.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/testing/worker-run-dispatch-contracts.test.ts @@ -1,5 +1,3 @@ import { registerWorkerListRunScopeRpcTests } from '../fleet/worker-list-run-scope-rpc.spec' -import { registerWorkerStartTerminalTargetTests } from '../start/placement/worker-start-terminal-target.spec' registerWorkerListRunScopeRpcTests() -registerWorkerStartTerminalTargetTests() diff --git a/src/main/ssh/authentication/ssh-keyboard-interactive.test.ts b/src/main/ssh/authentication/ssh-keyboard-interactive.test.ts deleted file mode 100644 index 43e4f362d3e..00000000000 --- a/src/main/ssh/authentication/ssh-keyboard-interactive.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - collectKeyboardInteractiveResponses, - isKeyboardInteractivePasswordPrompt, - type KeyboardInteractiveSession -} from './ssh-keyboard-interactive' - -function createSession( - overrides: Partial = {} -): KeyboardInteractiveSession & { cancelled: { value: boolean } } { - const cancelled = { value: false } - return { - targetId: 'target-1', - hostDetail: 'example.com', - requestCredential: vi.fn(async () => 'answer'), - getCachedPassword: () => null, - setCachedPassword: vi.fn(), - markCachedPasswordRejected: vi.fn(), - markCancelled: () => { - cancelled.value = true - }, - isCancelled: () => cancelled.value, - state: { passwordAutoAnswered: false }, - cancelled, - ...overrides - } -} - -describe('isKeyboardInteractivePasswordPrompt', () => { - it('rejects echoed prompts even when they mention a password', () => { - expect(isKeyboardInteractivePasswordPrompt({ prompt: 'Password: ', echo: true })).toBe(false) - }) - - it('rejects one-time password and OTP prompts', () => { - expect(isKeyboardInteractivePasswordPrompt({ prompt: 'One-time password:', echo: false })).toBe( - false - ) - expect(isKeyboardInteractivePasswordPrompt({ prompt: 'OTP password code:', echo: false })).toBe( - false - ) - }) -}) - -describe('collectKeyboardInteractiveResponses', () => { - it('answers a password prompt from the cache without prompting', async () => { - const requestCredential = vi.fn(async () => 'unused') - const session = createSession({ - requestCredential, - getCachedPassword: () => 'password-123' - }) - - const responses = await collectKeyboardInteractiveResponses(session, '', [ - { prompt: 'Password: ', echo: false } - ]) - - expect(responses).toEqual(['password-123']) - expect(requestCredential).not.toHaveBeenCalled() - expect(session.state.passwordAutoAnswered).toBe(true) - }) - - it('re-prompts when the server rejects the auto-answered cached password', async () => { - const requestCredential = vi.fn(async () => 'corrected-password') - const setCachedPassword = vi.fn() - const markCachedPasswordRejected = vi.fn() - const session = createSession({ - requestCredential, - getCachedPassword: () => 'stale-password', - setCachedPassword, - markCachedPasswordRejected, - state: { passwordAutoAnswered: true } - }) - - const responses = await collectKeyboardInteractiveResponses(session, '', [ - { prompt: 'Password: ', echo: false } - ]) - - expect(responses).toEqual(['corrected-password']) - expect(markCachedPasswordRejected).toHaveBeenCalledTimes(1) - expect(requestCredential).toHaveBeenCalledWith('target-1', 'password', 'example.com') - expect(setCachedPassword).toHaveBeenCalledWith('corrected-password') - }) - - it('returns null and marks the session cancelled when the user dismisses a prompt', async () => { - const session = createSession({ requestCredential: vi.fn(async () => null) }) - - const responses = await collectKeyboardInteractiveResponses(session, '', [ - { prompt: 'Duo passcode:', echo: false } - ]) - - expect(responses).toBeNull() - expect(session.isCancelled()).toBe(true) - }) - - it('discards a password resolved after the attempt is cancelled', async () => { - let answer: (value: string) => void = () => {} - const requestCredential = vi - .fn(async () => 'code') - .mockImplementationOnce( - () => - new Promise((resolve) => { - answer = resolve - }) - ) - const setCachedPassword = vi.fn() - const session = createSession({ requestCredential, setCachedPassword }) - const collecting = collectKeyboardInteractiveResponses(session, '', [ - { prompt: 'Password:', echo: false }, - { prompt: 'Code:', echo: false } - ]) - session.markCancelled() - answer('obsolete-password') - expect(await collecting).toBeNull() - expect(setCachedPassword).not.toHaveBeenCalled() - expect(requestCredential).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/components/agent/agent-launch-picker-retirement.test.ts b/src/renderer/src/components/agent/agent-launch-picker-retirement.test.ts deleted file mode 100644 index 94a270f9890..00000000000 --- a/src/renderer/src/components/agent/agent-launch-picker-retirement.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { expect, it } from 'vitest' -import type { AgentPickerRetainedSetup } from '../../../../shared/agent-launch/picker/agent-launch-picker-authority' -import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' -import { retireAgentPickerSetups } from './agent-launch-picker-retirement' - -const entry: AgentPickerEntry = { - agent: 'codex', - label: 'Codex', - rows: [{ agent: 'codex', kind: 'cli' }], - surfaces: ['terminal'], - defaultSurface: 'terminal', - terminal: {}, - structured: {}, - catalog: { - origin: 'probe', - fetchedAt: 1, - models: [{ id: 'saved', label: 'Saved', isDefault: false, efforts: [] }] - } -} - -it('preserves edited presets until a completed catalog confirms their model or effort was removed', () => { - const setups = new Map([ - [ - 'missing-model', - { - target: undefined, - agent: 'codex', - preset: { model: 'fresh' }, - source: undefined, - draft: { - agent: 'codex', - surface: 'terminal', - choices: { model: 'saved' }, - arguments: '--add-dir model-edits' - }, - active: false - } - ], - [ - 'missing-effort', - { - target: undefined, - agent: 'codex', - preset: { model: 'saved', effort: 'high' }, - source: undefined, - draft: { - agent: 'codex', - surface: 'terminal', - choices: { model: 'saved', options: { effort: 'low' } }, - arguments: '--add-dir effort-edits' - }, - active: false - } - ] - ]) - for (const catalogRead of ['pending', 'failed', 'unsupported'] as const) { - retireAgentPickerSetups([{ ...entry, catalogRead }], setups, undefined, 'select') - expect([...setups.values()].map(({ draft }) => draft.arguments)).toEqual([ - '--add-dir model-edits', - '--add-dir effort-edits' - ]) - } - - retireAgentPickerSetups( - [ - { - ...entry, - catalogRead: 'settled', - catalog: { - origin: 'probe', - fetchedAt: 2, - models: [ - { id: 'fresh', label: 'Fresh', isDefault: false, efforts: [] }, - { - id: 'saved', - label: 'Saved', - isDefault: false, - efforts: [{ value: 'high', label: 'High' }] - } - ] - } - } - ], - setups, - undefined, - 'select' - ) - expect([...setups.values()].map(({ draft }) => draft.arguments)).toEqual([ - '--add-dir model-edits', - '--add-dir effort-edits' - ]) - - retireAgentPickerSetups([{ ...entry, catalogRead: 'settled' }], setups, undefined, 'select') - expect([...setups.keys()]).toEqual([]) -}) diff --git a/src/renderer/src/components/automations/authoring/automation-legacy-schedule-editing.test.ts b/src/renderer/src/components/automations/authoring/automation-legacy-schedule-editing.test.ts deleted file mode 100644 index f6db545bc1d..00000000000 --- a/src/renderer/src/components/automations/authoring/automation-legacy-schedule-editing.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { Automation } from '../../../../../shared/automations/automation-definition' -import { isValidAutomationSchedule } from '../../../../../shared/automations/scheduling/automation-schedule-parsing' - -import { buildAutomationEditDraft } from './automation-edit-draft' - -import { acceptsAutomationDraftSchedule } from '../../../../../shared/automations/scheduling/automation-schedule-input-gate' - -// `*/90` on minutes was accepted before the oversized-step refusal (#15895) and still runs, -// firing at :00. Only a row persisted by an older build can hold it. -const LEGACY_OVERSIZED_STEP = '*/90 * * * *' - -const makeAutomation = (overrides: Partial = {}): Automation => ({ - id: 'a1', - name: 'Nightly sweep', - prompt: 'Check the repo', - precheck: null, - agentId: 'claude', - projectId: 'r1', - executionTargetType: 'local', - executionTargetId: 'local', - schedulerOwner: 'local_host_service', - workspaceMode: 'existing', - workspaceId: 'wt1', - baseBranch: null, - reuseSession: false, - timezone: 'UTC', - rrule: LEGACY_OVERSIZED_STEP, - dtstart: 0, - enabled: true, - nextRunAt: 0, - missedRunPolicy: 'run_once_within_grace', - missedRunGraceMinutes: 720, - createdAt: 0, - updatedAt: 0, - ...overrides -}) - -describe('editing an automation whose saved schedule predates the input gate', () => { - it('opens the editor with the saved schedule intact and no warning', () => { - const draft = buildAutomationEditDraft(makeAutomation()) - expect(draft.preset).toBe('custom') - expect(draft.customSchedule).toBe(LEGACY_OVERSIZED_STEP) - expect(draft.scheduleWarning).toBeNull() - }) - - // Untouched legacy schedules must not block unrelated renames behind re-authoring. - - it('still refuses a schedule the user actually changes', () => { - const automation = makeAutomation() - for (const edited of ['*/91 * * * *', '0 */25 * * *', 'nonsense']) { - expect( - acceptsAutomationDraftSchedule({ - customSchedule: edited, - savedRrule: automation.rrule, - validate: isValidAutomationSchedule - }) - ).toBe(false) - } - }) - - it('refuses an oversized step on a new automation, which has nothing saved', () => { - expect( - acceptsAutomationDraftSchedule({ - customSchedule: LEGACY_OVERSIZED_STEP, - savedRrule: null, - validate: isValidAutomationSchedule - }) - ).toBe(false) - }) - - // Only oversized steps receive legacy leniency; unparseable schedules still need warnings. -}) diff --git a/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-local-images.test.ts b/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-local-images.test.ts deleted file mode 100644 index 0c755179474..00000000000 --- a/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-local-images.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - extractMarkdownPreviewLocalImageCandidates, - prewarmMarkdownPreviewLocalImages -} from './markdown-preview-local-images' - -async function flushPromises(): Promise { - await Promise.resolve() - await Promise.resolve() -} - -function markdownImages(count: number): string { - return Array.from({ length: count }, (_, index) => `![${index}](images/${index}.png)`).join('\n') -} - -describe('extractMarkdownPreviewLocalImageCandidates', () => { - it('extracts direct, reference-style, and GFM table images in document order', () => { - const candidates = extractMarkdownPreviewLocalImageCandidates( - [ - '![Direct](./direct.png)', - '![Reference][logo]', - '', - '| Asset |', - '| --- |', - '| ![Table](table.png) |', - '', - '[logo]: ../assets/logo.png' - ].join('\n'), - '/repo/docs/readme.md' - ) - - expect(candidates.map((candidate) => candidate.absolutePath)).toEqual([ - '/repo/docs/direct.png', - '/repo/assets/logo.png', - '/repo/docs/table.png' - ]) - }) -}) - -describe('prewarmMarkdownPreviewLocalImages', () => { - it('never starts more reads than the concurrency limit at once', async () => { - const releaseNext: (() => void)[] = [] - const started: string[] = [] - let active = 0 - let maxActive = 0 - - const prewarm = prewarmMarkdownPreviewLocalImages(markdownImages(6), '/repo/docs/readme.md', { - concurrency: 2, - loadImage: (candidate) => { - started.push(candidate.absolutePath) - active += 1 - maxActive = Math.max(maxActive, active) - return new Promise((resolve) => { - releaseNext.push(() => { - active -= 1 - resolve(null) - }) - }) - } - }) - - expect(started).toHaveLength(2) - releaseNext.shift()?.() - await flushPromises() - expect(started).toHaveLength(3) - - while (releaseNext.length > 0) { - releaseNext.shift()?.() - await flushPromises() - } - await prewarm.done - - expect(maxActive).toBe(2) - expect(started).toHaveLength(6) - }) - - it('stops scheduling not-yet-started work after cancellation', async () => { - const pending: (() => void)[] = [] - const started: string[] = [] - const prewarm = prewarmMarkdownPreviewLocalImages(markdownImages(5), '/repo/docs/readme.md', { - concurrency: 2, - loadImage: (candidate) => { - started.push(candidate.absolutePath) - return new Promise((resolve) => { - pending.push(() => resolve(null)) - }) - } - }) - - expect(started).toHaveLength(2) - prewarm.cancel() - for (const release of pending) { - release() - } - await prewarm.done - - expect(started).toHaveLength(2) - }) -}) diff --git a/src/renderer/src/components/editor/markdown-preview/viewport/use-preserve-section-during-external-edit.test.tsx b/src/renderer/src/components/editor/markdown-preview/viewport/use-preserve-section-during-external-edit.test.tsx deleted file mode 100644 index 25f338e2f3f..00000000000 --- a/src/renderer/src/components/editor/markdown-preview/viewport/use-preserve-section-during-external-edit.test.tsx +++ /dev/null @@ -1,90 +0,0 @@ -// @vitest-environment happy-dom -import { useRef } from 'react' -import { act, cleanup, render } from '@testing-library/react' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { usePreserveSectionDuringExternalEdit } from './usePreserveSectionDuringExternalEdit' - -let now = 0 -let nextFrame = 0 -const frames = new Map() - -function Preview({ content }: { content: string }) { - const body = useRef(null) - const rendered = usePreserveSectionDuringExternalEdit(content, body) - return
{rendered}
-} - -beforeEach(() => { - now = 0 - nextFrame = 0 - frames.clear() - vi.spyOn(performance, 'now').mockImplementation(() => now) - vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => { - const id = ++nextFrame - frames.set(id, callback) - return id - }) - vi.spyOn(window, 'cancelAnimationFrame').mockImplementation((id) => { - frames.delete(id) - }) -}) - -afterEach(() => { - cleanup() - window.getSelection()?.removeAllRanges() - vi.restoreAllMocks() -}) - -function fixture() { - const view = render() - return { - ...view, - update(content: string, time: number) { - now = time - view.rerender() - }, - frame(time: number) { - now = time - const pending = [...frames.values()] - frames.clear() - act(() => { - for (const callback of pending) { - callback(time) - } - }) - }, - select() { - const node = view.container.firstChild?.firstChild - const selection = window.getSelection() - if (!node || !selection) { - throw new Error('Expected a selectable preview text node') - } - const range = document.createRange() - range.setStart(node, 0) - range.setEnd(node, 3) - selection.removeAllRanges() - selection.addRange(range) - } - } -} - -it('applies the latest external source by the original deadline during continuous edits', () => { - const view = fixture() - view.select() - for (let step = 1; step <= 3; step++) { - view.update(`external-${step}`, step * 1000) - view.frame(step * 1000) - expect(view.container.textContent).toBe('initial selected text') - } - view.frame(3999) - expect(view.container.textContent).toBe('initial selected text') - view.update('external-4', 4000) - view.frame(4000) - expect(view.container.textContent).toBe('external-4') - view.select() - view.update('next episode', 4500) - view.frame(7499) - expect(view.container.textContent).toBe('external-4') - view.frame(7500) - expect(view.container.textContent).toBe('next episode') -}) diff --git a/src/renderer/src/components/editor/monaco/monaco-cursor-line-lifetime.test.ts b/src/renderer/src/components/editor/monaco/monaco-cursor-line-lifetime.test.ts deleted file mode 100644 index 1c9b7040426..00000000000 --- a/src/renderer/src/components/editor/monaco/monaco-cursor-line-lifetime.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { editor } from 'monaco-editor' -import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { createEditorStore } from '@/store/slices/editor/editor-slice-test-harness' -import { installMonacoViewStateTracking } from './monaco-view-state-persistence' - -function makeFile(id: string, filePath: string): OpenFile { - return { - id, - filePath, - relativePath: 'file.ts', - worktreeId: 'wt-1', - language: 'typescript', - mode: 'edit', - isDirty: false - } -} - -function startTracking( - store: ReturnType, - file: OpenFile, - line: number -): ReturnType { - const mockEditor = { - getPosition: () => ({ lineNumber: line, column: 1 }), - onDidChangeCursorPosition: () => ({ dispose: vi.fn() }), - onDidScrollChange: () => ({ dispose: vi.fn() }) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Cursor tracking calls only the three mocked editor methods above. - const editorInstance = mockEditor as unknown as editor.IStandaloneCodeEditor - const params = { - editorInstance, - fileIdRef: { current: file.id }, - viewStateKey: file.id, - scrollThrottleTimerRef: { current: null }, - setEditorCursorLine: store.getState().setEditorCursorLine - } - return installMonacoViewStateTracking(params) -} - -describe('Monaco cursor-line ownership lifetime', () => { - it('isolates same-path positions and closes only the selected file identity', () => { - const store = createEditorStore() - const local = makeFile('editor:wt-1:local:file.ts', '/repo/file.ts') - const remote = { - ...makeFile('editor:wt-1:remote-a:file.ts', '/repo/file.ts'), - runtimeEnvironmentId: 'remote-a' - } - store.setState({ openFiles: [local, remote], unifiedTabsByWorktree: {} }) - const localTracking = startTracking(store, local, 12) - const remoteTracking = startTracking(store, remote, 35) - - expect(store.getState().editorCursorLine).toEqual({ [local.id]: 12, [remote.id]: 35 }) - localTracking.cursorPositionSub.dispose() - localTracking.scrollStateSub.dispose() - store.getState().closeFile(local.id) - expect(store.getState().editorCursorLine).toEqual({ [remote.id]: 35 }) - remoteTracking.cursorPositionSub.dispose() - remoteTracking.scrollStateSub.dispose() - store.getState().closeFile(remote.id) - expect(store.getState().editorCursorLine).toEqual({}) - }) -}) diff --git a/src/renderer/src/components/native-chat/pane/routing/native-chat-leaf-routing.test.ts b/src/renderer/src/components/native-chat/pane/routing/native-chat-leaf-routing.test.ts deleted file mode 100644 index 83ea68e3765..00000000000 --- a/src/renderer/src/components/native-chat/pane/routing/native-chat-leaf-routing.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resolveNativeChatLeafRoute } from './native-chat-leaf-routing' - -describe('resolveNativeChatLeafRoute', () => { - it('keeps chat attached to its eligible leaf when focus moves to a shell sibling', () => { - expect( - resolveNativeChatLeafRoute({ - isChatViewMode: true, - chatLeafId: 'agent-leaf', - activeLeafId: 'shell-leaf', - chatLeafStillMounted: true, - activeLeafIsEligible: false - }) - ).toEqual({ chatLeafId: 'agent-leaf', exitChat: false }) - }) - - it('exits chat when the user closes its pane', () => { - expect( - resolveNativeChatLeafRoute({ - isChatViewMode: true, - chatLeafId: 'closed-leaf', - activeLeafId: 'agent-sibling', - chatLeafStillMounted: false, - activeLeafIsEligible: true - }) - ).toEqual({ chatLeafId: null, exitChat: true }) - }) - - it('exits chat when the mounted agent has authoritatively returned to its shell', () => { - expect( - resolveNativeChatLeafRoute({ - isChatViewMode: true, - chatLeafId: 'exited-agent', - activeLeafId: 'exited-agent', - chatLeafStillMounted: true, - activeLeafIsEligible: true, - chatLeafHasConfirmedAgentExit: true - }) - ).toEqual({ chatLeafId: null, exitChat: true }) - }) - - it('moves chat to an eligible sibling after the owning agent exits', () => { - expect( - resolveNativeChatLeafRoute({ - isChatViewMode: true, - chatLeafId: 'exited-agent', - activeLeafId: 'agent-sibling', - chatLeafStillMounted: true, - activeLeafIsEligible: true, - chatLeafHasConfirmedAgentExit: true - }) - ).toEqual({ chatLeafId: 'agent-sibling', exitChat: false }) - }) - - it('attaches a tab-level chat request to the eligible active leaf', () => { - expect( - resolveNativeChatLeafRoute({ - isChatViewMode: true, - chatLeafId: null, - activeLeafId: 'active-agent', - chatLeafStillMounted: false, - activeLeafIsEligible: true - }) - ).toEqual({ chatLeafId: 'active-agent', exitChat: false }) - }) - - it('waits through manager hydration when there is no concrete active leaf', () => { - expect( - resolveNativeChatLeafRoute({ - isChatViewMode: true, - chatLeafId: 'restored-agent', - activeLeafId: null, - chatLeafStillMounted: false, - activeLeafIsEligible: false - }) - ).toEqual({ chatLeafId: 'restored-agent', exitChat: false }) - }) -}) diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.test.ts b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.test.ts deleted file mode 100644 index 4eb18bec2be..00000000000 --- a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { Tab } from '../../../../../../shared/tab-types' -import { replaceTabBuckets } from '@/store/keyed-record-transitions' -import { getStructuredAgentSessionTabs } from './structured-agent-session-tabs' - -function tab(id: string, worktreeId: string, contentType: Tab['contentType']): Tab { - return { - id, - worktreeId, - groupId: 'group', - contentType, - entityId: contentType === 'agent-session' ? 'session-shared' : id, - label: id, - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 0, - isPinned: false, - ...(contentType === 'agent-session' ? { agentSessionAgent: 'codex' as const } : {}) - } -} - -const ids = (map: Record) => getStructuredAgentSessionTabs(map).map((t) => t.id) - -describe('getStructuredAgentSessionTabs order', () => { - it('keeps source workspace order through addressed close and reopen', () => { - const start = { - early: [tab('t1', 'early', 'terminal'), tab('c1', 'early', 'agent-session')], - later: [tab('c2', 'later', 'agent-session')] - } - expect(ids(start)).toEqual(['c1', 'c2']) - const closed = replaceTabBuckets(start, [['early', [start.early[0]]]]) - expect(ids(closed)).toEqual(['c2']) - const reopened = replaceTabBuckets(closed, [ - ['early', [start.early[0], tab('c1b', 'early', 'agent-session')]] - ]) - expect(ids(reopened)).toEqual(['c1b', 'c2']) - expect(ids({ ...reopened })).toEqual(['c1b', 'c2']) - }) - - it('follows source order when a workspace is deleted and added back', () => { - const start = { - early: [tab('c1', 'early', 'agent-session')], - later: [tab('c2', 'later', 'agent-session')] - } - expect(ids(start)).toEqual(['c1', 'c2']) - const removed = replaceTabBuckets(start, [['early', null]]) - const restored = replaceTabBuckets(removed, [['early', start.early]]) - expect(ids(restored)).toEqual(['c2', 'c1']) - expect(ids({ ...restored })).toEqual(['c2', 'c1']) - }) - - it('keeps the list through chatless workspace changes and places new workspaces last', () => { - const start = { a: [tab('c1', 'a', 'agent-session')] } - const list = getStructuredAgentSessionTabs(start) - const added = replaceTabBuckets(start, [['b', [tab('t1', 'b', 'terminal')]]]) - expect(getStructuredAgentSessionTabs(added)).toBe(list) - const chat = replaceTabBuckets(added, [ - ['b', [tab('t1', 'b', 'terminal'), tab('cb', 'b', 'agent-session')]] - ]) - expect(ids(chat)).toEqual(['c1', 'cb']) - const removed = replaceTabBuckets(chat, [['a', null]]) - expect(ids(removed)).toEqual(['cb']) - expect(ids({ ...removed })).toEqual(['cb']) - }) -}) diff --git a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-handoff.test.ts b/src/renderer/src/components/native-chat/subagents/native-chat-subagent-handoff.test.ts deleted file mode 100644 index 359d9d5f663..00000000000 --- a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-handoff.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AgentJournalRenderItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types' -import { nativeChatSubagentHandoff } from './native-chat-subagent-handoff' - -function row(id: string, blocks: NativeChatMessage['blocks']): NativeChatMessage { - return { id, role: 'assistant', blocks, timestamp: 1, source: 'transcript' } -} - -describe('nativeChatSubagentHandoff', () => { - it("reads a Claude subagent's prompt and reply from the Agent call its run names", () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handoff reads only each item's body blocks. - const journalItems = [ - { - itemId: 'spawn', - revision: 1, - sequence: 2, - observedAt: 1, - body: { - kind: 'message', - role: 'assistant', - blocks: [ - { - type: 'subagent', - id: 'agent-a', - label: 'List src', - state: 'completed', - groupId: 'g', - run: 'toolu_2' - } - ] - } - } - ] as unknown as AgentJournalRenderItem[] - const conversation = [ - row('call', [ - { type: 'tool-call', name: 'Agent', callId: 'toolu_1', input: { prompt: 'Other task' } }, - { type: 'tool-call', name: 'Agent', callId: 'toolu_2', input: { prompt: 'List src/' } }, - { type: 'tool-result', callId: 'toolu_1', output: 'Other reply' }, - { - type: 'tool-result', - callId: 'toolu_2', - output: - ' Bash\n \n[Subagent hand-back] The report follows:\n src holds:\n \n - `math.ts`' - } - ]) - ] - expect( - nativeChatSubagentHandoff({ - agentId: 'agent-a', - journalItems, - conversation, - subagentRows: new Map() - }) - ).toEqual({ prompt: 'List src/', reply: 'src holds:\n\n- `math.ts`', error: null }) - }) - - it("reads a Codex subagent's prompt from the spawn call naming it, leaving its reply to its own rows", () => { - const conversation = [ - row('spawn', [ - { - type: 'tool-call', - name: 'spawn_agent', - callId: 'call_1', - input: { agents: ['thread-child'], prompt: 'Map token refresh' } - }, - { type: 'tool-result', callId: 'call_1', output: 'Spawned' } - ]) - ] - expect( - nativeChatSubagentHandoff({ - agentId: 'thread-child', - journalItems: [], - conversation, - subagentRows: new Map() - }) - ).toEqual({ prompt: 'Map token refresh', reply: null, error: null }) - }) -}) diff --git a/src/renderer/src/components/native-chat/tools/runs/native-chat-tool-fold.test.ts b/src/renderer/src/components/native-chat/tools/runs/native-chat-tool-fold.test.ts deleted file mode 100644 index 1821a4904ca..00000000000 --- a/src/renderer/src/components/native-chat/tools/runs/native-chat-tool-fold.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { describe, it, expect } from 'vitest' -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' - -import { foldToolMessages } from '../../../../../../shared/native-chat/tools/native-chat-tool-fold' - -function msg( - overrides: Partial & Pick -): NativeChatMessage { - return { - role: 'assistant', - blocks: [], - timestamp: 0, - source: 'transcript', - ...overrides - } -} - -describe('foldToolMessages', () => { - it('drops a result after a user turn abandons the pending call', () => { - const folded = foldToolMessages([ - msg({ id: 'c', role: 'assistant', blocks: [{ type: 'tool-call', name: 'Bash', input: {} }] }), - msg({ id: 'u', role: 'user', blocks: [{ type: 'text', text: 'stop' }] }), - msg({ id: 't', role: 'tool', blocks: [{ type: 'tool-result', output: 'x' }] }) - ]) - expect(folded.map((m) => m.id)).toEqual(['c', 'u']) - }) - - it('attributes a Claude tool result carried with a harness sidecar', () => { - const folded = foldToolMessages([ - msg({ - id: 'a', - role: 'assistant', - blocks: [{ type: 'tool-call', name: 'Read', input: {} }] - }), - msg({ - id: 'u', - role: 'user', - blocks: [ - { type: 'tool-result', output: 'important output' }, - { type: 'text', text: 'continue' } - ] - }) - ]) - - expect(folded).toEqual([ - expect.objectContaining({ - id: 'a', - blocks: [ - { type: 'tool-call', name: 'Read', input: {} }, - { type: 'tool-result', output: 'important output' } - ] - }), - expect.objectContaining({ - id: 'u', - blocks: [{ type: 'text', text: 'continue' }] - }) - ]) - }) - - it('does not traverse an interruption sidecar carrying a stale result', () => { - const folded = foldToolMessages([ - msg({ - id: 'a', - role: 'assistant', - blocks: [{ type: 'tool-call', name: 'Read', input: {} }] - }), - msg({ - id: 'i', - role: 'user', - blocks: [ - { type: 'tool-result', output: 'stale' }, - { type: 'text', text: '[Request interrupted by user]' } - ] - }) - ]) - - expect(folded).toEqual([ - expect.objectContaining({ - id: 'a', - blocks: [{ type: 'tool-call', name: 'Read', input: {} }] - }), - expect.objectContaining({ - id: 'i', - blocks: [{ type: 'text', text: '[Request interrupted by user]' }] - }) - ]) - }) -}) diff --git a/src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.test.tsx b/src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.test.tsx deleted file mode 100644 index b0f0c919da5..00000000000 --- a/src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.test.tsx +++ /dev/null @@ -1,93 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, render, screen } from '@testing-library/react' -import userEvent from '@testing-library/user-event' -import type { ComponentProps } from 'react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { NeedsSetupProjectHostOption } from '@/lib/workspace/creation/project-host-setup-options' - -const storeMocks = vi.hoisted(() => ({ - setupProjectExistingFolder: vi.fn(), - setupProjectClone: vi.fn() -})) - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: unknown) => unknown) => selector(storeMocks) -})) - -vi.mock('@/components/sidebar/host-path-browser/RemoteFileBrowser', () => ({ - RemoteFileBrowser: ({ - targetId, - onSelect, - onCancel - }: { - targetId?: string - onSelect: (path: string) => void - onCancel: () => void - }) => ( -
- - -
- ) -})) - -import { SetProjectLocationDialog } from './SetProjectLocationDialog' - -const option: NeedsSetupProjectHostOption = { - kind: 'needs-setup', - id: 'needs-setup:ssh:openclaw', - projectId: 'project-orca', - hostId: 'ssh:openclaw', - label: 'openclaw', - detail: 'Project location not set', - isAvailable: true, - attention: false, - canSetLocation: true -} - -function renderDialog( - overrides: Partial> = {} -): ReturnType { - const user = userEvent.setup() - render( - - ) - return user -} - -afterEach(() => { - cleanup() -}) - -describe('SetProjectLocationDialog', () => { - it('backs out of the host browser on Escape instead of discarding the form', async () => { - const onClose = vi.fn() - const user = renderDialog({ onClose }) - - await user.click(screen.getByRole('button', { name: /Browse folder/ })) - await user.click(screen.getByRole('button', { name: 'Browse host filesystem' })) - expect(screen.getByTestId('remote-file-browser')).toBeTruthy() - - await user.keyboard('{Escape}') - - expect(onClose).not.toHaveBeenCalled() - expect(screen.queryByTestId('remote-file-browser')).toBeNull() - expect(screen.getByRole('button', { name: 'Set location' })).toBeTruthy() - - await user.keyboard('{Escape}') - expect(onClose).toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/review/use-hosted-review-eligibility.test.tsx b/src/renderer/src/components/right-sidebar/source-control/review/use-hosted-review-eligibility.test.tsx deleted file mode 100644 index 29b643d8fdf..00000000000 --- a/src/renderer/src/components/right-sidebar/source-control/review/use-hosted-review-eligibility.test.tsx +++ /dev/null @@ -1,77 +0,0 @@ -// @vitest-environment happy-dom -import { memo } from 'react' -import { act, cleanup, render } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import type { HostedReviewProvider } from '../../../../../../shared/source-control/hosted-review/hosted-review-contracts' -import { useSourceControlHostedReviewEligibility } from './use-hosted-review-eligibility' - -afterEach(cleanup) - -const setRequestState = (): void => {} -const hint = { - current: { repoId: null, worktreeId: null, branch: '', provider: 'github' as const } -} - -const Host = memo(function Host({ - provider, - getEligibility, - setState -}: { - provider: HostedReviewProvider - getEligibility: () => Promise - setState: (state: unknown) => void -}): null { - useSourceControlHostedReviewEligibility({ - activeRepoConnectionId: null, - activeRepoExecutionHostId: null, - activeRepoId: 'repo', - activeRepoPath: '/repo', - activeWorktreeId: 'wt', - branchName: 'feature', - effectiveBaseRef: 'origin/main', - fallbackGitHubPRNumber: null, - getHostedReviewCreationEligibility: getEligibility, - hasUncommittedEntries: true, - isBranchVisible: true, - isCreatePrIntentInFlight: false, - isCreatingPr: false, - isFolder: false, - linkedAzureDevOpsPR: null, - linkedBitbucketPR: null, - linkedGitHubPR: null, - linkedGitLabMR: null, - linkedGiteaPR: null, - prGenerating: false, - provisionalHostedReviewProvider: provider, - remoteStatus: undefined, - hostedReviewCreationProviderHintRef: hint, - setHostedReviewCreationRequestState: setRequestState, - setHostedReviewCreationState: setState, - worktreePath: '/repo' - }) - return null -}) - -it('builds the failure fallback with the provider inferred after the probe started', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - let fail: (error: Error) => void = () => {} - const probe = new Promise((_resolve, reject) => { - fail = reject - }) - const getEligibility = vi.fn(() => probe) - const setState = vi.fn() - const { rerender } = render( - - ) - rerender() - - await act(async () => { - fail(new Error('offline')) - await probe.catch(() => {}) - }) - - expect(getEligibility).toHaveBeenCalledTimes(1) - expect(setState).toHaveBeenLastCalledWith( - expect.objectContaining({ data: expect.objectContaining({ provider: 'gitlab' }) }) - ) -}) diff --git a/src/renderer/src/components/sidebar/hidden-projects/set-project-hidden.test.ts b/src/renderer/src/components/sidebar/hidden-projects/set-project-hidden.test.ts deleted file mode 100644 index 580e631c247..00000000000 --- a/src/renderer/src/components/sidebar/hidden-projects/set-project-hidden.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import { TEST_REPO } from '@/store/repos/repo.test-fixture' -import { getRepoExecutionHostId } from '../../../../../shared/execution-host' -import type { Repo } from '../../../../../shared/repo-types' -import { setProjectHidden } from './set-project-hidden' - -const { toastSuccess, toastInfo, toastError } = vi.hoisted(() => ({ - toastSuccess: vi.fn(), - toastInfo: vi.fn(), - toastError: vi.fn() -})) -vi.mock('sonner', () => ({ - toast: { success: toastSuccess, info: toastInfo, error: toastError } -})) - -const initialState = useAppStore.getState() -const local: Repo = { ...TEST_REPO, id: 'r' } -let clock = 1000 - -// Writes land in the store, as a host that echoes hiddenAt would. -const updateRepo = vi.fn( - async (id: string, updates: { hiddenAt?: number | null }, options?: { hostId?: string }) => { - useAppStore.setState((state) => ({ - repos: state.repos.map((repo) => { - if (repo.id !== id || getRepoExecutionHostId(repo) !== options?.hostId) { - return repo - } - const { hiddenAt: _previous, ...rest } = repo - return typeof updates.hiddenAt === 'number' ? { ...rest, hiddenAt: updates.hiddenAt } : rest - }) - })) - return true - } -) - -beforeEach(() => { - vi.spyOn(Date, 'now').mockImplementation(() => (clock += 1)) -}) - -afterEach(() => { - useAppStore.setState(initialState, true) - vi.clearAllMocks() - vi.restoreAllMocks() -}) - -function undo(toastIndex = 0): void { - const options: unknown = toastSuccess.mock.calls[toastIndex]?.[1] - if ( - typeof options !== 'object' || - options === null || - !('action' in options) || - typeof options.action !== 'object' || - options.action === null || - !('onClick' in options.action) || - typeof options.action.onClick !== 'function' - ) { - throw new Error('expected an Undo action on the hide toast') - } - options.action.onClick() -} - -describe('setProjectHidden', () => { - it('leaves a newer hide in place when an older toast’s Undo is clicked', async () => { - useAppStore.setState({ repos: [local], updateRepo }) - await setProjectHidden([local], true, 'r') - await setProjectHidden([local], false, 'r') - await setProjectHidden([local], true, 'r') - const newerHiddenAt = useAppStore.getState().repos[0]?.hiddenAt - updateRepo.mockClear() - - undo(0) - await Promise.resolve() - - expect(updateRepo).not.toHaveBeenCalled() - expect(useAppStore.getState().repos[0]?.hiddenAt).toBe(newerHiddenAt) - }) -}) diff --git a/src/renderer/src/components/sidebar/workspace-actions/deletion/folder-workspace-delete.test.ts b/src/renderer/src/components/sidebar/workspace-actions/deletion/folder-workspace-delete.test.ts deleted file mode 100644 index a2d5de66b39..00000000000 --- a/src/renderer/src/components/sidebar/workspace-actions/deletion/folder-workspace-delete.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -// @vitest-environment happy-dom -import { expect, it, vi } from 'vitest' -import { createUIStore } from '@/store/slices/ui/ui-slice-test-harness' -import { makeFolderWorkspace } from '@/store/folder-workspaces/folder-workspace.test-fixture' -import { deleteFolderWorkspaceUnlessUnsaved } from './folder-workspace-delete' -import { MIXED_GROUP } from '../../../../../../shared/folder-workspaces/folder-workspace-host-routing.test-fixture' -import type { AppState } from '@/store/types' - -function fixture() { - const store = createUIStore() - const folder = makeFolderWorkspace({ projectGroupId: MIXED_GROUP.id, executionHostId: 'local' }) - store.setState({ - folderWorkspaces: [folder], - projectGroups: [MIXED_GROUP], - repos: [], - openFiles: [], - editorDrafts: {}, - editorBufferIdOf: {}, - editorBufferViews: {}, - activeWorktreeId: null - }) - return { store, folder } -} - -it('coalesces pending folder removals and releases them after every completion', async () => { - const { store, folder } = fixture() - const remove = vi.fn() - store.setState({ deleteFolderWorkspace: remove }) - for (let cycle = 0; cycle < 20; cycle++) { - const deferred = Promise.withResolvers() - remove.mockReturnValueOnce(deferred.promise) - const first = deleteFolderWorkspaceUnlessUnsaved(store.getState, folder.id, 'local') - for (let press = 0; press < 4; press++) { - expect(deleteFolderWorkspaceUnlessUnsaved(store.getState, folder.id, 'local')).toBe(first) - } - expect(remove).toHaveBeenCalledTimes(cycle + 1) - deferred.resolve(true) - await expect(first).resolves.toBe(true) - } -}) - -it('keeps host twins independent and releases a rejected removal for retry', async () => { - const { store, folder } = fixture() - store.setState({ folderWorkspaces: [folder, { ...folder, executionHostId: 'runtime:other' }] }) - const local = Promise.withResolvers() - const remote = Promise.withResolvers() - const remove = vi - .fn() - .mockReturnValueOnce(local.promise) - .mockReturnValueOnce(remote.promise) - .mockResolvedValue(false) - store.setState({ deleteFolderWorkspace: remove }) - const localDeletion = deleteFolderWorkspaceUnlessUnsaved(store.getState, folder.id, 'local') - const remoteDeletion = deleteFolderWorkspaceUnlessUnsaved( - store.getState, - folder.id, - 'runtime:other' - ) - expect(remove).toHaveBeenCalledTimes(2) - const rejection = expect(localDeletion).rejects.toThrow('offline') - local.reject(new Error('offline')) - await rejection - await expect( - deleteFolderWorkspaceUnlessUnsaved(store.getState, folder.id, 'local') - ).resolves.toBe(false) - expect(remove).toHaveBeenCalledTimes(3) - remote.resolve(true) - await expect(remoteDeletion).resolves.toBe(true) -}) diff --git a/src/renderer/src/components/ssh-host-form/ssh-target-draft.test.ts b/src/renderer/src/components/ssh-host-form/ssh-target-draft.test.ts deleted file mode 100644 index 87508d78bf9..00000000000 --- a/src/renderer/src/components/ssh-host-form/ssh-target-draft.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - EMPTY_FORM, - applyParsedSshHostInput, - getEditingTargetForSshTarget, - getSshTargetDraftConnectionFields, - parseSshHostInput -} from './ssh-target-draft' - -describe('parseSshHostInput', () => { - it('normalizes bracketed IPv6 hosts from ssh URLs', () => { - expect(parseSshHostInput('ssh://deploy@[::1]:2202/srv/app')).toEqual({ - host: '::1', - username: 'deploy', - port: 2202, - configHost: '::1' - }) - }) - - it('does not throw on malformed username escapes in invalid ssh URL ports', () => { - expect(parseSshHostInput('ssh://bad%ZZ@example.com:99999/srv/app')).toEqual({ - host: 'example.com', - username: 'bad%ZZ', - port: undefined, - invalidPort: true, - configHost: 'example.com' - }) - }) -}) - -describe('applyParsedSshHostInput', () => { - it('does not overwrite explicit username or non-default port', () => { - expect( - applyParsedSshHostInput({ - ...EMPTY_FORM, - host: 'deploy@example.com:2202', - username: 'root', - port: '2022' - }) - ).toMatchObject({ - host: 'example.com', - username: 'root', - port: '2022' - }) - }) -}) - -describe('getSshTargetDraftConnectionFields', () => { - it('surfaces invalid pasted ports to the form validator', () => { - const fields = getSshTargetDraftConnectionFields({ - ...EMPTY_FORM, - host: 'deploy@example.com:99999' - }) - - expect(fields).toMatchObject({ - host: 'example.com', - configHost: 'example.com', - username: 'deploy' - }) - expect(Number.isNaN(fields.port)).toBe(true) - }) -}) - -describe('getEditingTargetForSshTarget', () => { - it('recomputes implicit configHost when a manual target host is edited', () => { - const draft = getEditingTargetForSshTarget({ - id: 'ssh-1', - label: 'Server', - configHost: 'old.example.com', - host: 'old.example.com', - port: 22, - username: '' - }) - - expect( - getSshTargetDraftConnectionFields({ - ...draft, - host: 'new.example.com' - }) - ).toEqual({ - host: 'new.example.com', - configHost: 'new.example.com', - username: '', - port: 22 - }) - }) - - it('preserves explicit SSH config aliases when editing imported targets', () => { - const draft = getEditingTargetForSshTarget({ - id: 'ssh-1', - label: 'Production', - configHost: 'prod', - host: 'prod.internal', - port: 22, - username: 'deploy' - }) - - expect(draft.configHost).toBe('prod') - expect(getSshTargetDraftConnectionFields(draft)).toEqual({ - host: 'prod.internal', - configHost: 'prod', - username: 'deploy', - port: 22 - }) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/clipboard/create-terminal-pane-menu-copy-actions.test.ts b/src/renderer/src/components/terminal-pane/clipboard/create-terminal-pane-menu-copy-actions.test.ts deleted file mode 100644 index 4cf3cd7d60a..00000000000 --- a/src/renderer/src/components/terminal-pane/clipboard/create-terminal-pane-menu-copy-actions.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -// @vitest-environment happy-dom -import { expect, it, vi } from 'vitest' -import type { ManagedPane } from '@/lib/pane-manager/pane-manager-types' -import { toWebTerminalSurfaceTabId } from '../../../../../shared/workspace-layout/terminal-surface-id' - -const rpc = vi.hoisted(() => ({ - call: vi.fn<(target: unknown, method: string, params: unknown) => Promise>() -})) -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: rpc.call })) -vi.mock('@/store/slices/worktrees/listing/worktree-owner-target', () => ({ - tryRuntimeTargetForWorktreeOwner: () => ({ kind: 'environment', environmentId: 'ssh-host' }) -})) -vi.mock('@/store/index', () => ({ useAppStore: { getState: () => ({}) } })) - -import { createTerminalPaneMenuCopyActions } from './create-terminal-pane-menu-copy-actions' - -const LEAF = '0517a0f3-3b48-40c8-b8f4-2c2664bf206d' - -it("asks a remote pane's host by the host's own pane key", async () => { - rpc.call.mockResolvedValue({ orcaSessionId: 'orca_session_id:claude_0123456789abcdef' }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: resolve reads only the pane's leaf id. - const pane = { leafId: LEAF } as ManagedPane - const { agentIdCopy } = createTerminalPaneMenuCopyActions({ - paneTransportsRef: { current: new Map() }, - tabId: toWebTerminalSurfaceTabId('host-tab'), - worktreeId: 'wt-1', - resolveMenuPane: () => pane - }) - expect(await agentIdCopy.resolve()).toBe('orca_session_id:claude_0123456789abcdef') - expect(rpc.call).toHaveBeenCalledWith( - { kind: 'environment', environmentId: 'ssh-host' }, - 'terminal.agentId', - { paneKey: `host-tab:${LEAF}`, worktreeId: 'wt-1' } - ) -}) - -it('returns focus to the pane only if nothing else took it during the wait', async () => { - let answer!: (value: unknown) => void - rpc.call.mockReturnValue(new Promise((resolve) => (answer = resolve))) - const container = document.createElement('div') - const editor = document.createElement('input') - document.body.append(container, editor) - const focus = vi.fn() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the copy reads only the pane's leaf, container and focus. - const pane = { leafId: LEAF, container, terminal: { focus } } as unknown as ManagedPane - const { agentIdCopy } = createTerminalPaneMenuCopyActions({ - paneTransportsRef: { current: new Map() }, - tabId: 'tab-1', - worktreeId: 'wt-1', - resolveMenuPane: () => pane - }) - const copied = agentIdCopy.resolve() - // The user moves to an editor while the host answers. - editor.focus() - answer({ orcaSessionId: null }) - await copied - agentIdCopy.focusPane() - expect(focus).not.toHaveBeenCalled() - editor.blur() - agentIdCopy.focusPane() - expect(focus).toHaveBeenCalledOnce() -}) diff --git a/src/renderer/src/components/workspace-cleanup/browse/use-workspace-cleanup-browse-state.test.tsx b/src/renderer/src/components/workspace-cleanup/browse/use-workspace-cleanup-browse-state.test.tsx deleted file mode 100644 index f60b6674fac..00000000000 --- a/src/renderer/src/components/workspace-cleanup/browse/use-workspace-cleanup-browse-state.test.tsx +++ /dev/null @@ -1,81 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { create } from 'zustand' -import type { AppState } from '@/store/types' -import { - createWorkspaceCleanupBrowseSlice, - resetWorkspaceCleanupBrowsePersistTimer -} from '@/store/slices/workspace-cleanup/workspace-cleanup-browse' -import { createDefaultWorkspaceCleanupBrowseState } from '../../../../../shared/workspace-cleanup/workspace-cleanup-browse-state' - -import { - useWorkspaceCleanupBrowseState, - type WorkspaceCleanupBrowseController -} from './use-workspace-cleanup-browse-state' - -const store = create()( - (...a) => - ({ - workspaceCleanupDismissals: {}, - ...createWorkspaceCleanupBrowseSlice(...a) - }) as unknown as AppState -) - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: AppState) => T): T => store(selector) -})) - -let root: Root | null = null -let container: HTMLDivElement | null = null - -function mountController(): { current: WorkspaceCleanupBrowseController | null } { - const ref: { current: WorkspaceCleanupBrowseController | null } = { current: null } - function Probe(): null { - ref.current = useWorkspaceCleanupBrowseState() - return null - } - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - act(() => root!.render()) - return ref -} - -describe('useWorkspaceCleanupBrowseState', () => { - beforeEach(() => { - vi.useFakeTimers() - ;(globalThis as { window: unknown }).window = { - ...globalThis.window, - api: { ui: { set: vi.fn().mockResolvedValue(undefined) } } - } - store.setState({ - workspaceCleanupBrowse: createDefaultWorkspaceCleanupBrowseState() - } as Partial) - }) - - afterEach(() => { - if (root) { - act(() => root!.unmount()) - } - root = null - container = null - document.body.replaceChildren() - resetWorkspaceCleanupBrowsePersistTimer() - vi.useRealTimers() - }) - - it('keeps both patches when the same group is written twice in one tick', () => { - const controller = mountController() - - act(() => { - controller.current!.patchFilters('git', { minAhead: 2 }) - controller.current!.patchFilters('git', { branchQuery: 'release' }) - }) - - const git = store.getState().workspaceCleanupBrowse.filters.git - expect(git.minAhead).toBe(2) - expect(git.branchQuery).toBe('release') - }) -}) diff --git a/src/renderer/src/components/workspace-cleanup/candidate-evidence/workspace-cleanup-host-index.test.ts b/src/renderer/src/components/workspace-cleanup/candidate-evidence/workspace-cleanup-host-index.test.ts deleted file mode 100644 index c10fe076afc..00000000000 --- a/src/renderer/src/components/workspace-cleanup/candidate-evidence/workspace-cleanup-host-index.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - buildWorkspaceCleanupSizeIndex, - buildWorkspaceCleanupWorktreeIndex -} from './workspace-cleanup-host-indexes' -import { getWorkspaceCleanupHostIdentity } from '../../../../../shared/workspace-cleanup/workspace-cleanup-host-identity' -import { makeFacetCandidate } from '../query/workspace-cleanup-facet.test.fixture' - -describe('facet building', () => { - it('keeps same-id worktrees and sizes isolated by host', () => { - const candidates = [ - makeFacetCandidate({ executionHostId: 'local' }), - makeFacetCandidate({ - executionHostId: 'ssh:builder', - connectionId: 'builder' - }) - ] - const sizes = buildWorkspaceCleanupSizeIndex( - [ - { - worktreeId: candidates[0]!.worktreeId, - executionHostId: 'local', - status: 'ok', - sizeBytes: 10 - }, - { - worktreeId: candidates[1]!.worktreeId, - executionHostId: 'ssh:builder', - status: 'ok', - sizeBytes: 20 - } - ], - candidates - ) - - expect(sizes.get(getWorkspaceCleanupHostIdentity('local', candidates[0]!.worktreeId))).toBe(10) - expect( - sizes.get(getWorkspaceCleanupHostIdentity('ssh:builder', candidates[1]!.worktreeId)) - ).toBe(20) - expect(sizes.has(candidates[0]!.worktreeId)).toBe(false) - }) - - it('does not apply a legacy size to duplicate candidate ids', () => { - const candidates = [ - makeFacetCandidate({ executionHostId: 'local' }), - makeFacetCandidate({ - executionHostId: 'ssh:builder', - connectionId: 'builder' - }) - ] - const sizes = buildWorkspaceCleanupSizeIndex( - [{ worktreeId: candidates[0]!.worktreeId, status: 'ok', sizeBytes: 10 }], - candidates - ) - - expect(sizes.size).toBe(0) - }) - - it('does not apply duplicate legacy size rows to one current candidate', () => { - const candidate = makeFacetCandidate({ executionHostId: 'local' }) - const sizes = buildWorkspaceCleanupSizeIndex( - [ - { worktreeId: candidate.worktreeId, status: 'ok', sizeBytes: 10 }, - { worktreeId: candidate.worktreeId, status: 'ok', sizeBytes: 20 } - ], - [candidate] - ) - - expect(sizes.size).toBe(0) - }) - - it('does not assign legacy worktree metadata with multi-host repo ownership', () => { - const index = buildWorkspaceCleanupWorktreeIndex( - { 'repo-1': [{ id: 'w1', repoId: 'repo-1' }] }, - [ - { id: 'repo-1', executionHostId: 'local' }, - { id: 'repo-1', executionHostId: 'ssh:builder' } - ] - ) - - expect(index.size).toBe(0) - }) -}) diff --git a/src/renderer/src/components/worktree-jump/tabs/use-worktree-jump-palette-browser-ownership.test.ts b/src/renderer/src/components/worktree-jump/tabs/use-worktree-jump-palette-browser-ownership.test.ts deleted file mode 100644 index e0f94c91403..00000000000 --- a/src/renderer/src/components/worktree-jump/tabs/use-worktree-jump-palette-browser-ownership.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, renderHook } from '@testing-library/react' -import { afterEach, expect, it } from 'vitest' -import { useAppStore } from '@/store/index' -import type { BrowserPage, BrowserWorkspace } from '../../../../../shared/browser-workspace-types' -import type { Tab } from '../../../../../shared/tab-types' -import { makeUnifiedTab, makeWorktree } from '../worktree-jump-palette-test-fixtures' -import { useWorktreeJumpPaletteOpenTabs } from './use-worktree-jump-palette-open-tabs' - -afterEach(cleanup) - -it('keeps same-id browser results on their owner with recency, and follows ownership changes', () => { - const worktrees = [ - makeWorktree('same-id', 'Local workspace', { hostId: 'local' }), - makeWorktree('same-id', 'Remote workspace', { hostId: 'runtime:paired' }) - ] - const page: BrowserPage = { - id: 'page', - workspaceId: 'browser', - worktreeId: 'same-id', - url: 'https://example.test/docs', - title: 'Browser proof', - loading: false, - faviconUrl: null, - canGoBack: false, - canGoForward: false, - loadError: null, - createdAt: 1 - } - const workspace: BrowserWorkspace = { - ...page, - id: 'browser', - activePageId: page.id, - pageIds: [page.id] - } - const tab: Tab = { - ...makeUnifiedTab('tab', 'same-id', 'browser', 'Browser proof'), - contentType: 'browser', - executionHostId: 'runtime:paired', - lastFocusedAt: 5_000 - } - type PaletteInput = Parameters[0] - const input: Partial = { - ...useAppStore.getInitialState(), - // The store holds {key, result}; the hook takes the unwrapped result. - workspacePortScan: null, - paletteStatusInputsActive: true, - workspaces: worktrees, - browserSortedWorktrees: worktrees, - repoMap: new Map(), - repoByHostIdentity: new Map(), - worktreeOrder: new Map(), - worktreeMatches: [], - hasQuery: true, - deferredQuery: 'Browser proof', - browserTabsByWorktree: { 'same-id': [workspace] }, - browserPagesByWorkspace: { browser: [page] }, - unifiedTabsByWorktree: { 'same-id': [tab] } - } - const { result, rerender } = renderHook( - (props: Partial) => useWorktreeJumpPaletteOpenTabs(props as PaletteInput), - { initialProps: input } - ) - // lastActiveAt rides the same map: without it every browser row sorts as never-focused. - const owners = () => - result.current.browserItems.map(({ result: entry }) => [ - entry.pageId, - entry.executionHostId, - entry.lastActiveAt - ]) - - expect(owners()).toEqual([['page', 'runtime:paired', 5_000]]) - - rerender({ - ...input, - unifiedTabsByWorktree: { - 'same-id': [{ ...tab, executionHostId: 'local' }] - } - }) - expect(owners()).toEqual([['page', 'local', 5_000]]) -}) diff --git a/src/renderer/src/lib/keyboard/app-keyboard-router.test.ts b/src/renderer/src/lib/keyboard/app-keyboard-router.test.ts deleted file mode 100644 index 73396fd3ff6..00000000000 --- a/src/renderer/src/lib/keyboard/app-keyboard-router.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, describe, expect, it } from 'vitest' -import { - addAppKeyListener, - installAppKeyboardRouter, - removeAppKeyListener -} from './app-keyboard-router' - -installAppKeyboardRouter(window) - -const cleanups: (() => void)[] = [] -afterEach(() => { - cleanups.splice(0).forEach((cleanup) => cleanup()) -}) - -function onWindow(listener: (event: KeyboardEvent) => void): void { - window.addEventListener('keydown', listener, { capture: true }) - cleanups.push(() => window.removeEventListener('keydown', listener, { capture: true })) -} - -function onApp(listener: (event: KeyboardEvent) => void): void { - addAppKeyListener('keydown', listener) - cleanups.push(() => removeAppKeyListener('keydown', listener)) -} - -function press(): string[] { - const seen: string[] = [] - const record = (name: string) => () => seen.push(name) - const target = document.createElement('textarea') - document.body.append(target) - document.addEventListener('keydown', record('document'), { capture: true, once: true }) - target.addEventListener('keydown', record('terminal input'), { once: true }) - cleanups.push(() => target.remove()) - target.dispatchEvent( - new KeyboardEvent('keydown', { key: 'ArrowRight', metaKey: true, bubbles: true }) - ) - return seen -} - -describe('app keyboard router', () => { - it('leaves the terminal fallback when no app owner claims the key', () => { - const seen: string[] = [] - onWindow(() => seen.push('pane translation')) - onApp(() => seen.push('owner declined')) - const tail = press() - expect([...seen, ...tail]).toEqual([ - 'owner declined', - 'pane translation', - 'document', - 'terminal input' - ]) - }) - - it('runs a first owner ahead of owners registered before it', () => { - const seen: string[] = [] - onApp((event) => { - seen.push('overlay') - event.stopImmediatePropagation() - }) - const dictation = (event: KeyboardEvent): void => { - seen.push('dictation') - event.stopImmediatePropagation() - } - addAppKeyListener('keydown', dictation, { first: true }) - cleanups.push(() => removeAppKeyListener('keydown', dictation)) - const tail = press() - expect([...seen, ...tail]).toEqual(['dictation']) - }) - - it('keeps native stop semantics between app owners', () => { - const seen: string[] = [] - onApp((event) => { - seen.push('stops propagation') - event.stopPropagation() - }) - onApp(() => seen.push('later owner')) - onWindow(() => seen.push('pane')) - const tail = press() - expect([...seen, ...tail]).toEqual(['stops propagation', 'later owner', 'pane']) - }) -}) diff --git a/src/renderer/src/store/plugins/catalog/plugin-panels.test.ts b/src/renderer/src/store/plugins/catalog/plugin-panels.test.ts deleted file mode 100644 index 3fc9444743c..00000000000 --- a/src/renderer/src/store/plugins/catalog/plugin-panels.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { PluginHostListEntry } from '../../../../../shared/plugins/plugin-list-entry' -import { usePluginPanelsStore } from './plugin-contribution-catalog' - -function plugin(pluginKey: string): PluginHostListEntry { - return { - pluginKey, - consentFingerprint: 'sha256-test', - name: pluginKey, - version: '1.0.0', - publisher: 'samples', - status: 'idle', - needsReconsent: false, - isDev: false, - official: false, - bundled: false, - capabilities: [], - panels: [], - commands: [], - hasWorker: false, - restarts: 0 - } -} - -afterEach(() => { - usePluginPanelsStore.getState().setPlugins([]) - usePluginPanelsStore.setState({ plugins: [], panelErrors: {}, fetchStatus: 'idle' }) - vi.useRealTimers() - vi.unstubAllGlobals() -}) - -describe('plugin panel list loading', () => { - it('does not let an older request overwrite a newer plugin list', async () => { - let resolveFirst!: (plugins: PluginHostListEntry[]) => void - let resolveSecond!: (plugins: PluginHostListEntry[]) => void - const list = vi - .fn() - .mockImplementationOnce(() => new Promise((resolve) => (resolveFirst = resolve))) - .mockImplementationOnce(() => new Promise((resolve) => (resolveSecond = resolve))) - vi.stubGlobal('window', { api: { plugins: { list } } }) - - const first = usePluginPanelsStore.getState().fetchPlugins() - const second = usePluginPanelsStore.getState().fetchPlugins() - resolveSecond([plugin('samples.current')]) - await second - resolveFirst([plugin('samples.stale')]) - await first - - expect(usePluginPanelsStore.getState().plugins.map((entry) => entry.pluginKey)).toEqual([ - 'samples.current' - ]) - }) - - it('recovers automatically from a transient list failure with bounded backoff', async () => { - vi.useFakeTimers() - const list = vi - .fn() - .mockRejectedValueOnce(new Error('transport starting')) - .mockResolvedValueOnce([plugin('samples.recovered')]) - vi.stubGlobal('window', { api: { plugins: { list } } }) - - await usePluginPanelsStore.getState().fetchPlugins() - expect(usePluginPanelsStore.getState().fetchStatus).toBe('error') - - await vi.advanceTimersByTimeAsync(250) - - expect(list).toHaveBeenCalledTimes(2) - expect(usePluginPanelsStore.getState()).toMatchObject({ - fetchStatus: 'ready', - plugins: [expect.objectContaining({ pluginKey: 'samples.recovered' })] - }) - }) -}) diff --git a/src/renderer/src/store/slices/agent-status/agent-hibernation-live-anchor-e2e.test.ts b/src/renderer/src/store/slices/agent-status/agent-hibernation-live-anchor-e2e.test.ts deleted file mode 100644 index 238b54737d6..00000000000 --- a/src/renderer/src/store/slices/agent-status/agent-hibernation-live-anchor-e2e.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import type { AppState } from '../../types' -import { createTestStore } from '../../testing/app-store-test-fixture' -import { makeTab } from '../../terminals/testing/terminal-tab.test-fixture' -import { DEFAULT_AGENT_HIBERNATION_IDLE_MS } from '../../../lib/agent-session/hibernation/agent-hibernation-planner' -import { resetHibernationPaneAgeForTests } from '../../../lib/agent-session/hibernation/agent-hibernation-pane-age' - -const LEAF = '11111111-1111-4111-8111-111111111111' -const PANE = `tab-1:${LEAF}` -const DONE_AT = 1_000_000 -const NOW = DONE_AT + DEFAULT_AGENT_HIBERNATION_IDLE_MS + 60_000 -const ROUTING = { tabId: 'tab-1', worktreeId: 'wt-bg', connectionId: null } -const PROVIDER_SESSION = { key: 'session_id' as const, id: 'claude-session-1' } - -function seedWorkspace(store: ReturnType): void { - store.setState({ - activeWorktreeId: 'wt-active', - tabsByWorktree: { 'wt-bg': [makeTab({ id: 'tab-1', worktreeId: 'wt-bg' })] }, - terminalLayoutsByTabId: { - 'tab-1': { - root: { type: 'leaf', leafId: LEAF }, - activeLeafId: LEAF, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF]: 'pty-1' } - } - }, - ptyIdsByTabId: { 'tab-1': ['pty-1'] }, - settings: { - experimentalAgentHibernation: true, - agentHibernationIdleMs: DEFAULT_AGENT_HIBERNATION_IDLE_MS - } - } as unknown as Partial) -} - -describe('a finished Claude turn retains its live status timing', () => { - beforeEach(() => { - resetHibernationPaneAgeForTests() - }) - - it('is not restarted by a done→done repaint carrying a fresh updatedAt', () => { - const store = createTestStore() - seedWorkspace(store) - for (const timing of [ - { updatedAt: DONE_AT - 5_000, stateStartedAt: DONE_AT - 5_000 }, - { updatedAt: DONE_AT, stateStartedAt: DONE_AT } - ]) { - store.getState().setAgentStatus( - PANE, - { - state: timing.updatedAt === DONE_AT ? 'done' : 'working', - prompt: 'ship it', - agentType: 'claude' - }, - 'Claude', - timing, - ROUTING, - { providerSession: PROVIDER_SESSION } - ) - } - // Metadata-less reconnect/OSC repaint refreshes updatedAt but preserves original stateStartedAt. - store - .getState() - .setAgentStatus( - PANE, - { state: 'done', prompt: 'ship it', agentType: 'claude' }, - 'Claude', - { updatedAt: NOW - 1_000, stateStartedAt: DONE_AT }, - ROUTING - ) - const state = store.getState() - expect(state.agentStatusByPaneKey[PANE]?.updatedAt).toBe(NOW - 1_000) - expect(state.agentStatusByPaneKey[PANE]?.stateStartedAt).toBe(DONE_AT) - }) -}) diff --git a/src/renderer/src/store/slices/worktrees/metadata/worktrees-multiple-attachments.test.ts b/src/renderer/src/store/slices/worktrees/metadata/worktrees-multiple-attachments.test.ts deleted file mode 100644 index e4525c0fb09..00000000000 --- a/src/renderer/src/store/slices/worktrees/metadata/worktrees-multiple-attachments.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { getWorkspaceAttachments } from '../../../../../../shared/workspace-attachments/workspace-attachments' -import { makeWorktree } from '../worktree.test-fixture' -import { - createTestStore, - mockApi, - resetRemoteRuntimeMocks, - resetWorktreeSliceModuleMemory -} from '../worktrees-slice-test-harness' - -beforeEach(() => { - vi.clearAllMocks() - resetRemoteRuntimeMocks() - resetWorktreeSliceModuleMemory() -}) - -describe('workspace attachment collections', () => { - it('retains earlier reviews locally while persisting a compatible scalar mutation', async () => { - const store = createTestStore() - const wt = makeWorktree({ id: 'repo1::/work', repoId: 'repo1', linkedPR: 42 }) - store.setState({ worktreesByRepo: { repo1: [wt] } }) - await store.getState().updateWorktreeMeta(wt.id, { linkedGitLabMR: 7 }) - const saved = store.getState().worktreesByRepo.repo1[0] - expect(saved.linkedPR).toBeNull() - expect(saved.linkedGitLabMR).toBe(7) - expect(getWorkspaceAttachments(saved)).toEqual([ - { provider: 'github', type: 'pr', number: 42 }, - { provider: 'gitlab', type: 'mr', number: 7 } - ]) - expect(mockApi.worktrees.updateMeta).toHaveBeenCalledWith( - expect.objectContaining({ - updates: expect.objectContaining({ linkedGitLabMR: 7 }) - }) - ) - const updates = mockApi.worktrees.updateMeta.mock.lastCall?.[0].updates - expect(updates).not.toHaveProperty('linkedItems') - expect(updates).not.toHaveProperty('linkedItemsBase') - expect(updates).not.toHaveProperty('linkedPR') - }) - - it('carries the editor snapshot unchanged through optimistic state and host persistence', async () => { - const store = createTestStore() - const base = [1, 2].map((number) => ({ provider: 'github', type: 'pr', number }) as const) - const peer = { provider: 'github', type: 'pr', number: 3 } as const - const wt = makeWorktree({ - id: 'repo1::/work', - repoId: 'repo1', - linkedPR: 2, - linkedItems: [...base, peer] - }) - store.setState({ worktreesByRepo: { repo1: [wt] } }) - await store - .getState() - .updateWorktreeMeta(wt.id, { linkedItemsBase: base, linkedItems: [base[1]] }) - expect(store.getState().worktreesByRepo.repo1[0].linkedItems).toEqual([base[1], peer]) - const write = mockApi.worktrees.updateMeta.mock.lastCall?.[0].updates - expect(write).toMatchObject({ linkedItemsBase: base, linkedItems: [base[1]] }) - }) -}) diff --git a/src/renderer/src/store/terminals/pty/terminal-exited-pane-liveness.test.ts b/src/renderer/src/store/terminals/pty/terminal-exited-pane-liveness.test.ts deleted file mode 100644 index 26f1485cc60..00000000000 --- a/src/renderer/src/store/terminals/pty/terminal-exited-pane-liveness.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { TerminalLayoutSnapshot } from '../../../../../shared/workspace-layout/terminal-tab-types' - -import { createTestStore } from '../../testing/app-store-test-fixture' -import { makeTab } from '../testing/terminal-tab.test-fixture' -import { makeWorktree } from '../../slices/worktrees/worktree.test-fixture' -import { createStoreSessionMockApi } from '../../testing/app-store-session-api.test-fixture' - -vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) - -createStoreSessionMockApi() - -// Exited panes retain one stale reattach binding; liveness stays window-owned while layout bindings move to main. - -const WORKTREE = 'repo1::/path/wt1' -const LEFT = '11111111-1111-4111-8111-111111111111' -const RIGHT = '22222222-2222-4222-8222-222222222222' - -function splitLayout(): TerminalLayoutSnapshot { - return { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEFT }, - second: { type: 'leaf', leafId: RIGHT } - }, - activeLeafId: LEFT, - expandedLeafId: null, - ptyIdsByLeafId: { [LEFT]: 'pty-left', [RIGHT]: 'pty-right' } - } -} - -function storeWithSplitTab() { - const store = createTestStore() - store.setState({ - repos: [{ id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 }], - worktreesByRepo: { - repo1: [makeWorktree({ id: WORKTREE, repoId: 'repo1', path: '/path/wt1', hostId: 'local' })] - }, - tabsByWorktree: { - [WORKTREE]: [makeTab({ id: 'tab-1', worktreeId: WORKTREE, ptyId: 'pty-right' })] - }, - ptyIdsByTabId: { 'tab-1': ['pty-left', 'pty-right'] }, - terminalLayoutsByTabId: { 'tab-1': splitLayout() } - }) - return store -} - -describe('exited pane in a split', () => { - it('drops only the exited PTY from liveness and keeps every layout binding', () => { - const store = storeWithSplitTab() - - // Ctrl-D in the left pane. - store.getState().clearTabPtyId('tab-1', 'pty-left') - - const state = store.getState() - expect(state.ptyIdsByTabId['tab-1']).toEqual(['pty-right']) - - expect(state.terminalLayoutsByTabId['tab-1']).toEqual(splitLayout()) - }) - - it('reads the tab as not running once both panes exit, with the bindings still saved', () => { - const store = storeWithSplitTab() - - store.getState().clearTabPtyId('tab-1', 'pty-left') - store.getState().clearTabPtyId('tab-1', 'pty-right') - - const state = store.getState() - - expect(state.tabsByWorktree[WORKTREE]?.[0]?.ptyId).toBeNull() - expect(state.terminalLayoutsByTabId['tab-1']?.ptyIdsByLeafId).toEqual({ - [LEFT]: 'pty-left', - [RIGHT]: 'pty-right' - }) - }) -}) diff --git a/src/renderer/src/store/terminals/pty/terminal-tab-recovery-remount.test.ts b/src/renderer/src/store/terminals/pty/terminal-tab-recovery-remount.test.ts deleted file mode 100644 index 078a6786041..00000000000 --- a/src/renderer/src/store/terminals/pty/terminal-tab-recovery-remount.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createTestStore, seedStore } from '../../testing/app-store-test-fixture' -import { makeWorktree } from '../../slices/worktrees/worktree.test-fixture' -import '../retirement/terminal-tab-retirement' -import { folderWorkspaceKey } from '../../../../../shared/workspace-scope' -import { createStoreSessionMockApi } from '../../testing/app-store-session-api.test-fixture' - -const WORKTREE_ID = 'repo1::/path/wt1' - -beforeEach(() => { - // Track the original global before the shared fixture installs the renderer API. - vi.stubGlobal('window', undefined) - createStoreSessionMockApi() -}) - -afterEach(() => { - vi.unstubAllGlobals() -}) - -describe.each([['a folder workspace', folderWorkspaceKey('fw-1')]])( - 'the recovery ledger on %s', - (_label, bucketId) => { - function seedBucket(store: ReturnType): string { - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', path: '/path/wt1' })] - } - }) - return store.getState().createTab(bucketId).id - } - - const AUTOMATIC = { reason: 'write-stalled', trigger: 'automatic', now: 0 } as const - - it('admits, observes and then refuses the same reason until a new trigger', () => { - const store = createTestStore() - const tabId = seedBucket(store) - const row = (): { recovery?: unknown } | undefined => - store.getState().tabsByWorktree[bucketId]?.find((tab) => tab.id === tabId) - - const first = store.getState().remountTerminalTabForRecovery(tabId, AUTOMATIC) - expect(first.remounted).toBe(true) - expect(row()?.recovery).toMatchObject({ outcome: 'pending', reason: 'write-stalled' }) - - // Unsettled blocks the next automatic ask, even past the cooldown. - expect( - store.getState().remountTerminalTabForRecovery(tabId, { ...AUTOMATIC, now: 16_000 }) - ).toEqual({ remounted: false, declinedBy: 'unsettled', retryInMs: 15_000 }) - - if (!first.remounted) { - throw new Error('unreachable: the first remount was admitted') - } - store.getState().settleTerminalTabRecovery(tabId, first.generation, 'failed') - expect(row()?.recovery).toMatchObject({ outcome: 'failed' }) - expect( - store.getState().remountTerminalTabForRecovery(tabId, { ...AUTOMATIC, now: 600_000 }) - ).toEqual({ remounted: false, declinedBy: 'settled-failure' }) - - // The user asking again is the new trigger the refusal waits for. - expect( - store - .getState() - .remountTerminalTabForRecovery(tabId, { ...AUTOMATIC, trigger: 'user', now: 600_000 }) - .remounted - ).toBe(true) - }) - } -) diff --git a/src/shared/native-chat/input/session-options/native-chat-session-option-snapshot.test.ts b/src/shared/native-chat/input/session-options/native-chat-session-option-snapshot.test.ts deleted file mode 100644 index 55c6aa0075e..00000000000 --- a/src/shared/native-chat/input/session-options/native-chat-session-option-snapshot.test.ts +++ /dev/null @@ -1,272 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - sessionOptionDispatchUnconfirmed, - type SessionOptionDescriptor -} from '../native-chat-session-options' -import { mergeDiscoveredAuthoritativeModels } from '../../../agent-session/options/agent-session-option-catalog' -import { - CLAUDE_SESSION_OPTION_CATALOG, - CODEX_SESSION_OPTION_CATALOG -} from '../../../agent-session/options/catalog-providers/agent-session-option-catalog-claude-codex' -import { CURSOR_SESSION_OPTION_CATALOG } from '../../../agent-session/options/catalog-providers/agent-session-option-catalog-gemini-cursor' -import { GROK_SESSION_OPTION_CATALOG } from '../../../agent-session/options/catalog-providers/agent-session-option-catalog-grok' -import { resolveAgentSessionOptionLaunch } from '../../../agent-session/options/launch/agent-session-option-launch' -import { - createNativeChatSessionOptionRecord, - type NativeChatSessionOptionRecord -} from './native-chat-session-option-state' -import { - buildNativeChatSessionOptionSnapshot, - withTrackedNativeChatModel -} from './native-chat-session-option-snapshot' - -function claudeRecord(): NativeChatSessionOptionRecord { - return createNativeChatSessionOptionRecord('claude') -} - -describe('buildNativeChatSessionOptionSnapshot', () => { - // Both lanes emit dispatched; only an explicit transport distinguishes their descriptors. - it.each(['catalog', 'agent-session'] as const)( - 'stamps every descriptor with the %s transport it was built for', - (liveTransport) => { - const record = claudeRecord() - record.model = { value: 'sonnet', source: 'dispatched' } - const snapshot = buildNativeChatSessionOptionSnapshot({ - catalog: CLAUDE_SESSION_OPTION_CATALOG, - models: CLAUDE_SESSION_OPTION_CATALOG.models, - record, - mode: 'live', - modelLabel: 'Model', - liveTransport - }) - expect(snapshot.length).toBeGreaterThan(1) - expect(snapshot.every((descriptor) => descriptor.transport === liveTransport)).toBe(true) - const dispatched = snapshot.filter((descriptor) => descriptor.valueSource === 'dispatched') - expect(dispatched.length).toBeGreaterThan(0) - expect(dispatched.every(sessionOptionDispatchUnconfirmed)).toBe(liveTransport === 'catalog') - } - ) - - describe('withTrackedNativeChatModel', () => { - it('keeps an unlisted tracked model as a choice, preferring the seed row', () => { - const record = claudeRecord() - record.model = { value: 'opus', source: 'reported' } - // A discovered list that dropped the `opus` alias this host no longer lists. - const discovered = CLAUDE_SESSION_OPTION_CATALOG.models.filter((model) => model.id !== 'opus') - const reconciled = withTrackedNativeChatModel( - CLAUDE_SESSION_OPTION_CATALOG, - discovered, - record - ) - // The seed row carries the model's own options, so they don't vanish. - const snapshot = buildNativeChatSessionOptionSnapshot({ - catalog: CLAUDE_SESSION_OPTION_CATALOG, - models: reconciled, - record, - mode: 'live', - modelLabel: 'Model', - liveTransport: 'catalog' - }) - const model = snapshot[0]! - if (model.kind.type !== 'select') { - throw new Error('model descriptor must be a select') - } - expect(model.kind.currentValue).toBe('opus') - expect(model.kind.choices.some((choice) => choice.value === 'opus')).toBe(true) - expect(snapshot.length).toBeGreaterThan(1) - }) - - it('re-injects a grok seed model an authoritative discovery dropped', () => { - // PTY retires picks after authoritative discovery; shared reconciliation retains labeled pre-discovery selections. - const record = createNativeChatSessionOptionRecord('grok') - record.model = { value: 'grok-4.5', source: 'dispatched' } - const discovered = mergeDiscoveredAuthoritativeModels(GROK_SESSION_OPTION_CATALOG.models, [ - { id: 'grok-build', label: 'Grok Build', options: [] } - ]) - expect(discovered.map(({ id }) => id)).toEqual(['grok-build']) - - const reconciled = withTrackedNativeChatModel(GROK_SESSION_OPTION_CATALOG, discovered, record) - expect(reconciled.map(({ id }) => id)).toEqual(['grok-build', 'grok-4.5']) - - const snapshot = buildNativeChatSessionOptionSnapshot({ - catalog: GROK_SESSION_OPTION_CATALOG, - models: reconciled, - record, - mode: 'live', - modelLabel: 'Model', - liveTransport: 'catalog' - }) - expect(snapshot.map((descriptor) => descriptor.id)).toEqual(['model', 'effort']) - expect(resolveAgentSessionOptionLaunch('grok', { model: 'grok-4.5' }).args).toEqual([ - '-m', - 'grok-4.5', - '--reasoning-effort', - 'high' - ]) - }) - }) - - it('describes Codex model changes as agent-picker actions', () => { - const snapshot = buildNativeChatSessionOptionSnapshot({ - catalog: CODEX_SESSION_OPTION_CATALOG, - models: CODEX_SESSION_OPTION_CATALOG.models, - record: createNativeChatSessionOptionRecord('codex'), - mode: 'live', - modelLabel: 'Model', - liveTransport: 'catalog' - }) - expect(snapshot[0]).toMatchObject({ settable: true }) - expect(snapshot[0]?.action).toEqual({ type: 'agent-picker' }) - }) - - it('marks flip-only toggles without a baseline as toggle actions', () => { - const record = claudeRecord() - record.model = { value: 'opus', source: 'reported' } - const snapshot = buildNativeChatSessionOptionSnapshot({ - catalog: CLAUDE_SESSION_OPTION_CATALOG, - models: CLAUDE_SESSION_OPTION_CATALOG.models, - record, - mode: 'live', - modelLabel: 'Model', - liveTransport: 'catalog' - }) - const fastMode = snapshot.find((descriptor) => descriptor.id === 'fastMode') - expect(fastMode).toMatchObject({ action: { type: 'toggle-command' } }) - }) -}) - -describe('defaults on load', () => { - const grokDraft = ( - models = GROK_SESSION_OPTION_CATALOG.models, - mode: 'draft' | 'live' = 'draft' - ): SessionOptionDescriptor[] => - buildNativeChatSessionOptionSnapshot({ - catalog: GROK_SESSION_OPTION_CATALOG, - models, - record: createNativeChatSessionOptionRecord('grok'), - mode, - modelLabel: 'Model', - liveTransport: 'catalog' - }) - - it('offers the effort row under that default model without naming its value', () => { - // Grok documents no effort default and unpicked launches emit no flag, so the CLI choice is unknown. - const effort = grokDraft().find((descriptor) => descriptor.id === 'effort') - expect(effort).toMatchObject({ valueSource: 'unknown' }) - expect(effort?.kind.type === 'select' ? effort.kind.currentValue : null).toBeUndefined() - }) - - it('names no model when discovery retired the one the catalog marks default', () => { - // Guessing a replacement would misreport which model the launch actually picks. - const retired = mergeDiscoveredAuthoritativeModels(GROK_SESSION_OPTION_CATALOG.models, [ - { id: 'grok-build', label: 'Grok Build', options: [] } - ]) - const snapshot = grokDraft(retired) - expect(snapshot).toHaveLength(1) - expect(snapshot[0]).toMatchObject({ valueSource: 'unknown' }) - }) - - it('leaves a tracked pick as the authority over the default', () => { - const record = createNativeChatSessionOptionRecord('grok') - record.model = { value: 'grok-build', source: 'dispatched' } - const snapshot = buildNativeChatSessionOptionSnapshot({ - catalog: GROK_SESSION_OPTION_CATALOG, - models: [ - ...GROK_SESSION_OPTION_CATALOG.models, - { id: 'grok-build', label: 'Grok Build', options: [] } - ], - record, - mode: 'draft', - modelLabel: 'Model', - liveTransport: 'catalog' - }) - expect(snapshot[0]).toMatchObject({ valueSource: 'dispatched' }) - expect(snapshot[0]!.kind.type === 'select' ? snapshot[0]!.kind.currentValue : null).toBe( - 'grok-build' - ) - }) - - it('shows no default for an agent whose isDefault is only decorative', () => { - // Claude’s account/settings choose its real default; untouched launches send no --model, so seeded sonnet is unproven. - const snapshot = buildNativeChatSessionOptionSnapshot({ - catalog: CLAUDE_SESSION_OPTION_CATALOG, - models: CLAUDE_SESSION_OPTION_CATALOG.models, - record: claudeRecord(), - mode: 'draft', - modelLabel: 'Model', - liveTransport: 'catalog' - }) - expect(snapshot).toHaveLength(1) - expect(snapshot[0]).toMatchObject({ valueSource: 'unknown' }) - }) -}) - -describe('a boolean option always carries a value to render', () => { - // Cursor defaults thinking true; omitting the display value would falsely render the switch off. - function cursorSnapshot(mode: 'draft' | 'live'): SessionOptionDescriptor[] { - const record = createNativeChatSessionOptionRecord('cursor') - record.model = { value: 'claude-opus-4-8', source: 'reported' } - return buildNativeChatSessionOptionSnapshot({ - catalog: CURSOR_SESSION_OPTION_CATALOG, - models: CURSOR_SESSION_OPTION_CATALOG.models, - record, - mode, - modelLabel: 'Model', - liveTransport: mode === 'live' ? 'agent-session' : 'catalog' - }) - } - const thinkingOf = (mode: 'draft' | 'live'): SessionOptionDescriptor | undefined => - cursorSnapshot(mode).find((descriptor) => descriptor.id === 'thinking') - - it('resolves an unreported live boolean to the catalog default, not to off', () => { - // Switches cannot display unknown; resolve to the same default used by composed dispatch. - const thinking = thinkingOf('live') - expect(thinking?.kind.type).toBe('boolean') - expect(thinking?.kind.type === 'boolean' ? thinking.kind.currentValue : null).toBe(true) - }) - - it('keeps provenance on its own track when it resolves that value', () => { - // Resolved display values are not agent confirmation; keep provenance unknown/default for pills. - expect(thinkingOf('live')).toMatchObject({ valueSource: 'unknown' }) - expect(thinkingOf('draft')).toMatchObject({ valueSource: 'default' }) - }) - - it('resolves a tracked boolean to the tracked value, not the catalog default', () => { - const record = createNativeChatSessionOptionRecord('cursor') - record.model = { value: 'claude-opus-4-8', source: 'reported' } - record.valuesByModel['claude-opus-4-8'] = { thinking: { value: false, source: 'reported' } } - const snapshot = buildNativeChatSessionOptionSnapshot({ - catalog: CURSOR_SESSION_OPTION_CATALOG, - models: CURSOR_SESSION_OPTION_CATALOG.models, - record, - mode: 'live', - modelLabel: 'Model', - liveTransport: 'agent-session' - }) - const thinking = snapshot.find((descriptor) => descriptor.id === 'thinking') - expect(thinking?.kind.type === 'boolean' ? thinking.kind.currentValue : null).toBe(false) - expect(thinking).toMatchObject({ valueSource: 'reported' }) - }) - - it('leaves a select able to render nothing selected', () => { - // Only the boolean kind resolves: a radio group can show no selection - // truthfully, so nothing forces a value onto it. - const effort = cursorSnapshot('live')!.find((descriptor) => descriptor.id === 'effort') - expect(effort?.kind.type === 'select' ? effort.kind.currentValue : null).toBeUndefined() - expect(effort).toMatchObject({ valueSource: 'unknown' }) - }) - - it('includes composed launch defaults only when requested', () => { - // Composed model uses caller picks, never display descriptors; resolving a switch cannot alter dispatch. - expect(resolveAgentSessionOptionLaunch('cursor', { model: 'claude-opus-4-8' })).toEqual({ - args: ['--model', 'claude-opus-4-8-thinking-high'], - appliedValues: { model: 'claude-opus-4-8', thinking: true, effort: 'high' } - }) - expect( - resolveAgentSessionOptionLaunch('cursor', { model: 'claude-opus-4-8' }, [], false) - ).toEqual({ - args: ['--model', 'claude-opus-4-8'], - appliedValues: { model: 'claude-opus-4-8' } - }) - }) -}) diff --git a/src/shared/native-chat/transcript/native-chat-transcript-contracts.test.ts b/src/shared/native-chat/transcript/native-chat-transcript-contracts.test.ts index e575dbd1d4b..9986b7ce27e 100644 --- a/src/shared/native-chat/transcript/native-chat-transcript-contracts.test.ts +++ b/src/shared/native-chat/transcript/native-chat-transcript-contracts.test.ts @@ -1,9 +1,7 @@ -import './row-content/native-chat-reasoning-row.spec' import '../native-chat-reasoning-order.spec' import '../tools/native-chat-tool-activity.spec' import '../tools/native-chat-tool-pair-limit.spec' import '../tools/native-chat-tool-fold-attribution.spec' -import './turns/native-chat-turn-grouping.spec' import '../tools/native-chat-tool-pairing.spec' import '../native-chat-streaming.spec' import '../tools/native-chat-tool-result-orphans.spec' diff --git a/src/shared/native-chat/transcript/row-content/native-chat-reasoning-row.spec.ts b/src/shared/native-chat/transcript/row-content/native-chat-reasoning-row.spec.ts deleted file mode 100644 index 6538be1ce62..00000000000 --- a/src/shared/native-chat/transcript/row-content/native-chat-reasoning-row.spec.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { selectNativeChatLiveReasoning } from './native-chat-reasoning-row' -import type { NativeChatMessage } from '../../native-chat-types' - -function row( - id: string, - role: NativeChatMessage['role'], - text: string, - fields: Partial = {} -): NativeChatMessage { - return { - id, - role, - blocks: [{ type: 'text', text }], - timestamp: 1_000, - source: 'transcript', - ...fields - } -} - -const prompt = row('user-1', 'user', 'Start the task') -const open = row('r-1', 'reasoning', 'Weighing two approaches', { state: 'running' }) -const inTurn = (): boolean => true - -describe('the open block the live line discloses', () => { - const select = (messages: NativeChatMessage[], live: (index: number) => boolean = inTurn) => - selectNativeChatLiveReasoning(messages, live)?.message ?? null - - it('is the newest root reasoning row with text, with the text it has so far', () => { - expect(selectNativeChatLiveReasoning([prompt, open], inTurn)).toEqual({ - message: open, - markdown: 'Weighing two approaches' - }) - // A host that keeps no lifecycle gets the same single live slot. - const stateless = row('r-1', 'reasoning', 'Weighing two approaches') - expect(select([prompt, stateless])).toBe(stateless) - }) - - it('is nothing when the block is blank or ended', () => { - expect(select([prompt, row('r-1', 'reasoning', ' \n', { state: 'running' })])).toBeNull() - expect(select([prompt, { ...open, state: 'completed' }])).toBeNull() - }) - - it('is nothing once a tool or the answer is newer than the block', () => { - expect(select([prompt, open, row('a-1', 'assistant', 'Here it is')])).toBeNull() - const tool = row('t-1', 'assistant', '', { - blocks: [{ type: 'tool-call', name: 'Read', input: { file_path: 'a.ts' }, state: 'running' }] - }) - expect(select([prompt, open, tool])).toBeNull() - }) - - it('looks past notices, empty rows and rows outside the live working turn', () => { - const notice = row('s-1', 'system', 'Compacting') - const empty = row('a-0', 'assistant', '') - const waiting = row('user-2', 'user', 'Also say banana') - expect(select([prompt, open, notice, empty, waiting], (index) => index < 4)).toBe(open) - }) - - it('stops at the live turn prompt and ignores a subagent reasoning', () => { - expect(select([open, prompt])).toBeNull() - const child = row('r-2', 'reasoning', 'Child thinking', { state: 'running', agentId: 'sub-1' }) - expect(select([prompt, child])).toBeNull() - expect(select([prompt, open, child])).toBe(open) - }) -}) diff --git a/src/shared/native-chat/transcript/subagents/native-chat-subagent-summary.test.ts b/src/shared/native-chat/transcript/subagents/native-chat-subagent-summary.test.ts deleted file mode 100644 index 6511d8e55e0..00000000000 --- a/src/shared/native-chat/transcript/subagents/native-chat-subagent-summary.test.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - isSubagentGroupFallbackText, - isTerminalSubagentState, - normalizeSubagentState, - subagentGroupFallbackText, - summarizeSubagentGroup, - withoutSubagentGroupTwins -} from './native-chat-subagent-summary' -import type { NativeChatSubagentEntry } from '../../native-chat-types' - -function agent(entry: Partial): NativeChatSubagentEntry { - return { id: 'a', label: 'task', state: 'working', ...entry } -} - -describe('summarizeSubagentGroup', () => { - it('ranks the settled verdict worst-first and reports ✓ completed last', () => { - const cascade: [NativeChatSubagentEntry['state'][], string][] = [ - [['failed', 'stopped', 'idle', 'completed'], 'failed'], - [['stopped', 'idle', 'completed'], 'stopped'], - [['unverifiable', 'idle', 'completed'], 'unverifiable'], - [['idle', 'completed'], 'idle'], - [['completed', 'completed'], 'completed'] - ] - - for (const [states, expected] of cascade) { - const summary = summarizeSubagentGroup( - states.map((state, index) => agent({ id: `a${index}`, state })) - ) - expect(summary.settledState).toBe(expected) - } - }) - - it('reports the earliest start and withholds a settled time while work continues', () => { - const working = summarizeSubagentGroup([ - agent({ id: 'a', state: 'completed', startedAt: 50, settledAt: 80 }), - agent({ id: 'b', state: 'working', startedAt: 20 }) - ]) - const settled = summarizeSubagentGroup([ - agent({ id: 'a', state: 'completed', startedAt: 50, settledAt: 80 }), - agent({ id: 'b', state: 'stopped', startedAt: 20, settledAt: 95 }) - ]) - - expect(working).toMatchObject({ clockStartedAt: 20, settledAt: null }) - expect(settled).toMatchObject({ clockStartedAt: 20, settledAt: 95 }) - }) - - it('reads a state this build does not know as unverifiable, never as working', () => { - expect(normalizeSubagentState('paused-for-review')).toBe('unverifiable') - expect(isTerminalSubagentState('paused-for-review')).toBe(true) - expect(summarizeSubagentGroup([agent({ state: 'unheard-of' as 'working' })])).toMatchObject({ - working: 0, - settledState: 'unverifiable' - }) - }) - - it('reports an adverse outcome before the group settles', () => { - const summary = summarizeSubagentGroup([ - agent({ id: 'a', state: 'working' }), - agent({ id: 'b', state: 'working' }), - agent({ id: 'c', state: 'failed' }) - ]) - - // The group verdict is still withheld, but the failure is not. - expect(summary).toMatchObject({ - working: 2, - settledState: null, - adverseState: 'failed', - adverseCount: 1 - }) - }) -}) - -describe('subagentGroupFallbackText', () => { - it('names the failure a client without the block type would otherwise never see', () => { - expect( - subagentGroupFallbackText([ - agent({ id: 'a', state: 'working' }), - agent({ id: 'b', state: 'working' }), - agent({ id: 'c', state: 'failed' }) - ]) - ).toBe('Kicked off 3 subagents (1 failed)') - expect( - subagentGroupFallbackText([ - agent({ id: 'a', state: 'completed' }), - agent({ id: 'b', state: 'stopped' }) - ]) - ).toBe('Ran 2 subagents (1 stopped)') - }) - - // Frozen journal text replays to non-reconciling clients. Claim only spawn/latched outcomes; Kicked off versus Ran records write-time outcome presence, never liveness. - it('makes no liveness claim a replayed row could not still justify', () => { - const inFlight = subagentGroupFallbackText([ - agent({ id: 'a', state: 'working' }), - agent({ id: 'b', state: 'working' }), - agent({ id: 'c', state: 'completed' }) - ]) - - expect(inFlight).toBe('Kicked off 3 subagents') - expect(inFlight).not.toMatch(/\bworking\b/) - expect( - subagentGroupFallbackText([ - agent({ id: 'a', state: 'working' }), - agent({ id: 'b', state: 'unverifiable' }) - ]) - ).toBe('Kicked off 2 subagents (1 unverifiable)') - }) -}) - -// Twin false positives hide real prose; false negatives duplicate rosters. Match shape because newer states cannot reproduce byte-for-byte here. -describe('isSubagentGroupFallbackText', () => { - it('recognizes every sentence the producer writes, including an unknown state', () => { - // Not reproducible here: this build normalizes `cancelled` to `unverifiable`. - expect(isSubagentGroupFallbackText('Ran 2 subagents (1 cancelled)')).toBe(true) - expect(isSubagentGroupFallbackText('Kicked off 4 subagents — 2 working (1 timed-out)')).toBe( - true - ) - }) - - // Legacy dev journals retain live-count twins forever; continue matching them to avoid duplicate replay rows. - it('still recognizes the legacy twin already frozen into existing journals', () => { - for (const legacy of [ - 'Kicked off 1 subagent — 1 working', - 'Kicked off 4 subagents — 2 working', - 'Kicked off 4 subagents — 2 working (1 failed)', - 'Kicked off 4 subagents — 2 working (1 timed-out)' - ]) { - expect(isSubagentGroupFallbackText(legacy)).toBe(true) - } - }) - - it('leaves prose that merely mentions subagents alone', () => { - for (const prose of [ - 'Handing the audit to two children.', - 'I kicked off 2 subagents to look at this', - 'Ran 2 subagents and then cleaned up', - 'Ran 2 subagents (1 failed) — see below', - 'Ran two subagents' - ]) { - expect(isSubagentGroupFallbackText(prose)).toBe(false) - } - }) -}) - -describe('withoutSubagentGroupTwins', () => { - const twin = { type: 'text' as const, text: 'Ran 1 subagent' } - const prose = { type: 'text' as const, text: 'Delegating the review.' } - - it('drops the twin only beside a group that draws', () => { - const group = { type: 'subagent-group' as const, groupId: 'g', agents: [agent({})] } - expect(withoutSubagentGroupTwins([twin, prose, group])).toEqual([prose, group]) - const childless = { type: 'subagent-group' as const, groupId: 'g', agents: [] } - expect(withoutSubagentGroupTwins([twin, childless])).toEqual([twin, childless]) - expect(withoutSubagentGroupTwins([twin])).toEqual([twin]) - }) -}) diff --git a/src/shared/native-chat/transcript/turns/native-chat-turn-activity.test.ts b/src/shared/native-chat/transcript/turns/native-chat-turn-activity.test.ts deleted file mode 100644 index 67da219b7dc..00000000000 --- a/src/shared/native-chat/transcript/turns/native-chat-turn-activity.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { - AgentJournalItemBody, - AgentJournalRenderItem -} from '../../../agent-session/journal/agent-session-journal-types' -import { selectStructuredAgentTurnActivity } from './native-chat-turn-activity' - -function item(sequence: number, body: AgentJournalItemBody): AgentJournalRenderItem { - return { itemId: `item-${sequence}`, revision: 1, sequence, observedAt: sequence, body } -} - -const turnStart = item(1, { - kind: 'status', - text: 'Codex is working…', - turnLifecycle: { turnId: 'turn-1', state: 'running' } -}) - -describe('selectStructuredAgentTurnActivity', () => { - it("never puts the model's reasoning on the indicator line", () => { - const reasoning = item(2, { - kind: 'message', - role: 'reasoning', - blocks: [{ type: 'text', text: 'Let me check whether the journal already records this' }] - }) - - // Reasoning is the turn's content; the row says the turn is thinking instead. - expect(selectStructuredAgentTurnActivity([turnStart, reasoning], 'turn-1')).toBeNull() - // Provider-authored copy is unaffected, so Codex keeps its line. - expect( - selectStructuredAgentTurnActivity([turnStart, reasoning], 'turn-1', { - turnId: 'turn-1', - text: 'Running a command' - }) - ).toEqual({ kind: 'description', text: 'Running a command' }) - }) - - it('ignores ephemeral activity from another or settled turn', () => { - const providerActivity = { turnId: 'turn-1', text: 'Inspecting the session wire' } - - expect(selectStructuredAgentTurnActivity([turnStart], 'turn-2', providerActivity)).toBeNull() - expect(selectStructuredAgentTurnActivity([turnStart], null, providerActivity)).toBeNull() - }) - - it.each([ - ['active', 'Still running pnpm test'], - ['most recently settled', 'Running shell pnpm lint now'] - ])('never repeats the %s tool label as provider activity', (_kind, text) => { - const activity = selectStructuredAgentTurnActivity( - [ - turnStart, - item(2, { - kind: 'tool-call', - name: 'shell', - input: { command: 'pnpm test' }, - state: 'running' - }), - item(3, { - kind: 'tool-call', - name: 'shell', - input: { command: 'pnpm lint' }, - state: 'completed' - }) - ], - 'turn-1', - { turnId: 'turn-1', text } - ) - - expect(activity).toBeNull() - }) -}) - -describe('selectStructuredAgentTurnActivity — which agent it answers for', () => { - /** A row a subagent produced, which shares the session's journal. */ - function childItem(sequence: number, body: AgentJournalItemBody): AgentJournalRenderItem { - return { ...item(sequence, body), agentId: 'task-1', producerKind: 'agent' } - } - - const childRunningBash = childItem(2, { - kind: 'tool-call', - name: 'shell', - input: { command: 'pnpm test' }, - state: 'running' - }) - - it("does not let a child's tool label suppress the provider's line for the parent", () => { - // Child tool labels cannot dedupe the session parent’s own provider activity line. - expect( - selectStructuredAgentTurnActivity([turnStart, childRunningBash], 'turn-1', { - turnId: 'turn-1', - text: 'pnpm test' - }) - ).toEqual({ kind: 'description', text: 'pnpm test' }) - }) - - it("still suppresses a line repeating the session's OWN running tool", () => { - // The scoping must not disable the de-duplication it was narrowing. - expect( - selectStructuredAgentTurnActivity( - [ - turnStart, - item(2, { - kind: 'tool-call', - name: 'shell', - input: { command: 'pnpm test' }, - state: 'running' - }) - ], - 'turn-1', - { turnId: 'turn-1', text: 'pnpm test' } - ) - ).toBeNull() - }) -}) diff --git a/src/shared/native-chat/transcript/turns/native-chat-turn-grouping.spec.ts b/src/shared/native-chat/transcript/turns/native-chat-turn-grouping.spec.ts deleted file mode 100644 index 012a0df1f11..00000000000 --- a/src/shared/native-chat/transcript/turns/native-chat-turn-grouping.spec.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { NativeChatMessage } from '../../native-chat-types' -import { - nativeChatRowTurnKeys, - nativeChatTurnBarRows, - nativeChatTurnDrawOrder -} from './native-chat-turn-grouping' - -function message(id: string, role: NativeChatMessage['role'] = 'assistant'): NativeChatMessage { - return { id, role, blocks: [{ type: 'text', text: id }], timestamp: null, source: 'transcript' } -} - -describe('nativeChatRowTurnKeys', () => { - it('keeps rows after a mid-turn send with the turn that produced them', () => { - // The #23621 shape: B lands mid-turn, three tool rows follow, all one turn. - const messages = [ - message('A', 'user'), - message('t1'), - message('B', 'user'), - message('t2'), - message('t3'), - message('t4') - ] - const owned = new Map([ - ['A', 'A'], - ['t1', 'A'], - ['B', 'A'], - ['t2', 'A'], - ['t3', 'A'], - ['t4', 'A'] - ]) - expect(nativeChatRowTurnKeys(messages, owned)).toEqual(['A', 'A', 'A', 'A', 'A', 'A']) - }) - - it('lets an unmapped user row key itself and unmapped rows inherit it', () => { - // C is an optimistic echo the journal has not admitted yet: positional rules. - const messages = [message('A', 'user'), message('t1'), message('C', 'user'), message('t2')] - const owned = new Map([ - ['A', 'A'], - ['t1', 'A'] - ]) - expect(nativeChatRowTurnKeys(messages, owned)).toEqual(['A', 'A', 'C', 'C']) - }) - - it('reproduces preceding-user grouping exactly when the host attributes nothing', () => { - const messages = [ - message('lead'), - message('A', 'user'), - message('t1'), - message('B', 'user'), - message('t2') - ] - const positional = [undefined, 'A', 'A', 'B', 'B'] - expect(nativeChatRowTurnKeys(messages, null)).toEqual(positional) - expect(nativeChatRowTurnKeys(messages, new Map())).toEqual(positional) - }) - - it('keys a provider-opened turn to a record no message carries', () => { - const messages = [message('A', 'user'), message('t1'), message('t2')] - const owned = new Map([ - ['A', 'A'], - ['t1', 'wake-turn'], - ['t2', 'wake-turn'] - ]) - expect(nativeChatRowTurnKeys(messages, owned)).toEqual(['A', 'wake-turn', 'wake-turn']) - }) -}) - -describe('nativeChatTurnBarRows', () => { - it('anchors a turn with no user bubble above its first rendered row', () => { - const messages = [message('A', 'user'), message('t1'), message('t2'), message('t3')] - const turnKeys = ['A', 'A', 'wake-turn', 'wake-turn'] - expect(nativeChatTurnBarRows(messages, turnKeys)).toEqual( - new Map([ - ['A', { index: 0, above: false }], - ['wake-turn', { index: 2, above: true }] - ]) - ) - }) -}) - -describe('nativeChatTurnDrawOrder', () => { - it("draws a message that opened a later turn after the earlier turn's remaining rows", () => { - // B was sent while A ran and Claude queued it: A's tool run and answer follow B in the journal. - const messages = [ - message('A', 'user'), - message('a1'), - message('B', 'user'), - message('a2'), - message('a-done'), - message('b1') - ] - const turnKeys = ['A', 'A', 'B', 'A', 'A', 'B'] - expect(nativeChatTurnDrawOrder(messages, turnKeys, new Set(['A', 'B']))).toEqual([ - 0, 1, 3, 4, 2, 5 - ]) - }) - - it('keeps each of several queued openers ahead of its own rows', () => { - const messages = [ - message('A', 'user'), - message('B', 'user'), - message('C', 'user'), - message('a-done'), - message('b1'), - message('c1') - ] - const turnKeys = ['A', 'B', 'C', 'A', 'B', 'C'] - const order = nativeChatTurnDrawOrder(messages, turnKeys, new Set(['A', 'B', 'C'])) - expect(order?.map((index) => messages[index]!.id)).toEqual([ - 'A', - 'a-done', - 'B', - 'b1', - 'C', - 'c1' - ]) - }) - - it('leaves a steer, and a message that opened no turn, where they were written', () => { - const messages = [message('A', 'user'), message('steer', 'user'), message('a1')] - expect(nativeChatTurnDrawOrder(messages, ['A', 'A', 'A'], new Set(['A']))).toBeNull() - const waiting = [message('A', 'user'), message('C', 'user'), message('a1')] - expect(nativeChatTurnDrawOrder(waiting, ['A', 'C', 'A'], new Set(['A']))).toBeNull() - }) -}) diff --git a/src/shared/workspace-layout/tab-groups/tab-group-moves.test.ts b/src/shared/workspace-layout/tab-groups/tab-group-moves.test.ts deleted file mode 100644 index fdf03a21eaf..00000000000 --- a/src/shared/workspace-layout/tab-groups/tab-group-moves.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - buildHeadlessTabGroupMove, - buildHeadlessTabGroupSplit, - collectTabGroupLayoutGroupIds -} from './tab-group-moves' - -const group = (id: string, tabs: string[]) => ({ id, tabOrder: tabs }) - -describe('buildHeadlessTabGroupSplit', () => { - it('splits a tab into a new group to the right (horizontal, second)', () => { - const result = buildHeadlessTabGroupSplit({ - groups: [group('g1', ['a', 'b'])], - layout: { type: 'leaf', groupId: 'g1' }, - tabId: 'b', - targetGroupId: 'g1', - splitDirection: 'right', - newGroupId: 'g2' - }) - expect(result).not.toBeNull() - expect(result!.groups).toHaveLength(2) - expect(result!.groups.find((g) => g.id === 'g1')!.tabOrder).toEqual(['a']) - expect(result!.groups.find((g) => g.id === 'g2')!.tabOrder).toEqual(['b']) - expect(result!.layout).toEqual({ - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', groupId: 'g1' }, - second: { type: 'leaf', groupId: 'g2' }, - ratio: 0.5 - }) - }) - - it('collapses an emptied source group out of the layout when moving across groups', () => { - const result = buildHeadlessTabGroupSplit({ - groups: [group('g1', ['a']), group('g2', ['b'])], - layout: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', groupId: 'g1' }, - second: { type: 'leaf', groupId: 'g2' } - }, - tabId: 'b', - targetGroupId: 'g1', - splitDirection: 'right', - newGroupId: 'g3' - }) - const ids = result!.groups.map((g) => g.id).sort() - expect(ids).toEqual(['g1', 'g3']) - expect([...collectTabGroupLayoutGroupIds(result!.layout)].sort()).toEqual(['g1', 'g3']) - }) - - it('synthesizes a leaf layout when none exists yet', () => { - const result = buildHeadlessTabGroupSplit({ - groups: [group('g1', ['a', 'b'])], - layout: null, - tabId: 'b', - targetGroupId: 'g1', - splitDirection: 'right', - newGroupId: 'g2' - }) - expect(result!.layout).toMatchObject({ type: 'split' }) - expect([...collectTabGroupLayoutGroupIds(result!.layout)].sort()).toEqual(['g1', 'g2']) - }) -}) - -describe('buildHeadlessTabGroupMove', () => { - const twoGroupLayout = { - type: 'split' as const, - direction: 'horizontal' as const, - first: { type: 'leaf' as const, groupId: 'g1' }, - second: { type: 'leaf' as const, groupId: 'g2' } - } - - it('moves a tab into an existing group at the given index', () => { - const result = buildHeadlessTabGroupMove({ - groups: [group('g1', ['a', 'b']), group('g2', ['c'])], - layout: twoGroupLayout, - tabId: 'b', - targetGroupId: 'g2', - index: 0 - }) - expect(result!.groups.find((g) => g.id === 'g1')!.tabOrder).toEqual(['a']) - expect(result!.groups.find((g) => g.id === 'g2')!.tabOrder).toEqual(['b', 'c']) - }) - - it('collapses the source group out of the layout when the move empties it', () => { - const result = buildHeadlessTabGroupMove({ - groups: [group('g1', ['a']), group('g2', ['b'])], - layout: twoGroupLayout, - tabId: 'a', - targetGroupId: 'g2' - }) - expect(result!.groups.map((g) => g.id)).toEqual(['g2']) - expect(result!.layout).toEqual({ type: 'leaf', groupId: 'g2' }) - }) -})