diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index fb86c7904..0dd16bca1 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -2224,6 +2224,7 @@ "Advanced Active Server setting", "saved server Connect and Disconnect", "remote workspace navigation", + "Add Project host selection, scan, import, and catalog refresh", "terminal reveal and create", "browser and mobile handoff", "app restart" @@ -2232,12 +2233,16 @@ "providers": ["local", "remote-runtime", "ssh", "wsl"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "remote-runtime", "ssh", "wsl"], - "coverageNotes": "Platform-neutral deterministic tests separate the durable Active Server preference from per-client connection, selected-workspace, browser-session, and execution-host routing. The composed regression models Local desktop -> connect/navigate Windows 2 -> reveal a local terminal -> restart. Multi-client browser host overrides, multi-server profile caches, generic settings IPC rejection, local and remote workspace ownership, and restart reset of transient routing are covered. Live desktop UI runs remain uncollected.", + "coverageNotes": "Platform-neutral deterministic tests separate the durable Active Server preference from per-client connection, selected-workspace, browser-session, Add Project, and execution-host routing. The composed regression models Local desktop -> connect/navigate Windows 2 -> reveal a local terminal -> restart. Multi-client browser host overrides, multi-server profile caches, generic settings IPC rejection, local and remote workspace ownership, Add Project owner capture and stale-result fencing, host-qualified group/folder/worktree identity, and restart reset of transient routing are covered. A visible macOS Orca desktop server plus a separate paired Electron client proves real Git, plain-folder, Clone, Create, nested import, runtime-switch, disconnect, reconnect, concurrently visible same-ID local/runtime repo/worktree/group/folder rows, reversed catalog order, reversed refresh completion, local-after-runtime catalog refresh routing, and first paired-terminal activation without local fallback; hidden-window parity also passed. Live Linux, Windows, WSL, and SSH Add Project journeys remain uncollected.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/9687"], - "invariant": "Only an explicit user change in Settings > Remote Orca Servers > Advanced > Active Server may mutate activeRuntimeEnvironmentId. Connecting, pairing, disconnecting, selecting or revealing a workspace or terminal, browser/mobile handoff, remote navigation, and reconnect must use transient or target-owner routing and must never rewrite the durable preference. Generic settings mutation cannot bypass the dedicated preference IPC.", - "oracle": "Start with Active Server=Local desktop, connect and navigate Windows 2, then reveal a local terminal and assert it succeeds while the persisted preference remains local before and after restart. Repeat with multiple clients and servers, browser host switches, remote-owned and local-owned workspaces, pairing/connect/disconnect, and generic settings writes. Assert only the dedicated validated preference method changes activeRuntimeEnvironmentId and stale host-operation completions cannot overwrite the newly selected transient host.", + "invariant": "Only an explicit user change in Settings > Remote Orca Servers > Advanced > Active Server may mutate activeRuntimeEnvironmentId. Connecting, pairing, disconnecting, selecting or revealing a workspace or terminal, browser/mobile handoff, remote navigation, and reconnect must use transient or target-owner routing and must never rewrite the durable preference. Every Add Project scan, add, import, catalog refresh, and worktree refresh must stay on the host selected when that operation began, even if the durable preference changes or the repo catalog is not hydrated. Generic settings mutation cannot bypass the dedicated preference IPC.", + "oracle": "Start with Active Server=Local desktop, connect and navigate Windows 2, then reveal a local terminal and assert it succeeds while the persisted preference remains local before and after restart. Repeat with multiple clients and servers, browser host switches, remote-owned and local-owned workspaces, pairing/connect/disconnect, and generic settings writes. In a separate paired Electron client, select a non-default headed runtime and add a real Git repo, plain folder, clone, created project, and nested repos while switching the preference and disconnecting/reconnecting. Before Git Add, plain-folder Add, Clone, and Create completion, insert a same-ID local repo/worktree decoy; require final activation to remain on the captured runtime. Merge same-ID local/runtime repo, worktree, group, and folder rows, reverse same-host refresh completions, overlap refresh with reconnect, issue ordinary unqualified local refreshes, then create the first paired runtime terminal while the same-ID local/runtime worktrees remain visible. Require only the selected server inventory to change, exact runtime ownership in the client store, preserved host-qualified catalogs, authoritative direct-SSH pruning without runtime sibling loss, visible projects, and zero direct SSH fallback. Assert only the dedicated validated preference method changes activeRuntimeEnvironmentId and stale host-operation completions cannot overwrite the newly selected transient host.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/settings.test.ts src/main/ipc/runtime-environments.test.ts src/renderer/src/store/slices/settings.test.ts src/renderer/src/store/slices/browser.test.ts src/renderer/src/components/settings/browser-session-host-selection.test.ts src/renderer/src/components/settings/RuntimeEnvironmentsPane.test.ts src/renderer/src/components/status-bar/SshStatusSegment.test.ts src/renderer/src/components/sidebar/use-add-repo-host-selection.test.ts src/renderer/src/hooks/useIpcEvents.test.ts src/renderer/src/web/web-preload-api.test.ts --maxWorkers=1" + "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/settings.test.ts src/main/ipc/runtime-environments.test.ts src/renderer/src/store/slices/settings.test.ts src/renderer/src/store/slices/browser.test.ts src/renderer/src/components/settings/browser-session-host-selection.test.ts src/renderer/src/components/settings/RuntimeEnvironmentsPane.test.ts src/renderer/src/components/status-bar/SshStatusSegment.test.ts src/renderer/src/components/sidebar/use-add-repo-host-selection.test.ts src/renderer/src/hooks/useIpcEvents.test.ts src/renderer/src/web/web-preload-api.test.ts --maxWorkers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts src/renderer/src/components/sidebar/project-added-default-checkout.test.ts src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts src/renderer/src/components/sidebar/worktree-list-host-filtering.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/worktree-runtime-owner.test.ts src/renderer/src/store/selectors.test.ts src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts src/renderer/src/store/slices/repos-project-groups.test.ts src/renderer/src/store/slices/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees.test.ts --maxWorkers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts src/renderer/src/components/sidebar/project-added-default-checkout.test.ts src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts src/renderer/src/components/sidebar/worktree-list-host-filtering.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/worktree-runtime-owner.test.ts src/renderer/src/store/selectors.test.ts src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts src/renderer/src/store/slices/repos-project-groups.test.ts src/renderer/src/store/slices/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees.test.ts src/renderer/src/runtime/web-runtime-session.test.ts --maxWorkers=1", + "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", + "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" ], "testFiles": [ "src/main/ipc/settings.test.ts", @@ -2249,7 +2254,28 @@ "src/renderer/src/components/status-bar/SshStatusSegment.test.ts", "src/renderer/src/components/sidebar/use-add-repo-host-selection.test.ts", "src/renderer/src/hooks/useIpcEvents.test.ts", - "src/renderer/src/web/web-preload-api.test.ts" + "src/renderer/src/web/web-preload-api.test.ts", + "src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx", + "src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx", + "src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts", + "src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts", + "src/renderer/src/components/sidebar/project-added-default-checkout.test.ts", + "src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts", + "src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts", + "src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts", + "src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts", + "src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts", + "src/renderer/src/components/sidebar/worktree-list-host-filtering.test.ts", + "src/renderer/src/lib/resolved-worktree-execution-host.test.ts", + "src/renderer/src/lib/worktree-runtime-owner.test.ts", + "src/renderer/src/store/selectors.test.ts", + "src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts", + "src/renderer/src/store/slices/repos-project-groups.test.ts", + "src/renderer/src/store/slices/repos-selected-owner-routing.test.ts", + "src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts", + "src/renderer/src/store/slices/worktrees.test.ts", + "src/renderer/src/runtime/web-runtime-session.test.ts", + "tests/e2e/pr11346-selected-runtime-add.spec.ts" ], "assertionRefs": [ { @@ -2292,6 +2318,73 @@ "generic web settings writes cannot mutate Active Server", "the dedicated web preference setter rejects unknown server identities without corrupting the saved choice" ] + }, + { + "file": "src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts", + "assertions": [ + "stamps a Clone response with the captured runtime or SSH owner before store upsert and worktree refresh", + "preserves same-ID repository siblings that belong to different execution hosts" + ] + }, + { + "file": "src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts", + "assertions": [ + "stamps Create responses with the captured runtime or SSH owner before store upsert and Git or folder worktree refresh" + ] + }, + { + "file": "src/renderer/src/store/slices/repos-selected-owner-routing.test.ts", + "assertions": [ + "keeps same-ID local, direct-SSH, and runtime group/folder rows partitioned by execution host", + "drops reversed same-host and pre-reconnect group/folder responses without pruning newer catalogs", + "prunes deleted direct-SSH rows from the desktop-owned catalog without erasing same-ID runtime siblings", + "keeps explicit runtime groups and folders after a later ordinary local refresh", + "keeps a selected-runtime import refresh across an overlapping local refresh", + "pins selected SSH scans and cancellation to local IPC over an ambient runtime" + ] + }, + { + "file": "src/renderer/src/components/sidebar/project-added-default-checkout.test.ts", + "assertions": [ + "filters loaded, detected, refreshed, and activated default checkouts by the captured execution host when repo IDs collide" + ] + }, + { + "file": "src/renderer/src/store/slices/worktrees.test.ts", + "assertions": [ + "honors an explicit runtime owner before the repo catalog is hydrated", + "honors an explicit SSH owner before the repo catalog is hydrated", + "rejects a missing-owner SSH result after the repo catalog changes", + "rejects a missing-owner SSH result after the provider reconnects" + ] + }, + { + "file": "src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts", + "assertions": [ + "selects the runtime worktree when exact repo/worktree IDs collide in local-first or reversed order", + "keeps exact-ID folder/group activation on the explicitly selected runtime without local fallback" + ] + }, + { + "file": "src/renderer/src/store/selectors.test.ts", + "assertions": [ + "does not fall back to a same-ID local repo when the selected runtime row is unavailable" + ] + }, + { + "file": "src/renderer/src/runtime/web-runtime-session.test.ts", + "assertions": [ + "terminal, browser, and staged-browser selection preserve the explicit runtime execution host when local and runtime worktree IDs collide" + ] + }, + { + "file": "tests/e2e/pr11346-selected-runtime-add.spec.ts", + "assertions": [ + "routes Git Add, plain-folder Add, Clone, Create, and nested import to a selected non-default headed runtime while exact-ID local siblings remain visible and cannot capture final activation @headful", + "preserves same-ID runtime group/folder/worktree catalogs across reversed order, local refresh, switch, disconnect, and reconnect-overlap completion", + "keeps every expanded selected-runtime Add Project path in hidden-window desktop parity", + "creates the first paired runtime terminal while same-ID local/runtime worktrees remain visible without clearing the selected runtime owner" + ] } ], "evidenceRuns": [ @@ -2303,34 +2396,91 @@ "result": "passed", "durationSeconds": 6.55, "summary": "Ten files and 282 tests passed, including the composed Local -> Windows 2 navigation -> local reveal -> restart regression, dedicated-only preference persistence, removed transient-host fallback, multi-client browser routing, late host-operation suppression, and web pairing/preference separation." + }, + { + "date": "2026-07-30", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts src/renderer/src/components/sidebar/project-added-default-checkout.test.ts src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts src/renderer/src/components/sidebar/worktree-list-host-filtering.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/worktree-runtime-owner.test.ts src/renderer/src/store/selectors.test.ts src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts src/renderer/src/store/slices/repos-project-groups.test.ts src/renderer/src/store/slices/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees.test.ts --maxWorkers=1", + "result": "passed", + "durationSeconds": 8.77, + "summary": "Nineteen files and 386 tests passed after rebasing onto 94cf2f1422f30fc309cb47c5e864a831d516fa8b, including exact-ID repo/worktree/group/folder host identity in both catalog orders, fail-closed active-repo selection when a runtime row is unavailable, selected runtime and SSH owner capture through final Add/Clone/Create/folder activation, direct-SSH authoritative pruning, reversed catalog responses, reconnect generation fencing, local-after-runtime isolation, and missing-catalog worktree routing." + }, + { + "date": "2026-07-30", + "runner": "local", + "platform": "macos", + "command": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", + "result": "passed", + "durationSeconds": 23, + "summary": "A visible isolated Orca desktop server and separate paired Electron client added one real Git repo, one plain folder, one clone, one created project, and two nested repos to the selected non-default runtime across preference switches and disconnect/reconnect. Exact-ID local/runtime repo, worktree, group, and folder rows remained concurrently visible in local-first and reversed order without capturing final activation. Server inventory, active host identity, rendered rows, local-client exclusion, preserved post-reconnect catalogs, and zero direct SSH fallback agreed. Runtime switch/Git/folder/Clone/Create/reconnect/nested-import measurements were 307/1667/2932/1247/1321/259/1319 ms." + }, + { + "date": "2026-07-30", + "runner": "local", + "platform": "macos", + "command": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", + "result": "passed", + "durationSeconds": 66, + "summary": "The hidden-window desktop-server parity journey passed with exact-ID Add/Clone/Create activation, selected-runtime inventory, reversed catalog order, reconnect overlap, ownership, local exclusion, and host-qualified catalog-preservation assertions. Runtime switch/Git/folder/Clone/Create/reconnect/nested-import measurements were 59/1770/4330/1375/2137/279/1945 ms." + }, + { + "date": "2026-07-31", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts src/renderer/src/components/sidebar/project-added-default-checkout.test.ts src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts src/renderer/src/components/sidebar/worktree-list-host-filtering.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/worktree-runtime-owner.test.ts src/renderer/src/store/selectors.test.ts src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts src/renderer/src/store/slices/repos-project-groups.test.ts src/renderer/src/store/slices/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees.test.ts src/renderer/src/runtime/web-runtime-session.test.ts --maxWorkers=1", + "result": "passed", + "durationSeconds": 7.1, + "summary": "Twenty files and 430 tests passed on current main integration, including explicit runtime-owner preservation for terminal and browser session activation." + }, + { + "date": "2026-07-31", + "runner": "local", + "platform": "macos", + "command": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", + "result": "passed", + "durationSeconds": 19.9, + "summary": "The visible headed server and separate paired client passed the strengthened same-ID terminal-activation oracle with a disposable runtime Git identity. Runtime switch/Git/folder/Clone/Create/reconnect/nested-import measurements were 43/1513/3841/1200/790/202/1312 ms." + }, + { + "date": "2026-07-31", + "runner": "local", + "platform": "macos", + "command": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", + "result": "passed", + "durationSeconds": 19.7, + "summary": "The hidden-window server and separate paired client passed the strengthened same-ID terminal-activation oracle with a disposable runtime Git identity. Runtime switch/Git/folder/Clone/Create/reconnect/nested-import measurements were 51/1502/3843/880/939/200/1359 ms." } ], "runtimeBudget": { - "p95Seconds": 20, - "scope": "focused persistence and routing contract tests" + "p95Seconds": 180, + "scope": "focused persistence/routing contracts plus isolated paired Electron journeys" }, "flakeHistory": { "status": "unknown", - "evidence": "New deterministic gate with no soak history." + "evidence": "Deterministic contracts and the final visible plus hidden-window paired Electron runs passed locally. During expansion, attempts exposed three harness-only assumptions: exact project labels did not allow path disambiguation, clicking the inner host label raced cmdk layout, and a disposable CI runtime had no Git author identity for Create. The oracle now targets the host command item, accepts the rendered disambiguated label, seeds only its isolated runtime home with a test Git identity, and explicitly creates a first paired terminal while same-ID local/runtime worktrees remain present. CI soak history is not yet available." }, "redGreenEvidence": { - "status": "partial", - "evidence": "The user-observed local terminal reveal failure and unintended Active Server switch are encoded by deterministic routing and persistence tests; a saved intentional-break artifact is not yet attached." + "status": "complete", + "evidence": "The byte-identical focused oracle (SHA-256 6de18c140a86801460e58f52287e27a58b97f1576f9f387fa82e1bd4eb378f7b) fails 2/3 on review baseline aa6f945001a5f78a07663c854fabb95c55d8b40b and on the r5-disabled parent e21f4ca58e: local-first lookup returns /local/repo and folder activation has no runtime host. It passes 3/3 on the candidate. Main later advanced to 94cf2f1422f30fc309cb47c5e864a831d516fa8b without changing any of the candidate's 68 files or the focused oracle production boundary; the rebased disabled parent f247d961cab15237bc7fcf0598fe76007f78ec7c has the same stable patch ID as e21f4ca58e. The final paired spec and fixture have SHA-256 bd6d9014d1bed2715397bcd2121d5d7e01792347b13ff14778ccf608bf98789c and d1d78a82f868e2f3152777550825c0ca2d4dc3cba5c6de548e066d2931751fc7. With the final runtime-session owner fix disabled, the focused session test fails 3/43 and the byte-identical hidden paired oracle deterministically creates the host terminal but reports null active client owner while same-ID local/runtime worktrees remain. The integrated candidate passes the same focused test and both headed/hidden paired oracles with exact runtime ownership, server inventory, local exclusion, preserved catalogs, visible rows, and zero direct SSH fallback. Earlier Active Server preference paths retain deterministic coverage but do not yet have a saved intentional-break artifact." }, "performanceBudget": { - "required": false, - "evidence": "Preference writes are explicit user actions; transient routing adds no polling and uses existing host/worktree indexes." + "required": true, + "evidence": "Preference writes are explicit user actions; transient routing adds no polling or provider fanout and retains one authoritative worktree refresh per completed add. Host-qualified owner indexes are WeakMap-cached and do not add subprocesses or network calls. The final headed journey measured 43 ms for three preference switches, 1,513 ms for Git add, 3,841 ms for folder add, 1,200 ms for Clone, 790 ms for Create with controlled exact-ID completion gates, 202 ms for disconnect/reconnect with overlapping catalog refreshes, and 1,312 ms for nested import. The final session-activation fix adds one execution-host string conversion per explicit terminal/browser activation and no provider call, scan, timer, or retry. Existing Zustand selector fan-out evidence remained 0 render invalidations across 5,000,000 selector runs." }, "promotionCriteria": [ "Run the focused gate in soak across macOS, Linux, and Windows.", "Attach a live Windows Local -> Windows 2 -> local reveal -> restart artifact.", - "Attach saved red/green evidence for generic settings mutation and transient connection routing." + "Attach saved red/green evidence for generic settings mutation and transient connection routing.", + "Run the paired Add Project journey on Linux and native Windows, plus live SSH and WSL hosts." ], "knownGaps": [ "The exact journey is deterministic contract coverage, not a packaged Windows UI automation run.", - "Browser/mobile handoff is covered through transient routing state and preload contracts, not a live phone browser session." + "Browser/mobile handoff is covered through transient routing state and preload contracts, not a live phone browser session.", + "The paired Add Project journey is macOS-only; native Windows was unavailable.", + "SSH and WSL Add Project ownership is deterministic store/controller coverage, not a live host journey." ], - "demotionRule": "Demote or block release if any non-Advanced path mutates Active Server, if local reveal depends on the durable default instead of workspace ownership, or if transient host state survives restart." + "demotionRule": "Demote or block release if any non-Advanced path mutates Active Server, if local reveal or Add Project depends on the durable default instead of captured workspace/host ownership, if an Add Project operation reaches a different host after it begins, or if transient host state survives restart." }, { "id": "terminal-geometry.visible-convergence", diff --git a/src/renderer/src/components/WorktreeJumpPalette.tsx b/src/renderer/src/components/WorktreeJumpPalette.tsx index efe91e4e7..9eee43a6a 100644 --- a/src/renderer/src/components/WorktreeJumpPalette.tsx +++ b/src/renderer/src/components/WorktreeJumpPalette.tsx @@ -1267,22 +1267,25 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null { ) const handleSelectWorktree = useCallback( - (worktreeId: string) => { - const worktree = findWorktreeById(useAppStore.getState().worktreesByRepo, worktreeId) - if (!worktree) { + (worktree: Worktree) => { + const current = useAppStore.getState().getKnownWorktreeById(worktree.id, worktree.hostId) + if (!current) { toast.error( translate('auto.components.WorktreeJumpPalette.2c38630a01', 'Workspace no longer exists') ) return } - const activation = activateAndRevealWorktree(worktreeId) + const activation = activateAndRevealWorktree( + worktree.id, + worktree.hostId ? { executionHostId: worktree.hostId } : {} + ) recordFeatureInteraction('cmd-j-workspace-open') skipRestoreFocusRef.current = true closeModal() setSelectedItemId('') // Why: #9939 — the unscoped fallback grabs the first terminal in the document, which is // often the worktree we just left, now hidden. Focus the destination's own tab instead. - if (!queueWorkspaceActivationTerminalFocus(worktreeId, activation)) { + if (!queueWorkspaceActivationTerminalFocus(worktree.id, activation)) { focusFallbackSurface() } }, @@ -1304,7 +1307,10 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null { } // Why: capture page info before activateAndRevealWorktree mutates store state — a later findBrowserSelection would be unreliable. const { worktree, workspace, page } = selection - const activated = activateAndRevealWorktree(worktree.id) + const activated = activateAndRevealWorktree( + worktree.id, + worktree.hostId ? { executionHostId: worktree.hostId } : {} + ) if (!activated) { toast.error( translate('auto.components.WorktreeJumpPalette.2c38630a01', 'Workspace no longer exists') @@ -1470,7 +1476,7 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null { const handleSelectItem = useCallback( (item: PaletteItem) => { if (item.type === 'worktree') { - handleSelectWorktree(item.worktree.id) + handleSelectWorktree(item.worktree) } else if (item.type === 'project-target') { handleSelectProjectTarget(item.result) } else if (item.type === 'browser-page') { diff --git a/src/renderer/src/components/cmd-j/palette-activation-focus-routing.test.ts b/src/renderer/src/components/cmd-j/palette-activation-focus-routing.test.ts index c63948e7c..afe3b97da 100644 --- a/src/renderer/src/components/cmd-j/palette-activation-focus-routing.test.ts +++ b/src/renderer/src/components/cmd-j/palette-activation-focus-routing.test.ts @@ -24,10 +24,10 @@ describe('Cmd+J activation focus routing (#9939)', () => { 'const handleSelectBrowserPage' ) - expect(handler).toContain('queueWorkspaceActivationTerminalFocus(worktreeId, activation)') + expect(handler).toContain('queueWorkspaceActivationTerminalFocus(worktree.id, activation)') // The fallback must be reachable only when the helper declines the destination. expect(handler).toMatch( - /if \(!queueWorkspaceActivationTerminalFocus\(worktreeId, activation\)\) \{\s*focusFallbackSurface\(\)\s*\}/ + /if \(!queueWorkspaceActivationTerminalFocus\(worktree\.id, activation\)\) \{\s*focusFallbackSurface\(\)\s*\}/ ) // An unconditional fallback is the exact shape of the original bug, so the only bare call // allowed is the guarded one inside the if-block above. diff --git a/src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx b/src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx index 56d32c5ae..ddff8f752 100644 --- a/src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx +++ b/src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx @@ -152,12 +152,14 @@ describe('AddProjectFromFolderDialog', () => { expect(mocks.state.addRepoPath).toHaveBeenCalledWith('/projects/child') expect(mocks.state.fetchWorktrees).toHaveBeenCalledWith(repo.id, { - requireAuthoritative: true + requireAuthoritative: true, + executionHostId: 'local' }) expect(mocks.finishProjectAddWithDefaultCheckout).toHaveBeenCalledWith({ repoId: repo.id, source: 'local_folder_picker', selectedPath: '/projects/child', + executionHostId: 'local', closeModal: mocks.state.closeModal, setHideDefaultBranchWorkspace: mocks.state.setHideDefaultBranchWorkspace }) @@ -200,14 +202,16 @@ describe('AddProjectFromFolderDialog', () => { connectionId: 'ssh-target-1', remotePath: '/srv/projects/child' }) - expect(mocks.state.repos).toEqual([repo]) + expect(mocks.state.repos).toEqual([{ ...repo, executionHostId: 'ssh:ssh-target-1' }]) expect(mocks.state.fetchWorktrees).toHaveBeenCalledWith(repo.id, { - requireAuthoritative: true + requireAuthoritative: true, + executionHostId: 'ssh:ssh-target-1' }) expect(mocks.finishProjectAddWithDefaultCheckout).toHaveBeenCalledWith({ repoId: repo.id, source: 'ssh_remote_path', selectedPath: '/srv/projects/child', + executionHostId: 'ssh:ssh-target-1', closeModal: mocks.state.closeModal, setHideDefaultBranchWorkspace: mocks.state.setHideDefaultBranchWorkspace }) @@ -226,12 +230,14 @@ describe('AddProjectFromFolderDialog', () => { await clickAddProject() expect(mocks.state.fetchWorktrees).toHaveBeenCalledWith(repo.id, { - requireAuthoritative: true + requireAuthoritative: true, + executionHostId: 'local' }) expect(mocks.finishProjectAddWithDefaultCheckout).toHaveBeenCalledWith({ repoId: repo.id, source: 'local_folder_picker', selectedPath: '/projects/child', + executionHostId: 'local', closeModal: mocks.state.closeModal, setHideDefaultBranchWorkspace: mocks.state.setHideDefaultBranchWorkspace }) @@ -252,7 +258,8 @@ describe('AddProjectFromFolderDialog', () => { const addPromise = getButton('Add Project').onClick?.() await Promise.resolve() expect(mocks.state.fetchWorktrees).toHaveBeenCalledWith(repo.id, { - requireAuthoritative: true + requireAuthoritative: true, + executionHostId: 'local' }) getButton('Cancel').onClick?.() resolveRefresh(true) diff --git a/src/renderer/src/components/sidebar/AddProjectFromFolderDialog.tsx b/src/renderer/src/components/sidebar/AddProjectFromFolderDialog.tsx index 483476e9c..78a0f2b02 100644 --- a/src/renderer/src/components/sidebar/AddProjectFromFolderDialog.tsx +++ b/src/renderer/src/components/sidebar/AddProjectFromFolderDialog.tsx @@ -16,6 +16,8 @@ import type { Repo } from '../../../../shared/types' import { isGitRepoKind } from '../../../../shared/repo-kind' import { finishProjectAddWithDefaultCheckout } from './project-added-default-checkout' import { translate } from '@/i18n/i18n' +import { upsertAddedRepoWithProjectHostSetup } from './add-repo-store-upsert' +import { worktreeRefreshOptions } from './add-repo-runtime-owner' const NON_GIT_REPO_ERROR = 'Not a valid git repository' @@ -74,16 +76,12 @@ const AddProjectFromFolderDialog = React.memo(function AddProjectFromFolderDialo if ('error' in result) { throw new Error(result.error) } - repo = result.repo - const state = useAppStore.getState() - const existingIdx = state.repos.findIndex((r) => r.id === repo?.id) - if (existingIdx !== -1) { - state.clearOrcaHookTrustForRepo(repo.id) - const updated = [...state.repos] - updated[existingIdx] = repo - useAppStore.setState({ repos: updated }) - } else { - useAppStore.setState({ repos: [...state.repos, repo] }) + const upserted = upsertAddedRepoWithProjectHostSetup(result.repo, { + sshConnectionId: connectionId + }) + repo = upserted.repo + if (upserted.alreadyPresent) { + useAppStore.getState().clearOrcaHookTrustForRepo(repo.id) } if (!mountedRef.current || gen !== addGenRef.current) { return @@ -111,7 +109,8 @@ const AddProjectFromFolderDialog = React.memo(function AddProjectFromFolderDialo } // Why: after the repo is already added, a non-authoritative refresh // should still close onto the project row instead of trapping the user. - await fetchWorktrees(repo.id, { requireAuthoritative: true }) + const ownerOptions = worktreeRefreshOptions(null, connectionId) + await fetchWorktrees(repo.id, ownerOptions) if (!mountedRef.current || gen !== addGenRef.current) { return } @@ -119,6 +118,7 @@ const AddProjectFromFolderDialog = React.memo(function AddProjectFromFolderDialo repoId: repo.id, source: connectionId ? 'ssh_remote_path' : 'local_folder_picker', selectedPath: folderPath, + executionHostId: ownerOptions.executionHostId, closeModal, setHideDefaultBranchWorkspace }) diff --git a/src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts b/src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts index 5ae2c3666..edcfa01f1 100644 --- a/src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts +++ b/src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts @@ -1,44 +1,27 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' import { describe, expect, it } from 'vitest' +import { + LOCAL_EXECUTION_HOST_ID, + toRuntimeExecutionHostId +} from '../../../../shared/execution-host' +import { worktreeRefreshOptions } from './add-repo-runtime-owner' -const ADD_REPO_DIALOG_PATH = join(import.meta.dirname, 'AddRepoDialog.tsx') -const ADD_REPO_FLOW_PATHS = [ - ADD_REPO_DIALOG_PATH, - join(import.meta.dirname, 'AddRepoSteps.tsx'), - join(import.meta.dirname, 'useAddRepoCloneFlow.ts'), - join(import.meta.dirname, 'useAddRepoLocalFolderFlow.ts'), - join(import.meta.dirname, 'useAddRepoServerPathFlow.ts'), - join(import.meta.dirname, 'useAddRepoNestedImportFlow.ts') -] - -function readAddRepoFlowSource(): string { - return ADD_REPO_FLOW_PATHS.map((path) => readFileSync(path, 'utf8')).join('\n') -} - -describe('AddRepoDialog default-checkout handoff', () => { - it('does not retain the removed setup-step routing branch', () => { - const source = readFileSync(ADD_REPO_DIALOG_PATH, 'utf8') - - expect(source).not.toContain("setStep('setup')") - expect(source).not.toContain(' { + it('routes an explicitly local completion to the local host', () => { + expect(worktreeRefreshOptions(null)).toEqual({ + requireAuthoritative: true, + executionHostId: LOCAL_EXECUTION_HOST_ID + }) }) - it('requests authoritative worktree refresh before Git handoff paths complete', () => { - const source = readAddRepoFlowSource() - - expect(source.match(/requireAuthoritative: true/g)?.length ?? 0).toBeGreaterThanOrEqual(4) - expect(source).toContain("onGitRepoReady(repo.id, 'clone_url')") - expect(source).toContain("onGitRepoReady(repo.id, 'runtime_server_path')") - expect(source).toContain('onGitRepoReady(repo.id, source)') + it('routes an explicitly runtime completion to its captured runtime', () => { + expect(worktreeRefreshOptions('runtime-1')).toEqual({ + requireAuthoritative: true, + executionHostId: toRuntimeExecutionHostId('runtime-1') + }) }) - it('does not fail nested import completion on non-authoritative refresh', () => { - const source = readAddRepoFlowSource() - - expect(source).not.toContain('Could not refresh project worktrees. Try again.') - expect(source).toContain('await fetchWorktrees(projectId, { requireAuthoritative: true })') - expect(source).toContain('await onGitRepoReady(repo.id, source)') + it('leaves an absent owner distinguishable from explicit local ownership', () => { + expect(worktreeRefreshOptions(undefined)).toEqual({ requireAuthoritative: true }) + expect(worktreeRefreshOptions(undefined)).not.toEqual(worktreeRefreshOptions(null)) }) }) diff --git a/src/renderer/src/components/sidebar/AddRepoDialog.tsx b/src/renderer/src/components/sidebar/AddRepoDialog.tsx index be41bb175..54148a0d4 100644 --- a/src/renderer/src/components/sidebar/AddRepoDialog.tsx +++ b/src/renderer/src/components/sidebar/AddRepoDialog.tsx @@ -4,24 +4,22 @@ import { useRemoteRepo } from './AddRepoSteps' import { useCreateRepo } from './useCreateRepo' import { AddRepoDialogStepContent } from './AddRepoDialogStepContent' import type { AddRepoDialogStep } from './add-repo-dialog-types' -import { useAddRepoNestedReviewState } from './useAddRepoNestedReviewState' import { useAddRepoCloneFlow } from './useAddRepoCloneFlow' import { useAddRepoLocalFolderFlow } from './useAddRepoLocalFolderFlow' import { useAddRepoServerPathFlow } from './useAddRepoServerPathFlow' -import { useAddRepoNestedImportFlow } from './useAddRepoNestedImportFlow' import { useAddRepoHostSelection } from './use-add-repo-host-selection' import { useCompleteGitRepoAdd } from './use-complete-git-repo-add' import { useCreateProjectDefaults } from './useCreateProjectDefaults' import { useAddRepoHostChangeReset } from './use-add-repo-host-change-reset' import { AddRepoDialogChrome } from './AddRepoDialogChrome' import { AddRepoHostSelectorSlot } from './AddRepoHostSelectorSlot' -import { useAddRepoRemoteNestedScan } from './use-add-repo-remote-nested-scan' +import { useAddRepoNestedReviewController } from './useAddRepoNestedReviewController' import { useAddRepoHostedController, type AddRepoDialogHostedController } from './use-add-repo-hosted-controller' -const AddRepoDialog = React.memo(function AddRepoDialog({ +export default React.memo(function AddRepoDialog({ hosted }: { hosted?: AddRepoDialogHostedController @@ -42,25 +40,25 @@ const AddRepoDialog = React.memo(function AddRepoDialog({ const settings = useAppStore((s) => s.settings) const { closeModal, closeForFolderHandoff, finishProjectAdd, handleOpenSshSettings } = useAddRepoHostedController(hosted) + const [step, setStep] = useState('add') + const [isAdding, setIsAdding] = useState(false) + const [addProjectBusyLabel, setAddProjectBusyLabel] = useState(null) const completeGitRepoAdd = useCompleteGitRepoAdd({ closeModal, setHideDefaultBranchWorkspace, finishProjectAdd }) - - const [step, setStep] = useState('add') - const [isAdding, setIsAdding] = useState(false) - const [addProjectBusyLabel, setAddProjectBusyLabel] = useState(null) + const hostSelection = useAddRepoHostSelection({ isOpen, setStep }) + const selectedRuntimeEnvironmentId = + hostSelection.selectedParsedHost?.kind === 'runtime' + ? hostSelection.selectedParsedHost.environmentId + : null const { nestedScan, nestedSelectedPaths, nestedGroupName, - nestedConnectionId, - nestedAttemptId, - nestedRuntimeKind, nestedScanInProgress, nestedScanId, - nestedImportScanId, setNestedSelectedPaths, setNestedGroupName, setNestedScanInProgress, @@ -68,22 +66,24 @@ const AddRepoDialog = React.memo(function AddRepoDialog({ showNestedRepoReview, setActiveNestedScanId, handleStopNestedScan, - resetNestedRepoReviewState - } = useAddRepoNestedReviewState({ - activeRuntimeEnvironmentId: settings?.activeRuntimeEnvironmentId, + resetNestedRepoReviewState, + showRemoteNestedRepoReview, + trackRemoteNestedScanResult, + handleImportNestedRepos, + handleOpenNestedRootFolder, + resetNestedImportFlow, + trackNestedBackAction + } = useAddRepoNestedReviewController({ + reviewRuntimeEnvironmentId: selectedRuntimeEnvironmentId, cancelNestedRepoScan, + closeModal: closeForFolderHandoff, + fetchWorktrees, + importNestedRepos, + onGitRepoReady: completeGitRepoAdd, + setIsAdding, + activeRuntimeEnvironmentId: selectedRuntimeEnvironmentId, setStep }) - - const hostSelection = useAddRepoHostSelection({ isOpen, setStep }) - const selectedRuntimeEnvironmentId = - hostSelection.selectedParsedHost?.kind === 'runtime' - ? hostSelection.selectedParsedHost.environmentId - : null - const { showRemoteNestedRepoReview, trackRemoteNestedScanResult } = useAddRepoRemoteNestedScan({ - setActiveNestedScanId, - showNestedRepoReview - }) const { sshTargets, selectedTargetId, @@ -104,12 +104,11 @@ const AddRepoDialog = React.memo(function AddRepoDialog({ setStep, // Why: useRemoteRepo closes only for the non-git → confirm-dialog handoff. closeForFolderHandoff, - (repoId) => completeGitRepoAdd(repoId, 'ssh_remote_path'), + (repoId, executionHostId) => completeGitRepoAdd(repoId, 'ssh_remote_path', executionHostId), scanNestedRepos, showRemoteNestedRepoReview, trackRemoteNestedScanResult ) - const { createName, createParent, @@ -123,9 +122,8 @@ const AddRepoDialog = React.memo(function AddRepoDialog({ handleCreate } = useCreateRepo( fetchWorktrees, - // Why: useCreateRepo closes only after a folder (non-git) create. closeForFolderHandoff, - (repoId) => completeGitRepoAdd(repoId, 'create_project'), + (repoId, executionHostId) => completeGitRepoAdd(repoId, 'create_project', executionHostId), { hostId: hostSelection.selectedHostId, runtimeEnvironmentId: selectedRuntimeEnvironmentId, @@ -195,6 +193,7 @@ const AddRepoDialog = React.memo(function AddRepoDialog({ handleAddServerPath } = useAddRepoServerPathFlow({ addRepoPath, + activeRuntimeEnvironmentId: selectedRuntimeEnvironmentId, // Why: closes only after a folder add, which activates the folder workspace. closeModal: closeForFolderHandoff, fetchWorktrees, @@ -206,29 +205,6 @@ const AddRepoDialog = React.memo(function AddRepoDialog({ onGitRepoReady: completeGitRepoAdd, setAddProjectBusyLabel }) - const { - handleImportNestedRepos, - handleOpenNestedRootFolder, - resetNestedImportFlow, - trackNestedBackAction - } = useAddRepoNestedImportFlow({ - nestedAttemptId, - nestedScan, - nestedSelectedPaths, - nestedRuntimeKind, - nestedConnectionId, - nestedGroupName, - nestedImportScanId, - activeRuntimeEnvironmentId: selectedRuntimeEnvironmentId, - // Why: open-as-folder outcomes navigate; git imports finish via - // completeGitRepoAdd instead. - closeModal: closeForFolderHandoff, - fetchWorktrees, - importNestedRepos, - getNestedRepoRuntimeKind, - onGitRepoReady: completeGitRepoAdd, - setIsAdding - }) const resetState = useCallback(() => { // Why: kill the git clone process if one is running, so backing out @@ -259,6 +235,7 @@ const AddRepoDialog = React.memo(function AddRepoDialog({ const resetHostScopedState = useCallback(() => { setIsAdding(false) setAddProjectBusyLabel(null) + resetLocalFolderFlow() resetServerPathFlow() resetCloneFlow() resetCreateDefaultState() @@ -269,6 +246,7 @@ const AddRepoDialog = React.memo(function AddRepoDialog({ resetCreateDefaultState, resetCreateState, resetRemoteState, + resetLocalFolderFlow, resetServerPathFlow ]) @@ -420,5 +398,3 @@ const AddRepoDialog = React.memo(function AddRepoDialog({ ) }) - -export default AddRepoDialog diff --git a/src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts b/src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts index db874556e..fc8829474 100644 --- a/src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts +++ b/src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts @@ -135,7 +135,12 @@ describe('useRemoteRepo default-checkout handoff', () => { remotePath: '/srv/repo' }) expect(mocks.fetchWorktrees).toHaveBeenCalledWith(repo.id, { - requireAuthoritative: true + requireAuthoritative: true, + executionHostId: 'ssh:ssh-1' + }) + expect(mocks.storeState.repos).toContainEqual({ + ...repo, + executionHostId: 'ssh:ssh-1' }) expect(mocks.storeState.projects).toEqual( expect.arrayContaining([expect.objectContaining({ sourceRepoIds: [repo.id] })]) @@ -143,7 +148,7 @@ describe('useRemoteRepo default-checkout handoff', () => { expect(mocks.storeState.projectHostSetups).toEqual( expect.arrayContaining([expect.objectContaining({ repoId: repo.id, path: repo.path })]) ) - expect(mocks.onGitRepoReady).toHaveBeenCalledWith(repo.id) + expect(mocks.onGitRepoReady).toHaveBeenCalledWith(repo.id, 'ssh:ssh-1') }) it('continues to completion when refresh is not authoritative after remote add', async () => { @@ -162,9 +167,10 @@ describe('useRemoteRepo default-checkout handoff', () => { await result.handleAddRemoteRepo() expect(mocks.fetchWorktrees).toHaveBeenCalledWith(repo.id, { - requireAuthoritative: true + requireAuthoritative: true, + executionHostId: 'ssh:ssh-1' }) - expect(mocks.onGitRepoReady).toHaveBeenCalledWith(repo.id) + expect(mocks.onGitRepoReady).toHaveBeenCalledWith(repo.id, 'ssh:ssh-1') expect(mocks.stateSetters[3]).not.toHaveBeenCalledWith( 'Could not refresh project worktrees. Try again.' ) @@ -188,4 +194,36 @@ describe('useRemoteRepo default-checkout handoff', () => { expect(mocks.getState).toHaveBeenCalledWith({ targetId: 'ssh-2' }) expect(mocks.stateSetters[1]).toHaveBeenCalledWith('ssh-2') }) + + it('pins SSH nested scans and cancellation to the local provider', async () => { + const scanNestedRepos = vi.fn().mockResolvedValue(null) + mocks.addRemote.mockResolvedValue({ repo: makeRepo() }) + mocks.fetchWorktrees.mockResolvedValue(true) + const { useRemoteRepo } = await import('./AddRepoSteps') + + const result = useRemoteRepo( + mocks.fetchWorktrees, + vi.fn(), + vi.fn(), + mocks.onGitRepoReady, + scanNestedRepos + ) + await result.handleAddRemoteRepo() + + expect(scanNestedRepos).toHaveBeenCalledWith( + '/srv/repo', + 'ssh-1', + expect.objectContaining({ runtimeEnvironmentId: null }) + ) + + mocks.stateIndex = 0 + mocks.stateValues = [[], 'ssh-1', '/srv/repo', null, false, 'scan-ssh'] + const active = useRemoteRepo(mocks.fetchWorktrees, vi.fn(), vi.fn()) + active.stopRemoteNestedScan() + active.resetRemoteState() + + expect(mocks.storeState.cancelNestedRepoScan).toHaveBeenCalledWith('scan-ssh', { + runtimeEnvironmentId: null + }) + }) }) diff --git a/src/renderer/src/components/sidebar/AddRepoSteps.tsx b/src/renderer/src/components/sidebar/AddRepoSteps.tsx index 5ab96be88..0acdaa888 100644 --- a/src/renderer/src/components/sidebar/AddRepoSteps.tsx +++ b/src/renderer/src/components/sidebar/AddRepoSteps.tsx @@ -8,21 +8,27 @@ import { createNestedRepoTelemetryAttemptId } from '../../../../shared/nested-re import { translate } from '@/i18n/i18n' import { extractIpcErrorMessage } from '@/lib/ipc-error' import { upsertAddedRepoWithProjectHostSetup } from './add-repo-store-upsert' +import { worktreeRefreshOptions } from './add-repo-runtime-owner' +import type { ExecutionHostId } from '../../../../shared/execution-host' // ── SSH host project hook ─────────────────────────────────────────── export function useRemoteRepo( fetchWorktrees: ( repoId: string, - options?: { requireAuthoritative?: boolean } + options?: { requireAuthoritative?: boolean; executionHostId?: ExecutionHostId } ) => Promise, setStep: (step: 'add' | 'clone' | 'remote' | 'create' | 'nested') => void, closeModal: () => void, - onGitRepoReady?: (repoId: string) => void | Promise, + onGitRepoReady?: (repoId: string, executionHostId?: ExecutionHostId) => void | Promise, scanNestedRepos?: ( path: string, connectionId?: string, - controls?: { scanId?: string; onProgress?: (scan: NestedRepoScanResult) => void } + controls?: { + scanId?: string + onProgress?: (scan: NestedRepoScanResult) => void + runtimeEnvironmentId?: string | null + } ) => Promise, showNestedRepoReview?: ( scan: NestedRepoScanResult, @@ -52,7 +58,7 @@ export function useRemoteRepo( setRemoteError(null) setIsAddingRemote(false) if (remoteNestedScanId) { - void cancelNestedRepoScan(remoteNestedScanId) + void cancelNestedRepoScan(remoteNestedScanId, { runtimeEnvironmentId: null }) } setRemoteNestedScanId(null) }, [cancelNestedRepoScan, remoteNestedScanId]) @@ -61,7 +67,7 @@ export function useRemoteRepo( if (!remoteNestedScanId) { return } - void cancelNestedRepoScan(remoteNestedScanId) + void cancelNestedRepoScan(remoteNestedScanId, { runtimeEnvironmentId: null }) }, [cancelNestedRepoScan, remoteNestedScanId]) const handleOpenRemoteStep = useCallback( @@ -146,6 +152,7 @@ export function useRemoteRepo( setRemoteNestedScanId(scanId) const scan = await scanNestedRepos?.(trimmedRemotePath, selectedTargetId, { scanId, + runtimeEnvironmentId: null, onProgress: (progressScan) => { if ( gen !== remoteGenRef.current || @@ -182,14 +189,13 @@ export function useRemoteRepo( if ('error' in result) { throw new Error(result.error) } - const repo = result.repo + const { alreadyPresent, repo } = upsertAddedRepoWithProjectHostSetup(result.repo, { + sshConnectionId: selectedTargetId + }) - const state = useAppStore.getState() - const existingIdx = state.repos.findIndex((r) => r.id === repo.id) - if (existingIdx !== -1) { - state.clearOrcaHookTrustForRepo(repo.id) + if (alreadyPresent) { + useAppStore.getState().clearOrcaHookTrustForRepo(repo.id) } - upsertAddedRepoWithProjectHostSetup(repo) if (!mountedRef.current || gen !== remoteGenRef.current) { return @@ -200,11 +206,12 @@ export function useRemoteRepo( ) // Why: the repo is already persisted here; if SSH refresh is temporarily // non-authoritative, finish onto the project row instead of stranding the dialog. - await fetchWorktrees(repo.id, { requireAuthoritative: true }) + const ownerOptions = worktreeRefreshOptions(undefined, selectedTargetId) + await fetchWorktrees(repo.id, ownerOptions) if (!mountedRef.current || gen !== remoteGenRef.current) { return } - await onGitRepoReady?.(repo.id) + await onGitRepoReady?.(repo.id, ownerOptions.executionHostId) } catch (err) { const message = extractIpcErrorMessage(err, String(err)) if (message.includes('Not a valid git repository')) { diff --git a/src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx b/src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx index a6f7bbff3..a39237476 100644 --- a/src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx +++ b/src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx @@ -1,6 +1,7 @@ import { renderToStaticMarkup } from 'react-dom/server' import type * as ReactModule from 'react' import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { Repo, Worktree } from '../../../../shared/types' type ButtonCapture = { label: string @@ -17,8 +18,17 @@ const mocks = vi.hoisted(() => ({ } as Record, closeModal: vi.fn(), addNonGitFolder: vi.fn(), - runtimeEnvironments: [{ id: 'env-1', name: 'Remote Mac' }] - } + runtimeEnvironments: [{ id: 'env-1', name: 'Remote Mac' }], + repos: [] as Repo[], + projects: [], + projectHostSetups: [], + worktreesByRepo: {} as Record, + fetchWorktrees: vi.fn(), + settings: {} + }, + addRemote: vi.fn(), + onboardingGet: vi.fn(), + activateAndRevealWorktree: vi.fn() })) function textContent(node: ReactModule.ReactNode): string { @@ -74,11 +84,34 @@ vi.mock('sonner', () => ({ })) vi.mock('@/lib/worktree-activation', () => ({ - activateAndRevealWorktree: vi.fn() + activateAndRevealWorktree: mocks.activateAndRevealWorktree })) import NonGitFolderDialog from './NonGitFolderDialog' +function makeWorktree(id: string, path: string, hostId: Worktree['hostId']): Worktree { + return { + id, + repoId: 'shared-repo', + path, + hostId, + displayName: 'Folder', + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + head: '', + branch: '', + isBare: false, + isMainWorktree: true + } +} + describe('NonGitFolderDialog', () => { beforeEach(() => { vi.clearAllMocks() @@ -89,6 +122,18 @@ describe('NonGitFolderDialog', () => { runtimeEnvironmentId: 'env-1' } mocks.state.runtimeEnvironments = [{ id: 'env-1', name: 'Remote Mac' }] + mocks.state.repos = [] + mocks.state.projects = [] + mocks.state.projectHostSetups = [] + mocks.state.worktreesByRepo = {} + mocks.state.fetchWorktrees.mockResolvedValue(true) + mocks.onboardingGet.mockResolvedValue(null) + vi.stubGlobal('window', { + api: { + repos: { addRemote: mocks.addRemote }, + onboarding: { get: mocks.onboardingGet } + } + }) }) it('shows the checked host in the folder confirmation', () => { @@ -109,4 +154,54 @@ describe('NonGitFolderDialog', () => { }) expect(mocks.state.closeModal).toHaveBeenCalled() }) + + it('activates only the selected SSH folder when repo IDs collide', async () => { + const repo: Repo = { + id: 'shared-repo', + path: '/srv/non-git', + displayName: 'SSH folder', + badgeColor: '#111', + addedAt: 1, + kind: 'folder', + connectionId: 'ssh-1' + } + const localWorktree = makeWorktree('shared-repo::/local/non-git', '/local/non-git', 'local') + const sshWorktree = makeWorktree('shared-repo::/srv/non-git', '/srv/non-git', 'ssh:ssh-1') + mocks.state.modalData = { + folderPath: '/srv/non-git', + connectionId: 'ssh-1' + } + mocks.state.repos = [ + { + ...repo, + path: '/local/non-git', + connectionId: null, + executionHostId: 'local' + } + ] + mocks.addRemote.mockResolvedValue({ repo }) + mocks.state.fetchWorktrees.mockImplementation(async () => { + mocks.state.worktreesByRepo = { [repo.id]: [localWorktree, sshWorktree] } + return true + }) + renderToStaticMarkup() + + const button = mocks.buttons.find((entry) => entry.label.includes('Open as Folder')) + button?.onClick?.() + + await vi.waitFor(() => + expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith(sshWorktree.id, { + sidebarRevealBehavior: 'auto', + executionHostId: 'ssh:ssh-1' + }) + ) + expect(mocks.state.fetchWorktrees).toHaveBeenCalledWith(repo.id, { + requireAuthoritative: true, + executionHostId: 'ssh:ssh-1' + }) + expect(mocks.activateAndRevealWorktree).not.toHaveBeenCalledWith( + localWorktree.id, + expect.anything() + ) + }) }) diff --git a/src/renderer/src/components/sidebar/NonGitFolderDialog.tsx b/src/renderer/src/components/sidebar/NonGitFolderDialog.tsx index 5ec3354ec..8cc5ed91d 100644 --- a/src/renderer/src/components/sidebar/NonGitFolderDialog.tsx +++ b/src/renderer/src/components/sidebar/NonGitFolderDialog.tsx @@ -14,6 +14,8 @@ import { activateAndRevealWorktree } from '@/lib/worktree-activation' import { buildDismissedOnboardingFolderAgentStartup } from '@/lib/onboarding-folder-agent-startup' import { markOnboardingProjectAdded } from '@/lib/onboarding-project-checklist' import { translate } from '@/i18n/i18n' +import { upsertAddedRepoWithProjectHostSetup } from './add-repo-store-upsert' +import { worktreeRefreshOptions } from './add-repo-runtime-owner' const NonGitFolderDialog = React.memo(function NonGitFolderDialog() { const activeModal = useAppStore((s) => s.activeModal) @@ -60,19 +62,23 @@ const NonGitFolderDialog = React.memo(function NonGitFolderDialog() { if ('error' in result) { throw new Error(result.error) } - const repo = result.repo + const { repo } = upsertAddedRepoWithProjectHostSetup(result.repo, { + sshConnectionId: connectionId + }) const state = useAppStore.getState() const hadProjectBeforeAdd = stateBeforeAdd.repos.length > 0 - if (!state.repos.some((r) => r.id === repo.id)) { - useAppStore.setState({ repos: [...state.repos, repo] }) - } await markOnboardingProjectAdded('addedFolder') - await state.fetchWorktrees(repo.id) + const ownerOptions = worktreeRefreshOptions(undefined, connectionId) + await state.fetchWorktrees(repo.id, ownerOptions) // Why: mirror the local non-git folder flow — without this the // dialog closes and the UI shows no visible change, making the // add feel like a no-op. Activating the synthetic folder // worktree reveals it in the sidebar and opens the workspace. - const folderWorktree = useAppStore.getState().worktreesByRepo[repo.id]?.[0] + const folderWorktree = useAppStore + .getState() + .worktreesByRepo[repo.id]?.find( + (worktree) => worktree.hostId === ownerOptions.executionHostId + ) if (folderWorktree) { const onboarding = await window.api.onboarding.get().catch(() => null) // Why: SSH users can hit this dialog from Add Project after @@ -84,6 +90,7 @@ const NonGitFolderDialog = React.memo(function NonGitFolderDialog() { ) activateAndRevealWorktree(folderWorktree.id, { sidebarRevealBehavior: 'auto', + executionHostId: ownerOptions.executionHostId, ...(startup ? { startup } : {}) }) } diff --git a/src/renderer/src/components/sidebar/WorktreeCard.affiliate-list-mode.test.tsx b/src/renderer/src/components/sidebar/WorktreeCard.affiliate-list-mode.test.tsx index 31e29c839..1f15663a5 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.affiliate-list-mode.test.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCard.affiliate-list-mode.test.tsx @@ -206,7 +206,8 @@ describe('WorktreeCard affiliate list mode', () => { }) expect(testDoubles.activateWorktreeFromSidebar).toHaveBeenCalledWith( - 'repo-1::/repo/worktrees/affiliate' + 'repo-1::/repo/worktrees/affiliate', + 'local' ) }) diff --git a/src/renderer/src/components/sidebar/WorktreeCard.tsx b/src/renderer/src/components/sidebar/WorktreeCard.tsx index 2dfd73a21..9cc437fc5 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCard.tsx @@ -84,6 +84,7 @@ import { translate } from '@/i18n/i18n' import { recordRendererCrashBreadcrumb } from '@/lib/crash-diagnostics' import { folderWorkspaceKey, parseWorkspaceKey } from '../../../../shared/workspace-scope' import { + getRepoExecutionHostId, isRuntimeOwnedSshTargetId, parseExecutionHostId, toRuntimeExecutionHostId @@ -872,7 +873,10 @@ const WorktreeCard = React.memo(function WorktreeCard({ sshDisconnected: isSshDisconnected }) onImmediateActivate?.(worktree.id, activationRowKey) - void activateWorktreeFromSidebar(worktree.id) + void activateWorktreeFromSidebar( + worktree.id, + worktree.hostId ?? (repo ? getRepoExecutionHostId(repo) : undefined) + ) // Why: a deliberate card click warrants the blocking reconnect prompt; skip it when a terminal already shows the overlay. if (isSshDisconnected && !activeViewIsTerminal) { setShowDisconnectedDialog(true) @@ -883,6 +887,8 @@ const WorktreeCard = React.memo(function WorktreeCard({ affiliateListMode, worktree.id, worktree.repoId, + worktree.hostId, + repo, isActive, isDeleting, activationRowKey, diff --git a/src/renderer/src/components/sidebar/add-repo-runtime-owner.ts b/src/renderer/src/components/sidebar/add-repo-runtime-owner.ts new file mode 100644 index 000000000..3bcc06d4a --- /dev/null +++ b/src/renderer/src/components/sidebar/add-repo-runtime-owner.ts @@ -0,0 +1,35 @@ +import { + LOCAL_EXECUTION_HOST_ID, + toRuntimeExecutionHostId, + toSshExecutionHostId, + type ExecutionHostId +} from '../../../../shared/execution-host' + +export type CapturedRuntimeOwner = string | null | undefined + +export function capturedAddRepoExecutionHostId( + owner: CapturedRuntimeOwner, + sshConnectionId?: string | null +): ExecutionHostId | undefined { + return sshConnectionId + ? toSshExecutionHostId(sshConnectionId) + : owner !== undefined + ? owner + ? toRuntimeExecutionHostId(owner) + : LOCAL_EXECUTION_HOST_ID + : undefined +} + +export function worktreeRefreshOptions( + owner: CapturedRuntimeOwner, + sshConnectionId?: string | null +): { + requireAuthoritative: true + executionHostId?: ExecutionHostId +} { + const executionHostId = capturedAddRepoExecutionHostId(owner, sshConnectionId) + return { + requireAuthoritative: true, + ...(executionHostId ? { executionHostId } : {}) + } +} diff --git a/src/renderer/src/components/sidebar/add-repo-store-upsert.ts b/src/renderer/src/components/sidebar/add-repo-store-upsert.ts index 664d5e3e9..1593b3cda 100644 --- a/src/renderer/src/components/sidebar/add-repo-store-upsert.ts +++ b/src/renderer/src/components/sidebar/add-repo-store-upsert.ts @@ -1,12 +1,46 @@ import { projectHostSetupProjectionFromRepos } from '../../../../shared/project-host-setup-projection' +import { + LOCAL_EXECUTION_HOST_ID, + toRuntimeExecutionHostId, + toSshExecutionHostId +} from '../../../../shared/execution-host' import type { Repo } from '../../../../shared/types' import { useAppStore } from '@/store' +import { getRepoHostIdentity } from '@/store/slices/repo-host-identity' -export function upsertAddedRepoWithProjectHostSetup(repo: Repo): void { +type AddedRepoOwner = { + runtimeEnvironmentId?: string | null + sshConnectionId?: string | null +} + +function repoWithCapturedOwner(repo: Repo, owner: AddedRepoOwner): Repo { + const sshConnectionId = owner.sshConnectionId?.trim() + if (sshConnectionId) { + return { ...repo, executionHostId: toSshExecutionHostId(sshConnectionId) } + } + if (owner.runtimeEnvironmentId !== undefined) { + const runtimeEnvironmentId = owner.runtimeEnvironmentId?.trim() + return { + ...repo, + executionHostId: runtimeEnvironmentId + ? toRuntimeExecutionHostId(runtimeEnvironmentId) + : LOCAL_EXECUTION_HOST_ID + } + } + return repo +} + +export function upsertAddedRepoWithProjectHostSetup( + repo: Repo, + owner: AddedRepoOwner = {} +): { alreadyPresent: boolean; repo: Repo } { const state = useAppStore.getState() - const repos = state.repos.some((entry) => entry.id === repo.id) - ? state.repos.map((entry) => (entry.id === repo.id ? repo : entry)) - : [...state.repos, repo] + const ownedRepo = repoWithCapturedOwner(repo, owner) + const repoIdentity = getRepoHostIdentity(ownedRepo) + const alreadyPresent = state.repos.some((entry) => getRepoHostIdentity(entry) === repoIdentity) + const repos = alreadyPresent + ? state.repos.map((entry) => (getRepoHostIdentity(entry) === repoIdentity ? ownedRepo : entry)) + : [...state.repos, ownedRepo] const projection = projectHostSetupProjectionFromRepos(repos) // Why: these Add Project flows call IPC directly, bypassing the repo slice @@ -16,4 +50,5 @@ export function upsertAddedRepoWithProjectHostSetup(repo: Repo): void { projects: projection.projects, projectHostSetups: projection.setups }) + return { alreadyPresent, repo: ownedRepo } } diff --git a/src/renderer/src/components/sidebar/complete-nested-folder-open.ts b/src/renderer/src/components/sidebar/complete-nested-folder-open.ts new file mode 100644 index 000000000..329027b6a --- /dev/null +++ b/src/renderer/src/components/sidebar/complete-nested-folder-open.ts @@ -0,0 +1,51 @@ +import { toast } from 'sonner' +import { useAppStore } from '@/store' +import type { NestedRepoScanResult } from '../../../../shared/types' +import type { CapturedRuntimeOwner } from './add-repo-runtime-owner' +import { trackNestedFolderOpen } from './track-nested-folder-open' + +export async function completeNestedFolderOpen(args: { + scan: NestedRepoScanResult + generation: number + currentGeneration: () => number + attemptId: string | null + runtimeKind: Parameters[0]['runtimeKind'] + connectionId: string | null + selectedCount: number + getRuntimeKind: Parameters[0]['getRuntimeKind'] + owner: CapturedRuntimeOwner + closeModal: () => void + setIsAdding: (value: boolean) => void +}): Promise { + trackNestedFolderOpen(args) + args.setIsAdding(true) + try { + const state = useAppStore.getState() + if (args.connectionId) { + args.closeModal() + state.openModal('confirm-non-git-folder', { + folderPath: args.scan.selectedPath, + connectionId: args.connectionId, + runtimeEnvironmentId: args.owner + }) + return + } + const repo = await state.addNonGitFolder(args.scan.selectedPath, { + runtimeEnvironmentId: args.owner ?? null + }) + if (args.generation !== args.currentGeneration()) { + return + } + if (repo) { + args.closeModal() + } + } catch (err) { + if (args.generation === args.currentGeneration()) { + toast.error(err instanceof Error ? err.message : String(err)) + } + } finally { + if (args.generation === args.currentGeneration()) { + args.setIsAdding(false) + } + } +} diff --git a/src/renderer/src/components/sidebar/project-added-default-checkout.test.ts b/src/renderer/src/components/sidebar/project-added-default-checkout.test.ts index d4a2831f2..0f5ad7cfe 100644 --- a/src/renderer/src/components/sidebar/project-added-default-checkout.test.ts +++ b/src/renderer/src/components/sidebar/project-added-default-checkout.test.ts @@ -3,6 +3,7 @@ import { getDefaultOnboardingState } from '../../../../shared/constants' import type { DetectedWorktree, DetectedWorktreeListResult, + Repo, Worktree } from '../../../../shared/types' import { @@ -17,6 +18,7 @@ const mocks = vi.hoisted(() => ({ filterRepoIds: [] as string[], showActiveOnly: false, hideDefaultBranchWorkspace: false, + repos: [] as Repo[], worktreesByRepo: {} as Record, detectedWorktreesByRepo: {} as Record, setActiveRepo: vi.fn(), @@ -125,6 +127,7 @@ describe('finishProjectAddWithDefaultCheckout', () => { mocks.state.filterRepoIds = [] mocks.state.showActiveOnly = false mocks.state.hideDefaultBranchWorkspace = false + mocks.state.repos = [] mocks.state.worktreesByRepo = {} mocks.state.detectedWorktreesByRepo = {} mocks.state.updateRepo.mockResolvedValue(true) @@ -173,6 +176,51 @@ describe('finishProjectAddWithDefaultCheckout', () => { expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith('repo-1::/repo') }) + it('activates only the captured host default checkout when repo IDs collide', async () => { + const localMain = makeWorktree({ + id: 'repo-1::same-id', + path: '/local/repo', + hostId: 'local' + }) + const runtimeMain = makeWorktree({ + id: 'repo-1::same-id', + path: '/runtime/repo', + hostId: 'runtime:env-1' + }) + mocks.state.repos = [ + { + id: 'repo-1', + path: '/local/repo', + displayName: 'local', + badgeColor: '#111', + addedAt: 1, + executionHostId: 'local' + }, + { + id: 'repo-1', + path: '/runtime/repo', + displayName: 'runtime', + badgeColor: '#222', + addedAt: 2, + executionHostId: 'runtime:env-1' + } + ] + mocks.state.worktreesByRepo = { + 'repo-1': [localMain, runtimeMain] + } + + await openProjectDefaultCheckout({ + repoId: 'repo-1', + source: 'clone_url', + executionHostId: 'runtime:env-1', + setHideDefaultBranchWorkspace: vi.fn() + }) + + expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith(runtimeMain.id, { + executionHostId: 'runtime:env-1' + }) + }) + it('passes a contained selected path through as the initial terminal cwd', async () => { mocks.state.worktreesByRepo = { 'repo-1': [makeWorktree()] diff --git a/src/renderer/src/components/sidebar/project-added-default-checkout.ts b/src/renderer/src/components/sidebar/project-added-default-checkout.ts index b30ca0bb2..0c7fc74f7 100644 --- a/src/renderer/src/components/sidebar/project-added-default-checkout.ts +++ b/src/renderer/src/components/sidebar/project-added-default-checkout.ts @@ -9,6 +9,7 @@ import type { DetectedWorktreeListResult, Worktree } from '../../../../shared/ty import { relativePathInsideRoot } from '../../../../shared/cross-platform-path' import { markOnboardingProjectAdded } from '@/lib/onboarding-project-checklist' import { finalizeImportedRepoAfterSkip } from './add-repo-skip-finalization' +import type { ExecutionHostId } from '../../../../shared/execution-host' type DefaultCheckoutHandoffReason = EventProps<'add_repo_default_checkout_handoff'>['reason'] @@ -16,22 +17,53 @@ export function getProjectDefaultCheckout(worktrees: readonly Worktree[]): Workt return worktrees.find((worktree) => worktree.isMainWorktree) ?? null } +function getProjectWorktreesForHost( + worktrees: readonly T[], + executionHostId?: ExecutionHostId +): T[] { + if (!executionHostId) { + return [...worktrees] + } + return worktrees.filter((worktree) => { + if (worktree.hostId) { + return worktree.hostId === executionHostId + } + if (worktree.runtimeOwnerEnvironmentId) { + return executionHostId === `runtime:${encodeURIComponent(worktree.runtimeOwnerEnvironmentId)}` + } + return executionHostId === 'local' + }) +} + +function ownerRefreshOptions(executionHostId?: ExecutionHostId) { + return { + requireAuthoritative: true as const, + ...(executionHostId ? { executionHostId } : {}) + } +} + function getDetectedProjectDefaultCheckout( - detected: DetectedWorktreeListResult | undefined + detected: DetectedWorktreeListResult | undefined, + executionHostId?: ExecutionHostId ): DetectedWorktreeListResult['worktrees'][number] | null { if (detected?.authoritative !== true) { return null } - return detected.worktrees.find((worktree) => worktree.isMainWorktree) ?? null + return ( + getProjectWorktreesForHost(detected.worktrees, executionHostId).find( + (worktree) => worktree.isMainWorktree + ) ?? null + ) } function hasDetectedHiddenLinkedExternalWorktrees( - detected: DetectedWorktreeListResult | undefined + detected: DetectedWorktreeListResult | undefined, + executionHostId?: ExecutionHostId ): boolean { if (detected?.authoritative !== true) { return false } - return detected.worktrees.some( + return getProjectWorktreesForHost(detected.worktrees, executionHostId).some( (worktree) => !worktree.isMainWorktree && !worktree.selectedCheckout && @@ -44,32 +76,47 @@ function hasDetectedHiddenLinkedExternalWorktrees( } async function revealDetectedHiddenLinkedExternalWorktrees( - repoId: string + repoId: string, + executionHostId?: ExecutionHostId ): Promise { const state = useAppStore.getState() - if (!hasDetectedHiddenLinkedExternalWorktrees(state.detectedWorktreesByRepo[repoId])) { + if ( + !hasDetectedHiddenLinkedExternalWorktrees( + state.detectedWorktreesByRepo[repoId], + executionHostId + ) + ) { return null } // Why: the removed setup step's existing-worktree path made linked external // worktrees visible; the automatic handoff must preserve that import result. - const updated = await state.updateRepo(repoId, { externalWorktreeVisibility: 'show' }) + const updated = executionHostId + ? await state.updateRepo( + repoId, + { externalWorktreeVisibility: 'show' }, + { hostId: executionHostId } + ) + : await state.updateRepo(repoId, { externalWorktreeVisibility: 'show' }) if (!updated) { return 'show_detected_linked_failed' } - const refreshed = await useAppStore.getState().fetchWorktrees(repoId, { - requireAuthoritative: true - }) + const refreshed = await useAppStore + .getState() + .fetchWorktrees(repoId, ownerRefreshOptions(executionHostId)) return refreshed ? null : 'linked_external_refresh_failed' } -async function findDetectedDefaultCheckout(repoId: string): Promise<{ +async function findDetectedDefaultCheckout( + repoId: string, + executionHostId?: ExecutionHostId +): Promise<{ worktree: Worktree | null reason: DefaultCheckoutHandoffReason }> { const state = useAppStore.getState() const detected = state.detectedWorktreesByRepo[repoId] - const detectedDefaultCheckout = getDetectedProjectDefaultCheckout(detected) + const detectedDefaultCheckout = getDetectedProjectDefaultCheckout(detected, executionHostId) if (!detectedDefaultCheckout) { return { worktree: null, @@ -80,18 +127,29 @@ async function findDetectedDefaultCheckout(repoId: string): Promise<{ if (!detectedDefaultCheckout.visible) { // Why: a freshly cloned primary checkout can be detected as a hidden // external worktree; adding a project should make that checkout usable. - const updated = await state.updateRepo(repoId, { externalWorktreeVisibility: 'show' }) + const updated = executionHostId + ? await state.updateRepo( + repoId, + { externalWorktreeVisibility: 'show' }, + { hostId: executionHostId } + ) + : await state.updateRepo(repoId, { externalWorktreeVisibility: 'show' }) if (!updated) { return { worktree: null, reason: 'show_detected_default_failed' } } } - const refreshed = await useAppStore.getState().fetchWorktrees(repoId, { - requireAuthoritative: true - }) + const refreshed = await useAppStore + .getState() + .fetchWorktrees(repoId, ownerRefreshOptions(executionHostId)) if (!refreshed) { return { worktree: null, reason: 'authoritative_refresh_failed' } } - const worktree = getProjectDefaultCheckout(useAppStore.getState().worktreesByRepo[repoId] ?? []) + const worktree = getProjectDefaultCheckout( + getProjectWorktreesForHost( + useAppStore.getState().worktreesByRepo[repoId] ?? [], + executionHostId + ) + ) return { worktree, reason: worktree ? 'detected_default_checkout' : 'refreshed_default_missing' @@ -113,25 +171,33 @@ export async function openProjectDefaultCheckout({ repoId, source, selectedPath, - setHideDefaultBranchWorkspace + setHideDefaultBranchWorkspace, + executionHostId }: { repoId: string source: AddRepoDefaultCheckoutHandoffSource selectedPath?: string setHideDefaultBranchWorkspace: (value: boolean) => void + executionHostId?: ExecutionHostId }): Promise { let defaultCheckout = getProjectDefaultCheckout( - useAppStore.getState().worktreesByRepo[repoId] ?? [] + getProjectWorktreesForHost( + useAppStore.getState().worktreesByRepo[repoId] ?? [], + executionHostId + ) ) let reason: DefaultCheckoutHandoffReason = 'loaded_default_checkout' if (!defaultCheckout) { - const detectedDefaultCheckout = await findDetectedDefaultCheckout(repoId) + const detectedDefaultCheckout = await findDetectedDefaultCheckout(repoId, executionHostId) defaultCheckout = detectedDefaultCheckout.worktree reason = detectedDefaultCheckout.reason } if (defaultCheckout) { - const revealLinkedFailureReason = await revealDetectedHiddenLinkedExternalWorktrees(repoId) + const revealLinkedFailureReason = await revealDetectedHiddenLinkedExternalWorktrees( + repoId, + executionHostId + ) if (revealLinkedFailureReason) { track('add_repo_default_checkout_handoff', { source, @@ -153,8 +219,11 @@ export async function openProjectDefaultCheckout({ reason }) const initialCwd = resolveInitialCwdForDefaultCheckout(defaultCheckout, selectedPath) - if (initialCwd) { - activateAndRevealWorktree(defaultCheckout.id, { initialCwd }) + if (initialCwd || executionHostId) { + activateAndRevealWorktree(defaultCheckout.id, { + ...(initialCwd ? { initialCwd } : {}), + ...(executionHostId ? { executionHostId } : {}) + }) } else { activateAndRevealWorktree(defaultCheckout.id) } @@ -174,13 +243,15 @@ export async function finishProjectAddWithDefaultCheckout({ source, selectedPath, closeModal, - setHideDefaultBranchWorkspace + setHideDefaultBranchWorkspace, + executionHostId }: { repoId: string source: AddRepoDefaultCheckoutHandoffSource selectedPath?: string closeModal: () => void setHideDefaultBranchWorkspace: (value: boolean) => void + executionHostId?: ExecutionHostId }): Promise { await markOnboardingProjectAdded('addedRepo') closeModal() @@ -188,6 +259,7 @@ export async function finishProjectAddWithDefaultCheckout({ repoId, source, selectedPath, + executionHostId, setHideDefaultBranchWorkspace }) } diff --git a/src/renderer/src/components/sidebar/track-nested-folder-open.ts b/src/renderer/src/components/sidebar/track-nested-folder-open.ts new file mode 100644 index 000000000..add9c4aae --- /dev/null +++ b/src/renderer/src/components/sidebar/track-nested-folder-open.ts @@ -0,0 +1,30 @@ +import { track } from '@/lib/telemetry' +import { + buildNestedRepoImportActionTelemetry, + type NestedRepoTelemetryRuntimeKind +} from '../../../../shared/nested-repo-telemetry' +import type { NestedRepoScanResult } from '../../../../shared/types' + +export function trackNestedFolderOpen(args: { + attemptId: string | null + runtimeKind: NestedRepoTelemetryRuntimeKind | null + connectionId: string | null + scan: NestedRepoScanResult + selectedCount: number + getRuntimeKind: (connectionId: string | null) => NestedRepoTelemetryRuntimeKind +}): void { + if (!args.attemptId) { + return + } + track( + 'add_repo_nested_import_action', + buildNestedRepoImportActionTelemetry({ + attemptId: args.attemptId, + surface: 'sidebar', + runtimeKind: args.runtimeKind ?? args.getRuntimeKind(args.connectionId), + action: 'open_as_folder', + foundCount: args.scan.repos.length, + selectedCount: args.selectedCount + }) + ) +} diff --git a/src/renderer/src/components/sidebar/use-add-repo-remote-nested-scan.ts b/src/renderer/src/components/sidebar/use-add-repo-remote-nested-scan.ts index 1f451b0a1..c57557f0c 100644 --- a/src/renderer/src/components/sidebar/use-add-repo-remote-nested-scan.ts +++ b/src/renderer/src/components/sidebar/use-add-repo-remote-nested-scan.ts @@ -7,7 +7,7 @@ export function useAddRepoRemoteNestedScan({ setActiveNestedScanId, showNestedRepoReview }: { - setActiveNestedScanId: (scanId: string | null) => void + setActiveNestedScanId: (scanId: string | null, runtimeEnvironmentId?: string | null) => void showNestedRepoReview: (options: { scan: NestedRepoScanResult selectedPath: string @@ -16,6 +16,7 @@ export function useAddRepoRemoteNestedScan({ runtimeKind: 'ssh' inProgress: boolean scanId: string | null + runtimeEnvironmentId?: string | null }) => void }) { const showRemoteNestedRepoReview = useCallback( @@ -27,7 +28,7 @@ export function useAddRepoRemoteNestedScan({ inProgress: boolean, scanId: string | null ) => { - setActiveNestedScanId(inProgress ? scanId : null) + setActiveNestedScanId(inProgress ? scanId : null, null) showNestedRepoReview({ scan, selectedPath, @@ -35,7 +36,8 @@ export function useAddRepoRemoteNestedScan({ attemptId, runtimeKind: 'ssh', inProgress, - scanId + scanId, + runtimeEnvironmentId: null }) }, [setActiveNestedScanId, showNestedRepoReview] diff --git a/src/renderer/src/components/sidebar/use-complete-git-repo-add.ts b/src/renderer/src/components/sidebar/use-complete-git-repo-add.ts index fe16881c7..a7ec91232 100644 --- a/src/renderer/src/components/sidebar/use-complete-git-repo-add.ts +++ b/src/renderer/src/components/sidebar/use-complete-git-repo-add.ts @@ -8,6 +8,7 @@ import { } from './add-repo-existing-workspaces-telemetry' import { compareWorktreeDisplayName } from '@/lib/worktree-display-name-order' import { finishProjectAddWithDefaultCheckout } from './project-added-default-checkout' +import type { ExecutionHostId } from '../../../../shared/execution-host' type CompleteGitRepoAddOptions = { closeModal: () => void @@ -15,7 +16,11 @@ type CompleteGitRepoAddOptions = { /** Why: the nested Add Project flow (hosted inside the workspace composer) * keeps the composer open and selects the new project instead of running * the default-checkout navigation handoff. Telemetry above still applies. */ - finishProjectAdd?: (repoId: string, source: AddRepoExistingWorkspaceSource) => Promise + finishProjectAdd?: ( + repoId: string, + source: AddRepoExistingWorkspaceSource, + executionHostId?: ExecutionHostId + ) => Promise } export function useCompleteGitRepoAdd({ @@ -24,13 +29,23 @@ export function useCompleteGitRepoAdd({ finishProjectAdd }: CompleteGitRepoAddOptions): ( repoId: string, - source: AddRepoExistingWorkspaceSource + source: AddRepoExistingWorkspaceSource, + executionHostId?: ExecutionHostId ) => Promise { const detectedTelemetryTrackedRef = useRef>(new Set()) return useCallback( - async (repoId: string, source: AddRepoExistingWorkspaceSource): Promise => { - const worktrees = useAppStore.getState().worktreesByRepo[repoId] ?? [] + async ( + repoId: string, + source: AddRepoExistingWorkspaceSource, + executionHostId?: ExecutionHostId + ): Promise => { + const worktrees = (useAppStore.getState().worktreesByRepo[repoId] ?? []).filter( + (worktree) => + executionHostId === undefined || + worktree.hostId === executionHostId || + (!worktree.hostId && executionHostId === 'local') + ) const sortedWorktrees = [...worktrees].sort((a, b) => { if (a.lastActivityAt !== b.lastActivityAt) { return b.lastActivityAt - a.lastActivityAt @@ -50,12 +65,13 @@ export function useCompleteGitRepoAdd({ track('add_repo_existing_workspaces_detected', existingWorkspaceTelemetry) } if (finishProjectAdd) { - await finishProjectAdd(repoId, source) + await finishProjectAdd(repoId, source, executionHostId) return } await finishProjectAddWithDefaultCheckout({ repoId, source, + executionHostId, closeModal, setHideDefaultBranchWorkspace }) diff --git a/src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts b/src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts index 3d02f5fe1..579581265 100644 --- a/src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts +++ b/src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts @@ -136,7 +136,12 @@ describe('useAddRepoCloneFlow', () => { }) expect(mocks.cloneLocal).not.toHaveBeenCalled() expect(mocks.fetchWorktrees).toHaveBeenCalledWith(repo.id, { - requireAuthoritative: true + requireAuthoritative: true, + executionHostId: 'ssh:ssh-1' + }) + expect(mocks.storeState.repos).toContainEqual({ + ...repo, + executionHostId: 'ssh:ssh-1' }) expect(mocks.storeState.projects).toEqual( expect.arrayContaining([expect.objectContaining({ sourceRepoIds: [repo.id] })]) @@ -144,7 +149,7 @@ describe('useAddRepoCloneFlow', () => { expect(mocks.storeState.projectHostSetups).toEqual( expect.arrayContaining([expect.objectContaining({ repoId: repo.id, path: repo.path })]) ) - expect(mocks.onGitRepoReady).toHaveBeenCalledWith(repo.id, 'clone_url') + expect(mocks.onGitRepoReady).toHaveBeenCalledWith(repo.id, 'clone_url', 'ssh:ssh-1') }) it('does not prefill SSH clone destinations from the local workspace directory', async () => { @@ -186,7 +191,13 @@ describe('useAddRepoCloneFlow', () => { }) it('clones through the selected runtime environment', async () => { - const repo = makeRepo({ id: 'runtime-repo', executionHostId: 'runtime:env-1' }) + const repo = makeRepo({ id: 'runtime-repo' }) + const localRepo = makeRepo({ + id: repo.id, + path: '/local/runtime-repo', + executionHostId: 'local' + }) + mocks.storeState.repos = [localRepo] mocks.callRuntimeRpc.mockResolvedValue({ repo }) mocks.fetchWorktrees.mockResolvedValue(true) const { useAddRepoCloneFlow } = await import('./useAddRepoCloneFlow') @@ -213,8 +224,14 @@ describe('useAddRepoCloneFlow', () => { expect(mocks.cloneLocal).not.toHaveBeenCalled() expect(mocks.cloneRemote).not.toHaveBeenCalled() expect(mocks.fetchWorktrees).toHaveBeenCalledWith(repo.id, { - requireAuthoritative: true + requireAuthoritative: true, + executionHostId: 'runtime:env-1' }) - expect(mocks.onGitRepoReady).toHaveBeenCalledWith(repo.id, 'clone_url') + expect(mocks.storeState.repos).toContainEqual({ + ...repo, + executionHostId: 'runtime:env-1' + }) + expect(mocks.storeState.repos).toContainEqual(localRepo) + expect(mocks.onGitRepoReady).toHaveBeenCalledWith(repo.id, 'clone_url', 'runtime:env-1') }) }) diff --git a/src/renderer/src/components/sidebar/useAddRepoCloneFlow.ts b/src/renderer/src/components/sidebar/useAddRepoCloneFlow.ts index cd376a014..24d275239 100644 --- a/src/renderer/src/components/sidebar/useAddRepoCloneFlow.ts +++ b/src/renderer/src/components/sidebar/useAddRepoCloneFlow.ts @@ -9,6 +9,8 @@ import type { AddRepoDialogStep } from './add-repo-dialog-types' import { translate } from '@/i18n/i18n' import { extractIpcErrorMessage } from '@/lib/ipc-error' import { upsertAddedRepoWithProjectHostSetup } from './add-repo-store-upsert' +import { worktreeRefreshOptions } from './add-repo-runtime-owner' +import type { ExecutionHostId } from '../../../../shared/execution-host' export function useAddRepoCloneFlow({ step, @@ -22,8 +24,15 @@ export function useAddRepoCloneFlow({ activeRuntimeEnvironmentId: string | null | undefined sshTargetId?: string | null workspaceDir: string | null | undefined - fetchWorktrees: (repoId: string, options?: { requireAuthoritative?: boolean }) => Promise - onGitRepoReady: (repoId: string, source: AddRepoExistingWorkspaceSource) => Promise + fetchWorktrees: ( + repoId: string, + options?: { requireAuthoritative?: boolean; executionHostId?: ExecutionHostId } + ) => Promise + onGitRepoReady: ( + repoId: string, + source: AddRepoExistingWorkspaceSource, + executionHostId?: ExecutionHostId + ) => Promise }): { cloneUrl: string cloneDestination: string @@ -148,18 +157,22 @@ export function useAddRepoCloneFlow({ if (gen !== cloneGenRef.current || requestHostToken !== hostTokenRef.current) { return } + const { repo: ownedRepo } = upsertAddedRepoWithProjectHostSetup(repo, { + runtimeEnvironmentId: activeRuntimeEnvironmentId, + sshConnectionId: sshTargetId + }) toast.success( translate('auto.components.sidebar.useAddRepoCloneFlow.4d0013cc93', 'Repository cloned'), - { description: repo.displayName } + { description: ownedRepo.displayName } ) - upsertAddedRepoWithProjectHostSetup(repo) // Why: once the repo exists, a transient non-authoritative refresh // should fall through to project reveal instead of leaving the add flow open. - await fetchWorktrees(repo.id, { requireAuthoritative: true }) + const ownerOptions = worktreeRefreshOptions(activeRuntimeEnvironmentId, sshTargetId) + await fetchWorktrees(ownedRepo.id, ownerOptions) if (gen !== cloneGenRef.current || requestHostToken !== hostTokenRef.current) { return } - await onGitRepoReady(repo.id, 'clone_url') + await onGitRepoReady(ownedRepo.id, 'clone_url', ownerOptions.executionHostId) } catch (err) { if (gen !== cloneGenRef.current || requestHostToken !== hostTokenRef.current) { return diff --git a/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts b/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts index 799c655f0..acc96258c 100644 --- a/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts +++ b/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts @@ -106,12 +106,27 @@ describe('useAddRepoLocalFolderFlow', () => { expect(pickFolders).toHaveBeenCalledTimes(1) expect(addRepoPath).toHaveBeenCalledTimes(2) - expect(addRepoPath).toHaveBeenNthCalledWith(1, '/projects/alpha') - expect(addRepoPath).toHaveBeenNthCalledWith(2, '/projects/beta') - expect(fetchWorktrees).toHaveBeenCalledWith('alpha', { requireAuthoritative: true }) - expect(fetchWorktrees).toHaveBeenCalledWith('beta', { requireAuthoritative: true }) + expect(addRepoPath).toHaveBeenNthCalledWith(1, '/projects/alpha', undefined, { + runtimeEnvironmentId: null + }) + expect(addRepoPath).toHaveBeenNthCalledWith(2, '/projects/beta', undefined, { + runtimeEnvironmentId: null + }) + expect(scanNestedRepos).toHaveBeenCalledWith( + '/projects/alpha', + undefined, + expect.objectContaining({ runtimeEnvironmentId: null }) + ) + expect(fetchWorktrees).toHaveBeenCalledWith('alpha', { + requireAuthoritative: true, + executionHostId: 'local' + }) + expect(fetchWorktrees).toHaveBeenCalledWith('beta', { + requireAuthoritative: true, + executionHostId: 'local' + }) expect(onGitRepoReady).toHaveBeenCalledTimes(1) - expect(onGitRepoReady).toHaveBeenCalledWith('alpha', 'local_folder_picker') + expect(onGitRepoReady).toHaveBeenCalledWith('alpha', 'local_folder_picker', 'local') }) it('skips nested-review folders in a multi-folder add and continues with git folders', async () => { @@ -146,9 +161,11 @@ describe('useAddRepoLocalFolderFlow', () => { expect(showNestedRepoReview).not.toHaveBeenCalled() expect(addRepoPath).toHaveBeenCalledTimes(1) - expect(addRepoPath).toHaveBeenCalledWith('/projects/later') + expect(addRepoPath).toHaveBeenCalledWith('/projects/later', undefined, { + runtimeEnvironmentId: null + }) expect(scanNestedRepos).toHaveBeenCalledTimes(2) - expect(onGitRepoReady).toHaveBeenCalledWith('later', 'local_folder_picker') + expect(onGitRepoReady).toHaveBeenCalledWith('later', 'local_folder_picker', 'local') }) it('still completes handoff when a later selected folder is skipped', async () => { @@ -181,7 +198,44 @@ describe('useAddRepoLocalFolderFlow', () => { expect(showNestedRepoReview).not.toHaveBeenCalled() expect(addRepoPath).toHaveBeenCalledTimes(1) - expect(addRepoPath).toHaveBeenCalledWith('/projects/git') - expect(onGitRepoReady).toHaveBeenCalledWith('git', 'local_folder_picker') + expect(addRepoPath).toHaveBeenCalledWith('/projects/git', undefined, { + runtimeEnvironmentId: null + }) + expect(onGitRepoReady).toHaveBeenCalledWith('git', 'local_folder_picker', 'local') + }) + + it('drops a local scan completion after host-scoped reset', async () => { + pickFolders.mockResolvedValue(['/projects/stale']) + let resolveScan!: (scan: NestedRepoScanResult) => void + scanNestedRepos.mockReturnValueOnce( + new Promise((resolve) => { + resolveScan = resolve + }) + ) + const { useAddRepoLocalFolderFlow } = await import('./useAddRepoLocalFolderFlow') + const flow = useAddRepoLocalFolderFlow({ + isOpen: true, + droppedLocalPath: '', + activeRuntimeEnvironmentId: null, + addRepoPath, + closeModal, + fetchWorktrees, + scanNestedRepos, + setActiveNestedScanId, + setNestedScanInProgress, + showNestedRepoReview, + onGitRepoReady, + setIsAdding, + setAddProjectBusyLabel + }) + + const adding = flow.handleBrowse() + await vi.waitFor(() => expect(scanNestedRepos).toHaveBeenCalled()) + flow.resetLocalFolderFlow() + resolveScan(makeScan('/projects/stale')) + await adding + + expect(addRepoPath).not.toHaveBeenCalled() + expect(onGitRepoReady).not.toHaveBeenCalled() }) }) diff --git a/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts b/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts index 844eb11ad..859698f19 100644 --- a/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts +++ b/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts @@ -9,8 +9,12 @@ import { } from '../../../../shared/nested-repo-telemetry' import type { AddRepoExistingWorkspaceSource } from '../../../../shared/telemetry-events' import type { NestedRepoScanResult, Repo } from '../../../../shared/types' +import type { WorktreeFetchOptions } from '@/store/slices/worktree-helpers' +import type { RepoSlice } from '@/store/slices/repos' import { createNestedRepoScanId } from './add-repo-dialog-types' import { translate } from '@/i18n/i18n' +import { worktreeRefreshOptions } from './add-repo-runtime-owner' +import type { ExecutionHostId } from '../../../../shared/execution-host' type ShowNestedRepoReview = (args: { scan: NestedRepoScanResult @@ -20,6 +24,7 @@ type ShowNestedRepoReview = (args: { runtimeKind: NestedRepoTelemetryRuntimeKind inProgress: boolean scanId: string | null + runtimeEnvironmentId?: string | null }) => void type LocalPathAddResult = @@ -46,18 +51,18 @@ export function useAddRepoLocalFolderFlow({ isOpen: boolean droppedLocalPath: string activeRuntimeEnvironmentId: string | null | undefined - addRepoPath: (path: string, kind?: 'git' | 'folder') => Promise + addRepoPath: RepoSlice['addRepoPath'] closeModal: () => void - fetchWorktrees: (repoId: string, options?: { requireAuthoritative?: boolean }) => Promise - scanNestedRepos: ( - path: string, - connectionId?: string, - controls?: { scanId?: string; onProgress?: (scan: NestedRepoScanResult) => void } - ) => Promise - setActiveNestedScanId: (scanId: string | null) => void + fetchWorktrees: (repoId: string, options?: WorktreeFetchOptions) => Promise + scanNestedRepos: RepoSlice['scanNestedRepos'] + setActiveNestedScanId: (scanId: string | null, runtimeEnvironmentId?: string | null) => void setNestedScanInProgress: (inProgress: boolean) => void showNestedRepoReview: ShowNestedRepoReview - onGitRepoReady: (repoId: string, source: AddRepoExistingWorkspaceSource) => Promise + onGitRepoReady: ( + repoId: string, + source: AddRepoExistingWorkspaceSource, + executionHostId?: ExecutionHostId + ) => Promise setIsAdding: (isAdding: boolean) => void setAddProjectBusyLabel: (label: string | null) => void }): { @@ -98,10 +103,11 @@ export function useAddRepoLocalFolderFlow({ try { const attemptId = createNestedRepoTelemetryAttemptId() const scanId = createNestedRepoScanId() - setActiveNestedScanId(scanId) + setActiveNestedScanId(scanId, activeRuntimeEnvironmentId ?? null) setNestedScanInProgress(true) const scan = await scanNestedRepos(path, undefined, { scanId, + runtimeEnvironmentId: activeRuntimeEnvironmentId ?? null, onProgress: (progressScan) => { if ( gen !== localAddGenRef.current || @@ -118,7 +124,8 @@ export function useAddRepoLocalFolderFlow({ attemptId, runtimeKind: 'local', inProgress: true, - scanId + scanId, + runtimeEnvironmentId: activeRuntimeEnvironmentId }) } }) @@ -139,8 +146,7 @@ export function useAddRepoLocalFolderFlow({ return { status: 'skipped' } } if (scan?.selectedPathKind === 'non_git_folder' && scan.repos.length > 0) { - // Why: the existing nested-repo review is a single-folder decision point. - // Pause batch imports here instead of queueing competing review states. + // Why: a single-folder decision point cannot queue competing batch review states. showNestedRepoReview({ scan, selectedPath: path, @@ -148,12 +154,15 @@ export function useAddRepoLocalFolderFlow({ attemptId, runtimeKind: 'local', inProgress: false, - scanId + scanId, + runtimeEnvironmentId: activeRuntimeEnvironmentId }) return { status: 'paused' } } setAddProjectBusyLabel('Opening project...') - const repo = await addRepoPath(path) + const repo = await addRepoPath(path, undefined, { + runtimeEnvironmentId: activeRuntimeEnvironmentId ?? null + }) if (gen !== localAddGenRef.current) { return { status: 'cancelled' } } @@ -161,16 +170,16 @@ export function useAddRepoLocalFolderFlow({ return { status: 'paused' } } if (isGitRepoKind(repo)) { - // Why: once the repo exists, a transient non-authoritative refresh - // should fall through to project reveal instead of leaving the add flow open. - await fetchWorktrees(repo.id, { requireAuthoritative: true }) + // Why: a transient non-authoritative refresh must not strand a persisted repo. + const ownerOptions = worktreeRefreshOptions(activeRuntimeEnvironmentId ?? null) + await fetchWorktrees(repo.id, ownerOptions) if (gen !== localAddGenRef.current) { return { status: 'cancelled' } } if (mode === 'batch') { return { status: 'completed', repo } } - await onGitRepoReady(repo.id, source) + await onGitRepoReady(repo.id, source, ownerOptions.executionHostId) } else { // Why: folder repos skip the Git default-checkout handoff and activate // their synthetic root workspace in the folder add flow. @@ -260,10 +269,14 @@ export function useAddRepoLocalFolderFlow({ ) } if (shouldDeferGitRepoReady && gitRepoIds.length > 0) { - await onGitRepoReady(gitRepoIds[0], source) + await onGitRepoReady( + gitRepoIds[0], + source, + worktreeRefreshOptions(activeRuntimeEnvironmentId ?? null).executionHostId + ) } }, - [addLocalPathForGeneration, onGitRepoReady] + [activeRuntimeEnvironmentId, addLocalPathForGeneration, onGitRepoReady] ) useEffect(() => { diff --git a/src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts b/src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts index aa5a4b9fd..6f56f454e 100644 --- a/src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts +++ b/src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts @@ -111,7 +111,8 @@ describe('useAddRepoNestedImportFlow open folder fallback', () => { it('keeps runtime folder opens on the runtime that produced the scan', async () => { const { handleOpenNestedRootFolder } = useTestAddRepoNestedImportFlow({ - activeRuntimeEnvironmentId: 'env-1' + activeRuntimeEnvironmentId: 'env-1', + nestedRuntimeEnvironmentId: 'env-1' }) await handleOpenNestedRootFolder() @@ -153,4 +154,52 @@ describe('useAddRepoNestedImportFlow open folder fallback', () => { connectionId: 'ssh-builder' }) }) + + it('keeps SSH import and completion pinned when repo hydration is missing', async () => { + const importedRepo: Repo = { + ...folderRepo, + id: 'ssh-app', + path: scan.repos[0].path, + kind: 'git', + connectionId: 'ssh-builder' + } + const importNestedRepos = vi.fn().mockResolvedValue({ + projects: [ + { path: importedRepo.path, projectId: importedRepo.id, status: 'imported' as const } + ], + importedCount: 1, + alreadyKnownCount: 0, + failedCount: 0 + }) + const fetchWorktrees = vi.fn() + const onGitRepoReady = vi.fn() + mocks.state.repos = [] + const { handleImportNestedRepos } = useTestAddRepoNestedImportFlow({ + activeRuntimeEnvironmentId: null, + nestedConnectionId: 'ssh-builder', + nestedRuntimeEnvironmentId: null, + nestedRuntimeKind: 'ssh', + nestedSelectedPaths: new Set([importedRepo.path]), + importNestedRepos, + fetchWorktrees, + onGitRepoReady + }) + + await handleImportNestedRepos('group') + + expect(importNestedRepos).toHaveBeenCalledWith({ + parentPath: scan.selectedPath, + groupName: 'platform', + projectPaths: [importedRepo.path], + connectionId: 'ssh-builder', + scanId: 'scan-1', + runtimeEnvironmentId: null, + mode: 'group' + }) + expect(fetchWorktrees).toHaveBeenCalledWith(importedRepo.id, { + requireAuthoritative: true, + executionHostId: 'ssh:ssh-builder' + }) + expect(onGitRepoReady).not.toHaveBeenCalled() + }) }) diff --git a/src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.ts b/src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.ts index c0a697518..c0c505cc9 100644 --- a/src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.ts +++ b/src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.ts @@ -11,7 +11,11 @@ import { } from '../../../../shared/nested-repo-telemetry' import type { AddRepoExistingWorkspaceSource } from '../../../../shared/telemetry-events' import type { NestedRepoScanResult, ProjectGroupImportResult } from '../../../../shared/types' +import type { WorktreeFetchOptions } from '@/store/slices/worktree-helpers' import { translate } from '@/i18n/i18n' +import { worktreeRefreshOptions, type CapturedRuntimeOwner } from './add-repo-runtime-owner' +import { completeNestedFolderOpen } from './complete-nested-folder-open' +import type { ExecutionHostId } from '../../../../shared/execution-host' export function useAddRepoNestedImportFlow({ nestedAttemptId, @@ -21,6 +25,7 @@ export function useAddRepoNestedImportFlow({ nestedConnectionId, nestedGroupName, nestedImportScanId, + nestedRuntimeEnvironmentId, activeRuntimeEnvironmentId, closeModal, fetchWorktrees, @@ -36,21 +41,25 @@ export function useAddRepoNestedImportFlow({ nestedConnectionId: string | null nestedGroupName: string nestedImportScanId: string | null + nestedRuntimeEnvironmentId?: CapturedRuntimeOwner activeRuntimeEnvironmentId: string | null | undefined - /** Why: hosted (composer-nested) mode routes this to closing only the - * nested dialog; store-modal mode routes it to the activeModal slot. */ closeModal: () => void - fetchWorktrees: (repoId: string, options?: { requireAuthoritative?: boolean }) => Promise + fetchWorktrees: (repoId: string, options?: WorktreeFetchOptions) => Promise importNestedRepos: (args: { parentPath: string groupName: string projectPaths: string[] connectionId?: string scanId?: string + runtimeEnvironmentId?: string | null mode: 'group' | 'separate' }) => Promise getNestedRepoRuntimeKind: (connectionId: string | null) => NestedRepoTelemetryRuntimeKind - onGitRepoReady: (repoId: string, source: AddRepoExistingWorkspaceSource) => Promise + onGitRepoReady: ( + repoId: string, + source: AddRepoExistingWorkspaceSource, + executionHostId?: ExecutionHostId + ) => Promise setIsAdding: (isAdding: boolean) => void }): { handleImportNestedRepos: (mode: 'group' | 'separate') => Promise @@ -59,11 +68,9 @@ export function useAddRepoNestedImportFlow({ trackNestedBackAction: () => void } { const nestedImportGenRef = useRef(0) - const resetNestedImportFlow = useCallback((): void => { nestedImportGenRef.current++ }, []) - const trackNestedBackAction = useCallback((): void => { if (!nestedScan || !nestedAttemptId) { return @@ -126,11 +133,10 @@ export function useAddRepoNestedImportFlow({ const result = await importNestedRepos({ parentPath: nestedScan.selectedPath, groupName: nestedGroupName, - // Why: Set insertion order can drift after deselect/reselect; import - // ordering should match the visible scan order users reviewed. projectPaths: selectedProjectPaths, ...(nestedConnectionId ? { connectionId: nestedConnectionId } : {}), ...(nestedImportScanId ? { scanId: nestedImportScanId } : {}), + runtimeEnvironmentId: nestedRuntimeEnvironmentId, mode }) track( @@ -168,10 +174,10 @@ export function useAddRepoNestedImportFlow({ } return } + const completionOwner = nestedConnectionId === null ? nestedRuntimeEnvironmentId : undefined + const completionOwnerOptions = worktreeRefreshOptions(completionOwner, nestedConnectionId) for (const projectId of importedRepoIds) { - // Why: imported repos are already persisted; non-authoritative SSH - // refreshes should not block revealing the first imported project. - await fetchWorktrees(projectId, { requireAuthoritative: true }) + await fetchWorktrees(projectId, completionOwnerOptions) } if (gen !== nestedImportGenRef.current) { return @@ -198,7 +204,7 @@ export function useAddRepoNestedImportFlow({ : activeRuntimeEnvironmentId?.trim() ? 'runtime_server_path' : 'local_folder_picker' - await onGitRepoReady(repo.id, source) + await onGitRepoReady(repo.id, source, completionOwnerOptions.executionHostId) } } catch (err) { if (gen === nestedImportGenRef.current) { @@ -232,6 +238,7 @@ export function useAddRepoNestedImportFlow({ nestedConnectionId, nestedGroupName, nestedImportScanId, + nestedRuntimeEnvironmentId, nestedRuntimeKind, nestedScan, nestedSelectedPaths, @@ -240,70 +247,35 @@ export function useAddRepoNestedImportFlow({ setIsAdding ] ) - - const handleOpenNestedRootFolder = useCallback(async (): Promise => { + const handleOpenNestedRootFolder = useCallback(() => { if (!nestedScan) { - return - } - const gen = ++nestedImportGenRef.current - const path = nestedScan.selectedPath - if (nestedAttemptId) { - track( - 'add_repo_nested_import_action', - buildNestedRepoImportActionTelemetry({ - attemptId: nestedAttemptId, - surface: 'sidebar', - runtimeKind: nestedRuntimeKind ?? getNestedRepoRuntimeKind(nestedConnectionId), - action: 'open_as_folder', - foundCount: nestedScan.repos.length, - selectedCount: nestedSelectedPaths.size - }) - ) - } - setIsAdding(true) - try { - const state = useAppStore.getState() - if (nestedConnectionId) { - // Why: the non-git confirm dialog is a store-modal handoff that ends - // in folder-workspace activation; close this add flow (nested dialog - // or store modal) before handing over. - closeModal() - state.openModal('confirm-non-git-folder', { - folderPath: path, - connectionId: nestedConnectionId - }) - return - } - const repo = await state.addNonGitFolder(path, { - runtimeEnvironmentId: activeRuntimeEnvironmentId?.trim() || null - }) - if (gen !== nestedImportGenRef.current) { - return - } - if (repo) { - closeModal() - } - } catch (err) { - if (gen === nestedImportGenRef.current) { - toast.error(err instanceof Error ? err.message : String(err)) - } - } finally { - if (gen === nestedImportGenRef.current) { - setIsAdding(false) - } + return Promise.resolve() } + const generation = ++nestedImportGenRef.current + return completeNestedFolderOpen({ + scan: nestedScan, + generation, + currentGeneration: () => nestedImportGenRef.current, + attemptId: nestedAttemptId, + runtimeKind: nestedRuntimeKind, + connectionId: nestedConnectionId, + selectedCount: nestedSelectedPaths.size, + getRuntimeKind: getNestedRepoRuntimeKind, + owner: nestedRuntimeEnvironmentId, + closeModal, + setIsAdding + }) }, [ - activeRuntimeEnvironmentId, closeModal, getNestedRepoRuntimeKind, nestedAttemptId, nestedConnectionId, nestedRuntimeKind, + nestedRuntimeEnvironmentId, nestedScan, nestedSelectedPaths.size, setIsAdding ]) - return { handleImportNestedRepos, handleOpenNestedRootFolder, diff --git a/src/renderer/src/components/sidebar/useAddRepoNestedReviewController.ts b/src/renderer/src/components/sidebar/useAddRepoNestedReviewController.ts new file mode 100644 index 000000000..a5f471537 --- /dev/null +++ b/src/renderer/src/components/sidebar/useAddRepoNestedReviewController.ts @@ -0,0 +1,82 @@ +import type { Dispatch, SetStateAction } from 'react' +import type { AddRepoExistingWorkspaceSource } from '../../../../shared/telemetry-events' +import type { ProjectGroupImportResult } from '../../../../shared/types' +import type { WorktreeFetchOptions } from '@/store/slices/worktree-helpers' +import { useAddRepoNestedImportFlow } from './useAddRepoNestedImportFlow' +import { useAddRepoNestedReviewState } from './useAddRepoNestedReviewState' +import { useAddRepoRemoteNestedScan } from './use-add-repo-remote-nested-scan' +import type { AddRepoDialogStep } from './add-repo-dialog-types' +import type { ExecutionHostId } from '../../../../shared/execution-host' + +export function useAddRepoNestedReviewController({ + activeRuntimeEnvironmentId, + cancelNestedRepoScan, + closeModal, + fetchWorktrees, + importNestedRepos, + onGitRepoReady, + setIsAdding, + setStep, + reviewRuntimeEnvironmentId +}: { + activeRuntimeEnvironmentId: string | null | undefined + reviewRuntimeEnvironmentId: string | null | undefined + cancelNestedRepoScan: ( + scanId: string, + options?: { runtimeEnvironmentId?: string | null } + ) => Promise + closeModal: () => void + fetchWorktrees: (repoId: string, options?: WorktreeFetchOptions) => Promise + importNestedRepos: (args: { + parentPath: string + groupName: string + projectPaths: string[] + connectionId?: string + scanId?: string + runtimeEnvironmentId?: string | null + mode: 'group' | 'separate' + }) => Promise + onGitRepoReady: ( + repoId: string, + source: AddRepoExistingWorkspaceSource, + executionHostId?: ExecutionHostId + ) => Promise + setIsAdding: (isAdding: boolean) => void + setStep: Dispatch> +}): ReturnType & + Pick< + ReturnType, + | 'handleImportNestedRepos' + | 'handleOpenNestedRootFolder' + | 'resetNestedImportFlow' + | 'trackNestedBackAction' + > & + ReturnType { + const review = useAddRepoNestedReviewState({ + activeRuntimeEnvironmentId: reviewRuntimeEnvironmentId, + cancelNestedRepoScan, + setStep + }) + const remote = useAddRepoRemoteNestedScan({ + setActiveNestedScanId: review.setActiveNestedScanId, + showNestedRepoReview: review.showNestedRepoReview + }) + const imports = useAddRepoNestedImportFlow({ + activeRuntimeEnvironmentId, + closeModal, + fetchWorktrees, + importNestedRepos, + onGitRepoReady, + setIsAdding, + nestedAttemptId: review.nestedAttemptId, + nestedScan: review.nestedScan, + nestedSelectedPaths: review.nestedSelectedPaths, + nestedRuntimeKind: review.nestedRuntimeKind, + nestedConnectionId: review.nestedConnectionId, + nestedGroupName: review.nestedGroupName, + nestedImportScanId: review.nestedImportScanId, + nestedRuntimeEnvironmentId: review.nestedRuntimeEnvironmentId, + getNestedRepoRuntimeKind: review.getNestedRepoRuntimeKind + }) + return { ...review, ...remote, ...imports } +} diff --git a/src/renderer/src/components/sidebar/useAddRepoNestedReviewState.ts b/src/renderer/src/components/sidebar/useAddRepoNestedReviewState.ts index 967229e95..a8f41592f 100644 --- a/src/renderer/src/components/sidebar/useAddRepoNestedReviewState.ts +++ b/src/renderer/src/components/sidebar/useAddRepoNestedReviewState.ts @@ -11,6 +11,7 @@ type ShowNestedRepoReviewArgs = { runtimeKind: NestedRepoTelemetryRuntimeKind inProgress: boolean scanId: string | null + runtimeEnvironmentId?: string | null } export function useAddRepoNestedReviewState({ @@ -19,7 +20,10 @@ export function useAddRepoNestedReviewState({ setStep }: { activeRuntimeEnvironmentId: string | null | undefined - cancelNestedRepoScan: (scanId: string) => Promise + cancelNestedRepoScan: ( + scanId: string, + options?: { runtimeEnvironmentId?: string | null } + ) => Promise setStep: (step: AddRepoDialogStep) => void }): { nestedScan: NestedRepoScanResult | null @@ -31,12 +35,13 @@ export function useAddRepoNestedReviewState({ nestedScanInProgress: boolean nestedScanId: string | null nestedImportScanId: string | null + nestedRuntimeEnvironmentId: string | null | undefined setNestedSelectedPaths: Dispatch>> setNestedGroupName: Dispatch> setNestedScanInProgress: Dispatch> getNestedRepoRuntimeKind: (connectionId: string | null) => NestedRepoTelemetryRuntimeKind showNestedRepoReview: (args: ShowNestedRepoReviewArgs) => void - setActiveNestedScanId: (scanId: string | null) => void + setActiveNestedScanId: (scanId: string | null, runtimeEnvironmentId?: string | null) => void handleStopNestedScan: () => void resetNestedRepoReviewState: () => void } { @@ -51,7 +56,11 @@ export function useAddRepoNestedReviewState({ const [nestedScanInProgress, setNestedScanInProgress] = useState(false) const [nestedScanId, setNestedScanId] = useState(null) const [nestedImportScanId, setNestedImportScanId] = useState(null) + const [nestedRuntimeEnvironmentId, setNestedRuntimeEnvironmentId] = useState< + string | null | undefined + >(undefined) const nestedScanIdRef = useRef(null) + const nestedScanRuntimeEnvironmentIdRef = useRef(undefined) const getNestedRepoRuntimeKind = useCallback( (connectionId: string | null): NestedRepoTelemetryRuntimeKind => { @@ -75,28 +84,37 @@ export function useAddRepoNestedReviewState({ setNestedRuntimeKind(args.runtimeKind) setNestedScanInProgress(args.inProgress) setNestedImportScanId(args.scanId) + setNestedRuntimeEnvironmentId(args.runtimeEnvironmentId ?? null) setStep('nested') }, [setStep] ) - const setActiveNestedScanId = useCallback((scanId: string | null): void => { - nestedScanIdRef.current = scanId - setNestedScanId(scanId) - }, []) + const setActiveNestedScanId = useCallback( + (scanId: string | null, runtimeEnvironmentId?: string | null): void => { + nestedScanIdRef.current = scanId + nestedScanRuntimeEnvironmentIdRef.current = scanId ? runtimeEnvironmentId : undefined + setNestedScanId(scanId) + }, + [] + ) const handleStopNestedScan = useCallback(() => { const scanId = nestedScanIdRef.current if (!scanId) { return } - void cancelNestedRepoScan(scanId) + void cancelNestedRepoScan(scanId, { + runtimeEnvironmentId: nestedScanRuntimeEnvironmentIdRef.current + }) }, [cancelNestedRepoScan]) const resetNestedRepoReviewState = useCallback((): void => { const activeNestedScanId = nestedScanIdRef.current if (activeNestedScanId) { - void cancelNestedRepoScan(activeNestedScanId) + void cancelNestedRepoScan(activeNestedScanId, { + runtimeEnvironmentId: nestedScanRuntimeEnvironmentIdRef.current + }) } setNestedScan(null) setNestedSelectedPaths(new Set()) @@ -106,6 +124,7 @@ export function useAddRepoNestedReviewState({ setNestedRuntimeKind(null) setNestedScanInProgress(false) setNestedImportScanId(null) + setNestedRuntimeEnvironmentId(null) setActiveNestedScanId(null) }, [cancelNestedRepoScan, setActiveNestedScanId]) @@ -119,6 +138,7 @@ export function useAddRepoNestedReviewState({ nestedScanInProgress, nestedScanId, nestedImportScanId, + nestedRuntimeEnvironmentId, setNestedSelectedPaths, setNestedGroupName, setNestedScanInProgress, diff --git a/src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts b/src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts index b6b50008f..53d2b3341 100644 --- a/src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts +++ b/src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts @@ -76,6 +76,7 @@ describe('useAddRepoServerPathFlow', () => { const result = useAddRepoServerPathFlow({ addRepoPath: mocks.addRepoPath, + activeRuntimeEnvironmentId: 'box1-environment-id', closeModal: mocks.closeModal, fetchWorktrees: mocks.fetchWorktrees, getNestedRepoRuntimeKind: mocks.getNestedRepoRuntimeKind, @@ -88,11 +89,53 @@ describe('useAddRepoServerPathFlow', () => { }) await result.handleAddServerPath('folder') - expect(mocks.addRepoPath).toHaveBeenCalledWith('/server/docs', 'folder') + expect(mocks.addRepoPath).toHaveBeenCalledWith('/server/docs', 'folder', { + runtimeEnvironmentId: 'box1-environment-id' + }) expect(mocks.scanNestedRepos).not.toHaveBeenCalled() expect(mocks.fetchWorktrees).not.toHaveBeenCalled() expect(mocks.onGitRepoReady).not.toHaveBeenCalled() expect(mocks.markOnboardingProjectAdded).toHaveBeenCalledWith('addedFolder') expect(mocks.closeModal).toHaveBeenCalled() }) + + it('routes the nested Git pre-scan and add through the selected runtime', async () => { + const repo = makeRepo({ id: 'server-git', kind: 'git' }) + mocks.getNestedRepoRuntimeKind.mockReturnValue('runtime') + mocks.scanNestedRepos.mockResolvedValue({ + selectedPath: '/server/docs', + selectedPathKind: 'git_repo', + repos: [] + }) + mocks.addRepoPath.mockResolvedValue(repo) + const { useAddRepoServerPathFlow } = await import('./useAddRepoServerPathFlow') + + const result = useAddRepoServerPathFlow({ + addRepoPath: mocks.addRepoPath, + activeRuntimeEnvironmentId: 'box1-environment-id', + closeModal: mocks.closeModal, + fetchWorktrees: mocks.fetchWorktrees, + getNestedRepoRuntimeKind: mocks.getNestedRepoRuntimeKind, + scanNestedRepos: mocks.scanNestedRepos, + setActiveNestedScanId: mocks.setActiveNestedScanId, + setNestedScanInProgress: mocks.setNestedScanInProgress, + showNestedRepoReview: mocks.showNestedRepoReview, + onGitRepoReady: mocks.onGitRepoReady, + setAddProjectBusyLabel: mocks.setAddProjectBusyLabel + }) + await result.handleAddServerPath('git') + + expect(mocks.scanNestedRepos).toHaveBeenCalledWith( + '/server/docs', + undefined, + expect.objectContaining({ runtimeEnvironmentId: 'box1-environment-id' }) + ) + expect(mocks.addRepoPath).toHaveBeenCalledWith('/server/docs', 'git', { + runtimeEnvironmentId: 'box1-environment-id' + }) + expect(mocks.fetchWorktrees).toHaveBeenCalledWith('server-git', { + requireAuthoritative: true, + executionHostId: 'runtime:box1-environment-id' + }) + }) }) diff --git a/src/renderer/src/components/sidebar/useAddRepoServerPathFlow.ts b/src/renderer/src/components/sidebar/useAddRepoServerPathFlow.ts index 9f2d49dc9..a02bdbcf3 100644 --- a/src/renderer/src/components/sidebar/useAddRepoServerPathFlow.ts +++ b/src/renderer/src/components/sidebar/useAddRepoServerPathFlow.ts @@ -9,7 +9,10 @@ import { } from '../../../../shared/nested-repo-telemetry' import type { AddRepoExistingWorkspaceSource } from '../../../../shared/telemetry-events' import type { NestedRepoScanResult, Repo } from '../../../../shared/types' +import type { WorktreeFetchOptions } from '@/store/slices/worktree-helpers' import { createNestedRepoScanId } from './add-repo-dialog-types' +import { worktreeRefreshOptions } from './add-repo-runtime-owner' +import type { ExecutionHostId } from '../../../../shared/execution-host' type ShowNestedRepoReview = (args: { scan: NestedRepoScanResult @@ -19,10 +22,12 @@ type ShowNestedRepoReview = (args: { runtimeKind: NestedRepoTelemetryRuntimeKind inProgress: boolean scanId: string | null + runtimeEnvironmentId?: string | null }) => void export function useAddRepoServerPathFlow({ addRepoPath, + activeRuntimeEnvironmentId, closeModal, fetchWorktrees, getNestedRepoRuntimeKind, @@ -33,19 +38,32 @@ export function useAddRepoServerPathFlow({ onGitRepoReady, setAddProjectBusyLabel }: { - addRepoPath: (path: string, kind?: 'git' | 'folder') => Promise + addRepoPath: ( + path: string, + kind?: 'git' | 'folder', + options?: { runtimeEnvironmentId?: string | null } + ) => Promise + activeRuntimeEnvironmentId: string | null closeModal: () => void - fetchWorktrees: (repoId: string, options?: { requireAuthoritative?: boolean }) => Promise + fetchWorktrees: (repoId: string, options?: WorktreeFetchOptions) => Promise getNestedRepoRuntimeKind: (connectionId: string | null) => NestedRepoTelemetryRuntimeKind scanNestedRepos: ( path: string, connectionId?: string, - controls?: { scanId?: string; onProgress?: (scan: NestedRepoScanResult) => void } + controls?: { + scanId?: string + onProgress?: (scan: NestedRepoScanResult) => void + runtimeEnvironmentId?: string | null + } ) => Promise - setActiveNestedScanId: (scanId: string | null) => void + setActiveNestedScanId: (scanId: string | null, runtimeEnvironmentId?: string | null) => void setNestedScanInProgress: (inProgress: boolean) => void showNestedRepoReview: ShowNestedRepoReview - onGitRepoReady: (repoId: string, source: AddRepoExistingWorkspaceSource) => Promise + onGitRepoReady: ( + repoId: string, + source: AddRepoExistingWorkspaceSource, + executionHostId?: ExecutionHostId + ) => Promise setAddProjectBusyLabel: (label: string | null) => void }): { serverPath: string @@ -80,16 +98,15 @@ export function useAddRepoServerPathFlow({ const supportsStreamingScan = runtimeKind !== 'runtime' const scanId = supportsStreamingScan ? createNestedRepoScanId() : null if (scanId) { - setActiveNestedScanId(scanId) + setActiveNestedScanId(scanId, activeRuntimeEnvironmentId) setNestedScanInProgress(true) } - const scan = await scanNestedRepos( - path, - undefined, - scanId + const scan = await scanNestedRepos(path, undefined, { + runtimeEnvironmentId: activeRuntimeEnvironmentId, + ...(scanId ? { scanId, - onProgress: (progressScan) => { + onProgress: (progressScan: NestedRepoScanResult) => { if ( gen !== serverAddGenRef.current || progressScan.selectedPathKind !== 'non_git_folder' || @@ -104,12 +121,13 @@ export function useAddRepoServerPathFlow({ attemptId, runtimeKind, inProgress: true, - scanId + scanId, + runtimeEnvironmentId: activeRuntimeEnvironmentId }) } } - : undefined - ) + : {}) + }) if (gen !== serverAddGenRef.current) { return } @@ -132,24 +150,28 @@ export function useAddRepoServerPathFlow({ attemptId, runtimeKind, inProgress: false, - scanId + scanId, + runtimeEnvironmentId: activeRuntimeEnvironmentId }) return } } setAddProjectBusyLabel(kind === 'git' ? 'Opening project...' : 'Opening folder...') - const repo = await addRepoPath(path, kind) + const repo = await addRepoPath(path, kind, { + runtimeEnvironmentId: activeRuntimeEnvironmentId + }) if (gen !== serverAddGenRef.current) { return } if (repo && isGitRepoKind(repo)) { // Why: once the repo exists, a transient non-authoritative refresh // should fall through to project reveal instead of leaving the add flow open. - await fetchWorktrees(repo.id, { requireAuthoritative: true }) + const ownerOptions = worktreeRefreshOptions(activeRuntimeEnvironmentId ?? null) + await fetchWorktrees(repo.id, ownerOptions) if (gen !== serverAddGenRef.current) { return } - await onGitRepoReady(repo.id, 'runtime_server_path') + await onGitRepoReady(repo.id, 'runtime_server_path', ownerOptions.executionHostId) } else if (repo) { // Why: folder repos skip the Git default-checkout handoff; their synthetic // root workspace is opened by the folder add flow. @@ -167,6 +189,7 @@ export function useAddRepoServerPathFlow({ }, [ addRepoPath, + activeRuntimeEnvironmentId, closeModal, fetchWorktrees, getNestedRepoRuntimeKind, diff --git a/src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts b/src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts index 51a5ad755..832ce5b26 100644 --- a/src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts +++ b/src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts @@ -240,13 +240,18 @@ describe('useCreateRepo default-checkout handoff', () => { }) expect(mocks.createRepo).not.toHaveBeenCalled() expect(mocks.fetchWorktrees).toHaveBeenCalledWith(repo.id, { - requireAuthoritative: true + requireAuthoritative: true, + executionHostId: 'ssh:ssh-1' }) - expect(mocks.onGitRepoReady).toHaveBeenCalledWith(repo.id) + expect(mocks.storeState.repos).toContainEqual({ + ...repo, + executionHostId: 'ssh:ssh-1' + }) + expect(mocks.onGitRepoReady).toHaveBeenCalledWith(repo.id, 'ssh:ssh-1') }) it('creates projects through the selected runtime environment', async () => { - const repo = makeRepo({ executionHostId: 'runtime:env-1', path: '/srv/created' }) + const repo = makeRepo({ path: '/srv/created' }) mocks.callRuntimeRpc.mockResolvedValue({ repo }) mocks.fetchWorktrees.mockResolvedValue(true) const { useCreateRepo } = await import('./useCreateRepo') @@ -270,8 +275,13 @@ describe('useCreateRepo default-checkout handoff', () => { expect(mocks.createRepo).not.toHaveBeenCalled() expect(mocks.createRemoteRepo).not.toHaveBeenCalled() expect(mocks.fetchWorktrees).toHaveBeenCalledWith(repo.id, { - requireAuthoritative: true + requireAuthoritative: true, + executionHostId: 'runtime:env-1' }) - expect(mocks.onGitRepoReady).toHaveBeenCalledWith(repo.id) + expect(mocks.storeState.repos).toContainEqual({ + ...repo, + executionHostId: 'runtime:env-1' + }) + expect(mocks.onGitRepoReady).toHaveBeenCalledWith(repo.id, 'runtime:env-1') }) }) diff --git a/src/renderer/src/components/sidebar/useCreateRepo.ts b/src/renderer/src/components/sidebar/useCreateRepo.ts index abf35db7e..a9c6c8c65 100644 --- a/src/renderer/src/components/sidebar/useCreateRepo.ts +++ b/src/renderer/src/components/sidebar/useCreateRepo.ts @@ -12,14 +12,16 @@ import type { Repo } from '../../../../shared/types' import { translate } from '@/i18n/i18n' import { extractIpcErrorMessage } from '@/lib/ipc-error' import { upsertAddedRepoWithProjectHostSetup } from './add-repo-store-upsert' +import { worktreeRefreshOptions } from './add-repo-runtime-owner' +import type { ExecutionHostId } from '../../../../shared/execution-host' export function useCreateRepo( fetchWorktrees: ( repoId: string, - options?: { requireAuthoritative?: boolean } + options?: { requireAuthoritative?: boolean; executionHostId?: ExecutionHostId } ) => Promise, closeModal: () => void, - onGitRepoReady?: (repoId: string) => void | Promise, + onGitRepoReady?: (repoId: string, executionHostId?: ExecutionHostId) => void | Promise, options: { hostId?: string | null runtimeEnvironmentId?: string | null @@ -137,15 +139,17 @@ export function useCreateRepo( setCreateError(result.error) return } - const repo = result.repo - const state = useAppStore.getState() - const existingIdx = state.repos.findIndex((r) => r.id === repo.id) + const { alreadyPresent: wasDeduped, repo } = upsertAddedRepoWithProjectHostSetup( + result.repo, + { + runtimeEnvironmentId: options.runtimeEnvironmentId, + sshConnectionId: options.sshTargetId + } + ) // Why: the IPC handler dedupes by path (see repos:create) and returns - // the existing repo unchanged. If its ID is already in our store, the + // the existing repo unchanged. If its host identity is already in our store, the // handler took the dedup path — no new project was created, so don't // claim one was. - const wasDeduped = existingIdx !== -1 - upsertAddedRepoWithProjectHostSetup(repo) if (wasDeduped) { toast.info( translate( @@ -168,7 +172,11 @@ export function useCreateRepo( // Why: Git repos use the shared default-checkout completion path. // Why: if refresh is temporarily non-authoritative, the shared opener // still reveals the project so the user is not left in a completed add flow. - await fetchWorktrees(repo.id, { requireAuthoritative: true }) + const ownerOptions = worktreeRefreshOptions( + options.runtimeEnvironmentId, + options.sshTargetId + ) + await fetchWorktrees(repo.id, ownerOptions) if ( gen !== createGenRef.current || requestHostToken !== hostTokenRef.current || @@ -176,11 +184,19 @@ export function useCreateRepo( ) { return } - await onGitRepoReady?.(repo.id) + await (ownerOptions.executionHostId + ? onGitRepoReady?.(repo.id, ownerOptions.executionHostId) + : onGitRepoReady?.(repo.id)) } else { // Why: folder repos skip the Git default-checkout handoff, so activate the synthetic // root workspace before closing. Matches addNonGitFolder's behavior. - await fetchWorktrees(repo.id) + const ownerOptions = worktreeRefreshOptions( + options.runtimeEnvironmentId, + options.sshTargetId + ) + await (ownerOptions.executionHostId + ? fetchWorktrees(repo.id, { executionHostId: ownerOptions.executionHostId }) + : fetchWorktrees(repo.id)) if ( gen !== createGenRef.current || requestHostToken !== hostTokenRef.current || @@ -188,9 +204,20 @@ export function useCreateRepo( ) { return } - const folderWorktree = useAppStore.getState().worktreesByRepo[repo.id]?.[0] + const folderWorktree = useAppStore + .getState() + .worktreesByRepo[repo.id]?.find( + (worktree) => + ownerOptions.executionHostId === undefined || + worktree.hostId === ownerOptions.executionHostId + ) if (folderWorktree) { - activateAndRevealWorktree(folderWorktree.id, { sidebarRevealBehavior: 'auto' }) + activateAndRevealWorktree(folderWorktree.id, { + sidebarRevealBehavior: 'auto', + ...(ownerOptions.executionHostId + ? { executionHostId: ownerOptions.executionHostId } + : {}) + }) } await markOnboardingProjectAdded('addedFolder') closeModal() diff --git a/src/renderer/src/components/sidebar/worktree-list-host-filtering.ts b/src/renderer/src/components/sidebar/worktree-list-host-filtering.ts index 302739579..655c4e4f2 100644 --- a/src/renderer/src/components/sidebar/worktree-list-host-filtering.ts +++ b/src/renderer/src/components/sidebar/worktree-list-host-filtering.ts @@ -72,10 +72,14 @@ export function getFolderWorkspaceExecutionHostIdForRows({ projectGroup, defaultHostId }: { - folderWorkspace: Pick + folderWorkspace: Pick projectGroup: Pick | undefined defaultHostId: ExecutionHostId }): ExecutionHostId { + const explicitFolderHostId = normalizeExecutionHostId(folderWorkspace.executionHostId) + if (explicitFolderHostId) { + return explicitFolderHostId + } if (projectGroup) { const explicitProjectGroupHostId = normalizeExecutionHostId(projectGroup.executionHostId) if (explicitProjectGroupHostId) { @@ -132,7 +136,7 @@ export function getFolderPathStatusRouteOptionsForRows({ request.scope === 'project-group' ? getProjectGroupExecutionHostIdForFolderPathStatus(group) : getFolderWorkspaceExecutionHostIdForRows({ - folderWorkspace: folderWorkspace ?? { connectionId: null }, + folderWorkspace: folderWorkspace ?? { connectionId: null, executionHostId: null }, projectGroup: group, defaultHostId: getProjectGroupExecutionHostIdForFolderPathStatus(group) }) diff --git a/src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts b/src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts index 55cb0f286..8b2096844 100644 --- a/src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts +++ b/src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts @@ -1,5 +1,28 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createRuntimeProjectRefreshScheduler } from './runtime-project-refresh-scheduler' +import { + createRuntimeProjectRefreshScheduler, + refreshRuntimeProjectWorktrees +} from './runtime-project-refresh-scheduler' + +describe('refreshRuntimeProjectWorktrees', () => { + it('pins same-ID repo refreshes to the event runtime', async () => { + const fetchWorktrees = vi.fn().mockResolvedValue(true) + + await refreshRuntimeProjectWorktrees( + 'env-1', + [{ id: 'same-repo' }, { id: 'same-repo' }], + fetchWorktrees + ) + + expect(fetchWorktrees).toHaveBeenCalledTimes(2) + expect(fetchWorktrees).toHaveBeenNthCalledWith(1, 'same-repo', { + executionHostId: 'runtime:env-1' + }) + expect(fetchWorktrees).toHaveBeenNthCalledWith(2, 'same-repo', { + executionHostId: 'runtime:env-1' + }) + }) +}) describe('createRuntimeProjectRefreshScheduler', () => { beforeEach(() => { diff --git a/src/renderer/src/hooks/runtime-project-refresh-scheduler.ts b/src/renderer/src/hooks/runtime-project-refresh-scheduler.ts index 46bf35466..e02305d20 100644 --- a/src/renderer/src/hooks/runtime-project-refresh-scheduler.ts +++ b/src/renderer/src/hooks/runtime-project-refresh-scheduler.ts @@ -1,3 +1,5 @@ +import { toRuntimeExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' + export type RuntimeProjectRefreshSchedulerDeps = { refresh: (environmentId: string) => Promise debounceMs?: number @@ -20,6 +22,46 @@ type RefreshEntry = { const DEFAULT_DEBOUNCE_MS = 250 const DEFAULT_MIN_INTERVAL_MS = 5_000 +const DEFAULT_REFRESH_CONCURRENCY = 5 + +export async function refreshRuntimeProjectWorktrees( + environmentId: string, + repos: readonly { id: string }[], + fetchWorktrees: ( + repoId: string, + options: { executionHostId: ExecutionHostId } + ) => Promise, + concurrency = DEFAULT_REFRESH_CONCURRENCY +): Promise { + let nextIndex = 0 + const failures: { repoId: string; error: unknown }[] = [] + const workerCount = Math.min(concurrency, repos.length) + const executionHostId = toRuntimeExecutionHostId(environmentId) + + // Why: one coalesced event can represent many repos; bound probes without dropping host identity. + await Promise.all( + Array.from({ length: workerCount }, async () => { + while (nextIndex < repos.length) { + const index = nextIndex + nextIndex += 1 + const repoId = repos[index].id + try { + await fetchWorktrees(repoId, { executionHostId }) + } catch (error) { + failures.push({ repoId, error }) + } + } + }) + ) + if (failures.length > 0) { + throw new AggregateError( + failures.map((failure) => failure.error), + `Failed to refresh ${failures.length} runtime project worktree(s): ${failures + .map((failure) => failure.repoId) + .join(', ')}` + ) + } +} export function createRuntimeProjectRefreshScheduler( deps: RuntimeProjectRefreshSchedulerDeps diff --git a/src/renderer/src/hooks/useIpcEvents.test.ts b/src/renderer/src/hooks/useIpcEvents.test.ts index cfc4bd5d8..1d956f716 100644 --- a/src/renderer/src/hooks/useIpcEvents.test.ts +++ b/src/renderer/src/hooks/useIpcEvents.test.ts @@ -4904,7 +4904,7 @@ describe('useIpcEvents CLI-created worktree activation', () => { fetchWorktrees.mockClear() fetchWorktreeLineage.mockClear() - mockSettings.activeRuntimeEnvironmentId = 'env-1' + mockSettings.activeRuntimeEnvironmentId = null if (!runtimeOnResponse) { throw new Error('Expected runtime client event callbacks') } @@ -4915,8 +4915,12 @@ describe('useIpcEvents CLI-created worktree activation', () => { await new Promise((resolve) => setTimeout(resolve, 0)) await new Promise((resolve) => setTimeout(resolve, 0)) - expect(fetchWorktrees).toHaveBeenCalledWith('repo-1', undefined) - expect(fetchWorktreeLineage).toHaveBeenCalledWith(undefined) + expect(fetchWorktrees).toHaveBeenCalledWith('repo-1', { + executionHostId: 'runtime:env-1' + }) + expect(fetchWorktreeLineage).toHaveBeenCalledWith({ + executionHostId: 'runtime:env-1' + }) }) }) diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index ba500554a..3c8b19068 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -31,7 +31,11 @@ import type { } from '../../../shared/types' import type { RateLimitState } from '../../../shared/rate-limit-types' import type { DirectSshAuthority, SshConnectionState } from '../../../shared/ssh-types' -import { toSshExecutionHostId } from '../../../shared/execution-host' +import { + toRuntimeExecutionHostId, + toSshExecutionHostId, + type ExecutionHostId +} from '../../../shared/execution-host' import { isWslHookRelayConnectionId } from '../../../shared/wsl-hook-relay-contract' import type { RuntimeBrowserDriverState, @@ -96,7 +100,10 @@ import { applyRuntimeEnvironmentSshStateChanged, hydrateRuntimeEnvironmentSshState } from '@/runtime/runtime-environment-ssh-state' -import { createRuntimeProjectRefreshScheduler } from './runtime-project-refresh-scheduler' +import { + createRuntimeProjectRefreshScheduler, + refreshRuntimeProjectWorktrees +} from './runtime-project-refresh-scheduler' import { createRuntimeClientEventsSync } from './runtime-client-events-sync' import { detectLanguage } from '@/lib/language-detect' import { makePaneKey, parsePaneKey } from '../../../shared/stable-pane-id' @@ -184,7 +191,6 @@ function getShortcutPlatform(): NodeJS.Platform { } const BROWSER_AUTOMATION_BOOTSTRAP_LEASE_MS = 10_000 -const RUNTIME_PROJECT_REFRESH_CONCURRENCY = 5 const browserAutomationBootstrapLeaseByPageId = new Map() function resolveTerminalPresentation(data: { @@ -588,36 +594,6 @@ export function getRuntimeProjectRefreshEnvironmentIds(args: { ] } -async function refreshRuntimeProjectWorktrees(repos: readonly { id: string }[]): Promise { - let nextIndex = 0 - const failures: { repoId: string; error: unknown }[] = [] - const workerCount = Math.min(RUNTIME_PROJECT_REFRESH_CONCURRENCY, repos.length) - - // Why: one coalesced repo event can represent many repos; bound the probes so idle refresh never floods the renderer. - await Promise.all( - Array.from({ length: workerCount }, async () => { - while (nextIndex < repos.length) { - const index = nextIndex - nextIndex += 1 - const repoId = repos[index].id - try { - await useAppStore.getState().fetchWorktrees(repoId) - } catch (error) { - failures.push({ repoId, error }) - } - } - }) - ) - if (failures.length > 0) { - throw new AggregateError( - failures.map((failure) => failure.error), - `Failed to refresh ${failures.length} runtime project worktree(s): ${failures - .map((failure) => failure.repoId) - .join(', ')}` - ) - } -} - function getWorktreeRuntimeEnvironmentId(worktreeId: string | null | undefined): string | null { return getRuntimeEnvironmentIdForWorktree(useAppStore.getState(), worktreeId) } @@ -788,7 +764,7 @@ export function useIpcEvents(): void { const handleWorktreesChanged = async ( repoId: string, renamed?: { oldWorktreeId: string; newWorktreeId: string }, - options?: { forceLocalOwner?: boolean } + options?: { forceLocalOwner?: boolean; executionHostId?: ExecutionHostId } ): Promise => { const localRefreshStartedWithRuntime = options?.forceLocalOwner === true && isRuntimeEnvironmentActive() @@ -809,11 +785,21 @@ export function useIpcEvents(): void { getVisibleWorktreeIdsForRepo(state, repoId) await state.fetchWorktrees( repoId, - options?.forceLocalOwner ? { forceLocalOwner: true } : undefined + options?.forceLocalOwner + ? { forceLocalOwner: true } + : options?.executionHostId + ? { executionHostId: options.executionHostId } + : undefined ) await useAppStore .getState() - .fetchWorktreeLineage(options?.forceLocalOwner ? { forceLocalOwner: true } : undefined) + .fetchWorktreeLineage( + options?.forceLocalOwner + ? { forceLocalOwner: true } + : options?.executionHostId + ? { executionHostId: options.executionHostId } + : undefined + ) // Why: an id change unmounts the active pane; re-activate so the tab reconciles, else it vanishes until re-select. if (renamedWasActive && renamed) { useAppStore.getState().setActiveWorktree(renamed.newWorktreeId) @@ -909,8 +895,12 @@ export function useIpcEvents(): void { // Why: refresh the env's SSH bucket on (re)connect so a pre-drop snapshot can't keep a reconnect overlay stale. void hydrateRuntimeEnvironmentSshState(environmentId, { force: true }).catch(() => {}) const repos = await useAppStore.getState().fetchRuntimeEnvironmentRepos(environmentId) - await refreshRuntimeProjectWorktrees(repos) - await useAppStore.getState().fetchWorktreeLineage() + await refreshRuntimeProjectWorktrees(environmentId, repos, (repoId, options) => + useAppStore.getState().fetchWorktrees(repoId, options) + ) + await useAppStore.getState().fetchWorktreeLineage({ + executionHostId: toRuntimeExecutionHostId(environmentId) + }) }, onError: (error) => { console.error('Failed to refresh runtime projects:', error) @@ -956,7 +946,10 @@ export function useIpcEvents(): void { } if (event.type === 'worktreesChanged') { void ensureRuntimeEventRepoKnown(environmentId, event.repoId).then(() => - worktreeChangeRefreshQueue.enqueue({ repoId: event.repoId }) + worktreeChangeRefreshQueue.enqueue({ + repoId: event.repoId, + executionHostId: toRuntimeExecutionHostId(environmentId) + }) ) return } diff --git a/src/renderer/src/hooks/worktree-change-refresh-queue.test.ts b/src/renderer/src/hooks/worktree-change-refresh-queue.test.ts index 7c04b18cf..c04225859 100644 --- a/src/renderer/src/hooks/worktree-change-refresh-queue.test.ts +++ b/src/renderer/src/hooks/worktree-change-refresh-queue.test.ts @@ -173,6 +173,29 @@ describe('createWorktreeChangeRefreshQueue', () => { expect(handler).toHaveBeenNthCalledWith(3, 'repo-1', undefined, { forceLocalOwner: true }) }) + it('does not coalesce same-ID refreshes from different runtime hosts', async () => { + const firstRefresh = deferred() + const handler = vi.fn().mockReturnValueOnce(firstRefresh.promise).mockResolvedValue(undefined) + const queue = createWorktreeChangeRefreshQueue(handler) + + queue.enqueue({ repoId: 'same-repo', executionHostId: 'runtime:env-1' }) + queue.enqueue({ repoId: 'same-repo', executionHostId: 'runtime:env-1' }) + queue.enqueue({ repoId: 'same-repo', executionHostId: 'runtime:env-2' }) + + firstRefresh.resolve() + await flushPromises() + + expect(handler).toHaveBeenCalledTimes(3) + expect(handler).toHaveBeenNthCalledWith(2, 'same-repo', undefined, { + forceLocalOwner: undefined, + executionHostId: 'runtime:env-1' + }) + expect(handler).toHaveBeenNthCalledWith(3, 'same-repo', undefined, { + forceLocalOwner: undefined, + executionHostId: 'runtime:env-2' + }) + }) + it('drops queued trailing refreshes after disposal', async () => { const firstRefresh = deferred() const handler = vi.fn().mockReturnValueOnce(firstRefresh.promise).mockResolvedValue(undefined) diff --git a/src/renderer/src/hooks/worktree-change-refresh-queue.ts b/src/renderer/src/hooks/worktree-change-refresh-queue.ts index ef69da6dd..b3ff2b586 100644 --- a/src/renderer/src/hooks/worktree-change-refresh-queue.ts +++ b/src/renderer/src/hooks/worktree-change-refresh-queue.ts @@ -1,26 +1,31 @@ +import type { ExecutionHostId } from '../../../shared/execution-host' + type WorktreeRename = { oldWorktreeId: string newWorktreeId: string } +type WorktreeChangeOwner = { + forceLocalOwner?: boolean + executionHostId?: ExecutionHostId +} + type WorktreeChangeEvent = { repoId: string renamed?: WorktreeRename // Why: set on local worktrees:changed while a remote runtime is active, so the // refresh pins to the local host instead of dropping the event (see useIpcEvents). forceLocalOwner?: boolean + executionHostId?: ExecutionHostId } type WorktreeChangeRefreshHandler = ( repoId: string, renamed?: WorktreeRename, - options?: { forceLocalOwner?: boolean } + options?: WorktreeChangeOwner ) => Promise -type QueuedWorktreeChange = { - renamed?: WorktreeRename - forceLocalOwner?: boolean -} +type QueuedWorktreeChange = WorktreeChangeOwner & { renamed?: WorktreeRename } type RepoRefreshState = { running: boolean @@ -44,7 +49,10 @@ export function createWorktreeChangeRefreshQueue( while (!disposed && state.queue.length > 0) { const next = state.queue.shift() try { - await handler(repoId, next?.renamed, { forceLocalOwner: next?.forceLocalOwner }) + await handler(repoId, next?.renamed, { + forceLocalOwner: next?.forceLocalOwner, + ...(next?.executionHostId ? { executionHostId: next.executionHostId } : {}) + }) } catch (error) { console.error('Failed to refresh changed worktrees:', error) } @@ -76,7 +84,11 @@ export function createWorktreeChangeRefreshQueue( } if (event.renamed) { - state.queue.push({ renamed: event.renamed, forceLocalOwner: event.forceLocalOwner }) + state.queue.push({ + renamed: event.renamed, + forceLocalOwner: event.forceLocalOwner, + executionHostId: event.executionHostId + }) } else { const lastQueued = state.queue.at(-1) // Why: Windows/OneDrive can emit a burst for one checkout change. Keep a @@ -86,9 +98,13 @@ export function createWorktreeChangeRefreshQueue( if ( !lastQueued || lastQueued.renamed !== undefined || - Boolean(lastQueued.forceLocalOwner) !== Boolean(event.forceLocalOwner) + Boolean(lastQueued.forceLocalOwner) !== Boolean(event.forceLocalOwner) || + lastQueued.executionHostId !== event.executionHostId ) { - state.queue.push({ forceLocalOwner: event.forceLocalOwner }) + state.queue.push({ + forceLocalOwner: event.forceLocalOwner, + executionHostId: event.executionHostId + }) } } diff --git a/src/renderer/src/lib/ai-vault-resume-target.ts b/src/renderer/src/lib/ai-vault-resume-target.ts index 3c9206ae3..fca20f25c 100644 --- a/src/renderer/src/lib/ai-vault-resume-target.ts +++ b/src/renderer/src/lib/ai-vault-resume-target.ts @@ -178,7 +178,7 @@ function getAiVaultResumeFolderTargetStatus( } const group = state.projectGroups.find((entry) => entry.id === workspace.projectGroupId) - const groupHostId = normalizeExecutionHostId(group?.executionHostId) + const groupHostId = normalizeExecutionHostId(workspace.executionHostId ?? group?.executionHostId) if (groupHostId) { return getAiVaultResumeExecutionHostTargetStatus(groupHostId) } @@ -202,7 +202,7 @@ function getAiVaultResumeFolderExecutionHostId( } const group = state.projectGroups.find((entry) => entry.id === workspace.projectGroupId) - const groupHostId = normalizeExecutionHostId(group?.executionHostId) + const groupHostId = normalizeExecutionHostId(workspace.executionHostId ?? group?.executionHostId) if (groupHostId) { return groupHostId } diff --git a/src/renderer/src/lib/direct-ssh-target-scope-types.ts b/src/renderer/src/lib/direct-ssh-target-scope-types.ts index e063a64c4..1c12e0a25 100644 --- a/src/renderer/src/lib/direct-ssh-target-scope-types.ts +++ b/src/renderer/src/lib/direct-ssh-target-scope-types.ts @@ -31,7 +31,7 @@ export type DirectSshWorktreeOwner = Pick< > export type DirectSshFolderOwner = Pick< FolderWorkspace, - 'id' | 'projectGroupId' | 'folderPath' | 'connectionId' + 'id' | 'projectGroupId' | 'folderPath' | 'connectionId' | 'executionHostId' > export type DirectSshGroupOwner = Pick< ProjectGroup, diff --git a/src/renderer/src/lib/folder-workspace-connection.ts b/src/renderer/src/lib/folder-workspace-connection.ts index 6b74c701f..4afb696d7 100644 --- a/src/renderer/src/lib/folder-workspace-connection.ts +++ b/src/renderer/src/lib/folder-workspace-connection.ts @@ -1,6 +1,7 @@ import type { FolderWorkspace, ProjectGroup, Repo } from '../../../shared/types' import { isPathInsideOrEqual } from '../../../shared/cross-platform-path' import { getProjectGroupSubtreeIds } from '../../../shared/project-groups' +import { parseExecutionHostId } from '../../../shared/execution-host' export type FolderWorkspaceConnectionState = { folderWorkspaces: FolderWorkspace[] @@ -66,6 +67,10 @@ export function getFolderWorkspaceConnectionId( if (!workspace) { return undefined } + const explicitHost = parseExecutionHostId(workspace.executionHostId) + if (explicitHost) { + return explicitHost.kind === 'ssh' ? explicitHost.targetId : null + } const scopeConnectionId = workspace.connectionId ?? state.projectGroups.find((entry) => entry.id === workspace.projectGroupId)?.connectionId ?? diff --git a/src/renderer/src/lib/folder-workspace-runtime-owner.ts b/src/renderer/src/lib/folder-workspace-runtime-owner.ts index eaa36c44e..4bf99a1b7 100644 --- a/src/renderer/src/lib/folder-workspace-runtime-owner.ts +++ b/src/renderer/src/lib/folder-workspace-runtime-owner.ts @@ -14,27 +14,60 @@ import { type RuntimeExecutionHost = Extract export type FolderWorkspaceRuntimeOwnerState = SingleRuntimeLegacyOwnerState & { - folderWorkspaces?: readonly Pick[] + folderWorkspaces?: readonly Pick< + FolderWorkspace, + 'id' | 'projectGroupId' | 'connectionId' | 'executionHostId' + >[] projectGroups?: readonly Pick[] restoredRuntimeHostIdByWorkspaceSessionKey?: Record + activeWorktreeId?: string | null + activeWorkspaceExecutionHostId?: ExecutionHostId | null +} + +function getPreferredFolderExecutionHostId( + state: FolderWorkspaceRuntimeOwnerState, + folderWorkspaceId: string, + executionHostId?: ExecutionHostId +): ExecutionHostId | undefined { + if (executionHostId) { + return executionHostId + } + return state.activeWorktreeId === folderWorkspaceKey(folderWorkspaceId) + ? (state.activeWorkspaceExecutionHostId ?? undefined) + : undefined } export function findFolderWorkspaceOwner( state: FolderWorkspaceRuntimeOwnerState, - folderWorkspaceId: string -): Pick | null { - return findIndexedFolderWorkspaceOwner(state.folderWorkspaces, folderWorkspaceId) + folderWorkspaceId: string, + executionHostId?: ExecutionHostId +): Pick | null { + return findIndexedFolderWorkspaceOwner( + state.folderWorkspaces, + folderWorkspaceId, + getPreferredFolderExecutionHostId(state, folderWorkspaceId, executionHostId) + ) } function findFolderProjectGroup( state: FolderWorkspaceRuntimeOwnerState, - folderWorkspaceId: string + folderWorkspaceId: string, + executionHostId?: ExecutionHostId ): Pick | null { - const folderWorkspace = findFolderWorkspaceOwner(state, folderWorkspaceId) + const preferredHostId = getPreferredFolderExecutionHostId( + state, + folderWorkspaceId, + executionHostId + ) + const folderWorkspace = findFolderWorkspaceOwner(state, folderWorkspaceId, preferredHostId) if (!folderWorkspace) { return null } - return findIndexedProjectGroupOwner(state.projectGroups, folderWorkspace.projectGroupId) + return findIndexedProjectGroupOwner( + state.projectGroups, + folderWorkspace.projectGroupId, + preferredHostId + ) } function getRestoredRuntimeHostForFolderWorkspace( @@ -52,11 +85,14 @@ function getRestoredRuntimeHostForFolderWorkspace( export function getRuntimeEnvironmentIdForFolderWorkspace( state: FolderWorkspaceRuntimeOwnerState, - folderWorkspaceId: string + folderWorkspaceId: string, + executionHostId?: ExecutionHostId ): string | null { - const folderWorkspace = findFolderWorkspaceOwner(state, folderWorkspaceId) - const projectGroup = findFolderProjectGroup(state, folderWorkspaceId) - const parsed = parseExecutionHostId(projectGroup?.executionHostId) + const folderWorkspace = findFolderWorkspaceOwner(state, folderWorkspaceId, executionHostId) + const projectGroup = findFolderProjectGroup(state, folderWorkspaceId, executionHostId) + const parsed = parseExecutionHostId( + folderWorkspace?.executionHostId ?? projectGroup?.executionHostId + ) if (parsed?.kind === 'runtime') { return parsed.environmentId } @@ -77,11 +113,14 @@ export function getRuntimeEnvironmentIdForFolderWorkspace( export function getExplicitRuntimeEnvironmentIdForFolderWorkspace( state: FolderWorkspaceRuntimeOwnerState, - folderWorkspaceId: string + folderWorkspaceId: string, + executionHostId?: ExecutionHostId ): string | null { - const folderWorkspace = findFolderWorkspaceOwner(state, folderWorkspaceId) - const projectGroup = findFolderProjectGroup(state, folderWorkspaceId) - const parsed = parseExecutionHostId(projectGroup?.executionHostId) + const folderWorkspace = findFolderWorkspaceOwner(state, folderWorkspaceId, executionHostId) + const projectGroup = findFolderProjectGroup(state, folderWorkspaceId, executionHostId) + const parsed = parseExecutionHostId( + folderWorkspace?.executionHostId ?? projectGroup?.executionHostId + ) if (parsed) { return parsed.kind === 'runtime' ? parsed.environmentId : null } @@ -93,11 +132,19 @@ export function getExplicitRuntimeEnvironmentIdForFolderWorkspace( export function getExecutionHostIdForFolderWorkspace( state: FolderWorkspaceRuntimeOwnerState, - folderWorkspaceId: string + folderWorkspaceId: string, + executionHostId?: ExecutionHostId ): ExecutionHostId { - const folderWorkspace = findFolderWorkspaceOwner(state, folderWorkspaceId) - const projectGroup = findFolderProjectGroup(state, folderWorkspaceId) - const parsed = parseExecutionHostId(projectGroup?.executionHostId) + const preferredHostId = getPreferredFolderExecutionHostId( + state, + folderWorkspaceId, + executionHostId + ) + const folderWorkspace = findFolderWorkspaceOwner(state, folderWorkspaceId, preferredHostId) + const projectGroup = findFolderProjectGroup(state, folderWorkspaceId, preferredHostId) + const parsed = parseExecutionHostId( + folderWorkspace?.executionHostId ?? projectGroup?.executionHostId + ) if (parsed) { return parsed.id } @@ -105,6 +152,9 @@ export function getExecutionHostIdForFolderWorkspace( if (connectionId) { return toSshExecutionHostId(connectionId) } + if (preferredHostId && folderWorkspace) { + return preferredHostId + } const restoredRuntimeHost = getRestoredRuntimeHostForFolderWorkspace(state, folderWorkspaceId) if (restoredRuntimeHost) { return restoredRuntimeHost.id diff --git a/src/renderer/src/lib/resolved-worktree-execution-host.test.ts b/src/renderer/src/lib/resolved-worktree-execution-host.test.ts index fab9ccbf7..12b15d63a 100644 --- a/src/renderer/src/lib/resolved-worktree-execution-host.test.ts +++ b/src/renderer/src/lib/resolved-worktree-execution-host.test.ts @@ -56,4 +56,25 @@ describe('getResolvedExecutionHostIdForWorktree', () => { ) ).toBe('runtime:runtime-1') }) + + it('uses the folder host stamp when same-ID project groups exist on different hosts', () => { + expect( + getResolvedExecutionHostIdForWorktree( + { + folderWorkspaces: [ + { + id: 'same-folder', + projectGroupId: 'same-group', + executionHostId: 'runtime:runtime-1' + } + ], + projectGroups: [ + { id: 'same-group', executionHostId: 'local' }, + { id: 'same-group', executionHostId: 'runtime:runtime-1' } + ] + }, + 'folder:same-folder' + ) + ).toBe('runtime:runtime-1') + }) }) diff --git a/src/renderer/src/lib/resolved-worktree-execution-host.ts b/src/renderer/src/lib/resolved-worktree-execution-host.ts index df86e8f47..8052ccec6 100644 --- a/src/renderer/src/lib/resolved-worktree-execution-host.ts +++ b/src/renderer/src/lib/resolved-worktree-execution-host.ts @@ -10,7 +10,9 @@ import { findIndexedFolderWorkspaceOwner, findIndexedProjectGroupOwner, findIndexedRepoOwner, - findIndexedWorktreeOwner + findIndexedRepoOwnerForHost, + findIndexedWorktreeOwner, + findIndexedWorktreeOwnerForHost } from './worktree-runtime-owner-index' import type { WorktreeRuntimeOwnerState } from './worktree-runtime-owner' @@ -18,11 +20,19 @@ function getResolvedFolderHost( state: WorktreeRuntimeOwnerState, folderWorkspaceId: string ): ExecutionHostId | null { - const folder = findIndexedFolderWorkspaceOwner(state.folderWorkspaces, folderWorkspaceId) + const preferredHostId = + state.activeWorktreeId === folderWorkspaceKey(folderWorkspaceId) + ? (state.activeWorkspaceExecutionHostId ?? undefined) + : undefined + const folder = findIndexedFolderWorkspaceOwner( + state.folderWorkspaces, + folderWorkspaceId, + preferredHostId + ) const group = folder - ? findIndexedProjectGroupOwner(state.projectGroups, folder.projectGroupId) + ? findIndexedProjectGroupOwner(state.projectGroups, folder.projectGroupId, preferredHostId) : null - const explicitHost = parseExecutionHostId(group?.executionHostId) + const explicitHost = parseExecutionHostId(folder?.executionHostId ?? group?.executionHostId) if (explicitHost) { return explicitHost.id } @@ -36,7 +46,7 @@ function getResolvedFolderHost( if (restoredHost?.kind === 'runtime') { return restoredHost.id } - return folder && group ? LOCAL_EXECUTION_HOST_ID : null + return folder && (group || preferredHostId) ? (preferredHostId ?? LOCAL_EXECUTION_HOST_ID) : null } /** @@ -57,7 +67,13 @@ export function getResolvedExecutionHostIdForWorktree( if (scope?.type === 'folder') { return getResolvedFolderHost(state, scope.folderWorkspaceId) } - const worktree = findIndexedWorktreeOwner(state.worktreesByRepo, worktreeId) + const preferredHostId = + state.activeWorktreeId === worktreeId + ? (state.activeWorkspaceExecutionHostId ?? undefined) + : undefined + const worktree = preferredHostId + ? findIndexedWorktreeOwnerForHost(state.worktreesByRepo, worktreeId, preferredHostId) + : findIndexedWorktreeOwner(state.worktreesByRepo, worktreeId) const worktreeHost = parseExecutionHostId(worktree?.hostId) if (worktreeHost) { return worktreeHost.id @@ -65,7 +81,9 @@ export function getResolvedExecutionHostIdForWorktree( if (!worktree) { return null } - const repo = findIndexedRepoOwner(state.repos, worktree.repoId) + const repo = preferredHostId + ? findIndexedRepoOwnerForHost(state.repos, worktree.repoId, preferredHostId) + : findIndexedRepoOwner(state.repos, worktree.repoId) if (!repo) { return null } diff --git a/src/renderer/src/lib/sidebar-worktree-activation.ts b/src/renderer/src/lib/sidebar-worktree-activation.ts index a668909fe..664895013 100644 --- a/src/renderer/src/lib/sidebar-worktree-activation.ts +++ b/src/renderer/src/lib/sidebar-worktree-activation.ts @@ -5,11 +5,21 @@ import { import { parseWorkspaceKey } from '../../../shared/workspace-scope' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' +import type { ExecutionHostId } from '../../../shared/execution-host' -export async function activateWorktreeFromSidebar(worktreeId: string): Promise { +export async function activateWorktreeFromSidebar( + worktreeId: string, + executionHostId?: ExecutionHostId +): Promise { const workspaceScope = parseWorkspaceKey(worktreeId) if (workspaceScope?.type === 'folder') { - activateAndRevealFolderWorkspace(workspaceScope.folderWorkspaceId) + if (executionHostId) { + activateAndRevealFolderWorkspace(workspaceScope.folderWorkspaceId, { + executionHostId + }) + } else { + activateAndRevealFolderWorkspace(workspaceScope.folderWorkspaceId) + } return } @@ -37,5 +47,8 @@ export async function activateWorktreeFromSidebar(worktreeId: string): Promise[] projectGroups?: readonly { id: string; executionHostId?: string | null }[] - folderWorkspaces?: readonly { id: string; projectGroupId: string }[] + folderWorkspaces?: readonly { + id: string + projectGroupId: string + executionHostId?: ExecutionHostId | null + }[] worktreesByRepo: Record restoredRuntimeHostIdByWorkspaceSessionKey?: Record } @@ -145,7 +149,7 @@ function getFolderWorkspaceRuntimeHostId( const group = workspace ? state.projectGroups?.find((entry) => entry.id === workspace.projectGroupId) : null - const parsed = parseExecutionHostId(group?.executionHostId) + const parsed = parseExecutionHostId(workspace?.executionHostId ?? group?.executionHostId) if (parsed) { return parsed.kind === 'runtime' ? parsed.id : LOCAL_EXECUTION_HOST_ID } diff --git a/src/renderer/src/lib/workspace-session-relevant-fields.test.ts b/src/renderer/src/lib/workspace-session-relevant-fields.test.ts index 84b874a09..0a15b8207 100644 --- a/src/renderer/src/lib/workspace-session-relevant-fields.test.ts +++ b/src/renderer/src/lib/workspace-session-relevant-fields.test.ts @@ -7,6 +7,7 @@ describe('SESSION_RELEVANT_FIELDS', () => { const fixture: Record = { activeRepoId: true, activeWorkspaceKey: true, + activeWorkspaceExecutionHostId: true, activeWorktreeId: true, activeTabId: true, tabsByWorktree: true, diff --git a/src/renderer/src/lib/workspace-session.ts b/src/renderer/src/lib/workspace-session.ts index 1324a8891..cfe1bbf30 100644 --- a/src/renderer/src/lib/workspace-session.ts +++ b/src/renderer/src/lib/workspace-session.ts @@ -53,6 +53,7 @@ export type WorkspaceSessionSnapshot = Pick< | 'lastVisitedAtByWorktreeId' | 'defaultTerminalTabsAppliedByWorktreeId' > & { + activeWorkspaceExecutionHostId?: AppState['activeWorkspaceExecutionHostId'] sleepingAgentSessionsByPaneKey?: AppState['sleepingAgentSessionsByPaneKey'] } @@ -60,6 +61,7 @@ export type WorkspaceSessionSnapshot = Pick< export const SESSION_RELEVANT_FIELDS = [ 'activeRepoId', 'activeWorkspaceKey', + 'activeWorkspaceExecutionHostId', 'activeWorktreeId', 'activeTabId', 'tabsByWorktree', @@ -92,8 +94,7 @@ type _MissingSessionField = Exclude< keyof WorkspaceSessionSnapshot, (typeof SESSION_RELEVANT_FIELDS)[number] > -const _exhaustive: [_MissingSessionField] extends [never] ? true : never = true -void _exhaustive +void (true satisfies [_MissingSessionField] extends [never] ? true : never) /** Build the editor-file portion of the workspace session for persistence. * Only edit-mode files are saved — diffs and conflict views are transient. */ @@ -298,6 +299,7 @@ export function buildWorkspaceSessionPayload( const payload = { activeRepoId: snapshot.activeRepoId, activeWorkspaceKey: snapshot.activeWorkspaceKey, + activeWorkspaceExecutionHostId: snapshot.activeWorkspaceExecutionHostId, activeWorktreeId: snapshot.activeWorktreeId, activeTabId: snapshot.activeTabId, tabsByWorktree: buildSanitizedTabsByWorktree(snapshot.tabsByWorktree), diff --git a/src/renderer/src/lib/worktree-activation.ts b/src/renderer/src/lib/worktree-activation.ts index e2a268f1c..0be0503c9 100644 --- a/src/renderer/src/lib/worktree-activation.ts +++ b/src/renderer/src/lib/worktree-activation.ts @@ -56,6 +56,8 @@ import { isDetachedHeadWorkspace } from '@/components/sidebar/visible-worktrees' import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability' import { seedNativeChatAppliedSessionOptions } from '@/components/native-chat/native-chat-session-option-cache' import type { SessionOptionValue } from '../../../shared/native-chat-session-options' +import type { ExecutionHostId } from '../../../shared/execution-host' +import { findFolderWorkspaceOwner } from './folder-workspace-runtime-owner' /** Telemetry threaded from the launch site to `pty:spawn`; main fires `agent_started` * only after the spawn succeeds. See telemetry-plan.md§Agent launch semantics. */ @@ -195,11 +197,17 @@ export function activateAndRevealFolderWorkspace( sidebarRevealBehavior?: PendingSidebarWorktreeReveal['behavior'] startup?: WorktreeStartupPayload runtimeEnvironmentId?: string | null + executionHostId?: ExecutionHostId } ): ActivateAndRevealResult | false { const state = useAppStore.getState() + const folderWorkspaceOwner = findFolderWorkspaceOwner( + state, + folderWorkspaceId, + opts?.executionHostId + ) const folderWorkspace = state.folderWorkspaces.find( - (workspace) => workspace.id === folderWorkspaceId + (workspace) => workspace === folderWorkspaceOwner ) if (!folderWorkspace) { return false @@ -226,7 +234,7 @@ export function activateAndRevealFolderWorkspace( state.setActiveView('terminal') } - state.setActiveFolderWorkspace(folderWorkspaceId) + state.setActiveFolderWorkspace(folderWorkspaceId, opts?.executionHostId) const workspaceKey = folderWorkspaceKey(folderWorkspaceId) state.markWorktreeVisited(workspaceKey) @@ -256,10 +264,11 @@ export function activateAndRevealWorktree( sidebarRevealBehavior?: PendingSidebarWorktreeReveal['behavior'] notifyHostRuntime?: boolean revealInSidebar?: boolean + executionHostId?: ExecutionHostId } ): ActivateAndRevealResult | false { const state = useAppStore.getState() - const wt = state.getKnownWorktreeById(worktreeId) + const wt = state.getKnownWorktreeById(worktreeId, opts?.executionHostId) if (!wt) { return false } @@ -271,6 +280,7 @@ export function activateAndRevealWorktree( !hasActivationWork && state.activeRepoId === wt.repoId && state.activeWorktreeId === worktreeId && + state.activeWorkspaceExecutionHostId === (opts?.executionHostId ?? null) && state.activeView === 'terminal' // 1. Set activeRepoId if crossing repos @@ -284,7 +294,7 @@ export function activateAndRevealWorktree( } // 3. Core activation: setActiveWorktree also restores per-worktree state, clears unread, bumps dead PTY generations, refreshes GitHub - state.setActiveWorktree(worktreeId) + state.setActiveWorktree(worktreeId, opts?.executionHostId) const postActivationState = useAppStore.getState() const ownerRuntimeEnvironmentId = getRuntimeEnvironmentIdForWorktree(postActivationState, wt.id) if (opts?.notifyHostRuntime !== false && isWebRuntimeSessionActive(ownerRuntimeEnvironmentId)) { diff --git a/src/renderer/src/lib/worktree-operation-route.ts b/src/renderer/src/lib/worktree-operation-route.ts index 04468c5e9..c2281b28a 100644 --- a/src/renderer/src/lib/worktree-operation-route.ts +++ b/src/renderer/src/lib/worktree-operation-route.ts @@ -134,6 +134,19 @@ export function resolveWorktreeOperationRouteResult( state: WorktreeOperationRouteState, worktreeId: string ): WorktreeOperationRouteResolution { + const activeHost = + state.activeWorktreeId === worktreeId + ? parseExecutionHostId(state.activeWorkspaceExecutionHostId) + : null + if (activeHost) { + return { + kind: 'resolved', + route: { + executionHostId: activeHost.id, + runtimeEnvironmentId: activeHost.kind === 'runtime' ? activeHost.environmentId : null + } + } + } // Why: folder workspaces are not Git worktrees — they never appear in the worktree/repo // catalogs scanned below, so without this branch a plain local folder workspace reads as an // unresolved cross-host identity and every owner-routed operation fails closed (#10251). diff --git a/src/renderer/src/lib/worktree-runtime-owner-index.ts b/src/renderer/src/lib/worktree-runtime-owner-index.ts index 6e9a4a6f1..c9d2afbc4 100644 --- a/src/renderer/src/lib/worktree-runtime-owner-index.ts +++ b/src/renderer/src/lib/worktree-runtime-owner-index.ts @@ -1,8 +1,18 @@ import type { FolderWorkspace, ProjectGroup, Repo, Worktree } from '../../../shared/types' +import { + getRepoExecutionHostId, + parseExecutionHostId, + toRuntimeExecutionHostId, + toSshExecutionHostId, + type ExecutionHostId +} from '../../../shared/execution-host' type WorktreeOwnerRecord = Pick type RepoOwnerRecord = Pick -type FolderWorkspaceOwnerRecord = Pick +type FolderWorkspaceOwnerRecord = Pick< + FolderWorkspace, + 'id' | 'projectGroupId' | 'connectionId' | 'executionHostId' +> type ProjectGroupOwnerRecord = Pick // Why: owner resolution runs inside retained selectors and interaction paths; @@ -17,35 +27,56 @@ const repoOwnerIndexCache = new WeakMap< >() const folderWorkspaceOwnerIndexCache = new WeakMap< readonly FolderWorkspaceOwnerRecord[], - ReadonlyMap + ReadonlyMap >() const projectGroupOwnerIndexCache = new WeakMap< readonly ProjectGroupOwnerRecord[], - ReadonlyMap + ReadonlyMap >() -function findIndexedOwnerRecord( - records: readonly T[] | undefined, - id: string, - cache: WeakMap> -): T | null { - if (!records) { - return null +type IndexedFolderWorkspaceOwnerResolution = + | { kind: 'resolved'; owner: FolderWorkspaceOwnerRecord } + | { kind: 'missing' } + | { kind: 'ambiguous' } + +type IndexedProjectGroupOwnerResolution = + | { kind: 'resolved'; owner: ProjectGroupOwnerRecord } + | { kind: 'missing' } + | { kind: 'ambiguous' } + +function catalogOwnerHostId(owner: { + connectionId?: string | null + executionHostId?: string | null +}): ExecutionHostId { + const explicitHost = parseExecutionHostId(owner.executionHostId) + if (explicitHost) { + return explicitHost.id } - let index = cache.get(records) - if (!index) { - const next = new Map() - for (const record of records) { - const recordId = record.id - if (!next.has(recordId)) { - // Preserve the prior Array.find behavior for invalid duplicate IDs. - next.set(recordId, record) - } + const connectionId = owner.connectionId?.trim() + return connectionId ? toSshExecutionHostId(connectionId) : 'local' +} + +function buildCatalogOwnerIndex< + T extends { id: string; connectionId?: string | null; executionHostId?: string | null } +>( + records: readonly T[] +): ReadonlyMap { + const next = new Map() + for (const record of records) { + const id = record.id + const hostId = catalogOwnerHostId(record) + const current = next.get(id) + if (!current) { + next.set(id, { kind: 'resolved', owner: record }) + } else if (current.kind === 'resolved' && catalogOwnerHostId(current.owner) !== hostId) { + next.set(id, { kind: 'ambiguous' }) } - index = next - cache.set(records, index) + next.set(`${id}\0${hostId}`, { + kind: 'resolved', + owner: record + }) } - return index.get(id) ?? null + return next } export function findIndexedWorktreeOwner( @@ -56,6 +87,21 @@ export function findIndexedWorktreeOwner( return resolution.kind === 'resolved' ? resolution.owner : null } +export function findIndexedWorktreeOwnerForHost( + worktreesByRepo: Record | undefined, + worktreeId: string, + executionHostId: ExecutionHostId +): WorktreeOwnerRecord | null { + if (!worktreesByRepo) { + return null + } + resolveIndexedWorktreeOwner(worktreesByRepo, worktreeId) + const resolution = worktreeOwnerIndexCache + .get(worktreesByRepo) + ?.get(`${worktreeId}\0${executionHostId}`) + return resolution?.kind === 'resolved' ? resolution.owner : null +} + export type IndexedRepoOwnerResolution = | { kind: 'resolved'; owner: RepoOwnerRecord } | { kind: 'missing' } @@ -86,6 +132,10 @@ export function resolveIndexedRepoOwner( ) { next.set(repoId, { kind: 'ambiguous' }) } + next.set(`${repoId}\0${getRepoExecutionHostId(repo)}`, { + kind: 'resolved', + owner: repo + }) } index = next repoOwnerIndexCache.set(repos, index) @@ -106,6 +156,15 @@ function worktreeOwnerIdentity(owner: WorktreeOwnerRecord): string { ]) } +function worktreeOwnerHostId(owner: WorktreeOwnerRecord): ExecutionHostId { + return ( + parseExecutionHostId(owner.hostId)?.id ?? + (owner.runtimeOwnerEnvironmentId + ? toRuntimeExecutionHostId(owner.runtimeOwnerEnvironmentId) + : 'local') + ) +} + export function resolveIndexedWorktreeOwner( worktreesByRepo: Record | undefined, worktreeId: string @@ -128,6 +187,10 @@ export function resolveIndexedWorktreeOwner( ) { next.set(id, { kind: 'ambiguous' }) } + next.set(`${id}\0${worktreeOwnerHostId(worktree)}`, { + kind: 'resolved', + owner: worktree + }) } } index = next @@ -144,16 +207,53 @@ export function findIndexedRepoOwner( return resolution.kind === 'resolved' ? resolution.owner : null } +export function findIndexedRepoOwnerForHost( + repos: readonly RepoOwnerRecord[] | undefined, + repoId: string, + executionHostId: ExecutionHostId +): RepoOwnerRecord | null { + if (!repos) { + return null + } + resolveIndexedRepoOwner(repos, repoId) + const resolution = repoOwnerIndexCache.get(repos)?.get(`${repoId}\0${executionHostId}`) + return resolution?.kind === 'resolved' ? resolution.owner : null +} + export function findIndexedFolderWorkspaceOwner( folderWorkspaces: readonly FolderWorkspaceOwnerRecord[] | undefined, - folderWorkspaceId: string + folderWorkspaceId: string, + executionHostId?: ExecutionHostId ): FolderWorkspaceOwnerRecord | null { - return findIndexedOwnerRecord(folderWorkspaces, folderWorkspaceId, folderWorkspaceOwnerIndexCache) + if (!folderWorkspaces) { + return null + } + let index = folderWorkspaceOwnerIndexCache.get(folderWorkspaces) + if (!index) { + index = buildCatalogOwnerIndex(folderWorkspaces) + folderWorkspaceOwnerIndexCache.set(folderWorkspaces, index) + } + const resolution = index.get( + executionHostId ? `${folderWorkspaceId}\0${executionHostId}` : folderWorkspaceId + ) + return resolution?.kind === 'resolved' ? resolution.owner : null } export function findIndexedProjectGroupOwner( projectGroups: readonly ProjectGroupOwnerRecord[] | undefined, - projectGroupId: string + projectGroupId: string, + executionHostId?: ExecutionHostId ): ProjectGroupOwnerRecord | null { - return findIndexedOwnerRecord(projectGroups, projectGroupId, projectGroupOwnerIndexCache) + if (!projectGroups) { + return null + } + let index = projectGroupOwnerIndexCache.get(projectGroups) + if (!index) { + index = buildCatalogOwnerIndex(projectGroups) + projectGroupOwnerIndexCache.set(projectGroups, index) + } + const resolution = index.get( + executionHostId ? `${projectGroupId}\0${executionHostId}` : projectGroupId + ) + return resolution?.kind === 'resolved' ? resolution.owner : null } diff --git a/src/renderer/src/lib/worktree-runtime-owner-state.ts b/src/renderer/src/lib/worktree-runtime-owner-state.ts index 7c9976d19..6e65f7a1b 100644 --- a/src/renderer/src/lib/worktree-runtime-owner-state.ts +++ b/src/renderer/src/lib/worktree-runtime-owner-state.ts @@ -20,9 +20,14 @@ export type WorktreeRuntimeOwnerState = { worktrees: readonly Pick[] } > - folderWorkspaces?: readonly Pick[] + folderWorkspaces?: readonly Pick< + FolderWorkspace, + 'id' | 'projectGroupId' | 'connectionId' | 'executionHostId' + >[] projectGroups?: readonly Pick[] restoredRuntimeHostIdByWorkspaceSessionKey?: Record + activeWorktreeId?: string | null + activeWorkspaceExecutionHostId?: ExecutionHostId | null runtimeEnvironments?: readonly { id: string }[] runtimeEnvironmentCatalogHydrated?: boolean removedRuntimeEnvironmentIds?: ReadonlySet diff --git a/src/renderer/src/lib/worktree-runtime-owner.test.ts b/src/renderer/src/lib/worktree-runtime-owner.test.ts index bb5aab3e1..410c3b3be 100644 --- a/src/renderer/src/lib/worktree-runtime-owner.test.ts +++ b/src/renderer/src/lib/worktree-runtime-owner.test.ts @@ -62,6 +62,27 @@ describe('getSettingsForWorktreeRuntimeOwner', () => { expect(getExecutionHostIdForWorktree(state, 'folder:runtime-folder')).toBe('runtime:folder-env') }) + it('uses the folder host stamp when same-ID project groups exist on different hosts', () => { + const collisionState: WorktreeRuntimeOwnerState = { + settings: { activeRuntimeEnvironmentId: null }, + folderWorkspaces: [ + { + id: 'same-folder', + projectGroupId: 'same-group', + executionHostId: 'runtime:folder-env' + } + ], + projectGroups: [ + { id: 'same-group', connectionId: null, executionHostId: 'local' }, + { id: 'same-group', connectionId: null, executionHostId: 'runtime:folder-env' } + ] + } + + expect(getExecutionHostIdForWorktree(collisionState, 'folder:same-folder')).toBe( + 'runtime:folder-env' + ) + }) + it('routes restored runtime folder workspaces before their catalog loads', () => { const restoredFolderState: WorktreeRuntimeOwnerState = { settings: { activeRuntimeEnvironmentId: 'focused-env' }, diff --git a/src/renderer/src/lib/worktree-runtime-owner.ts b/src/renderer/src/lib/worktree-runtime-owner.ts index 4bd54c0c5..0ad6b696c 100644 --- a/src/renderer/src/lib/worktree-runtime-owner.ts +++ b/src/renderer/src/lib/worktree-runtime-owner.ts @@ -43,6 +43,15 @@ function getExecutionHostIdFromWorktreeHost( return parseExecutionHostId(hostId)?.id ?? null } +function getActiveWorkspaceExecutionHostId( + state: WorktreeRuntimeOwnerState, + worktreeId: string +): ExecutionHostId | null { + return state.activeWorktreeId === worktreeId + ? (state.activeWorkspaceExecutionHostId ?? null) + : null +} + export function getRuntimeEnvironmentIdForWorktree( state: WorktreeRuntimeOwnerState, worktreeId: string | null | undefined @@ -53,6 +62,10 @@ export function getRuntimeEnvironmentIdForWorktree( if (worktreeId === FLOATING_TERMINAL_WORKTREE_ID) { return null } + const activeHost = parseExecutionHostId(getActiveWorkspaceExecutionHostId(state, worktreeId)) + if (activeHost) { + return activeHost.kind === 'runtime' ? activeHost.environmentId : null + } const workspaceScope = parseWorkspaceKey(worktreeId) if (workspaceScope?.type === 'folder') { return getRuntimeEnvironmentIdForFolderWorkspace(state, workspaceScope.folderWorkspaceId) @@ -100,6 +113,10 @@ export function getExplicitRuntimeEnvironmentIdForWorktree( if (!worktreeId) { return null } + const activeHost = parseExecutionHostId(getActiveWorkspaceExecutionHostId(state, worktreeId)) + if (activeHost) { + return activeHost.kind === 'runtime' ? activeHost.environmentId : null + } const workspaceScope = parseWorkspaceKey(worktreeId) if (workspaceScope?.type === 'folder') { return getExplicitRuntimeEnvironmentIdForFolderWorkspace( @@ -151,6 +168,10 @@ export function getExecutionHostIdForWorktree( if (worktreeId === FLOATING_TERMINAL_WORKTREE_ID) { return 'local' } + const activeHostId = getActiveWorkspaceExecutionHostId(state, worktreeId) + if (activeHostId) { + return activeHostId + } const workspaceScope = parseWorkspaceKey(worktreeId) if (workspaceScope?.type === 'folder') { return getExecutionHostIdForFolderWorkspace(state, workspaceScope.folderWorkspaceId) diff --git a/src/renderer/src/runtime/web-runtime-session.test.ts b/src/renderer/src/runtime/web-runtime-session.test.ts index bd42dda2b..7eee47842 100644 --- a/src/renderer/src/runtime/web-runtime-session.test.ts +++ b/src/renderer/src/runtime/web-runtime-session.test.ts @@ -33,6 +33,7 @@ import { recordWebAgentSessionHandoff, resetWebAgentSessionHandoffsForTests } from './web-agent-session-handoff' +import { toRuntimeExecutionHostId } from '../../../shared/execution-host' const mocks = vi.hoisted(() => ({ getState: vi.fn(), @@ -79,6 +80,7 @@ vi.mock('@/lib/agent-launch-prompt-delivery', () => ({ })) const ENVIRONMENT_ID = 'web-env-1' +const RUNTIME_EXECUTION_HOST_ID = toRuntimeExecutionHostId(ENVIRONMENT_ID) const WORKTREE_ID = 'repo::/worktree' const FOCUS_LEAF_ID = '11111111-1111-4111-8111-111111111111' @@ -392,7 +394,7 @@ describe('createWebRuntimeSessionBrowserTab', () => { await vi.waitFor(() => expect(mocks.applyFreshWebSessionTabsSnapshot).toHaveBeenCalledTimes(1)) - expect(mocks.setActiveWorktree).toHaveBeenCalledWith(WORKTREE_ID) + expect(mocks.setActiveWorktree).toHaveBeenCalledWith(WORKTREE_ID, RUNTIME_EXECUTION_HOST_ID) expect(mocks.applyFreshWebSessionTabsSnapshot).toHaveBeenCalledWith( { state: 'before-stage', activeWorktreeId: 'other-worktree' }, snapshot, @@ -489,7 +491,7 @@ describe('createWebRuntimeSessionBrowserTab', () => { ).resolves.toBe(true) expect(mocks.focusBrowserTabInWorktree).not.toHaveBeenCalled() - expect(mocks.setActiveWorktree).toHaveBeenCalledWith(WORKTREE_ID) + expect(mocks.setActiveWorktree).toHaveBeenCalledWith(WORKTREE_ID, RUNTIME_EXECUTION_HOST_ID) await vi.waitFor(() => expect(mocks.setState).toHaveBeenCalledTimes(1)) }) @@ -563,6 +565,33 @@ describe('createWebRuntimeSessionTerminal', () => { vi.clearAllMocks() }) + it('keeps same-ID local and runtime worktrees on the selected runtime owner', async () => { + const selectedHosts: (string | undefined)[] = [] + mocks.setActiveWorktree.mockImplementation((_worktreeId: string, executionHostId?: string) => { + selectedHosts.push(executionHostId) + }) + const runtimeCall = vi + .fn() + .mockResolvedValueOnce({ + id: 'create', + ok: true, + result: { tab: { id: 'host-tab-1', leafId: 'host-leaf-1' } } + }) + .mockResolvedValueOnce({ id: 'list', ok: true, result: makeSnapshot() }) + vi.stubGlobal('window', { + api: { runtimeEnvironments: { call: runtimeCall } } + }) + + await expect( + createWebRuntimeSessionTerminal({ + worktreeId: WORKTREE_ID, + environmentId: ENVIRONMENT_ID + }) + ).resolves.toEqual({ status: 'created' }) + + expect(selectedHosts).toEqual([RUNTIME_EXECUTION_HOST_ID]) + }) + it.each([ { sessionKind: 'fresh' as const, activate: true }, { sessionKind: 'fresh' as const, activate: false }, diff --git a/src/renderer/src/runtime/web-runtime-session.ts b/src/renderer/src/runtime/web-runtime-session.ts index ee85894fc..05ee84260 100644 --- a/src/renderer/src/runtime/web-runtime-session.ts +++ b/src/renderer/src/runtime/web-runtime-session.ts @@ -60,6 +60,7 @@ import { runRemoteAgentSessionLaunch } from './remote-agent-session-launch' import { translate } from '../i18n/i18n' import { getRuntimeEnvironmentRevision } from './runtime-environment-revision' import { parsePaneKey } from '../../../shared/stable-pane-id' +import { toRuntimeExecutionHostId } from '../../../shared/execution-host' export { HOST_TERMINAL_SURFACE_SEPARATOR, @@ -229,7 +230,7 @@ async function createWebRuntimeSessionTerminalResult( const callEnvironment = captureRuntimeEnvironmentCall(environmentId, intentOwner.pairingRevision) if (args.selectWorktree !== false) { - selectWebRuntimeSessionWorktree(args.worktreeId) + selectWebRuntimeSessionWorktree(args.worktreeId, environmentId) } let hostCreated = false let createdTabId: string | undefined @@ -437,7 +438,7 @@ export async function createWebRuntimeSessionBrowserTab(args: { const shouldSelectWorktree = args.selectWorktree !== false const stagedFromWorktreeId = useAppStore.getState().activeWorktreeId if (shouldSelectWorktree) { - selectWebRuntimeSessionWorktree(args.worktreeId) + selectWebRuntimeSessionWorktree(args.worktreeId, environmentId) } try { const response = await callEnvironment({ @@ -503,7 +504,7 @@ function stageWebRuntimeBrowserTab(args: { remotePageId ) if (args.restoreFocus !== false) { - selectWebRuntimeSessionWorktree(args.worktreeId) + selectWebRuntimeSessionWorktree(args.worktreeId, args.environmentId) } if (existing) { @@ -533,8 +534,8 @@ function stageWebRuntimeBrowserTab(args: { }) } -function selectWebRuntimeSessionWorktree(worktreeId: string): void { - useAppStore.getState().setActiveWorktree(worktreeId) +function selectWebRuntimeSessionWorktree(worktreeId: string, environmentId: string): void { + useAppStore.getState().setActiveWorktree(worktreeId, toRuntimeExecutionHostId(environmentId)) } function findLocalBrowserPageForRemotePage( diff --git a/src/renderer/src/store/selectors.test.ts b/src/renderer/src/store/selectors.test.ts index 8059cf68d..ca9248a3a 100644 --- a/src/renderer/src/store/selectors.test.ts +++ b/src/renderer/src/store/selectors.test.ts @@ -8,6 +8,7 @@ import { getProjectHostSetupProjectionFromState, getWorktreeMapFromState, resetFloatingVisibleTabCountSelectorCacheForTest, + selectRepoByIdForActiveWorkspace, selectFloatingVisibleTabCount, selectFloatingWorkspaceHasUnread } from './selectors' @@ -261,6 +262,32 @@ describe('store selectors', () => { expect(getProjectHostSetupProjectionFromState({ repos: [...repos] })).not.toBe(projection) }) + it('does not fall back to a same-ID local repo when the active runtime row is absent', () => { + const local = makeRepo({ + id: 'same-repo', + path: '/local/repo', + displayName: 'local', + executionHostId: 'local' + }) + const runtime = makeRepo({ + id: 'same-repo', + path: '/runtime/repo', + displayName: 'runtime', + executionHostId: toRuntimeExecutionHostId('env-1') + }) + const activeState = { + activeRepoId: 'same-repo', + activeWorkspaceExecutionHostId: toRuntimeExecutionHostId('env-1') + } + + expect( + selectRepoByIdForActiveWorkspace({ ...activeState, repos: [local, runtime] }, 'same-repo') + ).toBe(runtime) + expect( + selectRepoByIdForActiveWorkspace({ ...activeState, repos: [local] }, 'same-repo') + ).toBeNull() + }) + it('prefers hydrated project host setup state when present', () => { const repos = [ makeRepo({ diff --git a/src/renderer/src/store/selectors.ts b/src/renderer/src/store/selectors.ts index 76dcb5336..1904074f4 100644 --- a/src/renderer/src/store/selectors.ts +++ b/src/renderer/src/store/selectors.ts @@ -3,6 +3,7 @@ import { useShallow } from 'zustand/react/shallow' import type { Repo, Worktree, TerminalTab } from '../../../shared/types' import type { AppState } from './types' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' +import { getRepoExecutionHostId } from '../../../shared/execution-host' import { getProjectHostSetupProjectionFromState } from './project-host-setup-selector' import { getIndexedAllWorktrees as getCachedAllWorktrees, @@ -170,10 +171,30 @@ export function getRepoMapFromState(state: Pick): Map useAppStore((s) => s.repos) export const useActiveRepo = () => - useAppStore(useShallow((s) => s.repos.find((r) => r.id === s.activeRepoId) ?? null)) + useAppStore(useShallow((s) => selectRepoByIdForActiveWorkspace(s, s.activeRepoId))) export const useRepoMap = () => useAppStore((s) => getCachedRepoMap(s.repos)) + +export function selectRepoByIdForActiveWorkspace( + state: Pick, + repoId: string | null +): Repo | null { + if (!repoId) { + return null + } + if (repoId === state.activeRepoId && state.activeWorkspaceExecutionHostId) { + return ( + state.repos.find( + (repo) => + repo.id === repoId && + getRepoExecutionHostId(repo) === state.activeWorkspaceExecutionHostId + ) ?? null + ) + } + return getCachedRepoMap(state.repos).get(repoId) ?? null +} + export const useRepoById = (repoId: string | null) => - useAppStore((s) => (repoId ? (getCachedRepoMap(s.repos).get(repoId) ?? null) : null)) + useAppStore((s) => selectRepoByIdForActiveWorkspace(s, repoId)) export const useProjectHostSetupProjection = () => useAppStore((s) => getProjectHostSetupProjectionFromState(s)) @@ -185,11 +206,21 @@ export const useAllWorktrees = () => useAppStore((s) => getCachedAllWorktrees(s. export const useWorktreeMap = () => useAppStore((s) => getCachedWorktreeMap(s.worktreesByRepo)) export const useWorktreeById = (worktreeId: string | null) => useAppStore((s) => - worktreeId ? (getCachedWorktreeMap(s.worktreesByRepo).get(worktreeId) ?? null) : null + worktreeId + ? (s.getKnownWorktreeById( + worktreeId, + worktreeId === s.activeWorktreeId + ? (s.activeWorkspaceExecutionHostId ?? undefined) + : undefined + ) ?? null) + : null ) export const useActiveWorktree = () => { const activeWorktreeId = useActiveWorktreeId() return useAppStore((s) => - activeWorktreeId ? (s.getKnownWorktreeById(activeWorktreeId) ?? null) : null + activeWorktreeId + ? (s.getKnownWorktreeById(activeWorktreeId, s.activeWorkspaceExecutionHostId ?? undefined) ?? + null) + : null ) } diff --git a/src/renderer/src/store/slices/direct-ssh-terminal-workspace-scope.ts b/src/renderer/src/store/slices/direct-ssh-terminal-workspace-scope.ts index c970e4fe4..e24ca1cdc 100644 --- a/src/renderer/src/store/slices/direct-ssh-terminal-workspace-scope.ts +++ b/src/renderer/src/store/slices/direct-ssh-terminal-workspace-scope.ts @@ -59,6 +59,9 @@ function folderHasContradictoryOwner( const expectedHostId = toSshExecutionHostId(input.targetId) const folders = (input.folderWorkspaces ?? []).filter((folder) => folder.id === folderWorkspaceId) for (const folder of folders) { + if (isExplicitContradictoryHost(folder.executionHostId, expectedHostId)) { + return true + } if (folder.connectionId?.trim() && folder.connectionId.trim() !== input.targetId) { return true } diff --git a/src/renderer/src/store/slices/folder-workspace-owner-routed-mutations.test.ts b/src/renderer/src/store/slices/folder-workspace-owner-routed-mutations.test.ts index 736201137..83ea704c6 100644 --- a/src/renderer/src/store/slices/folder-workspace-owner-routed-mutations.test.ts +++ b/src/renderer/src/store/slices/folder-workspace-owner-routed-mutations.test.ts @@ -237,6 +237,55 @@ describe('folder workspace owner-routed mutations', () => { expect(store.getState().folderWorkspaces[0]?.updatedAt).toBe(2) }) + it('does not fence a runtime update when the local same-ID catalog refreshes', async () => { + const localWorkspace = makeFolderWorkspace({ updatedAt: 3 }) + const runtimeWorkspace = { + ...makeFolderWorkspace(), + executionHostId: 'runtime:env-owner' as const + } + let resolveRuntimeUpdate!: (response: { + id: string + ok: true + result: { folderWorkspace: FolderWorkspace } + _meta: { runtimeId: string } + }) => void + runtimeEnvironmentCall.mockImplementation( + () => + new Promise((resolve) => { + resolveRuntimeUpdate = resolve + }) + ) + folderWorkspacesList.mockResolvedValue([localWorkspace]) + const store = createTestStore() + store.setState({ + projectGroups: [{ ...projectGroup, executionHostId: 'local' }], + folderWorkspaces: [localWorkspace, runtimeWorkspace] + }) + + const pendingUpdate = store + .getState() + .updateFolderWorkspace( + runtimeWorkspace.id, + { isUnread: true }, + { executionHostId: 'runtime:env-owner' } + ) + await store.getState().fetchFolderWorkspaces({ runtimeEnvironmentId: null }) + resolveRuntimeUpdate({ + id: 'rpc-update-folder', + ok: true, + result: { + folderWorkspace: { ...runtimeWorkspace, isUnread: true, updatedAt: 2 } + }, + _meta: { runtimeId: 'runtime-owner' } + }) + await pendingUpdate + + expect(store.getState().folderWorkspaces).toEqual([ + { ...localWorkspace, executionHostId: 'local' }, + { ...runtimeWorkspace, isUnread: true, updatedAt: 2 } + ]) + }) + it('does not rewind newer optimistic activity when an older response arrives', async () => { const folderWorkspace = makeFolderWorkspace() let resolveUpdate!: (workspace: FolderWorkspace) => void diff --git a/src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts b/src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts index dea0120fe..bbbd90d64 100644 --- a/src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts +++ b/src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts @@ -276,7 +276,9 @@ describe('all-host folder workspace startup catalogs', () => { expect(store.getState().projectGroups).toEqual([ { ...localProjectGroup, executionHostId: 'local' } ]) - expect(store.getState().folderWorkspaces).toEqual([localFolderWorkspace]) + expect(store.getState().folderWorkspaces).toEqual([ + { ...localFolderWorkspace, executionHostId: 'local' } + ]) }) it('does not repeat offline runtime compatibility probes across startup catalog loads', async () => { @@ -305,7 +307,9 @@ describe('all-host folder workspace startup catalogs', () => { expect(store.getState().projectGroups).toEqual([ { ...localProjectGroup, executionHostId: 'local' } ]) - expect(store.getState().folderWorkspaces).toEqual([localFolderWorkspace]) + expect(store.getState().folderWorkspaces).toEqual([ + { ...localFolderWorkspace, executionHostId: 'local' } + ]) expect(runtimeEnvironmentTransportCall.mock.calls.map((call) => call[0].method)).toEqual([ 'status.get' ]) diff --git a/src/renderer/src/store/slices/repos-all-hosts.test.ts b/src/renderer/src/store/slices/repos-all-hosts.test.ts index 638941df0..9d38bc0bf 100644 --- a/src/renderer/src/store/slices/repos-all-hosts.test.ts +++ b/src/renderer/src/store/slices/repos-all-hosts.test.ts @@ -780,7 +780,9 @@ describe('fetchReposForAllHosts', () => { expect(store.getState().projectGroups).toEqual([ { ...localProjectGroup, executionHostId: 'local' } ]) - expect(store.getState().folderWorkspaces).toEqual([localFolderWorkspace]) + expect(store.getState().folderWorkspaces).toEqual([ + { ...localFolderWorkspace, executionHostId: 'local' } + ]) }) it('preserves remote repo filters during first-paint local catalog refresh', async () => { diff --git a/src/renderer/src/store/slices/repos-project-groups.test.ts b/src/renderer/src/store/slices/repos-project-groups.test.ts index 7b32c5b6b..9fbf45558 100644 --- a/src/renderer/src/store/slices/repos-project-groups.test.ts +++ b/src/renderer/src/store/slices/repos-project-groups.test.ts @@ -270,7 +270,7 @@ describe('project group store routing', () => { { projectGroupId: projectGroup.id, name: 'Runtime folder' }, { runtimeEnvironmentId: 'env-1' } ) - ).resolves.toEqual(folderWorkspace) + ).resolves.toEqual({ ...folderWorkspace, executionHostId: 'runtime:env-1' }) expect(runtimeEnvironmentCall).toHaveBeenCalledWith({ selector: 'env-1', @@ -350,7 +350,7 @@ describe('project group store routing', () => { name: 'Refund fix', linkedTask }) - ).resolves.toEqual(folderWorkspace) + ).resolves.toEqual({ ...folderWorkspace, executionHostId: 'local' }) await expect( store.getState().updateFolderWorkspace(folderWorkspace.id, { comment: 'Ready' }) ).resolves.toBe(true) @@ -805,9 +805,13 @@ describe('project group store routing', () => { _meta: { runtimeId: 'runtime-remote' } }) const store = createTestStore() - store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never }) + store.setState({ settings: { activeRuntimeEnvironmentId: 'env-ambient' } as never }) - await expect(store.getState().scanNestedRepos('/platform')).resolves.toEqual({ + await expect( + store.getState().scanNestedRepos('/platform', undefined, { + runtimeEnvironmentId: 'env-selected' + }) + ).resolves.toEqual({ selectedPath: '/platform', selectedPathKind: 'non_git_folder', repos: [{ path: '/platform/api', displayName: 'api', depth: 1 }], @@ -821,7 +825,7 @@ describe('project group store routing', () => { }) expect(runtimeEnvironmentCall).toHaveBeenCalledWith({ - selector: 'env-1', + selector: 'env-selected', method: 'projectGroup.scanNested', params: { path: '/platform' }, timeoutMs: 20_000 diff --git a/src/renderer/src/store/slices/repos-selected-owner-routing.test.ts b/src/renderer/src/store/slices/repos-selected-owner-routing.test.ts new file mode 100644 index 000000000..691a9fbda --- /dev/null +++ b/src/renderer/src/store/slices/repos-selected-owner-routing.test.ts @@ -0,0 +1,536 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { FolderWorkspace, ProjectGroup, Repo } from '../../../../shared/types' +import { + createCompatibleRuntimeStatusResponseIfNeeded, + type RuntimeEnvironmentCallRequest +} from '../../runtime/runtime-compatibility-test-fixture' +import { clearRuntimeCompatibilityCacheForTests } from '../../runtime/runtime-rpc-client' +import { createTestStore } from './store-test-helpers' + +const projectGroup: ProjectGroup = { + id: 'group-runtime', + name: 'Platform', + parentPath: '/runtime/platform', + parentGroupId: null, + createdFrom: 'manual', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 1, + updatedAt: 1 +} + +const baseRepo: Repo = { + id: 'repo', + path: '/repo', + displayName: 'Repo', + badgeColor: '#111', + addedAt: 1 +} + +const reposList = vi.fn() +const projectGroupsList = vi.fn() +const projectGroupsImportNested = vi.fn() +const projectGroupsScanNested = vi.fn() +const projectGroupsCancelNestedScan = vi.fn() +const folderWorkspacesList = vi.fn() +const runtimeEnvironmentCall = vi.fn() +const runtimeEnvironmentTransportCall = vi.fn() + +beforeEach(() => { + clearRuntimeCompatibilityCacheForTests() + vi.clearAllMocks() + runtimeEnvironmentTransportCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { + return createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args) + }) + vi.stubGlobal('window', { + api: { + repos: { list: reposList }, + projectGroups: { + list: projectGroupsList, + importNested: projectGroupsImportNested, + scanNested: projectGroupsScanNested, + cancelNestedScan: projectGroupsCancelNestedScan, + onNestedScanProgress: vi.fn(() => vi.fn()) + }, + folderWorkspaces: { list: folderWorkspacesList }, + runtimeEnvironments: { call: runtimeEnvironmentTransportCall } + } + }) +}) + +describe('selected Add Project owner routing', () => { + it('keeps same-ID project groups and folder workspaces partitioned by host', async () => { + const localGroup = { + ...projectGroup, + id: 'shared-group', + name: 'Local group', + parentPath: '/local/platform', + executionHostId: 'local' as const + } + const runtimeGroup = { + ...projectGroup, + id: localGroup.id, + name: 'Runtime group', + parentPath: '/runtime/platform' + } + const localFolder: FolderWorkspace = { + id: 'shared-folder', + projectGroupId: localGroup.id, + name: 'Local folder', + folderPath: '/local/platform', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 1, + updatedAt: 1 + } + const runtimeFolder = { + ...localFolder, + name: 'Runtime folder', + folderPath: '/runtime/platform' + } + runtimeEnvironmentCall.mockImplementation(async ({ method }) => ({ + id: `rpc-${method}`, + ok: true, + result: + method === 'projectGroup.list' + ? { groups: [runtimeGroup] } + : { folderWorkspaces: [runtimeFolder] }, + _meta: { runtimeId: 'runtime-remote' } + })) + const store = createTestStore() + store.setState({ + projectGroups: [localGroup], + folderWorkspaces: [localFolder] + }) + + await store.getState().fetchProjectGroups({ runtimeEnvironmentId: 'env-1' }) + await store.getState().fetchFolderWorkspaces({ runtimeEnvironmentId: 'env-1' }) + + expect(store.getState().projectGroups).toEqual([ + localGroup, + { ...runtimeGroup, executionHostId: 'runtime:env-1' } + ]) + expect(store.getState().folderWorkspaces).toEqual([ + localFolder, + { ...runtimeFolder, executionHostId: 'runtime:env-1' } + ]) + }) + + it('merges explicit runtime groups and folders without erasing local siblings', async () => { + const localGroup = { ...projectGroup, id: 'group-local', executionHostId: 'local' as const } + const runtimeGroup = { ...projectGroup, name: 'Runtime' } + const localFolder: FolderWorkspace = { + id: 'folder-local', + projectGroupId: localGroup.id, + name: 'Local folder', + folderPath: '/local/folder', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 1, + updatedAt: 1 + } + const runtimeFolder = { + ...localFolder, + id: 'folder-runtime', + projectGroupId: runtimeGroup.id, + name: 'Runtime folder', + folderPath: '/runtime/folder' + } + runtimeEnvironmentCall.mockImplementation(async ({ method }) => + method === 'projectGroup.list' + ? { + id: 'rpc-groups', + ok: true, + result: { groups: [runtimeGroup] }, + _meta: { runtimeId: 'runtime-remote' } + } + : { + id: 'rpc-folders', + ok: true, + result: { folderWorkspaces: [runtimeFolder] }, + _meta: { runtimeId: 'runtime-remote' } + } + ) + const store = createTestStore() + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-ambient' } as never, + projectGroups: [localGroup], + folderWorkspaces: [localFolder] + }) + + await store.getState().fetchProjectGroups({ runtimeEnvironmentId: 'env-1' }) + await store.getState().fetchFolderWorkspaces({ runtimeEnvironmentId: 'env-1' }) + + expect(store.getState().projectGroups).toEqual([ + localGroup, + { ...runtimeGroup, executionHostId: 'runtime:env-1' } + ]) + expect(store.getState().folderWorkspaces).toEqual([ + localFolder, + { ...runtimeFolder, executionHostId: 'runtime:env-1' } + ]) + + projectGroupsList.mockResolvedValue([localGroup]) + folderWorkspacesList.mockResolvedValue([localFolder]) + store.setState({ settings: { activeRuntimeEnvironmentId: null } as never }) + await store.getState().fetchProjectGroups() + await store.getState().fetchFolderWorkspaces() + + expect(store.getState().projectGroups).toEqual([ + localGroup, + { ...runtimeGroup, executionHostId: 'runtime:env-1' } + ]) + expect(store.getState().folderWorkspaces).toEqual([ + { ...localFolder, executionHostId: 'local' }, + { ...runtimeFolder, executionHostId: 'runtime:env-1' } + ]) + }) + + it('keeps a selected-runtime import refresh across an overlapping local refresh', async () => { + const localRepo = { ...baseRepo, id: 'local-repo', path: '/local/repo' } + const runtimeRepo = { + ...baseRepo, + id: 'runtime-repo', + path: '/runtime/platform/api', + projectGroupId: projectGroup.id + } + const result = { + group: projectGroup, + repos: [{ path: runtimeRepo.path, projectId: runtimeRepo.id, status: 'imported' as const }], + importedCount: 1, + alreadyKnownCount: 0, + failedCount: 0 + } + let resolveRuntimeRepos!: (value: unknown) => void + const runtimeRepos = new Promise((resolve) => { + resolveRuntimeRepos = resolve + }) + runtimeEnvironmentCall.mockImplementation(({ method }) => { + const responses: Record = { + 'projectGroup.importNested': result, + 'projectGroup.list': { groups: [projectGroup] }, + 'folderWorkspace.list': { folderWorkspaces: [] }, + 'project.list': { projects: [] }, + 'projectHostSetup.list': { setups: [] } + } + if (method === 'repo.list') { + return runtimeRepos + } + return Promise.resolve({ + id: `rpc-${method}`, + ok: true, + result: responses[method], + _meta: { runtimeId: 'runtime-remote' } + }) + }) + reposList.mockResolvedValue([localRepo]) + const store = createTestStore() + + const importing = store.getState().importNestedRepos({ + parentPath: '/runtime/platform', + groupName: 'Platform', + projectPaths: [runtimeRepo.path], + runtimeEnvironmentId: 'env-1', + mode: 'group' + }) + await vi.waitFor(() => + expect(runtimeEnvironmentCall).toHaveBeenCalledWith( + expect.objectContaining({ method: 'repo.list', selector: 'env-1' }) + ) + ) + await store.getState().fetchRepos({ runtimeEnvironmentId: null }) + resolveRuntimeRepos({ + id: 'rpc-repos', + ok: true, + result: { repos: [runtimeRepo] }, + _meta: { runtimeId: 'runtime-remote' } + }) + + await expect(importing).resolves.toEqual(result) + expect(store.getState().repos).toEqual( + expect.arrayContaining([ + { ...localRepo, executionHostId: 'local' }, + { ...runtimeRepo, executionHostId: 'runtime:env-1' } + ]) + ) + }) + + it('drops older same-host group and folder responses that finish last', async () => { + let resolveOldGroup!: (value: unknown) => void + let resolveNewGroup!: (value: unknown) => void + let resolveOldFolder!: (value: unknown) => void + let resolveNewFolder!: (value: unknown) => void + const groupResponses = [ + new Promise((resolve) => { + resolveOldGroup = resolve + }), + new Promise((resolve) => { + resolveNewGroup = resolve + }) + ] + const folderResponses = [ + new Promise((resolve) => { + resolveOldFolder = resolve + }), + new Promise((resolve) => { + resolveNewFolder = resolve + }) + ] + runtimeEnvironmentCall.mockImplementation(({ method }) => { + if (method === 'projectGroup.list') { + return groupResponses.shift() + } + if (method === 'folderWorkspace.list') { + return folderResponses.shift() + } + throw new Error(`Unexpected method: ${method}`) + }) + const store = createTestStore() + const oldGroup = { ...projectGroup, id: 'group-old', parentPath: '/runtime/old' } + const newGroup = { ...projectGroup, id: 'group-new', parentPath: '/runtime/new' } + const oldFolder: FolderWorkspace = { + id: 'old-folder', + projectGroupId: oldGroup.id, + name: 'Old folder', + folderPath: '/runtime/old', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 1, + updatedAt: 1 + } + const newFolder = { + ...oldFolder, + id: 'new-folder', + projectGroupId: newGroup.id, + name: 'New folder', + folderPath: '/runtime/new' + } + + const oldGroupsRequest = store.getState().fetchProjectGroups({ runtimeEnvironmentId: 'env-1' }) + const newGroupsRequest = store.getState().fetchProjectGroups({ runtimeEnvironmentId: 'env-1' }) + resolveNewGroup({ + id: 'rpc-new-group', + ok: true, + result: { groups: [newGroup] }, + _meta: { runtimeId: 'runtime-remote' } + }) + await newGroupsRequest + resolveOldGroup({ + id: 'rpc-old-group', + ok: true, + result: { groups: [oldGroup] }, + _meta: { runtimeId: 'runtime-remote' } + }) + await oldGroupsRequest + + store.setState({ + projectGroups: [{ ...newGroup, executionHostId: 'runtime:env-1' }] + }) + const oldFoldersRequest = store + .getState() + .fetchFolderWorkspaces({ runtimeEnvironmentId: 'env-1' }) + const newFoldersRequest = store + .getState() + .fetchFolderWorkspaces({ runtimeEnvironmentId: 'env-1' }) + resolveNewFolder({ + id: 'rpc-new-folder', + ok: true, + result: { folderWorkspaces: [newFolder] }, + _meta: { runtimeId: 'runtime-remote' } + }) + await newFoldersRequest + resolveOldFolder({ + id: 'rpc-old-folder', + ok: true, + result: { folderWorkspaces: [oldFolder] }, + _meta: { runtimeId: 'runtime-remote' } + }) + await oldFoldersRequest + + expect(store.getState().projectGroups).toEqual([ + { ...newGroup, executionHostId: 'runtime:env-1' } + ]) + expect(store.getState().folderWorkspaces).toEqual([ + { ...newFolder, executionHostId: 'runtime:env-1' } + ]) + }) + + it('drops pre-reconnect group and folder responses without pruning the new catalog', async () => { + let resolveOldGroup!: (value: unknown) => void + let resolveOldFolder!: (value: unknown) => void + runtimeEnvironmentCall.mockImplementation(({ method }) => { + if (method === 'projectGroup.list') { + return new Promise((resolve) => { + resolveOldGroup = resolve + }) + } + if (method === 'folderWorkspace.list') { + return new Promise((resolve) => { + resolveOldFolder = resolve + }) + } + throw new Error(`Unexpected method: ${method}`) + }) + const store = createTestStore() + store + .getState() + .setRuntimeEnvironments([{ id: 'env-1', createdAt: 1, pairingRevision: 1 } as never]) + const pending = store.getState().fetchProjectGroups({ runtimeEnvironmentId: 'env-1' }) + const pendingFolders = store.getState().fetchFolderWorkspaces({ runtimeEnvironmentId: 'env-1' }) + await vi.waitFor(() => expect(resolveOldGroup).toBeTypeOf('function')) + await vi.waitFor(() => expect(resolveOldFolder).toBeTypeOf('function')) + store + .getState() + .setRuntimeEnvironments([{ id: 'env-1', createdAt: 1, pairingRevision: 2 } as never]) + const newGroup = { + ...projectGroup, + id: 'group-after-reconnect', + executionHostId: 'runtime:env-1' + } + const newFolder: FolderWorkspace = { + id: 'folder-after-reconnect', + projectGroupId: newGroup.id, + name: 'New folder', + folderPath: '/runtime/new', + executionHostId: 'runtime:env-1', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 1, + updatedAt: 1 + } + store.setState({ projectGroups: [newGroup], folderWorkspaces: [newFolder] }) + resolveOldGroup({ + id: 'rpc-before-reconnect', + ok: true, + result: { groups: [{ ...projectGroup, id: 'stale-group' }] }, + _meta: { runtimeId: 'runtime-old' } + }) + resolveOldFolder({ + id: 'rpc-folder-before-reconnect', + ok: true, + result: { + folderWorkspaces: [ + { + ...newFolder, + id: 'stale-folder', + executionHostId: undefined + } + ] + }, + _meta: { runtimeId: 'runtime-old' } + }) + await pending + await pendingFolders + + expect(store.getState().projectGroups).toEqual([newGroup]) + expect(store.getState().folderWorkspaces).toEqual([newFolder]) + }) + + it('prunes deleted desktop and direct-SSH catalog rows without erasing runtime siblings', async () => { + const sshGroup = { + ...projectGroup, + id: 'ssh-group', + connectionId: 'ssh-1', + executionHostId: 'ssh:ssh-1' + } + const runtimeGroup = { + ...projectGroup, + id: sshGroup.id, + executionHostId: 'runtime:env-1' + } + const sshFolder: FolderWorkspace = { + id: 'ssh-folder', + projectGroupId: sshGroup.id, + name: 'SSH folder', + folderPath: '/srv/folder', + connectionId: 'ssh-1', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 1, + updatedAt: 1 + } + const runtimeFolder = { + ...sshFolder, + id: sshFolder.id, + projectGroupId: runtimeGroup.id, + connectionId: null, + executionHostId: 'runtime:env-1' as const + } + projectGroupsList.mockResolvedValue([]) + folderWorkspacesList.mockResolvedValue([]) + const store = createTestStore() + store.setState({ + projectGroups: [sshGroup, runtimeGroup], + folderWorkspaces: [sshFolder, runtimeFolder] + }) + + await store.getState().fetchProjectGroups({ runtimeEnvironmentId: null }) + await store.getState().fetchFolderWorkspaces({ runtimeEnvironmentId: null }) + + expect(store.getState().projectGroups).toEqual([runtimeGroup]) + expect(store.getState().folderWorkspaces).toEqual([runtimeFolder]) + }) + + it('pins selected SSH scans and cancellation to local IPC over an ambient runtime', async () => { + const scan = { + selectedPath: '/srv/platform', + selectedPathKind: 'git_repo' as const, + repos: [], + truncated: false, + timedOut: false, + stopped: false, + durationMs: 1, + maxDepth: 3, + maxRepos: 100, + timeoutMs: null + } + projectGroupsScanNested.mockResolvedValue(scan) + projectGroupsCancelNestedScan.mockResolvedValue(true) + const store = createTestStore() + store.setState({ settings: { activeRuntimeEnvironmentId: 'env-ambient' } as never }) + + await expect( + store.getState().scanNestedRepos('/srv/platform', 'ssh-1', { + scanId: 'scan-ssh', + runtimeEnvironmentId: null + }) + ).resolves.toEqual(scan) + await expect( + store.getState().cancelNestedRepoScan('scan-ssh', { runtimeEnvironmentId: null }) + ).resolves.toBe(true) + + expect(projectGroupsScanNested).toHaveBeenCalledWith({ + path: '/srv/platform', + connectionId: 'ssh-1', + scanId: 'scan-ssh' + }) + expect(projectGroupsCancelNestedScan).toHaveBeenCalledWith({ scanId: 'scan-ssh' }) + expect(runtimeEnvironmentCall).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/store/slices/repos.ts b/src/renderer/src/store/slices/repos.ts index dac56c841..2c80b970d 100644 --- a/src/renderer/src/store/slices/repos.ts +++ b/src/renderer/src/store/slices/repos.ts @@ -65,7 +65,8 @@ import { import { assertRuntimeEnvironmentCapability, callRuntimeRpc, - getActiveRuntimeTarget + getActiveRuntimeTarget, + settingsForRuntimeOwner } from '../../runtime/runtime-rpc-client' import { syncRuntimeGitForkDefaultBranch } from '../../runtime/runtime-git-client' import { toRuntimeWorktreeSelector } from '../../runtime/runtime-worktree-selector' @@ -102,6 +103,14 @@ const ERROR_TOAST_DURATION = 60_000 const SAFE_AUTO_FORK_SYNC_COOLDOWN_MS = 10 * 60 * 1000 const safeAutoForkSyncAttempts = new Map }>() const runtimeRepoFetchGenerationByEnvironment = new Map() +type HostCatalogKind = 'project-groups' | 'folder-workspaces' +type HostCatalogFence = { + key: string + generation: number + target: ReturnType + sshStateGeneration: number | null + runtimeConnectionGeneration: number | null +} export type RepoUpdate = Partial< Pick< @@ -177,6 +186,11 @@ function getFolderWorkspaceUpdateCoordinator( type NestedRepoScanControls = { scanId?: string onProgress?: (scan: NestedRepoScanResult) => void + runtimeEnvironmentId?: string | null +} + +type NestedRepoScanCancelOptions = { + runtimeEnvironmentId?: string | null } export type FolderWorkspacePathStatusCacheEntry = { @@ -843,13 +857,18 @@ function mergeFetchedProjectCompatibilityForHost({ } } -function mergeById(base: readonly T[], overlay: readonly T[]): T[] { +function mergeByIdentity( + base: readonly T[], + overlay: readonly T[], + getIdentity: (entry: T) => string +): T[] { const merged = [...base] - const indexById = new Map(merged.map((entry, index) => [entry.id, index])) + const indexById = new Map(merged.map((entry, index) => [getIdentity(entry), index])) for (const entry of overlay) { - const index = indexById.get(entry.id) + const identity = getIdentity(entry) + const index = indexById.get(identity) if (index === undefined) { - indexById.set(entry.id, merged.length) + indexById.set(identity, merged.length) merged.push(entry) } else { merged[index] = entry @@ -940,17 +959,66 @@ function getProjectGroupHostId(group: Pick group.id)) + const fetchedIdentities = new Set(fetched.map(getProjectGroupHostIdentity)) const preserved = previous.filter((group) => { const existingHostId = getProjectGroupHostId(group) - return existingHostId !== hostId || fetchedIds.has(group.id) + return ( + !catalogOwnsHost(hostId, existingHostId) || + fetchedIdentities.has(getProjectGroupHostIdentity(group)) + ) }) - return mergeById(preserved, fetched) + return mergeByIdentity(preserved, fetched, getProjectGroupHostIdentity) +} + +function getFolderWorkspaceHostId( + workspace: FolderWorkspace, + projectGroups: readonly ProjectGroup[] +): ExecutionHostId { + const explicitHostId = parseExecutionHostId(workspace.executionHostId)?.id + if (explicitHostId) { + return explicitHostId + } + if (workspace.connectionId) { + return toSshExecutionHostId(workspace.connectionId) + } + const matchingHosts = new Set( + projectGroups + .filter((group) => group.id === workspace.projectGroupId) + .map(getProjectGroupHostId) + ) + return matchingHosts.size === 1 + ? ([...matchingHosts][0] as ExecutionHostId) + : LOCAL_EXECUTION_HOST_ID +} + +function getFolderWorkspaceHostIdentity( + workspace: FolderWorkspace, + projectGroups: readonly ProjectGroup[] +): string { + return JSON.stringify([getFolderWorkspaceHostId(workspace, projectGroups), workspace.id]) +} + +function getFolderWorkspaceUpdateIdentity( + hostId: ExecutionHostId, + folderWorkspaceId: string +): string { + return `${hostId}\0${folderWorkspaceId}` } function mergeFetchedFolderWorkspacesForHost({ @@ -964,15 +1032,19 @@ function mergeFetchedFolderWorkspacesForHost({ projectGroups: readonly ProjectGroup[] hostId: string }): FolderWorkspace[] { - const fetchedIds = new Set(fetched.map((workspace) => workspace.id)) - const projectGroupHostIds = new Map( - projectGroups.map((group) => [group.id, getProjectGroupHostId(group)]) + const fetchedIdentities = new Set( + fetched.map((workspace) => getFolderWorkspaceHostIdentity(workspace, projectGroups)) ) const preserved = previous.filter((workspace) => { - const existingHostId = projectGroupHostIds.get(workspace.projectGroupId) - return existingHostId === undefined || existingHostId !== hostId || fetchedIds.has(workspace.id) + const existingHostId = getFolderWorkspaceHostId(workspace, projectGroups) + return ( + !catalogOwnsHost(hostId, existingHostId) || + fetchedIdentities.has(getFolderWorkspaceHostIdentity(workspace, projectGroups)) + ) }) - return mergeById(preserved, fetched) + return mergeByIdentity(preserved, fetched, (workspace) => + getFolderWorkspaceHostIdentity(workspace, projectGroups) + ) } type FetchedRepoCatalog = { @@ -991,21 +1063,26 @@ type FetchedFolderWorkspaceCatalog = { hostId: ReturnType } -function getFolderWorkspaceCatalogReplacementIds( +function getFolderWorkspaceCatalogReplacementIdentities( catalog: FetchedFolderWorkspaceCatalog, currentFolderWorkspaces: readonly FolderWorkspace[], projectGroups: readonly ProjectGroup[] ): Set { - const replacedIds = new Set(catalog.folderWorkspaces.map((workspace) => workspace.id)) - const projectGroupHostIds = new Map( - projectGroups.map((group) => [group.id, getProjectGroupHostId(group)]) + const replacedIdentities = new Set( + catalog.folderWorkspaces.map((workspace) => + getFolderWorkspaceUpdateIdentity( + getFolderWorkspaceHostId(workspace, projectGroups), + workspace.id + ) + ) ) for (const workspace of currentFolderWorkspaces) { - if (projectGroupHostIds.get(workspace.projectGroupId) === catalog.hostId) { - replacedIds.add(workspace.id) + const hostId = getFolderWorkspaceHostId(workspace, projectGroups) + if (catalogOwnsHost(catalog.hostId, hostId)) { + replacedIdentities.add(getFolderWorkspaceUpdateIdentity(hostId, workspace.id)) } } - return replacedIds + return replacedIdentities } async function fetchRepoCatalogForTarget( @@ -1172,18 +1249,9 @@ function mergeFetchedProjectGroupCatalog( } } -async function fetchProjectGroupsForTarget( - target: ReturnType, - currentProjectGroups: readonly ProjectGroup[] -): Promise<{ projectGroups: ProjectGroup[]; hostId: ReturnType }> { - return mergeFetchedProjectGroupCatalog( - await fetchProjectGroupCatalogForTarget(target), - currentProjectGroups - ) -} - async function fetchFolderWorkspaceCatalogForTarget( - target: ReturnType + target: ReturnType, + projectGroups: readonly ProjectGroup[] ): Promise { const fetchedFolderWorkspaces = target.kind === 'local' @@ -1197,11 +1265,27 @@ async function fetchFolderWorkspaceCatalogForTarget( ) ).folderWorkspaces return { - folderWorkspaces: fetchedFolderWorkspaces, + folderWorkspaces: fetchedFolderWorkspaces.map((workspace) => + folderWorkspaceWithFetchedOwner(workspace, target, projectGroups) + ), hostId: getRuntimeTargetHostId(target) } } +function folderWorkspaceWithFetchedOwner( + workspace: FolderWorkspace, + target: ReturnType, + projectGroups: readonly ProjectGroup[] +): FolderWorkspace { + return { + ...workspace, + executionHostId: + target.kind === 'environment' + ? getRuntimeTargetHostId(target) + : getFolderWorkspaceHostId(workspace, projectGroups) + } +} + function mergeFetchedFolderWorkspaceCatalog( catalog: FetchedFolderWorkspaceCatalog, currentFolderWorkspaces: readonly FolderWorkspace[], @@ -1224,14 +1308,19 @@ function mergeFetchedFolderWorkspaceCatalog( async function reconcileFailedFolderWorkspaceUpdate(args: { target: ReturnType folderWorkspaceId: string + updateIdentity: string + ownerHostId: ExecutionHostId ticket: FolderWorkspaceUpdateTicket coordinator: FolderWorkspaceUpdateCoordinatorInstance set: Parameters>[0] get: Parameters>[1] }): Promise { try { - const catalog = await fetchFolderWorkspaceCatalogForTarget(args.target) - const latestFields = args.coordinator.latestFields(args.folderWorkspaceId, args.ticket) + const catalog = await fetchFolderWorkspaceCatalogForTarget( + args.target, + args.get().projectGroups + ) + const latestFields = args.coordinator.latestFields(args.updateIdentity, args.ticket) if (latestFields.length === 0) { return } @@ -1241,11 +1330,16 @@ async function reconcileFailedFolderWorkspaceUpdate(args: { args.set((state) => ({ folderWorkspaces: refreshed ? state.folderWorkspaces.map((workspace) => - workspace.id === args.folderWorkspaceId + workspace.id === args.folderWorkspaceId && + getFolderWorkspaceHostId(workspace, state.projectGroups) === args.ownerHostId ? mergeFolderWorkspaceUpdateResponse(workspace, refreshed, latestFields) : workspace ) - : state.folderWorkspaces.filter((workspace) => workspace.id !== args.folderWorkspaceId), + : state.folderWorkspaces.filter( + (workspace) => + workspace.id !== args.folderWorkspaceId || + getFolderWorkspaceHostId(workspace, state.projectGroups) !== args.ownerHostId + ), ...(folderWorkspaceUpdateInvalidatesPathStatus(latestFields) || !refreshed ? { folderWorkspacePathStatuses: {} } : {}) @@ -1313,6 +1407,7 @@ function getRuntimeTargetCachePrefix( type FolderWorkspacePathStatusRouteOptions = { runtimeEnvironmentId?: string | null } type AddRepoPathRouteOptions = { runtimeEnvironmentId?: string | null } +type RuntimeCatalogFetchOptions = { runtimeEnvironmentId?: string | null } function getFolderWorkspacePathStatusRouteSettings( options: FolderWorkspacePathStatusRouteOptions | undefined, @@ -1534,13 +1629,13 @@ export type RepoSlice = { reposFetchGeneration: number pendingSshRepoReadoptions: SshRepoReadoption[] recordSshRepoReadoptions: (readoptions: SshRepoReadoption[]) => void - fetchRepos: () => Promise + fetchRepos: (options?: RuntimeCatalogFetchOptions) => Promise fetchReposForAllHosts: (options?: AllHostCatalogFetchOptions) => Promise awaitLocalRepoCatalogSettlement: () => Promise fetchRuntimeEnvironmentRepos: (environmentId: string) => Promise - fetchProjectGroups: () => Promise + fetchProjectGroups: (options?: RuntimeCatalogFetchOptions) => Promise fetchProjectGroupsForAllHosts: (options?: AllHostCatalogFetchOptions) => Promise - fetchFolderWorkspaces: () => Promise + fetchFolderWorkspaces: (options?: RuntimeCatalogFetchOptions) => Promise fetchFolderWorkspacesForAllHosts: (options?: AllHostCatalogFetchOptions) => Promise addRepo: () => Promise addRepoPath: ( @@ -1567,13 +1662,14 @@ export type RepoSlice = { connectionId?: string, controls?: NestedRepoScanControls ) => Promise - cancelNestedRepoScan: (scanId: string) => Promise + cancelNestedRepoScan: (scanId: string, options?: NestedRepoScanCancelOptions) => Promise importNestedRepos: (args: { parentPath: string groupName: string projectPaths: string[] connectionId?: string scanId?: string + runtimeEnvironmentId?: string | null mode: 'group' | 'separate' }) => Promise createProjectGroup: (name: string) => Promise @@ -1604,7 +1700,8 @@ export type RepoSlice = { ) => Promise updateFolderWorkspace: ( folderWorkspaceId: string, - updates: FolderWorkspaceUpdates + updates: FolderWorkspaceUpdates, + options?: { executionHostId?: ExecutionHostId } ) => Promise deleteFolderWorkspace: (folderWorkspaceId: string) => Promise updateProjectGroup: ( @@ -1644,6 +1741,51 @@ const latestLocalRepoCatalogFetchByStore = new WeakMap< >() const latestRepoCatalogGenerationByHostByStore = new WeakMap<() => AppState, Map>() const latestAllHostRepoCatalogGenerationByStore = new WeakMap<() => AppState, number>() +const latestHostCatalogGenerationByStore = new WeakMap<() => AppState, Map>() + +function claimHostCatalogFence( + get: () => AppState, + kind: HostCatalogKind, + target: ReturnType +): HostCatalogFence { + const key = `${kind}:${getRuntimeTargetHostId(target)}` + let generations = latestHostCatalogGenerationByStore.get(get) + if (!generations) { + generations = new Map() + latestHostCatalogGenerationByStore.set(get, generations) + } + const generation = (generations.get(key) ?? 0) + 1 + generations.set(key, generation) + return { + key, + generation, + target, + sshStateGeneration: + target.kind === 'environment' ? getEnvironmentSshStateGeneration(target.environmentId) : null, + runtimeConnectionGeneration: + target.kind === 'environment' + ? getRuntimeEnvironmentConnectionGeneration(target.environmentId) + : null + } +} + +function isHostCatalogFenceCurrent(get: () => AppState, fence: HostCatalogFence): boolean { + if (latestHostCatalogGenerationByStore.get(get)?.get(fence.key) !== fence.generation) { + return false + } + if (fence.target.kind !== 'environment') { + return true + } + return ( + !isRemovedRuntimeHostId( + getRuntimeTargetHostId(fence.target), + get().removedRuntimeEnvironmentIds + ) && + getEnvironmentSshStateGeneration(fence.target.environmentId) === fence.sshStateGeneration && + getRuntimeEnvironmentConnectionGeneration(fence.target.environmentId) === + fence.runtimeConnectionGeneration + ) +} function startLocalRepoCatalogFetch( get: () => AppState @@ -1727,8 +1869,10 @@ export const createRepoSlice: StateCreator = (set, } }), - fetchRepos: async () => { - const target = getActiveRuntimeTarget(get().settings) + fetchRepos: async (options) => { + const target = getActiveRuntimeTarget( + settingsForRuntimeOwner(get().settings, options?.runtimeEnvironmentId) + ) const settleLocalCatalog: (outcome: LocalRepoCatalogFetchOutcome) => void = target.kind === 'local' ? startLocalRepoCatalogFetch(get) : () => undefined let localCatalogOutcome: LocalRepoCatalogFetchOutcome = { status: 'fulfilled' } @@ -2006,14 +2150,25 @@ export const createRepoSlice: StateCreator = (set, awaitLocalRepoCatalogSettlement: () => awaitLatestLocalRepoCatalogFetch(get), - fetchProjectGroups: async () => { + fetchProjectGroups: async (options) => { try { - const target = getActiveRuntimeTarget(get().settings) - const { projectGroups } = await fetchProjectGroupsForTarget(target, []) - set({ - projectGroups, - folderWorkspacePathStatuses: {} - }) + const target = getActiveRuntimeTarget( + settingsForRuntimeOwner(get().settings, options?.runtimeEnvironmentId) + ) + const fence = claimHostCatalogFence(get, 'project-groups', target) + const catalog = await fetchProjectGroupCatalogForTarget(target) + if (!isHostCatalogFenceCurrent(get, fence)) { + return + } + set((current) => + isHostCatalogFenceCurrent(get, fence) + ? { + projectGroups: mergeFetchedProjectGroupCatalog(catalog, current.projectGroups) + .projectGroups, + folderWorkspacePathStatuses: {} + } + : current + ) } catch (err) { console.error('Failed to fetch project groups:', err) } @@ -2021,15 +2176,25 @@ export const createRepoSlice: StateCreator = (set, fetchProjectGroupsForAllHosts: async (options) => { // Why: startup renders an all-host sidebar; replacing groups with only the active host leaves other hosts' repos visible but ungrouped. - const applyCatalog = (catalog: FetchedProjectGroupCatalog): void => { - set((s) => ({ - projectGroups: mergeFetchedProjectGroupCatalog(catalog, s.projectGroups).projectGroups, - folderWorkspacePathStatuses: {} - })) + const applyCatalog = (catalog: FetchedProjectGroupCatalog, fence: HostCatalogFence): void => { + if (!isHostCatalogFenceCurrent(get, fence)) { + return + } + set((s) => + isHostCatalogFenceCurrent(get, fence) + ? { + projectGroups: mergeFetchedProjectGroupCatalog(catalog, s.projectGroups) + .projectGroups, + folderWorkspacePathStatuses: {} + } + : s + ) } try { - applyCatalog(await fetchProjectGroupCatalogForTarget({ kind: 'local' })) + const target = { kind: 'local' as const } + const fence = claimHostCatalogFence(get, 'project-groups', target) + applyCatalog(await fetchProjectGroupCatalogForTarget(target), fence) } catch (err) { console.error('Failed to fetch local project groups for all-host load:', err) } @@ -2040,13 +2205,13 @@ export const createRepoSlice: StateCreator = (set, const environments = await listRuntimeEnvironmentsForAllHostLoad() await Promise.all( environments.map(async (environment) => { + const target = { + kind: 'environment' as const, + environmentId: environment.id + } + const fence = claimHostCatalogFence(get, 'project-groups', target) try { - applyCatalog( - await fetchProjectGroupCatalogForTarget({ - kind: 'environment', - environmentId: environment.id - }) - ) + applyCatalog(await fetchProjectGroupCatalogForTarget(target), fence) } catch (err) { console.warn(`Skipped project groups for runtime environment ${environment.id}:`, err) } @@ -2054,25 +2219,35 @@ export const createRepoSlice: StateCreator = (set, ) }, - fetchFolderWorkspaces: async () => { + fetchFolderWorkspaces: async (options) => { try { const folderWorkspaceUpdates = getFolderWorkspaceUpdateCoordinator(get) - const target = getActiveRuntimeTarget(get().settings) - const catalog = await fetchFolderWorkspaceCatalogForTarget(target) - const current = get() - folderWorkspaceUpdates.recordCatalogReplacement( - getFolderWorkspaceCatalogReplacementIds( + const target = getActiveRuntimeTarget( + settingsForRuntimeOwner(get().settings, options?.runtimeEnvironmentId) + ) + const fence = claimHostCatalogFence(get, 'folder-workspaces', target) + const catalog = await fetchFolderWorkspaceCatalogForTarget(target, get().projectGroups) + if (!isHostCatalogFenceCurrent(get, fence)) { + return + } + set((current) => { + if (!isHostCatalogFenceCurrent(get, fence)) { + return current + } + folderWorkspaceUpdates.recordCatalogReplacement( + getFolderWorkspaceCatalogReplacementIdentities( + catalog, + current.folderWorkspaces, + current.projectGroups + ) + ) + const { folderWorkspaces } = mergeFetchedFolderWorkspaceCatalog( catalog, current.folderWorkspaces, current.projectGroups ) - ) - const { folderWorkspaces } = mergeFetchedFolderWorkspaceCatalog( - catalog, - [], - current.projectGroups - ) - set({ folderWorkspaces, folderWorkspacePathStatuses: {} }) + return { folderWorkspaces, folderWorkspacePathStatuses: {} } + }) } catch (err) { console.error('Failed to fetch folder workspaces:', err) } @@ -2081,10 +2256,19 @@ export const createRepoSlice: StateCreator = (set, fetchFolderWorkspacesForAllHosts: async (options) => { const folderWorkspaceUpdates = getFolderWorkspaceUpdateCoordinator(get) // Why: folder workspaces are owned through their project groups; fetch groups first, then merge each host's folder slice. - const applyCatalog = (catalog: FetchedFolderWorkspaceCatalog): void => { + const applyCatalog = ( + catalog: FetchedFolderWorkspaceCatalog, + fence: HostCatalogFence + ): void => { + if (!isHostCatalogFenceCurrent(get, fence)) { + return + } set((current) => { + if (!isHostCatalogFenceCurrent(get, fence)) { + return current + } folderWorkspaceUpdates.recordCatalogReplacement( - getFolderWorkspaceCatalogReplacementIds( + getFolderWorkspaceCatalogReplacementIdentities( catalog, current.folderWorkspaces, current.projectGroups @@ -2103,7 +2287,9 @@ export const createRepoSlice: StateCreator = (set, let failed = false try { - applyCatalog(await fetchFolderWorkspaceCatalogForTarget({ kind: 'local' })) + const target = { kind: 'local' as const } + const fence = claimHostCatalogFence(get, 'folder-workspaces', target) + applyCatalog(await fetchFolderWorkspaceCatalogForTarget(target, get().projectGroups), fence) } catch (err) { failed = true console.error('Failed to fetch local folder workspaces for all-host load:', err) @@ -2115,12 +2301,15 @@ export const createRepoSlice: StateCreator = (set, const environments = await listRuntimeEnvironmentsForAllHostLoad() await Promise.all( environments.map(async (environment) => { + const target = { + kind: 'environment' as const, + environmentId: environment.id + } + const fence = claimHostCatalogFence(get, 'folder-workspaces', target) try { applyCatalog( - await fetchFolderWorkspaceCatalogForTarget({ - kind: 'environment', - environmentId: environment.id - }) + await fetchFolderWorkspaceCatalogForTarget(target, get().projectGroups), + fence ) } catch (err) { failed = true @@ -2196,7 +2385,9 @@ export const createRepoSlice: StateCreator = (set, scanNestedRepos: async (path, connectionId, controls) => { try { - const target = getActiveRuntimeTarget(get().settings) + const target = getActiveRuntimeTarget( + settingsForRuntimeOwner(get().settings, controls?.runtimeEnvironmentId) + ) if (target.kind === 'local') { const unsubscribe = controls?.scanId && controls.onProgress @@ -2233,9 +2424,11 @@ export const createRepoSlice: StateCreator = (set, } }, - cancelNestedRepoScan: async (scanId) => { + cancelNestedRepoScan: async (scanId, options) => { try { - const target = getActiveRuntimeTarget(get().settings) + const target = getActiveRuntimeTarget( + settingsForRuntimeOwner(get().settings, options?.runtimeEnvironmentId) + ) if (target.kind !== 'local') { return false } @@ -2248,7 +2441,9 @@ export const createRepoSlice: StateCreator = (set, importNestedRepos: async (args) => { try { - const target = getActiveRuntimeTarget(get().settings) + const target = getActiveRuntimeTarget( + settingsForRuntimeOwner(get().settings, args.runtimeEnvironmentId) + ) const result = target.kind === 'local' ? await window.api.projectGroups.importNested(args) @@ -2264,9 +2459,15 @@ export const createRepoSlice: StateCreator = (set, }, { timeoutMs: 60_000 } ) - await get().fetchProjectGroups() - await get().fetchFolderWorkspaces() - await get().fetchRepos() + const catalogOptions = + 'runtimeEnvironmentId' in args + ? { runtimeEnvironmentId: args.runtimeEnvironmentId } + : undefined + await get().fetchProjectGroups(catalogOptions) + await get().fetchFolderWorkspaces(catalogOptions) + await (args.runtimeEnvironmentId + ? get().fetchRuntimeEnvironmentRepos(args.runtimeEnvironmentId) + : get().fetchRepos(catalogOptions)) set({ folderWorkspacePathStatuses: {} }) return result } catch (err) { @@ -2337,11 +2538,12 @@ export const createRepoSlice: StateCreator = (set, { timeoutMs: 15_000 } ) ).folderWorkspace + const ownedWorkspace = folderWorkspaceWithFetchedOwner(workspace, target, get().projectGroups) set((s) => ({ - folderWorkspaces: [workspace, ...s.folderWorkspaces], + folderWorkspaces: [ownedWorkspace, ...s.folderWorkspaces], folderWorkspacePathStatuses: {} })) - return workspace + return ownedWorkspace } catch (err) { console.error('Failed to create folder workspace:', err) const { title, description } = formatFolderWorkspaceCreateError(err) @@ -2349,15 +2551,26 @@ export const createRepoSlice: StateCreator = (set, } }, - updateFolderWorkspace: async (folderWorkspaceId, updates) => { + updateFolderWorkspace: async (folderWorkspaceId, updates, options) => { const folderWorkspaceUpdates = getFolderWorkspaceUpdateCoordinator(get) const state = get() - if (!findFolderWorkspaceOwner(state, folderWorkspaceId)) { + const executionHostId = + options?.executionHostId ?? + (state.activeWorktreeId === folderWorkspaceKey(folderWorkspaceId) + ? (state.activeWorkspaceExecutionHostId ?? undefined) + : undefined) + if (!findFolderWorkspaceOwner(state, folderWorkspaceId, executionHostId)) { return false } - const runtimeEnvironmentId = getRuntimeEnvironmentIdForFolderWorkspace(state, folderWorkspaceId) + const runtimeEnvironmentId = getRuntimeEnvironmentIdForFolderWorkspace( + state, + folderWorkspaceId, + executionHostId + ) // Why: owner-scoped mutations must not follow whichever runtime happens to be focused. const target = getActiveRuntimeTarget({ activeRuntimeEnvironmentId: runtimeEnvironmentId }) + const ownerHostId = executionHostId ?? getRuntimeTargetHostId(target) + const updateIdentity = getFolderWorkspaceUpdateIdentity(ownerHostId, folderWorkspaceId) // Why: same gate as folderWorkspace.create — an older paired runtime would drop the Jira link silently. if ( target.kind === 'environment' && @@ -2371,7 +2584,7 @@ export const createRepoSlice: StateCreator = (set, ) } const updateTicket = folderWorkspaceUpdates.begin( - folderWorkspaceId, + updateIdentity, Object.keys(updates) as FolderWorkspaceUpdateField[] ) try { @@ -2390,6 +2603,8 @@ export const createRepoSlice: StateCreator = (set, await reconcileFailedFolderWorkspaceUpdate({ target, folderWorkspaceId, + updateIdentity, + ownerHostId, ticket: updateTicket, coordinator: folderWorkspaceUpdates, set, @@ -2397,12 +2612,13 @@ export const createRepoSlice: StateCreator = (set, }) return false } - const latestFields = folderWorkspaceUpdates.latestFields(folderWorkspaceId, updateTicket) - const catalogChanged = folderWorkspaceUpdates.catalogChanged(folderWorkspaceId, updateTicket) + const latestFields = folderWorkspaceUpdates.latestFields(updateIdentity, updateTicket) + const catalogChanged = folderWorkspaceUpdates.catalogChanged(updateIdentity, updateTicket) if (latestFields.length > 0) { set((s) => ({ folderWorkspaces: s.folderWorkspaces.map((workspace) => - workspace.id === folderWorkspaceId + workspace.id === folderWorkspaceId && + getFolderWorkspaceHostId(workspace, s.projectGroups) === ownerHostId ? mergeFolderWorkspaceUpdateResponse(workspace, updated, latestFields, { rejectOlderResponse: catalogChanged }) @@ -2419,6 +2635,8 @@ export const createRepoSlice: StateCreator = (set, await reconcileFailedFolderWorkspaceUpdate({ target, folderWorkspaceId, + updateIdentity, + ownerHostId, ticket: updateTicket, coordinator: folderWorkspaceUpdates, set, @@ -2426,7 +2644,7 @@ export const createRepoSlice: StateCreator = (set, }) return false } finally { - folderWorkspaceUpdates.finish(folderWorkspaceId, updateTicket) + folderWorkspaceUpdates.finish(updateIdentity, updateTicket) } }, @@ -3028,8 +3246,16 @@ export const createRepoSlice: StateCreator = (set, } await markOnboardingProjectAdded('addedFolder') // Why: focus the new folder so the add is visible; lazy-import worktree-activation to avoid a circular module load (it imports the store root). - await get().fetchWorktrees(repo.id) - const folderWorktree = get().worktreesByRepo[repo.id]?.[0] + const executionHostId = + options?.runtimeEnvironmentId === undefined + ? undefined + : options.runtimeEnvironmentId + ? toRuntimeExecutionHostId(options.runtimeEnvironmentId) + : LOCAL_EXECUTION_HOST_ID + await get().fetchWorktrees(repo.id, executionHostId ? { executionHostId } : undefined) + const folderWorktree = get().worktreesByRepo[repo.id]?.find( + (worktree) => executionHostId === undefined || worktree.hostId === executionHostId + ) if (folderWorktree) { const { activateAndRevealWorktree } = await import('../../lib/worktree-activation') const onboarding = await window.api.onboarding.get().catch(() => null) @@ -3041,6 +3267,7 @@ export const createRepoSlice: StateCreator = (set, ) activateAndRevealWorktree(folderWorktree.id, { sidebarRevealBehavior: 'auto', + ...(executionHostId ? { executionHostId } : {}), ...(startup ? { startup } : {}) }) } @@ -3219,6 +3446,7 @@ export const createRepoSlice: StateCreator = (set, activeView: 'terminal' as const, activeWorktreeId: null, activeWorkspaceKey: null, + activeWorkspaceExecutionHostId: null, activeRepoId: null } : {}) diff --git a/src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts b/src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts new file mode 100644 index 000000000..a18fbfe23 --- /dev/null +++ b/src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts @@ -0,0 +1,185 @@ +import { afterEach, describe, expect, it } from 'vitest' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { Worktree } from '../../../../shared/types' +import { getExecutionHostIdForWorktree } from '@/lib/worktree-runtime-owner' +import { useAppStore } from '@/store' + +const SAME_REPO_ID = 'same-repo' +const SAME_WORKTREE_ID = 'same-worktree' +const RUNTIME_HOST: ExecutionHostId = 'runtime:env-1' + +function worktree(path: string, hostId: ExecutionHostId): Worktree { + return { + id: SAME_WORKTREE_ID, + repoId: SAME_REPO_ID, + path, + displayName: path, + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + head: 'abc', + branch: 'refs/heads/main', + isBare: false, + isMainWorktree: true, + hostId + } +} + +afterEach(() => { + useAppStore.setState({ + repos: [], + worktreesByRepo: {}, + detectedWorktreesByRepo: {}, + projectGroups: [], + folderWorkspaces: [], + activeRepoId: null, + activeWorktreeId: null, + activeWorkspaceKey: null, + activeWorkspaceExecutionHostId: null + } as never) +}) + +describe('selected-host active workspace identity', () => { + it('selects the runtime worktree when exact IDs collide in local-first order', () => { + const local = worktree('/local/repo', 'local') + const runtime = worktree('/runtime/repo', RUNTIME_HOST) + useAppStore.setState({ + repos: [ + { + id: SAME_REPO_ID, + path: local.path, + displayName: 'local', + badgeColor: '#000', + addedAt: 1, + executionHostId: 'local' + }, + { + id: SAME_REPO_ID, + path: runtime.path, + displayName: 'runtime', + badgeColor: '#000', + addedAt: 2, + executionHostId: RUNTIME_HOST + } + ], + worktreesByRepo: { [SAME_REPO_ID]: [local, runtime] }, + refreshGitHubForWorktreeIfStale: () => undefined + }) + + const selected = useAppStore.getState().getKnownWorktreeById(SAME_WORKTREE_ID, RUNTIME_HOST) + expect(selected?.path).toBe(runtime.path) + + useAppStore.getState().setActiveWorktree(SAME_WORKTREE_ID, RUNTIME_HOST) + const state = useAppStore.getState() + expect(state.activeWorkspaceExecutionHostId).toBe(RUNTIME_HOST) + expect(getExecutionHostIdForWorktree(state, SAME_WORKTREE_ID)).toBe(RUNTIME_HOST) + }) + + it('selects the runtime worktree when exact-ID catalog order is reversed', () => { + const local = worktree('/local/repo', 'local') + const runtime = worktree('/runtime/repo', RUNTIME_HOST) + useAppStore.setState({ + repos: [ + { + id: SAME_REPO_ID, + path: runtime.path, + displayName: 'runtime', + badgeColor: '#000', + addedAt: 1, + executionHostId: RUNTIME_HOST + }, + { + id: SAME_REPO_ID, + path: local.path, + displayName: 'local', + badgeColor: '#000', + addedAt: 2, + executionHostId: 'local' + } + ], + worktreesByRepo: { [SAME_REPO_ID]: [runtime, local] } + }) + + expect(useAppStore.getState().getKnownWorktreeById(SAME_WORKTREE_ID, RUNTIME_HOST)?.path).toBe( + runtime.path + ) + }) + + it('keeps exact-ID folder and group activation on the selected runtime', () => { + useAppStore.setState({ + projectGroups: [ + { + id: 'same-group', + name: 'local', + parentPath: '/local', + executionHostId: 'local', + parentGroupId: null, + createdFrom: 'manual', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 1, + updatedAt: 1 + }, + { + id: 'same-group', + name: 'runtime', + parentPath: '/runtime', + executionHostId: RUNTIME_HOST, + parentGroupId: null, + createdFrom: 'manual', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 1, + updatedAt: 1 + } + ], + folderWorkspaces: [ + { + id: 'same-folder', + projectGroupId: 'same-group', + name: 'local', + folderPath: '/local/folder', + executionHostId: 'local', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 1, + updatedAt: 1 + }, + { + id: 'same-folder', + projectGroupId: 'same-group', + name: 'runtime', + folderPath: '/runtime/folder', + executionHostId: RUNTIME_HOST, + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 1, + updatedAt: 1 + } + ] + }) + + useAppStore.getState().setActiveFolderWorkspace('same-folder', RUNTIME_HOST) + const state = useAppStore.getState() + expect(state.activeWorkspaceExecutionHostId).toBe(RUNTIME_HOST) + expect(getExecutionHostIdForWorktree(state, 'folder:same-folder')).toBe(RUNTIME_HOST) + }) +}) diff --git a/src/renderer/src/store/slices/tabs.ts b/src/renderer/src/store/slices/tabs.ts index b38aa9800..9574cd3a6 100644 --- a/src/renderer/src/store/slices/tabs.ts +++ b/src/renderer/src/store/slices/tabs.ts @@ -974,6 +974,7 @@ export const createTabsSlice: StateCreator = (set, ? { activeWorktreeId: null, activeWorkspaceKey: null, + activeWorkspaceExecutionHostId: null, activeTabId: null, activeBrowserTabId: null, activeFileId: null, diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index 27fd094ba..2ff1dbc3c 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -837,6 +837,7 @@ type WorkspaceHydrationPatch = Pick< | 'activeRepoId' | 'activeWorktreeId' | 'activeWorkspaceKey' + | 'activeWorkspaceExecutionHostId' | 'activeTabId' | 'activeTabIdByWorktree' | 'restoredRuntimeHostIdByWorkspaceSessionKey' @@ -930,6 +931,9 @@ function targetScopedWorkspaceHydrationPatch( activeRepoId: activeOutsideScope ? state.activeRepoId : hydrated.activeRepoId, activeWorktreeId: activeOutsideScope ? state.activeWorktreeId : hydrated.activeWorktreeId, activeWorkspaceKey: activeOutsideScope ? state.activeWorkspaceKey : hydrated.activeWorkspaceKey, + activeWorkspaceExecutionHostId: activeOutsideScope + ? state.activeWorkspaceExecutionHostId + : hydrated.activeWorkspaceExecutionHostId, activeTabId: activeOutsideScope ? state.activeTabId : hydrated.activeTabId, activeTabIdByWorktree: replaceHydratedRecordKeys( state.activeTabIdByWorktree, @@ -3805,6 +3809,10 @@ export const createTerminalSlice: StateCreator ? (activeWorktreeId as WorkspaceKey) : worktreeWorkspaceKey(activeWorktreeId) : null + const activeWorkspaceExecutionHostId = + activeWorkspaceKey && session.activeWorkspaceExecutionHostId + ? session.activeWorkspaceExecutionHostId + : null const activeTabId = session.activeTabId && validTabIds.has(session.activeTabId) ? session.activeTabId : null const activeRepoId = @@ -3941,6 +3949,7 @@ export const createTerminalSlice: StateCreator activeRepoId, activeWorktreeId, activeWorkspaceKey, + activeWorkspaceExecutionHostId, activeTabId, activeTabIdByWorktree, restoredRuntimeHostIdByWorkspaceSessionKey: diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts index bb3a908f8..c10243998 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -77,6 +77,7 @@ export type WorktreeSlice = { workspaceLineageByChildKey: Record activeWorktreeId: string | null activeWorkspaceKey: WorkspaceKey | null + activeWorkspaceExecutionHostId: ExecutionHostId | null /** * In-flight / failed background worktree creations, keyed by a renderer * `creationId`. Kept separate from `worktreesByRepo` on purpose — a real @@ -146,7 +147,10 @@ export type WorktreeSlice = { (repoId: string, options?: WorktreeFetchOptions): Promise } fetchAllWorktrees: (options?: { hydrationPurge?: 'allow' | 'defer' }) => Promise - fetchWorktreeLineage: (options?: { forceLocalOwner?: boolean }) => Promise + fetchWorktreeLineage: (options?: { + forceLocalOwner?: boolean + executionHostId?: ExecutionHostId + }) => Promise updateWorktreeLineage: ( worktreeId: string, args: { parentWorktreeId?: string; noParent?: boolean } @@ -273,7 +277,7 @@ export type WorktreeSlice = { * fresh visit. */ seedActiveWorktreeLastVisitedIfMissing: () => void - setActiveWorktree: (worktreeId: string | null) => void + setActiveWorktree: (worktreeId: string | null, executionHostId?: ExecutionHostId) => void /** * Health-driven remount of one terminal tab: bumps the tab's generation so * TerminalPane unmounts, detaches (preserving a live PTY), and remounts with @@ -282,10 +286,13 @@ export type WorktreeSlice = { * undeliverable while the PTY is alive. Returns false when the tab is gone. */ remountTerminalTabForRecovery: (tabId: string) => boolean - setActiveFolderWorkspace: (folderWorkspaceId: string) => void + setActiveFolderWorkspace: (folderWorkspaceId: string, executionHostId?: ExecutionHostId) => void setRenamingWorktreeId: (request: string | WorktreeRenameRequest | null) => void allWorktrees: () => Worktree[] - getKnownWorktreeById: (worktreeId: string) => Worktree | DetectedWorktree | undefined + getKnownWorktreeById: ( + worktreeId: string, + executionHostId?: ExecutionHostId + ) => Worktree | DetectedWorktree | undefined /** * Wipes every terminal- and worktree-scoped map entry for each given id. * Called by the `worktrees:changed` listener on server-side deletions and diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index 44f45376f..cda7f0de2 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -2066,6 +2066,154 @@ describe('fetchWorktrees', () => { expect(store.getState().worktreesByRepo['same-repo']).toEqual([localWorktree]) }) + it('honors an explicit runtime owner before the repo catalog is hydrated', async () => { + const store = createTestStore() + const remote = makeWorktree({ + id: 'repo-missing::/runtime/wt', + repoId: 'repo-missing', + path: '/runtime/wt', + hostId: 'local' + }) + store.setState({ + settings: { activeRuntimeEnvironmentId: null } as never, + repos: [] + } as Partial) + runtimeEnvironmentCall.mockResolvedValue({ + id: 'rpc-missing-repo', + ok: true, + result: makeDetectedResult('repo-missing', [remote]), + _meta: { runtimeId: 'runtime-remote' } + }) + + await store.getState().fetchWorktrees('repo-missing', { + executionHostId: 'runtime:env-1', + requireAuthoritative: true + }) + + expect(runtimeEnvironmentCall).toHaveBeenCalledWith({ + selector: 'env-1', + method: 'worktree.detectedList', + params: { repo: 'repo-missing' }, + timeoutMs: 15_000 + }) + expect(mockApi.worktrees.listDetected).not.toHaveBeenCalled() + expect(store.getState().worktreesByRepo['repo-missing']).toEqual([ + { ...remote, hostId: 'runtime:env-1', runtimeOwnerEnvironmentId: 'env-1' } + ]) + }) + + it('honors an explicit SSH owner before the repo catalog is hydrated', async () => { + const store = createTestStore() + const remote = makeWorktree({ + id: 'repo-missing::/ssh/wt', + repoId: 'repo-missing', + path: '/ssh/wt', + hostId: 'local' + }) + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-ambient' } as never, + repos: [] + } as Partial) + mockApi.worktrees.listDetected.mockImplementationOnce(async (args: ListDetectedWorktreesArgs) => + qualifyDetectedResult(args, makeDetectedResult('repo-missing', [remote])) + ) + + await store.getState().fetchWorktrees('repo-missing', { + executionHostId: 'ssh:ssh-1', + requireAuthoritative: true + }) + + expect(mockApi.worktrees.listDetected).toHaveBeenCalledWith( + expect.objectContaining({ + repoId: 'repo-missing', + executionHostId: 'ssh:ssh-1', + expectedAuthority: TEST_SSH_AUTHORITY + }) + ) + expect(runtimeEnvironmentCall).not.toHaveBeenCalled() + expect(store.getState().worktreesByRepo['repo-missing']).toEqual([ + { ...remote, hostId: 'ssh:ssh-1' } + ]) + }) + + it('rejects a missing-owner SSH result after the repo catalog changes', async () => { + const store = createTestStore() + const remote = makeWorktree({ + id: 'repo-missing::/ssh/wt', + repoId: 'repo-missing', + path: '/ssh/wt' + }) + let release!: () => void + const started = new Promise((resolve) => { + mockApi.worktrees.listDetected.mockImplementationOnce( + async (args: ListDetectedWorktreesArgs) => { + resolve() + await new Promise((resume) => { + release = resume + }) + return qualifyDetectedResult(args, makeDetectedResult('repo-missing', [remote])) + } + ) + }) + + const refresh = store.getState().fetchWorktrees('repo-missing', { + executionHostId: 'ssh:ssh-1', + requireAuthoritative: true + }) + await started + store.setState({ repos: [] }) + release() + + await expect(refresh).resolves.toBe(false) + expect(store.getState().worktreesByRepo['repo-missing']).toBeUndefined() + }) + + it('rejects a missing-owner SSH result after the provider reconnects', async () => { + const store = createTestStore() + const remote = makeWorktree({ + id: 'repo-missing::/ssh/wt', + repoId: 'repo-missing', + path: '/ssh/wt' + }) + let release!: () => void + const started = new Promise((resolve) => { + mockApi.worktrees.listDetected.mockImplementationOnce( + async (args: ListDetectedWorktreesArgs) => { + resolve() + await new Promise((resume) => { + release = resume + }) + return qualifyDetectedResult(args, makeDetectedResult('repo-missing', [remote])) + } + ) + }) + + const refresh = store.getState().fetchWorktrees('repo-missing', { + executionHostId: 'ssh:ssh-1', + requireAuthoritative: true + }) + await started + store.setState({ + sshConnectionStates: new Map([ + [ + TEST_SSH_AUTHORITY.targetId, + { + targetId: TEST_SSH_AUTHORITY.targetId, + status: 'connected', + error: null, + reconnectAttempt: 0, + providerEpoch: 'provider-ssh-2' as SshProviderEpoch, + connectionGeneration: TEST_SSH_AUTHORITY.connectionGeneration + 1 + } + ] + ]) + }) + release() + + await expect(refresh).resolves.toBe(false) + expect(store.getState().worktreesByRepo['repo-missing']).toBeUndefined() + }) + it('stamps remote runtime worktrees with the owning repo runtime host', async () => { const store = createTestStore() // Why: a remote runtime returns worktrees from its own perspective, so their hostId arrives as the default "local". @@ -2667,6 +2815,31 @@ describe('worktree lineage state', () => { expect(store.getState().worktreeLineageById).toEqual({ [lineage.worktreeId]: lineage }) }) + it('pins lineage refresh to the event runtime when the default is local', async () => { + const store = createTestStore() + const lineage = makeLineage() + runtimeEnvironmentCall.mockResolvedValue({ + id: 'rpc-lineage-list', + ok: true, + result: { lineage: { [lineage.worktreeId]: lineage } }, + _meta: { runtimeId: 'runtime-remote' } + }) + store.setState({ + settings: { activeRuntimeEnvironmentId: null } as never, + worktreesByRepo: {} + } as Partial) + + await store.getState().fetchWorktreeLineage({ executionHostId: 'runtime:env-1' }) + + expect(runtimeEnvironmentCall).toHaveBeenCalledWith({ + selector: 'env-1', + method: 'worktree.lineageList', + params: undefined, + timeoutMs: 15_000 + }) + expect(mockApi.worktrees.listLineage).not.toHaveBeenCalled() + }) + it('pins lineage refresh to the local host when forceLocalOwner is set', async () => { const store = createTestStore() const lineage = makeLineage() diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index f51e76fef..cf0474554 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -120,6 +120,7 @@ import type { SshExecutionHostId } from '../../../../shared/detected-worktree-provider-contract' import type { DirectSshAuthority } from '../../../../shared/ssh-types' +import { findIndexedWorktreeOwnerForHost } from '@/lib/worktree-runtime-owner-index' export type { WorktreeSlice, WorktreeDeleteState } from './worktree-helpers' // Why: old runtime servers only have `worktree.list`; preserve the large-list UI hydration parity used before `worktree.detectedList` existed. @@ -450,7 +451,10 @@ function repoHostId( hostId?: ExecutionHostId | null ): ExecutionHostId { const repo = findRepoForHost(state.repos, repoId, { hostId, settings: state.settings }) - return repo ? getRepoExecutionHostId(repo) : LOCAL_EXECUTION_HOST_ID + if (repo) { + return getRepoExecutionHostId(repo) + } + return hostId && parseExecutionHostId(hostId) ? hostId : LOCAL_EXECUTION_HOST_ID } function repoHasExactlyOneExecutionHostOwner( @@ -807,14 +811,29 @@ function applyDetectedWorktreeUpdates( return changed ? nextByRepo : detectedWorktreesByRepo } +function folderWorkspaceMatchesHost( + workspace: Pick, + executionHostId: ExecutionHostId +): boolean { + return ( + (parseExecutionHostId(workspace.executionHostId)?.id ?? + (workspace.connectionId?.trim() + ? toSshExecutionHostId(workspace.connectionId) + : LOCAL_EXECUTION_HOST_ID)) === executionHostId + ) +} + function findKnownWorktreeById( state: Pick, - worktreeId: string + worktreeId: string, + executionHostId?: ExecutionHostId ): Worktree | DetectedWorktreeListResult['worktrees'][number] | undefined { const workspaceScope = parseWorkspaceKey(worktreeId) if (workspaceScope?.type === 'folder') { const folderWorkspace = state.folderWorkspaces.find( - (workspace) => workspace.id === workspaceScope.folderWorkspaceId + (workspace) => + workspace.id === workspaceScope.folderWorkspaceId && + (!executionHostId || folderWorkspaceMatchesHost(workspace, executionHostId)) ) if (!folderWorkspace) { return undefined @@ -827,12 +846,25 @@ function findKnownWorktreeById( folderWorkspaceWorktreeCache.set(folderWorkspace, worktree) return worktree } - const visible = findWorktreeById(state.worktreesByRepo, worktreeId) + const visible = executionHostId + ? (findIndexedWorktreeOwnerForHost( + state.worktreesByRepo, + worktreeId, + executionHostId + ) as Worktree | null) + : findWorktreeById(state.worktreesByRepo, worktreeId) if (visible) { return visible } for (const result of Object.values(state.detectedWorktreesByRepo)) { - const detected = result.worktrees.find((worktree) => worktree.id === worktreeId) + const detected = result.worktrees.find( + (worktree) => + worktree.id === worktreeId && + (!executionHostId || + worktreeMatchesHost(worktree, executionHostId, { + unhostedWorktreesMatchHost: executionHostId === LOCAL_EXECUTION_HOST_ID + })) + ) if (detected) { return detected } @@ -981,13 +1013,25 @@ function replaceWorktreeInRepoLists( function settingsForRepoOwner( state: Pick, repoId: string, - hostId?: ExecutionHostId | null + hostId?: ExecutionHostId | null, + honorMissingHostId = false ) { const repo = findRepoForHost(state.repos, repoId, { hostId, settings: state.settings }) - if (!repo) { - return state.settings + if (repo) { + return settingsForKnownRepoOwner(state.settings, repo) } - return settingsForKnownRepoOwner(state.settings, repo) + const parsedHost = honorMissingHostId && hostId ? parseExecutionHostId(hostId) : null + if (parsedHost?.kind === 'runtime') { + return state.settings + ? { ...state.settings, activeRuntimeEnvironmentId: parsedHost.environmentId } + : ({ activeRuntimeEnvironmentId: parsedHost.environmentId } as AppState['settings']) + } + if (parsedHost?.kind === 'local' || parsedHost?.kind === 'ssh') { + return state.settings + ? { ...state.settings, activeRuntimeEnvironmentId: null } + : ({ activeRuntimeEnvironmentId: null } as AppState['settings']) + } + return state.settings } function settingsForKnownRepoOwner( @@ -2703,6 +2747,7 @@ function buildWorktreePurgeState(s: AppState, worktreeIds: string[]): Partial { if (s.activeWorkspaceKey && worktreeIdSet.has(s.activeWorkspaceKey)) { return null @@ -2811,6 +2856,7 @@ type FencedWorktreeMergeArgs = { repoId: string hostId: ExecutionHostId ownerWasMissingAtStart: boolean + missingDirectSshOwnerReposSnapshot?: AppState['repos'] requestStartedWorktrees: readonly Worktree[] | undefined setup?: ProjectHostSetup refresh: AdmittedDetectedWorktreeRefresh @@ -2829,7 +2875,8 @@ function mergeFetchedWorktrees( s, args.repoId, args.hostId, - args.ownerWasMissingAtStart && !args.refresh.directSshAuthority + args.ownerWasMissingAtStart && + (!args.refresh.directSshAuthority || s.repos === args.missingDirectSshOwnerReposSnapshot) ) ) { return s @@ -3017,6 +3064,7 @@ export const createWorktreeSlice: StateCreator workspaceLineageByChildKey: {}, activeWorktreeId: null, activeWorkspaceKey: null, + activeWorkspaceExecutionHostId: null, pendingWorktreeCreations: {}, activePendingCreationId: null, renamingWorktreeId: null, @@ -3127,7 +3175,12 @@ export const createWorktreeSlice: StateCreator hostId, settings: ownerState.settings }) - const ownerSettings = settingsForRepoOwner(ownerState, repoId, hostId) + const ownerSettings = settingsForRepoOwner( + ownerState, + repoId, + hostId, + ownerWasMissingAtStart && (useLocalOwner || options?.executionHostId !== undefined) + ) const settings = useLocalOwner && ownerSettings?.activeRuntimeEnvironmentId ? { ...ownerSettings, activeRuntimeEnvironmentId: null } @@ -3157,6 +3210,10 @@ export const createWorktreeSlice: StateCreator repoId, hostId, ownerWasMissingAtStart, + missingDirectSshOwnerReposSnapshot: + ownerWasMissingAtStart && options?.executionHostId === hostId + ? ownerState.repos + : undefined, requestStartedWorktrees, setup, refresh @@ -3340,12 +3397,18 @@ export const createWorktreeSlice: StateCreator try { // Why: lineage is a focused-host refresh; host-merge so other hosts' fetched lineage is preserved. const ownerSettings = get().settings - // Why: local worktree-change events while a runtime is focused are paired - // with a forced-local list refresh; lineage must follow the same owner. - const settings = - options?.forceLocalOwner && ownerSettings?.activeRuntimeEnvironmentId - ? { ...ownerSettings, activeRuntimeEnvironmentId: null } - : ownerSettings + const parsedHost = options?.executionHostId + ? parseExecutionHostId(options.executionHostId) + : null + const activeRuntimeEnvironmentId = + parsedHost?.kind === 'runtime' + ? parsedHost.environmentId + : parsedHost || options?.forceLocalOwner + ? null + : ownerSettings?.activeRuntimeEnvironmentId + const settings = ownerSettings + ? { ...ownerSettings, activeRuntimeEnvironmentId } + : ({ activeRuntimeEnvironmentId } as AppState['settings']) await refreshWorktreeLineageForSettings(settings, set, { reuseRecentCompatibilityFailure: true }) @@ -4206,6 +4269,9 @@ export const createWorktreeSlice: StateCreator return next })(), activeWorktreeId: removedActiveWorktree ? null : s.activeWorktreeId, + activeWorkspaceExecutionHostId: removedActiveWorktree + ? null + : s.activeWorkspaceExecutionHostId, activeTabId: s.activeTabId && tabIds.has(s.activeTabId) ? null : s.activeTabId, openFiles: newOpenFiles, browserTabsByWorktree: nextBrowserTabsByWorktree, @@ -5041,8 +5107,11 @@ export const createWorktreeSlice: StateCreator changed = true } } - const patch: { lastVisitedAtByWorktreeId?: Record; activeWorktreeId?: null } = - {} + const patch: { + lastVisitedAtByWorktreeId?: Record + activeWorktreeId?: null + activeWorkspaceExecutionHostId?: null + } = {} if (changed) { patch.lastVisitedAtByWorktreeId = next } @@ -5059,6 +5128,7 @@ export const createWorktreeSlice: StateCreator const activeRepoWorktreeIds = validIdsByRepo.get(getRepoIdFromWorktreeId(activeId)) if (activeRepoWorktreeIds && !activeRepoWorktreeIds.has(activeId)) { patch.activeWorktreeId = null + patch.activeWorkspaceExecutionHostId = null } } return Object.keys(patch).length > 0 ? patch : {} @@ -5121,7 +5191,7 @@ export const createWorktreeSlice: StateCreator return remounted }, - setActiveWorktree: (worktreeId) => { + setActiveWorktree: (worktreeId, executionHostId) => { const workspaceScope = worktreeId ? parseWorkspaceKey(worktreeId) : null if (worktreeId && shouldDeferActivationTerminalPrep()) { markInputQuietSchedulerInput() @@ -5141,12 +5211,13 @@ export const createWorktreeSlice: StateCreator return { activeWorktreeId: null, activeWorkspaceKey: null, + activeWorkspaceExecutionHostId: null, // Why: clearing/activating a worktree must dismiss the background-creation panel so the user isn't stranded on it. activePendingCreationId: null } } - const worktree = findKnownWorktreeById(s, worktreeId) + const worktree = findKnownWorktreeById(s, worktreeId, executionHostId) shouldClearUnread = Boolean(worktree?.isUnread) // Why: Search lives under Explorer, so the files/search sub-route must switch with the worktree, not leak the prior one. @@ -5313,6 +5384,7 @@ export const createWorktreeSlice: StateCreator : { ...s.activeTabTypeByWorktree, [worktreeId]: activeTabType } const hasStateChange = s.activeWorktreeId !== worktreeId || + s.activeWorkspaceExecutionHostId !== (executionHostId ?? null) || // Why: a pending-creation panel can show over the prior worktree; a non-null activePendingCreationId counts as a change. s.activePendingCreationId !== null || s.activeFileId !== activeFileId || @@ -5337,6 +5409,7 @@ export const createWorktreeSlice: StateCreator activeWorkspaceKey: isWorkspaceKey(worktreeId) ? worktreeId : worktreeWorkspaceKey(worktreeId), + activeWorkspaceExecutionHostId: executionHostId ?? null, activePendingCreationId: null, activeFileId, activeBrowserTabId, @@ -5410,7 +5483,7 @@ export const createWorktreeSlice: StateCreator get().refreshGitHubForWorktreeIfStale(worktreeId) } - if (!worktreeId || !get().getKnownWorktreeById(worktreeId)) { + if (!worktreeId || !get().getKnownWorktreeById(worktreeId, executionHostId)) { return } @@ -5428,9 +5501,9 @@ export const createWorktreeSlice: StateCreator } }, - setActiveFolderWorkspace: (folderWorkspaceId) => { + setActiveFolderWorkspace: (folderWorkspaceId, executionHostId) => { const workspaceKey = folderWorkspaceKey(folderWorkspaceId) - const workspace = get().folderWorkspaces.find((entry) => entry.id === folderWorkspaceId) + const workspace = findKnownWorktreeById(get(), workspaceKey, executionHostId) if (!workspace) { return } @@ -5516,6 +5589,7 @@ export const createWorktreeSlice: StateCreator activeRepoId: null, activeWorktreeId: workspaceKey, activeWorkspaceKey: workspaceKey, + activeWorkspaceExecutionHostId: executionHostId ?? null, activePendingCreationId: null, activeFileId, activeBrowserTabId, @@ -5528,19 +5602,27 @@ export const createWorktreeSlice: StateCreator everActivatedWorktreeIds: nextEverActivated, folderWorkspaces: workspace.isUnread ? s.folderWorkspaces.map((entry) => - entry.id === folderWorkspaceId ? { ...entry, isUnread: false } : entry + entry.id === folderWorkspaceId && + (!executionHostId || folderWorkspaceMatchesHost(entry, executionHostId)) + ? { ...entry, isUnread: false } + : entry ) : s.folderWorkspaces } }) if (workspace.isUnread) { - void get().updateFolderWorkspace(folderWorkspaceId, { isUnread: false }) + void get().updateFolderWorkspace( + folderWorkspaceId, + { isUnread: false }, + executionHostId ? { executionHostId } : undefined + ) } }, allWorktrees: () => Object.values(get().worktreesByRepo).flat(), - getKnownWorktreeById: (worktreeId) => findKnownWorktreeById(get(), worktreeId), + getKnownWorktreeById: (worktreeId, executionHostId) => + findKnownWorktreeById(get(), worktreeId, executionHostId), purgeWorktreeTerminalState: (worktreeIds: string[]) => { const purgeableWorktreeIds = worktreeIds.filter((id) => id !== FLOATING_TERMINAL_WORKTREE_ID) diff --git a/src/shared/folder-workspace-worktree.ts b/src/shared/folder-workspace-worktree.ts index 0eb224237..0b427f424 100644 --- a/src/shared/folder-workspace-worktree.ts +++ b/src/shared/folder-workspace-worktree.ts @@ -1,5 +1,6 @@ import type { FolderWorkspace, Worktree } from './types' import { folderWorkspaceKey } from './workspace-scope' +import { toSshExecutionHostId } from './execution-host' export function folderWorkspaceToWorktree(folderWorkspace: FolderWorkspace): Worktree { const linkedTask = folderWorkspace.linkedTask @@ -37,6 +38,9 @@ export function folderWorkspaceToWorktree(folderWorkspace: FolderWorkspace): Wor branch: '', isBare: false, isSparse: false, - isMainWorktree: false + isMainWorktree: false, + hostId: + folderWorkspace.executionHostId ?? + (folderWorkspace.connectionId ? toSshExecutionHostId(folderWorkspace.connectionId) : 'local') } } diff --git a/src/shared/pr-check-status.ts b/src/shared/pr-check-status.ts index bf7dd5f08..2f8e68e15 100644 --- a/src/shared/pr-check-status.ts +++ b/src/shared/pr-check-status.ts @@ -45,7 +45,11 @@ function normalizeRollupCheck(raw: RawCheckRollup, index: number): PRCheckDetail conclusion === 'error' || conclusion === 'startup_failure' ? 'failure' : conclusion || - (state === 'failure' || state === 'error' ? 'failure' : state === 'success' ? 'success' : '') + (state === 'failure' || state === 'error' + ? 'failure' + : state === 'success' + ? 'success' + : '') const isPending = status === 'queued' || status === 'in_progress' || diff --git a/src/shared/types.ts b/src/shared/types.ts index fa6ca7b9f..f713ada06 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -328,6 +328,8 @@ export type FolderWorkspace = { folderPath: string /** SSH target ID for folder workspaces whose folder path lives remotely. */ connectionId?: string | null + /** Renderer-owned host stamp for host-qualified folder catalogs. */ + executionHostId?: ExecutionHostId | null linkedTask: WorkspaceLinkedItem | null linkedTaskSourceContext?: TaskSourceContext | null comment: string @@ -1117,6 +1119,7 @@ export type WorkspaceSessionState = { activeRepoId: string | null /** Scope-aware active owner for folder workspaces. Legacy worktree UI still reads activeWorktreeId. */ activeWorkspaceKey?: WorkspaceKey | null + activeWorkspaceExecutionHostId?: ExecutionHostId | null activeWorktreeId: string | null activeTabId: string | null /** Keys may be legacy raw worktree IDs or canonical WorkspaceKey values. */ diff --git a/src/shared/workspace-session-schema.ts b/src/shared/workspace-session-schema.ts index 72ebd026e..da5fe4ef0 100644 --- a/src/shared/workspace-session-schema.ts +++ b/src/shared/workspace-session-schema.ts @@ -18,6 +18,7 @@ import type { WorkspaceSessionState } from './types' import { isValidTerminalTabId } from './terminal-tab-id' +import { parseExecutionHostId, type ExecutionHostId } from './execution-host' import { isTuiAgent } from './tui-agent-config' import { normalizeBrowserHistoryEntries } from './workspace-session-browser-history' import { isWorkspaceKey } from './workspace-scope' @@ -250,6 +251,12 @@ const browserHistoryEntriesSchema = z export const workspaceSessionStateSchema: z.ZodType = z.object({ activeRepoId: z.string().nullable(), activeWorkspaceKey: workspaceKeySchema.nullable().optional(), + activeWorkspaceExecutionHostId: z + .custom( + (value) => typeof value === 'string' && Boolean(parseExecutionHostId(value)) + ) + .nullable() + .optional(), activeWorktreeId: z.string().nullable(), activeTabId: z.string().nullable(), tabsByWorktree: z.record(z.string(), z.array(terminalTabSchema)), diff --git a/src/shared/workspace-session-terminal-tab-close.ts b/src/shared/workspace-session-terminal-tab-close.ts index 2b0b17a9d..e5f2d6cd2 100644 --- a/src/shared/workspace-session-terminal-tab-close.ts +++ b/src/shared/workspace-session-terminal-tab-close.ts @@ -265,6 +265,7 @@ export function closeTerminalTabInWorkspaceSession( if (!hasSurface) { next.activeWorktreeId = null next.activeWorkspaceKey = null + next.activeWorkspaceExecutionHostId = null } } if ((next.tabsByWorktree[worktreeId]?.length ?? 0) === 0) { diff --git a/tests/e2e/pr11346-selected-runtime-add.spec.ts b/tests/e2e/pr11346-selected-runtime-add.spec.ts new file mode 100644 index 000000000..f4e86d8b0 --- /dev/null +++ b/tests/e2e/pr11346-selected-runtime-add.spec.ts @@ -0,0 +1,757 @@ +import { rmSync } from 'node:fs' +import path from 'node:path' +import type { ElectronApplication, Locator, Page, TestInfo } from '@stablyai/playwright-test' +import { RuntimeClient } from '../../src/cli/runtime/client' +import type { FolderWorkspace, ProjectGroup, Repo } from '../../src/shared/types' +import { expect, test } from './helpers/orca-app' +import { + createRuntimeDesktopPairingOffer, + launchPairedElectronClient +} from './helpers/paired-electron-client' +import { waitForSessionReady } from './helpers/store' +import { + configureIsolatedGitIdentity, + createProjectFixtures, + expectRuntimeActivation, + injectSameIdLocalActivationCollision, + installFinalActivationGate +} from './pr11346-selected-runtime-identity-oracle' + +async function selectRuntimeHost(page: Page, runtimeName: string): Promise { + await page + .getByRole('button', { name: /Add Project/i }) + .first() + .click() + const dialog = page.getByRole('dialog', { name: /Add a project/i }) + await expect(dialog).toBeVisible() + const hostPicker = dialog.getByRole('combobox') + if (!(await hostPicker.textContent())?.includes(runtimeName)) { + await hostPicker.click() + await page.locator('[cmdk-item]').filter({ hasText: runtimeName }).click() + } + await expect(hostPicker).toContainText(runtimeName) + return dialog +} + +async function selectRuntimeHostAndOpenManualPath( + page: Page, + runtimeName: string +): Promise { + const dialog = await selectRuntimeHost(page, runtimeName) + await dialog.getByRole('button', { name: /Browse folder|Browse host/i }).click() + const browseDialog = page.getByRole('dialog', { name: /Browse host filesystem/i }) + await expect(browseDialog).toBeVisible() + await browseDialog.getByRole('button', { name: /^Cancel$/i }).click() + const manualDialog = page.getByRole('dialog', { name: /Open host project/i }) + await expect(manualDialog.locator('#server-project-path')).toBeVisible() + return manualDialog +} + +async function listRuntimeInventory(client: RuntimeClient): Promise<{ + folderWorkspaces: FolderWorkspace[] + projectGroups: ProjectGroup[] + repos: Repo[] +}> { + const [repoResult, folderResult, projectGroupResult] = await Promise.all([ + client.call<{ repos: Repo[] }>('repo.list'), + client.call<{ folderWorkspaces: FolderWorkspace[] }>('folderWorkspace.list'), + client.call<{ groups: ProjectGroup[] }>('projectGroup.list') + ]) + return { + repos: repoResult.result.repos, + folderWorkspaces: folderResult.result.folderWorkspaces, + projectGroups: projectGroupResult.result.groups + } +} + +async function setActiveRuntimePreference(page: Page, environmentId: string | null): Promise { + const selected = await page.evaluate(async (nextEnvironmentId) => { + const next = await window.api.settings.setActiveRuntimeEnvironmentPreference({ + environmentId: nextEnvironmentId + }) + window.__store?.setState({ settings: next }) + return next.activeRuntimeEnvironmentId + }, environmentId) + expect(selected).toBe(environmentId) +} + +async function runSelectedRuntimeAddJourney( + electronApp: ElectronApplication, + orcaPage: Page, + testInfo: TestInfo, + visible: boolean +): Promise { + const runtimeName = `PR 11346 ${visible ? 'headed' : 'hidden-window'} runtime` + const fixture = await createProjectFixtures() + await waitForSessionReady(orcaPage) + const serverVisible = await electronApp.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows().some((window) => window.isVisible()) + ) + expect(serverVisible).toBe(visible) + configureIsolatedGitIdentity(await electronApp.evaluate(({ app }) => app.getPath('home'))) + + const offer = await createRuntimeDesktopPairingOffer(orcaPage) + const client = await launchPairedElectronClient(offer, testInfo, runtimeName) + const serverUserDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) + const clientUserDataDir = await client.app.evaluate(({ app }) => app.getPath('userData')) + const serverRuntime = new RuntimeClient(serverUserDataDir) + const clientLocalRuntime = new RuntimeClient(clientUserDataDir) + + try { + const measurements: Record = {} + if (visible) { + await client.app.evaluate(({ BrowserWindow }) => { + BrowserWindow.getAllWindows()[0]?.show() + }) + expect( + await client.app.evaluate( + ({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible() ?? false + ) + ).toBe(true) + } + let startedAt = Date.now() + await setActiveRuntimePreference(client.page, null) + await setActiveRuntimePreference(client.page, client.environmentId) + await setActiveRuntimePreference(client.page, null) + measurements.runtimeSwitchMs = Date.now() - startedAt + + const initialServerInventory = await listRuntimeInventory(serverRuntime) + const initialClientInventory = await listRuntimeInventory(clientLocalRuntime) + expect(initialServerInventory.repos.map((repo) => repo.path)).not.toContain(fixture.gitPath) + expect(initialClientInventory.repos.map((repo) => repo.path)).not.toContain(fixture.gitPath) + + startedAt = Date.now() + await installFinalActivationGate(client.page, fixture.gitPath) + const gitDialog = await selectRuntimeHostAndOpenManualPath(client.page, runtimeName) + await gitDialog.locator('#server-project-path').fill(fixture.gitPath) + await gitDialog.getByRole('button', { name: /Add Git Project/i }).click() + const gitCollision = await injectSameIdLocalActivationCollision( + client.page, + fixture.gitPath, + fixture.localCloneCollisionPath + ) + await expect(gitDialog).toBeHidden({ timeout: 30_000 }) + measurements.gitAddMs = Date.now() - startedAt + + startedAt = Date.now() + await installFinalActivationGate(client.page, fixture.folderPath) + const folderDialog = await selectRuntimeHostAndOpenManualPath(client.page, runtimeName) + await folderDialog.locator('#server-project-path').fill(fixture.folderPath) + await folderDialog.getByRole('button', { name: /Open as Folder/i }).click() + const folderCollision = await injectSameIdLocalActivationCollision( + client.page, + fixture.folderPath, + fixture.localCreateCollisionPath + ) + await expect(folderDialog).toBeHidden({ timeout: 30_000 }) + measurements.folderAddMs = Date.now() - startedAt + + startedAt = Date.now() + await installFinalActivationGate(client.page, fixture.clonedRepoPath) + const cloneDialog = await selectRuntimeHost(client.page, runtimeName) + await cloneDialog.getByRole('button', { name: /Clone from URL/i }).click() + const cloneStep = client.page.getByRole('dialog', { name: /Clone from URL/i }) + await cloneStep.getByRole('textbox').nth(0).fill(fixture.gitPath) + await cloneStep.getByRole('textbox').nth(1).fill(fixture.cloneParentPath) + await cloneStep.getByRole('button', { name: /^Clone$/i }).click() + const cloneCollision = await injectSameIdLocalActivationCollision( + client.page, + fixture.clonedRepoPath, + fixture.localCloneCollisionPath + ) + await expect(cloneStep).toBeHidden({ timeout: 30_000 }) + await expectRuntimeActivation(client.page, cloneCollision) + measurements.cloneMs = Date.now() - startedAt + + startedAt = Date.now() + await installFinalActivationGate(client.page, fixture.createdRepoPath) + const createDialog = await selectRuntimeHost(client.page, runtimeName) + await createDialog.getByRole('button', { name: /Create (?:on host|new project)/i }).click() + const createStep = client.page.getByRole('dialog', { name: /Create a new project/i }) + await createStep.locator('#create-project-name').fill('runtime-created-project') + await createStep.getByPlaceholder('/home/user/projects').fill(fixture.createParentPath) + await createStep.getByRole('button', { name: 'Create project', exact: true }).click() + const createCollision = await injectSameIdLocalActivationCollision( + client.page, + fixture.createdRepoPath, + fixture.localCreateCollisionPath + ) + await expect(createStep).toBeHidden({ timeout: 30_000 }) + await expectRuntimeActivation(client.page, createCollision) + measurements.createMs = Date.now() - startedAt + + startedAt = Date.now() + const reconnectCatalog = await client.page.evaluate( + async ({ environmentId, reconnectCatalogPath }) => { + const store = window.__store + if (!store) { + throw new Error('Renderer store unavailable') + } + const oldRequests = [ + store.getState().fetchProjectGroups({ runtimeEnvironmentId: environmentId }), + store.getState().fetchFolderWorkspaces({ runtimeEnvironmentId: environmentId }) + ] + await window.api.runtimeEnvironments.disconnect({ selector: environmentId }) + store.getState().setRuntimeEnvironmentStatus(environmentId, { + status: null, + checkedAt: Date.now() + }) + const response = await window.api.runtimeEnvironments.connect({ + selector: environmentId, + timeoutMs: 15_000 + }) + if (!response.ok) { + throw new Error(response.error.message) + } + store.getState().setRuntimeEnvironmentStatus(environmentId, { + status: response.result, + checkedAt: Date.now() + }) + const groupResponse = await window.api.runtimeEnvironments.call({ + selector: environmentId, + method: 'projectGroup.create', + params: { + name: 'Reconnect catalog', + parentPath: reconnectCatalogPath, + createdFrom: 'manual' + }, + timeoutMs: 15_000 + }) + if (!groupResponse.ok) { + throw new Error(groupResponse.error.message) + } + const group = (groupResponse.result as { group: ProjectGroup }).group + const folderResponse = await window.api.runtimeEnvironments.call({ + selector: environmentId, + method: 'folderWorkspace.create', + params: { + folderPath: reconnectCatalogPath, + name: 'Reconnect catalog workspace', + projectGroupId: group.id + }, + timeoutMs: 15_000 + }) + if (!folderResponse.ok) { + throw new Error(folderResponse.error.message) + } + await store.getState().fetchProjectGroups({ runtimeEnvironmentId: environmentId }) + await store.getState().fetchFolderWorkspaces({ runtimeEnvironmentId: environmentId }) + await Promise.allSettled(oldRequests) + if (!(await store.getState().refreshRuntimeEnvironmentStatus(environmentId))) { + throw new Error('Paired runtime did not recover after reconnect') + } + return { + folder: store + .getState() + .folderWorkspaces.find((workspace) => workspace.folderPath === reconnectCatalogPath), + group: store + .getState() + .projectGroups.find((entry) => entry.parentPath === reconnectCatalogPath) + } + }, + { + environmentId: client.environmentId, + reconnectCatalogPath: fixture.reconnectCatalogPath + } + ) + expect(reconnectCatalog).toEqual({ + folder: expect.objectContaining({ + executionHostId: `runtime:${client.environmentId}`, + folderPath: fixture.reconnectCatalogPath + }), + group: expect.objectContaining({ + executionHostId: `runtime:${client.environmentId}`, + parentPath: fixture.reconnectCatalogPath + }) + }) + await setActiveRuntimePreference(client.page, client.environmentId) + await setActiveRuntimePreference(client.page, null) + measurements.reconnectMs = Date.now() - startedAt + + startedAt = Date.now() + const nestedDialog = await selectRuntimeHostAndOpenManualPath(client.page, runtimeName) + await nestedDialog.locator('#server-project-path').fill(fixture.nestedParentPath) + await nestedDialog.getByRole('button', { name: /Add Git Project/i }).click() + const importDialog = client.page.getByRole('dialog', { + name: /Import repositories from folder/i + }) + await expect(importDialog.getByText('nested-api', { exact: true }).first()).toBeVisible({ + timeout: 30_000 + }) + await expect(importDialog.getByText('nested-web', { exact: true }).first()).toBeVisible() + await importDialog.getByRole('button', { name: 'Yes, import as group', exact: true }).click() + await expect(importDialog).toBeHidden({ timeout: 30_000 }) + measurements.nestedImportMs = Date.now() - startedAt + + const remoteBrowse = await client.page.evaluate( + async ({ environmentId, rootPath }) => { + const response = await window.api.runtimeEnvironments.call({ + selector: environmentId, + method: 'files.browseServerDir', + params: { path: rootPath }, + timeoutMs: 15_000 + }) + if (!response.ok) { + throw new Error(response.error.message) + } + return response.result as { entries: { name: string; isDirectory: boolean }[] } + }, + { environmentId: client.environmentId, rootPath: fixture.rootPath } + ) + expect(remoteBrowse.entries).toEqual( + expect.arrayContaining([ + expect.objectContaining({ name: path.basename(fixture.gitPath), isDirectory: true }), + expect.objectContaining({ name: path.basename(fixture.folderPath), isDirectory: true }), + expect.objectContaining({ + name: path.basename(fixture.nestedParentPath), + isDirectory: true + }) + ]) + ) + + await expect + .poll(async () => { + const inventory = await listRuntimeInventory(serverRuntime) + return { + groupParentPaths: inventory.projectGroups.map((group) => group.parentPath), + repoPaths: inventory.repos.map((repo) => repo.path) + } + }) + .toEqual({ + groupParentPaths: expect.arrayContaining([fixture.nestedParentPath]), + repoPaths: expect.arrayContaining([ + fixture.gitPath, + fixture.folderPath, + fixture.clonedRepoPath, + fixture.createdRepoPath, + ...fixture.nestedRepoPaths + ]) + }) + + const runtimeCatalog = await listRuntimeInventory(serverRuntime) + const runtimeGroup = runtimeCatalog.projectGroups.find( + (group) => group.parentPath === fixture.nestedParentPath + ) + if (!runtimeGroup) { + throw new Error('Runtime project group unavailable for folder catalog boundary') + } + await serverRuntime.call('folderWorkspace.create', { + folderPath: fixture.catalogFolderPath, + name: 'Runtime catalog workspace', + projectGroupId: runtimeGroup.id + }) + expect( + (await listRuntimeInventory(serverRuntime)).folderWorkspaces.map( + (workspace) => workspace.folderPath + ) + ).toContain(fixture.catalogFolderPath) + + const sameIdCatalog = await client.page.evaluate( + async ({ + catalogFolderPath, + localGroupPath, + localWorkspacePath, + nestedParentPath, + runtimeEnvironmentId + }) => { + const store = window.__store + if (!store) { + throw new Error('Renderer store unavailable') + } + await store.getState().fetchProjectGroups({ runtimeEnvironmentId }) + await store.getState().fetchFolderWorkspaces({ runtimeEnvironmentId }) + const state = store.getState() + const runtimeGroup = state.projectGroups.find( + (group) => + group.parentPath === nestedParentPath && + group.executionHostId === `runtime:${runtimeEnvironmentId}` + ) + const runtimeFolder = state.folderWorkspaces.find( + (workspace) => + workspace.folderPath === catalogFolderPath && + workspace.executionHostId === `runtime:${runtimeEnvironmentId}` + ) + if (!runtimeGroup || !runtimeFolder) { + throw new Error('Runtime catalog unavailable for same-ID collision') + } + const localGroup = { + ...runtimeGroup, + name: 'Local same-ID group', + parentPath: localGroupPath, + executionHostId: 'local' as const + } + const localFolder = { + ...runtimeFolder, + name: 'Local same-ID folder', + folderPath: localWorkspacePath, + executionHostId: 'local' as const + } + store.setState({ + projectGroups: [localGroup, ...state.projectGroups], + folderWorkspaces: [localFolder, ...state.folderWorkspaces] + }) + await store.getState().fetchProjectGroups({ runtimeEnvironmentId }) + await store.getState().fetchFolderWorkspaces({ runtimeEnvironmentId }) + const collided = store.getState() + const result = { + folders: collided.folderWorkspaces + .filter((workspace) => workspace.id === runtimeFolder.id) + .map((workspace) => ({ + executionHostId: workspace.executionHostId, + folderPath: workspace.folderPath + })), + groups: collided.projectGroups + .filter((group) => group.id === runtimeGroup.id) + .map((group) => ({ + executionHostId: group.executionHostId, + parentPath: group.parentPath + })) + } + return result + }, + { + catalogFolderPath: fixture.catalogFolderPath, + localGroupPath: fixture.localCloneCollisionPath, + localWorkspacePath: fixture.localCreateCollisionPath, + nestedParentPath: fixture.nestedParentPath, + runtimeEnvironmentId: client.environmentId + } + ) + expect(sameIdCatalog).toEqual({ + folders: expect.arrayContaining([ + { + executionHostId: 'local', + folderPath: fixture.localCreateCollisionPath + }, + { + executionHostId: `runtime:${client.environmentId}`, + folderPath: fixture.catalogFolderPath + } + ]), + groups: expect.arrayContaining([ + { + executionHostId: 'local', + parentPath: fixture.localCloneCollisionPath + }, + { + executionHostId: `runtime:${client.environmentId}`, + parentPath: fixture.nestedParentPath + } + ]) + }) + + const reversedFolderActivation = await client.page.evaluate( + ({ catalogFolderPath, runtimeEnvironmentId }) => { + const store = window.__store + if (!store) { + throw new Error('Renderer store unavailable') + } + const hostId = `runtime:${runtimeEnvironmentId}` as const + const state = store.getState() + const runtimeFolder = state.folderWorkspaces.find( + (workspace) => + workspace.folderPath === catalogFolderPath && workspace.executionHostId === hostId + ) + if (!runtimeFolder) { + throw new Error('Runtime folder unavailable for reversed activation') + } + const sameFolders = state.folderWorkspaces + .filter((workspace) => workspace.id === runtimeFolder.id) + .toReversed() + const sameGroups = state.projectGroups + .filter((group) => group.id === runtimeFolder.projectGroupId) + .toReversed() + store.setState({ + folderWorkspaces: [ + ...state.folderWorkspaces.filter((workspace) => workspace.id !== runtimeFolder.id), + ...sameFolders + ], + projectGroups: [ + ...state.projectGroups.filter((group) => group.id !== runtimeFolder.projectGroupId), + ...sameGroups + ] + }) + store.getState().setActiveFolderWorkspace(runtimeFolder.id, hostId) + const activated = store.getState() + return { + activeHostId: activated.activeWorkspaceExecutionHostId, + activePath: activated.getKnownWorktreeById(`folder:${runtimeFolder.id}`, hostId)?.path, + sameIdHosts: activated.folderWorkspaces + .filter((workspace) => workspace.id === runtimeFolder.id) + .map((workspace) => workspace.executionHostId) + .sort() + } + }, + { + catalogFolderPath: fixture.catalogFolderPath, + runtimeEnvironmentId: client.environmentId + } + ) + expect(reversedFolderActivation).toEqual({ + activeHostId: `runtime:${client.environmentId}`, + activePath: fixture.catalogFolderPath, + sameIdHosts: ['local', `runtime:${client.environmentId}`] + }) + + const collisionReconnect = await client.page.evaluate( + async ({ catalogFolderPath, environmentId }) => { + const store = window.__store + if (!store) { + throw new Error('Renderer store unavailable') + } + const runtimeFolder = store + .getState() + .folderWorkspaces.find((workspace) => workspace.folderPath === catalogFolderPath) + if (!runtimeFolder) { + throw new Error('Runtime folder unavailable before collision reconnect') + } + const staleRequests = [ + store.getState().fetchProjectGroups({ runtimeEnvironmentId: environmentId }), + store.getState().fetchFolderWorkspaces({ runtimeEnvironmentId: environmentId }) + ] + await window.api.runtimeEnvironments.disconnect({ selector: environmentId }) + store.getState().setRuntimeEnvironmentStatus(environmentId, { + status: null, + checkedAt: Date.now() + }) + const response = await window.api.runtimeEnvironments.connect({ + selector: environmentId, + timeoutMs: 15_000 + }) + if (!response.ok) { + throw new Error(response.error.message) + } + store.getState().setRuntimeEnvironmentStatus(environmentId, { + status: response.result, + checkedAt: Date.now() + }) + await store.getState().fetchProjectGroups({ runtimeEnvironmentId: environmentId }) + await store.getState().fetchFolderWorkspaces({ runtimeEnvironmentId: environmentId }) + await Promise.allSettled(staleRequests) + if (!(await store.getState().refreshRuntimeEnvironmentStatus(environmentId))) { + throw new Error('Paired runtime did not recover after collision reconnect') + } + store.getState().setActiveFolderWorkspace(runtimeFolder.id, `runtime:${environmentId}`) + const state = store.getState() + return { + activeHostId: state.activeWorkspaceExecutionHostId, + folderHosts: state.folderWorkspaces + .filter((workspace) => workspace.id === runtimeFolder.id) + .map((workspace) => workspace.executionHostId) + .sort(), + groupHosts: state.projectGroups + .filter((group) => group.id === runtimeFolder.projectGroupId) + .map((group) => group.executionHostId) + .sort() + } + }, + { + catalogFolderPath: fixture.catalogFolderPath, + environmentId: client.environmentId + } + ) + expect(collisionReconnect).toEqual({ + activeHostId: `runtime:${client.environmentId}`, + folderHosts: ['local', `runtime:${client.environmentId}`], + groupHosts: ['local', `runtime:${client.environmentId}`] + }) + + const catalogAfterLocalRefresh = await client.page.evaluate(async () => { + const store = window.__store + if (!store) { + throw new Error('Renderer store unavailable') + } + await store.getState().fetchProjectGroups() + await store.getState().fetchFolderWorkspaces() + return { + folderWorkspaces: store.getState().folderWorkspaces, + projectGroups: store.getState().projectGroups + } + }) + expect(catalogAfterLocalRefresh.projectGroups).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + executionHostId: `runtime:${client.environmentId}`, + parentPath: fixture.nestedParentPath + }) + ]) + ) + expect(catalogAfterLocalRefresh.folderWorkspaces).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + executionHostId: `runtime:${client.environmentId}`, + folderPath: fixture.catalogFolderPath + }) + ]) + ) + + const clientRegistration = await client.page.evaluate( + ({ + clonedRepoPath, + createdRepoPath, + environmentId, + folderCollisionId, + folderPath, + gitCollisionId, + gitPath, + nestedParentPath, + nestedRepoPaths + }) => { + const state = window.__store?.getState() + const nestedGroup = state?.projectGroups.find( + (group) => group.parentPath === nestedParentPath + ) + const nestedRepos = state?.repos.filter((repo) => nestedRepoPaths.includes(repo.path)) ?? [] + return { + clonedOwner: + state?.repos.find((repo) => repo.path === clonedRepoPath)?.executionHostId ?? null, + createdOwner: + state?.repos.find((repo) => repo.path === createdRepoPath)?.executionHostId ?? null, + folderKind: state?.repos.find((repo) => repo.path === folderPath)?.kind ?? null, + folderSameIdHosts: + Object.values(state?.worktreesByRepo ?? {}) + .flat() + .filter((worktree) => worktree.id === folderCollisionId) + .map((worktree) => worktree.hostId ?? 'local') + .sort() ?? [], + folderOwner: + state?.repos.find((repo) => repo.path === folderPath)?.executionHostId ?? null, + gitSameIdHosts: + Object.values(state?.worktreesByRepo ?? {}) + .flat() + .filter((worktree) => worktree.id === gitCollisionId) + .map((worktree) => worktree.hostId ?? 'local') + .sort() ?? [], + gitOwner: state?.repos.find((repo) => repo.path === gitPath)?.executionHostId ?? null, + nestedGroupOwner: nestedGroup?.executionHostId ?? null, + nestedRepoOwners: nestedRepos.map((repo) => repo.executionHostId ?? null).sort(), + nestedReposInGroup: + nestedGroup !== undefined && + nestedRepos.length === nestedRepoPaths.length && + nestedRepos.every((repo) => repo.projectGroupId === nestedGroup.id), + activeRuntimeEnvironmentId: state?.settings?.activeRuntimeEnvironmentId ?? null, + expectedOwner: `runtime:${environmentId}` + } + }, + { + clonedRepoPath: fixture.clonedRepoPath, + createdRepoPath: fixture.createdRepoPath, + environmentId: client.environmentId, + folderCollisionId: folderCollision.runtimeWorktreeId, + folderPath: fixture.folderPath, + gitCollisionId: gitCollision.runtimeWorktreeId, + gitPath: fixture.gitPath, + nestedParentPath: fixture.nestedParentPath, + nestedRepoPaths: fixture.nestedRepoPaths + } + ) + expect(clientRegistration).toEqual({ + activeRuntimeEnvironmentId: null, + clonedOwner: `runtime:${client.environmentId}`, + createdOwner: `runtime:${client.environmentId}`, + expectedOwner: `runtime:${client.environmentId}`, + folderKind: 'folder', + folderOwner: `runtime:${client.environmentId}`, + folderSameIdHosts: ['local', `runtime:${client.environmentId}`], + gitOwner: `runtime:${client.environmentId}`, + gitSameIdHosts: ['local', `runtime:${client.environmentId}`], + nestedGroupOwner: `runtime:${client.environmentId}`, + nestedRepoOwners: [`runtime:${client.environmentId}`, `runtime:${client.environmentId}`], + nestedReposInGroup: true + }) + + const terminalActivation = await client.page.evaluate( + async ({ environmentId, worktreeId }) => { + const bridge = ( + window as unknown as { + __webRuntimeSessionE2E?: { + createTerminal: ( + args: Record + ) => Promise<{ status: string; message?: string }> + } + } + ).__webRuntimeSessionE2E + const store = window.__store + if (!bridge || !store) { + throw new Error('Runtime terminal activation bridge unavailable') + } + const outcome = await bridge.createTerminal({ environmentId, worktreeId }) + const state = store.getState() + return { + activeHostId: state.activeWorkspaceExecutionHostId, + activeWorktreeId: state.activeWorktreeId, + outcome, + sameIdHosts: Object.values(state.worktreesByRepo) + .flat() + .filter((worktree) => worktree.id === worktreeId) + .map((worktree) => worktree.hostId ?? 'local') + .sort() + } + }, + { + environmentId: client.environmentId, + worktreeId: gitCollision.runtimeWorktreeId + } + ) + expect(terminalActivation).toEqual({ + activeHostId: `runtime:${client.environmentId}`, + activeWorktreeId: gitCollision.runtimeWorktreeId, + outcome: { status: 'created' }, + sameIdHosts: ['local', `runtime:${client.environmentId}`] + }) + + const finalClientInventory = await listRuntimeInventory(clientLocalRuntime) + expect(finalClientInventory.repos.map((repo) => repo.path)).toEqual( + expect.not.arrayContaining([ + fixture.gitPath, + fixture.folderPath, + fixture.clonedRepoPath, + fixture.createdRepoPath + ]) + ) + expect(finalClientInventory.repos.map((repo) => repo.path)).toEqual( + expect.not.arrayContaining(fixture.nestedRepoPaths) + ) + expect(finalClientInventory.projectGroups.map((group) => group.parentPath)).not.toContain( + fixture.nestedParentPath + ) + expect( + finalClientInventory.folderWorkspaces.map((workspace) => workspace.folderPath) + ).not.toContain(fixture.catalogFolderPath) + for (const projectName of [ + path.basename(fixture.gitPath), + path.basename(fixture.folderPath), + path.basename(fixture.clonedRepoPath), + path.basename(fixture.createdRepoPath), + ...fixture.nestedRepoPaths.map((repoPath) => path.basename(repoPath)) + ]) { + // Why: duplicate checkout names are disambiguated with a parent path. + await expect(client.page.getByText(projectName, { exact: false }).first()).toBeVisible() + } + expect(await client.getDirectSshAttemptTargetIds()).toEqual([]) + console.info(`[pr11346-routing] ${JSON.stringify({ topology: runtimeName, ...measurements })}`) + await client.page.screenshot({ + path: testInfo.outputPath(`${visible ? 'headed' : 'hidden-window'}-selected-runtime-add.png`), + fullPage: true + }) + } finally { + await client.dispose() + rmSync(fixture.rootPath, { recursive: true, force: true }) + } +} + +test('routes every Add Project path to a selected non-default headed runtime @headful', async ({ + electronApp, + orcaPage +}, testInfo) => { + test.setTimeout(300_000) + await runSelectedRuntimeAddJourney(electronApp, orcaPage, testInfo, true) +}) + +test('keeps every selected-runtime Add Project path in hidden-window desktop parity', async ({ + electronApp, + orcaPage +}, testInfo) => { + test.setTimeout(300_000) + await runSelectedRuntimeAddJourney(electronApp, orcaPage, testInfo, false) +}) diff --git a/tests/e2e/pr11346-selected-runtime-identity-oracle.ts b/tests/e2e/pr11346-selected-runtime-identity-oracle.ts new file mode 100644 index 000000000..2918a6928 --- /dev/null +++ b/tests/e2e/pr11346-selected-runtime-identity-oracle.ts @@ -0,0 +1,247 @@ +import { execFileSync } from 'node:child_process' +import { mkdirSync, realpathSync, writeFileSync } from 'node:fs' +import { mkdtemp } from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import type { Page } from '@stablyai/playwright-test' +import type { AppState } from '../../src/renderer/src/store/types' +import { expect } from './helpers/orca-app' + +export function configureIsolatedGitIdentity(homePath: string): void { + writeFileSync( + path.join(homePath, '.gitconfig'), + '[user]\n\tname = PR 11346 E2E\n\temail = pr11346@test.local\n' + ) +} + +function initializeGitRepo(repoPath: string, markerName: string): void { + mkdirSync(repoPath, { recursive: true }) + execFileSync('git', ['init'], { cwd: repoPath, stdio: 'pipe' }) + execFileSync('git', ['config', 'user.email', 'pr11346@test.local'], { + cwd: repoPath, + stdio: 'pipe' + }) + execFileSync('git', ['config', 'user.name', 'PR 11346 E2E'], { + cwd: repoPath, + stdio: 'pipe' + }) + writeFileSync(path.join(repoPath, markerName), `# ${path.basename(repoPath)} authority\n`) + execFileSync('git', ['add', markerName], { cwd: repoPath, stdio: 'pipe' }) + execFileSync('git', ['commit', '-m', 'Initial remote fixture'], { + cwd: repoPath, + stdio: 'pipe' + }) +} + +export async function createProjectFixtures(): Promise<{ + catalogFolderPath: string + cloneParentPath: string + clonedRepoPath: string + createdRepoPath: string + createParentPath: string + folderPath: string + gitPath: string + localCloneCollisionPath: string + localCreateCollisionPath: string + nestedParentPath: string + nestedRepoPaths: string[] + reconnectCatalogPath: string + rootPath: string +}> { + const rootPath = realpathSync(await mkdtemp(path.join(os.tmpdir(), 'orca-pr11346-headed-'))) + const gitPath = path.join(rootPath, 'remote-git-project') + const folderPath = path.join(rootPath, 'remote-plain-folder') + const cloneParentPath = path.join(rootPath, 'remote-clones') + const createParentPath = path.join(rootPath, 'remote-created-projects') + const nestedParentPath = path.join(rootPath, 'remote-nested-projects') + const catalogFolderPath = path.join(nestedParentPath, 'catalog-workspace') + const reconnectCatalogPath = path.join(rootPath, 'reconnect-catalog') + const localCloneCollisionPath = path.join(rootPath, 'local-clone-collision') + const localCreateCollisionPath = path.join(rootPath, 'local-create-collision') + const nestedRepoPaths = ['nested-api', 'nested-web'].map((name) => + path.join(nestedParentPath, name) + ) + mkdirSync(folderPath) + mkdirSync(cloneParentPath) + mkdirSync(createParentPath) + writeFileSync(path.join(folderPath, 'REMOTE_FOLDER_MARKER.txt'), 'remote-folder-authority\n') + initializeGitRepo(gitPath, 'REMOTE_GIT_MARKER.md') + initializeGitRepo(localCloneCollisionPath, 'LOCAL_CLONE_COLLISION.md') + initializeGitRepo(localCreateCollisionPath, 'LOCAL_CREATE_COLLISION.md') + nestedRepoPaths.forEach((repoPath) => initializeGitRepo(repoPath, 'NESTED_REMOTE_MARKER.md')) + mkdirSync(catalogFolderPath) + mkdirSync(reconnectCatalogPath) + return { + catalogFolderPath, + cloneParentPath, + clonedRepoPath: path.join(cloneParentPath, path.basename(gitPath)), + createParentPath, + createdRepoPath: path.join(createParentPath, 'runtime-created-project'), + folderPath, + gitPath, + localCloneCollisionPath, + localCreateCollisionPath, + nestedParentPath, + nestedRepoPaths, + reconnectCatalogPath, + rootPath + } +} + +type ActivationCollision = { + localWorktreeId: string + runtimeWorktreeId: string +} + +export async function installFinalActivationGate(page: Page, targetPath: string): Promise { + await page.evaluate((pathToGate) => { + const store = window.__store + if (!store) { + throw new Error('Renderer store unavailable') + } + const originalFetchWorktrees = store.getState().fetchWorktrees + let release!: () => void + const released = new Promise((resolve) => { + release = resolve + }) + const gateWindow = window as typeof window & { + __pr11346ActivationGate?: { + originalFetchWorktrees: typeof originalFetchWorktrees + release: () => void + waiting: boolean + } + } + gateWindow.__pr11346ActivationGate = { + originalFetchWorktrees, + release, + waiting: false + } + store.setState({ + fetchWorktrees: async (...args: Parameters) => { + const result = await originalFetchWorktrees(...args) + const targetRepo = store + .getState() + .repos.find( + (repo) => + repo.path === pathToGate && repo.executionHostId?.startsWith('runtime:') === true + ) + if (targetRepo?.id === args[0]) { + gateWindow.__pr11346ActivationGate!.waiting = true + await released + } + return result + } + }) + }, targetPath) +} + +export async function injectSameIdLocalActivationCollision( + page: Page, + targetPath: string, + localPath: string +): Promise { + await expect + .poll( + () => + page.evaluate( + () => + ( + window as typeof window & { + __pr11346ActivationGate?: { waiting: boolean } + } + ).__pr11346ActivationGate?.waiting ?? false + ), + { timeout: 60_000 } + ) + .toBe(true) + + return page.evaluate( + ({ localCollisionPath, runtimePath }) => { + const store = window.__store + const gateWindow = window as typeof window & { + __pr11346ActivationGate?: { + originalFetchWorktrees: AppState['fetchWorktrees'] + release: () => void + } + } + const gate = gateWindow.__pr11346ActivationGate + if (!store || !gate) { + throw new Error('Activation gate unavailable') + } + const state = store.getState() + const runtimeRepo = state.repos.find( + (repo) => repo.path === runtimePath && repo.executionHostId?.startsWith('runtime:') === true + ) + if (!runtimeRepo) { + throw new Error(`Runtime repo unavailable for ${runtimePath}`) + } + const runtimeWorktree = state.worktreesByRepo[runtimeRepo.id]?.find( + (worktree) => + worktree.hostId === runtimeRepo.executionHostId && + (worktree.isMainWorktree || worktree.path === runtimePath) + ) + if (!runtimeWorktree) { + throw new Error(`Runtime default checkout unavailable for ${runtimePath}`) + } + const localWorktree = { + ...runtimeWorktree, + path: localCollisionPath, + hostId: 'local' as const, + runtimeOwnerEnvironmentId: null + } + store.setState({ + repos: [ + { + ...runtimeRepo, + path: localCollisionPath, + displayName: `Local collision for ${runtimeRepo.displayName}`, + executionHostId: 'local', + connectionId: null + }, + ...state.repos + ], + worktreesByRepo: { + ...state.worktreesByRepo, + [runtimeRepo.id]: [localWorktree, ...(state.worktreesByRepo[runtimeRepo.id] ?? [])] + }, + fetchWorktrees: gate.originalFetchWorktrees + }) + gate.release() + delete gateWindow.__pr11346ActivationGate + return { + localWorktreeId: localWorktree.id, + runtimeWorktreeId: runtimeWorktree.id + } + }, + { localCollisionPath: localPath, runtimePath: targetPath } + ) +} + +export async function expectRuntimeActivation( + page: Page, + collision: ActivationCollision +): Promise { + await expect + .poll( + () => + page.evaluate(() => { + const state = window.__store?.getState() + return { + activeWorktreeId: state?.activeWorktreeId ?? null, + activeWorktreeHost: state?.activeWorkspaceExecutionHostId ?? null, + sameIdHosts: Object.values(state?.worktreesByRepo ?? {}) + .flat() + .filter((worktree) => worktree.id === state?.activeWorktreeId) + .map((worktree) => worktree.hostId ?? 'local') + .sort() + } + }), + { timeout: 60_000 } + ) + .toEqual({ + activeWorktreeHost: expect.stringMatching(/^runtime:/), + activeWorktreeId: collision.runtimeWorktreeId, + sameIdHosts: ['local', expect.stringMatching(/^runtime:/)] + }) + expect(collision.runtimeWorktreeId).toBe(collision.localWorktreeId) +}