mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 11:54:46 +00:00
test: remove 208 low-value test declarations (#38160)
Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
@@ -33,7 +33,6 @@
|
||||
1 test-no-in-test-import-actual:src/main/window/dropped-path-preparation.test.ts
|
||||
1 test-no-in-test-import-actual:src/main/workspaces/removal/local-worktree-removal-recovery.test.ts
|
||||
1 test-no-in-test-import-actual:src/renderer/src/components/native-chat/use-native-chat-context-menu.test.tsx
|
||||
1 test-no-in-test-import-actual:src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts
|
||||
1 test-no-in-test-import-actual:src/renderer/src/components/sidebar/sidebar-feedback/SidebarFeedbackDialog.test.tsx
|
||||
1 test-no-in-test-import-actual:src/renderer/src/components/sidebar/workspace-card/activity/WorktreeCardAgents.activation.test.tsx
|
||||
1 test-no-in-test-import-actual:src/renderer/src/components/terminal-pane/pty-connection-hook-idle-arbitration.test.ts
|
||||
|
||||
@@ -4809,15 +4809,15 @@
|
||||
"providers": ["local", "ssh"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local", "ssh"],
|
||||
"coverageNotes": "Local deterministic evidence covers git-common classification, desktop watcher debounce counts, non-overlapping poller semantics, macOS native-watch fallback, preload cleanup, Source Control active-visible repo filtering, paired-runtime publication to two independent clients with reconnect and stale-cache checks, and process generation-scope rollover across sibling targets. A headed macOS Electron host and separate paired Electron client both rendered a worktree created through the real Git binary and watcher entry path without reconnect. Linux/Windows desktop clients, multi-target live fanout, and WSL runs remain gaps. Audit1309: src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts: Keep real filesystem HEAD/loose/packed/relative metadata reads and traversal refusal. Remove invalid-oid/nonstandard-layout characterization. Lose malformed object-id and bare-dir omission alarms; no Git-produced layout claim. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.",
|
||||
"coverageNotes": "Local deterministic evidence covers git-common classification, desktop watcher debounce counts, non-overlapping poller semantics, macOS native-watch fallback, preload cleanup, paired-runtime publication to two independent clients with reconnect and stale-cache checks, and process generation-scope rollover across sibling targets. A headed macOS Electron host and separate paired Electron client both rendered a worktree created through the real Git binary and watcher entry path without reconnect. Linux/Windows desktop clients, multi-target live fanout, and WSL runs remain gaps. Audit1309: src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts: Keep real filesystem HEAD/loose/packed/relative metadata reads and traversal refusal. Remove invalid-oid/nonstandard-layout characterization. Lose malformed object-id and bare-dir omission alarms; no Git-produced layout claim. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed.",
|
||||
"motivatingLinks": [
|
||||
"https://github.com/stablyai/orca/pull/7086",
|
||||
"https://github.com/stablyai/orca/issues/16477"
|
||||
],
|
||||
"invariant": "Index-only Git activity below the common Git directory must not emit worktrees:changed, invalidate worktree caches, or trigger fetchWorktrees fanout; structural add/remove/HEAD/gitdir/locked/config.worktree changes must still refresh worktrees and nudge Source Control. When the authoritative paired host accepts an external structural change for a uniquely identified server-local repo, each live client for that host must receive one existing host-scoped worktreesChanged invalidation and converge to the same repo/worktree identity without reconnect; duplicate watcher events must coalesce, stale cached or in-flight catalogs must not survive invalidation, and event-ignoring clients must remain compatible. Colliding local/SSH repo IDs must not publish the host-blind event until existing semantics can carry owner identity. External head moves (commit, amend, reset) must reach background worktree rows through spawn-free metadata reads, never through structural fanout. A process generation-scope rollover revokes every direct SSH target and old-scope provider request, not only the target whose counter exhausted.",
|
||||
"oracle": "Classify exact git-common paths as structural, status-only, or ignored; count notifications from debounced watcher events; force the Linux/Windows poll path to emit allowlisted leaf events, detect linked HEAD rewrites independent of entry-directory mtime, and surface in-place index rewrites via the backstop re-stat; diff head identities from metadata-file reads and notify only real head moves; assert Source Control subscribes to both structural and status-only signals with active-repo and visibility filters. Join the real runtime RPC server to two independently authenticated E2EE clients plus an event-ignoring client, advance the host Git inventory, trigger duplicate structural watcher callbacks, and require one host renderer notification plus one runtime event and a refreshed catalog per subscribed client; require the event-ignoring client to refresh safely on explicit read. Hold a scan after it captures old inventory, join it from a second paired client, publish the watcher invalidation, advance Git independently, and require both overlapping RPCs to retry or join one fresh scan before returning. Disconnect one client, advance inventory again, and require reconnect to read current state without stale event replay. Give a watcher a local repo ID colliding with an SSH owner and require the host renderer refresh while the unqualified runtime event stays absent. Force the real path in isolated Electron apps with git worktree add, a host Git inventory assertion, store-subscription barriers, matching host/client worktree identity, and visible rows in both renderers. For direct SSH, roll one exhausted target into a fresh process generation scope while invalidating sibling target tokens, and fill a partial pushed authority before clearing that target's PTY bindings once.",
|
||||
"oracle": "Classify exact git-common paths as structural, status-only, or ignored; count notifications from debounced watcher events; force the Linux/Windows poll path to emit allowlisted leaf events, detect linked HEAD rewrites independent of entry-directory mtime, and surface in-place index rewrites via the backstop re-stat; diff head identities from metadata-file reads and notify only real head moves. Join the real runtime RPC server to two independently authenticated E2EE clients plus an event-ignoring client, advance the host Git inventory, trigger duplicate structural watcher callbacks, and require one host renderer notification plus one runtime event and a refreshed catalog per subscribed client; require the event-ignoring client to refresh safely on explicit read. Hold a scan after it captures old inventory, join it from a second paired client, publish the watcher invalidation, advance Git independently, and require both overlapping RPCs to retry or join one fresh scan before returning. Disconnect one client, advance inventory again, and require reconnect to read current state without stale event replay. Give a watcher a local repo ID colliding with an SSH owner and require the host renderer refresh while the unqualified runtime event stays absent. Force the real path in isolated Electron apps with git worktree add, a host Git inventory assertion, store-subscription barriers, matching host/client worktree identity, and visible rows in both renderers. For direct SSH, roll one exhausted target into a fresh process generation scope while invalidating sibling target tokens, and fill a partial pushed authority before clearing that target's PTY bindings once. Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.test.ts src/main/ipc/worktrees/creation/worktree-base-directory-watcher.test.ts src/main/ipc/worktrees/creation/worktree-base-directory-poller.test.ts src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.test.ts src/main/ipc/worktrees/creation/worktree-base-directory-watcher.test.ts src/main/ipc/worktrees/creation/worktree-base-directory-poller.test.ts src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/external-worktree-paired-client-discovery.integration.test.ts src/main/window/attach-main-window-services.test.ts",
|
||||
"ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-external-worktree-discovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/connection/ssh-connection-generation.test.ts src/main/ssh/ssh-provider-authority.test.ts --reporter=dot",
|
||||
@@ -4828,7 +4828,6 @@
|
||||
"src/main/ipc/worktrees/creation/worktree-base-directory-watcher.test.ts",
|
||||
"src/main/ipc/worktrees/creation/worktree-base-directory-poller.test.ts",
|
||||
"src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts",
|
||||
"src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts",
|
||||
"src/main/runtime/external-worktree-paired-client-discovery.integration.test.ts",
|
||||
"src/main/window/attach-main-window-services.test.ts",
|
||||
"tests/e2e/paired-external-worktree-discovery.spec.ts",
|
||||
@@ -4866,13 +4865,6 @@
|
||||
"primary checkout HEAD changes and macOS narrow watch/fallback behavior still emit"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts",
|
||||
"assertions": [
|
||||
"Source Control nudges only for the active visible repo on structural and status-only signals",
|
||||
"preload subscriptions and terminal command-finished listeners are cleaned up"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts",
|
||||
"assertions": [
|
||||
@@ -4995,7 +4987,9 @@
|
||||
"Paired web clients intentionally do not run the desktop direct SSH coordinator, and paired-close non-interference lacks a new live run.",
|
||||
"WSL direct SSH fanout remains an explicit live-test gap rather than inferred coverage.",
|
||||
"Audit1309: src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts: Keep real filesystem HEAD/loose/packed/relative metadata reads and traversal refusal. Remove invalid-oid/nonstandard-layout characterization. Lose malformed object-id and bare-dir omission alarms; no Git-produced layout claim. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.",
|
||||
"Audit1309 retired the complete dated receipt after source coverage changed. Its result does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-07-12\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktree-base-directory-event-filter.test.ts src/main/ipc/worktree-base-directory-watcher.test.ts src/main/ipc/worktree-base-directory-poller.test.ts src/main/ipc/worktree-head-identity-reader.test.ts src/renderer/src/hooks/worktree-head-identity-apply.test.ts src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts src/renderer/src/hooks/useIpcEvents-browser-tab-create.test.ts\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.test.ts src/main/ipc/worktrees/creation/worktree-base-directory-watcher.test.ts src/main/ipc/worktrees/creation/worktree-base-directory-poller.test.ts src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 3.12,\n \"summary\": \"7 files and 130 tests passed locally, adding head-identity emit-on-change without structural fanout, reflog status triggers, config.worktree structural classification, the in-place index backstop, and the spawn-free head reader with symref traversal rejection and hex-object-id output validation.\"\n }"
|
||||
"Audit1309 retired the complete dated receipt after source coverage changed. Its result does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-07-12\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktree-base-directory-event-filter.test.ts src/main/ipc/worktree-base-directory-watcher.test.ts src/main/ipc/worktree-base-directory-poller.test.ts src/main/ipc/worktree-head-identity-reader.test.ts src/renderer/src/hooks/worktree-head-identity-apply.test.ts src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts src/renderer/src/hooks/useIpcEvents-browser-tab-create.test.ts\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.test.ts src/main/ipc/worktrees/creation/worktree-base-directory-watcher.test.ts src/main/ipc/worktrees/creation/worktree-base-directory-poller.test.ts src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 3.12,\n \"summary\": \"7 files and 130 tests passed locally, adding head-identity emit-on-change without structural fanout, reflog status triggers, config.worktree structural classification, the in-place index backstop, and the spawn-free head reader with symref traversal rejection and hex-object-id output validation.\"\n }",
|
||||
"Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed.",
|
||||
"Audit1381 historical assertion inventory for removed suite:\n[\n {\n \"file\": \"src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts\",\n \"assertions\": [\n \"Source Control nudges only for the active visible repo on structural and status-only signals\",\n \"preload subscriptions and terminal command-finished listeners are cleaned up\"\n ]\n }\n]"
|
||||
],
|
||||
"demotionRule": "Keep experimental or demote if the focused gate flakes without a product or harness bug, if index-only churn can emit worktrees:changed, or if structural add/remove/HEAD/lock changes fail to converge."
|
||||
},
|
||||
|
||||
@@ -6729,7 +6729,6 @@
|
||||
"src/preload/ssh-authority-forwarding.test.ts": 1111,
|
||||
"src/preload/updater-package-recovery.test.ts": 1102,
|
||||
"src/preload/usage-provider-api.test.ts": 46,
|
||||
"src/renderer/src/app-shell/app-command-handlers-child-workspaces.test.ts": 1576,
|
||||
"src/renderer/src/app-shell/app-command-handlers-tab-rename.test.ts": 1786,
|
||||
"src/renderer/src/app-shell/app-root-surface-settings.test.tsx": 480,
|
||||
"src/renderer/src/app-shell/app-window-chrome.test.ts": 47,
|
||||
@@ -7146,13 +7145,11 @@
|
||||
"src/renderer/src/components/editor/EditorPanel.diff-rich-owner.test.tsx": 2823,
|
||||
"src/renderer/src/components/editor/EditorPanelHeaderPath.test.tsx": 2664,
|
||||
"src/renderer/src/components/editor/external-changes/ExternalFileChangeBanner.test.tsx": 2142,
|
||||
"src/renderer/src/components/editor/external-changes/ExternalFileChangeCompareDialog.test.tsx": 775,
|
||||
"src/renderer/src/components/editor/ImageViewer.test.tsx": 1872,
|
||||
"src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.external-sync.test.tsx": 1660,
|
||||
"src/renderer/src/components/editor/notebook/kernel/IpynbKernelToolbar.test.tsx": 736,
|
||||
"src/renderer/src/components/editor/notebook/document/IpynbRendering.test.tsx": 2143,
|
||||
"src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.link-routing.interaction.test.tsx": 1127,
|
||||
"src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.test.ts": 1754,
|
||||
"src/renderer/src/components/editor/MediaViewer.test.tsx": 308,
|
||||
"src/renderer/src/components/editor/MermaidBlock.test.tsx": 814,
|
||||
"src/renderer/src/components/editor/MermaidViewer.test.tsx": 3079,
|
||||
@@ -7170,7 +7167,6 @@
|
||||
"src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.test.tsx": 722,
|
||||
"src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditor.focus-leave.test.tsx": 4927,
|
||||
"src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownErrorBoundary.lazy-chunk.test.tsx": 367,
|
||||
"src/renderer/src/components/editor/rich-markdown/tables/RichMarkdownTableControls.test.tsx": 2354,
|
||||
"src/renderer/src/components/editor/ai-vault-session-log-content.test.tsx": 1899,
|
||||
"src/renderer/src/components/editor/check-details/actions/check-annotation-path.test.ts": 53,
|
||||
"src/renderer/src/components/editor/check-details/reading/check-details-reading-viewport.test.ts": 259,
|
||||
@@ -7181,14 +7177,12 @@
|
||||
"src/renderer/src/components/editor/model-lifetime/retention/closed-editor-view-state-retention.test.ts": 9012,
|
||||
"src/renderer/src/components/editor/closed-unsaved-files-toast.test.ts": 448,
|
||||
"src/renderer/src/components/editor/combined-diff/scroll-viewport/combined-diff-cursor-reveal.test.tsx": 3685,
|
||||
"src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-render.test.tsx": 923,
|
||||
"src/renderer/src/components/editor/combined-diff/browse-files/use-combined-diff-file-tree-resize.test.tsx": 308,
|
||||
"src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-load-scheduler.test.ts": 53,
|
||||
"src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-metadata-retention.test.tsx": 1151,
|
||||
"src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-section-connection.test.ts": 1699,
|
||||
"src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-section-load-state.test.ts": 55,
|
||||
"src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-stale-analysis-work-budget.test.tsx": 1214,
|
||||
"src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-viewport-load-order.test.tsx": 3134,
|
||||
"src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-cache-body-budget.test.ts": 116,
|
||||
"src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-cache.test.ts": 45,
|
||||
"src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-draft-retention.test.ts": 54,
|
||||
@@ -7215,7 +7209,6 @@
|
||||
"src/renderer/src/components/editor/csv/useCsvPendingCell.test.tsx": 714,
|
||||
"src/renderer/src/components/editor/view-mode/custom-editor-routing.test.ts": 2715,
|
||||
"src/renderer/src/components/editor/rich-markdown/details/details-markdown-html.test.ts": 93,
|
||||
"src/renderer/src/components/editor/diff/monaco-view/diff-editor-shift-wheel-scroll.test.ts": 194,
|
||||
"src/renderer/src/components/editor/diff/sections/diff-section-layout.test.ts": 95,
|
||||
"src/renderer/src/components/editor/save/flush/discard-editor-file-changes.save-race.test.ts": 1150,
|
||||
"src/renderer/src/components/editor/rich-markdown/schema/drag-selection-guard-lifetime.test.ts": 626,
|
||||
@@ -7223,7 +7216,6 @@
|
||||
"src/renderer/src/components/editor/autosave/editor-autosave-controller.test.ts": 2324,
|
||||
"src/renderer/src/components/editor/autosave/editor-autosave.test.ts": 529,
|
||||
"src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-adapter.test.ts": 2812,
|
||||
"src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-entry-points.parity.test.ts": 1804,
|
||||
"src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-sharing.test.ts": 5929,
|
||||
"src/renderer/src/components/editor/save/bytes/editor-bytes-documents.test.ts": 690,
|
||||
"src/renderer/src/components/editor/save/commands/editor-child-owner-save.test.tsx": 2480,
|
||||
@@ -7362,7 +7354,6 @@
|
||||
"src/renderer/src/components/editor/rich-markdown/review/rich-markdown-review-text-ranges.test.ts": 53,
|
||||
"src/renderer/src/components/editor/rich-markdown/search/rich-markdown-search-focus.adversarial.test.ts": 301,
|
||||
"src/renderer/src/components/editor/rich-markdown/search/rich-markdown-search-focus.test.ts": 238,
|
||||
"src/renderer/src/components/editor/rich-markdown/document/rich-markdown-serialization-commit.test.ts": 1804,
|
||||
"src/renderer/src/components/editor/rich-markdown/images/rich-markdown-signed-images.test.ts": 2230,
|
||||
"src/renderer/src/components/editor/rich-markdown/document/rich-markdown-source-eol-allocation.test.ts": 73,
|
||||
"src/renderer/src/components/editor/rich-markdown/document/rich-markdown-source-reconcile.test.ts": 2239,
|
||||
@@ -7726,7 +7717,6 @@
|
||||
"src/renderer/src/components/native-chat/native-chat-unkerned-run-decorations.test.ts": 594,
|
||||
"src/renderer/src/components/native-chat/native-chat-visual-markdown-syntax.test.tsx": 2351,
|
||||
"src/renderer/src/components/native-chat/native-chat-visual-read-client.test.ts": 163,
|
||||
"src/renderer/src/components/native-chat/native-chat-web-link-actions.test.ts": 401,
|
||||
"src/renderer/src/components/native-chat/native-chat-working-status-shared-clock.test.tsx": 412,
|
||||
"src/renderer/src/components/native-chat/omp-model-switch-capability.test.ts": 211,
|
||||
"src/renderer/src/components/native-chat/serialized-screen-background-rows.test.ts": 131,
|
||||
@@ -7791,7 +7781,6 @@
|
||||
"src/renderer/src/components/native-chat/use-native-chat-retained-session.test.ts": 229,
|
||||
"src/renderer/src/components/native-chat/use-native-chat-rewind.test.tsx": 686,
|
||||
"src/renderer/src/components/native-chat/use-native-chat-root-input-routing.test.tsx": 613,
|
||||
"src/renderer/src/components/native-chat/use-native-chat-row-typography.test.tsx": 2051,
|
||||
"src/renderer/src/components/native-chat/use-native-chat-send-lifecycle.test.tsx": 281,
|
||||
"src/renderer/src/components/native-chat/use-native-chat-session-options.test.ts": 1068,
|
||||
"src/renderer/src/components/native-chat/use-native-chat-skills.react.test.tsx": 908,
|
||||
@@ -7922,7 +7911,6 @@
|
||||
"src/renderer/src/components/quick-open-selection-owner.react.test.tsx": 2131,
|
||||
"src/renderer/src/components/render-phase-adjustment-discarded-render.test.tsx": 2577,
|
||||
"src/renderer/src/components/repo/repo-icon.test.tsx": 463,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/panel/AiVaultPanel.legacy-filter.test.tsx": 2664,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/scanning/AiVaultScanProgressStrip.test.tsx": 893,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/session-list/AiVaultSessionHistoryDialog.test.tsx": 2796,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/session-list/AiVaultSessionRow.structured-title.test.tsx": 2744,
|
||||
@@ -7962,7 +7950,6 @@
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-original-pane-index.test.ts": 86,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-original-pane.test.ts": 64,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-panel-session-list-request.test.tsx": 3044,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/scope/ai-vault-panel-transient-state.test.tsx": 333,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/scanning/ai-vault-scan-issue-state.test.ts": 222,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/search/ai-vault-search-session.test.ts": 201,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/accounts/ai-vault-session-account-render.test.tsx": 2885,
|
||||
@@ -8007,7 +7994,6 @@
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-drag-scroll-marker.test.tsx": 2937,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-expanded-dirs-refresh.test.ts": 1962,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/mutations/file-explorer-inline-input-ime-enter.test.tsx": 479,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/tree/file-explorer-instant-dir-toggle.test.ts": 836,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/selection/file-explorer-keyboard-navigation.test.ts": 58,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-linked-recovery.test.tsx": 2158,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-linked-watch.test.ts": 1831,
|
||||
@@ -8018,7 +8004,6 @@
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-watch-reconcile.test.ts": 1906,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/watching/file-explorer-watch-refresh-scheduler.test.ts": 79,
|
||||
"src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.test.ts": 70,
|
||||
"src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts": 77,
|
||||
"src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh-scheduler.test.ts": 75,
|
||||
"src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh.test.ts": 553,
|
||||
"src/renderer/src/components/right-sidebar/source-control/sync/git-status-twin-copy.test.ts": 1841,
|
||||
@@ -8037,7 +8022,6 @@
|
||||
"src/renderer/src/components/right-sidebar/source-control/review/source-control-create-pr-intent-flow.test.ts": 71,
|
||||
"src/renderer/src/components/right-sidebar/source-control/review/source-control-dropdown-items.create-pr-intent.test.ts": 324,
|
||||
"src/renderer/src/components/right-sidebar/source-control/panel/source-control-dropdown-items.test.ts": 409,
|
||||
"src/renderer/src/components/right-sidebar/source-control/review/source-control-hosted-review-creation-eligibility-snapshot.test.ts": 67,
|
||||
"src/renderer/src/components/right-sidebar/source-control/review/source-control-manual-review-url.test.ts": 77,
|
||||
"src/renderer/src/components/right-sidebar/source-control/review/source-control-primary-action.create-pr-intent.test.ts": 340,
|
||||
"src/renderer/src/components/right-sidebar/source-control/review/source-control-primary-action.test.ts": 287,
|
||||
@@ -8065,7 +8049,6 @@
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/panel/use-file-explorer-name-filter.runtime-listing.test.tsx": 2153,
|
||||
"src/renderer/src/components/right-sidebar/hosted-review/creation/use-generate-before-create-pull-request-context.test.tsx": 2246,
|
||||
"src/renderer/src/components/right-sidebar/hosted-review/provider-actions/use-hosted-review-actions.test.tsx": 628,
|
||||
"src/renderer/src/components/right-sidebar/ai-vault/scope/use-persisted-ai-vault-view-options.test.tsx": 304,
|
||||
"src/renderer/src/components/right-sidebar/plugin-panels/declarative/use-plugin-declarative-tree.test.ts": 464,
|
||||
"src/renderer/src/components/right-sidebar/plugin-panels/health/use-plugin-panel-draw-report.test.tsx": 204,
|
||||
"src/renderer/src/components/right-sidebar/source-control/sync/use-source-control-branch-compare.test.tsx": 712,
|
||||
@@ -8080,7 +8063,6 @@
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/mutations/useFileExplorerImport.remote.test.tsx": 2054,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/tree/useFileExplorerTree.lifecycle.test.tsx": 1925,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/tree/useFileExplorerTree.paged-dirs.test.tsx": 2484,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/tree/useFileExplorerTree.refresh-projection-churn.test.tsx": 2408,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/tree/useFileExplorerTree.scoped-root.test.tsx": 2131,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerTree.stale-dirs.test.tsx": 1958,
|
||||
"src/renderer/src/components/right-sidebar/file-explorer/watching/useFileExplorerWatch.pending-refresh.test.tsx": 405,
|
||||
@@ -8198,7 +8180,6 @@
|
||||
"src/renderer/src/components/settings/ssh/targets/ssh-target-list-model.test.ts": 56,
|
||||
"src/renderer/src/components/settings/tasks/task-source-setup-state.test.ts": 59,
|
||||
"src/renderer/src/components/integrations/task-trackers/linear-integration-card.test.tsx": 1414,
|
||||
"src/renderer/src/components/settings/accounts/usage/usage-credential-host-sections.test.tsx": 942,
|
||||
"src/renderer/src/components/settings/appearance/themes/use-catalog-app-themes.test.ts": 2159,
|
||||
"src/renderer/src/components/settings/form-controls/use-debounced-settings-text-draft.test.ts": 308,
|
||||
"src/renderer/src/components/settings/repository/execution/use-repository-hook-settings-draft.test.tsx": 586,
|
||||
@@ -8219,7 +8200,6 @@
|
||||
"src/renderer/src/components/sidebar/host-admission/ssh/AddRemoteHostDialog.config-picker.test.tsx": 1178,
|
||||
"src/renderer/src/components/sidebar/project-admission/dialog/AddRepoDialogChrome.test.tsx": 714,
|
||||
"src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx": 822,
|
||||
"src/renderer/src/components/sidebar/host-admission/wsl/AddWslHostFormPanel.test.tsx": 291,
|
||||
"src/renderer/src/components/sidebar/workspace-card/identity/AutoRenameFailedDialog.test.tsx": 2254,
|
||||
"src/renderer/src/components/sidebar/CommentMarkdown.code-block-renderer.test.tsx": 2109,
|
||||
"src/renderer/src/components/sidebar/CommentMarkdown.github-attachment-image.test.tsx": 2122,
|
||||
@@ -8236,7 +8216,6 @@
|
||||
"src/renderer/src/components/sidebar/CommentMermaidBlock.system-theme.test.tsx": 389,
|
||||
"src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteNestedWorktreesDialog.test.tsx": 1807,
|
||||
"src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteWorktreeDialog.test.tsx": 1290,
|
||||
"src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteWorktreeDialog.unsaved-edits.test.tsx": 1150,
|
||||
"src/renderer/src/components/sidebar/workspace-actions/deletion/DeleteWorktreeTargetPreview.test.tsx": 2363,
|
||||
"src/renderer/src/components/sidebar/HostRemoveDialog.test.tsx": 6650,
|
||||
"src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.reminder-toast.test.tsx": 2248,
|
||||
@@ -8254,7 +8233,6 @@
|
||||
"src/renderer/src/components/sidebar/sidebar-feedback/SidebarFeedbackDialog.test.tsx": 2529,
|
||||
"src/renderer/src/components/sidebar/SidebarHeader.test.tsx": 581,
|
||||
"src/renderer/src/components/sidebar/SidebarNav.test.tsx": 1507,
|
||||
"src/renderer/src/components/sidebar/worktree-list/controls/SidebarRepositoryFilterSection.test.tsx": 749,
|
||||
"src/renderer/src/components/sidebar/SidebarSettingsHelpMenu.test.tsx": 904,
|
||||
"src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.test.tsx": 320,
|
||||
"src/renderer/src/components/sidebar/workspace-card/review/WorkspaceAttachmentOrigins.test.tsx": 2145,
|
||||
@@ -8265,7 +8243,6 @@
|
||||
"src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCard.affiliate-list-mode.test.tsx": 2513,
|
||||
"src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCard.compact-hover.test.tsx": 3316,
|
||||
"src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCard.host-badge-toggle.test.tsx": 2689,
|
||||
"src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCard.hosted-review-refresh.test.tsx": 2275,
|
||||
"src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCard.pr-display.test.tsx": 2817,
|
||||
"src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCard.quick-actions.test.tsx": 3258,
|
||||
"src/renderer/src/components/sidebar/workspace-card/surface/WorktreeCard.single-reference-details.test.tsx": 2032,
|
||||
@@ -8309,7 +8286,6 @@
|
||||
"src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-path-status.test.tsx": 2113,
|
||||
"src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit-host-platform.test.ts": 2264,
|
||||
"src/renderer/src/components/sidebar/workspace-creation/folder/folder-workspace-composer-submit.test.ts": 2665,
|
||||
"src/renderer/src/components/sidebar/worktree-list/listing/hide-sleeping-transient-pty-gap.test.ts": 2211,
|
||||
"src/renderer/src/components/sidebar/worktree-list/drag/host-header-drag.test.tsx": 281,
|
||||
"src/renderer/src/components/sidebar/worktree-list/grouping/host-section-project-headers.test.ts": 308,
|
||||
"src/renderer/src/components/sidebar/worktree-list/grouping/host-section-reveal.test.tsx": 2294,
|
||||
@@ -8321,7 +8297,6 @@
|
||||
"src/renderer/src/components/sidebar/worktree-list/grouping/pinned-section-worktrees.test.ts": 446,
|
||||
"src/renderer/src/components/sidebar/workspace-actions/deletion/preserved-branch-batch-toast.test.tsx": 627,
|
||||
"src/renderer/src/components/sidebar/project-admission/completion/project-added-default-checkout.test.ts": 128,
|
||||
"src/renderer/src/components/sidebar/worktree-list/drag/project-group-header-drag-start.test.ts": 205,
|
||||
"src/renderer/src/components/sidebar/worktree-list/drag/project-group-header-drop.test.ts": 198,
|
||||
"src/renderer/src/components/sidebar/worktree-list/drag/project-header-drop.test.ts": 206,
|
||||
"src/renderer/src/components/sidebar/project-move-pause-follower.test.ts": 938,
|
||||
@@ -8345,13 +8320,11 @@
|
||||
"src/renderer/src/components/sidebar/worktree-list/navigation/use-workspace-reveal-body-redirect.test.tsx": 215,
|
||||
"src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.test.tsx": 565,
|
||||
"src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows-subscriptions.test.tsx": 3635,
|
||||
"src/renderer/src/components/sidebar/workspace-card/details/use-worktree-card-secondary-details.store-subscriptions.test.tsx": 2446,
|
||||
"src/renderer/src/components/sidebar/host-admission/wsl/use-wsl-distro-list.test.ts": 542,
|
||||
"src/renderer/src/components/sidebar/useRenderedSetupScriptPromptState.test.ts": 623,
|
||||
"src/renderer/src/components/sidebar/useSetupScriptPromptRevalidation.test.tsx": 2035,
|
||||
"src/renderer/src/components/sidebar/workspace-board/surface/useWorkspaceBoardPanel.test.tsx": 284,
|
||||
"src/renderer/src/components/sidebar/workspace-card/activity/useWorktreeAgentRows.test.ts": 450,
|
||||
"src/renderer/src/components/sidebar/worktree-list/listing/visible-worktree-indexes.test.ts": 259,
|
||||
"src/renderer/src/components/sidebar/worktree-list/listing/visible-worktrees.test.ts": 314,
|
||||
"src/renderer/src/components/sidebar/workspace-card/review/workspace-attachment-source-result.test.ts": 1897,
|
||||
"src/renderer/src/components/sidebar/workspace-board/projection/workspace-board-task-status-sync.test.ts": 378,
|
||||
@@ -8758,7 +8731,6 @@
|
||||
"src/renderer/src/components/terminal-pane/newer-daemon-hold-banner.test.tsx": 477,
|
||||
"src/renderer/src/components/terminal-pane/osc52-clipboard-default-on-notice.test.ts": 381,
|
||||
"src/renderer/src/components/terminal-pane/override-affected-panes.test.ts": 44,
|
||||
"src/renderer/src/components/terminal-pane/paired-parking-unverifiable-host.test.ts": 176,
|
||||
"src/renderer/src/components/terminal-pane/paired-reconnect-multi-pane-materialization.test.ts": 1040,
|
||||
"src/renderer/src/components/terminal-pane/pane-delayed-agent-startup.test.ts": 285,
|
||||
"src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts": 486,
|
||||
@@ -8891,7 +8863,6 @@
|
||||
"src/renderer/src/components/terminal-pane/remote-runtime-pty-latched-pane-retention.test.ts": 5267,
|
||||
"src/renderer/src/components/terminal-pane/remote-runtime-pty-query-reply-immediate.test.ts": 1556,
|
||||
"src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts": 85,
|
||||
"src/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-source-grid.test.ts": 924,
|
||||
"src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-activation-inventory-fallback.test.ts": 1311,
|
||||
"src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-attach-subscription.test.ts": 2346,
|
||||
"src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-create-handoff.test.ts": 14353,
|
||||
@@ -9309,7 +9280,6 @@
|
||||
"src/renderer/src/hooks/use-os-file-drop-owner.test.tsx": 401,
|
||||
"src/renderer/src/hooks/use-terminal-quick-command-hosts.test.ts": 476,
|
||||
"src/renderer/src/hooks/use-window-stream-visibility.test.ts": 289,
|
||||
"src/renderer/src/hooks/useActiveProjectSkillRuntime.test.tsx": 2045,
|
||||
"src/renderer/src/hooks/useAutomationDispatchEvents.test.ts": 788,
|
||||
"src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts": 95,
|
||||
"src/renderer/src/hooks/useComposerState.integration.test.ts": 4419,
|
||||
@@ -9817,7 +9787,6 @@
|
||||
"src/renderer/src/runtime/remote-server-update-coordinator.test.ts": 322,
|
||||
"src/renderer/src/runtime/restored-client-hosted-browser-host-attach.test.ts": 43,
|
||||
"src/renderer/src/runtime/restored-client-hosted-browser-host-restart-attach.test.ts": 474,
|
||||
"src/renderer/src/runtime/restored-editor-move-reload.test.ts": 2154,
|
||||
"src/renderer/src/runtime/runtime-client-events.test.ts": 64,
|
||||
"src/renderer/src/runtime/runtime-directory-page-client.test.ts": 268,
|
||||
"src/renderer/src/runtime/runtime-environment-pairing-refresh.test.ts": 109,
|
||||
@@ -9883,7 +9852,6 @@
|
||||
"src/renderer/src/runtime/web-session-close-replay.test.ts": 1119,
|
||||
"src/renderer/src/runtime/web-session-open-files-batch-equivalence.test.ts": 1478,
|
||||
"src/renderer/src/runtime/web-session-restored-placeholder-identity.test.ts": 985,
|
||||
"src/renderer/src/runtime/web-session-split-pane-retirement-fences.test.ts": 1019,
|
||||
"src/renderer/src/runtime/web-session-tabs-agent-completion-notifications.test.ts": 1953,
|
||||
"src/renderer/src/runtime/web-session-tabs-late-merged-predecessor-lockout.test.ts": 779,
|
||||
"src/renderer/src/runtime/web-session-tabs-removed-frame-retires-live-publisher.test.ts": 854,
|
||||
@@ -10085,7 +10053,6 @@
|
||||
"src/renderer/src/store/slices/jira-status-filter-cache.test.ts": 1770,
|
||||
"src/renderer/src/store/slices/jira-web-client-status.test.ts": 1901,
|
||||
"src/renderer/src/store/slices/jira.test.ts": 312,
|
||||
"src/renderer/src/store/slices/layout-owner-written-session-hydration.test.ts": 1780,
|
||||
"src/renderer/src/store/slices/linear-invalidation.test.ts": 117,
|
||||
"src/renderer/src/store/slices/local-detected-agent-state.test.ts": 596,
|
||||
"src/renderer/src/store/slices/native-chat-launch-draft-teardown.test.ts": 1854,
|
||||
@@ -10252,7 +10219,6 @@
|
||||
"src/renderer/src/store/slices/worktrees/teardown/remove-worktree-shared-records.test.ts": 2086,
|
||||
"src/renderer/src/store/slices/worktrees/teardown/removed-workspace-unsaved-files.test.ts": 2481,
|
||||
"src/renderer/src/store/slices/worktrees/teardown/worktree-delete-state.test.ts": 1160,
|
||||
"src/renderer/src/store/slices/wsl-moved-project-chat-hydration.test.ts": 1658,
|
||||
"src/renderer/src/store/slices/wsl-moved-project-chat-purge.test.ts": 1222,
|
||||
"src/renderer/src/store/store-identity-churn-probe.test.ts": 67,
|
||||
"src/renderer/src/store/terminals/legacy-relay-bridged-tab-close.test.ts": 310,
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AppShortcutState, ShortcutDispatchInput } from './app-command-handlers'
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const target: { groupKey: string | null } = { groupKey: 'lineage:parent' }
|
||||
return {
|
||||
target,
|
||||
floatingFocused: false,
|
||||
visibleModal: false,
|
||||
requestScrollAnchor: vi.fn(),
|
||||
notifyTerminalCapture: vi.fn(),
|
||||
store: {
|
||||
activeModal: 'none',
|
||||
collapsedGroups: new Set<string>(),
|
||||
setSidebarOpen: vi.fn(),
|
||||
toggleCollapsedGroup: vi.fn()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../store', () => ({
|
||||
useAppStore: Object.assign(vi.fn(), { getState: () => mocks.store })
|
||||
}))
|
||||
|
||||
vi.mock('../components/sidebar/workspace-card/identity/child-workspaces-toggle-target', () => ({
|
||||
getRenderedLineageChipKeys: () => new Set<string>(),
|
||||
resolveChildWorkspacesToggleGroupKey: () => mocks.target.groupKey
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/requestVirtualizedScrollAnchorRecord', () => ({
|
||||
requestVirtualizedScrollAnchorRecord: mocks.requestScrollAnchor
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/floating-workspace-terminal-actions', () => ({
|
||||
isFloatingWorkspacePanelFocused: () => mocks.floatingFocused
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/visible-overlay', () => ({
|
||||
hasVisibleOverlay: () => mocks.visibleModal
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/terminal-shortcut-capture-notification', () => ({
|
||||
showTerminalShortcutCaptureNotification: mocks.notifyTerminalCapture
|
||||
}))
|
||||
|
||||
import { createAppCommandHandlers } from './app-command-handlers'
|
||||
|
||||
function shortcutState(): AppShortcutState {
|
||||
return {
|
||||
activeView: 'terminal',
|
||||
activeWorktreeId: 'parent',
|
||||
actions: {
|
||||
toggleSidebar: vi.fn(),
|
||||
toggleRightSidebar: vi.fn(),
|
||||
setRightSidebarOpen: vi.fn(),
|
||||
setRightSidebarTab: vi.fn(),
|
||||
showRightSidebarFiles: vi.fn(),
|
||||
showRightSidebarSearch: vi.fn(),
|
||||
openDiffNotesSendMenuForActiveWorktree: vi.fn()
|
||||
},
|
||||
creationLayoutActive: false,
|
||||
floatingTerminalEnabled: false,
|
||||
floatingTerminalOpen: false,
|
||||
floatingVisibleTabCount: 0,
|
||||
keybindings: {},
|
||||
openFloatingWorkspaceMaximized: vi.fn(),
|
||||
pluginCommands: [],
|
||||
setFloatingTerminalOpen: vi.fn(),
|
||||
terminalShortcutPolicy: 'orca-first',
|
||||
workspaceChromeActive: true
|
||||
}
|
||||
}
|
||||
|
||||
function shortcutInput(): ShortcutDispatchInput {
|
||||
return { target: null, defaultPrevented: false, preventDefault: vi.fn() }
|
||||
}
|
||||
|
||||
function runToggle(input: ShortcutDispatchInput): boolean | undefined {
|
||||
return createAppCommandHandlers(shortcutState(), input).get('sidebar.childWorkspaces.toggle')?.()
|
||||
}
|
||||
|
||||
describe('child workspaces toggle app command', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.target.groupKey = 'lineage:parent'
|
||||
mocks.floatingFocused = false
|
||||
mocks.visibleModal = false
|
||||
mocks.store.activeModal = 'none'
|
||||
mocks.store.collapsedGroups = new Set()
|
||||
})
|
||||
|
||||
it('hides the target’s children without forcing the sidebar open', () => {
|
||||
const input = shortcutInput()
|
||||
|
||||
expect(runToggle(input)).toBe(true)
|
||||
expect(input.preventDefault).toHaveBeenCalledOnce()
|
||||
expect(mocks.requestScrollAnchor).toHaveBeenCalledWith('[data-worktree-sidebar]')
|
||||
expect(mocks.store.toggleCollapsedGroup).toHaveBeenCalledWith('lineage:parent')
|
||||
expect(mocks.store.setSidebarOpen).not.toHaveBeenCalled()
|
||||
expect(mocks.requestScrollAnchor.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
mocks.store.toggleCollapsedGroup.mock.invocationCallOrder[0] ?? 0
|
||||
)
|
||||
})
|
||||
|
||||
it('opens the sidebar when showing hidden children', () => {
|
||||
mocks.store.collapsedGroups = new Set(['lineage:parent'])
|
||||
|
||||
expect(runToggle(shortcutInput())).toBe(true)
|
||||
expect(mocks.store.toggleCollapsedGroup).toHaveBeenCalledWith('lineage:parent')
|
||||
expect(mocks.store.setSidebarOpen).toHaveBeenCalledWith(true)
|
||||
})
|
||||
|
||||
it('lets the chord through when the target is in no lineage', () => {
|
||||
mocks.target.groupKey = null
|
||||
const input = shortcutInput()
|
||||
|
||||
expect(runToggle(input)).toBe(false)
|
||||
expect(input.preventDefault).not.toHaveBeenCalled()
|
||||
expect(mocks.store.toggleCollapsedGroup).not.toHaveBeenCalled()
|
||||
expect(mocks.requestScrollAnchor).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('lets a modal keep its keyboard input', () => {
|
||||
mocks.store.activeModal = 'delete-worktree'
|
||||
const input = shortcutInput()
|
||||
|
||||
expect(runToggle(input)).toBe(false)
|
||||
expect(input.preventDefault).not.toHaveBeenCalled()
|
||||
expect(mocks.store.toggleCollapsedGroup).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('lets the focused floating workspace keep its keyboard input', () => {
|
||||
mocks.floatingFocused = true
|
||||
const input = shortcutInput()
|
||||
|
||||
expect(runToggle(input)).toBe(false)
|
||||
expect(input.preventDefault).not.toHaveBeenCalled()
|
||||
expect(mocks.store.toggleCollapsedGroup).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves locally controlled modal input and persistence untouched', () => {
|
||||
mocks.visibleModal = true
|
||||
const input = shortcutInput()
|
||||
|
||||
expect(runToggle(input)).toBe(false)
|
||||
expect(input.preventDefault).not.toHaveBeenCalled()
|
||||
expect(mocks.store.toggleCollapsedGroup).not.toHaveBeenCalled()
|
||||
expect(mocks.requestScrollAnchor).not.toHaveBeenCalled()
|
||||
expect(mocks.store.setSidebarOpen).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports a claimed terminal shortcut through the existing notification policy', () => {
|
||||
const input = shortcutInput()
|
||||
expect(
|
||||
createAppCommandHandlers(shortcutState(), input, 'terminal').get(
|
||||
'sidebar.childWorkspaces.toggle'
|
||||
)?.()
|
||||
).toBe(true)
|
||||
expect(mocks.notifyTerminalCapture).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ actionId: 'sidebar.childWorkspaces.toggle' })
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -50,53 +50,6 @@ beforeEach(() => {
|
||||
})
|
||||
afterEach(cleanup)
|
||||
|
||||
it('selects a new sole result after typing and opens its suffix location with Enter', async () => {
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<QuickOpen />
|
||||
</TooltipProvider>
|
||||
)
|
||||
const input = screen.getByRole('combobox')
|
||||
fireEvent.change(input, { target: { value: '.env api' } })
|
||||
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(1))
|
||||
expect(screen.getByRole('option').getAttribute('aria-selected')).toBe('true')
|
||||
fireEvent.change(input, { target: { value: 'product-detail:2:3' } })
|
||||
await waitFor(() => expect(screen.getByRole('option').textContent).toContain('product_detail.ts'))
|
||||
expect(screen.getByRole('option').getAttribute('aria-selected')).toBe('true')
|
||||
fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' })
|
||||
await waitFor(() => expect(mocks.open).toHaveBeenCalledOnce())
|
||||
expect(mocks.open).toHaveBeenCalledWith(
|
||||
'src/product_detail.ts',
|
||||
'workspace',
|
||||
'/workspace',
|
||||
{ pathQuery: 'product-detail', line: 2, column: 3 },
|
||||
'product-detail:2:3',
|
||||
expect.any(Function)
|
||||
)
|
||||
expect(mocks.close).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('retains the dialog on failure and recovers after changing the query', async () => {
|
||||
mocks.open.mockRejectedValueOnce(new Error('File no longer exists'))
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<QuickOpen />
|
||||
</TooltipProvider>
|
||||
)
|
||||
const input = screen.getByRole('combobox')
|
||||
fireEvent.change(input, { target: { value: 'product-detail' } })
|
||||
await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(1))
|
||||
fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' })
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('alert').textContent).toContain('File no longer exists')
|
||||
)
|
||||
expect(mocks.close).not.toHaveBeenCalled()
|
||||
fireEvent.change(input, { target: { value: '.env api' } })
|
||||
await waitFor(() => expect(screen.queryByRole('alert')).toBeNull())
|
||||
fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' })
|
||||
await waitFor(() => expect(mocks.close).toHaveBeenCalledOnce())
|
||||
})
|
||||
|
||||
it.each(['settings', 'workspace-change', 'query-change'])(
|
||||
'does not close or focus after %s replaces a pending selection',
|
||||
async (change) => {
|
||||
@@ -136,13 +89,3 @@ it.each(['settings', 'workspace-change', 'query-change'])(
|
||||
expect(mocks.close).not.toHaveBeenCalled()
|
||||
}
|
||||
)
|
||||
|
||||
it('renders the separator match beneath a same-named ancestor', async () => {
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<QuickOpen />
|
||||
</TooltipProvider>
|
||||
)
|
||||
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'user-profile' } })
|
||||
await waitFor(() => expect(screen.getByRole('option').textContent).toContain('index.tsx'))
|
||||
})
|
||||
|
||||
@@ -77,20 +77,6 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('AgentDashboardDrawer', () => {
|
||||
it('leaves Escape to an open terminal panel before dismissing the drawer', () => {
|
||||
mocks.blockingOverlay = true
|
||||
const view = render(<AgentDashboardDrawer statusBarVisible />)
|
||||
|
||||
act(() => useAppStore.setState({ agentDashboardDrawerOpen: true }))
|
||||
fireEvent.keyDown(document.body, { key: 'Escape' })
|
||||
expect(useAppStore.getState().agentDashboardDrawerOpen).toBe(true)
|
||||
|
||||
mocks.blockingOverlay = false
|
||||
view.rerender(<AgentDashboardDrawer statusBarVisible />)
|
||||
fireEvent.keyDown(document.body, { key: 'Escape' })
|
||||
expect(useAppStore.getState().agentDashboardDrawerOpen).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the dismissal Escape from a focused terminal but not from other fields', () => {
|
||||
const terminalInput = document.createElement('textarea')
|
||||
terminalInput.className = 'xterm-helper-textarea'
|
||||
@@ -112,40 +98,4 @@ describe('AgentDashboardDrawer', () => {
|
||||
expect(useAppStore.getState().agentDashboardDrawerOpen).toBe(false)
|
||||
expect(fieldKeyDown).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
type RevealAgent = (args: {
|
||||
repoId: string
|
||||
worktreeId: string
|
||||
executionHostId?: string
|
||||
tabId: string
|
||||
leafId: string | null
|
||||
}) => void
|
||||
|
||||
function revealFromBoard(executionHostId: string): void {
|
||||
render(<AgentDashboardDrawer statusBarVisible />)
|
||||
act(() => useAppStore.setState({ agentDashboardDrawerOpen: true }))
|
||||
const onRevealAgent = mocks.boardProps?.onRevealAgent
|
||||
expect(onRevealAgent).toBeTypeOf('function')
|
||||
act(() => {
|
||||
;(onRevealAgent as RevealAgent)({
|
||||
repoId: 'repo-1',
|
||||
worktreeId: 'shared-worktree',
|
||||
executionHostId,
|
||||
tabId: 'tab-1',
|
||||
leafId: 'leaf-1'
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
it('activates a parked SSH workspace before reaching for its pane', () => {
|
||||
revealFromBoard('ssh:devbox')
|
||||
|
||||
expect(mocks.activateAndRevealWorkspace).toHaveBeenCalledWith('shared-worktree', {
|
||||
executionHostId: 'ssh:devbox'
|
||||
})
|
||||
// Ordering is the fix: a parked remote tab only exists after activation revives it.
|
||||
expect(mocks.activateAndRevealWorkspace.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
mocks.activateTabAndFocusPane.mock.invocationCallOrder[0] as number
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
-168
@@ -1,168 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import React, { act, useCallback, useMemo, useState, type ReactElement } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { GitBranchChangeEntry } from '../../../../../../shared/git/diff/git-diff-compare-types'
|
||||
import type { CombinedDiffFileTreeRow as CombinedDiffFileTreeRowComponent } from './combined-diff-file-tree-row'
|
||||
|
||||
const rowRenders = vi.hoisted(() => ({ count: 0 }))
|
||||
const mountedRows = vi.hoisted(() => ({ count: 0 }))
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: (selector: (state: Record<string, unknown>) => unknown) =>
|
||||
selector({ combinedDiffFileTreeWidth: 420, setCombinedDiffFileTreeWidth: () => {} })
|
||||
}))
|
||||
|
||||
vi.mock('./combined-diff-file-tree-row', async (importOriginal) => {
|
||||
const actual = (await importOriginal()) as {
|
||||
CombinedDiffFileTreeRow: typeof CombinedDiffFileTreeRowComponent
|
||||
}
|
||||
const react = await import('react')
|
||||
const Row = actual.CombinedDiffFileTreeRow
|
||||
// Use React’s default memo comparison so counts reflect the real row’s render decisions.
|
||||
const CountingRow = react.memo((props: React.ComponentProps<typeof Row>) => {
|
||||
rowRenders.count += 1
|
||||
react.useEffect(() => {
|
||||
mountedRows.count += 1
|
||||
return () => {
|
||||
mountedRows.count -= 1
|
||||
}
|
||||
}, [])
|
||||
return react.createElement(Row, props)
|
||||
})
|
||||
return { ...actual, CombinedDiffFileTreeRow: CountingRow }
|
||||
})
|
||||
|
||||
const { CombinedDiffFileTree } = await import('./combined-diff-file-tree')
|
||||
const { createCombinedDiffSectionIndexMap } =
|
||||
await import('../resolve-changes/combined-diff-section-identity')
|
||||
const { useCombinedDiffSectionIndexMap } =
|
||||
await import('../resolve-changes/use-combined-diff-section-index-map')
|
||||
const { getCombinedDiffBranchEntriesInTreeOrder } = await import('./combined-diff-file-tree-filter')
|
||||
|
||||
const EMPTY_VIEWED_KEYS: ReadonlySet<string> = new Set()
|
||||
|
||||
class NoopResizeObserver implements ResizeObserver {
|
||||
observe(): void {}
|
||||
unobserve(): void {}
|
||||
disconnect(): void {}
|
||||
}
|
||||
|
||||
let host: HTMLDivElement
|
||||
let root: Root
|
||||
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
rowRenders.count = 0
|
||||
mountedRows.count = 0
|
||||
host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
root = createRoot(host)
|
||||
vi.stubGlobal('ResizeObserver', NoopResizeObserver)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
host.remove()
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
type TestSection = { key: string; loading: boolean }
|
||||
|
||||
function buildEntries(fileCount: number, directoryCount: number): GitBranchChangeEntry[] {
|
||||
const raw: GitBranchChangeEntry[] = Array.from({ length: fileCount }, (_, index) => ({
|
||||
path: `src/dir${String(index % directoryCount).padStart(2, '0')}/file-${String(index).padStart(4, '0')}.ts`,
|
||||
status: 'modified'
|
||||
}))
|
||||
return getCombinedDiffBranchEntriesInTreeOrder('commit', raw)
|
||||
}
|
||||
|
||||
function buildSections(entries: readonly GitBranchChangeEntry[]): TestSection[] {
|
||||
return entries.map((entry) => ({ key: `combined-commit:${entry.path}`, loading: true }))
|
||||
}
|
||||
|
||||
let loadSectionAt: (index: number) => void = () => {}
|
||||
|
||||
/** Match viewer loads: replace sections and regenerate navigation callbacks from the section index map. */
|
||||
function TreeHarness({
|
||||
entries,
|
||||
initialSections,
|
||||
stableSectionIndexMap
|
||||
}: {
|
||||
entries: readonly GitBranchChangeEntry[]
|
||||
initialSections: TestSection[]
|
||||
stableSectionIndexMap: boolean
|
||||
}): ReactElement {
|
||||
const [sections, setSections] = useState(initialSections)
|
||||
loadSectionAt = (index) => {
|
||||
setSections((prev) =>
|
||||
prev.map((section, sectionIndex) =>
|
||||
sectionIndex === index ? { ...section, loading: false } : section
|
||||
)
|
||||
)
|
||||
}
|
||||
const rebuiltMap = useMemo(() => createCombinedDiffSectionIndexMap(sections), [sections])
|
||||
const cachedMap = useCombinedDiffSectionIndexMap({ entrySignature: 'pr-1', sections })
|
||||
const sectionIndexByKey = stableSectionIndexMap ? cachedMap : rebuiltMap
|
||||
const onNavigate = useCallback(() => {
|
||||
void sectionIndexByKey
|
||||
}, [sectionIndexByKey])
|
||||
|
||||
return (
|
||||
<CombinedDiffFileTree
|
||||
mode="commit"
|
||||
worktreePath="/repo"
|
||||
entries={entries}
|
||||
sectionIndexByKey={sectionIndexByKey}
|
||||
activeSectionKey={null}
|
||||
viewedSectionKeys={EMPTY_VIEWED_KEYS}
|
||||
collapsed={false}
|
||||
onCollapsedChange={() => {}}
|
||||
onNavigate={onNavigate}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function mountedRowCount(): number {
|
||||
return mountedRows.count
|
||||
}
|
||||
|
||||
function renderHarness(
|
||||
entries: readonly GitBranchChangeEntry[],
|
||||
sections: TestSection[],
|
||||
stableSectionIndexMap: boolean
|
||||
): void {
|
||||
act(() => {
|
||||
root.render(
|
||||
<TreeHarness
|
||||
entries={entries}
|
||||
initialSections={sections}
|
||||
stableSectionIndexMap={stableSectionIndexMap}
|
||||
/>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/** Commit section loads separately, matching lazy scroll-time delivery. */
|
||||
function runScrollPass(loadCount: number): number {
|
||||
rowRenders.count = 0
|
||||
for (let index = 0; index < loadCount; index += 1) {
|
||||
act(() => loadSectionAt(index))
|
||||
}
|
||||
return rowRenders.count
|
||||
}
|
||||
|
||||
describe('combined diff file tree re-renders on section loads', () => {
|
||||
const SMALL_FILE_COUNT = 30
|
||||
const SCROLL_PASS_LOADS = 10
|
||||
|
||||
it('re-renders no rows per section load when the section index map keeps its identity', () => {
|
||||
const entries = buildEntries(SMALL_FILE_COUNT, 3)
|
||||
renderHarness(entries, buildSections(entries), true)
|
||||
expect(mountedRowCount()).toBeGreaterThan(SMALL_FILE_COUNT)
|
||||
|
||||
expect(runScrollPass(SCROLL_PASS_LOADS)).toBe(0)
|
||||
})
|
||||
})
|
||||
-162
@@ -1,162 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { useEffect, useLayoutEffect, useMemo, useState } from 'react'
|
||||
import { act, cleanup, renderHook } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { createTestStore, makeWorktree } from '@/store/slices/store-test-helpers'
|
||||
import type { OpenFile } from '@/store/slices/editor'
|
||||
import type { GitDiffResult } from '../../../../../../shared/git/diff/git-diff-compare-types'
|
||||
import type { DiffSection } from '../../diff/sections/diff-section-types'
|
||||
import type { CombinedDiffEntrySet } from '../resolve-changes/use-combined-diff-entry-set'
|
||||
import { useCombinedDiffSectionLoadRegistry } from './combined-diff-section-load-registry'
|
||||
import { useCombinedDiffSectionLoader } from './use-combined-diff-section-loader'
|
||||
import { useCombinedDiffSectionRetry } from './use-combined-diff-section-retry'
|
||||
|
||||
const transport = vi.hoisted(() => ({ diff: vi.fn(), getState: vi.fn() }))
|
||||
vi.mock('@/runtime/runtime-git-diff-client', () => ({
|
||||
getRuntimeGitDiff: transport.diff,
|
||||
getRuntimeGitBranchDiff: transport.diff,
|
||||
getRuntimeGitCommitDiff: transport.diff
|
||||
}))
|
||||
vi.mock('@/store', () => ({ useAppStore: { getState: transport.getState } }))
|
||||
|
||||
const file: OpenFile = {
|
||||
id: 'review',
|
||||
filePath: '/repo',
|
||||
relativePath: 'review',
|
||||
worktreeId: 'workspace',
|
||||
language: 'plaintext',
|
||||
isDirty: false,
|
||||
mode: 'diff',
|
||||
diffSource: 'combined-uncommitted'
|
||||
}
|
||||
|
||||
function useReview({ count, rendered }: { count: number; rendered: number[] }) {
|
||||
const entrySet = useMemo<CombinedDiffEntrySet>(() => {
|
||||
const entries = Array.from({ length: count }, (_, index) => ({
|
||||
path: `${index}.ts`,
|
||||
status: 'modified' as const,
|
||||
area: 'unstaged' as const
|
||||
}))
|
||||
return {
|
||||
entries,
|
||||
uncommittedEntries: entries,
|
||||
allEntries: entries,
|
||||
commitEntries: [],
|
||||
renderableBranchEntries: [],
|
||||
branchCompare: null,
|
||||
commitCompare: null,
|
||||
entrySignature: `${count}`,
|
||||
hasUncommittedEntriesSnapshot: true,
|
||||
shouldAutoReloadFromGitStatus: false,
|
||||
isAllMode: false,
|
||||
isBranchMode: false,
|
||||
isCommitMode: false,
|
||||
treeMode: 'uncommitted'
|
||||
}
|
||||
}, [count])
|
||||
const [sections, setSections] = useState<DiffSection[]>(() =>
|
||||
entrySet.entries.map((entry) => ({
|
||||
...entry,
|
||||
key: entry.path,
|
||||
originalContent: '',
|
||||
modifiedContent: '',
|
||||
collapsed: false,
|
||||
loading: true,
|
||||
dirty: false,
|
||||
diffResult: null,
|
||||
largeDiffRenderLimit: null
|
||||
}))
|
||||
)
|
||||
const [, setSectionHeights] = useState<Record<number, number>>({})
|
||||
const registry = useCombinedDiffSectionLoadRegistry(sections)
|
||||
const loader = useCombinedDiffSectionLoader({
|
||||
entrySet,
|
||||
file,
|
||||
generation: 0,
|
||||
registry,
|
||||
sectionCount: count,
|
||||
setSectionHeights,
|
||||
setSections
|
||||
})
|
||||
const retry = useCombinedDiffSectionRetry({
|
||||
invalidateViewStateCache: () => {},
|
||||
registry,
|
||||
setSectionHeights,
|
||||
setSections
|
||||
})
|
||||
useLayoutEffect(() => {
|
||||
registry.renderedIndicesRef.current = new Set(rendered)
|
||||
}, [registry.renderedIndicesRef, rendered])
|
||||
const { loadSection } = loader
|
||||
useEffect(() => {
|
||||
for (const index of rendered) {
|
||||
loadSection(index)
|
||||
}
|
||||
}, [loadSection, rendered])
|
||||
return { retry }
|
||||
}
|
||||
|
||||
function captureReads() {
|
||||
const started: string[] = []
|
||||
const pending = new Map<string, () => void>()
|
||||
transport.diff.mockImplementation((_scope: unknown, request: { filePath: string }) => {
|
||||
started.push(request.filePath)
|
||||
return new Promise<GitDiffResult>((resolve) => {
|
||||
pending.set(request.filePath, () => {
|
||||
pending.delete(request.filePath)
|
||||
resolve({
|
||||
kind: 'text',
|
||||
originalContent: `before ${request.filePath}`,
|
||||
modifiedContent: `after ${request.filePath}`,
|
||||
originalIsBinary: false,
|
||||
modifiedIsBinary: false
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
const settle = async (path: string): Promise<void> => {
|
||||
expect(pending.has(path)).toBe(true)
|
||||
await act(async () => pending.get(path)?.())
|
||||
}
|
||||
return { started, settle }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
const store = createTestStore()
|
||||
store.setState({
|
||||
openFiles: [file],
|
||||
worktreesByRepo: {
|
||||
repo: [makeWorktree({ id: file.worktreeId, repoId: 'repo', path: '/repo', hostId: 'local' })]
|
||||
}
|
||||
})
|
||||
transport.getState.mockImplementation(store.getState)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.useRealTimers()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('drops an automatic reload that leaves the viewport while queued, then refreshes on return', async () => {
|
||||
vi.useFakeTimers()
|
||||
const reads = captureReads()
|
||||
const hook = renderHook(useReview, { initialProps: { count: 8, rendered: [6] } })
|
||||
await act(async () => {})
|
||||
await reads.settle('6.ts')
|
||||
expect(reads.started).toEqual(['6.ts', '0.ts'])
|
||||
act(() => hook.result.current.retry.requestSectionReload(6))
|
||||
await act(async () => vi.advanceTimersByTime(300))
|
||||
hook.rerender({ count: 8, rendered: [7] })
|
||||
await reads.settle('0.ts')
|
||||
await reads.settle('7.ts')
|
||||
for (let index = 1; index < 6; index += 1) {
|
||||
await reads.settle(`${index}.ts`)
|
||||
}
|
||||
expect(reads.started.filter((path) => path === '6.ts')).toHaveLength(1)
|
||||
hook.rerender({ count: 8, rendered: [6] })
|
||||
await act(async () => {})
|
||||
await reads.settle('6.ts')
|
||||
expect(reads.started.filter((path) => path === '6.ts')).toHaveLength(2)
|
||||
})
|
||||
-152
@@ -1,152 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { installDiffEditorShiftWheelScroll } from './diff-editor-shift-wheel-scroll'
|
||||
|
||||
type PaneFixture = {
|
||||
container: HTMLDivElement
|
||||
input: HTMLDivElement
|
||||
setScrollLeft: ReturnType<typeof vi.fn<(value: number) => void>>
|
||||
getScrollLeft: () => number
|
||||
getContainerDomNode: () => HTMLElement
|
||||
getScrollWidth: () => number
|
||||
getLayoutInfo: () => { contentWidth: number }
|
||||
}
|
||||
|
||||
function createPaneFixture(initialScrollLeft = 10, scrollWidth = 1000): PaneFixture {
|
||||
const container = document.createElement('div')
|
||||
const input = document.createElement('div')
|
||||
let scrollLeft = initialScrollLeft
|
||||
const setScrollLeft = vi.fn((value: number) => {
|
||||
scrollLeft = value
|
||||
})
|
||||
Object.defineProperty(container, 'clientWidth', { value: 200 })
|
||||
container.appendChild(input)
|
||||
document.body.appendChild(container)
|
||||
return {
|
||||
container,
|
||||
input,
|
||||
setScrollLeft,
|
||||
getScrollLeft: () => scrollLeft,
|
||||
getContainerDomNode: () => container,
|
||||
getScrollWidth: () => scrollWidth,
|
||||
getLayoutInfo: () => ({ contentWidth: 200 })
|
||||
}
|
||||
}
|
||||
|
||||
function dispatchWheel(target: HTMLElement, init: WheelEventInit): WheelEvent {
|
||||
const event = new WheelEvent('wheel', { ...init, bubbles: true, cancelable: true })
|
||||
// Happy DOM's WheelEvent omits mouse modifier fields.
|
||||
Object.defineProperty(event, 'shiftKey', { value: init.shiftKey ?? false })
|
||||
target.dispatchEvent(event)
|
||||
return event
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.body.replaceChildren()
|
||||
})
|
||||
|
||||
describe('installDiffEditorShiftWheelScroll', () => {
|
||||
it.each([
|
||||
{ label: 'vertical pixel input', init: { deltaY: 24 }, expected: 34 },
|
||||
{ label: 'platform-converted horizontal input', init: { deltaX: 12 }, expected: 22 },
|
||||
{
|
||||
label: 'line-based input',
|
||||
init: { deltaY: -2, deltaMode: WheelEvent.DOM_DELTA_LINE },
|
||||
expected: -22
|
||||
},
|
||||
{
|
||||
label: 'page-based input',
|
||||
init: { deltaY: 1, deltaMode: WheelEvent.DOM_DELTA_PAGE },
|
||||
expected: 210
|
||||
}
|
||||
])('scrolls the pane under the pointer for $label', ({ init, expected }) => {
|
||||
const original = createPaneFixture()
|
||||
const modified = createPaneFixture()
|
||||
const onDownstreamWheel = vi.fn()
|
||||
original.input.addEventListener('wheel', onDownstreamWheel)
|
||||
const dispose = installDiffEditorShiftWheelScroll({
|
||||
getOriginalEditor: () => original,
|
||||
getModifiedEditor: () => modified
|
||||
})
|
||||
|
||||
const event = dispatchWheel(original.input, { ...init, shiftKey: true })
|
||||
|
||||
expect(event.defaultPrevented).toBe(true)
|
||||
expect(original.setScrollLeft).toHaveBeenCalledWith(expected)
|
||||
expect(modified.setScrollLeft).not.toHaveBeenCalled()
|
||||
expect(onDownstreamWheel).not.toHaveBeenCalled()
|
||||
dispose()
|
||||
})
|
||||
|
||||
it('leaves ordinary vertical wheel input for the outer combined-diff scroller', () => {
|
||||
const original = createPaneFixture()
|
||||
const modified = createPaneFixture()
|
||||
const onDownstreamWheel = vi.fn()
|
||||
original.input.addEventListener('wheel', onDownstreamWheel)
|
||||
const dispose = installDiffEditorShiftWheelScroll({
|
||||
getOriginalEditor: () => original,
|
||||
getModifiedEditor: () => modified
|
||||
})
|
||||
|
||||
const event = dispatchWheel(original.input, { deltaY: 24 })
|
||||
|
||||
expect(event.defaultPrevented).toBe(false)
|
||||
expect(original.setScrollLeft).not.toHaveBeenCalled()
|
||||
expect(onDownstreamWheel).toHaveBeenCalledTimes(1)
|
||||
dispose()
|
||||
})
|
||||
|
||||
it('leaves shift input alone when the pane has no horizontal overflow', () => {
|
||||
const original = createPaneFixture(0, 200)
|
||||
const modified = createPaneFixture(0, 200)
|
||||
const onDownstreamWheel = vi.fn()
|
||||
original.input.addEventListener('wheel', onDownstreamWheel)
|
||||
const dispose = installDiffEditorShiftWheelScroll({
|
||||
getOriginalEditor: () => original,
|
||||
getModifiedEditor: () => modified
|
||||
})
|
||||
|
||||
const event = dispatchWheel(original.input, { deltaY: 24, shiftKey: true })
|
||||
|
||||
expect(event.defaultPrevented).toBe(false)
|
||||
expect(original.setScrollLeft).not.toHaveBeenCalled()
|
||||
expect(onDownstreamWheel).toHaveBeenCalledTimes(1)
|
||||
dispose()
|
||||
})
|
||||
|
||||
// Monaco syncs pane scroll itself; this covers listener routing, not product-level pane independence.
|
||||
it('routes the wheel event to the pane under the pointer', () => {
|
||||
const original = createPaneFixture()
|
||||
const modified = createPaneFixture()
|
||||
const dispose = installDiffEditorShiftWheelScroll({
|
||||
getOriginalEditor: () => original,
|
||||
getModifiedEditor: () => modified
|
||||
})
|
||||
|
||||
const event = dispatchWheel(modified.input, { deltaY: 24, shiftKey: true })
|
||||
|
||||
expect(event.defaultPrevented).toBe(true)
|
||||
expect(modified.setScrollLeft).toHaveBeenCalledWith(34)
|
||||
expect(original.setScrollLeft).not.toHaveBeenCalled()
|
||||
dispose()
|
||||
})
|
||||
|
||||
it('removes both pane listeners when disposed', () => {
|
||||
const original = createPaneFixture()
|
||||
const modified = createPaneFixture()
|
||||
const dispose = installDiffEditorShiftWheelScroll({
|
||||
getOriginalEditor: () => original,
|
||||
getModifiedEditor: () => modified
|
||||
})
|
||||
dispose()
|
||||
|
||||
const originalEvent = dispatchWheel(original.input, { deltaY: 24, shiftKey: true })
|
||||
const modifiedEvent = dispatchWheel(modified.input, { deltaY: 24, shiftKey: true })
|
||||
|
||||
expect(originalEvent.defaultPrevented).toBe(false)
|
||||
expect(modifiedEvent.defaultPrevented).toBe(false)
|
||||
expect(original.setScrollLeft).not.toHaveBeenCalled()
|
||||
expect(modified.setScrollLeft).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
-165
@@ -1,165 +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 type { OpenFile } from '@/store/slices/editor/types/open-file'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
readRuntimeFileContent: vi.fn(),
|
||||
getConnectionIdForFile: vi.fn(),
|
||||
getState: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/runtime/runtime-file-read-client', () => ({
|
||||
readRuntimeFileContent: mocks.readRuntimeFileContent
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/connection-context', () => ({
|
||||
getConnectionIdForFile: mocks.getConnectionIdForFile
|
||||
}))
|
||||
vi.mock('@/store/index', () => ({
|
||||
useAppStore: { getState: mocks.getState }
|
||||
}))
|
||||
// Stub the lazy diff chunk under happy-dom and expose its disk-left/buffer-right props.
|
||||
vi.mock('@/lib/lazy-with-retry', () => ({
|
||||
lazyWithRetry: () => (props: { originalContent: string; modifiedContent: string }) => (
|
||||
<div data-testid="diff-stub">
|
||||
original:{props.originalContent}|modified:{props.modifiedContent}
|
||||
</div>
|
||||
)
|
||||
}))
|
||||
|
||||
import { ExternalFileChangeCompareDialog } from './ExternalFileChangeCompareDialog'
|
||||
|
||||
const file = {
|
||||
id: 'file-1',
|
||||
filePath: '/repo/notes.ts',
|
||||
relativePath: 'notes.ts',
|
||||
worktreeId: 'wt-1',
|
||||
mode: 'edit',
|
||||
isDirty: true,
|
||||
externalMutation: 'changed'
|
||||
} as OpenFile
|
||||
|
||||
describe('ExternalFileChangeCompareDialog', () => {
|
||||
let root: Root | null = null
|
||||
let container: HTMLElement | null = null
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.readRuntimeFileContent.mockReset()
|
||||
mocks.getConnectionIdForFile.mockReset()
|
||||
mocks.getConnectionIdForFile.mockReturnValue(undefined)
|
||||
mocks.getState.mockReturnValue({ settings: null })
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => {
|
||||
root?.unmount()
|
||||
})
|
||||
container?.remove()
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
async function render(element: React.JSX.Element): Promise<void> {
|
||||
await act(async () => {
|
||||
root = createRoot(container!)
|
||||
root.render(element)
|
||||
})
|
||||
}
|
||||
|
||||
it('shows the disk version left and the buffer right once the read resolves', async () => {
|
||||
mocks.readRuntimeFileContent.mockResolvedValue({ content: 'disk version', isBinary: false })
|
||||
|
||||
await render(
|
||||
<ExternalFileChangeCompareDialog
|
||||
file={file}
|
||||
currentContent="buffer version"
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
onReload={vi.fn()}
|
||||
onKeepEdits={vi.fn()}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(document.body.textContent).toContain('File changed on disk')
|
||||
expect(document.body.textContent).toContain('original:disk version|modified:buffer version')
|
||||
expect(document.body.textContent).toContain('Reload from Disk')
|
||||
expect(document.body.textContent).toContain('Keep My Edits')
|
||||
})
|
||||
|
||||
it('surfaces a read failure instead of a blank comparison', async () => {
|
||||
mocks.readRuntimeFileContent.mockRejectedValue(new Error('transport down'))
|
||||
|
||||
await render(
|
||||
<ExternalFileChangeCompareDialog
|
||||
file={file}
|
||||
currentContent="buffer version"
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
onReload={vi.fn()}
|
||||
onKeepEdits={vi.fn()}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(document.body.textContent).toContain('Could not read the file from disk')
|
||||
expect(document.body.textContent).toContain('transport down')
|
||||
})
|
||||
|
||||
it('wires the footer actions and closes the dialog around them', async () => {
|
||||
mocks.readRuntimeFileContent.mockResolvedValue({ content: 'disk version', isBinary: false })
|
||||
const onReload = vi.fn()
|
||||
const onKeepEdits = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
|
||||
await render(
|
||||
<ExternalFileChangeCompareDialog
|
||||
file={file}
|
||||
currentContent="buffer version"
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
onReload={onReload}
|
||||
onKeepEdits={onKeepEdits}
|
||||
/>
|
||||
)
|
||||
|
||||
const buttons = Array.from(document.body.querySelectorAll('button'))
|
||||
await act(async () => {
|
||||
buttons.find((b) => b.textContent === 'Reload from Disk')?.click()
|
||||
})
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false)
|
||||
expect(onReload).toHaveBeenCalledTimes(1)
|
||||
|
||||
await act(async () => {
|
||||
buttons.find((b) => b.textContent === 'Keep My Edits')?.click()
|
||||
})
|
||||
expect(onKeepEdits).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it.each([
|
||||
[
|
||||
'a floating-workspace tab as the file the user named',
|
||||
'global-floating-terminal',
|
||||
null,
|
||||
'user-file'
|
||||
],
|
||||
['a project tab inside its root', 'wt-1', null, undefined]
|
||||
])('reads %s', async (_label, worktreeId, connectionId, kind) => {
|
||||
mocks.getConnectionIdForFile.mockReturnValue(connectionId)
|
||||
mocks.readRuntimeFileContent.mockResolvedValue({ content: 'disk version', isBinary: false })
|
||||
|
||||
await render(
|
||||
<ExternalFileChangeCompareDialog
|
||||
file={{ ...file, worktreeId }}
|
||||
currentContent="buffer version"
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
onReload={vi.fn()}
|
||||
onKeepEdits={vi.fn()}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(mocks.readRuntimeFileContent.mock.calls[0]?.[0]?.access?.kind).toBe(kind)
|
||||
})
|
||||
})
|
||||
-76
@@ -18,66 +18,6 @@ class WorkerTransport extends EventTarget implements Worker {
|
||||
|
||||
afterEach(() => vi.useRealTimers())
|
||||
describe('Markdown preview worker ownership', () => {
|
||||
it('drops superseded replies and retains one pending request per kind', async () => {
|
||||
const worker = new WorkerTransport()
|
||||
const failure = vi.fn()
|
||||
const client = new MarkdownPreviewDocumentClient(worker, failure)
|
||||
const old = client.request({ type: 'blocks', indices: [0] }).catch((error) => error)
|
||||
const current = client.request({ type: 'blocks', indices: [20] })
|
||||
worker.reply({ id: 1, type: 'blocks', blocks: [] })
|
||||
worker.reply({
|
||||
id: 2,
|
||||
type: 'blocks',
|
||||
blocks: [{ index: 20, tree: { type: 'root', children: [] }, oversized: false }]
|
||||
})
|
||||
expect(await old).toBeInstanceOf(Error)
|
||||
expect(await current).toMatchObject({ id: 2, blocks: [{ index: 20 }] })
|
||||
expect(failure).not.toHaveBeenCalled()
|
||||
client.close()
|
||||
expect(worker.terminate).toHaveBeenCalledOnce()
|
||||
expect(worker.onmessage).toBeNull()
|
||||
})
|
||||
it('terminates stalled work and rejects every pending owner', async () => {
|
||||
vi.useFakeTimers()
|
||||
const worker = new WorkerTransport()
|
||||
const failure = vi.fn()
|
||||
const client = new MarkdownPreviewDocumentClient(worker, failure)
|
||||
const load = client.request({ type: 'load', content: '# Heading' }).catch((error) => error)
|
||||
const search = client.request({ type: 'search', query: 'heading' }).catch((error) => error)
|
||||
await vi.advanceTimersByTimeAsync(MARKDOWN_PREVIEW_WORKER_TIMEOUT_MS)
|
||||
expect(await load).toBeInstanceOf(Error)
|
||||
expect(await search).toBeInstanceOf(Error)
|
||||
expect(worker.terminate).toHaveBeenCalledOnce()
|
||||
expect(failure).toHaveBeenCalledOnce()
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
expect(
|
||||
await client.request({ type: 'blocks', indices: [] }).catch((error) => error)
|
||||
).toBeInstanceOf(Error)
|
||||
})
|
||||
it('closes on parse errors without a synchronous retry', async () => {
|
||||
const worker = new WorkerTransport()
|
||||
const failure = vi.fn()
|
||||
const client = new MarkdownPreviewDocumentClient(worker, failure)
|
||||
const load = client.request({ type: 'load', content: '# Heading' }).catch((error) => error)
|
||||
worker.reply({ id: 1, type: 'error', message: 'Too complex' })
|
||||
expect(await load).toBeInstanceOf(Error)
|
||||
expect(failure).toHaveBeenCalledWith(expect.objectContaining({ message: 'Too complex' }))
|
||||
expect(worker.terminate).toHaveBeenCalledOnce()
|
||||
})
|
||||
it('cleans up requests on content replacement or tab close', async () => {
|
||||
vi.useFakeTimers()
|
||||
const worker = new WorkerTransport()
|
||||
const failure = vi.fn()
|
||||
const client = new MarkdownPreviewDocumentClient(worker, failure)
|
||||
const pending = client.request({ type: 'search', query: 'text' }).catch((error) => error)
|
||||
client.close()
|
||||
client.close()
|
||||
expect(await pending).toBeInstanceOf(Error)
|
||||
expect(worker.terminate).toHaveBeenCalledOnce()
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
expect(failure).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('cancels a timed-out search without terminating a working preview', async () => {
|
||||
vi.useFakeTimers()
|
||||
const worker = new WorkerTransport()
|
||||
@@ -96,20 +36,4 @@ describe('Markdown preview worker ownership', () => {
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('treats search limits as local failures and sends cancellation when Find closes', async () => {
|
||||
const worker = new WorkerTransport()
|
||||
const failure = vi.fn()
|
||||
const client = new MarkdownPreviewDocumentClient(worker, failure)
|
||||
const search = client.request({ type: 'search', query: 'needle' }).catch((error) => error)
|
||||
worker.reply({ id: 1, type: 'error', message: 'Search too complex' })
|
||||
expect(await search).toEqual(new Error('Search too complex'))
|
||||
expect(worker.terminate).not.toHaveBeenCalled()
|
||||
const pending = client.request({ type: 'search', query: 'different' }).catch((error) => error)
|
||||
client.cancel('search')
|
||||
expect(await pending).toBeInstanceOf(Error)
|
||||
expect(worker.postMessage).toHaveBeenLastCalledWith({ id: 3, type: 'cancel-search' })
|
||||
expect(failure).not.toHaveBeenCalled()
|
||||
client.close()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,176 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Worktree } from '../../../../../../shared/worktree/types'
|
||||
import {
|
||||
deriveMarkdownPreviewSourceRoot,
|
||||
getMarkdownPreviewSourceRelativePath,
|
||||
findMarkdownPreviewOpenedEditFileId,
|
||||
findMarkdownPreviewSourceOpenFile,
|
||||
resolveMarkdownPreviewSourceWorktree
|
||||
} from '../links/markdown-preview-source-routing'
|
||||
import {
|
||||
decodeMarkdownPreviewAnchor,
|
||||
getMarkdownPreviewAnchorScrollTop
|
||||
} from '../viewport/markdown-preview-anchor-navigation'
|
||||
import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../../shared/constants'
|
||||
|
||||
function makeWorktree(id: string, path: string): Worktree {
|
||||
return {
|
||||
id,
|
||||
repoId: `repo-${id}`,
|
||||
path,
|
||||
branch: 'refs/heads/main',
|
||||
head: 'abc',
|
||||
isBare: false,
|
||||
isMainWorktree: true,
|
||||
displayName: id,
|
||||
comment: '',
|
||||
linkedIssue: null,
|
||||
linkedPR: null,
|
||||
linkedLinearIssue: null,
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 0
|
||||
}
|
||||
}
|
||||
|
||||
describe('MarkdownPreview source link routing', () => {
|
||||
it('falls back to the raw anchor when percent-decoding fails', () => {
|
||||
expect(decodeMarkdownPreviewAnchor('%E0%A4%A')).toBe('%E0%A4%A')
|
||||
})
|
||||
|
||||
it('keeps the explicit source worktree when it exists', () => {
|
||||
const source = makeWorktree('wt-source', '/repo')
|
||||
const nested = makeWorktree('wt-nested', '/repo/packages/app')
|
||||
|
||||
expect(
|
||||
resolveMarkdownPreviewSourceWorktree(
|
||||
{ repo: [source, nested] },
|
||||
'wt-source',
|
||||
'/repo/packages/app/docs/note.md'
|
||||
)
|
||||
).toBe(source)
|
||||
})
|
||||
|
||||
it('falls back to path-based repo ownership for repo-contained floating files', () => {
|
||||
const repoWorktree = makeWorktree('wt-repo', '/repo')
|
||||
|
||||
expect(
|
||||
resolveMarkdownPreviewSourceWorktree(
|
||||
{ repo: [repoWorktree] },
|
||||
FLOATING_TERMINAL_WORKTREE_ID,
|
||||
'/repo/docs/note.md'
|
||||
)
|
||||
).toBe(repoWorktree)
|
||||
})
|
||||
|
||||
it('matches Windows worktree ownership case-insensitively for floating previews', () => {
|
||||
const repoWorktree = makeWorktree('wt-repo', 'C:\\Repo')
|
||||
|
||||
expect(
|
||||
resolveMarkdownPreviewSourceWorktree(
|
||||
{ repo: [repoWorktree] },
|
||||
FLOATING_TERMINAL_WORKTREE_ID,
|
||||
'c:\\repo\\docs\\note.md'
|
||||
)
|
||||
).toBe(repoWorktree)
|
||||
})
|
||||
|
||||
it('derives Windows preview source relative paths case-insensitively', () => {
|
||||
expect(getMarkdownPreviewSourceRelativePath('c:\\repo\\docs\\note.md', 'C:\\Repo')).toBe(
|
||||
'docs/note.md'
|
||||
)
|
||||
})
|
||||
|
||||
it('derives a source root from floating file relative path', () => {
|
||||
expect(deriveMarkdownPreviewSourceRoot('/tmp/orca/docs/note.md', 'docs/note.md')).toBe(
|
||||
'/tmp/orca'
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to the source file directory when no relative path is available', () => {
|
||||
expect(deriveMarkdownPreviewSourceRoot('/tmp/orca/docs/note.md', null)).toBe('/tmp/orca/docs')
|
||||
})
|
||||
|
||||
it('derives Windows source roots without dropping the drive separator', () => {
|
||||
expect(deriveMarkdownPreviewSourceRoot('C:\\orca\\docs\\note.md', 'docs\\note.md')).toBe(
|
||||
'C:/orca'
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to the matching preview tab for preview-only source metadata', () => {
|
||||
const otherOwnerEdit = {
|
||||
id: '/tmp/orca/docs/note.md',
|
||||
filePath: '/tmp/orca/docs/note.md',
|
||||
relativePath: 'docs/note.md',
|
||||
worktreeId: 'wt-1',
|
||||
mode: 'edit'
|
||||
}
|
||||
const preview = {
|
||||
id: 'markdown-preview::/tmp/orca/docs/note.md',
|
||||
filePath: '/tmp/orca/docs/note.md',
|
||||
relativePath: 'docs/note.md',
|
||||
worktreeId: FLOATING_TERMINAL_WORKTREE_ID,
|
||||
runtimeEnvironmentId: null,
|
||||
mode: 'markdown-preview',
|
||||
markdownPreviewSourceFileId: '/tmp/orca/docs/note.md'
|
||||
}
|
||||
|
||||
expect(
|
||||
findMarkdownPreviewSourceOpenFile([otherOwnerEdit, preview], {
|
||||
sourceFileId: '/tmp/orca/docs/note.md',
|
||||
filePath: '/tmp/orca/docs/note.md',
|
||||
sourceWorktreeId: FLOATING_TERMINAL_WORKTREE_ID,
|
||||
sourceRuntimeEnvironmentId: null
|
||||
})
|
||||
).toBe(preview)
|
||||
expect(deriveMarkdownPreviewSourceRoot(preview.filePath, preview.relativePath)).toBe(
|
||||
'/tmp/orca'
|
||||
)
|
||||
})
|
||||
|
||||
it('uses the edit tab that openFile actually activated for line reveals', () => {
|
||||
const localEdit = {
|
||||
id: '/repo/docs/guide.md',
|
||||
filePath: '/repo/docs/guide.md',
|
||||
relativePath: 'docs/guide.md',
|
||||
worktreeId: 'wt-1',
|
||||
runtimeEnvironmentId: null,
|
||||
mode: 'edit'
|
||||
}
|
||||
const activeRuntimeEdit = {
|
||||
id: 'editor:wt-1:env-active:guide',
|
||||
filePath: '/repo/docs/guide.md',
|
||||
relativePath: 'docs/guide.md',
|
||||
worktreeId: 'wt-1',
|
||||
runtimeEnvironmentId: 'env-active',
|
||||
mode: 'edit'
|
||||
}
|
||||
|
||||
expect(
|
||||
findMarkdownPreviewOpenedEditFileId(
|
||||
[localEdit, activeRuntimeEdit],
|
||||
{
|
||||
'wt-1': activeRuntimeEdit.id
|
||||
},
|
||||
{
|
||||
filePath: '/repo/docs/guide.md',
|
||||
worktreeId: 'wt-1'
|
||||
}
|
||||
)
|
||||
).toBe(activeRuntimeEdit.id)
|
||||
})
|
||||
|
||||
it('computes anchor scroll from viewport position instead of offset parent', () => {
|
||||
const container = {
|
||||
scrollTop: 125,
|
||||
getBoundingClientRect: () => ({ top: 50 }) as DOMRect
|
||||
}
|
||||
const target = {
|
||||
getBoundingClientRect: () => ({ top: 430 }) as DOMRect
|
||||
}
|
||||
|
||||
expect(getMarkdownPreviewAnchorScrollTop(container, target)).toBe(493)
|
||||
})
|
||||
})
|
||||
@@ -1,82 +1,8 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import React from 'react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import Markdown from 'react-markdown'
|
||||
import type { MarkdownDocument } from '../../../../../../shared/filesystem-entry-types'
|
||||
import {
|
||||
createMarkdownDocumentIndex,
|
||||
getMarkdownDocLinkAnchor,
|
||||
remarkMarkdownDocLinks,
|
||||
resolveMarkdownDocLink,
|
||||
splitMarkdownDocLinkText
|
||||
} from './markdown-doc-links'
|
||||
|
||||
type TestNode = {
|
||||
type: string
|
||||
value?: string
|
||||
url?: string
|
||||
children?: TestNode[]
|
||||
}
|
||||
|
||||
const documents: MarkdownDocument[] = [
|
||||
{
|
||||
filePath: '/repo/docs/setup-guide.md',
|
||||
relativePath: 'docs/setup-guide.md',
|
||||
basename: 'setup-guide.md',
|
||||
name: 'setup-guide'
|
||||
},
|
||||
{
|
||||
filePath: '/repo/notes/README.MDX',
|
||||
relativePath: 'notes/README.MDX',
|
||||
basename: 'README.MDX',
|
||||
name: 'README'
|
||||
}
|
||||
]
|
||||
|
||||
describe('splitMarkdownDocLinkText', () => {
|
||||
it('splits multiple doc links', () => {
|
||||
expect(splitMarkdownDocLinkText('[[one]] and [[two]]')).toEqual([
|
||||
{ type: 'docLink', target: 'one', label: 'one' },
|
||||
{ type: 'text', value: ' and ' },
|
||||
{ type: 'docLink', target: 'two', label: 'two' }
|
||||
])
|
||||
})
|
||||
|
||||
it('leaves unsupported forms as text', () => {
|
||||
expect(splitMarkdownDocLinkText('[[]] [[doc|]] [[bad [target]] [[draft')).toEqual([
|
||||
{ type: 'text', value: '[[]]' },
|
||||
{ type: 'text', value: ' [[doc|]]' },
|
||||
{ type: 'text', value: ' [[bad [target]]' },
|
||||
{ type: 'text', value: ' [[draft' }
|
||||
])
|
||||
})
|
||||
})
|
||||
import { createMarkdownDocumentIndex, resolveMarkdownDocLink } from './markdown-doc-links'
|
||||
|
||||
describe('resolveMarkdownDocLink', () => {
|
||||
it('resolves heading anchors against the document target', () => {
|
||||
const index = createMarkdownDocumentIndex(documents)
|
||||
|
||||
expect(resolveMarkdownDocLink('docs/setup-guide#Install steps', index)).toMatchObject({
|
||||
status: 'resolved',
|
||||
document: { relativePath: 'docs/setup-guide.md' }
|
||||
})
|
||||
})
|
||||
|
||||
it('treats duplicate normalized basenames as ambiguous', () => {
|
||||
const index = createMarkdownDocumentIndex([
|
||||
...documents,
|
||||
{
|
||||
filePath: '/repo/other/Setup-Guide.md',
|
||||
relativePath: 'other/Setup-Guide.md',
|
||||
basename: 'Setup-Guide.md',
|
||||
name: 'Setup-Guide'
|
||||
}
|
||||
])
|
||||
|
||||
expect(resolveMarkdownDocLink('setup-guide', index).status).toBe('ambiguous')
|
||||
expect(resolveMarkdownDocLink('docs/setup-guide', index).status).toBe('resolved')
|
||||
})
|
||||
|
||||
it('prefers exact relative path over ambiguous extensionless match', () => {
|
||||
const index = createMarkdownDocumentIndex([
|
||||
{
|
||||
@@ -103,66 +29,4 @@ describe('resolveMarkdownDocLink', () => {
|
||||
})
|
||||
expect(resolveMarkdownDocLink('docs/guide', index).status).toBe('ambiguous')
|
||||
})
|
||||
|
||||
it('normalizes Windows-style targets', () => {
|
||||
const result = resolveMarkdownDocLink(
|
||||
'docs\\setup-guide.md',
|
||||
createMarkdownDocumentIndex(documents)
|
||||
)
|
||||
expect(result.status).toBe('resolved')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getMarkdownDocLinkAnchor', () => {
|
||||
it('extracts preview heading anchor ids from doc link targets', () => {
|
||||
expect(getMarkdownDocLinkAnchor('docs/setup-guide#Install steps')).toBe('install-steps')
|
||||
expect(getMarkdownDocLinkAnchor('docs/setup-guide#What is new?')).toBe('what-is-new')
|
||||
expect(getMarkdownDocLinkAnchor('docs/setup-guide#install-steps')).toBe('install-steps')
|
||||
expect(getMarkdownDocLinkAnchor('docs/setup-guide')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('remarkMarkdownDocLinks', () => {
|
||||
it('renders aliased doc links with the alias text', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(
|
||||
Markdown,
|
||||
{ remarkPlugins: [remarkMarkdownDocLinks] },
|
||||
'link to [[other.md|Other note]]'
|
||||
)
|
||||
)
|
||||
|
||||
expect(html).toContain('<a href="#orca-doc-link=other.md">Other note</a>')
|
||||
expect(html).not.toContain('[[other.md|Other note]]')
|
||||
})
|
||||
|
||||
it('transforms text nodes but not code, links, or images', () => {
|
||||
const tree: TestNode = {
|
||||
type: 'root',
|
||||
children: [
|
||||
{ type: 'text', value: 'See [[setup-guide]]' },
|
||||
{ type: 'inlineCode', value: '[[code]]' },
|
||||
{ type: 'link', url: '[[url]]', children: [{ type: 'text', value: '[[label]]' }] },
|
||||
{ type: 'image', url: '[[image]]' }
|
||||
]
|
||||
}
|
||||
|
||||
remarkMarkdownDocLinks()(tree)
|
||||
|
||||
expect(tree.children?.[0]).toMatchObject({
|
||||
type: 'text',
|
||||
value: 'See '
|
||||
})
|
||||
expect(tree.children?.[1]).toMatchObject({
|
||||
type: 'link',
|
||||
url: '#orca-doc-link=setup-guide'
|
||||
})
|
||||
expect(tree.children?.[2]).toEqual({ type: 'inlineCode', value: '[[code]]' })
|
||||
expect(tree.children?.[3]).toEqual({
|
||||
type: 'link',
|
||||
url: '[[url]]',
|
||||
children: [{ type: 'text', value: '[[label]]' }]
|
||||
})
|
||||
expect(tree.children?.[4]).toEqual({ type: 'image', url: '[[image]]' })
|
||||
})
|
||||
})
|
||||
|
||||
-93
@@ -54,46 +54,6 @@ function render(file: OpenFile) {
|
||||
})
|
||||
}
|
||||
|
||||
it('waits for the retained editor to take its managed workspace owner before listing', async () => {
|
||||
useAppStore.setState({
|
||||
repos: [
|
||||
{
|
||||
id: 'repo-1',
|
||||
path: '/remote/repo',
|
||||
displayName: 'repo',
|
||||
badgeColor: '#737373',
|
||||
addedAt: 1,
|
||||
executionHostId: 'runtime:env-1'
|
||||
}
|
||||
],
|
||||
worktreesByRepo: {
|
||||
'repo-1': [
|
||||
makeWorktree({
|
||||
id: worktreeId,
|
||||
repoId: 'repo-1',
|
||||
path: '/remote/repo',
|
||||
hostId: 'runtime:env-1',
|
||||
runtimeOwnerEnvironmentId: 'env-1'
|
||||
})
|
||||
]
|
||||
}
|
||||
})
|
||||
const { result, rerender } = render(file)
|
||||
expect(mocks.list).not.toHaveBeenCalled()
|
||||
expect(mocks.toastError).not.toHaveBeenCalled()
|
||||
rerender({ file: { ...file, id: 'owned', runtimeEnvironmentId: 'env-1' } })
|
||||
await waitFor(() => expect(result.current.markdownDocuments).toEqual([document]))
|
||||
expect(mocks.list).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.list).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
target: { kind: 'environment', environmentId: 'env-1' },
|
||||
worktreeId
|
||||
}),
|
||||
'/remote/repo',
|
||||
{ requireFresh: false }
|
||||
)
|
||||
})
|
||||
|
||||
it('waits for missing ownership and resumes when the SSH catalog lands without a path change', async () => {
|
||||
const { result } = render(file)
|
||||
expect(mocks.list).not.toHaveBeenCalled()
|
||||
@@ -119,56 +79,3 @@ it('waits for missing ownership and resumes when the SSH catalog lands without a
|
||||
{ requireFresh: false }
|
||||
)
|
||||
})
|
||||
|
||||
it('waits for ownership migration in a non-git folder workspace too', async () => {
|
||||
useAppStore.setState({
|
||||
worktreesByRepo: {},
|
||||
projectGroups: [
|
||||
{
|
||||
id: 'group-1',
|
||||
name: 'Notes',
|
||||
parentPath: '/notes',
|
||||
connectionId: null,
|
||||
executionHostId: 'runtime:env-1',
|
||||
parentGroupId: null,
|
||||
createdFrom: 'manual',
|
||||
tabOrder: 0,
|
||||
isCollapsed: false,
|
||||
color: null,
|
||||
createdAt: 1,
|
||||
updatedAt: 1
|
||||
}
|
||||
],
|
||||
folderWorkspaces: [
|
||||
{
|
||||
id: 'notes',
|
||||
projectGroupId: 'group-1',
|
||||
name: 'Notes',
|
||||
folderPath: '/notes',
|
||||
connectionId: null,
|
||||
linkedTask: null,
|
||||
comment: '',
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 1,
|
||||
createdAt: 1,
|
||||
updatedAt: 1
|
||||
}
|
||||
]
|
||||
})
|
||||
const folderFile = { ...file, worktreeId: 'folder:notes', filePath: '/notes/README.md' }
|
||||
const { result, rerender } = render(folderFile)
|
||||
expect(mocks.list).not.toHaveBeenCalled()
|
||||
rerender({ file: { ...folderFile, id: 'folder-owned', runtimeEnvironmentId: 'env-1' } })
|
||||
await waitFor(() => expect(result.current.markdownDocuments).toEqual([document]))
|
||||
expect(mocks.list).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
target: { kind: 'environment', environmentId: 'env-1' },
|
||||
worktreeId: 'folder:notes'
|
||||
}),
|
||||
'/notes',
|
||||
{ requireFresh: false }
|
||||
)
|
||||
})
|
||||
|
||||
-31
@@ -48,29 +48,6 @@ function mountDetails(): Editor {
|
||||
return editor
|
||||
}
|
||||
|
||||
it('opens only native details ancestors that conceal the destination', () => {
|
||||
document.body.innerHTML = `
|
||||
<details id="outer"><summary>Outer</summary>
|
||||
<details id="inner"><summary>Inner</summary><h2>Target</h2></details>
|
||||
</details>
|
||||
<details id="sibling"><summary>Sibling</summary></details>
|
||||
`
|
||||
revealMarkdownNavigationDetails(document.querySelector('h2')!)
|
||||
expect([...document.querySelectorAll('details')].map((details) => details.open)).toEqual([
|
||||
true,
|
||||
true,
|
||||
false
|
||||
])
|
||||
document.querySelector('#inner')?.removeAttribute('open')
|
||||
document.querySelector('#outer')?.removeAttribute('open')
|
||||
revealMarkdownNavigationDetails(document.querySelector<HTMLElement>('#inner summary')!)
|
||||
expect([...document.querySelectorAll('details')].map((details) => details.open)).toEqual([
|
||||
true,
|
||||
false,
|
||||
false
|
||||
])
|
||||
})
|
||||
|
||||
it('opens rich ancestors in one undoable transaction while retaining selection and variants', () => {
|
||||
const editor = mountDetails()
|
||||
editor.commands.setTextSelection(2)
|
||||
@@ -101,14 +78,6 @@ it('opens rich ancestors in one undoable transaction while retaining selection a
|
||||
expect(editor.state.doc.child(1).child(1).firstChild?.attrs.open).toBe(false)
|
||||
})
|
||||
|
||||
it('opens the outer rich fold without expanding a destination in its own summary', () => {
|
||||
const editor = mountDetails()
|
||||
revealMarkdownNavigationDetails(editor.view.dom.querySelectorAll<HTMLElement>('summary')[1])
|
||||
expect(editor.state.doc.child(1).attrs.open).toBe(true)
|
||||
expect(editor.state.doc.child(1).child(1).firstChild?.attrs.open).toBe(false)
|
||||
expect(editor.state.doc.child(2).attrs.open).toBe(false)
|
||||
})
|
||||
|
||||
it.each([false, true])(
|
||||
'reveals readonly rich content without changing its document (open: %s)',
|
||||
(open) => {
|
||||
|
||||
+1
-19
@@ -10,7 +10,7 @@ import { applyEditorBufferText } from './editor-buffer-adapter'
|
||||
|
||||
import { editorTabModelUri } from '../../save/queue/editor-save-disk-precondition'
|
||||
import { attachClosedEditorTabCleanup } from '../retention/closed-editor-tab-controller'
|
||||
import { attachModelLifetimeView } from '../retention/editor-model-lifetime-fixture'
|
||||
|
||||
import { showClosedUnsavedFilesToast } from '../../closed-unsaved-files-toast'
|
||||
|
||||
const storeRef = vi.hoisted((): { current: StoreApi<AppState> | null } => ({ current: null }))
|
||||
@@ -74,14 +74,6 @@ describe('applyEditorBufferText', () => {
|
||||
store.getState().setMarkdownViewMode(a, 'source')
|
||||
})
|
||||
|
||||
it("carries a rich commit into the record's model no editor shows, as one undoable edit", () => {
|
||||
const model = modelOf(store, a)
|
||||
applyEditorBufferText(store.getState(), file(store, b), 'rich edit', bridge)
|
||||
expect(model.getValue()).toBe('rich edit')
|
||||
model.undo()
|
||||
expect(model.getValue()).toBe('disk')
|
||||
})
|
||||
|
||||
it('makes each commit its own undo step, apart from typing before it', () => {
|
||||
const model = modelOf(store, a)
|
||||
model.pushEditOperations([], [{ range: model.getFullModelRange(), text: 'typed' }], () => null)
|
||||
@@ -92,16 +84,6 @@ describe('applyEditorBufferText', () => {
|
||||
model.undo()
|
||||
expect(model.getValue()).toBe('typed')
|
||||
})
|
||||
|
||||
it('leaves a shown model to its editor and ignores commits from a code view', () => {
|
||||
const model = modelOf(store, a)
|
||||
const detach = attachModelLifetimeView(model)
|
||||
applyEditorBufferText(store.getState(), file(store, b), 'rich edit', bridge)
|
||||
expect(model.getValue()).toBe('disk')
|
||||
detach()
|
||||
applyEditorBufferText(store.getState(), file(store, a), 'typed in source', bridge)
|
||||
expect(model.getValue()).toBe('disk')
|
||||
})
|
||||
})
|
||||
|
||||
describe('a kept dirty record owns its model', () => {
|
||||
|
||||
-153
@@ -1,153 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import type { AppState } from '@/store/types'
|
||||
import type { OpenFile } from '@/store/slices/editor/types/open-file'
|
||||
import { needsSavePromptOnClose } from '@/store/slices/editor/buffers/editor-buffer-close-rule'
|
||||
import type { EditorBufferViewIndex } from '@/store/slices/editor/buffers/editor-buffer-views'
|
||||
import { restartSaveTargets } from '../../autosave/editor-autosave-state-projections'
|
||||
import {
|
||||
flushPendingEditorBuffer,
|
||||
hasPendingEditorBufferChange,
|
||||
registerPendingEditorFlush
|
||||
} from '../../save/flush/editor-pending-flush'
|
||||
import { discardEditorFileChangesAndClose } from '../../save/flush/discard-editor-file-changes'
|
||||
import type * as EditorAutosave from '../../autosave/editor-autosave'
|
||||
|
||||
const quiesce = vi.hoisted(() => vi.fn(async () => () => {}))
|
||||
vi.mock('../../autosave/editor-autosave', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof EditorAutosave>()),
|
||||
requestEditorSaveQuiesce: quiesce
|
||||
}))
|
||||
|
||||
function tab(id: string, patch: Partial<OpenFile> = {}): OpenFile {
|
||||
return {
|
||||
id,
|
||||
filePath: '/repo/a.ts',
|
||||
relativePath: 'a.ts',
|
||||
worktreeId: 'wt-1',
|
||||
language: 'typescript',
|
||||
isDirty: false,
|
||||
mode: 'edit',
|
||||
...patch
|
||||
}
|
||||
}
|
||||
|
||||
// Cover shared workspace models, clean tabs and non-edit surfaces where the old entry points differ.
|
||||
const FIXTURE: OpenFile[] = [
|
||||
tab('/repo/a.ts', { isDirty: true }),
|
||||
tab('editor:wt-2:local:/repo/a.ts', { worktreeId: 'wt-2', isDirty: true }),
|
||||
tab('/repo/b.md', { filePath: '/repo/b.md', language: 'markdown' }),
|
||||
tab('wt-1::diff::unstaged::a.ts', { mode: 'diff', diffSource: 'unstaged', isDirty: true })
|
||||
]
|
||||
const IDS = [...FIXTURE.map((file) => file.id), 'not-open']
|
||||
|
||||
function seed(): AppState {
|
||||
useAppStore.setState({ openFiles: FIXTURE })
|
||||
return useAppStore.getState()
|
||||
}
|
||||
|
||||
const SHARED: EditorBufferViewIndex = {
|
||||
editorBufferIdOf: { a: 'rec', b: 'rec', c: 'c' },
|
||||
editorBufferViews: { rec: ['a', 'b'], c: ['c'] }
|
||||
}
|
||||
const SHARED_FILES = [tab('a', { isDirty: true }), tab('b', { isDirty: true }), tab('c')]
|
||||
|
||||
describe('editor buffer entry points return the per-tab answer', () => {
|
||||
beforeEach(() => {
|
||||
useAppStore.setState(useAppStore.getInitialState(), true)
|
||||
quiesce.mockClear()
|
||||
})
|
||||
|
||||
it.each(IDS)('needsSavePromptOnClose(%s) equals the tab dirty flag', (id) => {
|
||||
const state = seed()
|
||||
const old = state.openFiles.find((file) => file.id === id)?.isDirty === true
|
||||
expect(needsSavePromptOnClose(state, id)).toBe(old)
|
||||
})
|
||||
|
||||
it('restartSaveTargets equals the dirty tabs', () => {
|
||||
const state = seed()
|
||||
expect(restartSaveTargets(state)).toEqual(state.openFiles.filter((file) => file.isDirty))
|
||||
})
|
||||
|
||||
it.each([
|
||||
[false, ['rich-new', 'csv']],
|
||||
[true, ['rich-new']]
|
||||
])('record flush keeps the per-tab semantics (autosave=%s)', (autosave, expected) => {
|
||||
const state = seed()
|
||||
const calls: string[] = []
|
||||
const remove = [
|
||||
registerPendingEditorFlush('/repo/a.ts', () => calls.push('rich-old')),
|
||||
registerPendingEditorFlush('/repo/a.ts', () => calls.push('rich-new')),
|
||||
registerPendingEditorFlush(
|
||||
'/repo/a.ts',
|
||||
() => calls.push('csv'),
|
||||
() => true
|
||||
),
|
||||
registerPendingEditorFlush('editor:wt-2:local:/repo/a.ts', () => calls.push('other-tab'))
|
||||
]
|
||||
try {
|
||||
flushPendingEditorBuffer(state, '/repo/a.ts', autosave)
|
||||
expect(calls).toEqual(expected)
|
||||
expect(hasPendingEditorBufferChange(state, '/repo/a.ts')).toBe(true)
|
||||
expect(hasPendingEditorBufferChange(state, 'editor:wt-2:local:/repo/a.ts')).toBe(false)
|
||||
} finally {
|
||||
remove.forEach((unregister) => unregister())
|
||||
}
|
||||
})
|
||||
|
||||
it('Discard quiesces, clears dirty and the draft, then closes, as before', async () => {
|
||||
seed()
|
||||
useAppStore.getState().setEditorDraft('/repo/a.ts', 'edited')
|
||||
|
||||
await discardEditorFileChangesAndClose('/repo/a.ts')
|
||||
|
||||
expect(quiesce).toHaveBeenCalledWith({ fileId: '/repo/a.ts', discard: true })
|
||||
const state = useAppStore.getState()
|
||||
expect(state.openFiles.some((file) => file.id === '/repo/a.ts')).toBe(false)
|
||||
expect(state.editorDrafts['/repo/a.ts']).toBeUndefined()
|
||||
expect(state.editorBuffers['editor:wt-2:local:/repo/a.ts']?.isDirty).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('entry point bodies once views share a record', () => {
|
||||
const state = { openFiles: SHARED_FILES, ...SHARED }
|
||||
|
||||
it('prompts only on the last open view, whatever order a batch closes them in', () => {
|
||||
for (const [first, last] of [
|
||||
['a', 'b'],
|
||||
['b', 'a']
|
||||
]) {
|
||||
expect(needsSavePromptOnClose(state, first)).toBe(false)
|
||||
const afterFirstClosed = {
|
||||
openFiles: SHARED_FILES.filter((file) => file.id !== first),
|
||||
editorBufferIdOf: { [last]: 'rec', c: 'c' },
|
||||
editorBufferViews: { rec: [last], c: ['c'] }
|
||||
}
|
||||
expect(needsSavePromptOnClose(afterFirstClosed, last)).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('restart save writes one view per record', () => {
|
||||
expect(restartSaveTargets(state).map((file) => file.id)).toEqual(['a'])
|
||||
})
|
||||
|
||||
it('flushes pending text from every view of the record', () => {
|
||||
const calls: string[] = []
|
||||
const remove = [
|
||||
registerPendingEditorFlush('a', () => calls.push('a')),
|
||||
registerPendingEditorFlush(
|
||||
'b',
|
||||
() => calls.push('b'),
|
||||
() => true
|
||||
),
|
||||
registerPendingEditorFlush('c', () => calls.push('c'))
|
||||
]
|
||||
try {
|
||||
expect(hasPendingEditorBufferChange(state, 'a')).toBe(true)
|
||||
flushPendingEditorBuffer(state, 'a')
|
||||
expect(calls).toEqual(['a', 'b'])
|
||||
} finally {
|
||||
remove.forEach((unregister) => unregister())
|
||||
}
|
||||
})
|
||||
})
|
||||
+1
-59
@@ -6,12 +6,7 @@ import type { OpenFile } from '@/store/slices/editor/types/open-file'
|
||||
import { createEditorModelRegistry } from '@/lib/editor-model-registry'
|
||||
import { attachClosedEditorTabCleanup } from '@/components/editor/model-lifetime/retention/closed-editor-tab-controller'
|
||||
import { toEditorModelUri } from '@/components/editor/model-lifetime/identity/editor-model-uri'
|
||||
import {
|
||||
scrollTopCache,
|
||||
editorSelectionCache,
|
||||
pdfViewPositionCache,
|
||||
setWithLRU
|
||||
} from '@/lib/scroll-cache'
|
||||
import { scrollTopCache, editorSelectionCache, pdfViewPositionCache } from '@/lib/scroll-cache'
|
||||
|
||||
const disposeOwners: (() => void)[] = []
|
||||
afterEach(() => {
|
||||
@@ -58,59 +53,6 @@ function open(path: string, text = 'original') {
|
||||
}
|
||||
}
|
||||
|
||||
it('retires the actual model while retaining existing bounded scroll, selection and PDF state', async () => {
|
||||
const path = '/tradeoff/view-state.txt'
|
||||
const owner = open(path)
|
||||
const selection = [
|
||||
{
|
||||
selectionStartLineNumber: 3,
|
||||
selectionStartColumn: 2,
|
||||
positionLineNumber: 3,
|
||||
positionColumn: 7
|
||||
}
|
||||
]
|
||||
setWithLRU(scrollTopCache, path, 234)
|
||||
setWithLRU(editorSelectionCache, path, selection)
|
||||
setWithLRU(pdfViewPositionCache, `${path}:pdf`, { pageNumber: 2, top: 12, left: 0 })
|
||||
await owner.close()
|
||||
expect(scrollTopCache.get(path)).toBe(234)
|
||||
expect(editorSelectionCache.get(path)).toEqual(selection)
|
||||
expect(pdfViewPositionCache.get(`${path}:pdf`)).toEqual({ pageNumber: 2, top: 12, left: 0 })
|
||||
})
|
||||
|
||||
it('preserves the existing 20-entry LRU across 40 closed models without retaining the models', async () => {
|
||||
for (let index = 0; index < 40; index += 1) {
|
||||
const path = `/tradeoff/lru-${index}.txt`
|
||||
const owner = open(path)
|
||||
setWithLRU(scrollTopCache, path, index)
|
||||
await owner.close()
|
||||
}
|
||||
expect(monaco.editor.getModels()).toHaveLength(0)
|
||||
expect(scrollTopCache.size).toBe(20)
|
||||
expect(scrollTopCache.get('/tradeoff/lru-39.txt')).toBe(39)
|
||||
expect(scrollTopCache.has('/tradeoff/lru-0.txt')).toBe(false)
|
||||
})
|
||||
|
||||
it('measures the existing Monaco large-file undo retention limit', async () => {
|
||||
const path = '/tradeoff/undo-large-file.txt'
|
||||
const owner = open(path, 'x'.repeat(10 * 1024 * 1024 + 1))
|
||||
owner.model.pushEditOperations(
|
||||
[],
|
||||
[{ range: new monaco.Range(1, 1, 1, 1), text: 'saved ' }],
|
||||
() => null
|
||||
)
|
||||
owner.model.pushStackElement()
|
||||
expect(owner.model.canUndo()).toBe(true)
|
||||
const content = owner.model.getValue()
|
||||
await owner.close()
|
||||
const reopened = monaco.editor.createModel(
|
||||
content,
|
||||
'plaintext',
|
||||
monaco.Uri.parse(toEditorModelUri(path))
|
||||
)
|
||||
expect(reopened.canUndo()).toBe(false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
'/tradeoff/undo-posix.txt',
|
||||
'file:///C:/tradeoff/undo-file-uri.txt',
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { IpynbCellOutputs } from '../outputs/IpynbCellOutputs'
|
||||
import { IpynbCellSource } from '../cells/IpynbCellEditor'
|
||||
|
||||
import type { IpynbCell, IpynbOutput } from './ipynb-parse'
|
||||
|
||||
@@ -20,115 +19,9 @@ function cell(kind: IpynbCell['kind'], source: string, outputs: IpynbOutput[] =
|
||||
return { id: 'cell-1', kind, language: 'python', source, executionCount: 1, outputs }
|
||||
}
|
||||
|
||||
function renderSource(target: IpynbCell, onActivate = vi.fn()) {
|
||||
render(
|
||||
<IpynbCellSource
|
||||
modelKey={null}
|
||||
cell={target}
|
||||
source={target.source}
|
||||
active={false}
|
||||
onActivate={onActivate}
|
||||
onDeactivate={vi.fn()}
|
||||
onChange={vi.fn()}
|
||||
/>
|
||||
)
|
||||
return onActivate
|
||||
}
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
describe('notebook cell source', () => {
|
||||
it('shows markdown as a document and edits only on double-click or Enter', () => {
|
||||
const onActivate = renderSource(cell('markdown', '# Report'))
|
||||
const preview = screen.getByRole('button')
|
||||
expect(screen.getByRole('heading', { name: 'Report' })).toBeTruthy()
|
||||
|
||||
fireEvent.click(preview)
|
||||
expect(onActivate).not.toHaveBeenCalled()
|
||||
fireEvent.doubleClick(preview)
|
||||
fireEvent.keyDown(preview, { key: 'Enter' })
|
||||
expect(onActivate).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('activates code cells on primary press so a collapsing neighbour cannot swallow the click', () => {
|
||||
const onActivate = renderSource(cell('code', 'print(1)'))
|
||||
const preview = screen.getByRole('button')
|
||||
fireEvent.mouseDown(preview, { button: 2 })
|
||||
expect(onActivate).not.toHaveBeenCalled()
|
||||
fireEvent.mouseDown(preview, { button: 0 })
|
||||
expect(onActivate).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
|
||||
describe('notebook code preview', () => {
|
||||
it('shows source as literal text until Monaco colorizes it', () => {
|
||||
renderSource(cell('code', 'x = "<b>hi</b>"\n'))
|
||||
expect(screen.getByText('x = "<b>hi</b>"')).toBeTruthy()
|
||||
expect(document.querySelector('b')).toBeNull()
|
||||
// The trailing newline keeps its own row, matching the Monaco model.
|
||||
expect(document.querySelectorAll('code')).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('notebook outputs', () => {
|
||||
it('renders only the richest representation of a display bundle', () => {
|
||||
render(
|
||||
<IpynbCellOutputs
|
||||
cell={cell('code', 'df', [
|
||||
{
|
||||
kind: 'display',
|
||||
outputType: 'execute_result',
|
||||
executionCount: 1,
|
||||
items: [
|
||||
{ mime: 'text/html', value: '<table><tr><td>rich</td></tr></table>' },
|
||||
{ mime: 'text/plain', value: 'plain fallback' }
|
||||
]
|
||||
}
|
||||
])}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByTitle('Notebook HTML output').getAttribute('srcdoc')).toContain('rich')
|
||||
expect(screen.queryByText('plain fallback')).toBeNull()
|
||||
})
|
||||
|
||||
it('skips MIME types it cannot render in favour of the text fallback', () => {
|
||||
render(
|
||||
<IpynbCellOutputs
|
||||
cell={cell('code', 'w', [
|
||||
{
|
||||
kind: 'display',
|
||||
outputType: 'display_data',
|
||||
executionCount: null,
|
||||
items: [
|
||||
{ mime: 'application/vnd.custom-widget', value: {} },
|
||||
{ mime: 'text/plain', value: 'widget repr' }
|
||||
]
|
||||
}
|
||||
])}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByText('widget repr')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('colours ANSI tracebacks instead of printing escape codes', () => {
|
||||
render(
|
||||
<IpynbCellOutputs
|
||||
cell={cell('code', '1/0', [
|
||||
{
|
||||
kind: 'error',
|
||||
name: 'ZeroDivisionError',
|
||||
message: 'division by zero',
|
||||
traceback: '\u001b[0;31mZeroDivisionError\u001b[0m: division by zero'
|
||||
}
|
||||
])}
|
||||
/>
|
||||
)
|
||||
const name = screen.getByText('ZeroDivisionError')
|
||||
expect(name.tagName).toBe('SPAN')
|
||||
expect(name.style.color).not.toBe('')
|
||||
expect(document.body.textContent).not.toContain('\u001b')
|
||||
})
|
||||
|
||||
it('sandboxes HTML output behind a no-network CSP and strips scripts', () => {
|
||||
render(
|
||||
<IpynbCellOutputs
|
||||
|
||||
-136
@@ -1,136 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Editor } from '@tiptap/react'
|
||||
import {
|
||||
commitRichMarkdownSerialization,
|
||||
type RichMarkdownReconcileRefs
|
||||
} from './rich-markdown-serialization-commit'
|
||||
import { handleRichMarkdownSaveShortcut } from '../commands/rich-markdown-save-shortcut'
|
||||
import type { KeyHandlerContext } from '../commands/rich-markdown-key-handler-context'
|
||||
|
||||
// Mirror style rewrites and production EOF normalization so the injected safety reparse agrees with the editor without a DOM.
|
||||
function fakeCanonicalize(md: string): string {
|
||||
return md
|
||||
.replace(/__([^_]+)__/g, '**$1**')
|
||||
.replace(/_([^_]+)_/g, '*$1*')
|
||||
.replace(/\n+$/, '')
|
||||
}
|
||||
const roundTrip = (md: string): string => fakeCanonicalize(md)
|
||||
|
||||
function refs(originalSource: string, baseCanonical: string): RichMarkdownReconcileRefs {
|
||||
return {
|
||||
originalSourceRef: { current: originalSource },
|
||||
baseCanonicalRef: { current: baseCanonical },
|
||||
lastCommittedMarkdownRef: { current: '' }
|
||||
}
|
||||
}
|
||||
|
||||
function fakeEditor(getMarkdown: () => string): Editor {
|
||||
return { getMarkdown } as unknown as Editor
|
||||
}
|
||||
|
||||
describe('commitRichMarkdownSerialization (shared disk-bound serialize chokepoint)', () => {
|
||||
it('persists SOURCE-PRESERVING bytes, not raw getMarkdown (regression gate for #6080)', () => {
|
||||
const r = refs('# Title\n\n_word_\n', '# Title\n\n*word*')
|
||||
const editor = fakeEditor(() => '# Title!\n\n*word*')
|
||||
|
||||
const { markdown, didSerialize } = commitRichMarkdownSerialization(editor, r, roundTrip)
|
||||
|
||||
// Fails if this site reverted to raw getMarkdown() (would emit *word*).
|
||||
expect(markdown).toBe('# Title!\n\n_word_\n')
|
||||
expect(didSerialize).toBe(true)
|
||||
})
|
||||
|
||||
it('preserves source EOL and advances refs when reconciliation throws', () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const r = refs('# 이전\r\n\r\n_강조_\r\n', '# 이전\n\n*강조*')
|
||||
const editor = fakeEditor(() => '# 변경\n\n*강조*')
|
||||
const throwingRoundTrip = vi.fn(() => {
|
||||
throw new Error('round-trip failed')
|
||||
})
|
||||
|
||||
try {
|
||||
const { markdown, didSerialize } = commitRichMarkdownSerialization(
|
||||
editor,
|
||||
r,
|
||||
throwingRoundTrip
|
||||
)
|
||||
|
||||
expect(markdown).toBe('# 변경\r\n\r\n*강조*')
|
||||
expect(didSerialize).toBe(true)
|
||||
expect(r.originalSourceRef.current).toBe(markdown)
|
||||
expect(r.baseCanonicalRef.current).toBe('# 변경\n\n*강조*')
|
||||
expect(r.lastCommittedMarkdownRef.current).toBe(markdown)
|
||||
expect(throwingRoundTrip).toHaveBeenCalledTimes(1)
|
||||
expect(consoleError).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
consoleError.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleRichMarkdownSaveShortcut (Cmd/Ctrl+S persistence site)', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
function saveEvent(): KeyboardEvent & { preventDefault: ReturnType<typeof vi.fn> } {
|
||||
return {
|
||||
key: 's',
|
||||
code: 'KeyS',
|
||||
metaKey: true,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
isComposing: false,
|
||||
preventDefault: vi.fn()
|
||||
} as unknown as KeyboardEvent & { preventDefault: ReturnType<typeof vi.fn> }
|
||||
}
|
||||
|
||||
function saveContext(editor: Editor | null): {
|
||||
ctx: KeyHandlerContext
|
||||
onSave: ReturnType<typeof vi.fn>
|
||||
onContentChange: ReturnType<typeof vi.fn>
|
||||
flush: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
const onSave = vi.fn()
|
||||
const onContentChange = vi.fn()
|
||||
const flush = vi.fn()
|
||||
const ctx = {
|
||||
editorRef: { current: editor },
|
||||
originalSourceRef: { current: '# Title\n\n_word_\n' },
|
||||
baseCanonicalRef: { current: '# Title\n\n*word*' },
|
||||
lastCommittedMarkdownRef: { current: '' },
|
||||
reconcileRoundTripRef: { current: roundTrip },
|
||||
onContentChangeRef: { current: onContentChange },
|
||||
onSaveRef: { current: onSave },
|
||||
flushPendingSerialization: flush
|
||||
} as unknown as KeyHandlerContext
|
||||
return { ctx, onSave, onContentChange, flush }
|
||||
}
|
||||
|
||||
it('flushes then saves SOURCE-PRESERVING bytes on Cmd+S (mac)', () => {
|
||||
vi.stubGlobal('navigator', { userAgent: 'Macintosh' })
|
||||
const editor = fakeEditor(() => '# Title!\n\n*word*')
|
||||
const { ctx, onSave, onContentChange, flush } = saveContext(editor)
|
||||
const event = saveEvent()
|
||||
|
||||
expect(handleRichMarkdownSaveShortcut(ctx, event)).toBe(true)
|
||||
expect(event.preventDefault).toHaveBeenCalled()
|
||||
expect(flush).toHaveBeenCalledTimes(1)
|
||||
expect(onSave).toHaveBeenCalledWith('# Title!\n\n_word_\n')
|
||||
expect(onContentChange).toHaveBeenCalledWith('# Title!\n\n_word_\n')
|
||||
})
|
||||
|
||||
it('skips the save when the flush rejected the pending edit', () => {
|
||||
vi.stubGlobal('navigator', { userAgent: 'Macintosh' })
|
||||
const editor = fakeEditor(() => '# Title!\n\n*word*')
|
||||
const { ctx, onSave, onContentChange, flush } = saveContext(editor)
|
||||
flush.mockReturnValue(true)
|
||||
const event = saveEvent()
|
||||
|
||||
expect(handleRichMarkdownSaveShortcut(ctx, event)).toBe(true)
|
||||
expect(event.preventDefault).toHaveBeenCalled()
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
expect(onContentChange).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
-57
@@ -86,61 +86,4 @@ describe('task continuation inline markup', () => {
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it.each([
|
||||
'- [ ] Open [API\n docs](https://example.com/docs) now\n- [x] Done',
|
||||
'- Parent\n - [ ] Open [API\n docs](https://example.com/docs) now\n - [x] Done',
|
||||
'> - [ ] Open [API\n> docs](https://example.com/docs) now\n> - [x] Done',
|
||||
'- [ ] Parent\n - [ ] Open [API\n docs](https://example.com/docs) now\n - [x] Done'
|
||||
])('keeps the wrapped link in its container across canonical serialization: %s', (source) => {
|
||||
const editor = openMarkdown(source)
|
||||
try {
|
||||
expect(markedText(editor, 'link')).toEqual(['API\ndocs'])
|
||||
const reopened = openMarkdown(editor.getMarkdown())
|
||||
try {
|
||||
reopened.state.doc.check()
|
||||
expect(markedText(reopened, 'link')).toEqual(['API\ndocs'])
|
||||
} finally {
|
||||
reopened.destroy()
|
||||
}
|
||||
} finally {
|
||||
editor.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps blank-separated paragraphs from completing a link', () => {
|
||||
const editor = openMarkdown('- [ ] Open [API\n\n docs](https://example.com/docs) now')
|
||||
try {
|
||||
expect(editor.state.doc.firstChild?.firstChild?.childCount).toBe(2)
|
||||
expect(markedText(editor, 'link')).toEqual(['https://example.com/docs'])
|
||||
} finally {
|
||||
editor.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps a link wholly in the continuation paragraph separate', () => {
|
||||
const editor = openMarkdown('- [ ] Open\n [API docs](https://example.com/docs) now')
|
||||
try {
|
||||
expect(editor.state.doc.firstChild?.firstChild?.childCount).toBe(2)
|
||||
expect(markedText(editor, 'link')).toEqual(['API docs'])
|
||||
} finally {
|
||||
editor.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves an explicit hard break through task serialization', () => {
|
||||
const editor = openMarkdown('- [ ] First \n continuation\n- [x] Done')
|
||||
try {
|
||||
const reopened = openMarkdown(editor.getMarkdown())
|
||||
try {
|
||||
const first = reopened.state.doc.firstChild?.firstChild?.firstChild
|
||||
expect(first?.childCount).toBe(3)
|
||||
expect(first?.child(1).type.name).toBe('hardBreak')
|
||||
} finally {
|
||||
reopened.destroy()
|
||||
}
|
||||
} finally {
|
||||
editor.destroy()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
-16
@@ -151,20 +151,4 @@ describe('review submission owner', () => {
|
||||
})
|
||||
expect(highlightedText(review.editor)).toEqual(['abc', 'xyz'])
|
||||
})
|
||||
|
||||
it('preserves a failed draft for retry', async () => {
|
||||
const failure = mountReview()
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
try {
|
||||
const failedSubmission = failure.result.current.submitAnnotation('Review abc')
|
||||
await act(async () => {
|
||||
failure.pending.resolve(null)
|
||||
await failedSubmission
|
||||
})
|
||||
expect(failure.result.current.annotationPopover).toEqual(target)
|
||||
expect(highlightedText(failure.editor)).toEqual([])
|
||||
} finally {
|
||||
error.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
-41
@@ -75,47 +75,6 @@ describe('rich markdown editing with Find open', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves selection when edits remove every match and later restore one', () => {
|
||||
vi.useFakeTimers()
|
||||
const { editor, hook, scrollTo, dispose } = mountSearch()
|
||||
try {
|
||||
scrollTo.mockClear()
|
||||
act(() => editor.commands.setContent('<p>No results</p><p>End</p>'))
|
||||
expect(hook.result.current.searchState.matchCount).toBe(0)
|
||||
act(() => editor.commands.setTextSelection(editor.state.doc.content.size - 1))
|
||||
act(() => editor.commands.insertContent(' beta'))
|
||||
expect(hook.result.current.searchState.matchCount).toBe(1)
|
||||
expect(editor.state.selection.empty).toBe(true)
|
||||
expect(editor.state.selection.from).toBe(editor.state.doc.content.size - 1)
|
||||
expect(scrollTo).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('still navigates on Next with only one match, and advances after Replace', () => {
|
||||
vi.useFakeTimers()
|
||||
const { editor, hook, scrollTo, dispose } = mountSearch()
|
||||
try {
|
||||
act(() => hook.result.current.searchActions.setReplaceQuery('changed'))
|
||||
act(() => hook.result.current.searchActions.replaceCurrentMatch())
|
||||
expect(editor.getText()).toBe('changed beta\n\nEdit here')
|
||||
expect(hook.result.current.searchState.matchCount).toBe(1)
|
||||
expect(
|
||||
editor.state.doc.textBetween(editor.state.selection.from, editor.state.selection.to)
|
||||
).toBe('beta')
|
||||
act(() => editor.commands.setTextSelection(editor.state.doc.content.size - 1))
|
||||
scrollTo.mockClear()
|
||||
act(() => hook.result.current.searchActions.moveToMatch(1))
|
||||
expect(
|
||||
editor.state.doc.textBetween(editor.state.selection.from, editor.state.selection.to)
|
||||
).toBe('beta')
|
||||
expect(scrollTo).toHaveBeenCalledOnce()
|
||||
} finally {
|
||||
dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not apply delayed search navigation after focus returns to the document', () => {
|
||||
vi.useFakeTimers()
|
||||
const { editor, hook, scrollTo, dispose } = mountSearch()
|
||||
|
||||
-170
@@ -1,170 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Editor } from '@tiptap/core'
|
||||
import { createRichMarkdownExtensions } from '../schema/rich-markdown-extensions'
|
||||
import { createRichMarkdownEditorCodec } from '../document/rich-markdown-source-transport'
|
||||
import { RichMarkdownTableControls } from './RichMarkdownTableControls'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
|
||||
const TABLE = `| A | B |
|
||||
| --- | --- |
|
||||
| a1 | b1 |
|
||||
`
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(window, 'api', {
|
||||
configurable: true,
|
||||
value: {
|
||||
ui: {
|
||||
onRichMarkdownContextCommand: vi.fn(() => vi.fn()),
|
||||
setRichMarkdownContextMenuTarget: vi.fn()
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('RichMarkdownTableControls', () => {
|
||||
it('does not mutate header cells before ProseMirror handles pointer input', async () => {
|
||||
const scrollContainer = document.createElement('div')
|
||||
const editorElement = document.createElement('div')
|
||||
const controlsElement = document.createElement('div')
|
||||
scrollContainer.append(editorElement, controlsElement)
|
||||
document.body.append(scrollContainer)
|
||||
const editor = new Editor({
|
||||
element: editorElement,
|
||||
extensions: createRichMarkdownExtensions({ codec: createRichMarkdownEditorCodec() }),
|
||||
content: TABLE,
|
||||
contentType: 'markdown'
|
||||
})
|
||||
const view = render(
|
||||
<TooltipProvider>
|
||||
<RichMarkdownTableControls
|
||||
editor={editor}
|
||||
scrollContainerRef={{ current: scrollContainer }}
|
||||
/>
|
||||
</TooltipProvider>,
|
||||
{ container: controlsElement }
|
||||
)
|
||||
try {
|
||||
const header = editorElement.querySelector('th')
|
||||
if (!header) {
|
||||
throw new Error('Expected a table header cell')
|
||||
}
|
||||
let headerPosition = 0
|
||||
editor.state.doc.descendants((node, position) => {
|
||||
if (node.type.spec.tableRole === 'header_cell') {
|
||||
headerPosition = position
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
fireEvent.pointerDown(header, { clientX: 20, clientY: 20 })
|
||||
|
||||
expect(editor.state.doc.nodeAt(headerPosition)?.attrs.colwidth).toBeNull()
|
||||
} finally {
|
||||
view.unmount()
|
||||
editor.destroy()
|
||||
scrollContainer.remove()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps an add control reachable after scrolling without another pointer move', async () => {
|
||||
const scrollContainer = document.createElement('div')
|
||||
const editorElement = document.createElement('div')
|
||||
const controlsElement = document.createElement('div')
|
||||
scrollContainer.append(editorElement, controlsElement)
|
||||
document.body.append(scrollContainer)
|
||||
Object.defineProperties(scrollContainer, {
|
||||
clientHeight: { configurable: true, value: 100 },
|
||||
clientWidth: { configurable: true, value: 100 }
|
||||
})
|
||||
vi.spyOn(scrollContainer, 'getBoundingClientRect').mockReturnValue({
|
||||
bottom: 100,
|
||||
height: 100,
|
||||
left: 0,
|
||||
right: 100,
|
||||
top: 0,
|
||||
width: 100,
|
||||
x: 0,
|
||||
y: 0,
|
||||
toJSON: () => ({})
|
||||
})
|
||||
const editor = new Editor({
|
||||
element: editorElement,
|
||||
extensions: createRichMarkdownExtensions({ codec: createRichMarkdownEditorCodec() }),
|
||||
content: TABLE,
|
||||
contentType: 'markdown'
|
||||
})
|
||||
let bodyTextPosition = 0
|
||||
editor.state.doc.descendants((node, position) => {
|
||||
if (node.isText && node.text === 'a1') {
|
||||
bodyTextPosition = position
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
editor.commands.setTextSelection(bodyTextPosition)
|
||||
const cell = editorElement.querySelector('td')!
|
||||
const row = cell.parentElement!
|
||||
const table = cell.closest('table')!
|
||||
vi.spyOn(cell, 'getBoundingClientRect').mockImplementation(() => ({
|
||||
bottom: 100,
|
||||
height: 50,
|
||||
left: -scrollContainer.scrollLeft,
|
||||
right: 50 - scrollContainer.scrollLeft,
|
||||
top: 50,
|
||||
width: 50,
|
||||
x: -scrollContainer.scrollLeft,
|
||||
y: 50,
|
||||
toJSON: () => ({})
|
||||
}))
|
||||
vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => ({
|
||||
bottom: 100,
|
||||
height: 50,
|
||||
left: -scrollContainer.scrollLeft,
|
||||
right: 150 - scrollContainer.scrollLeft,
|
||||
top: 50,
|
||||
width: 150,
|
||||
x: -scrollContainer.scrollLeft,
|
||||
y: 50,
|
||||
toJSON: () => ({})
|
||||
}))
|
||||
vi.spyOn(table, 'getBoundingClientRect').mockImplementation(() => ({
|
||||
bottom: 100,
|
||||
height: 100,
|
||||
left: -scrollContainer.scrollLeft,
|
||||
right: 150 - scrollContainer.scrollLeft,
|
||||
top: 0,
|
||||
width: 150,
|
||||
x: -scrollContainer.scrollLeft,
|
||||
y: 0,
|
||||
toJSON: () => ({})
|
||||
}))
|
||||
const view = render(
|
||||
<TooltipProvider>
|
||||
<RichMarkdownTableControls
|
||||
editor={editor}
|
||||
scrollContainerRef={{ current: scrollContainer }}
|
||||
/>
|
||||
</TooltipProvider>,
|
||||
{ container: controlsElement }
|
||||
)
|
||||
try {
|
||||
fireEvent.pointerMove(cell, { clientX: 20, clientY: 95 })
|
||||
await waitFor(() => expect(view.getByLabelText('Add row').style.width).toBe('92px'))
|
||||
|
||||
scrollContainer.scrollLeft = 100
|
||||
fireEvent.scroll(scrollContainer)
|
||||
await waitFor(() => expect(view.getByLabelText('Add row').style.width).toBe('46px'))
|
||||
} finally {
|
||||
view.unmount()
|
||||
editor.destroy()
|
||||
scrollContainer.remove()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -98,22 +98,6 @@ describe('binary editor save acquired owner at the final replace boundary', () =
|
||||
return queue.queueSave(file, '')
|
||||
}
|
||||
|
||||
it('keeps the captured destination and saves when authority and writer survive the upload', async () => {
|
||||
const saved = save()
|
||||
await started.promise
|
||||
expect(replace).not.toHaveBeenCalled()
|
||||
uploaded.resolve()
|
||||
await expect(saved).resolves.toBe('written')
|
||||
expect(replace).toHaveBeenCalledTimes(1)
|
||||
expect(writeBytes.mock.calls[0]?.[0]).toMatchObject({
|
||||
target: { kind: 'local' },
|
||||
worktreeId: WORKTREE_ID,
|
||||
worktreePath: '/repo'
|
||||
})
|
||||
expect(useAppStore.getState().openFiles.find((tab) => tab.id === fileId)?.isDirty).toBe(false)
|
||||
expect(editorBytesDocument(fileId)?.bytes).toEqual(draft.bytes)
|
||||
})
|
||||
|
||||
it('refuses the final replace if the acquired workspace changes during upload, retaining edits', async () => {
|
||||
const saved = save()
|
||||
await started.promise
|
||||
|
||||
@@ -30,21 +30,6 @@ function tab(id: string, patch: Partial<OpenFile> = {}): OpenFile {
|
||||
}
|
||||
}
|
||||
|
||||
function holdNextWrite(disk: FakeEditorDisk): () => void {
|
||||
let release = (): void => {}
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve
|
||||
})
|
||||
disk.fs.writeFile.mockImplementationOnce(
|
||||
async ({ filePath, content }: { filePath: string; content: string }) => {
|
||||
await gate
|
||||
disk.files.set(filePath, content)
|
||||
return { ok: true }
|
||||
}
|
||||
)
|
||||
return release
|
||||
}
|
||||
|
||||
describe('editor save queue: one autosave timer per record across its views', () => {
|
||||
let disk: FakeEditorDisk
|
||||
let store: ReturnType<typeof createEditorStore>
|
||||
@@ -94,28 +79,6 @@ describe('editor save queue: one autosave timer per record across its views', ()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('writes typing from two workspaces once, with the latest text, and cleans both views', async () => {
|
||||
type('w1', 'abc')
|
||||
await vi.advanceTimersByTimeAsync(DELAY_MS / 2)
|
||||
type('w2', 'abcd')
|
||||
await vi.advanceTimersByTimeAsync(DELAY_MS)
|
||||
|
||||
expect(writtenContents()).toEqual(['abcd'])
|
||||
expect(view('w1').isDirty).toBe(false)
|
||||
expect(view('w2').isDirty).toBe(false)
|
||||
expect(store.getState().editorDrafts).toEqual({})
|
||||
})
|
||||
|
||||
it('keeps the timer when a read-only view of the record follows the writable one', async () => {
|
||||
share([view('w1'), tab('log', { readOnly: true })])
|
||||
withLoadedBaselines(store, disk)
|
||||
type('w1', 'abc')
|
||||
await vi.advanceTimersByTimeAsync(DELAY_MS)
|
||||
|
||||
expect(writtenContents()).toEqual(['abc'])
|
||||
expect(view('log').isDirty).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the timer when the view that scheduled it closes', async () => {
|
||||
type('w1', 'abc')
|
||||
await vi.advanceTimersByTimeAsync(DELAY_MS / 2)
|
||||
@@ -140,24 +103,4 @@ describe('editor save queue: one autosave timer per record across its views', ()
|
||||
expect(view('w2').isDirty).toBe(true)
|
||||
}
|
||||
)
|
||||
|
||||
it("runs one view's Cmd+S that another view's settle waits behind", async () => {
|
||||
type('w1', 'a')
|
||||
const release = holdNextWrite(disk)
|
||||
const first = queue.queueSave(view('w1'), 'a')
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
type('w1', 'ab')
|
||||
const cmdS = queue.queueSave(view('w1'), 'ab')
|
||||
let settled = false
|
||||
const settle = queue.settleFileSaves('w2').then(() => {
|
||||
settled = true
|
||||
})
|
||||
|
||||
release()
|
||||
await settle
|
||||
expect(settled).toBe(true)
|
||||
expect(await Promise.all([first, cmdS])).toEqual(['written', 'written'])
|
||||
expect(writtenContents()).toEqual(['a', 'ab'])
|
||||
expect(view('w2').isDirty).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
-131
@@ -1,131 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import {
|
||||
projectQueuedMessageCards,
|
||||
queuedMessagesQueuePause,
|
||||
type QueuedMessageCard
|
||||
} from '../../../../shared/agent-session/view/structured-agent-session-queued-cards'
|
||||
import { NativeChatQueuedMessageList } from './NativeChatQueuedMessageList'
|
||||
import type { StructuredAgentSessionQueuedMessagesController } from './use-structured-agent-session-queued-messages'
|
||||
import type { AgentSessionQueuedMessage } from '../../../../shared/agent-session/requests/agent-session-queued-message-wire'
|
||||
import type { AgentSessionFailureFact } from '../../../../shared/agent-session/failures/agent-session-failure'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
updateSettings: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))
|
||||
// A card's sender line opens and names agents through modules this test does not exercise.
|
||||
vi.mock('@/lib/open-agent-message-sender', () => ({ openAgentMessageSender: vi.fn() }))
|
||||
vi.mock('@/runtime/structured-conversation-name', () => ({
|
||||
useStructuredChatTabConversationName: () => null
|
||||
}))
|
||||
vi.mock('../../store', () => {
|
||||
const state = { updateSettings: mocks.updateSettings }
|
||||
const useAppStore = (selector: (value: typeof state) => unknown): unknown => selector(state)
|
||||
useAppStore.getState = () => state
|
||||
return { useAppStore }
|
||||
})
|
||||
|
||||
function renderList(
|
||||
owner: StructuredAgentSessionQueuedMessagesController,
|
||||
agentName?: string,
|
||||
statedFailures?: readonly AgentSessionFailureFact[]
|
||||
) {
|
||||
return render(
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<NativeChatQueuedMessageList
|
||||
chatWorktreeId={null}
|
||||
controller={owner}
|
||||
agentName={agentName}
|
||||
statedFailures={statedFailures}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function controller(
|
||||
cards: QueuedMessageCard[],
|
||||
pause: { reason: string } | null = null,
|
||||
queueCapable = true
|
||||
): StructuredAgentSessionQueuedMessagesController & {
|
||||
steer: ReturnType<typeof vi.fn>
|
||||
remove: ReturnType<typeof vi.fn>
|
||||
edit: ReturnType<typeof vi.fn>
|
||||
resume: ReturnType<typeof vi.fn>
|
||||
clear: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
return {
|
||||
cards,
|
||||
queueCapable,
|
||||
clearCapable: cards.every((entry) => entry.hold !== 'sending'),
|
||||
editCapable: true,
|
||||
editor: undefined,
|
||||
pause,
|
||||
resume: vi.fn(async () => false),
|
||||
clear: vi.fn(async () => true),
|
||||
queuePending: null,
|
||||
pending: () => null,
|
||||
steer: vi.fn(async () => {}),
|
||||
remove: vi.fn(async () => {}),
|
||||
edit: vi.fn(async () => {}),
|
||||
steerHead: vi.fn(() => false),
|
||||
isWorking: false
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
it('omits saved uncertainty words while keeping the full returned card, barrier and actions', async () => {
|
||||
const saved: AgentSessionQueuedMessage = {
|
||||
messageId: 'saved',
|
||||
position: 1,
|
||||
state: 'returned',
|
||||
returnedReason: "Couldn't confirm whether this was sent. It hasn't been resent.",
|
||||
returnedRejection: { kind: 'unconfirmed' },
|
||||
body: {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [
|
||||
{ type: 'text', text: 'Original full prose before the image.' },
|
||||
{ type: 'image-ref', path: '/tmp/saved.png' },
|
||||
{ type: 'text', text: 'Original full prose after the image.' }
|
||||
]
|
||||
}
|
||||
}
|
||||
const original = structuredClone(saved)
|
||||
const cards = projectQueuedMessageCards(
|
||||
[saved, { ...saved, messageId: 'later', position: 2, state: 'waiting' }],
|
||||
[],
|
||||
{}
|
||||
)
|
||||
const pause = queuedMessagesQueuePause(cards, { reason: 'stopped' })
|
||||
expect(
|
||||
cards.map(({ messageId, hold, resumeEligible }) => ({ messageId, hold, resumeEligible }))
|
||||
).toEqual([
|
||||
{ messageId: 'saved', hold: 'returned', resumeEligible: undefined },
|
||||
{ messageId: 'later', hold: 'behind-returned', resumeEligible: undefined }
|
||||
])
|
||||
expect(pause).toBeNull()
|
||||
const owner = controller(cards, pause)
|
||||
renderList(owner, 'Claude', [{ kind: 'unconfirmed' }])
|
||||
const row = screen.getAllByRole('listitem')[0]!
|
||||
expect(row.dataset.queuedMessageId).toBe('saved')
|
||||
expect(row.dataset.queuedMessageState).toBe('returned')
|
||||
expect(row.textContent).toContain('Original full prose before the image.')
|
||||
expect(row.textContent).toContain('Original full prose after the image.')
|
||||
expect(cards[0]?.images).toEqual([{ type: 'image-ref', path: '/tmp/saved.png' }])
|
||||
expect(row.textContent).not.toContain('confirm')
|
||||
expect(row.textContent).not.toContain('not sent')
|
||||
expect(screen.queryByRole('button', { name: 'Resume' })).toBeNull()
|
||||
fireEvent.click(within(row).getByRole('button', { name: 'Send' }))
|
||||
fireEvent.click(within(row).getByRole('button', { name: 'Delete' }))
|
||||
fireEvent.pointerDown(within(row).getByRole('button', { name: 'More actions' }))
|
||||
fireEvent.click(await screen.findByRole('menuitem', { name: 'Edit message' }))
|
||||
expect(owner.steer).toHaveBeenCalledExactlyOnceWith('saved')
|
||||
expect(owner.remove).toHaveBeenCalledExactlyOnceWith('saved')
|
||||
expect(owner.edit).toHaveBeenCalledExactlyOnceWith('saved')
|
||||
expect(saved).toEqual(original)
|
||||
})
|
||||
@@ -1,182 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { LinkActionRequest } from '@/components/link-actions/link-action-request'
|
||||
import type * as HttpLinkDestinations from '@/lib/http-link-destinations'
|
||||
import type { HttpLinkActionDestinations } from '@/lib/http-link-destinations'
|
||||
import { handleNativeChatWebLink } from './native-chat-web-link-actions'
|
||||
|
||||
const mocks = vi.hoisted(() => ({ openRoutedHttpLink: vi.fn() }))
|
||||
|
||||
vi.mock('@/lib/http-link-destinations', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof HttpLinkDestinations>()),
|
||||
openRoutedHttpLink: mocks.openRoutedHttpLink
|
||||
}))
|
||||
|
||||
function stubPlatform(isMac: boolean): void {
|
||||
vi.stubGlobal('navigator', { userAgent: isMac ? 'Mac OS X' : 'Windows NT 10.0' })
|
||||
}
|
||||
|
||||
type ClickInit = {
|
||||
metaKey?: boolean
|
||||
ctrlKey?: boolean
|
||||
shiftKey?: boolean
|
||||
altKey?: boolean
|
||||
button?: number
|
||||
}
|
||||
|
||||
function click(init: ClickInit = {}) {
|
||||
return {
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
button: 0,
|
||||
clientX: 120,
|
||||
clientY: 240,
|
||||
preventDefault: vi.fn(),
|
||||
...init
|
||||
}
|
||||
}
|
||||
|
||||
function deps(
|
||||
overrides: {
|
||||
destinations?: HttpLinkActionDestinations
|
||||
actionsEnabled?: boolean
|
||||
} = {}
|
||||
) {
|
||||
const requests: LinkActionRequest[] = []
|
||||
return {
|
||||
requests,
|
||||
deps: {
|
||||
worktreeId: 'wt-1',
|
||||
sourceOwner: { kind: 'local' } as const,
|
||||
destinations: overrides.destinations ?? { primary: 'system', alternate: 'orca' },
|
||||
actionsEnabled: overrides.actionsEnabled ?? true,
|
||||
restoreFocus: vi.fn(),
|
||||
request: (request: LinkActionRequest) => requests.push(request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('handleNativeChatWebLink', () => {
|
||||
it('anchors keyboard activation to the focused link', () => {
|
||||
stubPlatform(true)
|
||||
const { deps: d, requests } = deps()
|
||||
handleNativeChatWebLink(
|
||||
{
|
||||
...click(),
|
||||
detail: 0,
|
||||
currentTarget: {
|
||||
getBoundingClientRect: () => ({ left: 80, bottom: 160 }) as DOMRect
|
||||
}
|
||||
},
|
||||
'https://example.com',
|
||||
d
|
||||
)
|
||||
expect(requests[0]).toMatchObject({ anchorX: 80, anchorY: 160 })
|
||||
})
|
||||
|
||||
it('opens the destination popover on a plain click', () => {
|
||||
stubPlatform(true)
|
||||
const { deps: d, requests } = deps()
|
||||
const event = click()
|
||||
|
||||
expect(handleNativeChatWebLink(event, 'https://example.com/', d)).toBe(true)
|
||||
expect(event.preventDefault).toHaveBeenCalledOnce()
|
||||
expect(mocks.openRoutedHttpLink).not.toHaveBeenCalled()
|
||||
expect(requests).toHaveLength(1)
|
||||
expect(requests[0]).toMatchObject({
|
||||
anchorX: 120,
|
||||
anchorY: 240,
|
||||
destination: 'https://example.com/',
|
||||
kind: 'url'
|
||||
})
|
||||
expect(requests[0]?.primary.label).toBe('System Browser')
|
||||
expect(requests[0]?.alternate?.label).toBe('Orca Browser')
|
||||
})
|
||||
|
||||
it('routes the popover actions to their destinations', () => {
|
||||
stubPlatform(true)
|
||||
const { deps: d, requests } = deps()
|
||||
handleNativeChatWebLink(click(), 'https://example.com/', d)
|
||||
|
||||
void requests[0]?.alternate?.run()
|
||||
expect(mocks.openRoutedHttpLink).toHaveBeenCalledWith('https://example.com/', {
|
||||
worktreeId: 'wt-1',
|
||||
sourceOwner: { kind: 'local' },
|
||||
modifierHeld: false,
|
||||
forceDestination: 'orca'
|
||||
})
|
||||
})
|
||||
|
||||
it('opens the primary destination directly on a modifier click', () => {
|
||||
stubPlatform(true)
|
||||
const { deps: d, requests } = deps()
|
||||
const event = click({ metaKey: true })
|
||||
|
||||
expect(handleNativeChatWebLink(event, 'https://example.com/', d)).toBe(true)
|
||||
expect(requests).toHaveLength(0)
|
||||
expect(mocks.openRoutedHttpLink).toHaveBeenCalledWith(
|
||||
'https://example.com/',
|
||||
expect.objectContaining({ forceDestination: 'system' })
|
||||
)
|
||||
})
|
||||
|
||||
it('opens the alternate destination on a shift+modifier click', () => {
|
||||
stubPlatform(false)
|
||||
const { deps: d } = deps()
|
||||
|
||||
expect(handleNativeChatWebLink(click({ ctrlKey: true, shiftKey: true }), 'https://a/', d)).toBe(
|
||||
true
|
||||
)
|
||||
expect(mocks.openRoutedHttpLink).toHaveBeenCalledWith(
|
||||
'https://a/',
|
||||
expect.objectContaining({ forceDestination: 'orca' })
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to the primary destination when no alternate is offered', () => {
|
||||
stubPlatform(true)
|
||||
const { deps: d } = deps({ destinations: { primary: 'system' } })
|
||||
|
||||
handleNativeChatWebLink(click({ metaKey: true, shiftKey: true }), 'https://a/', d)
|
||||
expect(mocks.openRoutedHttpLink).toHaveBeenCalledWith(
|
||||
'https://a/',
|
||||
expect.objectContaining({ forceDestination: 'system' })
|
||||
)
|
||||
})
|
||||
|
||||
it('opens the link outright on a plain click when link actions are disabled', () => {
|
||||
stubPlatform(true)
|
||||
const { deps: d, requests } = deps({ actionsEnabled: false })
|
||||
const event = click()
|
||||
|
||||
expect(handleNativeChatWebLink(event, 'https://example.com/', d)).toBe(true)
|
||||
expect(event.preventDefault).toHaveBeenCalledOnce()
|
||||
expect(requests).toHaveLength(0)
|
||||
expect(mocks.openRoutedHttpLink).toHaveBeenCalledWith(
|
||||
'https://example.com/',
|
||||
expect.objectContaining({ forceDestination: 'system' })
|
||||
)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['shift-only click', { shiftKey: true }],
|
||||
['alt click', { altKey: true }],
|
||||
['middle click', { button: 1 }],
|
||||
['mac ctrl click', { ctrlKey: true }]
|
||||
])('leaves the anchor default for a %s', (_label, init) => {
|
||||
stubPlatform(true)
|
||||
const { deps: d, requests } = deps()
|
||||
const event = click(init)
|
||||
|
||||
expect(handleNativeChatWebLink(event, 'https://example.com/', d)).toBe(false)
|
||||
expect(event.preventDefault).not.toHaveBeenCalled()
|
||||
expect(requests).toHaveLength(0)
|
||||
expect(mocks.openRoutedHttpLink).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,122 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { useMemo, useRef } from 'react'
|
||||
import { act, cleanup, renderHook } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import * as terminalThemeSelection from '../../../../shared/terminal-themes/terminal-theme-selection'
|
||||
import { createGlobalSettingsFixture } from '../../../../shared/global-settings-test-fixture'
|
||||
import { useAppStore } from '../../store'
|
||||
import { resetSystemPrefersDarkSubscriptionForTests } from '../terminal-pane/use-system-prefers-dark'
|
||||
import { useNativeChatRowTypography } from './use-native-chat-row-typography'
|
||||
|
||||
const originalSettings = useAppStore.getState().settings
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
useAppStore.setState({ settings: originalSettings })
|
||||
resetSystemPrefersDarkSubscriptionForTests()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('memoized transcript row typography', () => {
|
||||
it('keeps row estimates stable across custom and inherited font changes', () => {
|
||||
const settings = createGlobalSettingsFixture({ appFontFamily: 'Geist' })
|
||||
useAppStore.setState({ settings })
|
||||
const { result } = renderHook(() => useNativeChatRowTypography(useRef<HTMLDivElement>(null)))
|
||||
const inherited = result.current.typography
|
||||
const custom = { ...settings, nativeChatAppearance: { fontFamily: 'Georgia' } }
|
||||
act(() => useAppStore.setState({ settings: custom }))
|
||||
expect(result.current.typography).toBe(inherited)
|
||||
act(() => useAppStore.setState({ settings: { ...custom, appFontFamily: 'Arial' } }))
|
||||
expect(result.current.typography).toBe(inherited)
|
||||
act(() => useAppStore.setState({ settings: { ...settings, appFontFamily: 'Arial' } }))
|
||||
expect(result.current.typography).toBe(inherited)
|
||||
})
|
||||
it('does no theme work on message renders or unrelated settings writes and follows text size and measured width', () => {
|
||||
const settings = createGlobalSettingsFixture({
|
||||
theme: 'dark',
|
||||
nativeChatAppearance: { matchTerminalInterface: true }
|
||||
})
|
||||
useAppStore.setState({ settings })
|
||||
const resolveColors = vi.spyOn(terminalThemeSelection, 'resolveConfiguredTerminalColors')
|
||||
const matchMedia = vi.spyOn(window, 'matchMedia')
|
||||
const rendered = vi.fn()
|
||||
const { result, rerender } = renderHook(() => {
|
||||
rendered()
|
||||
return useNativeChatRowTypography(useRef<HTMLDivElement>(null))
|
||||
})
|
||||
const initial = result.current.typography
|
||||
expect(resolveColors).toHaveBeenCalledTimes(1)
|
||||
const initialMediaReads = matchMedia.mock.calls.length
|
||||
rerender()
|
||||
rerender()
|
||||
expect(result.current.typography).toBe(initial)
|
||||
expect(resolveColors).toHaveBeenCalledTimes(1)
|
||||
expect(matchMedia).toHaveBeenCalledTimes(initialMediaReads)
|
||||
const renders = rendered.mock.calls.length
|
||||
const terminalSizeSettings = { ...settings, terminalFontSize: settings.terminalFontSize + 1 }
|
||||
act(() =>
|
||||
useAppStore.setState({
|
||||
settings: terminalSizeSettings
|
||||
})
|
||||
)
|
||||
expect(rendered).toHaveBeenCalledTimes(renders + 1)
|
||||
expect(result.current.typography.lineHeightPx).toBe((22 * 15) / 14)
|
||||
expect(resolveColors).toHaveBeenCalledTimes(2)
|
||||
act(() =>
|
||||
useAppStore.setState({
|
||||
settings: {
|
||||
...terminalSizeSettings,
|
||||
nativeChatAppearance: { matchTerminalInterface: true, fontSize: 20 }
|
||||
}
|
||||
})
|
||||
)
|
||||
expect(result.current.typography.lineHeightPx).toBe((22 * 15) / 14)
|
||||
expect(resolveColors).toHaveBeenCalledTimes(3)
|
||||
const node = document.createElement('div')
|
||||
vi.spyOn(node, 'getBoundingClientRect').mockReturnValue(DOMRect.fromRect({ width: 384 }))
|
||||
act(() => result.current.measureContent(node))
|
||||
expect(result.current.typography.charsPerLine).toBe(46)
|
||||
expect(resolveColors).toHaveBeenCalledTimes(4)
|
||||
const measured = result.current.typography
|
||||
vi.mocked(node.getBoundingClientRect).mockReturnValue(DOMRect.fromRect({ width: 399 }))
|
||||
act(() => result.current.measureContent(node))
|
||||
expect(result.current.typography).toBe(measured)
|
||||
expect(resolveColors).toHaveBeenCalledTimes(4)
|
||||
act(() => result.current.measureContent(null))
|
||||
})
|
||||
|
||||
it('preserves the slot memo on default-width mount and pixel resizes, then refreshes for a new bucket', () => {
|
||||
useAppStore.setState({ settings: createGlobalSettingsFixture() })
|
||||
let slotBuilds = 0
|
||||
const { result } = renderHook(() => {
|
||||
const ref = useRef<HTMLDivElement | null>(null)
|
||||
const { typography, measureContent } = useNativeChatRowTypography(ref)
|
||||
const slots = useMemo(() => {
|
||||
slotBuilds += 1
|
||||
return { typography }
|
||||
}, [typography])
|
||||
return { slots, measureContent }
|
||||
})
|
||||
const node = document.createElement('div')
|
||||
const bounds = vi.spyOn(node, 'getBoundingClientRect')
|
||||
const measure = (width: number) => {
|
||||
bounds.mockReturnValue(DOMRect.fromRect({ width }))
|
||||
act(() => result.current.measureContent(node))
|
||||
}
|
||||
const initial = result.current.slots
|
||||
measure(736)
|
||||
expect(result.current.slots).toBe(initial)
|
||||
expect(slotBuilds).toBe(1)
|
||||
measure(735)
|
||||
const narrower = result.current.slots
|
||||
measure(734)
|
||||
measure(733)
|
||||
expect(result.current.slots).toBe(narrower)
|
||||
expect(slotBuilds).toBe(2)
|
||||
expect(narrower).not.toBe(initial)
|
||||
measure(672)
|
||||
expect(slotBuilds).toBe(3)
|
||||
expect(result.current.slots).not.toBe(narrower)
|
||||
act(() => result.current.measureContent(null))
|
||||
})
|
||||
})
|
||||
-163
@@ -1,163 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import type { AiVaultSession } from '../../../../../../shared/ai-vault/contracts/ai-vault-types'
|
||||
import type { AiVaultSessionListGroup } from '../session-list/ai-vault-session-filters'
|
||||
|
||||
const mockState: {
|
||||
settings: { aiVaultSearch?: { enabled: boolean } }
|
||||
runtimeEnvironments: never[]
|
||||
folderWorkspaces: never[]
|
||||
projectGroups: never[]
|
||||
repos: never[]
|
||||
worktreesByRepo: Record<string, never>
|
||||
} = {
|
||||
settings: {},
|
||||
runtimeEnvironments: [],
|
||||
folderWorkspaces: [],
|
||||
projectGroups: [],
|
||||
repos: [],
|
||||
worktreesByRepo: {}
|
||||
}
|
||||
const updateSettingsOrThrow = vi.fn(async (next: { aiVaultSearch: { enabled: boolean } }) => {
|
||||
mockState.settings = next
|
||||
})
|
||||
|
||||
vi.mock('@/store/index', () => ({
|
||||
useAppStore: Object.assign((select: (state: typeof mockState) => unknown) => select(mockState), {
|
||||
getState: () => ({ ...mockState, updateSettingsOrThrow, markFeatureTipsSeen: vi.fn() })
|
||||
})
|
||||
}))
|
||||
vi.mock('@/store/selectors', () => ({
|
||||
useActiveRepo: () => null,
|
||||
useActiveWorktree: () => null,
|
||||
useActiveWorktreeId: () => null,
|
||||
useAllWorktrees: () => [],
|
||||
useProjectHostSetupProjection: () => ({ projects: [], setups: [] }),
|
||||
useRepos: () => []
|
||||
}))
|
||||
|
||||
const sessions: AiVaultSession[] = [
|
||||
vaultSession('claude:1', 'Fix the foo pipeline'),
|
||||
vaultSession('claude:2', 'Rename the bar widget')
|
||||
]
|
||||
vi.mock('../scanning/ai-vault-session-refresh', () => ({
|
||||
useAiVaultSessionRefresh: () => ({
|
||||
error: null,
|
||||
loading: false,
|
||||
refresh: vi.fn(),
|
||||
scanResult: { sessions, issues: [], scannedAt: '2026-05-01T10:10:00.000Z' },
|
||||
sessions
|
||||
})
|
||||
}))
|
||||
vi.mock('../session-actions/ai-vault-session-launch-actions', () => ({
|
||||
useAiVaultSessionLaunchActions: () => ({
|
||||
buildResumeStartup: vi.fn(),
|
||||
copyResumeCommand: vi.fn(),
|
||||
handleResume: vi.fn(),
|
||||
handleResumeInNewChat: vi.fn(),
|
||||
handleContinueInNewSession: vi.fn(),
|
||||
continuationRequest: null,
|
||||
handleContinuationDialogOpenChange: vi.fn()
|
||||
})
|
||||
}))
|
||||
vi.mock('../session-actions/ai-vault-original-pane-actions', () => ({
|
||||
useAiVaultOriginalPaneActions: () => ({
|
||||
getOriginalPaneTarget: vi.fn(),
|
||||
getSessionLiveState: vi.fn(),
|
||||
jumpToOriginalPane: vi.fn(),
|
||||
jumpToWorktree: vi.fn()
|
||||
})
|
||||
}))
|
||||
vi.mock('../session-actions/ai-vault-session-delete-action', () => ({
|
||||
useAiVaultSessionDeleteAction: () => vi.fn()
|
||||
}))
|
||||
// happy-dom has no measurable viewport; render the real grouped sessions in place of virtualized rows.
|
||||
vi.mock('../session-list/AiVaultSessionVirtualList', () => ({
|
||||
AiVaultSessionVirtualList: ({ groups }: { groups: readonly AiVaultSessionListGroup[] }) => (
|
||||
<ul data-group-labels={groups.map((group) => group.label ?? '(untitled)').join('|')}>
|
||||
{groups.flatMap((group) =>
|
||||
group.sessions.map((session) => <li key={session.id}>{session.title}</li>)
|
||||
)}
|
||||
</ul>
|
||||
)
|
||||
}))
|
||||
|
||||
const searchSessions = vi.fn()
|
||||
|
||||
function vaultSession(id: string, title: string): AiVaultSession {
|
||||
return {
|
||||
id,
|
||||
executionHostId: 'local',
|
||||
agent: 'claude',
|
||||
sessionId: id,
|
||||
title,
|
||||
cwd: '/Users/ada/repo',
|
||||
branch: null,
|
||||
model: null,
|
||||
filePath: `/Users/ada/.claude/${id}.jsonl`,
|
||||
codexHome: null,
|
||||
createdAt: '2026-05-01T10:00:00.000Z',
|
||||
updatedAt: '2026-05-01T10:10:00.000Z',
|
||||
modifiedAt: '2026-05-01T10:10:00.000Z',
|
||||
messageCount: 4,
|
||||
totalTokens: 10,
|
||||
previewMessages: [],
|
||||
queuedMessageCount: 0,
|
||||
subagentTranscriptCount: 0,
|
||||
resumeCommand: 'claude --resume',
|
||||
subagent: null
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockState.settings = {}
|
||||
searchSessions.mockReset().mockResolvedValue({
|
||||
kind: 'results',
|
||||
hits: [],
|
||||
page: { cursor: null, hasMore: false },
|
||||
generation: 1,
|
||||
durationMs: 1,
|
||||
truncated: { candidates: false, snippets: 0, query: false, freshness: false }
|
||||
})
|
||||
Object.defineProperty(window, 'api', {
|
||||
configurable: true,
|
||||
value: { aiVault: { searchSessions }, ui: { writeClipboardText: vi.fn() } }
|
||||
})
|
||||
})
|
||||
afterEach(cleanup)
|
||||
|
||||
async function typeQuery(text: string) {
|
||||
// Imported here, not at the top: the hoisted mock factories close over `mockState` and `sessions`.
|
||||
const { default: AiVaultPanel } = await import('./AiVaultPanel')
|
||||
render(<AiVaultPanel />)
|
||||
if (text) {
|
||||
await userEvent.type(screen.getByLabelText('Search sessions'), text)
|
||||
}
|
||||
}
|
||||
|
||||
it('offers indexing above the title-filtered history instead of hiding every session', async () => {
|
||||
await typeQuery('foo')
|
||||
|
||||
expect(screen.getByRole('status').textContent).toContain('Enable full-text search?')
|
||||
expect(screen.getByRole('button', { name: 'Enable' })).toBeTruthy()
|
||||
expect(screen.getByText('Fix the foo pipeline')).toBeTruthy()
|
||||
expect(screen.queryByText('Rename the bar widget')).toBeNull()
|
||||
expect(searchSessions).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('switches to index search with the same query once indexing is enabled', async () => {
|
||||
await typeQuery('foo')
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Enable' }))
|
||||
|
||||
expect(updateSettingsOrThrow).toHaveBeenCalledWith({
|
||||
aiVaultSearch: { enabled: true, historyDays: null }
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(searchSessions).toHaveBeenCalledWith(expect.objectContaining({ query: 'foo' }), 'local')
|
||||
)
|
||||
expect(screen.queryByRole('button', { name: 'Enable' })).toBeNull()
|
||||
await waitFor(() => expect(screen.queryByText('Fix the foo pipeline')).toBeNull())
|
||||
})
|
||||
-146
@@ -1,146 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, cleanup, renderHook } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { useAiVaultPanelScope as useScope } from './use-ai-vault-panel-scope'
|
||||
|
||||
let useAiVaultPanelScope: typeof useScope
|
||||
|
||||
type AiVaultPanelContext = {
|
||||
activeProjectKey: string | null
|
||||
activeWorktreePath: string | null
|
||||
}
|
||||
|
||||
const AVAILABLE_CONTEXT: AiVaultPanelContext = {
|
||||
activeProjectKey: 'project:orca',
|
||||
activeWorktreePath: '/repo'
|
||||
}
|
||||
|
||||
const UNAVAILABLE_PROJECT_CONTEXT: AiVaultPanelContext = {
|
||||
activeProjectKey: null,
|
||||
activeWorktreePath: '/repo'
|
||||
}
|
||||
|
||||
const UNAVAILABLE_WORKSPACE_CONTEXT: AiVaultPanelContext = {
|
||||
activeProjectKey: 'project:orca',
|
||||
activeWorktreePath: null
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules()
|
||||
useAiVaultPanelScope = (await import('./use-ai-vault-panel-scope')).useAiVaultPanelScope
|
||||
})
|
||||
afterEach(cleanup)
|
||||
|
||||
describe('useAiVaultPanelScope', () => {
|
||||
it('restores scope and collapsed groups when the panel remounts', () => {
|
||||
const first = renderHook(() => useAiVaultPanelScope(AVAILABLE_CONTEXT))
|
||||
|
||||
act(() => {
|
||||
first.result.current.selectScope('project')
|
||||
first.result.current.toggleGroup('project:orca')
|
||||
})
|
||||
first.unmount()
|
||||
|
||||
const restored = renderHook(() => useAiVaultPanelScope(AVAILABLE_CONTEXT))
|
||||
expect(restored.result.current.scope).toBe('project')
|
||||
expect(restored.result.current.collapsedGroups).toEqual(new Set(['project:orca']))
|
||||
})
|
||||
|
||||
it('falls back to all without forgetting a preferred project scope', () => {
|
||||
const first = renderHook((context: AiVaultPanelContext) => useAiVaultPanelScope(context), {
|
||||
initialProps: AVAILABLE_CONTEXT
|
||||
})
|
||||
act(() => first.result.current.selectScope('project'))
|
||||
first.unmount()
|
||||
|
||||
const restored = renderHook((context: AiVaultPanelContext) => useAiVaultPanelScope(context), {
|
||||
initialProps: UNAVAILABLE_PROJECT_CONTEXT
|
||||
})
|
||||
expect(restored.result.current.scope).toBe('all')
|
||||
|
||||
restored.rerender(AVAILABLE_CONTEXT)
|
||||
expect(restored.result.current.scope).toBe('project')
|
||||
})
|
||||
|
||||
it('restores the default workspace scope after an unavailable-context remount', () => {
|
||||
const first = renderHook((context: AiVaultPanelContext) => useAiVaultPanelScope(context), {
|
||||
initialProps: AVAILABLE_CONTEXT
|
||||
})
|
||||
expect(first.result.current.scope).toBe('workspace')
|
||||
|
||||
first.rerender(UNAVAILABLE_WORKSPACE_CONTEXT)
|
||||
expect(first.result.current.scope).toBe('all')
|
||||
first.unmount()
|
||||
|
||||
const restored = renderHook((context: AiVaultPanelContext) => useAiVaultPanelScope(context), {
|
||||
initialProps: UNAVAILABLE_WORKSPACE_CONTEXT
|
||||
})
|
||||
expect(restored.result.current.scope).toBe('all')
|
||||
|
||||
restored.rerender(AVAILABLE_CONTEXT)
|
||||
expect(restored.result.current.scope).toBe('workspace')
|
||||
})
|
||||
|
||||
it('keeps an explicit all scope sticky across context changes and remounts', () => {
|
||||
const first = renderHook(() => useAiVaultPanelScope(AVAILABLE_CONTEXT))
|
||||
act(() => first.result.current.selectScope('all'))
|
||||
first.unmount()
|
||||
|
||||
const restored = renderHook(() =>
|
||||
useAiVaultPanelScope({ activeProjectKey: null, activeWorktreePath: null })
|
||||
)
|
||||
expect(restored.result.current.scope).toBe('all')
|
||||
restored.unmount()
|
||||
|
||||
const availableAgain = renderHook(() => useAiVaultPanelScope(AVAILABLE_CONTEXT))
|
||||
expect(availableAgain.result.current.scope).toBe('all')
|
||||
})
|
||||
|
||||
it('bounds collapsed groups and evicts the oldest entries', () => {
|
||||
const hook = renderHook(() => useAiVaultPanelScope(AVAILABLE_CONTEXT))
|
||||
|
||||
act(() => {
|
||||
for (let index = 0; index <= 512; index += 1) {
|
||||
hook.result.current.toggleGroup(`group-${index}`)
|
||||
}
|
||||
})
|
||||
|
||||
expect(hook.result.current.collapsedGroups.size).toBe(512)
|
||||
expect(hook.result.current.collapsedGroups.has('group-0')).toBe(false)
|
||||
expect(hook.result.current.collapsedGroups.has('group-512')).toBe(true)
|
||||
|
||||
act(() => hook.result.current.toggleGroup('group-512'))
|
||||
expect(hook.result.current.collapsedGroups.size).toBe(511)
|
||||
expect(hook.result.current.collapsedGroups.has('group-512')).toBe(false)
|
||||
act(() => hook.result.current.toggleGroup('group-512'))
|
||||
expect(hook.result.current.collapsedGroups.size).toBe(512)
|
||||
expect(hook.result.current.collapsedGroups.has('group-1')).toBe(true)
|
||||
expect(hook.result.current.collapsedGroups.has('group-512')).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps a dialog local without inheriting or changing sidebar choices', () => {
|
||||
const sidebar = renderHook(() => useAiVaultPanelScope(AVAILABLE_CONTEXT))
|
||||
act(() => {
|
||||
sidebar.result.current.handleScopeChange('project')
|
||||
sidebar.result.current.toggleGroup('project:orca')
|
||||
})
|
||||
const dialog = renderHook(() => useAiVaultPanelScope({ ...AVAILABLE_CONTEXT, local: true }))
|
||||
expect(dialog.result.current.scope).toBe('workspace')
|
||||
expect(dialog.result.current.collapsedGroups.size).toBe(0)
|
||||
act(() => {
|
||||
dialog.result.current.handleScopeChange('all')
|
||||
dialog.result.current.toggleGroup('project:dialog')
|
||||
})
|
||||
expect(sidebar.result.current.scope).toBe('project')
|
||||
expect(sidebar.result.current.collapsedGroups).toEqual(new Set(['project:orca']))
|
||||
dialog.unmount()
|
||||
const reopened = renderHook(() => useAiVaultPanelScope({ ...AVAILABLE_CONTEXT, local: true }))
|
||||
expect(reopened.result.current.scope).toBe('workspace')
|
||||
expect(reopened.result.current.collapsedGroups.size).toBe(0)
|
||||
sidebar.unmount()
|
||||
const returned = renderHook(() => useAiVaultPanelScope(AVAILABLE_CONTEXT))
|
||||
expect(returned.result.current.scope).toBe('project')
|
||||
expect(returned.result.current.collapsedGroups).toEqual(new Set(['project:orca']))
|
||||
})
|
||||
})
|
||||
-124
@@ -1,124 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, cleanup, renderHook } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { AI_VAULT_AGENTS } from '../../../../../../shared/ai-vault/contracts/ai-vault-types'
|
||||
import { AI_VAULT_VIEW_OPTIONS_STORAGE_KEY } from './ai-vault-view-options-persistence'
|
||||
import { usePersistedAiVaultViewOptions } from './use-persisted-ai-vault-view-options'
|
||||
|
||||
beforeEach(() => {
|
||||
window.localStorage.removeItem(AI_VAULT_VIEW_OPTIONS_STORAGE_KEY)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
window.localStorage.removeItem(AI_VAULT_VIEW_OPTIONS_STORAGE_KEY)
|
||||
})
|
||||
|
||||
describe('usePersistedAiVaultViewOptions', () => {
|
||||
it('restores view options when the panel remounts', () => {
|
||||
const first = renderHook(() => usePersistedAiVaultViewOptions())
|
||||
|
||||
act(() => {
|
||||
first.result.current.setAgentEnabled('codex', false)
|
||||
first.result.current.setSort('created')
|
||||
first.result.current.setGroup('folder')
|
||||
first.result.current.setHideEmptySessions(true)
|
||||
first.result.current.setSessionLimit('unlimited')
|
||||
})
|
||||
first.unmount()
|
||||
|
||||
const restored = renderHook(() => usePersistedAiVaultViewOptions())
|
||||
expect(restored.result.current.agents).not.toContain('codex')
|
||||
expect(restored.result.current.sort).toBe('created')
|
||||
expect(restored.result.current.group).toBe('folder')
|
||||
expect(restored.result.current.hideEmptySessions).toBe(true)
|
||||
expect(restored.result.current.sessionLimit).toBe('unlimited')
|
||||
})
|
||||
|
||||
it("shares view options between panels but keeps a dialog's agent filter to itself", () => {
|
||||
const sidebar = renderHook(() => usePersistedAiVaultViewOptions())
|
||||
const dialog = renderHook(() => usePersistedAiVaultViewOptions(['claude']))
|
||||
expect(dialog.result.current.agents).toEqual(['claude'])
|
||||
|
||||
act(() => sidebar.result.current.setAgentEnabled('codex', false))
|
||||
act(() => dialog.result.current.setSort('created'))
|
||||
act(() => dialog.result.current.setAllAgentsEnabled(true))
|
||||
expect(dialog.result.current.agents).toEqual(AI_VAULT_AGENTS)
|
||||
expect(sidebar.result.current.agents).not.toContain('codex')
|
||||
expect(sidebar.result.current.sort).toBe('created')
|
||||
|
||||
dialog.unmount()
|
||||
sidebar.unmount()
|
||||
const restored = renderHook(() => usePersistedAiVaultViewOptions())
|
||||
expect(restored.result.current.agents).not.toContain('codex')
|
||||
expect(restored.result.current.sort).toBe('created')
|
||||
})
|
||||
|
||||
it('allows clearing every agent so a single agent can be re-enabled', () => {
|
||||
const hook = renderHook(() => usePersistedAiVaultViewOptions())
|
||||
|
||||
act(() => hook.result.current.setAllAgentsEnabled(false))
|
||||
expect(hook.result.current.agents).toEqual([])
|
||||
|
||||
act(() => hook.result.current.setAgentEnabled('claude', true))
|
||||
expect(hook.result.current.agents).toEqual(['claude'])
|
||||
|
||||
act(() => hook.result.current.setAllAgentsEnabled(true))
|
||||
expect(hook.result.current.agents).toEqual([...AI_VAULT_AGENTS])
|
||||
})
|
||||
|
||||
it('allows disabling the last remaining agent', () => {
|
||||
const hook = renderHook(() => usePersistedAiVaultViewOptions())
|
||||
const lastEnabled = AI_VAULT_AGENTS[0]
|
||||
|
||||
act(() => {
|
||||
for (const agent of AI_VAULT_AGENTS.slice(1)) {
|
||||
hook.result.current.setAgentEnabled(agent, false)
|
||||
}
|
||||
})
|
||||
expect(hook.result.current.agents).toEqual([lastEnabled])
|
||||
|
||||
act(() => hook.result.current.setAgentEnabled(lastEnabled, false))
|
||||
expect(hook.result.current.agents).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps in-memory options usable when persistence fails', () => {
|
||||
const setItem = vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
|
||||
throw new Error('quota exceeded')
|
||||
})
|
||||
const hook = renderHook(() => usePersistedAiVaultViewOptions())
|
||||
|
||||
act(() => hook.result.current.setSort('created'))
|
||||
|
||||
expect(setItem).toHaveBeenCalled()
|
||||
expect(hook.result.current.sort).toBe('created')
|
||||
})
|
||||
|
||||
it('resets every persisted option to its default', () => {
|
||||
const hook = renderHook(() => usePersistedAiVaultViewOptions())
|
||||
act(() => {
|
||||
hook.result.current.setAgentEnabled('codex', false)
|
||||
hook.result.current.setSort('created')
|
||||
hook.result.current.setGroup('agent')
|
||||
hook.result.current.setHideEmptySessions(true)
|
||||
hook.result.current.setSessionLimit(1000)
|
||||
hook.result.current.resetViewOptions()
|
||||
})
|
||||
|
||||
expect(hook.result.current.agents).toEqual([...AI_VAULT_AGENTS])
|
||||
expect(hook.result.current.sort).toBe('updated')
|
||||
expect(hook.result.current.group).toBe('project')
|
||||
expect(hook.result.current.hideEmptySessions).toBe(false)
|
||||
expect(hook.result.current.sessionLimit).toBe(250)
|
||||
|
||||
hook.unmount()
|
||||
const restored = renderHook(() => usePersistedAiVaultViewOptions())
|
||||
expect(restored.result.current.agents).toEqual([...AI_VAULT_AGENTS])
|
||||
expect(restored.result.current.sort).toBe('updated')
|
||||
expect(restored.result.current.group).toBe('project')
|
||||
expect(restored.result.current.hideEmptySessions).toBe(false)
|
||||
expect(restored.result.current.sessionLimit).toBe(250)
|
||||
})
|
||||
})
|
||||
+1
-24
@@ -21,7 +21,7 @@ vi.mock('@/runtime/runtime-file-search-client', () => ({
|
||||
}))
|
||||
|
||||
const initialAppState = useAppStore.getInitialState()
|
||||
const LOCAL_KEY = folderWorkspaceKey('local-workspace')
|
||||
|
||||
const REMOTE_KEY = folderWorkspaceKey('remote-workspace')
|
||||
|
||||
function projectGroup(id: string, parentPath: string, connectionId: string | null): ProjectGroup {
|
||||
@@ -88,10 +88,6 @@ async function settle(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
function renderNameFilter(activeWorktreeId: string) {
|
||||
return renderHook(() => useFileExplorerNameFilter({ isFilesViewActive: true, activeWorktreeId }))
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useAppStore.setState(initialAppState, true)
|
||||
listRuntimeFilesMock.mockReset().mockResolvedValue(['packages/app/package.json', 'src/main.ts'])
|
||||
@@ -106,25 +102,6 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('useFileExplorerNameFilter over the real runtime listing', () => {
|
||||
it('keeps the local listing across query edits without refetching it', async () => {
|
||||
const { result } = renderNameFilter(LOCAL_KEY)
|
||||
|
||||
await act(async () => {
|
||||
result.current.setNameFilterQuery('pack')
|
||||
})
|
||||
await settle()
|
||||
await act(async () => {
|
||||
result.current.setNameFilterQuery('package.json')
|
||||
})
|
||||
await settle()
|
||||
|
||||
expect(listRuntimeFilesMock).toHaveBeenCalledTimes(1)
|
||||
expect(result.current.nameFilterSource?.relativePaths).toEqual([
|
||||
'packages/app/package.json',
|
||||
'src/main.ts'
|
||||
])
|
||||
})
|
||||
|
||||
it('never projects the previous query answer after a remote query edit', async () => {
|
||||
vi.useFakeTimers()
|
||||
searchRuntimeFilePathsMock.mockResolvedValue({ files: ['first/hit.ts'], truncated: false })
|
||||
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, render } from '@testing-library/react'
|
||||
|
||||
import { createElement, createRef, type MouseEvent } from 'react'
|
||||
import { useFileExplorerHandlers } from '../mutations/useFileExplorerHandlers'
|
||||
import { useFileExplorerNodeCommands } from '../mutations/use-file-explorer-node-commands'
|
||||
import { createFileExplorerRowProjection } from './file-explorer-row-projection'
|
||||
import { RENAME_HOTSPOT_ATTR } from './file-explorer-dir-toggle-timing'
|
||||
import type { TreeNode } from './file-explorer-types'
|
||||
|
||||
vi.mock('../navigation/file-explorer-operation-owner', () => ({
|
||||
getFileExplorerOwnerUnresolvedMessage: () => 'unresolved',
|
||||
requireMatchingFileExplorerOperationRoute: () => ({ target: { kind: 'local' } })
|
||||
}))
|
||||
vi.mock('@/store/index', () => ({
|
||||
useAppStore: (selector: (state: Record<string, unknown>) => unknown) => selector({})
|
||||
}))
|
||||
vi.mock('@/components/terminal/terminal-tab-create', () => ({ createNewTerminalTab: vi.fn() }))
|
||||
vi.mock('../mutations/useFileDuplicate', () => ({ useFileDuplicate: () => vi.fn() }))
|
||||
vi.mock('../selection/useFileExplorerKeys', () => ({ useFileExplorerKeys: vi.fn() }))
|
||||
|
||||
const directoryNode: TreeNode = {
|
||||
name: 'components',
|
||||
path: '/repo/src/components',
|
||||
relativePath: 'src/components',
|
||||
isDirectory: true,
|
||||
depth: 1
|
||||
}
|
||||
|
||||
const symlinkDirectoryNode: TreeNode = {
|
||||
name: 'linked-components',
|
||||
path: '/repo/src/linked-components',
|
||||
relativePath: 'src/linked-components',
|
||||
isDirectory: false,
|
||||
isSymlink: true,
|
||||
depth: 1
|
||||
}
|
||||
|
||||
function createHandlerParams(toggleDir: (worktreeId: string, dirPath: string) => void) {
|
||||
return {
|
||||
activeWorktreeId: 'wt-1',
|
||||
openFile: vi.fn(),
|
||||
makePreviewFilePermanent: vi.fn(),
|
||||
toggleDir,
|
||||
loadDir: vi.fn().mockResolvedValue(true),
|
||||
statPath: vi.fn().mockResolvedValue({ isDirectory: true }),
|
||||
markPathAsDirectory: vi.fn(),
|
||||
setSelectedPath: vi.fn(),
|
||||
scrollRef: createRef<HTMLDivElement>()
|
||||
}
|
||||
}
|
||||
|
||||
function renderRow(node: TreeNode, toggleDir: (worktreeId: string, dirPath: string) => void) {
|
||||
const params = createHandlerParams(toggleDir)
|
||||
function Row() {
|
||||
const { handleClick } = useFileExplorerHandlers(params)
|
||||
const { handleRowClick } = useFileExplorerNodeCommands({
|
||||
activeWorktreeId: 'wt-1',
|
||||
worktreePath: '/repo',
|
||||
activeRepo: null,
|
||||
containerRef: createRef<HTMLDivElement>(),
|
||||
rowProjection: createFileExplorerRowProjection([node]),
|
||||
rowExpandedPaths: new Set(),
|
||||
selectedPaths: new Set(),
|
||||
selectedNode: null,
|
||||
selectRowWithModifiers: (target, _event, onReplaceClick) => onReplaceClick(target),
|
||||
moveSelection: vi.fn(),
|
||||
inlineInput: null,
|
||||
startRename: vi.fn(),
|
||||
requestDelete: vi.fn(),
|
||||
requestDeleteAll: vi.fn(),
|
||||
refreshDir: vi.fn().mockResolvedValue(undefined),
|
||||
handleClick,
|
||||
toggleDir,
|
||||
scrollToIndex: vi.fn(),
|
||||
pathOwner: 'local'
|
||||
})
|
||||
return createElement(
|
||||
'button',
|
||||
{
|
||||
'data-testid': 'row',
|
||||
onClick: (event: MouseEvent<HTMLButtonElement>) => handleRowClick(node, event)
|
||||
},
|
||||
createElement('span', { [RENAME_HOTSPOT_ATTR]: '', 'data-testid': 'name' }, node.name)
|
||||
)
|
||||
}
|
||||
const view = render(createElement(Row))
|
||||
return { ...view, setSelectedPath: params.setSelectedPath }
|
||||
}
|
||||
|
||||
async function clickAndSettle(target: Element, detail: number): Promise<void> {
|
||||
await act(async () => {
|
||||
fireEvent.click(target, { detail })
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
}
|
||||
|
||||
describe('instant directory toggle', () => {
|
||||
afterEach(() => cleanup())
|
||||
|
||||
it('toggles a filename click immediately, without waiting out the double-click window', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const toggleDir = vi.fn()
|
||||
const { getByTestId } = renderRow(directoryNode, toggleDir)
|
||||
|
||||
await clickAndSettle(getByTestId('name'), 1)
|
||||
|
||||
// No timer: delaying the folder-name click made the explorer feel laggy.
|
||||
expect(toggleDir).toHaveBeenCalledWith('wt-1', directoryNode.path)
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('drops only the second click of a double-click rename so the folder does not flip back', async () => {
|
||||
const toggleDir = vi.fn()
|
||||
const { getByTestId, setSelectedPath } = renderRow(directoryNode, toggleDir)
|
||||
|
||||
await clickAndSettle(getByTestId('name'), 1)
|
||||
await clickAndSettle(getByTestId('name'), 2)
|
||||
|
||||
expect(toggleDir).toHaveBeenCalledTimes(1)
|
||||
// Keep the row selected for the rename about to start.
|
||||
expect(setSelectedPath).toHaveBeenLastCalledWith(directoryNode.path)
|
||||
})
|
||||
|
||||
it('toggles a symlink directory once when the second click is a rename', async () => {
|
||||
const toggleDir = vi.fn()
|
||||
const { getByTestId, setSelectedPath } = renderRow(symlinkDirectoryNode, toggleDir)
|
||||
|
||||
// Real double-clicks can land before the first stat resolves.
|
||||
await act(async () => {
|
||||
fireEvent.click(getByTestId('name'), { detail: 1 })
|
||||
fireEvent.click(getByTestId('name'), { detail: 2 })
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
|
||||
expect(toggleDir).toHaveBeenCalledTimes(1)
|
||||
expect(toggleDir).toHaveBeenCalledWith('wt-1', symlinkDirectoryNode.path)
|
||||
expect(setSelectedPath).toHaveBeenLastCalledWith(symlinkDirectoryNode.path)
|
||||
})
|
||||
})
|
||||
+1
-61
@@ -4,7 +4,6 @@ import { act, cleanup, renderHook } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { useFileExplorerTree } from './useFileExplorerTree'
|
||||
import { useFileExplorerTreeLoadEffects } from './use-file-explorer-tree-load-effects'
|
||||
import { FILE_EXPLORER_RUNTIME_REFRESH_CONCURRENCY } from '../watching/file-explorer-refresh-concurrency'
|
||||
|
||||
const read = vi.hoisted(() => vi.fn())
|
||||
vi.mock('./file-explorer-directory-listing', async (original) => ({
|
||||
@@ -23,54 +22,10 @@ const listing = () => ({
|
||||
entries: [{ name: 'fresh.txt', isDirectory: false, isSymlink: false }],
|
||||
operationOwner: { kind: 'runtime', environmentId: 'host-a', executionHostId: 'runtime:host-a' }
|
||||
})
|
||||
function gateRead() {
|
||||
let resolve!: (value: ReturnType<typeof listing>) => void
|
||||
const promise = new Promise<ReturnType<typeof listing>>((finish) => {
|
||||
resolve = finish
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
beforeEach(() => read.mockReset().mockResolvedValue(listing()))
|
||||
afterEach(cleanup)
|
||||
|
||||
it('stops a retired tree before its root response can launch expanded-directory reads', async () => {
|
||||
const gate = gateRead()
|
||||
read.mockReturnValueOnce(gate.promise)
|
||||
const hook = renderHook(() => useFileExplorerTree('/repo', new Set(['/repo/subdir']), 'wt'))
|
||||
let refresh!: ReturnType<typeof hook.result.current.refreshTree>
|
||||
act(() => {
|
||||
refresh = hook.result.current.refreshTree()
|
||||
})
|
||||
hook.unmount()
|
||||
gate.resolve(listing())
|
||||
expect(await refresh).toBe('superseded')
|
||||
expect(read).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('cancels queued remote directory reads when an expanded refresh is retired', async () => {
|
||||
const gates = Array.from({ length: FILE_EXPLORER_RUNTIME_REFRESH_CONCURRENCY }, gateRead)
|
||||
read.mockImplementation((_id, _root, path) =>
|
||||
path === '/repo'
|
||||
? Promise.resolve(listing())
|
||||
: (gates.shift()?.promise ?? Promise.resolve(listing()))
|
||||
)
|
||||
const pending = [...gates]
|
||||
const expanded = new Set(Array.from({ length: 20 }, (_, index) => `/repo/dir-${index}`))
|
||||
const hook = renderHook(() => useFileExplorerTree('/repo', expanded, 'wt'))
|
||||
let refresh!: ReturnType<typeof hook.result.current.refreshTree>
|
||||
await act(async () => {
|
||||
refresh = hook.result.current.refreshTree()
|
||||
await Promise.resolve()
|
||||
})
|
||||
expect(read).toHaveBeenCalledTimes(FILE_EXPLORER_RUNTIME_REFRESH_CONCURRENCY + 1)
|
||||
hook.unmount()
|
||||
for (const gate of pending) {
|
||||
gate.resolve(listing())
|
||||
}
|
||||
expect(await refresh).toBe('superseded')
|
||||
expect(read).toHaveBeenCalledTimes(FILE_EXPLORER_RUNTIME_REFRESH_CONCURRENCY + 1)
|
||||
})
|
||||
|
||||
function StrictWrapper({ children }: PropsWithChildren) {
|
||||
return <StrictMode>{children}</StrictMode>
|
||||
}
|
||||
@@ -109,18 +64,3 @@ it('restarts the initial read after StrictMode retires the first effect lifetime
|
||||
expect(hook.result.current.rootCache?.children[0].name).toBe('fresh.txt')
|
||||
expect(hook.result.current.loadingDirPaths.size).toBe(0)
|
||||
})
|
||||
|
||||
it('preserves the same host tree when Files is hidden and reopened', async () => {
|
||||
const hook = renderVisibleTree()
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
expect(read).toHaveBeenCalledTimes(1)
|
||||
hook.rerender({ visible: false })
|
||||
hook.rerender({ visible: true })
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
expect(read).toHaveBeenCalledTimes(1)
|
||||
expect(hook.result.current.rootCache?.children[0].name).toBe('fresh.txt')
|
||||
})
|
||||
|
||||
-152
@@ -1,152 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, cleanup, renderHook } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import type { AppState } from '@/store/types'
|
||||
import type { DirEntry } from '../../../../../../shared/filesystem-entry-types'
|
||||
|
||||
import { useFileExplorerTreeLoadEffects } from './use-file-explorer-tree-load-effects'
|
||||
import { useFileExplorerTree } from './useFileExplorerTree'
|
||||
import { useFileExplorerVisibleRowProjection } from './useFileExplorerVisibleRowProjection'
|
||||
|
||||
const readDirectoryMock = vi.hoisted(() => vi.fn())
|
||||
vi.mock('./file-explorer-directory-listing', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
readFileExplorerDirectory: readDirectoryMock
|
||||
}))
|
||||
vi.mock('../navigation/file-explorer-operation-owner', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
getFileExplorerOperationOwner: () => ({ kind: 'local' as const })
|
||||
}))
|
||||
vi.mock('@/runtime/runtime-git-status-client', () => ({
|
||||
getRuntimeGitIgnoredPaths: vi.fn().mockResolvedValue([])
|
||||
}))
|
||||
|
||||
const initialAppState = useAppStore.getInitialState()
|
||||
const WORKTREE_PATH = '/repo'
|
||||
const SRC_DIR = '/repo/src'
|
||||
|
||||
function entry(name: string, isDirectory = false): DirEntry {
|
||||
return { name, isDirectory } as DirEntry
|
||||
}
|
||||
|
||||
function listing(...entries: DirEntry[]) {
|
||||
return { entries, operationOwner: { kind: 'local' as const } }
|
||||
}
|
||||
|
||||
function useTreeWithProjection(expanded: Set<string>) {
|
||||
const tree = useFileExplorerTree(WORKTREE_PATH, expanded, 'wt-1')
|
||||
const projection = useFileExplorerVisibleRowProjection(
|
||||
'wt-1',
|
||||
WORKTREE_PATH,
|
||||
tree.dirCache,
|
||||
expanded,
|
||||
false,
|
||||
true,
|
||||
null
|
||||
)
|
||||
return { tree, rowProjection: projection.rowProjection }
|
||||
}
|
||||
|
||||
function renderTreeWithProjectionRebuildCounter(expanded: Set<string>): {
|
||||
result: { current: ReturnType<typeof useTreeWithProjection> }
|
||||
rebuilds: () => number
|
||||
} {
|
||||
const seen = new Set<unknown>()
|
||||
const hook = renderHook(() => {
|
||||
const value = useTreeWithProjection(expanded)
|
||||
seen.add(value.rowProjection)
|
||||
return value
|
||||
})
|
||||
return { result: hook.result, rebuilds: () => seen.size }
|
||||
}
|
||||
|
||||
/** Holds the next directory read open so the loading commit lands in its own render. */
|
||||
function gateNextRead(): { resolve: (value: ReturnType<typeof listing>) => void } {
|
||||
let resolve!: (value: ReturnType<typeof listing>) => void
|
||||
const gate = new Promise<ReturnType<typeof listing>>((nextResolve) => {
|
||||
resolve = nextResolve
|
||||
})
|
||||
readDirectoryMock.mockImplementationOnce(() => gate)
|
||||
return { resolve }
|
||||
}
|
||||
|
||||
describe('file explorer directory refresh churn', () => {
|
||||
beforeEach(() => {
|
||||
readDirectoryMock.mockReset().mockResolvedValue(listing())
|
||||
useAppStore.setState(initialAppState, true)
|
||||
useAppStore.setState({
|
||||
settings: { activeRuntimeEnvironmentId: null } as AppState['settings']
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
useAppStore.setState(initialAppState, true)
|
||||
})
|
||||
|
||||
it('rebuilds the visible row projection once per touched-directory refresh', async () => {
|
||||
const expanded = new Set([SRC_DIR])
|
||||
readDirectoryMock.mockResolvedValue(listing(entry('index.ts')))
|
||||
const { result, rebuilds } = renderTreeWithProjectionRebuildCounter(expanded)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.tree.loadDir(WORKTREE_PATH, -1, { force: true })
|
||||
})
|
||||
await act(async () => {
|
||||
await result.current.tree.loadDir(SRC_DIR, 0, { force: true })
|
||||
})
|
||||
const rebuildsBeforeRefresh = rebuilds()
|
||||
|
||||
// Gate the refresh so loading commits before the new listing.
|
||||
const gatedRead = gateNextRead()
|
||||
let pendingRefresh!: Promise<void>
|
||||
await act(async () => {
|
||||
pendingRefresh = result.current.tree.refreshDir(SRC_DIR)
|
||||
await Promise.resolve()
|
||||
})
|
||||
expect(result.current.tree.loadingDirPaths.has(SRC_DIR)).toBe(true)
|
||||
// Loading must not replace identical dirCache rows and pay for a second full projection walk.
|
||||
expect(rebuilds()).toBe(rebuildsBeforeRefresh)
|
||||
|
||||
await act(async () => {
|
||||
gatedRead.resolve(listing(entry('index.ts')))
|
||||
await pendingRefresh
|
||||
})
|
||||
expect(rebuilds() - rebuildsBeforeRefresh).toBe(1)
|
||||
})
|
||||
|
||||
it('does not stack a second read on an expanded dir the loading set already owns', () => {
|
||||
const loadDir = vi.fn().mockResolvedValue(true)
|
||||
const params = {
|
||||
workspaceKey: null,
|
||||
visibleFilesWorktreePath: WORKTREE_PATH,
|
||||
expanded: new Set([SRC_DIR]),
|
||||
dirCache: {},
|
||||
loadingDirPaths: new Set([SRC_DIR]),
|
||||
rootError: null,
|
||||
isDirStale: () => false,
|
||||
loadDir,
|
||||
refreshTree: vi.fn().mockResolvedValue('refreshed'),
|
||||
resetAndLoad: vi.fn(),
|
||||
resetSelection: vi.fn(),
|
||||
setNameFilterQuery: vi.fn()
|
||||
}
|
||||
const hook = renderHook((props: typeof params) => useFileExplorerTreeLoadEffects(props), {
|
||||
initialProps: params
|
||||
})
|
||||
// Refresh waves premark owned dirs; expansion effects must not launch duplicate reads.
|
||||
expect(loadDir).not.toHaveBeenCalled()
|
||||
|
||||
// Rerun after the wave’s read has landed and cleared its loading mark.
|
||||
hook.rerender({
|
||||
...params,
|
||||
expanded: new Set([SRC_DIR]),
|
||||
loadingDirPaths: new Set<string>()
|
||||
})
|
||||
expect(loadDir).toHaveBeenCalledTimes(1)
|
||||
// Expanded since mount, not by the user now: the deferred read must not start WSL (E9).
|
||||
expect(loadDir).toHaveBeenCalledWith(SRC_DIR, 0, {})
|
||||
})
|
||||
})
|
||||
-160
@@ -1,160 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildCreatePrIntentUnavailableEligibility,
|
||||
buildLocalBlockerHostedReviewCreationEligibility,
|
||||
resolveHostedReviewCreationProviderForTarget
|
||||
} from './hosted-review-creation-eligibility-snapshot'
|
||||
import { resolveCreateReviewIntentEligibility as resolveCreatePrIntentEligibility } from '../../../../../../shared/source-control/decisions/source-control-create-review-intent'
|
||||
|
||||
const featureBranch = { branch: 'feature/create-pr', baseRef: 'main' }
|
||||
|
||||
describe('resolveHostedReviewCreationProviderForTarget', () => {
|
||||
const target = { repoId: 'repo-1', worktreeId: 'worktree-1', branch: 'feature/create-pr' }
|
||||
|
||||
it('does not leak a provider hint across worktrees', () => {
|
||||
expect(
|
||||
resolveHostedReviewCreationProviderForTarget(
|
||||
{ ...target, provider: 'gitlab' },
|
||||
{ ...target, worktreeId: 'worktree-2' },
|
||||
'github'
|
||||
)
|
||||
).toBe('github')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildLocalBlockerHostedReviewCreationEligibility', () => {
|
||||
it('reports dirty with unavailable lookup while still allowing prepare-only Create PR intent', () => {
|
||||
const eligibility = buildLocalBlockerHostedReviewCreationEligibility('github', {
|
||||
...featureBranch,
|
||||
hasUncommittedChanges: true,
|
||||
hasUpstream: false,
|
||||
ahead: 0,
|
||||
behind: 0
|
||||
})
|
||||
expect(eligibility).toMatchObject({
|
||||
blockedReason: 'dirty',
|
||||
nextAction: 'commit',
|
||||
reviewLookupOutcome: 'unavailable'
|
||||
})
|
||||
// Why: branch prep is safe without lookup authority; final create stays fail-closed in main.
|
||||
expect(
|
||||
resolveCreatePrIntentEligibility({
|
||||
stagedCount: 1,
|
||||
hasStageableChanges: true,
|
||||
hasMessage: true,
|
||||
hasUnresolvedConflicts: false,
|
||||
upstreamStatus: { hasUpstream: false, ahead: 0, behind: 0 },
|
||||
hostedReviewCreation: eligibility,
|
||||
branchCommitsAhead: 0
|
||||
})
|
||||
).toEqual({ eligible: true, kind: 'dirty' })
|
||||
})
|
||||
|
||||
it('returns null for an ahead-only branch, matching main which will not offer an un-auth-checked push', () => {
|
||||
expect(
|
||||
buildLocalBlockerHostedReviewCreationEligibility('github', {
|
||||
...featureBranch,
|
||||
hasUncommittedChanges: false,
|
||||
hasUpstream: true,
|
||||
ahead: 2,
|
||||
behind: 0
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null on the default branch even when dirty, so it cannot enable a commit onto the base branch', () => {
|
||||
// A failed default-branch probe must not synthesize dirty eligibility that enables committing to the base.
|
||||
expect(
|
||||
buildLocalBlockerHostedReviewCreationEligibility('github', {
|
||||
branch: 'main',
|
||||
baseRef: 'origin/main',
|
||||
hasUncommittedChanges: true,
|
||||
hasUpstream: true,
|
||||
ahead: 0,
|
||||
behind: 0
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when the default branch is unknown', () => {
|
||||
expect(
|
||||
buildLocalBlockerHostedReviewCreationEligibility('github', {
|
||||
branch: 'main',
|
||||
baseRef: null,
|
||||
hasUncommittedChanges: true,
|
||||
hasUpstream: true,
|
||||
ahead: 0,
|
||||
behind: 0
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for a detached HEAD', () => {
|
||||
expect(
|
||||
buildLocalBlockerHostedReviewCreationEligibility('github', {
|
||||
branch: 'HEAD',
|
||||
baseRef: 'main',
|
||||
hasUncommittedChanges: true,
|
||||
hasUpstream: false,
|
||||
ahead: 0,
|
||||
behind: 0
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('does not synthesize needs_sync when upstream is unknown but a stale behind count is set', () => {
|
||||
// Require confirmed upstream before needs_sync; unknown upstream stays retryable, matching main.
|
||||
expect(
|
||||
buildLocalBlockerHostedReviewCreationEligibility('github', {
|
||||
...featureBranch,
|
||||
hasUncommittedChanges: false,
|
||||
hasUpstream: undefined,
|
||||
ahead: 0,
|
||||
behind: 2
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for providers that do not support hosted review creation', () => {
|
||||
expect(
|
||||
buildLocalBlockerHostedReviewCreationEligibility('unsupported', {
|
||||
...featureBranch,
|
||||
hasUncommittedChanges: true,
|
||||
hasUpstream: false,
|
||||
ahead: 0,
|
||||
behind: 0
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildCreatePrIntentUnavailableEligibility', () => {
|
||||
it('keeps a rejected click-time probe moving through push and final preflight', () => {
|
||||
expect(
|
||||
buildCreatePrIntentUnavailableEligibility('github', {
|
||||
...featureBranch,
|
||||
hasUncommittedChanges: false,
|
||||
hasUpstream: true,
|
||||
ahead: 2,
|
||||
behind: 0
|
||||
})
|
||||
).toMatchObject({
|
||||
blockedReason: 'needs_push',
|
||||
nextAction: 'push',
|
||||
reviewLookupOutcome: 'unavailable'
|
||||
})
|
||||
expect(
|
||||
buildCreatePrIntentUnavailableEligibility('github', {
|
||||
...featureBranch,
|
||||
hasUncommittedChanges: false,
|
||||
hasUpstream: true,
|
||||
ahead: 0,
|
||||
behind: 0
|
||||
})
|
||||
).toMatchObject({
|
||||
blockedReason: null,
|
||||
nextAction: null,
|
||||
reviewLookupOutcome: 'unavailable'
|
||||
})
|
||||
})
|
||||
})
|
||||
-149
@@ -1,149 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as React from 'react'
|
||||
import { ORCA_TERMINAL_COMMAND_FINISHED_EVENT } from '@/hooks/terminal-command-finished-event'
|
||||
|
||||
type WorktreesChangedCallback = (data: { repoId: string }) => void
|
||||
type GitStatusMetadataChangedCallback = (data: { repoId: string; worktreePaths?: string[] }) => void
|
||||
type HookParams = {
|
||||
activeRepoId: string | null
|
||||
activeWorktreeId: string | null
|
||||
activeWorktreePath?: string | null
|
||||
enabled: boolean
|
||||
fetchStatus: () => void
|
||||
getRepoWorktreePaths?: (repoId: string) => readonly string[]
|
||||
}
|
||||
|
||||
async function renderHookOnce(params: HookParams): Promise<{
|
||||
emitWorktreesChanged: (repoId: string) => void
|
||||
emitGitStatusMetadataChanged: (repoId: string, worktreePaths?: string[]) => void
|
||||
emitCommandFinished: (worktreeId: string) => void
|
||||
onChangedSubscribe: ReturnType<typeof vi.fn>
|
||||
onGitStatusMetadataChangedSubscribe: ReturnType<typeof vi.fn>
|
||||
onChangedUnsubscribe: ReturnType<typeof vi.fn>
|
||||
onGitStatusMetadataChangedUnsubscribe: ReturnType<typeof vi.fn>
|
||||
windowListeners: Map<string, EventListener>
|
||||
cleanups: (() => void)[]
|
||||
}> {
|
||||
vi.resetModules()
|
||||
|
||||
const cleanups: (() => void)[] = []
|
||||
vi.doMock('react', async () => {
|
||||
const actual = await vi.importActual<typeof React>('react')
|
||||
return {
|
||||
...actual,
|
||||
useEffect: (effect: () => void | (() => void)) => {
|
||||
const cleanup = effect()
|
||||
if (typeof cleanup === 'function') {
|
||||
cleanups.push(cleanup)
|
||||
}
|
||||
},
|
||||
useRef: <T>(initial: T) => ({ current: initial })
|
||||
}
|
||||
})
|
||||
|
||||
let worktreesChangedCallback: WorktreesChangedCallback | null = null
|
||||
let gitStatusMetadataChangedCallback: GitStatusMetadataChangedCallback | null = null
|
||||
const onChangedUnsubscribe = vi.fn()
|
||||
const onGitStatusMetadataChangedUnsubscribe = vi.fn()
|
||||
const onChangedSubscribe = vi.fn((callback: WorktreesChangedCallback) => {
|
||||
worktreesChangedCallback = callback
|
||||
return onChangedUnsubscribe
|
||||
})
|
||||
const onGitStatusMetadataChangedSubscribe = vi.fn(
|
||||
(callback: GitStatusMetadataChangedCallback) => {
|
||||
gitStatusMetadataChangedCallback = callback
|
||||
return onGitStatusMetadataChangedUnsubscribe
|
||||
}
|
||||
)
|
||||
const windowListeners = new Map<string, EventListener>()
|
||||
|
||||
vi.stubGlobal('window', {
|
||||
api: {
|
||||
worktrees: {
|
||||
onChanged: onChangedSubscribe,
|
||||
onGitStatusMetadataChanged: onGitStatusMetadataChangedSubscribe
|
||||
}
|
||||
},
|
||||
addEventListener: vi.fn((type: string, listener: EventListener) => {
|
||||
windowListeners.set(type, listener)
|
||||
}),
|
||||
removeEventListener: vi.fn((type: string) => {
|
||||
windowListeners.delete(type)
|
||||
})
|
||||
})
|
||||
vi.stubGlobal('document', {
|
||||
visibilityState: 'visible',
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn()
|
||||
})
|
||||
|
||||
const { useGitStatusPushSignalRefresh } = await import('./git-status-push-signal-refresh')
|
||||
function PushSignalRefreshHarness(props: Required<HookParams>): null {
|
||||
useGitStatusPushSignalRefresh(props)
|
||||
return null
|
||||
}
|
||||
PushSignalRefreshHarness({
|
||||
activeWorktreePath: '/repo/wt-1',
|
||||
getRepoWorktreePaths: () => ['/repo', '/repo/wt-1', '/repo/wt-2'],
|
||||
...params
|
||||
})
|
||||
|
||||
return {
|
||||
emitWorktreesChanged: (repoId: string) => worktreesChangedCallback?.({ repoId }),
|
||||
emitGitStatusMetadataChanged: (repoId: string, worktreePaths?: string[]) =>
|
||||
gitStatusMetadataChangedCallback?.(worktreePaths ? { repoId, worktreePaths } : { repoId }),
|
||||
emitCommandFinished: (worktreeId: string) => {
|
||||
const listener = windowListeners.get(ORCA_TERMINAL_COMMAND_FINISHED_EVENT)
|
||||
listener?.({ detail: { worktreeId } } as unknown as Event)
|
||||
},
|
||||
onChangedSubscribe,
|
||||
onGitStatusMetadataChangedSubscribe,
|
||||
onChangedUnsubscribe,
|
||||
onGitStatusMetadataChangedUnsubscribe,
|
||||
windowListeners,
|
||||
cleanups
|
||||
}
|
||||
}
|
||||
|
||||
describe('useGitStatusPushSignalRefresh', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('skips metadata signals attributed only to sibling worktrees', async () => {
|
||||
const fetchStatus = vi.fn()
|
||||
const harness = await renderHookOnce({
|
||||
activeRepoId: 'repo-1',
|
||||
activeWorktreeId: 'wt-1',
|
||||
enabled: true,
|
||||
fetchStatus
|
||||
})
|
||||
|
||||
harness.emitGitStatusMetadataChanged('repo-1', ['/repo/wt-2'])
|
||||
harness.emitGitStatusMetadataChanged('repo-1', ['/repo'])
|
||||
expect(fetchStatus).not.toHaveBeenCalled()
|
||||
|
||||
harness.emitGitStatusMetadataChanged('repo-1', ['/repo/wt-2', '/repo/wt-1'])
|
||||
expect(fetchStatus).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('refreshes when attribution is missing or names no known worktree', async () => {
|
||||
const fetchStatus = vi.fn()
|
||||
const harness = await renderHookOnce({
|
||||
activeRepoId: 'repo-1',
|
||||
activeWorktreeId: 'wt-1',
|
||||
enabled: true,
|
||||
fetchStatus
|
||||
})
|
||||
|
||||
// Older main process / SSH watch: no attribution.
|
||||
harness.emitGitStatusMetadataChanged('repo-1')
|
||||
expect(fetchStatus).toHaveBeenCalledTimes(1)
|
||||
harness.emitGitStatusMetadataChanged('repo-1', [])
|
||||
expect(fetchStatus).toHaveBeenCalledTimes(2)
|
||||
// A differently spelled path (symlinked root) may be the active checkout.
|
||||
harness.emitGitStatusMetadataChanged('repo-1', ['/private/repo/wt-1'])
|
||||
expect(fetchStatus).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
})
|
||||
-155
@@ -1,155 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
|
||||
import React from 'react'
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as UsageCredentialsClient from '@/runtime/runtime-usage-credentials-client'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
callMiniMax: vi.fn(),
|
||||
callZcode: vi.fn(),
|
||||
update: vi.fn(),
|
||||
toastError: vi.fn(),
|
||||
settingsSearchQuery: ''
|
||||
}))
|
||||
|
||||
vi.mock('@/runtime/runtime-usage-credentials-client', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof UsageCredentialsClient>()),
|
||||
callMiniMaxCredentials: mocks.callMiniMax,
|
||||
callZcodePlanCredentials: mocks.callZcode
|
||||
}))
|
||||
vi.mock('@/lib/agent-catalog', () => ({ AgentIcon: () => React.createElement('span') }))
|
||||
vi.mock('../../../status-bar/icons', () => ({ MiniMaxIcon: () => React.createElement('span') }))
|
||||
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: mocks.toastError } }))
|
||||
vi.mock('@/i18n/i18n', () => ({
|
||||
translate: (_key: string, fallback: string, values?: Record<string, string>) => {
|
||||
let result = fallback
|
||||
for (const [key, value] of Object.entries(values ?? {})) {
|
||||
result = result.replace(`{{${key}}}`, value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}))
|
||||
vi.mock('../../../../store/index', () => ({
|
||||
useAppStore: (selector: (state: Record<string, unknown>) => unknown) =>
|
||||
selector({
|
||||
recordFeatureInteraction: vi.fn(),
|
||||
refreshRateLimits: vi.fn(),
|
||||
settingsSearchQuery: mocks.settingsSearchQuery,
|
||||
rateLimits: { zcode: null }
|
||||
})
|
||||
}))
|
||||
|
||||
import { UsageCredentialsHostOutdatedError } from '@/runtime/runtime-usage-credentials-client'
|
||||
import { MiniMaxAccountsSection } from './MiniMaxAccountsSection'
|
||||
import { ZcodePlanAccountsSection } from './ZcodePlanAccountsSection'
|
||||
|
||||
const owner = { kind: 'environment' as const, environmentId: 'server-a' }
|
||||
const host = { owner, label: 'Build box' }
|
||||
const usageSettings = {
|
||||
settings: { minimaxEndpoint: 'overseas' as const, zcodePlanSite: 'zai' as const },
|
||||
update: mocks.update
|
||||
}
|
||||
const miniMaxStatus = {
|
||||
configured: true,
|
||||
cookieConfigured: false,
|
||||
apiKeyConfigured: true,
|
||||
cookieProtection: null,
|
||||
apiKeyProtection: 'sealed' as const,
|
||||
sessionCookieSupported: false
|
||||
}
|
||||
|
||||
function renderMiniMax(): void {
|
||||
render(
|
||||
<MiniMaxAccountsSection
|
||||
host={host}
|
||||
usageSettings={usageSettings}
|
||||
miniMaxRateLimits={null}
|
||||
recordFeatureInteraction={vi.fn()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMiniMax.mockReset().mockResolvedValue(miniMaxStatus)
|
||||
mocks.callZcode.mockReset().mockResolvedValue({
|
||||
apiKeyConfigured: false,
|
||||
zcodeCliConfigured: false,
|
||||
apiKeyProtection: null
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
mocks.settingsSearchQuery = ''
|
||||
cleanup()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('usage keys on the Settings host', () => {
|
||||
it('says MiniMax keys are stored on the host and saves there', async () => {
|
||||
renderMiniMax()
|
||||
|
||||
expect(await screen.findByText('Stored on Build box')).toBeInTheDocument()
|
||||
fireEvent.change(screen.getByPlaceholderText('Paste your MiniMax API key'), {
|
||||
target: { value: ' key-a ' }
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Replace' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.callMiniMax).toHaveBeenCalledWith(owner, 'saveApiKey', 'key-a')
|
||||
)
|
||||
})
|
||||
|
||||
it('locks replacing a key the other Orca app on the host sealed, but still allows forgetting it', async () => {
|
||||
mocks.callMiniMax.mockResolvedValue({ ...miniMaxStatus, apiKeyUnreadable: 'sealed-elsewhere' })
|
||||
renderMiniMax()
|
||||
|
||||
expect(
|
||||
await screen.findByText(
|
||||
'Saved by another Orca app on Build box, which this one cannot read. Change it in that app, or forget it here.'
|
||||
)
|
||||
).toBeInTheDocument()
|
||||
expect(screen.getByPlaceholderText('Paste your MiniMax API key')).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Forget key' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('asks to update an older host and offers no save', async () => {
|
||||
mocks.callMiniMax.mockRejectedValue(new UsageCredentialsHostOutdatedError())
|
||||
renderMiniMax()
|
||||
|
||||
expect(
|
||||
await screen.findByText('Update Orca on Build box to save this key there.')
|
||||
).toBeInTheDocument()
|
||||
expect(screen.queryByText('Credentials not set')).not.toBeInTheDocument()
|
||||
expect(screen.getByPlaceholderText('Paste your MiniMax API key')).toBeDisabled()
|
||||
expect(mocks.callMiniMax).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('shows an unreachable host as unknown, not as having no key', async () => {
|
||||
mocks.callMiniMax.mockRejectedValue(new Error('timed out'))
|
||||
renderMiniMax()
|
||||
|
||||
expect(
|
||||
await screen.findByText(
|
||||
'Could not reach Build box, so whether a key is saved there is unknown.'
|
||||
)
|
||||
).toBeInTheDocument()
|
||||
expect(screen.queryByText('Credentials not set')).not.toBeInTheDocument()
|
||||
expect(screen.getByPlaceholderText('Paste your MiniMax API key')).toBeDisabled()
|
||||
})
|
||||
|
||||
it('asks to update an older host for the GLM key and keeps this computer’s CLI setup out', async () => {
|
||||
mocks.callZcode.mockRejectedValue(new UsageCredentialsHostOutdatedError())
|
||||
render(<ZcodePlanAccountsSection host={host} usageSettings={usageSettings} />)
|
||||
|
||||
expect(
|
||||
await screen.findByText('Update Orca on Build box to save this key there.')
|
||||
).toBeInTheDocument()
|
||||
expect(screen.queryByText('No GLM Coding Plan linked')).not.toBeInTheDocument()
|
||||
expect(screen.getByPlaceholderText('Paste your GLM Coding Plan API key')).toBeDisabled()
|
||||
expect(screen.getByRole('combobox')).toBeDisabled()
|
||||
expect(screen.queryByRole('button', { name: 'Refresh usage' })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,123 +0,0 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { WslHostDistro } from '../../../../../../shared/wsl-host-types'
|
||||
import {
|
||||
AddWslHostFormPanel,
|
||||
canAddWslDistro,
|
||||
hasWsl2Distro,
|
||||
wsl1DistroReason,
|
||||
wslDistroStateLabel,
|
||||
wslHostAddRequest
|
||||
} from './AddWslHostFormPanel'
|
||||
|
||||
vi.mock('@/components/ui/dialog', () => ({
|
||||
DialogHeader: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
DialogTitle: ({ children }: { children: React.ReactNode }) => <h2>{children}</h2>,
|
||||
DialogDescription: ({ children }: { children: React.ReactNode }) => <p>{children}</p>,
|
||||
DialogFooter: ({ children }: { children: React.ReactNode }) => <div>{children}</div>
|
||||
}))
|
||||
|
||||
// Renders the options inline, as an open list would.
|
||||
vi.mock('@/components/ui/select', () => ({
|
||||
Select: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
SelectTrigger: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
SelectValue: () => null,
|
||||
SelectContent: ({ children }: { children: React.ReactNode }) => <ul>{children}</ul>,
|
||||
SelectItem: ({
|
||||
children,
|
||||
value,
|
||||
disabled
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
value: string
|
||||
disabled?: boolean
|
||||
}) => (
|
||||
<li data-value={value} data-disabled={disabled ? 'true' : 'false'}>
|
||||
{children}
|
||||
</li>
|
||||
)
|
||||
}))
|
||||
|
||||
const ubuntu: WslHostDistro = { name: 'Ubuntu', state: 'running', version: 2, environmentId: null }
|
||||
const debian: WslHostDistro = { name: 'Debian', state: 'stopped', version: 2, environmentId: null }
|
||||
const legacy: WslHostDistro = { name: 'Legacy', state: 'running', version: 1, environmentId: null }
|
||||
const added: WslHostDistro = { ...ubuntu, name: 'Arch', environmentId: 'wsl:arch' }
|
||||
|
||||
function render(props: Partial<Parameters<typeof AddWslHostFormPanel>[0]> = {}): string {
|
||||
return renderToStaticMarkup(
|
||||
<AddWslHostFormPanel
|
||||
distros={[ubuntu, debian, legacy, added]}
|
||||
loading={false}
|
||||
refreshing={false}
|
||||
selectedDistro=""
|
||||
error={null}
|
||||
adding={false}
|
||||
serverFilesMissing={false}
|
||||
onSelectDistro={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
onSubmit={vi.fn()}
|
||||
onCancel={vi.fn()}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
describe('AddWslHostFormPanel', () => {
|
||||
it('Add starts a stopped or Unknown distro, and never asks to start a running one', () => {
|
||||
const unknown: WslHostDistro = { ...debian, state: 'unverifiable' }
|
||||
expect(canAddWslDistro(unknown)).toBe(true)
|
||||
expect(wslHostAddRequest(unknown)).toEqual({ distro: 'Debian', startIfStopped: true })
|
||||
expect(wslHostAddRequest(debian)).toEqual({ distro: 'Debian', startIfStopped: true })
|
||||
expect(wslHostAddRequest(ubuntu)).toEqual({ distro: 'Ubuntu', startIfStopped: false })
|
||||
})
|
||||
|
||||
it('shows Unknown, not Stopped, for a distro WSL could not vouch for, and adding starts it if needed', () => {
|
||||
const unknown: WslHostDistro = { ...debian, state: 'unverifiable' }
|
||||
expect(wslDistroStateLabel(unknown)).toBe('Unknown')
|
||||
const html = render({ distros: [unknown], selectedDistro: 'Debian' })
|
||||
expect(html).toContain('Adding it starts it if needed')
|
||||
expect(html).not.toContain('Start and add')
|
||||
expect(html).not.toContain('is stopped')
|
||||
})
|
||||
|
||||
it('says this build cannot run WSL hosts and offers nothing to add', () => {
|
||||
const html = render({ selectedDistro: 'Ubuntu', serverFilesMissing: true })
|
||||
expect(html).toContain('This build of Orca can’t run WSL hosts (server files missing).')
|
||||
expect(html).toContain('role="alert"')
|
||||
expect(html).not.toContain('wsl --install')
|
||||
expect(html).toMatch(/<button[^>]*disabled=""[^>]*>Add host<\/button>/)
|
||||
})
|
||||
|
||||
it('disables a WSL 1 row and says how to convert it', () => {
|
||||
const html = render()
|
||||
expect(html).toMatch(/<li data-value="Legacy" data-disabled="true">/)
|
||||
expect(html).toMatch(/<li data-value="Ubuntu" data-disabled="false">/)
|
||||
expect(html).toContain('WSL 1 can’t run an Orca host; convert with wsl --set-version Legacy 2')
|
||||
expect(canAddWslDistro(legacy)).toBe(false)
|
||||
expect(wsl1DistroReason('Legacy')).toContain('wsl --set-version Legacy 2')
|
||||
})
|
||||
|
||||
it('treats an unreported version as possibly WSL 2', () => {
|
||||
expect(hasWsl2Distro([legacy])).toBe(false)
|
||||
expect(hasWsl2Distro([legacy, { ...ubuntu, version: null }])).toBe(true)
|
||||
expect(hasWsl2Distro([])).toBe(false)
|
||||
})
|
||||
|
||||
it('shows install guidance when no distros are found', () => {
|
||||
const html = render({ distros: [] })
|
||||
expect(html).toContain('No WSL 2 distros found')
|
||||
expect(html).toContain('wsl --install')
|
||||
})
|
||||
|
||||
it('shows install guidance when only WSL 1 distros are found', () => {
|
||||
const html = render({ distros: [legacy] })
|
||||
expect(html).toContain('No WSL 2 distros found')
|
||||
expect(html).toContain('wsl --set-version Legacy 2')
|
||||
})
|
||||
|
||||
it('shows no empty state while listing, after a list error, or with a WSL 2 distro', () => {
|
||||
expect(render({ distros: [], loading: true })).not.toContain('No WSL 2 distros found')
|
||||
expect(render({ distros: [], error: 'wsl.exe failed' })).not.toContain('No WSL 2 distros found')
|
||||
expect(render({ distros: [legacy, debian] })).not.toContain('No WSL 2 distros found')
|
||||
})
|
||||
})
|
||||
-58
@@ -68,54 +68,6 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('useAddRepoWslHostPaths', () => {
|
||||
it('offers the Windows folder picker only for a WSL host', () => {
|
||||
expect(setup({ selectedHostId: WSL_HOST }).view.result.current.browseWslHost).not.toBeNull()
|
||||
expect(
|
||||
setup({ selectedHostId: 'runtime:paired-server' }).view.result.current.browseWslHost
|
||||
).toBeNull()
|
||||
expect(setup({ selectedHostId: 'local' }).view.result.current.browseWslHost).toBeNull()
|
||||
})
|
||||
|
||||
it('offers nothing off Windows', () => {
|
||||
vi.stubGlobal('navigator', { userAgent: 'Mozilla/5.0 (Macintosh)' })
|
||||
expect(setup({ selectedHostId: WSL_HOST }).view.result.current.browseWslHost).toBeNull()
|
||||
})
|
||||
|
||||
it('fills the host path from a pick under the host distro', async () => {
|
||||
mocks.pickDirectory.mockResolvedValue('\\\\wsl.localhost\\ubuntu\\home\\me\\repo')
|
||||
const { view, setServerPath, setStep } = setup({ selectedHostId: WSL_HOST })
|
||||
act(() => view.result.current.browseWslHost?.())
|
||||
await waitFor(() => expect(setServerPath).toHaveBeenCalledWith('/home/me/repo'))
|
||||
expect(setStep).toHaveBeenCalledWith('server-path')
|
||||
expect(mocks.browse).toHaveBeenCalledWith('wsl:Ubuntu', '~')
|
||||
expect(mocks.pickDirectory).toHaveBeenCalledWith({
|
||||
defaultPath: '\\\\wsl.localhost\\Ubuntu\\home\\me'
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
['C:\\Users\\me\\src', 'C:\\Users\\me\\src'],
|
||||
['\\\\wsl.localhost\\Ubuntu\\mnt\\c\\work', 'C:\\work']
|
||||
])(
|
||||
'refuses a %s pick before it reaches the host path step or any scan',
|
||||
async (picked, windowsPath) => {
|
||||
mocks.pickDirectory.mockResolvedValue(picked)
|
||||
const { view, setServerPath, setStep, onWindowsDriveRefusal } = setup({
|
||||
selectedHostId: WSL_HOST
|
||||
})
|
||||
act(() => view.result.current.browseWslHost?.())
|
||||
await waitFor(() =>
|
||||
expect(onWindowsDriveRefusal).toHaveBeenCalledWith({
|
||||
kind: 'wsl_host_windows_drive_path',
|
||||
windowsPath
|
||||
})
|
||||
)
|
||||
// The host path step is what scans and adds; a refused pick never gets there.
|
||||
expect(setServerPath).not.toHaveBeenCalled()
|
||||
expect(setStep).not.toHaveBeenCalled()
|
||||
}
|
||||
)
|
||||
|
||||
it('drops a pick that lands after the dialog closed', async () => {
|
||||
let resolvePick: (path: string) => void = () => {}
|
||||
mocks.pickDirectory.mockReturnValue(new Promise((resolve) => (resolvePick = resolve)))
|
||||
@@ -126,14 +78,4 @@ describe('useAddRepoWslHostPaths', () => {
|
||||
await act(async () => resolvePick('\\\\wsl.localhost\\Ubuntu\\home\\me\\repo'))
|
||||
expect(setServerPath).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fills a dropped folder once its WSL host is selected', () => {
|
||||
const { view, setServerPath, setStep } = setup({ selectedHostId: null, dropped: '/home/me/a' })
|
||||
expect(setServerPath).not.toHaveBeenCalled()
|
||||
view.rerender({ selectedHostId: WSL_HOST, isOpen: true })
|
||||
expect(setServerPath).toHaveBeenCalledWith('/home/me/a')
|
||||
expect(setStep).toHaveBeenCalledWith('server-path')
|
||||
view.rerender({ selectedHostId: WSL_HOST, isOpen: true })
|
||||
expect(setServerPath).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
-177
@@ -1,177 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
|
||||
import type { ButtonHTMLAttributes, ReactNode } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Repo } from '../../../../../../shared/repo-types'
|
||||
import type { Worktree } from '../../../../../../shared/worktree/types'
|
||||
import type { OpenFile } from '@/store/slices/editor/types/open-file'
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const modalData: Record<string, unknown> = {}
|
||||
const allWorktrees: Worktree[] = []
|
||||
const repos: Repo[] = []
|
||||
const openFiles: OpenFile[] = []
|
||||
const editorDrafts: Record<string, string> = {}
|
||||
const state = {
|
||||
activeModal: 'delete-worktree',
|
||||
modalData,
|
||||
closeModal: vi.fn(),
|
||||
removeWorktree: vi.fn(),
|
||||
clearWorktreeDeleteState: vi.fn(),
|
||||
allWorktrees,
|
||||
repos,
|
||||
worktreeLineageById: {},
|
||||
updateSettings: vi.fn(),
|
||||
openSettingsTarget: vi.fn(),
|
||||
openSettingsPage: vi.fn(),
|
||||
settings: null,
|
||||
sshTargetLabels: new Map<string, string>(),
|
||||
sshConnectionStates: new Map(),
|
||||
runtimeEnvironments: [],
|
||||
runtimeStatusByEnvironmentId: new Map(),
|
||||
gitStatusByWorktree: {},
|
||||
setGitStatus: vi.fn(),
|
||||
deleteStateByWorktreeId: {},
|
||||
openFiles,
|
||||
editorDrafts,
|
||||
openModal: vi.fn(),
|
||||
editorBufferIdOf: {},
|
||||
editorBufferViews: {}
|
||||
}
|
||||
return { state, preventFocus: vi.fn() }
|
||||
})
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: Object.assign(
|
||||
(selector: (state: typeof mocks.state) => unknown) => selector(mocks.state),
|
||||
{ getState: () => mocks.state }
|
||||
)
|
||||
}))
|
||||
|
||||
vi.mock('@/store/selectors', () => ({
|
||||
useAllWorktrees: () => mocks.state.allWorktrees,
|
||||
getWorktreeMapFromState: () => new Map(mocks.state.allWorktrees.map((w) => [w.id, w])),
|
||||
getWorktreeOnHostFromState: (_state: unknown, worktreeId: string) =>
|
||||
mocks.state.allWorktrees.find((w) => w.id === worktreeId)
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/dialog', () => ({
|
||||
Dialog: ({ open, children }: { open: boolean; children: ReactNode }) =>
|
||||
open ? <div>{children}</div> : null,
|
||||
DialogContent: ({
|
||||
children,
|
||||
onOpenAutoFocus
|
||||
}: {
|
||||
children: ReactNode
|
||||
onOpenAutoFocus?: (event: { preventDefault: () => void }) => void
|
||||
}) => {
|
||||
onOpenAutoFocus?.({ preventDefault: mocks.preventFocus })
|
||||
return <div>{children}</div>
|
||||
},
|
||||
DialogDescription: ({ children }: { children: ReactNode }) => <div>{children}</div>,
|
||||
DialogFooter: ({ children }: { children: ReactNode }) => <div>{children}</div>,
|
||||
DialogHeader: ({ children }: { children: ReactNode }) => <div>{children}</div>,
|
||||
DialogTitle: ({ children }: { children: ReactNode }) => <div>{children}</div>
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/button', () => ({
|
||||
Button: ({ children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (
|
||||
<button {...props}>{children}</button>
|
||||
)
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/tooltip', () => ({
|
||||
Tooltip: ({ children }: { children: ReactNode }) => <span>{children}</span>,
|
||||
TooltipTrigger: ({ children }: { children: ReactNode }) => <span>{children}</span>,
|
||||
TooltipContent: ({ children }: { children: ReactNode }) => <span>{children}</span>
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }))
|
||||
|
||||
vi.mock('./worktree-delete-execution', () => ({ runWorktreeDeletesInParallel: vi.fn() }))
|
||||
|
||||
vi.mock('@/components/editor/model-lifetime/identity/editor-model-owner', () => ({
|
||||
resolveEditorModelOwner: () => ({ environmentId: null, hostId: 'local' }),
|
||||
getEditorModelOwnerKey: () => ''
|
||||
}))
|
||||
|
||||
import './delete-worktree-flow'
|
||||
import { runWorktreeDeletesInParallel } from './worktree-delete-execution'
|
||||
import DeleteWorktreeDialog from './DeleteWorktreeDialog'
|
||||
|
||||
const repo: Repo = {
|
||||
id: 'repo',
|
||||
path: '/repo',
|
||||
displayName: 'repo',
|
||||
badgeColor: 'gray',
|
||||
addedAt: 1
|
||||
}
|
||||
|
||||
const workspace: Worktree = {
|
||||
id: 'wt',
|
||||
instanceId: 'wt-instance',
|
||||
repoId: 'repo',
|
||||
path: '/workspaces/wt',
|
||||
head: 'abc',
|
||||
branch: 'wt',
|
||||
isBare: false,
|
||||
isMainWorktree: false,
|
||||
displayName: 'wt',
|
||||
comment: '',
|
||||
linkedIssue: null,
|
||||
linkedPR: null,
|
||||
linkedLinearIssue: null,
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 1
|
||||
}
|
||||
|
||||
function dirty(id: string, filePath: string): OpenFile {
|
||||
return {
|
||||
id,
|
||||
filePath,
|
||||
relativePath: id,
|
||||
worktreeId: 'wt',
|
||||
language: 'ts',
|
||||
isDirty: true,
|
||||
mode: 'edit'
|
||||
}
|
||||
}
|
||||
|
||||
describe('DeleteWorktreeDialog unsaved edits', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.state.modalData = {
|
||||
worktreeId: workspace.id,
|
||||
worktreeDeleteIdentities: [{ id: workspace.id, instanceId: workspace.instanceId }]
|
||||
}
|
||||
mocks.state.allWorktrees = [workspace]
|
||||
mocks.state.repos = [repo]
|
||||
mocks.state.openFiles = []
|
||||
mocks.state.editorDrafts = {}
|
||||
vi.mocked(runWorktreeDeletesInParallel).mockResolvedValue([])
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
it('lists the files whose edits are discarded and leaves focus off Delete', async () => {
|
||||
mocks.state.openFiles = [
|
||||
dirty('a.ts', '/workspaces/wt/a.ts'),
|
||||
dirty('b.ts', '/workspaces/wt/b.ts')
|
||||
]
|
||||
render(<DeleteWorktreeDialog />)
|
||||
expect(
|
||||
await screen.findByText('Unsaved edits in 2 files will be discarded:')
|
||||
).toBeInTheDocument()
|
||||
expect(screen.getByText('a.ts')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /Save/ })).toBeNull()
|
||||
expect(mocks.preventFocus).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
-179
@@ -1,179 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, type ReactNode } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { getWorktreeCardDetails } from '../../../../../../shared/worktree/card-properties'
|
||||
import { useAppStore } from '@/store'
|
||||
import { readStoreListenerCount } from '@/store/store-listener-census'
|
||||
import type { GlobalSettings } from '../../../../../../shared/global-settings-types'
|
||||
import type { Worktree, WorkspaceAttachment } from '../../../../../../shared/worktree/types'
|
||||
import { usePromptCacheCountdownStartedAt } from '../activity/CacheTimer'
|
||||
import { useWorktreeCardSecondaryDetails } from './use-worktree-card-secondary-details'
|
||||
import { useWorktreeAgentRows } from '../activity/useWorktreeAgentRows'
|
||||
|
||||
const mocks = vi.hoisted(() => ({ toastError: vi.fn() }))
|
||||
vi.mock('sonner', () => ({ toast: { error: mocks.toastError } }))
|
||||
|
||||
const WORKTREE_ID = 'repo-1::/repo/worktrees/card'
|
||||
const originalState = useAppStore.getState()
|
||||
|
||||
let root: Root | null = null
|
||||
let container: HTMLDivElement | null = null
|
||||
|
||||
function mount(node: ReactNode): void {
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
act(() => root?.render(node))
|
||||
}
|
||||
|
||||
function unmount(): void {
|
||||
if (root) {
|
||||
act(() => root?.unmount())
|
||||
}
|
||||
root = null
|
||||
container?.remove()
|
||||
container = null
|
||||
}
|
||||
|
||||
function listenerCount(): number {
|
||||
const count = readStoreListenerCount()
|
||||
if (count === null) {
|
||||
throw new Error('store listener census unavailable')
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
function makeWorktree(): Worktree {
|
||||
return {
|
||||
id: WORKTREE_ID,
|
||||
repoId: 'repo-1',
|
||||
path: '/repo/worktrees/card',
|
||||
displayName: 'Card',
|
||||
branch: 'feature/card',
|
||||
head: 'abc123',
|
||||
isBare: false,
|
||||
isMainWorktree: false,
|
||||
comment: '',
|
||||
linkedIssue: null,
|
||||
linkedPR: null,
|
||||
linkedLinearIssue: null,
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 1
|
||||
}
|
||||
}
|
||||
|
||||
function makeSettings(promptCacheTtlMs: number): GlobalSettings {
|
||||
return { promptCacheTimerEnabled: true, promptCacheTtlMs } as GlobalSettings
|
||||
}
|
||||
|
||||
function secondaryDetailsArgs(settings: GlobalSettings) {
|
||||
return {
|
||||
worktree: makeWorktree(),
|
||||
repo: undefined,
|
||||
statusPrDisplay: null,
|
||||
showStatus: false,
|
||||
showIssue: false,
|
||||
showLinearIssue: false,
|
||||
showJiraIssue: false,
|
||||
showPR: false,
|
||||
showAutomation: false,
|
||||
showCli: false,
|
||||
showComment: false,
|
||||
showPorts: false,
|
||||
issueDisplay: null,
|
||||
linearIssue: null,
|
||||
linearIssueDisplay: null,
|
||||
jiraIssueDisplay: null,
|
||||
prDisplay: null,
|
||||
linkedGitLabMR: null,
|
||||
linkedBitbucketPR: null,
|
||||
linkedAzureDevOpsPR: null,
|
||||
linkedGiteaPR: null,
|
||||
newCardStyle: false,
|
||||
compactCards: false,
|
||||
cardDetails: getWorktreeCardDetails([], { compactWorktreeCards: false, newCardStyle: false }),
|
||||
agentActivityDisplayMode: 'compact' as const,
|
||||
workspacePorts: [],
|
||||
openTaskPage: (() => {}) as never,
|
||||
updateWorktreeMeta: (() => {}) as never,
|
||||
settings
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
unmount()
|
||||
useAppStore.setState(originalState, true)
|
||||
})
|
||||
|
||||
describe('useWorktreeCardSecondaryDetails store subscriptions', () => {
|
||||
it('adds no store listener of its own beyond the hooks it composes', () => {
|
||||
const settings = makeSettings(300_000)
|
||||
|
||||
// Baseline: the two hooks it composes, mounted on their own.
|
||||
const composedBaseline = listenerCount()
|
||||
function ComposedProbe(): null {
|
||||
useWorktreeAgentRows(WORKTREE_ID, false)
|
||||
usePromptCacheCountdownStartedAt(WORKTREE_ID, true)
|
||||
return null
|
||||
}
|
||||
mount(<ComposedProbe />)
|
||||
const composedListeners = listenerCount() - composedBaseline
|
||||
unmount()
|
||||
|
||||
const baseline = listenerCount()
|
||||
function Probe(): null {
|
||||
useWorktreeCardSecondaryDetails(secondaryDetailsArgs(settings))
|
||||
return null
|
||||
}
|
||||
mount(<Probe />)
|
||||
|
||||
// Reuse settings passed by the card rather than adding a per-card subscription for the same field.
|
||||
expect(listenerCount() - baseline).toBe(composedListeners)
|
||||
|
||||
unmount()
|
||||
expect(listenerCount()).toBe(baseline)
|
||||
})
|
||||
it('unlinks the chosen sibling while retaining the selected review and other sources', async () => {
|
||||
const primary: WorkspaceAttachment = {
|
||||
provider: 'github',
|
||||
type: 'pr',
|
||||
number: 42,
|
||||
url: 'https://github.com/acme/orca/pull/42'
|
||||
}
|
||||
const sibling: WorkspaceAttachment = {
|
||||
provider: 'github',
|
||||
type: 'pr',
|
||||
number: 42,
|
||||
url: 'https://github.com/other/orca/pull/42'
|
||||
}
|
||||
const updateWorktreeMeta = vi.fn().mockResolvedValue({ ok: true })
|
||||
let unlink: ((item?: WorkspaceAttachment) => Promise<void>) | null = null
|
||||
function Probe(): null {
|
||||
const details = useWorktreeCardSecondaryDetails({
|
||||
...secondaryDetailsArgs(makeSettings(300_000)),
|
||||
worktree: {
|
||||
...makeWorktree(),
|
||||
hostId: 'ssh:builder',
|
||||
linkedPR: 42,
|
||||
linkedItems: [primary, sibling]
|
||||
},
|
||||
prDisplay: { provider: 'github', number: 42, title: 'Primary', url: primary.url },
|
||||
updateWorktreeMeta
|
||||
})
|
||||
unlink = details.handleUnlinkReview
|
||||
return null
|
||||
}
|
||||
mount(<Probe />)
|
||||
await act(() => unlink?.(sibling))
|
||||
expect(updateWorktreeMeta).toHaveBeenCalledWith(
|
||||
WORKTREE_ID,
|
||||
{ linkedItemsBase: [primary, sibling], linkedItems: [primary] },
|
||||
{ executionHostId: 'ssh:builder' }
|
||||
)
|
||||
})
|
||||
})
|
||||
-181
@@ -1,181 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import type { ReactNode } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { act } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Repo } from '../../../../../../shared/repo-types'
|
||||
import type { WorktreeCardProperty } from '../../../../../../shared/ui-chrome-types'
|
||||
import type { Worktree } from '../../../../../../shared/worktree/types'
|
||||
|
||||
const fetchHostedReviewForBranch = vi.fn()
|
||||
const fetchIssue = vi.fn()
|
||||
const fetchLinearIssue = vi.fn()
|
||||
const openModal = vi.fn()
|
||||
const updateWorktreeMeta = vi.fn()
|
||||
|
||||
let worktreeCardProperties: WorktreeCardProperty[] = ['status']
|
||||
let root: Root | null = null
|
||||
let container: HTMLDivElement | null = null
|
||||
|
||||
vi.mock('@/store', () => {
|
||||
const getState = () => ({
|
||||
deleteStateByWorktreeId: {},
|
||||
fetchHostedReviewForBranch,
|
||||
fetchIssue,
|
||||
fetchLinearIssue,
|
||||
gitConflictOperationByWorktree: {},
|
||||
hostedReviewCache: {
|
||||
'local::repo-1::feature/branch': {
|
||||
data: null,
|
||||
fetchedAt: Date.now(),
|
||||
linkedReviewHintKey: ''
|
||||
}
|
||||
},
|
||||
issueCache: {},
|
||||
linearIssueCache: {},
|
||||
openModal,
|
||||
projectGroups: [],
|
||||
remoteBranchConflictByWorktreeId: {},
|
||||
settings: { experimentalNewWorktreeCardStyle: true },
|
||||
sshConnectionStates: new Map(),
|
||||
sshTargetLabels: new Map(),
|
||||
updateWorktreeMeta,
|
||||
workspacePortScan: null,
|
||||
worktreeCardProperties
|
||||
})
|
||||
return {
|
||||
useAppStore: Object.assign((selector: (state: unknown) => unknown) => selector(getState()), {
|
||||
getState,
|
||||
subscribe: () => () => {}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/sidebar-worktree-activation', () => ({
|
||||
activateWorktreeFromSidebar: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/tooltip', () => ({
|
||||
Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
TooltipContent: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}</>
|
||||
}))
|
||||
|
||||
vi.mock('../activity/CacheTimer', () => ({
|
||||
default: () => null,
|
||||
usePromptCacheCountdownStartedAt: () => null
|
||||
}))
|
||||
|
||||
vi.mock('../activity/WorktreeCardAgents', () => ({
|
||||
default: () => null
|
||||
}))
|
||||
|
||||
vi.mock('../../workspace-actions/context-menu/WorktreeContextMenu', () => ({
|
||||
default: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
WORKTREE_NATIVE_CONTEXT_MENU_ATTR: 'data-worktree-native-context-menu',
|
||||
WORKTREE_CONTEXT_MENU_SCOPE_ATTR: 'data-orca-context-menu-scope'
|
||||
}))
|
||||
|
||||
vi.mock('../activity/use-worktree-activity-status', () => ({
|
||||
useWorktreeActivityStatus: () => 'active'
|
||||
}))
|
||||
|
||||
vi.mock('../../workspace-actions/sleep/use-worktree-sleep-state', () => ({
|
||||
useIsSleepingWorktree: () => false
|
||||
}))
|
||||
|
||||
function makeRepo(): Repo {
|
||||
return {
|
||||
id: 'repo-1',
|
||||
path: '/repo',
|
||||
displayName: 'orca',
|
||||
badgeColor: '#999999',
|
||||
addedAt: 1
|
||||
}
|
||||
}
|
||||
|
||||
function makeWorktree(overrides: Partial<Worktree> = {}): Worktree {
|
||||
return {
|
||||
id: 'repo-1::/repo/worktrees/branch',
|
||||
repoId: 'repo-1',
|
||||
path: '/repo/worktrees/branch',
|
||||
displayName: 'feature/branch',
|
||||
branch: 'feature/branch',
|
||||
head: 'abc123',
|
||||
isBare: false,
|
||||
isMainWorktree: false,
|
||||
comment: '',
|
||||
linkedIssue: null,
|
||||
linkedPR: null,
|
||||
linkedLinearIssue: null,
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 1,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('WorktreeCard hosted review refresh', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.clearAllMocks()
|
||||
worktreeCardProperties = ['status']
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (root) {
|
||||
act(() => root?.unmount())
|
||||
}
|
||||
container?.remove()
|
||||
root = null
|
||||
container = null
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('leaves repeating metadata reads to the central visible-review scheduler', async () => {
|
||||
const { default: WorktreeCard } = await import('./WorktreeCard')
|
||||
act(() => {
|
||||
root?.render(<WorktreeCard worktree={makeWorktree()} repo={makeRepo()} isActive={false} />)
|
||||
})
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(15 * 60_000)
|
||||
})
|
||||
expect(fetchHostedReviewForBranch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refetches the linked Linear issue only when its source changes, not on metadata writes', async () => {
|
||||
worktreeCardProperties = ['linear-issue']
|
||||
const { default: WorktreeCard } = await import('./WorktreeCard')
|
||||
const render = (overrides: Partial<Worktree>) =>
|
||||
act(() => {
|
||||
root?.render(
|
||||
<WorktreeCard
|
||||
worktree={makeWorktree({ linkedLinearIssue: 'ENG-1', ...overrides })}
|
||||
repo={makeRepo()}
|
||||
isActive={false}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
render({})
|
||||
render({ comment: 'updated', lastActivityAt: 2 })
|
||||
expect(fetchLinearIssue).toHaveBeenCalledTimes(1)
|
||||
|
||||
const movedSource = {
|
||||
kind: 'task-source',
|
||||
provider: 'linear',
|
||||
projectId: 'p-2',
|
||||
hostId: 'ssh:box'
|
||||
} as const
|
||||
render({ linkedTaskSourceContext: movedSource })
|
||||
expect(fetchLinearIssue).toHaveBeenCalledTimes(2)
|
||||
expect(fetchLinearIssue).toHaveBeenLastCalledWith('ENG-1', 'all', {
|
||||
sourceContext: movedSource
|
||||
})
|
||||
})
|
||||
})
|
||||
-178
@@ -1,178 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
/** Exercise submenu focus timing and query reset, which flat-menu tests cannot cover. */
|
||||
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
state: {} as Record<string, unknown>
|
||||
}))
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: (selector: (state: Record<string, unknown>) => unknown) => selector(mocks.state)
|
||||
}))
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import SidebarRepositoryFilterSection from './SidebarRepositoryFilterSection'
|
||||
|
||||
const REPOS = [
|
||||
{ id: 'r1', displayName: 'alpha', path: '/tmp/alpha' },
|
||||
{ id: 'r2', displayName: 'beta', path: '/tmp/beta' },
|
||||
{ id: 'r3', displayName: 'gamma', path: '/tmp/gamma' }
|
||||
]
|
||||
|
||||
let container: HTMLDivElement
|
||||
let root: Root
|
||||
let setFilterRepoIds: ReturnType<typeof vi.fn>
|
||||
|
||||
function setState(overrides: Record<string, unknown> = {}): void {
|
||||
setFilterRepoIds = vi.fn()
|
||||
mocks.state = {
|
||||
repos: REPOS,
|
||||
filterRepoIds: [],
|
||||
setFilterRepoIds,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function render(): void {
|
||||
act(() => {
|
||||
root.render(
|
||||
<DropdownMenu defaultOpen>
|
||||
<DropdownMenuTrigger>Options</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem>Sort by</DropdownMenuItem>
|
||||
<SidebarRepositoryFilterSection />
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function openSubmenu(): void {
|
||||
const trigger = document.querySelector<HTMLElement>('[data-slot="dropdown-menu-sub-trigger"]')
|
||||
if (!trigger) {
|
||||
throw new Error('sub-trigger not rendered')
|
||||
}
|
||||
act(() => {
|
||||
trigger.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerType: 'mouse' }))
|
||||
trigger.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, pointerType: 'mouse' }))
|
||||
trigger.click()
|
||||
})
|
||||
}
|
||||
|
||||
function closeSubmenu(): void {
|
||||
const content = document.querySelector<HTMLElement>('[data-slot="dropdown-menu-sub-content"]')
|
||||
if (!content) {
|
||||
throw new Error('sub-content not rendered')
|
||||
}
|
||||
act(() => {
|
||||
content.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'ArrowLeft', bubbles: true, cancelable: true })
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function searchInput(): HTMLInputElement | null {
|
||||
return document.querySelector<HTMLInputElement>('[data-slot="command-input"]')
|
||||
}
|
||||
|
||||
/** Allow deferred focus to settle through one frame and a macrotask. */
|
||||
async function settle(): Promise<void> {
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => requestAnimationFrame(() => setTimeout(resolve, 0)))
|
||||
})
|
||||
}
|
||||
|
||||
/** Types into whatever currently holds focus, so routing is part of the assertion. */
|
||||
function typeIntoFocused(value: string): void {
|
||||
const input = document.activeElement
|
||||
if (!(input instanceof HTMLInputElement)) {
|
||||
throw new Error(`focus is on ${document.activeElement?.nodeName ?? 'nothing'}, not an input`)
|
||||
}
|
||||
act(() => {
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set
|
||||
setter?.call(input, value)
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
// Radix probes pointer capture and scrolling that happy-dom does not model.
|
||||
Element.prototype.hasPointerCapture ??= () => false
|
||||
Element.prototype.setPointerCapture ??= () => {}
|
||||
Element.prototype.releasePointerCapture ??= () => {}
|
||||
Element.prototype.scrollIntoView ??= () => {}
|
||||
globalThis.ResizeObserver ??= class {
|
||||
observe(): void {}
|
||||
unobserve(): void {}
|
||||
disconnect(): void {}
|
||||
} as unknown as typeof ResizeObserver
|
||||
setState()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('SidebarRepositoryFilterSection', () => {
|
||||
it('resets the query when the panel is reopened', async () => {
|
||||
render()
|
||||
openSubmenu()
|
||||
await settle()
|
||||
typeIntoFocused('alp')
|
||||
expect(searchInput()?.value).toBe('alp')
|
||||
|
||||
closeSubmenu()
|
||||
expect(searchInput()).toBeNull()
|
||||
|
||||
openSubmenu()
|
||||
await settle()
|
||||
expect(searchInput()?.value).toBe('')
|
||||
})
|
||||
|
||||
it('keeps ArrowLeft in the text field while the caret can still move', async () => {
|
||||
render()
|
||||
openSubmenu()
|
||||
await settle()
|
||||
typeIntoFocused('alp')
|
||||
|
||||
const input = searchInput()
|
||||
input?.setSelectionRange(3, 3)
|
||||
act(() => {
|
||||
input?.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'ArrowLeft', bubbles: true, cancelable: true })
|
||||
)
|
||||
})
|
||||
|
||||
expect(searchInput()).not.toBeNull()
|
||||
})
|
||||
|
||||
it('lets ArrowLeft close the panel once the caret is at the start', async () => {
|
||||
render()
|
||||
openSubmenu()
|
||||
await settle()
|
||||
|
||||
const input = searchInput()
|
||||
input?.setSelectionRange(0, 0)
|
||||
act(() => {
|
||||
input?.dispatchEvent(
|
||||
new KeyboardEvent('keydown', { key: 'ArrowLeft', bubbles: true, cancelable: true })
|
||||
)
|
||||
})
|
||||
|
||||
expect(searchInput()).toBeNull()
|
||||
})
|
||||
})
|
||||
-156
@@ -1,156 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { createProjectGroupHeaderDragSession } from './project-group-header-drag-start'
|
||||
import type { ProjectGroup } from '../../../../../../shared/project-group-types'
|
||||
|
||||
function group(id: string, overrides: Partial<ProjectGroup> = {}): ProjectGroup {
|
||||
return {
|
||||
id,
|
||||
name: id,
|
||||
parentPath: null,
|
||||
parentGroupId: null,
|
||||
createdFrom: 'manual',
|
||||
tabOrder: 0,
|
||||
isCollapsed: false,
|
||||
color: null,
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('createProjectGroupHeaderDragSession', () => {
|
||||
it('arms from the group icon svg (SVGElement target)', () => {
|
||||
const header = document.createElement('div')
|
||||
header.setAttribute('data-project-group-header-drag-handle', '')
|
||||
const iconSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
|
||||
header.append(iconSvg)
|
||||
const scrollContainer = document.createElement('div')
|
||||
document.body.append(scrollContainer, header)
|
||||
|
||||
const projectGroupById = new Map<string, ProjectGroup>([
|
||||
['group-a', group('group-a')],
|
||||
['group-b', group('group-b')]
|
||||
])
|
||||
const sidebarProjectGroupHeaderIdsByBucket = new Map([['root', ['group-a', 'group-b']]])
|
||||
|
||||
const session = createProjectGroupHeaderDragSession({
|
||||
event: {
|
||||
button: 0,
|
||||
pointerId: 1,
|
||||
clientX: 10,
|
||||
clientY: 20,
|
||||
target: iconSvg,
|
||||
currentTarget: header
|
||||
} as unknown as React.PointerEvent<HTMLElement>,
|
||||
groupId: 'group-a',
|
||||
projectGroupById,
|
||||
sidebarProjectGroupHeaderIdsByBucket,
|
||||
getScrollContainer: () => scrollContainer
|
||||
})
|
||||
|
||||
expect(session?.groupId).toBe('group-a')
|
||||
})
|
||||
|
||||
it('does not arm when pressing an svg icon inside an action button', () => {
|
||||
const header = document.createElement('div')
|
||||
header.setAttribute('data-project-group-header-drag-handle', '')
|
||||
const actionButton = document.createElement('button')
|
||||
actionButton.setAttribute('data-repo-header-action', '')
|
||||
const actionIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
|
||||
actionButton.append(actionIcon)
|
||||
header.append(actionButton)
|
||||
const scrollContainer = document.createElement('div')
|
||||
document.body.append(scrollContainer, header)
|
||||
|
||||
const projectGroupById = new Map<string, ProjectGroup>([
|
||||
['group-a', group('group-a')],
|
||||
['group-b', group('group-b')]
|
||||
])
|
||||
const sidebarProjectGroupHeaderIdsByBucket = new Map([['root', ['group-a', 'group-b']]])
|
||||
|
||||
const session = createProjectGroupHeaderDragSession({
|
||||
event: {
|
||||
button: 0,
|
||||
pointerId: 1,
|
||||
clientX: 10,
|
||||
clientY: 20,
|
||||
target: actionIcon,
|
||||
currentTarget: header
|
||||
} as unknown as React.PointerEvent<HTMLElement>,
|
||||
groupId: 'group-a',
|
||||
projectGroupById,
|
||||
sidebarProjectGroupHeaderIdsByBucket,
|
||||
getScrollContainer: () => scrollContainer
|
||||
})
|
||||
|
||||
expect(session).toBeNull()
|
||||
})
|
||||
|
||||
it('does not arm from the actions overlay even if the row is the drag handle', () => {
|
||||
const header = document.createElement('div')
|
||||
header.setAttribute('data-project-group-header-drag-handle', '')
|
||||
const dragSurface = document.createElement('div')
|
||||
const label = document.createElement('span')
|
||||
dragSurface.append(label)
|
||||
const actions = document.createElement('div')
|
||||
actions.setAttribute('data-repo-header-actions', '')
|
||||
header.append(dragSurface, actions)
|
||||
const scrollContainer = document.createElement('div')
|
||||
document.body.append(scrollContainer, header)
|
||||
|
||||
const projectGroupById = new Map<string, ProjectGroup>([
|
||||
['group-a', group('group-a')],
|
||||
['group-b', group('group-b')]
|
||||
])
|
||||
const sidebarProjectGroupHeaderIdsByBucket = new Map([['root', ['group-a', 'group-b']]])
|
||||
|
||||
const sessionFromActions = createProjectGroupHeaderDragSession({
|
||||
event: {
|
||||
button: 0,
|
||||
pointerId: 1,
|
||||
clientX: 10,
|
||||
clientY: 20,
|
||||
target: actions,
|
||||
currentTarget: header
|
||||
} as unknown as React.PointerEvent<HTMLElement>,
|
||||
groupId: 'group-a',
|
||||
projectGroupById,
|
||||
sidebarProjectGroupHeaderIdsByBucket,
|
||||
getScrollContainer: () => scrollContainer
|
||||
})
|
||||
const sessionFromLabel = createProjectGroupHeaderDragSession({
|
||||
event: {
|
||||
button: 0,
|
||||
pointerId: 2,
|
||||
clientX: 10,
|
||||
clientY: 20,
|
||||
target: label,
|
||||
currentTarget: header
|
||||
} as unknown as React.PointerEvent<HTMLElement>,
|
||||
groupId: 'group-a',
|
||||
projectGroupById,
|
||||
sidebarProjectGroupHeaderIdsByBucket,
|
||||
getScrollContainer: () => scrollContainer
|
||||
})
|
||||
const sessionFromRowPadding = createProjectGroupHeaderDragSession({
|
||||
event: {
|
||||
button: 0,
|
||||
pointerId: 3,
|
||||
clientX: 10,
|
||||
clientY: 20,
|
||||
target: header,
|
||||
currentTarget: header
|
||||
} as unknown as React.PointerEvent<HTMLElement>,
|
||||
groupId: 'group-a',
|
||||
projectGroupById,
|
||||
sidebarProjectGroupHeaderIdsByBucket,
|
||||
getScrollContainer: () => scrollContainer
|
||||
})
|
||||
|
||||
expect(sessionFromActions).toBeNull()
|
||||
expect(sessionFromLabel?.groupId).toBe('group-a')
|
||||
expect(sessionFromRowPadding?.groupId).toBe('group-a')
|
||||
})
|
||||
})
|
||||
-150
@@ -1,150 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import './visible-worktrees'
|
||||
import { computeVisibleWorktreeIds } from './compute-visible-worktrees'
|
||||
import {
|
||||
createSleepingSweepRetentionState,
|
||||
updateSleepingSweepRetention
|
||||
} from '../../../../../../shared/sidebar-list/sleeping-sweep-retention'
|
||||
import { hasActiveWorkspaceActivity } from '@/lib/worktree-activity-state'
|
||||
import { LOCAL_EXECUTION_HOST_ID } from '../../../../../../shared/execution-host'
|
||||
import type { Repo } from '../../../../../../shared/repo-types'
|
||||
import type { Worktree } from '../../../../../../shared/worktree/types'
|
||||
|
||||
// PTY rebind gaps must not hide an idle remote workspace and make the sidebar jump.
|
||||
|
||||
function makeRepo(id: string): Repo {
|
||||
return { id, path: `/${id}`, displayName: id, badgeColor: '#000', addedAt: 0 }
|
||||
}
|
||||
|
||||
function makeWorktree(id: string): Worktree {
|
||||
return {
|
||||
id,
|
||||
repoId: 'repo1',
|
||||
path: `/tmp/${id}`,
|
||||
head: 'abc123',
|
||||
branch: `refs/heads/${id}`,
|
||||
isBare: false,
|
||||
isMainWorktree: false,
|
||||
displayName: id,
|
||||
comment: '',
|
||||
linkedIssue: null,
|
||||
linkedPR: null,
|
||||
linkedLinearIssue: null,
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 0
|
||||
}
|
||||
}
|
||||
|
||||
const REMOTE = 'wt-dragfiles-remote'
|
||||
const OTHER = 'wt-resources-remote'
|
||||
const worktrees = [makeWorktree(REMOTE), makeWorktree(OTHER)]
|
||||
const sortedIds = worktrees.map((w) => w.id)
|
||||
const repoMap = new Map<string, Repo>([['repo1', makeRepo('repo1')]])
|
||||
|
||||
type VisibleOptions = Parameters<typeof computeVisibleWorktreeIds>[2]
|
||||
|
||||
const tabsByWorktree = {
|
||||
[REMOTE]: [{ id: 'tab-remote' }],
|
||||
[OTHER]: [{ id: 'tab-other' }]
|
||||
}
|
||||
|
||||
function visibleOptions(overrides: Partial<VisibleOptions> = {}): VisibleOptions {
|
||||
return {
|
||||
filterRepoIds: [],
|
||||
showSleepingWorkspaces: false,
|
||||
tabsByWorktree,
|
||||
ptyIdsByTabId: { 'tab-remote': ['remote:pty-1'], 'tab-other': ['remote:pty-2'] },
|
||||
browserTabsByWorktree: {},
|
||||
worktreeIdsWithLiveAgent: new Set<string>(),
|
||||
hideDefaultBranchWorkspace: false,
|
||||
hideAutomationGeneratedWorkspaces: false,
|
||||
hideCliCreatedWorkspaces: false,
|
||||
hideDetachedHeadWorkspaces: false,
|
||||
hideWorkspacesFromOtherDevices: false,
|
||||
pairedDeviceIdsByEnvironment: new Map(),
|
||||
repoMap,
|
||||
workspaceHostScope: 'all',
|
||||
defaultHostId: LOCAL_EXECUTION_HOST_ID,
|
||||
worktreeLineageById: {},
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function sweepPass(
|
||||
state: ReturnType<typeof createSleepingSweepRetentionState>,
|
||||
ptyIdsByTabId: Record<string, string[]>,
|
||||
nowMs: number
|
||||
): string[] {
|
||||
const worktreeIdsWithLiveAgent = new Set<string>()
|
||||
const { retainedIds } = updateSleepingSweepRetention({
|
||||
state,
|
||||
candidateWorktreeIds: sortedIds,
|
||||
isActive: (worktreeId) =>
|
||||
hasActiveWorkspaceActivity(
|
||||
worktreeId,
|
||||
tabsByWorktree,
|
||||
ptyIdsByTabId,
|
||||
{},
|
||||
worktreeIdsWithLiveAgent
|
||||
),
|
||||
nowMs
|
||||
})
|
||||
return computeVisibleWorktreeIds(
|
||||
{ repo1: worktrees },
|
||||
sortedIds,
|
||||
visibleOptions({ ptyIdsByTabId, sleepingSweepExemptWorktreeIds: retainedIds })
|
||||
)
|
||||
}
|
||||
|
||||
describe('#15996 transient PTY gap under "Hide sleeping"', () => {
|
||||
it('keeps the row through a one-commit gap in ptyIdsByTabId', () => {
|
||||
const state = createSleepingSweepRetentionState()
|
||||
const bound = { 'tab-remote': ['remote:pty-1'], 'tab-other': ['remote:pty-2'] }
|
||||
// Model the transient empty PTY binding during rebind.
|
||||
const rebinding = { 'tab-remote': [], 'tab-other': ['remote:pty-2'] }
|
||||
|
||||
expect(sweepPass(state, bound, 1_000)).toEqual([REMOTE, OTHER])
|
||||
expect(sweepPass(state, rebinding, 1_016)).toEqual([REMOTE, OTHER])
|
||||
expect(sweepPass(state, bound, 1_032)).toEqual([REMOTE, OTHER])
|
||||
})
|
||||
|
||||
it('still sweeps the row once the workspace is genuinely asleep', () => {
|
||||
const state = createSleepingSweepRetentionState()
|
||||
const bound = { 'tab-remote': ['remote:pty-1'], 'tab-other': ['remote:pty-2'] }
|
||||
const closed = { 'tab-remote': [], 'tab-other': ['remote:pty-2'] }
|
||||
|
||||
expect(sweepPass(state, bound, 1_000)).toEqual([REMOTE, OTHER])
|
||||
expect(sweepPass(state, closed, 1_100)).toEqual([REMOTE, OTHER])
|
||||
expect(sweepPass(state, closed, 10_000)).toEqual([OTHER])
|
||||
})
|
||||
|
||||
it('does not let a grace window outrank the repo filter', () => {
|
||||
const state = createSleepingSweepRetentionState()
|
||||
const bound = { 'tab-remote': ['remote:pty-1'], 'tab-other': ['remote:pty-2'] }
|
||||
const rebinding = { 'tab-remote': [], 'tab-other': ['remote:pty-2'] }
|
||||
|
||||
sweepPass(state, bound, 1_000)
|
||||
const { retainedIds } = updateSleepingSweepRetention({
|
||||
state,
|
||||
candidateWorktreeIds: sortedIds,
|
||||
isActive: (worktreeId) =>
|
||||
hasActiveWorkspaceActivity(worktreeId, tabsByWorktree, rebinding, {}, new Set()),
|
||||
nowMs: 1_016
|
||||
})
|
||||
expect([...retainedIds]).toEqual([REMOTE])
|
||||
|
||||
const visible = computeVisibleWorktreeIds(
|
||||
{ repo1: worktrees },
|
||||
sortedIds,
|
||||
visibleOptions({
|
||||
ptyIdsByTabId: rebinding,
|
||||
sleepingSweepExemptWorktreeIds: retainedIds,
|
||||
filterRepoIds: ['repo-other']
|
||||
})
|
||||
)
|
||||
expect(visible).toEqual([])
|
||||
})
|
||||
})
|
||||
-160
@@ -1,160 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type * as ResolvedWorktreeLineage from '../../../../../../shared/resolved-worktree-lineage'
|
||||
import type { Repo } from '../../../../../../shared/repo-types'
|
||||
import type { TerminalTab } from '../../../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types'
|
||||
import type { Worktree } from '../../../../../../shared/worktree/types'
|
||||
import { LOCAL_EXECUTION_HOST_ID } from '../../../../../../shared/execution-host'
|
||||
|
||||
const counters = vi.hoisted(() => ({ cycleDetections: 0 }))
|
||||
|
||||
vi.mock('../../../../../../shared/resolved-worktree-lineage', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof ResolvedWorktreeLineage>()
|
||||
return {
|
||||
...actual,
|
||||
getCyclicLineageChildKeys: (...args: Parameters<typeof actual.getCyclicLineageChildKeys>) => {
|
||||
counters.cycleDetections += 1
|
||||
return actual.getCyclicLineageChildKeys(...args)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
import {
|
||||
computeVisibleWorktreeIds,
|
||||
type computeVisibleWorktrees
|
||||
} from './compute-visible-worktrees'
|
||||
|
||||
import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity'
|
||||
import { getLineageAncestorIndex } from './visible-worktree-indexes'
|
||||
|
||||
type IdentifiedWorktree = Worktree & { instanceId: string }
|
||||
|
||||
function makeWorktree(id: string, repoId = 'repo1'): IdentifiedWorktree {
|
||||
return {
|
||||
id,
|
||||
instanceId: `${id}-instance`,
|
||||
repoId,
|
||||
path: `/tmp/${id}`,
|
||||
head: 'abc123',
|
||||
branch: 'refs/heads/main',
|
||||
isBare: false,
|
||||
isMainWorktree: false,
|
||||
displayName: id,
|
||||
comment: '',
|
||||
linkedIssue: null,
|
||||
linkedPR: null,
|
||||
linkedLinearIssue: null,
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 0
|
||||
}
|
||||
}
|
||||
|
||||
function makeLineage(child: IdentifiedWorktree, parent: IdentifiedWorktree): WorktreeLineage {
|
||||
return {
|
||||
worktreeId: child.id,
|
||||
worktreeInstanceId: child.instanceId,
|
||||
parentWorktreeId: parent.id,
|
||||
parentWorktreeInstanceId: parent.instanceId,
|
||||
origin: 'cli',
|
||||
capture: { source: 'terminal-context', confidence: 'inferred' },
|
||||
createdAt: 1
|
||||
}
|
||||
}
|
||||
|
||||
function makeTab(id: string, worktreeId: string, ptyId: string): TerminalTab {
|
||||
return {
|
||||
id,
|
||||
ptyId,
|
||||
worktreeId,
|
||||
title: id,
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 0
|
||||
}
|
||||
}
|
||||
|
||||
const repoMap = new Map<string, Repo>([
|
||||
['repo1', { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 }]
|
||||
])
|
||||
|
||||
function visibleOptions(
|
||||
overrides: Partial<Parameters<typeof computeVisibleWorktrees>[2]> = {}
|
||||
): Parameters<typeof computeVisibleWorktrees>[2] {
|
||||
return {
|
||||
filterRepoIds: [],
|
||||
showSleepingWorkspaces: true,
|
||||
tabsByWorktree: null,
|
||||
ptyIdsByTabId: null,
|
||||
browserTabsByWorktree: null,
|
||||
worktreeIdsWithLiveAgent: new Set<string>(),
|
||||
hideDefaultBranchWorkspace: false,
|
||||
hideAutomationGeneratedWorkspaces: false,
|
||||
hideCliCreatedWorkspaces: false,
|
||||
hideDetachedHeadWorkspaces: false,
|
||||
hideWorkspacesFromOtherDevices: false,
|
||||
pairedDeviceIdsByEnvironment: new Map<string, string>(),
|
||||
repoMap,
|
||||
workspaceHostScope: 'all',
|
||||
defaultHostId: LOCAL_EXECUTION_HOST_ID,
|
||||
worktreeLineageById: {},
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('visible worktree indexes', () => {
|
||||
it('reuses the lineage projection instead of rebuilding it on every store write', () => {
|
||||
const parent = makeWorktree('parent')
|
||||
const child = makeWorktree('child')
|
||||
const worktreesByRepo = { repo1: [parent, child] }
|
||||
const sortedIds = [parent.id, child.id]
|
||||
const worktreeLineageById = { [child.id]: makeLineage(child, parent) }
|
||||
|
||||
counters.cycleDetections = 0
|
||||
// Model unrelated store writes that rerun visibility without changing worktreesByRepo.
|
||||
for (let write = 0; write < 10; write += 1) {
|
||||
computeVisibleWorktreeIds(worktreesByRepo, sortedIds, visibleOptions({ worktreeLineageById }))
|
||||
}
|
||||
|
||||
expect(counters.cycleDetections).toBe(1)
|
||||
})
|
||||
|
||||
it('keeps archived parents out of the cached ancestor index', () => {
|
||||
const parent = makeWorktree('parent')
|
||||
parent.isArchived = true
|
||||
const child = makeWorktree('child')
|
||||
const worktreesByRepo = { repo1: [parent, child] }
|
||||
const sortedIds = [child.id, parent.id]
|
||||
const worktreeLineageById = { [child.id]: makeLineage(child, parent) }
|
||||
const opts = visibleOptions({
|
||||
showSleepingWorkspaces: false,
|
||||
tabsByWorktree: { [child.id]: [makeTab('t-child', child.id, 'p-child')] },
|
||||
ptyIdsByTabId: { 't-child': ['p-child'] },
|
||||
worktreeLineageById
|
||||
})
|
||||
|
||||
// Check the warm cache too: an archive-inclusive index would inject a phantom ancestor.
|
||||
expect(computeVisibleWorktreeIds(worktreesByRepo, sortedIds, opts)).toEqual([child.id])
|
||||
expect(computeVisibleWorktreeIds(worktreesByRepo, sortedIds, opts)).toEqual([child.id])
|
||||
expect(getLineageAncestorIndex(worktreesByRepo).has(getWorktreeHostIdentity(parent))).toBe(
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps both rows of a two-host id collision', () => {
|
||||
const local: Worktree = {
|
||||
...makeWorktree('shared'),
|
||||
hostId: LOCAL_EXECUTION_HOST_ID,
|
||||
path: '/tmp/local'
|
||||
}
|
||||
const remote: Worktree = { ...makeWorktree('shared'), hostId: 'ssh:box', path: '/tmp/remote' }
|
||||
const worktreesByRepo = { repo1: [local, remote] }
|
||||
|
||||
const index = getLineageAncestorIndex(worktreesByRepo)
|
||||
expect(index.get(getWorktreeHostIdentity(local))?.path).toBe('/tmp/local')
|
||||
expect(index.get(getWorktreeHostIdentity(remote))?.path).toBe('/tmp/remote')
|
||||
})
|
||||
})
|
||||
@@ -1,11 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type {
|
||||
TerminalLayoutSnapshot,
|
||||
TerminalTab
|
||||
} from '../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import {
|
||||
buildResourceSessionBindingIndex,
|
||||
countUnboundDaemonSessions,
|
||||
selectUnboundDaemonSessions
|
||||
} from './resource-session-bindings'
|
||||
|
||||
@@ -24,65 +20,7 @@ function makeTab(id: string, ptyId: string | null = null): TerminalTab {
|
||||
} as unknown as TerminalTab
|
||||
}
|
||||
|
||||
function makeLayout(ptyIdsByLeafId: Record<string, string>): TerminalLayoutSnapshot {
|
||||
return {
|
||||
root: { type: 'leaf', leafId: 'leaf-1' },
|
||||
activeLeafId: 'leaf-1',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId
|
||||
}
|
||||
}
|
||||
|
||||
describe('resource session bindings', () => {
|
||||
it('combines live PTYs with restored tab and split-pane wake hints', () => {
|
||||
const index = buildResourceSessionBindingIndex({
|
||||
ptyIdsByTabId: {
|
||||
'tab-active': ['pty-live', 'pty-live']
|
||||
},
|
||||
tabsByWorktree: {
|
||||
'repo::/workspace': [makeTab('tab-active'), makeTab('tab-restored', 'pty-restored')]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-restored': makeLayout({
|
||||
'leaf-1': 'pty-leaf-a',
|
||||
'leaf-2': 'pty-leaf-b'
|
||||
})
|
||||
},
|
||||
workspaceSessionReady: true
|
||||
})
|
||||
|
||||
expect(index.ptyIdToTabId).toEqual(
|
||||
new Map([
|
||||
['pty-live', 'tab-active'],
|
||||
['pty-restored', 'tab-restored'],
|
||||
['pty-leaf-a', 'tab-restored'],
|
||||
['pty-leaf-b', 'tab-restored']
|
||||
])
|
||||
)
|
||||
expect([...index.boundPtyIds].sort()).toEqual([
|
||||
'pty-leaf-a',
|
||||
'pty-leaf-b',
|
||||
'pty-live',
|
||||
'pty-restored'
|
||||
])
|
||||
})
|
||||
|
||||
it('ignores stale layout-only PTYs after their tab is gone', () => {
|
||||
const index = buildResourceSessionBindingIndex({
|
||||
ptyIdsByTabId: {},
|
||||
tabsByWorktree: {
|
||||
'repo::/workspace': [makeTab('tab-live', null)]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-closed': makeLayout({ 'leaf-1': 'pty-closed' })
|
||||
},
|
||||
workspaceSessionReady: true
|
||||
})
|
||||
|
||||
expect(index.ptyIdToTabId.has('pty-closed')).toBe(false)
|
||||
expect(index.boundPtyIds.has('pty-closed')).toBe(false)
|
||||
})
|
||||
|
||||
it('binds a session deferred for SSH reattach so it is never offered for cleanup', () => {
|
||||
const inputs = {
|
||||
ptyIdsByTabId: {},
|
||||
@@ -107,64 +45,4 @@ describe('resource session bindings', () => {
|
||||
)
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('ignores a deferred session whose tab no longer exists', () => {
|
||||
const index = buildResourceSessionBindingIndex({
|
||||
ptyIdsByTabId: {},
|
||||
tabsByWorktree: { 'repo::/workspace': [makeTab('tab-live')] },
|
||||
terminalLayoutsByTabId: {},
|
||||
deferredSshSessionIdsByTabId: { 'tab-gone': 'pty-stranded' },
|
||||
workspaceSessionReady: true
|
||||
})
|
||||
|
||||
expect(index.boundPtyIds.has('pty-stranded')).toBe(false)
|
||||
})
|
||||
|
||||
it('never offers an agent-owned session for cleanup even with no binding at all', () => {
|
||||
const inputs = {
|
||||
ptyIdsByTabId: {},
|
||||
tabsByWorktree: {},
|
||||
terminalLayoutsByTabId: {},
|
||||
workspaceSessionReady: true
|
||||
}
|
||||
const sessions = [
|
||||
{ id: 'pty-agent', cwd: '/workspace', title: 'codex', agentOwnership: 'present' as const },
|
||||
{ id: 'pty-shell', cwd: '/tmp', title: 'shell', agentOwnership: 'absent' as const }
|
||||
]
|
||||
|
||||
expect(selectUnboundDaemonSessions(sessions, inputs).map((s) => s.id)).toEqual(['pty-shell'])
|
||||
expect(countUnboundDaemonSessions(sessions, inputs)).toBe(1)
|
||||
})
|
||||
|
||||
it('never offers a session whose ownership could not be established', () => {
|
||||
// Older daemons/relays may omit ownership claims; unknown cannot establish owner absence.
|
||||
const inputs = {
|
||||
ptyIdsByTabId: {},
|
||||
tabsByWorktree: {},
|
||||
terminalLayoutsByTabId: {},
|
||||
workspaceSessionReady: true
|
||||
}
|
||||
const sessions = [
|
||||
{ id: 'pty-legacy', cwd: '/workspace', title: 'shell', agentOwnership: 'unknown' as const },
|
||||
{ id: 'pty-known', cwd: '/tmp', title: 'shell', agentOwnership: 'absent' as const }
|
||||
]
|
||||
|
||||
expect(selectUnboundDaemonSessions(sessions, inputs).map((s) => s.id)).toEqual(['pty-known'])
|
||||
expect(countUnboundDaemonSessions(sessions, inputs)).toBe(1)
|
||||
})
|
||||
|
||||
it('offers nothing while the workspace session is still loading', () => {
|
||||
const sessions = [
|
||||
{ id: 'pty-any', cwd: '/tmp', title: 'shell', agentOwnership: 'absent' as const }
|
||||
]
|
||||
const inputs = {
|
||||
ptyIdsByTabId: {},
|
||||
tabsByWorktree: {},
|
||||
terminalLayoutsByTabId: {},
|
||||
workspaceSessionReady: false
|
||||
}
|
||||
|
||||
expect(selectUnboundDaemonSessions(sessions, inputs)).toEqual([])
|
||||
expect(countUnboundDaemonSessions(sessions, inputs)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -19,9 +19,6 @@ globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
const TAB_ID = 'tab-1'
|
||||
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const PANE_KEY = makePaneKey(TAB_ID, LEAF_ID)
|
||||
const TITLE = 'This terminal was opened in a newer version of Orca'
|
||||
const BODY = 'Reopen it here to keep working. Your agent session will resume.'
|
||||
const FAILED_TITLE = "Couldn't reopen this terminal"
|
||||
|
||||
let paneElement: HTMLDivElement
|
||||
let root: Root
|
||||
@@ -76,57 +73,6 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('NewerDaemonHoldBanner', () => {
|
||||
it('renders nothing for a pane that is not held', async () => {
|
||||
await render()
|
||||
expect(paneElement.textContent).toBe('')
|
||||
})
|
||||
|
||||
it('promises a resume only for a pane with a resumable agent session', async () => {
|
||||
hold(PANE_KEY, true)
|
||||
await render()
|
||||
expect(paneElement.textContent).toContain(TITLE)
|
||||
expect(paneElement.textContent).toContain(BODY)
|
||||
hold(PANE_KEY, false)
|
||||
await render()
|
||||
expect(paneElement.textContent).toContain(TITLE)
|
||||
expect(paneElement.textContent).not.toContain(BODY)
|
||||
})
|
||||
|
||||
it('shows Reopening while the stop runs, then nothing once released', async () => {
|
||||
let finish!: (result: NewerDaemonReopenResult) => void
|
||||
reopenNewerDaemonTerminals.mockReturnValue(new Promise((resolve) => (finish = resolve)))
|
||||
hold(PANE_KEY, true)
|
||||
await render()
|
||||
await act(async () => button('Reopen terminal').click())
|
||||
expect(button('Reopening…').disabled).toBe(true)
|
||||
expect(paneElement.textContent).not.toContain('Dismiss')
|
||||
await act(async () => finish({ reopened: true }))
|
||||
expect(paneElement.textContent).toBe('')
|
||||
})
|
||||
|
||||
it('offers Try again after an unconfirmed stop, but not to a pane held afterwards', async () => {
|
||||
reopenNewerDaemonTerminals.mockResolvedValue({ reopened: false })
|
||||
hold(PANE_KEY, true)
|
||||
await render()
|
||||
await act(async () => button('Reopen terminal').click())
|
||||
expect(paneElement.textContent).toContain(FAILED_TITLE)
|
||||
expect(paneElement.textContent).not.toContain(BODY)
|
||||
expect(button('Try again').disabled).toBe(false)
|
||||
hold(PANE_KEY, true)
|
||||
await render()
|
||||
expect(paneElement.textContent).toContain(TITLE)
|
||||
expect(paneElement.textContent).not.toContain(FAILED_TITLE)
|
||||
})
|
||||
|
||||
it('counts every held pane in the label, since one click reopens them all', async () => {
|
||||
hold(PANE_KEY, false)
|
||||
await render()
|
||||
expect(button('Reopen terminal')).toBeTruthy()
|
||||
hold(OTHER_PANE_KEY, false)
|
||||
await render()
|
||||
expect(button('Reopen 2 terminals')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('dismisses only this pane, which stays held and still reopens with the others', async () => {
|
||||
const release = hold(PANE_KEY, false)
|
||||
const otherRelease = hold(OTHER_PANE_KEY, false)
|
||||
@@ -140,13 +86,4 @@ describe('NewerDaemonHoldBanner', () => {
|
||||
expect(release).toHaveBeenCalledTimes(1)
|
||||
expect(otherRelease).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('offers Dismiss after a failed stop', async () => {
|
||||
reopenNewerDaemonTerminals.mockResolvedValue({ reopened: false })
|
||||
hold(PANE_KEY, false)
|
||||
await render()
|
||||
expect(button('Dismiss')).toBeTruthy()
|
||||
await act(async () => button('Reopen terminal').click())
|
||||
expect(button('Dismiss')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { RuntimeHostStatusSnapshot } from '../../../../shared/remote-runtime/host-status/runtime-host-status'
|
||||
import '../../../../shared/protocol-version'
|
||||
import { TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY } from '../../../../shared/terminal/runtime-policy/terminal-runtime-capabilities'
|
||||
import { runtimeHostConnectionStateForEntry } from '@/runtime/runtime-host-connection-state'
|
||||
import {
|
||||
resetPairedRuntimeParkingEnvironmentIdsCacheForTest,
|
||||
selectPairedRuntimeParkingEnvironmentIds
|
||||
} from './paired-runtime-parking-capabilities'
|
||||
|
||||
const ENVIRONMENT_ID = 'runtime-a'
|
||||
|
||||
const getState = vi.fn()
|
||||
vi.mock('@/store', () => ({ useAppStore: { getState: () => getState() } }))
|
||||
vi.mock('@/runtime/runtime-terminal-stream', () => ({
|
||||
getRemoteRuntimePtyEnvironmentId: (ptyId: string) =>
|
||||
ptyId.startsWith('remote:') ? ptyId.slice('remote:'.length).split('/')[0] : null
|
||||
}))
|
||||
|
||||
/** The capability the host answered with while it was still reachable. */
|
||||
function verifiedSnapshot(
|
||||
overrides: Partial<RuntimeHostStatusSnapshot> = {}
|
||||
): RuntimeHostStatusSnapshot {
|
||||
return {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
pairingRevision: 1,
|
||||
sequence: 2,
|
||||
checkedAt: 2,
|
||||
status: {
|
||||
runtimeId: 'r1',
|
||||
rendererGraphEpoch: 1,
|
||||
graphStatus: 'ready',
|
||||
authoritativeWindowId: 1,
|
||||
liveTabCount: 0,
|
||||
liveLeafCount: 0,
|
||||
capabilities: [TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY]
|
||||
},
|
||||
verification: 'unavailable',
|
||||
transport: 'connecting',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('paired parking capability through an unverifiable probe', () => {
|
||||
beforeEach(() => {
|
||||
resetPairedRuntimeParkingEnvironmentIdsCacheForTest()
|
||||
})
|
||||
|
||||
it('keeps the environment capable when the probe nulled the entry status', () => {
|
||||
expect(
|
||||
selectPairedRuntimeParkingEnvironmentIds(
|
||||
new Map([[ENVIRONMENT_ID, { status: null, snapshot: verifiedSnapshot() }]])
|
||||
)
|
||||
).toEqual(new Set([ENVIRONMENT_ID]))
|
||||
})
|
||||
|
||||
// Only a terminal host verdict revokes parking; a transient probe failure must not unpark every hidden tab.
|
||||
it.each([
|
||||
['checking', { verification: 'checking' } as const, 'checking'],
|
||||
['reconnecting', { transport: 'disconnected' } as const, 'reconnecting'],
|
||||
['runtime-unavailable', { transport: 'ready' } as const, 'runtime-unavailable']
|
||||
])('keeps a %s host capable', (_label, patch, expectedState) => {
|
||||
const entry = { status: null, snapshot: verifiedSnapshot(patch) }
|
||||
expect(runtimeHostConnectionStateForEntry(entry)).toBe(expectedState)
|
||||
expect(selectPairedRuntimeParkingEnvironmentIds(new Map([[ENVIRONMENT_ID, entry]]))).toEqual(
|
||||
new Set([ENVIRONMENT_ID])
|
||||
)
|
||||
})
|
||||
|
||||
it('does not invent a capability the host never advertised', () => {
|
||||
expect(
|
||||
selectPairedRuntimeParkingEnvironmentIds(
|
||||
new Map([[ENVIRONMENT_ID, { status: null, snapshot: verifiedSnapshot({ status: null }) }]])
|
||||
)
|
||||
).toEqual(new Set())
|
||||
})
|
||||
|
||||
// A revoked host cannot authorize parking with a restore promise it can no longer fulfill, even when local captures survive.
|
||||
it.each(['blocked', 'retired'] as const)(
|
||||
'drops a %s host that can no longer honour a restore',
|
||||
(kind) => {
|
||||
expect(
|
||||
selectPairedRuntimeParkingEnvironmentIds(
|
||||
new Map([
|
||||
[
|
||||
ENVIRONMENT_ID,
|
||||
{
|
||||
status: null,
|
||||
snapshot: verifiedSnapshot(
|
||||
kind === 'blocked' ? { verification: 'blocked' } : { retired: true }
|
||||
)
|
||||
}
|
||||
]
|
||||
])
|
||||
)
|
||||
).toEqual(new Set())
|
||||
}
|
||||
)
|
||||
|
||||
it('still reads a live entry with no snapshot', () => {
|
||||
expect(
|
||||
selectPairedRuntimeParkingEnvironmentIds(
|
||||
new Map([
|
||||
[
|
||||
ENVIRONMENT_ID,
|
||||
{ status: { capabilities: [TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY] } }
|
||||
]
|
||||
])
|
||||
)
|
||||
).toEqual(new Set([ENVIRONMENT_ID]))
|
||||
})
|
||||
})
|
||||
|
||||
describe('paired parked terminal restore through an unverifiable probe', () => {
|
||||
it('keeps the parked session reattachable when the probe nulled the entry status', async () => {
|
||||
const { canRestorePairedParkedTerminal } =
|
||||
await import('./pty-connection/paired-parked-terminal-restore')
|
||||
getState.mockReturnValue({
|
||||
runtimeStatusByEnvironmentId: new Map([
|
||||
[ENVIRONMENT_ID, { status: null, snapshot: verifiedSnapshot() }]
|
||||
])
|
||||
})
|
||||
expect(canRestorePairedParkedTerminal(`remote:${ENVIRONMENT_ID}/pty-1`)).toBe(true)
|
||||
})
|
||||
|
||||
it.each(['blocked', 'retired'] as const)('refuses a %s host', async (kind) => {
|
||||
const { canRestorePairedParkedTerminal } =
|
||||
await import('./pty-connection/paired-parked-terminal-restore')
|
||||
getState.mockReturnValue({
|
||||
runtimeStatusByEnvironmentId: new Map([
|
||||
[
|
||||
ENVIRONMENT_ID,
|
||||
{
|
||||
status: null,
|
||||
snapshot: verifiedSnapshot(
|
||||
kind === 'blocked' ? { verification: 'blocked' } : { retired: true }
|
||||
)
|
||||
}
|
||||
]
|
||||
])
|
||||
})
|
||||
expect(canRestorePairedParkedTerminal(`remote:${ENVIRONMENT_ID}/pty-1`)).toBe(false)
|
||||
})
|
||||
|
||||
it('refuses a host that never advertised the capability', async () => {
|
||||
const { canRestorePairedParkedTerminal } =
|
||||
await import('./pty-connection/paired-parked-terminal-restore')
|
||||
getState.mockReturnValue({
|
||||
runtimeStatusByEnvironmentId: new Map([
|
||||
[ENVIRONMENT_ID, { status: null, snapshot: verifiedSnapshot({ status: null }) }]
|
||||
])
|
||||
})
|
||||
expect(canRestorePairedParkedTerminal(`remote:${ENVIRONMENT_ID}/pty-1`)).toBe(false)
|
||||
})
|
||||
})
|
||||
-139
@@ -1,139 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
const appStore = vi.hoisted(() => ({
|
||||
getState: vi.fn(() => {
|
||||
throw new Error('These transport fixtures must not read app-store ownership')
|
||||
})
|
||||
}))
|
||||
|
||||
vi.mock('@/store', () => ({ useAppStore: { getState: appStore.getState } }))
|
||||
|
||||
afterEach(() => {
|
||||
expect(appStore.getState).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
import {
|
||||
TerminalStreamOpcode,
|
||||
decodeTerminalStreamFrame,
|
||||
decodeTerminalStreamJson,
|
||||
encodeTerminalStreamFrame,
|
||||
encodeTerminalStreamJson,
|
||||
encodeTerminalStreamText
|
||||
} from '../../../../shared/terminal/stream/terminal-stream-protocol'
|
||||
import { stubRuntimeEnvironmentBridge } from '../../runtime/runtime-environment-bridge-fixture'
|
||||
|
||||
// Drive initial/recovery push grids through real codec→multiplexer→transport; use one singleton stream so every replay retains host dimensions and old-host omission remains unknown.
|
||||
|
||||
describe('remote transport snapshot source-grid threading', () => {
|
||||
const runtimeCall = vi.fn()
|
||||
const runtimeSubscribe = vi.fn()
|
||||
const subscriptionSendBinary = vi.fn()
|
||||
let subscriptionCallbacks: {
|
||||
onResponse: (response: unknown) => void
|
||||
onBinary?: (bytes: Uint8Array<ArrayBufferLike>) => void
|
||||
onError?: (error: { code: string; message: string }) => void
|
||||
onClose?: () => void
|
||||
} | null = null
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.doUnmock('../../runtime/remote-runtime-terminal-multiplexer')
|
||||
vi.clearAllMocks()
|
||||
subscriptionCallbacks = null
|
||||
subscriptionSendBinary.mockReset()
|
||||
runtimeCall.mockResolvedValue({
|
||||
ok: true,
|
||||
result: {
|
||||
terminal: {
|
||||
handle: 'terminal-1',
|
||||
tabId: 'tab-1',
|
||||
leafId: 'pane:1',
|
||||
worktreeId: 'wt-1'
|
||||
}
|
||||
}
|
||||
})
|
||||
runtimeSubscribe.mockImplementation(
|
||||
async (_args: unknown, callbacks: typeof subscriptionCallbacks) => {
|
||||
subscriptionCallbacks = callbacks
|
||||
return { unsubscribe: vi.fn(), sendBinary: subscriptionSendBinary }
|
||||
}
|
||||
)
|
||||
stubRuntimeEnvironmentBridge({ call: runtimeCall, subscribe: runtimeSubscribe })
|
||||
})
|
||||
|
||||
it('carries the host grid on pushed snapshots and omits it when the host has none', async () => {
|
||||
const { createRemoteRuntimePtyTransport } = await import('./remote-runtime-pty-transport')
|
||||
const transport = createRemoteRuntimePtyTransport('env-1', {
|
||||
worktreeId: 'wt-1',
|
||||
tabId: 'tab-1',
|
||||
leafId: 'pane:1'
|
||||
})
|
||||
const onReplayData = vi.fn()
|
||||
transport.attach({
|
||||
existingPtyId: 'remote:env-1@@terminal-1',
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
callbacks: { onReplayData }
|
||||
})
|
||||
|
||||
await expect.poll(() => subscriptionCallbacks !== null, { timeout: 5000 }).toBe(true)
|
||||
subscriptionCallbacks?.onResponse({ ok: true, result: { type: 'ready' } })
|
||||
await expect
|
||||
.poll(() => subscriptionSendBinary.mock.calls.length, { timeout: 5000 })
|
||||
.toBeGreaterThan(0)
|
||||
const subscribeFrame = subscriptionSendBinary.mock.calls
|
||||
.map((call) => decodeTerminalStreamFrame(call[0] as Uint8Array))
|
||||
.find((frame) => frame?.opcode === TerminalStreamOpcode.Subscribe)
|
||||
expect(subscribeFrame).toBeDefined()
|
||||
const streamId = decodeTerminalStreamJson<{ streamId: number }>(
|
||||
subscribeFrame!.payload
|
||||
)!.streamId
|
||||
|
||||
const deliverSnapshot = (start: Record<string, unknown>, body: string): void => {
|
||||
for (const frame of [
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.SnapshotStart,
|
||||
streamId,
|
||||
seq: 0,
|
||||
payload: encodeTerminalStreamJson(start)
|
||||
}),
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.SnapshotChunk,
|
||||
streamId,
|
||||
seq: 0,
|
||||
payload: encodeTerminalStreamText(body)
|
||||
}),
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.SnapshotEnd,
|
||||
streamId,
|
||||
seq: 0,
|
||||
payload: new Uint8Array(0)
|
||||
})
|
||||
]) {
|
||||
subscriptionCallbacks?.onBinary?.(frame)
|
||||
}
|
||||
}
|
||||
|
||||
// Initial subscribe push: the host's 143x43 grid must reach the restorer.
|
||||
deliverSnapshot({ cols: 143, rows: 43, seq: 7, source: 'headless' }, 'restored TUI frame')
|
||||
await expect.poll(() => onReplayData.mock.calls.length, { timeout: 5000 }).toBe(1)
|
||||
expect(onReplayData).toHaveBeenLastCalledWith(
|
||||
'restored TUI frame',
|
||||
expect.objectContaining({ snapshotCols: 143, snapshotRows: 43 })
|
||||
)
|
||||
|
||||
// Server-pushed recovery: untagged, after the initial snapshot landed.
|
||||
deliverSnapshot({ cols: 154, rows: 68, seq: 9, source: 'headless' }, 'recovered')
|
||||
await expect.poll(() => onReplayData.mock.calls.length, { timeout: 5000 }).toBe(2)
|
||||
expect(onReplayData).toHaveBeenLastCalledWith(
|
||||
'\x1b[?2026l\x1b[2J\x1b[3J\x1b[Hrecovered',
|
||||
expect.objectContaining({ snapshotCols: 154, snapshotRows: 68 })
|
||||
)
|
||||
|
||||
// A host that publishes no dimensions must read as unknown, not as a grid.
|
||||
deliverSnapshot({ seq: 11, source: 'headless' }, 'undimensioned')
|
||||
await expect.poll(() => onReplayData.mock.calls.length, { timeout: 5000 }).toBe(3)
|
||||
const [, meta] = onReplayData.mock.calls[2] as [string, Record<string, unknown> | undefined]
|
||||
expect(meta?.snapshotCols).toBeUndefined()
|
||||
expect(meta?.snapshotRows).toBeUndefined()
|
||||
})
|
||||
})
|
||||
+1
-31
@@ -4,7 +4,7 @@ import {
|
||||
captureTerminalPaneRecoveryGeneration,
|
||||
requestTerminalPaneRecovery
|
||||
} from './terminal-pane-recovery'
|
||||
import { bumpTabGeneration, settleCurrentRecovery } from './terminal-recovery-ledger-test-driver'
|
||||
import { bumpTabGeneration } from './terminal-recovery-ledger-test-driver'
|
||||
import {
|
||||
recoveryLedgerMocks as mocks,
|
||||
resetRecoveryLedgerStore,
|
||||
@@ -78,36 +78,6 @@ describe('a pane that never reports an outcome', () => {
|
||||
expect(mocks.remountTerminalTabForRecovery).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('lets the user reopen an unsettled attempt the automatic path is holding', async () => {
|
||||
expect(await requestTerminalPaneRecovery(NEVER_SETTLES)).toBe(true)
|
||||
vi.setSystemTime(16_000)
|
||||
expect(await requestTerminalPaneRecovery(NEVER_SETTLES)).toBe(false)
|
||||
|
||||
// Explicit Retry is new evidence and clears unsettled/cooldown refusal.
|
||||
expect(await requestTerminalPaneRecovery({ ...NEVER_SETTLES, trigger: 'user' })).toBe(true)
|
||||
expect(mocks.remountTerminalTabForRecovery).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('lets a PTY rebind reopen it the moment the pane finally reports', async () => {
|
||||
expect(await requestTerminalPaneRecovery(NEVER_SETTLES)).toBe(true)
|
||||
vi.setSystemTime(16_000)
|
||||
expect(await requestTerminalPaneRecovery(NEVER_SETTLES)).toBe(false)
|
||||
|
||||
settleCurrentRecovery('tab-1', 'success')
|
||||
expect(await requestTerminalPaneRecovery(NEVER_SETTLES)).toBe(true)
|
||||
expect(mocks.remountTerminalTabForRecovery).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('lets an authority change supersede an attempt still sitting pending', async () => {
|
||||
expect(await requestTerminalPaneRecovery(NEVER_SETTLES)).toBe(true)
|
||||
vi.setSystemTime(16_000)
|
||||
expect(await requestTerminalPaneRecovery(NEVER_SETTLES)).toBe(false)
|
||||
|
||||
bumpTabGeneration('tab-1')
|
||||
expect(await requestTerminalPaneRecovery(NEVER_SETTLES)).toBe(true)
|
||||
expect(mocks.remountTerminalTabForRecovery).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('keeps the cap above every trigger but the external lifecycle remount', async () => {
|
||||
for (const now of [0, 31_000, 62_000]) {
|
||||
vi.setSystemTime(now)
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { FLOATING_TERMINAL_WORKTREE_ID, getDefaultSettings } from '../../../shared/constants'
|
||||
import type { ExecutionHostId } from '../../../shared/execution-host'
|
||||
import { useAppStore } from '@/store'
|
||||
import { makeWorktree } from '@/store/slices/worktrees-slice-test-fixtures'
|
||||
import { useActiveProjectSkillRuntime } from './useActiveProjectSkillRuntime'
|
||||
|
||||
function setPlatform(platform: NodeJS.Platform): void {
|
||||
;(window as unknown as { api: unknown }).api = {
|
||||
platform: { get: () => ({ platform }) }
|
||||
}
|
||||
}
|
||||
|
||||
function setWindowsShell(terminalWindowsShell: string): void {
|
||||
useAppStore.setState({
|
||||
settings: { ...getDefaultSettings('/tmp'), terminalWindowsShell }
|
||||
})
|
||||
}
|
||||
|
||||
function setGlobalWslDefault(distro: string): void {
|
||||
useAppStore.setState({
|
||||
settings: {
|
||||
...getDefaultSettings('/tmp'),
|
||||
localWindowsRuntimeDefault: { kind: 'wsl', distro }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
describe('useActiveProjectSkillRuntime', () => {
|
||||
beforeEach(() => {
|
||||
setPlatform('win32')
|
||||
setWindowsShell('git-bash')
|
||||
useAppStore.setState({
|
||||
activeRepoId: null,
|
||||
activeWorktreeId: null,
|
||||
activeWorkspaceExecutionHostId: null,
|
||||
projects: [],
|
||||
repos: [],
|
||||
worktreesByRepo: {},
|
||||
folderWorkspaces: [],
|
||||
projectGroups: [],
|
||||
restoredRuntimeHostIdByWorkspaceSessionKey: {},
|
||||
runtimeEnvironmentCatalogSettled: true,
|
||||
runtimeEnvironments: []
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
delete (window as unknown as { api?: unknown }).api
|
||||
})
|
||||
|
||||
it('adopts the global WSL default when no project is active', () => {
|
||||
setGlobalWslDefault('Ubuntu')
|
||||
const { result } = renderHook(() => useActiveProjectSkillRuntime())
|
||||
|
||||
expect(result.current.agentRuntime).toEqual({
|
||||
runtime: 'wsl',
|
||||
wslDistro: 'Ubuntu',
|
||||
label: 'WSL Ubuntu'
|
||||
})
|
||||
expect(result.current.bundledSkillTarget).toBeNull()
|
||||
expect(result.current.discoveryRuntimeTarget).toEqual({ kind: 'local' })
|
||||
expect(result.current.canUseSkillFreshness).toBe(false)
|
||||
})
|
||||
|
||||
it('ignores a windows-host global default so skill discovery keeps no target', () => {
|
||||
const { result } = renderHook(() => useActiveProjectSkillRuntime())
|
||||
|
||||
expect(result.current.projectRuntime).toBeUndefined()
|
||||
expect(result.current.discoveryTarget).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not adopt the global default once a project is active', () => {
|
||||
setGlobalWslDefault('Ubuntu')
|
||||
useAppStore.setState({ activeRepoId: 'repo-1' })
|
||||
const { result } = renderHook(() => useActiveProjectSkillRuntime())
|
||||
|
||||
expect(result.current.agentRuntime).toBeUndefined()
|
||||
useAppStore.setState({ activeRepoId: null })
|
||||
})
|
||||
|
||||
it('does not inject the local WSL runtime into a remote environment', () => {
|
||||
setGlobalWslDefault('Ubuntu')
|
||||
useAppStore.setState({
|
||||
settings: {
|
||||
...useAppStore.getState().settings!,
|
||||
activeRuntimeEnvironmentId: 'ssh-production'
|
||||
},
|
||||
runtimeEnvironments: [{ id: 'ssh-production' }] as never
|
||||
})
|
||||
const { result } = renderHook(() => useActiveProjectSkillRuntime())
|
||||
|
||||
expect(result.current.agentRuntime).toBeUndefined()
|
||||
})
|
||||
|
||||
it.each<{ name: string; workspaceId: string; hostId: ExecutionHostId }>([
|
||||
{ name: 'SSH worktree', workspaceId: 'repo::/remote/ssh', hostId: 'ssh:box' },
|
||||
{ name: 'paired worktree', workspaceId: 'repo::/remote/paired', hostId: 'runtime:paired' },
|
||||
{ name: 'folder workspace', workspaceId: 'folder:restored', hostId: 'runtime:paired' }
|
||||
])(
|
||||
'keeps a restored $name unresolved while owner rows are missing',
|
||||
({ workspaceId, hostId }) => {
|
||||
useAppStore.setState({
|
||||
activeRepoId: 'repo',
|
||||
activeWorktreeId: workspaceId,
|
||||
activeWorkspaceExecutionHostId: hostId
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useActiveProjectSkillRuntime())
|
||||
|
||||
expect(result.current.bundledSkillTarget).toBeNull()
|
||||
expect(result.current.discoveryRuntimeTarget).toBeNull()
|
||||
expect(result.current.canUseSkillFreshness).toBe(false)
|
||||
}
|
||||
)
|
||||
|
||||
it('keeps a local target when no workspace is active', () => {
|
||||
const { result } = renderHook(() => useActiveProjectSkillRuntime())
|
||||
|
||||
expect(result.current.bundledSkillTarget).toEqual({ kind: 'local' })
|
||||
expect(result.current.canUseSkillFreshness).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps a proven local target for floating terminals', () => {
|
||||
useAppStore.setState({ activeWorktreeId: FLOATING_TERMINAL_WORKTREE_ID })
|
||||
const { result } = renderHook(() => useActiveProjectSkillRuntime())
|
||||
|
||||
expect(result.current.bundledSkillTarget).toEqual({ kind: 'local' })
|
||||
expect(result.current.canUseSkillFreshness).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps proven local workspace ownership ahead of a focused paired transport', () => {
|
||||
const worktree = makeWorktree({ id: 'repo::/local', repoId: 'repo', hostId: 'local' })
|
||||
useAppStore.setState({
|
||||
activeWorktreeId: worktree.id,
|
||||
activeWorkspaceExecutionHostId: 'local',
|
||||
worktreesByRepo: { repo: [worktree] },
|
||||
settings: { ...getDefaultSettings('/tmp'), activeRuntimeEnvironmentId: 'paired' },
|
||||
runtimeEnvironments: [
|
||||
{
|
||||
id: 'paired',
|
||||
name: 'Paired',
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
lastUsedAt: null,
|
||||
runtimeId: null,
|
||||
endpoints: [],
|
||||
preferredEndpointId: 'endpoint'
|
||||
}
|
||||
]
|
||||
})
|
||||
const { result } = renderHook(() => useActiveProjectSkillRuntime())
|
||||
expect(result.current.bundledSkillTarget).toEqual({ kind: 'local' })
|
||||
expect(result.current.discoveryRuntimeTarget).toEqual({ kind: 'local' })
|
||||
})
|
||||
})
|
||||
@@ -16,7 +16,6 @@ const SYNC_START = '\x1b[?2026h'
|
||||
const SYNC_END = '\x1b[?2026l'
|
||||
const ERASE_LINE = '\x1b[K'
|
||||
// xterm's SynchronizedOutputHandler safety timeout.
|
||||
const XTERM_SYNCHRONIZED_OUTPUT_TIMEOUT_MS = 1_000
|
||||
|
||||
// Codex 0.158 wraps each redraw in DEC 2026 and erases rows before repainting them.
|
||||
function firstCodexFrameWithErase(): { erased: string; rest: string } {
|
||||
@@ -130,15 +129,4 @@ describe('presentPaneViewport during synchronized output', () => {
|
||||
await vi.advanceTimersByTimeAsync(50)
|
||||
expect(screenText()).not.toContain(COHERENT_TEXT)
|
||||
})
|
||||
|
||||
it('still paints a frame the agent never closes once xterm times out', async () => {
|
||||
const frame = firstCodexFrameWithErase()
|
||||
await write(terminal, SYNC_START + frame.erased)
|
||||
|
||||
presentPaneViewport(pane)
|
||||
await vi.advanceTimersByTimeAsync(XTERM_SYNCHRONIZED_OUTPUT_TIMEOUT_MS - 1)
|
||||
expect(screenText()).toContain(COHERENT_TEXT)
|
||||
await vi.advanceTimersByTimeAsync(50)
|
||||
expect(screenText()).not.toContain(COHERENT_TEXT)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
// Reload main’s saved restored-editor move (F42/Q5); frame-drawn tab and file must exist only in destination workspace. Main Store counterpart: main/runtime/restored-editor-move-restart.test.ts.
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as AgentStatusModule from '@/lib/agent-status'
|
||||
import { applyLayoutCommand } from '../../../shared/workspace-layout/workspace-layout-commands'
|
||||
import { testContext } from '../../../shared/workspace-layout/workspace-layout-command.test-fixture'
|
||||
import { loadWorkspaceLayoutWithoutReport } from '../../../shared/workspace-layout/workspace-layout-load'
|
||||
import { nameBasedLoadContext } from '../../../shared/workspace-layout/workspace-layout-minted-ids'
|
||||
import { localDesktopSession } from '../../../shared/workspace-layout/workspace-layout-profile.test-fixture'
|
||||
import { saveWorkspaceLayout } from '../../../shared/workspace-layout/workspace-layout-save'
|
||||
import {
|
||||
FOLDER_KEY,
|
||||
GIT_KEY
|
||||
} from '../../../shared/workspace-layout/workspace-layout-session.test-fixture'
|
||||
import type { WorkspaceLayoutChangeFrame } from '../../../shared/workspace-layout/workspace-layout-stream-frames'
|
||||
import { ownedEditorFileId } from '../../../shared/workspace-session/workspace-session-pane-ownership'
|
||||
import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types'
|
||||
import { bootWindowFromPartitions } from '../app-shell/startup-window-view.test-fixture'
|
||||
import { createStoreSessionMockApi } from '../store/slices/store-session-test-harness'
|
||||
import { createTestStore } from '../store/slices/store-test-helpers'
|
||||
import { endLayoutFramePositions } from './layout-frame-position'
|
||||
import {
|
||||
loadMainLayoutModel,
|
||||
mainLayoutFrameSender,
|
||||
publishedLayoutsOf
|
||||
} from './main-loaded-layout-frames.test-fixture'
|
||||
import { installLayoutFrameApplyCheck } from './workspace-layout-frame-apply-check.test-fixture'
|
||||
import { openWorkspaceLayoutFrameSync } from './workspace-layout-frame-sync'
|
||||
|
||||
vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true }))
|
||||
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
|
||||
vi.mock('@/lib/agent-status', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof AgentStatusModule>()
|
||||
return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) }
|
||||
})
|
||||
|
||||
const stream = vi.hoisted(
|
||||
(): { onFrame: ((frame: WorkspaceLayoutChangeFrame) => void) | null } => ({ onFrame: null })
|
||||
)
|
||||
vi.mock('./runtime-layout-client', () => ({
|
||||
subscribeRuntimeLayout: (
|
||||
_target: unknown,
|
||||
_params: unknown,
|
||||
onFrame: (frame: WorkspaceLayoutChangeFrame) => void
|
||||
) => {
|
||||
stream.onFrame = onFrame
|
||||
return { close: () => {} }
|
||||
}
|
||||
}))
|
||||
|
||||
createStoreSessionMockApi()
|
||||
|
||||
const settle = () => new Promise<void>((resolve) => setTimeout(resolve, 0))
|
||||
|
||||
const TAB_ID = 'editor:src/app.ts'
|
||||
const FILE_PATH = '/Users/dev/orca/src/app.ts'
|
||||
const MOVED_ID = ownedEditorFileId(FILE_PATH, FOLDER_KEY, null)
|
||||
|
||||
/** The session main saves after applying the window's re-own of the restored tab to the folder. */
|
||||
function sessionSavedAfterMove(): WorkspaceSessionState {
|
||||
const loaded = loadWorkspaceLayoutWithoutReport(
|
||||
'local',
|
||||
localDesktopSession(),
|
||||
nameBasedLoadContext()
|
||||
)
|
||||
const moved = applyLayoutCommand(
|
||||
loaded.layout,
|
||||
{
|
||||
type: 'moveTabToWorkspace',
|
||||
workspace: GIT_KEY,
|
||||
toWorkspace: FOLDER_KEY,
|
||||
tabs: [{ tabId: TAB_ID, newTabId: TAB_ID, newEntityId: MOVED_ID }],
|
||||
groupId: 'group-folder',
|
||||
file: { filePath: FILE_PATH, relativePath: 'app.ts', language: 'typescript' }
|
||||
},
|
||||
testContext()
|
||||
)
|
||||
if (!moved.ok) {
|
||||
throw new Error(`main refused the move: ${moved.code}`)
|
||||
}
|
||||
return saveWorkspaceLayout({ ...loaded, layout: moved.model })
|
||||
}
|
||||
|
||||
let check: ReturnType<typeof installLayoutFrameApplyCheck>
|
||||
beforeEach(() => {
|
||||
check = installLayoutFrameApplyCheck()
|
||||
})
|
||||
afterEach(() => {
|
||||
endLayoutFramePositions()
|
||||
check.uninstall()
|
||||
expect(check.failures).toEqual([])
|
||||
})
|
||||
|
||||
describe('a window reloaded after main saved a restored-editor move', () => {
|
||||
it('shows the tab and its open file in the new workspace, once', async () => {
|
||||
const saved = sessionSavedAfterMove()
|
||||
const store = createTestStore()
|
||||
await bootWindowFromPartitions(store, [{ hostId: 'local', session: saved }])
|
||||
const sync = openWorkspaceLayoutFrameSync(store)
|
||||
stream.onFrame!(
|
||||
mainLayoutFrameSender().snapshot(publishedLayoutsOf(loadMainLayoutModel('local', saved)))
|
||||
)
|
||||
sync.start()
|
||||
await settle()
|
||||
|
||||
const state = store.getState()
|
||||
const editorTabs = Object.entries(state.unifiedTabsByWorktree).flatMap(([key, tabs]) =>
|
||||
tabs.filter((tab) => tab.contentType === 'editor').map((tab) => ({ key, tab }))
|
||||
)
|
||||
expect(editorTabs).toEqual([
|
||||
{ key: FOLDER_KEY, tab: expect.objectContaining({ id: TAB_ID, entityId: MOVED_ID }) }
|
||||
])
|
||||
expect(
|
||||
state.groupsByWorktree[FOLDER_KEY]?.find((group) => group.id === 'group-folder')?.tabOrder
|
||||
).toContain(TAB_ID)
|
||||
expect(state.groupsByWorktree[GIT_KEY]?.some((g) => g.tabOrder.includes(TAB_ID))).toBe(false)
|
||||
// The tab's file is the window's one open file for that path, under the tab's id.
|
||||
expect(
|
||||
state.openFiles
|
||||
.filter((file) => file.filePath === FILE_PATH)
|
||||
.map(({ id, worktreeId, relativePath }) => ({ id, worktreeId, relativePath }))
|
||||
).toEqual([{ id: MOVED_ID, worktreeId: FOLDER_KEY, relativePath: 'app.ts' }])
|
||||
sync.close()
|
||||
})
|
||||
})
|
||||
@@ -1,157 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-types'
|
||||
import { collectLeafIds } from '../../../shared/workspace-layout/terminal-pane-layout-tree'
|
||||
import {
|
||||
planTerminalLiveLayoutRemovals,
|
||||
selectRetiredPaneIds,
|
||||
trackRetiredLeafIds
|
||||
} from '../components/terminal-pane/terminal-live-layout-reconciliation'
|
||||
import { applyFreshWebSessionTabsSnapshot } from './web-session-tabs-sync/snapshot-api'
|
||||
import {
|
||||
clearWebSessionTerminalOrphanRecoveryForTests,
|
||||
recoverWebSessionTerminalOrphansBeforeApply
|
||||
} from './web-session-terminal-orphan-recovery'
|
||||
import {
|
||||
ENV,
|
||||
LEAF_ID,
|
||||
SECOND_LEAF_ID,
|
||||
makeSnapshot,
|
||||
makeState,
|
||||
resetWebSessionTabsSyncTestState
|
||||
} from './web-session-tabs-sync-test-harness'
|
||||
|
||||
vi.mock('../store', () => ({ useAppStore: { setState: vi.fn() } }))
|
||||
vi.mock('@/hooks/agent-hook-completion-notifications', () => ({
|
||||
observeAgentHookCompletionForNotification: vi.fn()
|
||||
}))
|
||||
|
||||
const TAB_ID = 'web-terminal-host-tab-1'
|
||||
const mountedLeaves = [LEAF_ID, SECOND_LEAF_ID]
|
||||
|
||||
function snapshot(version: number, leaves = mountedLeaves): RuntimeMobileSessionTabsResult {
|
||||
return makeSnapshot(
|
||||
leaves.map((leafId) => ({
|
||||
type: 'terminal' as const,
|
||||
id: `host-tab-1::${leafId}`,
|
||||
parentTabId: 'host-tab-1',
|
||||
leafId,
|
||||
title: 'shell',
|
||||
isActive: leafId === LEAF_ID,
|
||||
status: 'ready' as const,
|
||||
terminal: `terminal-${leafId}`
|
||||
})),
|
||||
{ snapshotVersion: version }
|
||||
)
|
||||
}
|
||||
|
||||
function retiredSnapshot(): RuntimeMobileSessionTabsResult {
|
||||
return {
|
||||
...snapshot(3, [LEAF_ID]),
|
||||
retiredTerminalSurfaces: [
|
||||
{
|
||||
parentTabId: 'host-tab-1',
|
||||
leafId: SECOND_LEAF_ID,
|
||||
terminal: `terminal-${SECOND_LEAF_ID}`,
|
||||
ptyId: 'native-second',
|
||||
incarnationId: 'inc-second'
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
function createReconciliation() {
|
||||
let state = makeState()
|
||||
let previousLayoutLeafIds: ReadonlySet<string> = new Set()
|
||||
let retiredLeafIds: ReadonlySet<string> = new Set()
|
||||
const mounted = new Set(mountedLeaves)
|
||||
const call = vi.fn(async () => {
|
||||
throw new Error('execution host unavailable')
|
||||
})
|
||||
|
||||
function plan(secondPtyId: string | null): number[] {
|
||||
const root = state.terminalLayoutsByTabId[TAB_ID]?.root
|
||||
expect(root).toBeDefined()
|
||||
const layoutLeafIds = new Set(root ? collectLeafIds(root) : [])
|
||||
retiredLeafIds = trackRetiredLeafIds({
|
||||
retiredLeafIds,
|
||||
previousLayoutLeafIds,
|
||||
layoutLeafIds,
|
||||
mountedLeafIds: mounted
|
||||
})
|
||||
previousLayoutLeafIds = layoutLeafIds
|
||||
return selectRetiredPaneIds(planTerminalLiveLayoutRemovals(root, mounted, retiredLeafIds), {
|
||||
paneCount: mounted.size,
|
||||
paneIdForLeaf: (leaf) => (leaf === LEAF_ID ? 1 : 2),
|
||||
ptyIdForPane: (pane) => (pane === 1 ? 'remote:first' : secondPtyId)
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
call,
|
||||
plan,
|
||||
removeSecond: () => mounted.delete(SECOND_LEAF_ID),
|
||||
leaves: () => collectLeafIds(state.terminalLayoutsByTabId[TAB_ID].root!),
|
||||
async receive(incoming: RuntimeMobileSessionTabsResult) {
|
||||
const recovered = await recoverWebSessionTerminalOrphansBeforeApply(state, incoming, ENV, {
|
||||
call
|
||||
})
|
||||
expect(recovered).not.toBeNull()
|
||||
if (recovered) {
|
||||
state = { ...state, ...applyFreshWebSessionTabsSnapshot(state, recovered, ENV) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('host snapshot fences before split-pane retirement', () => {
|
||||
beforeEach(() => {
|
||||
resetWebSessionTabsSyncTestState()
|
||||
clearWebSessionTerminalOrphanRecoveryForTests()
|
||||
})
|
||||
|
||||
it('keeps a null-transport pane when an older layout arrives', async () => {
|
||||
const view = createReconciliation()
|
||||
await view.receive(snapshot(2))
|
||||
expect(view.plan('remote:second')).toEqual([])
|
||||
await view.receive(retiredSnapshotWithVersion(1))
|
||||
expect(view.leaves()).toEqual(mountedLeaves)
|
||||
expect(view.plan(null)).toEqual([])
|
||||
})
|
||||
|
||||
it('retains a missing pane when a newer layout cannot verify the host inventory', async () => {
|
||||
const view = createReconciliation()
|
||||
await view.receive(snapshot(2))
|
||||
view.plan('remote:second')
|
||||
await view.receive(snapshot(3, [LEAF_ID]))
|
||||
expect(view.call).toHaveBeenCalled()
|
||||
expect(view.leaves()).toContain(SECOND_LEAF_ID)
|
||||
expect(view.plan(null)).toEqual([])
|
||||
})
|
||||
|
||||
it('defers proven retirement until the transport clears and does not close twice', async () => {
|
||||
const view = createReconciliation()
|
||||
await view.receive(snapshot(2))
|
||||
view.plan('remote:second')
|
||||
await view.receive(retiredSnapshot())
|
||||
expect(view.leaves()).toEqual([LEAF_ID])
|
||||
expect(view.plan('remote:second')).toEqual([])
|
||||
expect(view.plan(null)).toEqual([2])
|
||||
view.removeSecond()
|
||||
expect(view.plan(null)).toEqual([])
|
||||
})
|
||||
|
||||
it('clears deferred retirement when the host reintroduces the leaf before detach', async () => {
|
||||
const view = createReconciliation()
|
||||
await view.receive(snapshot(2))
|
||||
view.plan('remote:second')
|
||||
await view.receive(retiredSnapshot())
|
||||
expect(view.plan('remote:second')).toEqual([])
|
||||
await view.receive(snapshot(4))
|
||||
expect(view.leaves()).toEqual(mountedLeaves)
|
||||
expect(view.plan(null)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
function retiredSnapshotWithVersion(snapshotVersion: number): RuntimeMobileSessionTabsResult {
|
||||
return { ...retiredSnapshot(), snapshotVersion }
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type * as AgentStatusModule from '@/lib/agent-status'
|
||||
import { reconcileHydratedWorkspaceTabModels } from '../../app-shell/reconcile-hydrated-workspace-tab-models'
|
||||
import {
|
||||
LAYOUT_OWNER_WRITTEN_SESSION_GOLDEN_PATH,
|
||||
LAYOUT_OWNER_WRITTEN_SESSION_WORKTREE_ID as WT
|
||||
} from '../../../../shared/__fixtures__/layout-owner-written-session-golden-paths'
|
||||
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch'
|
||||
import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-pane-tree'
|
||||
import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types'
|
||||
import { createTestStore, makeWorktree } from './store-test-helpers'
|
||||
import { createStoreSessionMockApi } from './store-session-test-harness'
|
||||
|
||||
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
|
||||
vi.mock('@/lib/agent-status', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof AgentStatusModule>()
|
||||
return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) }
|
||||
})
|
||||
|
||||
createStoreSessionMockApi()
|
||||
|
||||
/** The startup hydration a switch-off window runs (use-app-startup-hydration.ts). */
|
||||
function restoredWindow(session: WorkspaceSessionState) {
|
||||
const store = createTestStore()
|
||||
store.setState({
|
||||
repos: [
|
||||
{
|
||||
id: 'repo-local',
|
||||
path: '/fixture/local',
|
||||
displayName: 'local',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0
|
||||
}
|
||||
],
|
||||
worktreesByRepo: {
|
||||
'repo-local': [makeWorktree({ id: WT, repoId: 'repo-local', path: '/fixture/local' })]
|
||||
}
|
||||
})
|
||||
const actions = store.getState()
|
||||
actions.hydrateWorkspaceSession(session, {})
|
||||
actions.hydrateTabsSession(session, {})
|
||||
actions.hydrateEditorSession(session, {})
|
||||
actions.hydrateBrowserSession(session, {})
|
||||
reconcileHydratedWorkspaceTabModels(session, store.getState().reconcileWorktreeTabModels)
|
||||
return store.getState()
|
||||
}
|
||||
|
||||
const leaf = (n: number): string => `${n}${n}${n}${n}${n}${n}${n}${n}-1111-4111-8111-111111111111`
|
||||
|
||||
describe.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN)(
|
||||
'a switch-off window restoring the session a layout-owner build wrote (downgrade probe, L8)',
|
||||
() => {
|
||||
it('shows the same tabs, panes, groups, editor file and browser tab', () => {
|
||||
const golden: WorkspaceSessionState = JSON.parse(
|
||||
readFileSync(LAYOUT_OWNER_WRITTEN_SESSION_GOLDEN_PATH, 'utf8')
|
||||
)
|
||||
|
||||
const state = restoredWindow(golden)
|
||||
|
||||
expect(
|
||||
state.tabsByWorktree[WT]?.map((tab) => [tab.id, tab.customTitle ?? tab.title])
|
||||
).toEqual([
|
||||
['tab-shell', 'Terminal 1'],
|
||||
['tab-build', 'Build']
|
||||
])
|
||||
const panes = (tabId: string) => {
|
||||
const layout = state.terminalLayoutsByTabId[tabId]
|
||||
return {
|
||||
leaves: collectLayoutLeafIdsInOrder(layout?.root),
|
||||
active: layout?.activeLeafId,
|
||||
bindings: layout?.ptyIdsByLeafId
|
||||
}
|
||||
}
|
||||
expect(state.terminalLayoutsByTabId['tab-shell']?.root).toMatchObject({
|
||||
type: 'split',
|
||||
direction: 'vertical'
|
||||
})
|
||||
// The pane binding must survive the downgrade, or the shell would not reattach.
|
||||
expect(panes('tab-shell')).toEqual({
|
||||
leaves: [leaf(1), leaf(3)],
|
||||
active: leaf(1),
|
||||
bindings: { [leaf(1)]: 'pty-shell' }
|
||||
})
|
||||
expect(panes('tab-build')).toEqual({ leaves: [leaf(2)], active: leaf(2), bindings: {} })
|
||||
const groups = state.groupsByWorktree[WT] ?? []
|
||||
expect(groups.map((group) => [group.tabOrder, group.activeTabId])).toEqual([
|
||||
[['tab-shell', 'tab-readme', 'tab-docs'], 'tab-shell'],
|
||||
[['tab-build'], 'tab-build']
|
||||
])
|
||||
expect(state.layoutByWorktree[WT]).toMatchObject({ type: 'split', direction: 'horizontal' })
|
||||
const byId = new Map(state.unifiedTabsByWorktree[WT]?.map((tab) => [tab.id, tab]))
|
||||
expect(
|
||||
groups.map((group) =>
|
||||
group.tabOrder.map((id) => [byId.get(id)?.contentType, byId.get(id)?.groupId])
|
||||
)
|
||||
).toEqual([
|
||||
[
|
||||
['terminal', groups[0]?.id],
|
||||
['editor', groups[0]?.id],
|
||||
['browser', groups[0]?.id]
|
||||
],
|
||||
[['terminal', groups[1]?.id]]
|
||||
])
|
||||
expect(byId.size).toBe(4)
|
||||
expect(
|
||||
state.unifiedTabsByWorktree[WT]?.find((tab) => tab.id === 'tab-build')?.customLabel
|
||||
).toBe('Build')
|
||||
expect(state.openFiles.map((file) => [file.filePath, file.mode])).toEqual([
|
||||
['/fixture/local/README.md', 'edit']
|
||||
])
|
||||
expect(state.browserTabsByWorktree[WT]?.map((tab) => [tab.id, tab.pageIds])).toEqual([
|
||||
['browser-docs', ['page-docs']]
|
||||
])
|
||||
expect(state.browserPagesByWorkspace['browser-docs']?.map((page) => page.url)).toEqual([
|
||||
'https://example.com/docs'
|
||||
])
|
||||
expect([state.activeWorktreeId, state.activeTabId]).toEqual([WT, 'tab-shell'])
|
||||
// The closed tab stays closed.
|
||||
expect(JSON.stringify(state.unifiedTabsByWorktree)).not.toContain('tab-scratch')
|
||||
expect(state.tabsByWorktree[WT]?.some((tab) => tab.id === 'tab-scratch')).toBe(false)
|
||||
})
|
||||
}
|
||||
)
|
||||
@@ -1,138 +0,0 @@
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import type * as AgentStatusModule from '@/lib/agent-status'
|
||||
import type { Tab } from '../../../../shared/tab-types'
|
||||
import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types'
|
||||
import type { WslMovedProject } from '../../../../shared/wsl-move/wsl-moved-project'
|
||||
import { getDefaultWorkspaceSession } from '../../../../shared/constants'
|
||||
|
||||
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
|
||||
vi.mock('@/lib/agent-status', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof AgentStatusModule>()
|
||||
return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) }
|
||||
})
|
||||
|
||||
// @ts-expect-error -- mocked browser preload API
|
||||
globalThis.window = { api: {} }
|
||||
|
||||
import { buildWorkspaceSessionPayload } from '@/lib/workspace-session'
|
||||
import {
|
||||
collectWslMovedWorkspaceKeysFromSession,
|
||||
findWslMovedProjectForWorkspace,
|
||||
selectWslMovedChatWorkspaces
|
||||
} from '../repos/wsl-moved-projects'
|
||||
import { createTestStore, makeTab, makeWorktree } from './store-test-helpers'
|
||||
|
||||
// The local row's checkout, as a UNC path; the host lists the same repo id at its Linux path.
|
||||
const MOVED = 'repo1::\\\\wsl.localhost\\Ubuntu\\home\\dev\\repo1'
|
||||
const ON_HOST = 'repo1::/home/dev/repo1'
|
||||
const GROUP = 'group-1'
|
||||
const TERMINAL = 'terminal-1'
|
||||
const EDITOR = '\\\\wsl.localhost\\Ubuntu\\home\\dev\\repo1\\README.md'
|
||||
const CHAT = 'agent-session:chat-1'
|
||||
const projects: WslMovedProject[] = [
|
||||
{ kind: 'repo', id: 'repo1', displayName: 'Repo 1', path: MOVED, distro: 'Ubuntu' }
|
||||
]
|
||||
|
||||
function tab(id: string, contentType: Tab['contentType'], sortOrder: number): Tab {
|
||||
return {
|
||||
id,
|
||||
entityId: contentType === 'agent-session' ? 'chat-1' : id,
|
||||
groupId: GROUP,
|
||||
worktreeId: MOVED,
|
||||
contentType,
|
||||
label: id,
|
||||
customLabel: null,
|
||||
color: null,
|
||||
sortOrder,
|
||||
createdAt: sortOrder
|
||||
}
|
||||
}
|
||||
|
||||
function movedSession(): WorkspaceSessionState {
|
||||
return {
|
||||
...getDefaultWorkspaceSession(),
|
||||
activeRepoId: 'repo1',
|
||||
activeWorktreeId: MOVED,
|
||||
tabsByWorktree: { [MOVED]: [makeTab({ id: TERMINAL, worktreeId: MOVED })] },
|
||||
openFilesByWorktree: {
|
||||
[MOVED]: [{ filePath: EDITOR, relativePath: 'README.md', worktreeId: MOVED, language: 'md' }]
|
||||
},
|
||||
unifiedTabs: {
|
||||
[MOVED]: [
|
||||
tab(TERMINAL, 'terminal', 0),
|
||||
tab(EDITOR, 'editor', 1),
|
||||
tab(CHAT, 'agent-session', 2)
|
||||
]
|
||||
},
|
||||
tabGroups: {
|
||||
[MOVED]: [
|
||||
{ id: GROUP, worktreeId: MOVED, activeTabId: TERMINAL, tabOrder: [TERMINAL, EDITOR, CHAT] }
|
||||
]
|
||||
},
|
||||
activeGroupIdByWorktree: { [MOVED]: GROUP }
|
||||
}
|
||||
}
|
||||
|
||||
function hydrate(store: ReturnType<typeof createTestStore>, session: WorkspaceSessionState) {
|
||||
// The host's same-id repo is known and listed; without the moved keys the degraded rule would
|
||||
// keep the unlisted local worktree whole.
|
||||
store.setState({
|
||||
repos: [
|
||||
{
|
||||
id: 'repo1',
|
||||
path: '/home/dev/repo1',
|
||||
displayName: 'Repo 1',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0
|
||||
}
|
||||
],
|
||||
worktreesByRepo: { repo1: [] },
|
||||
wslMovedProjects: projects
|
||||
})
|
||||
const options = {
|
||||
wslMovedChatWorkspaceKeys: collectWslMovedWorkspaceKeysFromSession(session, projects)
|
||||
}
|
||||
store.getState().hydrateWorkspaceSession(session, options)
|
||||
store.getState().hydrateTabsSession(session, options)
|
||||
store.getState().hydrateEditorSession(session, options)
|
||||
store.getState().hydrateBrowserSession(session, options)
|
||||
}
|
||||
|
||||
it("keeps only a moved project's chat tab through hydration and persistence", () => {
|
||||
const store = createTestStore()
|
||||
hydrate(store, movedSession())
|
||||
|
||||
const state = store.getState()
|
||||
expect(state.unifiedTabsByWorktree[MOVED]?.map((entry) => entry.id)).toEqual([CHAT])
|
||||
expect(state.groupsByWorktree[MOVED]?.[0]?.tabOrder).toEqual([CHAT])
|
||||
expect(state.tabsByWorktree[MOVED]).toBeUndefined()
|
||||
expect(state.openFiles).toEqual([])
|
||||
|
||||
store.setState({ workspaceSessionReady: true })
|
||||
store.getState().setHydrationSucceeded(true)
|
||||
const persisted = buildWorkspaceSessionPayload(store.getState())
|
||||
expect(persisted.unifiedTabs?.[MOVED]?.map((entry) => entry.id)).toEqual([CHAT])
|
||||
})
|
||||
|
||||
it("lists the moved chats under their project, and never the host's listed worktree", () => {
|
||||
const store = createTestStore()
|
||||
hydrate(store, movedSession())
|
||||
store.setState({
|
||||
worktreesByRepo: {
|
||||
repo1: [makeWorktree({ id: ON_HOST, repoId: 'repo1', path: '/home/dev/repo1' })]
|
||||
},
|
||||
unifiedTabsByWorktree: {
|
||||
...store.getState().unifiedTabsByWorktree,
|
||||
[ON_HOST]: [{ ...tab('agent-session:host', 'agent-session', 0), worktreeId: ON_HOST }]
|
||||
}
|
||||
})
|
||||
const state = store.getState()
|
||||
expect(findWslMovedProjectForWorkspace(state, MOVED)?.id).toBe('repo1')
|
||||
expect(findWslMovedProjectForWorkspace(state, ON_HOST)).toBeNull()
|
||||
expect(
|
||||
selectWslMovedChatWorkspaces(state).map(({ project, workspaces }) => ({
|
||||
project: project.id,
|
||||
workspaces: workspaces.map(({ key, chats }) => ({ key, chats: chats.map((c) => c.id) }))
|
||||
}))
|
||||
).toEqual([{ project: 'repo1', workspaces: [{ key: MOVED, chats: [CHAT] }] }])
|
||||
})
|
||||
Reference in New Issue
Block a user