Skip to content

Preserve shared project host setups on refresh - #6031

Closed
prateek wants to merge 5 commits into
stablyai:mainfrom
prateek:codex/upstream-project-host-setup-refresh-union
Closed

prateek wants to merge 5 commits into
stablyai:mainfrom
prateek:codex/upstream-project-host-setup-refresh-union

Conversation

@prateek

@prateek prateek commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Context

Tracking issue: #6032

This is the second PR in the Remote Orca Servers state stack. It should be reviewed after #6030. The branch includes #6030's commit until that PR lands because GitHub cannot use a fork-only branch as the base for an upstream PR.

Once repo refresh is host-aware, shared projects still have a second failure mode: project compatibility and projectHostSetups can be reconciled with bare repo ids. When the same project exists on a local host and a Remote Orca Server, refreshing one host can drop the other host from compatibility and setup state.

Changed

  • Merge project compatibility by host-qualified source repo identity.
  • Keep projectHostSetups for sibling hosts during a host-specific refresh.
  • Preserve setup rows without a repoId by falling back to setup id on the same host, so empty setup rows do not collapse.

Regression coverage

The new tests create a shared project with host-specific repo state, then refresh one host. On main, the refresh drops the other host from sourceRepoIds or collapses setup rows. With this stack, both hosts keep their project state.

Tests

  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/repo-identity-reconcile.test.ts src/renderer/src/store/slices/repo-host-refresh-merge.test.ts src/renderer/src/store/slices/repos-multi-host-refresh.test.ts src/renderer/src/store/slices/repos-same-id-host-mutations.test.ts src/renderer/src/store/slices/repo-reorder-host-split.test.ts src/renderer/src/lib/repo-runtime-owner.test.ts src/renderer/src/store/slices/repos-update-serialization.test.ts src/renderer/src/store/slices/project-host-setup-compatibility-merge.test.ts
  • pnpm exec oxlint src/renderer/src/lib/repo-runtime-owner.ts src/renderer/src/lib/repo-runtime-owner.test.ts src/renderer/src/store/slices/repo-host-refresh-merge.ts src/renderer/src/store/slices/repo-host-refresh-merge.test.ts src/renderer/src/store/slices/repo-identity-reconcile.ts src/renderer/src/store/slices/repo-identity-reconcile.test.ts src/renderer/src/store/slices/repo-reorder-host-split.ts src/renderer/src/store/slices/repo-reorder-host-split.test.ts src/renderer/src/store/slices/repos.ts src/renderer/src/store/slices/repos-multi-host-refresh.test.ts src/renderer/src/store/slices/repos-same-id-host-mutations.test.ts src/renderer/src/store/slices/project-host-setup-compatibility-merge.ts src/renderer/src/store/slices/project-host-setup-compatibility-merge.test.ts
  • pnpm run typecheck:web

Stack

  1. Preserve same-id repos across hosts #6030: preserve same-id repos across hosts.
  2. This PR: preserve shared project host setup state across host refreshes.

Open in Stage

@ghost

ghost commented Jun 22, 2026 •

Copy link
Copy Markdown

@coderabbitai

coderabbitai Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces composite (executionHostId + repoId) repo identity and canonical host-qualified worktree IDs across the storage, runtime, and renderer layers. Same-id repos on different runtime hosts become distinct entries via composite identity keys in reconciliation, merging, reordering, and mutation paths. A new repo-host-refresh-merge.ts module merges per-host repo fetches without clobbering other hosts' entries; project-host-setup-compatibility-merge.ts merges project and setup compatibility data across hosts. The repos.ts slice adds ownership helpers (getRepoMutationOwnerHostId, isRepoMutationTarget) and rewrites removeProject, updateRepo, and reorderRepos to scope mutations to the active host. repo-runtime-owner.ts selects the active-host repo when multiple repos share the same id.

Worktree IDs shift from legacy repoId::path format to canonical orca-worktree://v1?hostId=...&repoId=...&path=... with legacy alias acceptance at public boundaries. Storage and daemon layers migrate canonical IDs during persist, validate, and list operations while accepting legacy aliases. The runtime layer recognizes both formats transparently, resolving aliases during worktree selection, terminal filtering, PTY membership, and lineage handling. The renderer adds host scoping to worktree refresh: fetchWorktrees accepts optional ownerHostId, and refresh merges detected/visible worktrees per host without clobbering sibling hosts. Project host setup mutations scope update/delete operations by (setupId, hostId) composite key in the renderer and storage layers.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Preserve shared project host setups on refresh' accurately summarizes the main change: ensuring project host setups remain intact across host-specific refreshes.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, explaining the context, problem, solution, and regression coverage for preserving shared project host state.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Warning

Tools execution failed with the following error:

Failed to run tools: 8 RESOURCE_EXHAUSTED: Received message larger than max (324474373 vs 209715200)


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/renderer/src/store/slices/repo-identity-reconcile.ts (1)

47-49: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Document the composite identity delimiter contract inline.

getRepoIdentityKey on Line 47 encodes a non-obvious contract (host + "\0" + repo.id). Please add a short why-comment so future edits don’t accidentally drift from the cross-host identity rule.

Suggested patch
 function getRepoIdentityKey(repo: Repo): string {
+  // Why: repo ids can collide across execution hosts; keying by host + id
+  // keeps reconciliation stable for same-id repos across hosts.
   return `${getRepoExecutionHostId(repo)}\0${repo.id}`
 }

As per coding guidelines, "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does."

Source: Coding guidelines

src/renderer/src/store/slices/repo-reorder-host-split.ts (1)

28-41: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Add a short rationale comment for the per-id host queue behavior.

The queue-on-duplicate logic on Line 28 and Line 41 is core to same-id multi-host correctness but not obvious at a glance; please add a 1–2 line why-comment.

Suggested patch
   const focusedHostId = getSettingsFocusedExecutionHostId(settings)
+  // Why: the same repo id can exist on multiple hosts; queue host ids so each
+  // ordered id occurrence is assigned to the next matching host instance.
   const hostIdsByRepoId = new Map<string, string[]>()

As per coding guidelines, "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does."

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: a7ae1cc3-783c-4e61-8499-3ba4679dd0ff

📥 Commits

Reviewing files that changed from the base of the PR and between d9b2d89 and ae5f194.

📒 Files selected for processing (13)
  • src/renderer/src/lib/repo-runtime-owner.test.ts
  • src/renderer/src/lib/repo-runtime-owner.ts
  • src/renderer/src/store/slices/project-host-setup-compatibility-merge.test.ts
  • src/renderer/src/store/slices/project-host-setup-compatibility-merge.ts
  • src/renderer/src/store/slices/repo-host-refresh-merge.test.ts
  • src/renderer/src/store/slices/repo-host-refresh-merge.ts
  • src/renderer/src/store/slices/repo-identity-reconcile.test.ts
  • src/renderer/src/store/slices/repo-identity-reconcile.ts
  • src/renderer/src/store/slices/repo-reorder-host-split.test.ts
  • src/renderer/src/store/slices/repo-reorder-host-split.ts
  • src/renderer/src/store/slices/repos-multi-host-refresh.test.ts
  • src/renderer/src/store/slices/repos-same-id-host-mutations.test.ts
  • src/renderer/src/store/slices/repos.ts

Comment on lines +238 to +248
function reorderReposByIdPermutation(orderedIds: readonly string[], previous: readonly Repo[]) {
const reposById = queueReposById(previous)
const next: Repo[] = []
for (const id of orderedIds) {
const repo = reposById.get(id)?.shift()
if (repo) {
next.push(repo)
}
}
return next.length === previous.length ? next : null
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Reject non-permutations with extra IDs before optimistic reorder.

Line 247 only checks next.length === previous.length, so inputs with extra IDs can still pass. That contradicts the non-permutation guard used at Line 1924 and can hide malformed reorder payloads.

💡 Suggested fix
 function reorderReposByIdPermutation(orderedIds: readonly string[], previous: readonly Repo[]) {
+  if (orderedIds.length !== previous.length) {
+    return null
+  }
   const reposById = queueReposById(previous)
   const next: Repo[] = []
   for (const id of orderedIds) {

Comment on lines +472 to +486
function getRepoMutationOwnerHostId(
repos: readonly Pick<Repo, 'id' | 'connectionId' | 'executionHostId'>[],
repoId: string,
targetHostId: string
): string {
const candidates = repos.filter((repo) => repo.id === repoId)
const targetOwned = candidates.find(
(repo) => hasExplicitRepoOwner(repo) && getRepoExecutionHostId(repo) === targetHostId
)
if (targetOwned) {
return targetHostId
}
const explicitOwner = candidates.find(hasExplicitRepoOwner)
return explicitOwner ? getRepoExecutionHostId(explicitOwner) : targetHostId
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Align RPC mutation host with resolved mutation owner host.

Line 485 can resolve ownerHostId to a different host than targetHostId. But Line 1642 and Line 1858 still send RPC/IPC to target, while state mutation filters by ownerHostId. That can desynchronize backend vs in-memory state for mixed explicit/legacy ownership records.

💡 Suggested fix
+function runtimeTargetForExecutionHostId(hostId: string): ReturnType<typeof getActiveRuntimeTarget> {
+  const parsed = parseExecutionHostId(hostId)
+  return parsed?.kind === 'runtime'
+    ? ({ kind: 'environment', environmentId: parsed.environmentId } as const)
+    : ({ kind: 'local' } as const)
+}
...
-const target = getActiveRuntimeTarget(settingsForRepoOwner(get(), projectId))
-const targetHostId = getRuntimeTargetHostId(target)
+const initialTarget = getActiveRuntimeTarget(settingsForRepoOwner(get(), projectId))
+const targetHostId = getRuntimeTargetHostId(initialTarget)
 const ownerHostId = getRepoMutationOwnerHostId(get().repos, projectId, targetHostId)
+const target = runtimeTargetForExecutionHostId(ownerHostId)

Also applies to: 1637-1644, 1851-1854

@prateek

prateek commented Jun 22, 2026

Copy link
Copy Markdown
Contributor Author

Suggested reviewers: @Jinwoo-H for the Remote Orca Servers host model, and @brennanb2025 for project/folder workspace state and project host setup behavior. I tried to request reviews directly, but this fork account cannot call RequestReviewsByLogin on the upstream repo.

@Jinwoo-H Jinwoo-H mentioned this pull request Jun 22, 2026
11 tasks done

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/main/memory/hydrate-local-pty-registry.ts (1)

78-90: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Restrict alias hydration to local execution host repos.

This loop only excludes SSH repos. Repos on non-local execution hosts can still be indexed, which may register a local daemon session under the wrong canonical host key (or fail hydration while enumerating non-local paths).

💡 Suggested fix
+import { getRepoExecutionHostId } from '../../shared/execution-host'
 import { getRepoWorktreeIdAliases, makeRepoWorktreeKey } from '../../shared/worktree-id'

 for (const repo of repos) {
   const connectionId = repo.connectionId ?? null
-  if (connectionId) {
+  const repoHostId = getRepoExecutionHostId(repo)
+  if (connectionId || repoHostId !== 'local') {
     // Why: SSH PTYs are never registered for local process sampling, so
-    // avoid startup SSH/git enumeration for repos we will skip anyway.
+    // avoid startup SSH/git enumeration for repos we will skip anyway.
+    // Non-local execution hosts must also be skipped: this registry is local-only.
     continue
   }
   const worktrees = await listRepoWorktrees(repo)

Also applies to: 119-126

src/renderer/src/hooks/useIpcEvents.ts (1)

771-787: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Filter deletion diffs to the refreshed host before purging.

ownerHostId scopes the fetch, but before/after are still repo-wide. If another host’s detected list is missing or non-authoritative, a host-specific refresh can classify sibling-host worktrees as removed and purge their terminal/workspace state.

🛡️ Suggested host-scoped diff shape
+      const belongsToRefreshHost = (worktree: { hostId?: ExecutionHostId }): boolean =>
+        ownerHostId == null || worktree.hostId === ownerHostId
+      const authoritativeIdsForRefreshHost = (
+        snapshot: ReturnType<typeof useAppStore.getState>
+      ): Set<string> | null => {
+        const detected = snapshot.detectedWorktreesByRepo[repoId]
+        if (!detected?.authoritative) {
+          return null
+        }
+        return new Set(
+          detected.worktrees.filter(belongsToRefreshHost).map((worktree) => worktree.id)
+        )
+      }
+      const visibleIdsForRefreshHost = (
+        snapshot: ReturnType<typeof useAppStore.getState>
+      ): Set<string> =>
+        new Set(
+          (snapshot.worktreesByRepo[repoId] ?? [])
+            .filter(belongsToRefreshHost)
+            .map((worktree) => worktree.id)
+        )
       const state = useAppStore.getState()
       const before =
-        getAuthoritativeDetectedWorktreeIds(state, repoId) ??
-        getVisibleWorktreeIdsForRepo(state, repoId)
+        authoritativeIdsForRefreshHost(state) ?? visibleIdsForRefreshHost(state)
       await (ownerHostId
         ? state.fetchWorktrees(repoId, { ownerHostId })
         : state.fetchWorktrees(repoId))
       await useAppStore.getState().fetchWorktreeLineage()
@@
       }
       const afterState = useAppStore.getState()
-      const after = getAuthoritativeDetectedWorktreeIds(afterState, repoId)
+      const after = authoritativeIdsForRefreshHost(afterState)
       if (!after) {
         return
       }
🧹 Nitpick comments (4)
src/renderer/src/store/slices/repo-host-refresh-merge.ts (1)

10-16: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Add a brief “why” comment for host-block anchoring behavior.

This merge strategy is non-obvious (replace one host block while preserving sibling host ordering); add a 1–2 line rationale above firstHostIndex/insertAt to make the invariant explicit.

Suggested patch
 ): Repo[] {
+  // Keep the refreshed host block anchored at its previous first position so
+  // sibling host ordering is preserved across host-scoped refreshes.
   const firstHostIndex = previous.findIndex((repo) => getRepoExecutionHostId(repo) === hostId)
   const preserved = previous.filter((repo) => getRepoExecutionHostId(repo) !== hostId)

As per coding guidelines, **/*.{ts,tsx,js,jsx} requires a short comment for non-obvious/design-driven behavior.

Source: Coding guidelines

src/main/runtime/worktree-teardown.ts (1)

116-121: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Document the legacy-ID fallback intent.

This canonical→legacy alias expansion is a migration-specific behavior and is non-obvious at a glance. Add a short “Why” comment here to preserve intent.

Suggested patch
 function getTeardownWorktreeIds(worktreeId: string): Set<string> {
   const ids = new Set([worktreeId])
   const parsed = splitWorktreeId(worktreeId)
   if (parsed) {
+    // Why: during canonical-ID rollout, some persisted PTY/session rows may
+    // still reference legacy repoId::path identifiers; sweep both forms.
     ids.add(makeLegacyWorktreeId(parsed.repoId, parsed.worktreePath))
   }
   return ids
 }

As per coding guidelines, "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does."

Source: Coding guidelines

src/main/memory/hydrate-local-pty-registry.test.ts (1)

224-233: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Add a mixed-host hydration regression case.

Please add a case with same repoId/path on local and non-local execution hosts to assert hydration only registers the local canonical worktree ID. This guards alias-map regressions.

src/shared/worktree-id.ts (1)

95-97: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Document the strict query-parameter ordering contract.

This ordering check is a non-obvious compatibility rule. Add a short Why: comment so future edits don’t loosen the canonical format unintentionally.

Proposed patch
   const keys = [...params.keys()]
+  // Why: canonical worktree IDs are a versioned wire format; strict field order
+  // prevents accepting ambiguously shaped or re-serialized query strings.
   if (keys.length !== 3 || keys[0] !== 'hostId' || keys[1] !== 'repoId' || keys[2] !== 'path') {
     return null
   }

As per coding guidelines, **/*.{ts,tsx,js,jsx} requires a short comment for non-obvious constraints.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: f0454b31-cd32-4897-bbed-cfe73beb5cff

📥 Commits

Reviewing files that changed from the base of the PR and between ae5f194 and 8814267.

📒 Files selected for processing (43)
  • docs/worktree-host-identity-rollout-validation.md
  • src/main/daemon/pty-session-id.test.ts
  • src/main/ipc/remote-workspace.ts
  • src/main/ipc/repos.ts
  • src/main/ipc/workspace-cleanup.test.ts
  • src/main/ipc/workspace-cleanup.ts
  • src/main/ipc/worktree-metadata-merge.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/memory/hydrate-local-pty-registry.test.ts
  • src/main/memory/hydrate-local-pty-registry.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/project-runtime-rpc-methods.ts
  • src/main/runtime/worktree-teardown.ts
  • src/main/usage-worktree-metadata.ts
  • src/main/workspace-space-analysis.ts
  • src/renderer/src/components/settings/McpConfigSection.tsx
  • src/renderer/src/components/settings/RepositoryHostSetupsSection.test.tsx
  • src/renderer/src/components/settings/RepositoryHostSetupsSection.tsx
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/hooks/worktree-change-refresh-queue.ts
  • src/renderer/src/lib/project-host-workspace-target.test.ts
  • src/renderer/src/lib/project-host-workspace-target.ts
  • src/renderer/src/lib/worktree-runtime-owner.test.ts
  • src/renderer/src/lib/worktree-runtime-owner.ts
  • src/renderer/src/store/slices/repo-host-refresh-merge.test.ts
  • src/renderer/src/store/slices/repo-host-refresh-merge.ts
  • src/renderer/src/store/slices/repos-multi-host-refresh.test.ts
  • src/renderer/src/store/slices/repos-project-host-lifecycle.test.ts
  • src/renderer/src/store/slices/repos-same-id-host-mutations.test.ts
  • src/renderer/src/store/slices/repos.ts
  • src/renderer/src/store/slices/worktree-helpers.ts
  • src/renderer/src/store/slices/worktrees.test.ts
  • src/renderer/src/store/slices/worktrees.ts
  • src/shared/pty-session-id-format.ts
  • src/shared/types.ts
  • src/shared/worktree-id.test.ts
  • src/shared/worktree-id.ts
✅ Files skipped from review due to trivial changes (1)
  • docs/worktree-host-identity-rollout-validation.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/store/slices/repos.ts

Comment thread src/main/ipc/worktrees.ts
Comment on lines +697 to +707
function migrateLegacyFolderWorkspaceMetaIfSafe(store: Store, repo: Repo): void {
for (const [worktreeId, meta] of Object.entries(store.getAllWorktreeMeta())) {
if (!isLegacyFolderWorkspaceIdForRepo(repo, worktreeId)) {
continue
}
const repoHostId = getRepoExecutionHostId(repo)
if (meta.hostId !== undefined && meta.hostId !== repoHostId) {
continue
}
store.migrateWorktreeIdentity(worktreeId, getCanonicalFolderWorkspaceId(repo, worktreeId))
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Prevent legacy folder-meta migration from clobbering an existing canonical row.

migrateLegacyFolderWorkspaceMetaIfSafe migrates every legacy key without checking whether the canonical destination already exists. If both keys are present, this can overwrite newer canonical metadata during listing.

💡 Suggested fix
 function migrateLegacyFolderWorkspaceMetaIfSafe(store: Store, repo: Repo): void {
   for (const [worktreeId, meta] of Object.entries(store.getAllWorktreeMeta())) {
     if (!isLegacyFolderWorkspaceIdForRepo(repo, worktreeId)) {
       continue
     }
+    const canonicalId = getCanonicalFolderWorkspaceId(repo, worktreeId)
+    if (canonicalId === worktreeId || store.getWorktreeMeta(canonicalId)) {
+      continue
+    }
     const repoHostId = getRepoExecutionHostId(repo)
     if (meta.hostId !== undefined && meta.hostId !== repoHostId) {
       continue
     }
-    store.migrateWorktreeIdentity(worktreeId, getCanonicalFolderWorkspaceId(repo, worktreeId))
+    store.migrateWorktreeIdentity(worktreeId, canonicalId)
   }
 }

Comment on lines +67 to +75
id: makeRepoWorktreeKey(
{
id: repo.id,
connectionId: repo.connectionId,
executionHostId: repo.executionHostId
},
repo.path
),
path: repo.path

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add a short “why” comment for the host-qualified fallback worktree key.

This fallback now encodes host identity; please add a one-line rationale so future edits don’t regress cross-host disambiguation.

Suggested update
       worktreesForRepo[0] ?? {
+        // Why: fallback IDs must stay host-qualified so same repo IDs across hosts don't collide.
         id: makeRepoWorktreeKey(
           {
             id: repo.id,
             connectionId: repo.connectionId,
             executionHostId: repo.executionHostId
           },
           repo.path
         ),
         path: repo.path
       }

As per coding guidelines, "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does."

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
id: makeRepoWorktreeKey(
{
id: repo.id,
connectionId: repo.connectionId,
executionHostId: repo.executionHostId
},
repo.path
),
path: repo.path
id: makeRepoWorktreeKey(
{
id: repo.id,
connectionId: repo.connectionId,
executionHostId: repo.executionHostId
},
repo.path
),
path: repo.path
Suggested change
id: makeRepoWorktreeKey(
{
id: repo.id,
connectionId: repo.connectionId,
executionHostId: repo.executionHostId
},
repo.path
),
path: repo.path
worktreesForRepo[0] ?? {
// Why: fallback IDs must stay host-qualified so same repo IDs across hosts don't collide.
id: makeRepoWorktreeKey(
{
id: repo.id,
connectionId: repo.connectionId,
executionHostId: repo.executionHostId
},
repo.path
),
path: repo.path

Source: Coding guidelines

Comment on lines +27 to +29
function getProjectHostSetupKey(setup: Pick<ProjectHostSetup, 'hostId' | 'id'>): string {
return `${setup.hostId}\0${setup.id}`
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Document why the setup key uses a host-qualified composite format.

The \0 delimiter choice is non-obvious; add a brief why-comment to protect this disambiguation behavior during future refactors.

Suggested update
 function getProjectHostSetupKey(setup: Pick<ProjectHostSetup, 'hostId' | 'id'>): string {
+  // Why: setup IDs can repeat across hosts, so key by host+id to keep selection/removal stable.
   return `${setup.hostId}\0${setup.id}`
 }

As per coding guidelines, "When writing or modifying code driven by a design doc or non-obvious constraint, add a comment explaining why the code behaves the way it does."

Source: Coding guidelines

Comment on lines +221 to +223
setDeletingSetupKey(setupKey)
await deleteProjectHostSetup({ setupId: setup.id, hostId: setup.hostId })
setDeletingSetupKey(null)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Always clear deletingSetupKey when deletion fails.

If deleteProjectHostSetup rejects, the current code skips reset and can leave the row permanently non-removable until remount.

Suggested update
                   onClick={async () => {
-                    setDeletingSetupKey(setupKey)
-                    await deleteProjectHostSetup({ setupId: setup.id, hostId: setup.hostId })
-                    setDeletingSetupKey(null)
+                    setDeletingSetupKey(setupKey)
+                    try {
+                      await deleteProjectHostSetup({ setupId: setup.id, hostId: setup.hostId })
+                    } finally {
+                      setDeletingSetupKey(null)
+                    }
                   }}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
setDeletingSetupKey(setupKey)
await deleteProjectHostSetup({ setupId: setup.id, hostId: setup.hostId })
setDeletingSetupKey(null)
setDeletingSetupKey(setupKey)
try {
await deleteProjectHostSetup({ setupId: setup.id, hostId: setup.hostId })
} finally {
setDeletingSetupKey(null)
}

Comment on lines 8 to +17
type WorktreeChangeEvent = {
repoId: string
ownerHostId?: ExecutionHostId
renamed?: WorktreeRename
}

type WorktreeChangeRefreshHandler = (repoId: string, renamed?: WorktreeRename) => Promise<void>
type WorktreeChangeRefreshHandler = (
repoId: string,
ownerHostId?: ExecutionHostId,
renamed?: WorktreeRename

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not key queued refreshes to mutable focus.

The 'focused' fallback defers host selection until drain time. A local worktree event queued while local is active can drain after the user switches to a runtime host, causing the refresh to run against the wrong host.

🛡️ Suggested direction
 type WorktreeChangeEvent = {
   repoId: string
-  ownerHostId?: ExecutionHostId
+  ownerHostId: ExecutionHostId
   renamed?: WorktreeRename
 }
 
 type WorktreeChangeRefreshHandler = (
   repoId: string,
-  ownerHostId?: ExecutionHostId,
+  ownerHostId: ExecutionHostId,
   renamed?: WorktreeRename
 ) => Promise<void>
@@
 type RepoRefreshState = {
   repoId: string
-  ownerHostId?: ExecutionHostId
+  ownerHostId: ExecutionHostId
   running: boolean
   queue: QueuedWorktreeChange[]
 }
@@
   const getRefreshKey = (event: Pick<WorktreeChangeEvent, 'repoId' | 'ownerHostId'>) =>
-    `${event.ownerHostId ?? 'focused'}\0${event.repoId}`
+    `${event.ownerHostId}\0${event.repoId}`

Then pass the local owner explicitly at the local IPC enqueue site, e.g. { ...data, ownerHostId: LOCAL_EXECUTION_HOST_ID }.

Also applies to: 40-41, 64-70

Comment on lines +1608 to 1624
if (
!detectedForHost.authoritative &&
worktreesForHost.length === 0 &&
currentForHost &&
currentForHost.length > 0
) {
set((s) => ({
detectedWorktreesByRepo: { ...s.detectedWorktreesByRepo, [repoId]: detected }
detectedWorktreesByRepo: {
...s.detectedWorktreesByRepo,
[repoId]: mergeDetectedWorktreesForHost(
s.detectedWorktreesByRepo[repoId],
detectedForHost,
ownerHostId,
shouldTreatHostlessWorktreesAsLocal(s, repoId)
)
}
}))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve detected entries on transient empty host refreshes.

These stale-preservation branches keep worktreesByRepo, but still call mergeDetectedWorktreesForHost with an empty non-authoritative result. That splices out the current host’s detected entries, so later diffs/hidden-worktree metadata can behave as if those worktrees disappeared.

🛡️ Suggested preservation helper
+function preserveDetectedWorktreesAfterEmptyHostRefresh(
+  previous: DetectedWorktreeListResult | undefined,
+  fetched: DetectedWorktreeListResult
+): DetectedWorktreeListResult | undefined {
+  return previous
+    ? { ...previous, authoritative: false, source: fetched.source }
+    : previous
+}
+
@@
       if (
         !detectedForHost.authoritative &&
         worktreesForHost.length === 0 &&
         currentForHost &&
         currentForHost.length > 0
       ) {
-        set((s) => ({
-          detectedWorktreesByRepo: {
-            ...s.detectedWorktreesByRepo,
-            [repoId]: mergeDetectedWorktreesForHost(
-              s.detectedWorktreesByRepo[repoId],
-              detectedForHost,
-              ownerHostId,
-              shouldTreatHostlessWorktreesAsLocal(s, repoId)
-            )
-          }
-        }))
+        set((s) => {
+          const detected = preserveDetectedWorktreesAfterEmptyHostRefresh(
+            s.detectedWorktreesByRepo[repoId],
+            detectedForHost
+          )
+          return detected
+            ? { detectedWorktreesByRepo: { ...s.detectedWorktreesByRepo, [repoId]: detected } }
+            : s
+        })
         return false
       }

Apply the same branch-specific preservation in fetchAllWorktrees instead of falling through to the empty-host merge.

Also applies to: 1737-1747

@brennanb2025

Copy link
Copy Markdown
Contributor

Closing as superseded, with thanks — #6136 (merged June 23) covers this PR's scope renderer-side, including the headline behavior: repoId-less setup rows fall back to setup id per host and survive sibling-host refreshes (main keys setup ownership by host + repoId-or-setup-id), plus host-scoped pruning and ownership rules. The branch now conflicts with main in 23 files.

On the host-qualified worktree-identity commit: we reviewed it in depth, but it's a platform-scale ID migration (new persisted/wire format + lazy store migration) that needs its own design and a version-gated rollout rather than riding in a fix PR — the current head fails 60 of its own runtime tests, and in a real client↔server pairing the server's hostId=local perspective causes duplicated worktree lists on refresh.

Remaining host-blind lookups our review found on main are tracked in #9783.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

orca-remote-server Remote Orca Server / orca serve / paired remote runtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants