Repository navigation
fix: route server project adds to selected runtime - #11346
Conversation
Greptile SummaryThis PR fixes a bug where adding a server-hosted project from the Add Project dialog while a non-default runtime environment is selected would silently register the project against the global/local environment instead of the selected one. The fix propagates
Confidence Score: 5/5Safe to merge — the change is a tightly scoped routing fix with no UI changes, no IPC changes, and no new dependencies. The fix correctly threads Files Needing Attention: The
|
| Filename | Overview |
|---|---|
| src/renderer/src/components/sidebar/useAddRepoServerPathFlow.ts | Core fix: passes activeRuntimeEnvironmentId to addRepoPath, scanNestedRepos, setActiveNestedScanId, showNestedRepoReview, and fetchWorktrees — propagation is complete and consistent through both git and folder paths |
| src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts | Adds two test cases: folder path asserting runtimeEnvironmentId is passed to addRepoPath, and a new git path test covering the scan → add → fetchWorktrees chain; the previously flagged gap in git-path coverage is now addressed |
| src/renderer/src/components/sidebar/add-repo-runtime-owner.ts | New helper module encapsulating the mapping from `CapturedRuntimeOwner |
| src/renderer/src/components/sidebar/useAddRepoNestedReviewController.ts | New controller hook composing useAddRepoNestedReviewState, useAddRepoRemoteNestedScan, and useAddRepoNestedImportFlow; correctly wires nestedRuntimeEnvironmentId from state to the import flow |
| src/renderer/src/components/sidebar/useAddRepoNestedReviewState.ts | Adds nestedRuntimeEnvironmentId state captured from showNestedRepoReview; cancel calls correctly thread the runtime environment ID; resetNestedRepoReviewState sets this to null rather than the initial undefined, a minor semantic inconsistency with no practical impact |
| src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.ts | Correctly derives completionOwner from nestedRuntimeEnvironmentId (vs SSH connection) and passes it to fetchWorktrees and onGitRepoReady; refactors handleOpenNestedRootFolder to use shared completeNestedFolderOpen |
| src/renderer/src/components/sidebar/project-added-default-checkout.ts | Adds executionHostId filtering to worktree selection for default checkout; getProjectWorktreesForHost manually constructs runtime:${encodeURIComponent(...)} to compare against runtimeOwnerEnvironmentId, which is a coupling risk if the format ever changes |
| src/renderer/src/components/sidebar/AddRepoDialog.tsx | Replaces three separate hook usages with useAddRepoNestedReviewController; passes selectedRuntimeEnvironmentId to useAddRepoServerPathFlow; adds resetLocalFolderFlow to host-scoped reset |
| src/renderer/src/components/sidebar/use-complete-git-repo-add.ts | Filters worktrees by executionHostId before determining existing workspaces and default checkout; uses string literal 'local' which aligns with the known value of LOCAL_EXECUTION_HOST_ID |
| src/renderer/src/components/sidebar/add-repo-store-upsert.ts | Extends upsert to set executionHostId on the repo based on SSH or runtime owner; switches duplicate-detection from repo ID to getRepoHostIdentity, and now returns { alreadyPresent, repo } |
| src/renderer/src/components/sidebar/AddRepoSteps.tsx | SSH path: passes runtimeEnvironmentId: null to scan/cancel calls (correct for SSH), uses worktreeRefreshOptions with sshConnectionId, and propagates executionHostId to onGitRepoReady |
| src/renderer/src/components/sidebar/complete-nested-folder-open.ts | New extracted function for the open-as-folder path in nested review; correctly passes owner to addNonGitFolder and forwards connectionId to the non-git confirm modal |
| src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts | Local folder flow now also passes runtimeEnvironmentId to scans, review state, and addRepoPath; uses worktreeRefreshOptions consistently for fetch calls |
Sequence Diagram
sequenceDiagram
participant D as AddRepoDialog
participant SPF as useAddRepoServerPathFlow
participant ANRC as useAddRepoNestedReviewController
participant ANS as useAddRepoNestedReviewState
participant Store as Store (addRepoPath)
participant FW as fetchWorktrees
participant CGRA as useCompleteGitRepoAdd
D->>SPF: handleAddServerPath(kind, activeRuntimeEnvironmentId)
SPF->>Store: "scanNestedRepos(path, undefined, {runtimeEnvironmentId})"
Store-->>SPF: NestedRepoScanResult
alt "selectedPathKind === non_git_folder AND nested repos exist"
SPF->>ANRC: "showNestedRepoReview({runtimeEnvironmentId})"
ANRC->>ANS: setNestedRuntimeEnvironmentId(runtimeEnvironmentId)
Note over ANS: nestedRuntimeEnvironmentId stored
ANRC-->>D: (nested step shown)
else direct add (git or plain folder)
SPF->>Store: "addRepoPath(path, kind, {runtimeEnvironmentId}) FIXED"
Store-->>SPF: repo
SPF->>FW: "fetchWorktrees(repo.id, {requireAuthoritative, executionHostId})"
FW-->>SPF: result
SPF->>CGRA: onGitRepoReady(repo.id, source, executionHostId)
CGRA->>CGRA: filter worktrees by executionHostId
CGRA-->>D: default checkout activated
end
Reviews (9): Last reviewed commit: "test(runtime): seed isolated Git identit..." | Re-trigger Greptile
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe repository store now routes repository, project-group, folder-workspace, and nested-repository operations by runtime owner. Catalog merging and mutation reconciliation use host-qualified identities and stale-result fences. Worktree refresh and activation preserve the selected execution host. Runtime sessions pass their execution host during worktree selection. The Add Project server-path flow forwards the selected runtime environment to 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts (1)
92-94: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winCover the Git path in the regression test.
This assertion only exercises
handleAddServerPath('folder'). Add a Git case whose scan reachesaddRepoPathand assert the sameruntimeEnvironmentId; separately cover the nested-review path if it creates repositories.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9e9fd47e-158b-4f1e-bc42-ca84bd47549a
📥 Commits
Reviewing files that changed from the base of the PR and between ef55429 and 10f0cc4842c052836ed6994ed2b66f6a9efcbf9b.
📒 Files selected for processing (3)
src/renderer/src/components/sidebar/AddRepoDialog.tsxsrc/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.tssrc/renderer/src/components/sidebar/useAddRepoServerPathFlow.ts
10f0cc4 to
fcdaa30
Compare
# Conflicts: # src/renderer/src/store/slices/repos.ts
OrcaWin
left a comment
There was a problem hiding this comment.
Validated and completed the selected-runtime routing fix. Add, Clone, Create, folder, and nested import now preserve host-qualified ownership through refresh and final activation; same-ID local/runtime catalogs, reconnect fencing, and SSH pruning have deterministic coverage. Headed and hidden paired Electron journeys passed on the reviewed candidate.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
src/renderer/src/hooks/useIpcEvents.ts (2)
764-806: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winForward
executionHostIdwhen reactivating a renamed worktree.
handleWorktreesChangednow receivesoptions?.executionHostId, and it forwards this value tofetchWorktreesandfetchWorktreeLineage. But the reactivation call at line 805,setActiveWorktree(renamed.newWorktreeId), omits it.
setActiveWorktreestores exactly the passedexecutionHostId ?? nullintoactiveWorkspaceExecutionHostId; it does not derive the host from the resolved worktree. So renaming a worktree that is currently active under a runtime or SSH host resetsactiveWorkspaceExecutionHostIdtonull, misrepresenting the active workspace as local.🐛 Proposed fix
if (renamedWasActive && renamed) { - useAppStore.getState().setActiveWorktree(renamed.newWorktreeId) + useAppStore.getState().setActiveWorktree(renamed.newWorktreeId, options?.executionHostId) }
893-908: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winDo not let a partial worktree-refresh failure skip the lineage refresh.
refreshRuntimeProjectWorktreesthrows anAggregateErrorafter processing every repo when at least one repo fails. Because this call isawait-ed directly beforefetchWorktreeLineage, any single repo failure prevents the environment's lineage from refreshing at all, even when the majority of repos succeeded. This is a partial-error-propagation gap that leaves lineage stale until the next scheduled refresh.🛠️ Proposed fix: refresh lineage regardless of partial worktree-refresh failures
refresh: async (environmentId) => { void hydrateRuntimeEnvironmentSshState(environmentId, { force: true }).catch(() => {}) const repos = await useAppStore.getState().fetchRuntimeEnvironmentRepos(environmentId) - await refreshRuntimeProjectWorktrees(environmentId, repos, (repoId, options) => - useAppStore.getState().fetchWorktrees(repoId, options) - ) - await useAppStore.getState().fetchWorktreeLineage({ - executionHostId: toRuntimeExecutionHostId(environmentId) - }) + let worktreeRefreshError: unknown + try { + await refreshRuntimeProjectWorktrees(environmentId, repos, (repoId, options) => + useAppStore.getState().fetchWorktrees(repoId, options) + ) + } catch (error) { + worktreeRefreshError = error + } + await useAppStore.getState().fetchWorktreeLineage({ + executionHostId: toRuntimeExecutionHostId(environmentId) + }) + if (worktreeRefreshError) { + throw worktreeRefreshError + } },src/renderer/src/store/slices/worktrees.ts (1)
2974-3058: 🗄️ Data Integrity & Integration | 🟠 MajorCarry the missing-owner repos snapshot through direct-SSH merges.
mergeFetchedWorktreesskips all merging whenownerWasMissingAtStartis true unless the direct-SSH authority is current, and when present it enforcess.repos === args.missingDirectSshOwnerReposSnapshot.acquireDirectSshDetectedWorktreeRefreshbuilds the direct-SSH refresh but omitsmissingDirectSshOwnerReposSnapshot, so the reconnect path can miss the intended fence after ownership changes. Capture the snapshot whenownerWasMissingAtStartis true, likefetchWorktreesdoes, and pass it intomergeFetchedWorktrees.
[低 Effort/High Reward]
🧹 Nitpick comments (2)
tests/e2e/pr11346-selected-runtime-add.spec.ts (1)
193-207: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the duplicated reconnect-and-verify sequence into a shared helper.
The disconnect → clear status → reconnect → set status sequence at Lines 193-207 is duplicated almost verbatim at Lines 510-525. The paired follow-up check at Lines 238-240 (
refreshRuntimeEnvironmentStatusfailure throw) is also duplicated at Lines 529-531, differing only in the error message. Two independent copies of this simulation logic increase the maintenance surface for a flaky-prone reconnect sequence.Define a shared async function (e.g., in
pr11346-selected-runtime-identity-oracle.ts) that takespageandenvironmentId, and drives the disconnect/status-clear/reconnect/status-set/refresh-check sequence in its ownpage.evaluatecall. Call it from both places before running the block-specific catalog logic.♻️ Sketch of the shared helper
export async function reconnectRuntimeEnvironmentAndWaitForRecovery( page: Page, environmentId: string, failureMessage: string ): Promise<void> { await page.evaluate( async ({ environmentId }) => { const store = window.__store if (!store) { throw new Error('Renderer store unavailable') } 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() }) }, { environmentId } ) // ... run catalog-specific fetches here, then: const recovered = await page.evaluate( (environmentId) => window.__store?.getState().refreshRuntimeEnvironmentStatus(environmentId), environmentId ) if (!recovered) { throw new Error(failureMessage) } }Also applies to: 238-240, 510-531
src/renderer/src/store/slices/worktree-helpers.ts (1)
80-80: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDocument the new
activeWorkspaceExecutionHostIdfield.Every neighboring state field in
WorktreeSlicehas a comment explaining when it is set and why (seeactiveWorktreeId,renamingWorktreeId).activeWorkspaceExecutionHostIdhas none. Add a short comment stating that callers ofsetActiveWorktree/setActiveFolderWorkspacemust pass the correct host explicitly, because the value is not derived from the resolved worktree record.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: bec897c9-4707-482d-b802-d9afb2afa999
📒 Files selected for processing (12)
config/reliability-gates.jsoncsrc/renderer/src/hooks/runtime-project-refresh-scheduler.test.tssrc/renderer/src/hooks/runtime-project-refresh-scheduler.tssrc/renderer/src/hooks/useIpcEvents.test.tssrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/hooks/worktree-change-refresh-queue.test.tssrc/renderer/src/hooks/worktree-change-refresh-queue.tssrc/renderer/src/store/slices/worktree-helpers.tssrc/renderer/src/store/slices/worktrees.test.tssrc/renderer/src/store/slices/worktrees.tstests/e2e/pr11346-selected-runtime-add.spec.tstests/e2e/pr11346-selected-runtime-identity-oracle.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- config/reliability-gates.jsonc
… selection (#11818) * [P1] fix(routing): keep the paired-HUB owner for the active workspace selection #11346 made `activeWorkspaceExecutionHostId` authoritative for the active workspace, but the short-circuits that read it never see the owner record, so a project reached through a paired runtime HUB (`hostId: ssh:<target>` plus `runtimeOwnerEnvironmentId: <hub>`) loses its transport and its repo: - `resolveWorktreeOperationRouteResult` returned `runtimeEnvironmentId: null` for any non-`runtime:` selection, bypassing the HUB recovery in `resolveExactWorktreeRoute` — every owner-routed terminal/git/filesystem operation on the active workspace lost the HUB that proxies the SSH target. - `selectRepoByIdForActiveWorkspace` filtered `state.repos` by the selected host with no fallback, but `withRepoHostOwnership` deliberately keeps the SSH host on the worktree while the repo row stays HUB-owned — so the active repo read as `null` and `useGitStatusPolling` stopped polling the whole workspace. Route resolution now recovers the HUB owner from the owner rows on the selected host, and drops it only when rival HUBs project the same host. The repo selector opens exactly one hole in #11346's fail-closed rule — an `ssh:` selection over a `runtime:` repo row — and every other host mismatch still returns `null`. `worktree-owner-route.ts` is a pure extraction of the existing owner-route helpers; no behavior moved with it. * fix(routing): fail ambiguous paired-HUB repo selection closed
* fix: route server project adds to selected runtime * fix: preserve selected runtime for nested project scans * fix: retain nested review runtime ownership * fix: preserve nested runtime owner through completion * fix: preserve captured add repo owners * refactor: isolate add repo nested review controller * test: cover selected runtime project adds * fix: preserve selected project host ownership * fix: pin SSH nested import completion * fix: fence missing SSH repo refreshes * test: cover selected runtime reconnect routing * test: register selected runtime project routing gate * fix: preserve selected host across all project adds * fix: isolate selected-host project catalogs * fix: preserve host-qualified workspace identity * test: expect local folder host identity * test: preserve host-qualified activation assertions * fix: fence folder refreshes by host identity * fix: preserve runtime owner across project refresh events * test: fence selected-runtime reconnect oracle * fix(runtime): preserve selected host during session activation * test(runtime): force same-id paired terminal activation * chore(reliability): register prior selected-runtime evidence * test(runtime): seed isolated Git identity --------- Co-authored-by: OrcaWin <[email protected]>
… selection (stablyai#11818) * [P1] fix(routing): keep the paired-HUB owner for the active workspace selection stablyai#11346 made `activeWorkspaceExecutionHostId` authoritative for the active workspace, but the short-circuits that read it never see the owner record, so a project reached through a paired runtime HUB (`hostId: ssh:<target>` plus `runtimeOwnerEnvironmentId: <hub>`) loses its transport and its repo: - `resolveWorktreeOperationRouteResult` returned `runtimeEnvironmentId: null` for any non-`runtime:` selection, bypassing the HUB recovery in `resolveExactWorktreeRoute` — every owner-routed terminal/git/filesystem operation on the active workspace lost the HUB that proxies the SSH target. - `selectRepoByIdForActiveWorkspace` filtered `state.repos` by the selected host with no fallback, but `withRepoHostOwnership` deliberately keeps the SSH host on the worktree while the repo row stays HUB-owned — so the active repo read as `null` and `useGitStatusPolling` stopped polling the whole workspace. Route resolution now recovers the HUB owner from the owner rows on the selected host, and drops it only when rival HUBs project the same host. The repo selector opens exactly one hole in stablyai#11346's fail-closed rule — an `ssh:` selection over a `runtime:` repo row — and every other host mismatch still returns `null`. `worktree-owner-route.ts` is a pure extraction of the existing owner-route helpers; no behavior moved with it. * fix(routing): fail ambiguous paired-HUB repo selection closed
Summary
Fix adding a server-hosted project or folder from the Add Project dialog when a non-default runtime environment is selected.
Previously, the selected runtime environment ID was not passed to
addRepoPath. As a result, a path selected from a remote environment such asbox1could be registeredagainst the global/default environment instead.
The server-path flow now explicitly passes the selected runtime environment ID, ensuring the project is created in the environment from which it was selected.
Screenshots
No visual change.
Testing
pnpm lintpnpm typecheckpnpm testpnpm buildAdditional verification:
useAddRepoServerPathFlowVitest test passed.addRepoPathreceives the selectedruntimeEnvironmentId./home/ace/workrepo/zeal_platformfrombox1now registers the project in the correct environment.The unchecked commands were not run as complete repository-wide suites. Their relevant targeted checks were run successfully.
AI Review Report
An AI-assisted review was performed over the complete diff.
The review checked:
addRepoPathoptions argument.No blocking issues were found. The main risk identified was accidentally falling back to the global runtime configuration when adding a server path. This was addressed by
passing:
{ runtimeEnvironmentId: activeRuntimeEnvironmentId }directly to
addRepoPathand asserting it in the test.Cross-platform compatibility was explicitly reviewed for macOS, Linux, and Windows:
Security Audit
An AI-assisted basic security audit was performed.
Reviewed areas:
addRepoPathAPI.No new security issues or follow-up work were identified.
Notes