Skip to content

Preserve remote host repo state - #6136

Merged
brennanb2025 merged 7 commits into
mainfrom
brennanb2025/issue-6032-remote-host-state
Jun 23, 2026
Merged

brennanb2025 merged 7 commits into
mainfrom
brennanb2025/issue-6032-remote-host-state

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Preserves host-scoped repo, project, and worktree state when the same logical repo id exists on local and remote/runtime hosts. The renderer now routes repo refresh, update, remove, reorder, project compatibility, and worktree refresh paths through host-qualified repo identity instead of treating bare repo ids as globally unique.

Design Review

Brennan YOLO Lite design review completed cleanly after tightening the design around ambiguous duplicate-host fallback, host-scoped project compatibility merging, worktree bucket preservation, and map/set-style reconciliation cost.

Implementation Notes

  • Added concrete host identity helpers for repo rows.
  • Changed repo reconciliation and host refresh merging to key by execution-host plus repo id.
  • Scoped update/remove/reorder paths to the focused/owning host and preserved sibling host project compatibility and projectHostSetups.
  • Made worktree owner resolution and fetchAllWorktrees merge host-aware without changing the persisted worktreesByRepo shape.
  • Addressed CodeRabbit findings for queued repo update host pinning, ProjectHostSetup repo mutations, host-scoped recency cleanup, all-host reorder resync, hostless hydrated purge ids, and stable in-place host worktree merges.

No UI layout/copy changes were made.

Completeness Verification

Read-only completeness verification reported COMPLETE against the reviewed design. It noted non-blocking residual gaps around a few standalone helper edge tests and full remote-server e2e feasibility.

Code Review

Round 1 ran two independent reviewers. One reviewer found a real hostless legacy worktree purge bug in repo removal; fixed with a production predicate change and regression test. Round 2 ran two fresh independent reviewers; both returned No issues found, with only non-blocking residual test-gap notes.

Post-PR CodeRabbit review findings were fixed and rechecked. Latest CodeRabbit sweep reports no actionable comments on the current head.

Brennan Test Changes

Brennan test validation verdict: LAND. Deterministic store coverage exercises duplicate repo ids across local/runtime hosts for update, remove, reorder, reconciliation, and worktree refresh. Full remote-server e2e was not run; the remaining gap is explicit because the bug is store reconciliation/routing and is covered by deterministic mocked runtime transport tests.

Manual / Electron Validation

  • Launched Orca dev from this branch with CDP port 9335.
  • Verified window.api.app.getIdentity() reported devRepoRoot as this issue worktree.
  • Captured visible app screenshot evidence locally at design-docs/evidence/issue-6032-electron.png (ignored scratch evidence, not committed).

Tests

  • pnpm vitest run --config config/vitest.config.ts src/renderer/src/store/slices/repos-host-identity-routing.test.ts src/renderer/src/store/slices/settings.test.ts src/renderer/src/store/slices/worktrees.test.ts src/renderer/src/store/slices/repos-project-host-lifecycle.test.ts src/renderer/src/store/slices/repos.test.ts src/renderer/src/store/slices/repos-all-hosts.test.ts src/renderer/src/lib/repo-runtime-owner.test.ts src/renderer/src/store/slices/repo-reorder-host-split.test.ts — 209 passed
  • pnpm vitest run --config config/vitest.config.ts src/renderer/src/store/slices/repos-host-identity-routing.test.ts src/renderer/src/store/slices/repos.test.ts src/renderer/src/store/slices/worktrees.test.ts — 179 passed
  • pnpm run typecheck — passed
  • pnpm run typecheck:web — passed
  • Focused pnpm exec oxlint on changed files — passed
  • git diff --check — passed
  • pnpm test — one full local pass earlier in stabilization; later full local reruns hit unrelated transient timeouts/flakes (remote-runtime-shared-control-connection timeout once, WorktreeCard.quick-actions import timeout once), and both affected suites passed on immediate focused rerun.
  • PR verify check — passed on current head.
  • pnpm run lint — blocked locally by pre-existing localization catalog keys in untouched TerminalInteractionSection.tsx; localization coverage itself passed.

Post-PR Stabilization

Completed multiple required sleep 480 waits after pushes. CodeRabbit latest review reports no actionable comments on the current head, review threads are resolved/addressed, and GitHub PR verify is SUCCESS.

Risks / Gaps

  • A live Remote Orca Server e2e was not run; deterministic runtime RPC/store tests cover the affected reconciliation and routing behavior.
  • Ambiguous duplicate repo id operations intentionally no-op when the focused host cannot disambiguate; that is safer than choosing the wrong host, but future UI feedback could make the state clearer.

@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR introduces host-aware repo identity throughout the renderer store and library layers to correctly handle repos that share the same id but exist on different execution hosts (local vs. runtime environments). A new repo-host-identity.ts module provides composite hostId\0repoId identity strings and a findRepoForHost selector that disambiguates duplicates using the focused execution host from settings. This identity model is propagated into repo reconciliation (keyed map now uses host identity), reorder splitting (queue-per-id replaces single map), runtime owner resolution, and all major repos.ts mutation operations. The worktrees.ts slice similarly gains host-scoped merge, purge, and fetch paths, with comprehensive test coverage for duplicate-ID scenarios.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.38% 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 remote host repo state' clearly describes the main change: enabling the system to maintain separate state for the same repo ID across different hosts.
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.
Description check ✅ Passed The PR description comprehensively covers all required template sections with detailed information about the changes, design review, implementation notes, testing, and code review findings.

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


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.

@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: 7

Caution

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

⚠️ Outside diff range comments (5)
src/renderer/src/store/slices/repos.ts (4)

2221-2232: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

Pin queued repo updates to the captured owner host.

ownerHostId is captured before chaining, but applyRepoUpdate recomputes the RPC target from the current focused settings when the queued update runs. If focus changes while a prior update is pending, the next update can be sent to the wrong host and then applied to the captured host row.

🐛 Proposed fix
     }
     const ownerHostId = getRepoExecutionHostId(ownerRepo)
     const updateChainKey = getRepoHostIdentityForParts(projectId, ownerHostId)
+    const parsedOwnerHost = parseExecutionHostId(ownerHostId)
+    const ownerTarget =
+      parsedOwnerHost?.kind === 'runtime'
+        ? ({ kind: 'environment', environmentId: parsedOwnerHost.environmentId } as const)
+        : ({ kind: 'local' } as const)
     const applyRepoUpdate = async () => {
       try {
         const sanitizedUpdates = sanitizeRepoUpdate(updates)
-        const target = getActiveRuntimeTarget(settingsForRepoOwner(get(), projectId))
+        const target = ownerTarget
         const updatedRepo =

Also applies to: 2281-2286


1752-1761: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Use host identity in ProjectHostSetup repo mutations.

These setup flows still match repos by entry.id === repo.id. With duplicate local/runtime repo IDs, setup/create/update can overwrite the sibling host row, and setup delete can remove all siblings.

🐛 Proposed fix
       const repo = repoWithFetchedOwner(result.repo, target)
+      const repoHostId = getRepoExecutionHostId(repo)
       const setup = setupWithFetchedOwner(result.setup, target)
       set((s) => {
-        const nextRepos = s.repos.some((entry) => entry.id === repo.id)
-          ? s.repos.map((entry) => (entry.id === repo.id ? repo : entry))
+        const nextRepos = s.repos.some((entry) =>
+          repoMatchesHostIdentity(entry, repo.id, repoHostId)
+        )
+          ? s.repos.map((entry) =>
+              repoMatchesHostIdentity(entry, repo.id, repoHostId) ? repo : entry
+            )
           : [...s.repos, repo]
       const setup = setupWithFetchedOwner(result.setup, target)
       const repo = result.repo ? repoWithFetchedOwner(result.repo, target) : undefined
+      const repoHostId = repo ? getRepoExecutionHostId(repo) : null
       set((s) => ({
         repos: repo
-          ? s.repos.some((entry) => entry.id === repo.id)
-            ? s.repos.map((entry) => (entry.id === repo.id ? repo : entry))
+          ? s.repos.some((entry) => repoMatchesHostIdentity(entry, repo.id, repoHostId!))
+            ? s.repos.map((entry) =>
+                repoMatchesHostIdentity(entry, repo.id, repoHostId!) ? repo : entry
+              )
             : [...s.repos, repo]
           : s.repos,
       const repo = result.repo ? repoWithFetchedOwner(result.repo, target) : undefined
+      const repoHostId = repo ? getRepoExecutionHostId(repo) : null
       set((s) => {
         const projectHostSetups = s.projectHostSetups.filter(
           (setup) => setup.id !== result.setup.id
         )
-        const repos = repo ? s.repos.filter((entry) => entry.id !== repo.id) : s.repos
+        const repos =
+          repo && repoHostId
+            ? s.repos.filter((entry) => !repoMatchesHostIdentity(entry, repo.id, repoHostId))
+            : s.repos

Also applies to: 1839-1850, 1882-1887


2117-2139: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Filter last-visited cleanup by the host-owned worktree set.

The removal path now computes host-scoped worktreeIds, but this loop still deletes every timestamp whose worktree ID parses to the bare projectId. Removing one duplicate host can wipe the sibling host’s recency state.

🐛 Proposed fix
         let nextLastVisitedAtByWorktreeId = s.lastVisitedAtByWorktreeId
         for (const id of Object.keys(s.lastVisitedAtByWorktreeId)) {
-          if (getRepoIdFromWorktreeId(id) === projectId) {
+          if (worktreeIdSet.has(id)) {
             if (nextLastVisitedAtByWorktreeId === s.lastVisitedAtByWorktreeId) {
               nextLastVisitedAtByWorktreeId = { ...s.lastVisitedAtByWorktreeId }
             }

2349-2354: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Resync all hosts after a split reorder failure.

splitRepoReorderByHost can persist order to non-active hosts, but the rejection/catch fallback calls fetchRepos(), which refreshes only the focused target. A remote-host rejection while local is focused leaves the optimistic remote order stale.

🐛 Proposed fix
       )
       if (results.some((result) => result.status === 'rejected')) {
-        await get().fetchRepos()
+        await get().fetchReposForAllHosts()
       }
     } catch (err) {
       console.error('Failed to reorder repos:', err)
-      await get().fetchRepos()
+      await get().fetchReposForAllHosts()
     }
src/renderer/src/store/slices/worktrees.ts (1)

382-409: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Treat hostless hydrated purge IDs as local-only.

Now that this helper is host-scoped, Line 405 still adds legacy hydrated session IDs for every host. A runtime/SSH authoritative scan can then purge local legacy tab state just because those hostless IDs are absent from that remote scan. Gate this fallback to LOCAL_EXECUTION_HOST_ID.

🐛 Proposed fix
-  if (!state.hasHydratedWorktreePurge) {
+  if (!state.hasHydratedWorktreePurge && hostId === LOCAL_EXECUTION_HOST_ID) {
     // Why (`#1158`): hydration can preserve tab keys before worktree metadata exists;
     // the first authoritative scan still needs to reap deleted session-only keys.
     for (const id of getHydratedSessionWorktreeIdsForRepo(state, repoId)) {
       knownIds.add(id)
🧹 Nitpick comments (2)
src/renderer/src/store/slices/repos-host-identity-routing.test.ts (2)

74-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a regression for queued updates after focus changes.

This covers the immediate runtime update path, but not the chained updateRepo path where applyRepoUpdate can run after settings.activeRuntimeEnvironmentId changes. Add a pending first update, switch focus, then assert the queued update still targets env-1.


102-207: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert sibling-host recency metadata survives removal.

The removal tests cover worktrees, tabs, and PTYs, but not lastVisitedAtByWorktreeId. Add local/remote timestamp assertions so host-scoped removal cannot regress to bare-repo-ID purging.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: decf33fc-b00c-4c7d-94b7-6c90144e3b16

📥 Commits

Reviewing files that changed from the base of the PR and between f3e379d and 15e304f.

📒 Files selected for processing (11)
  • src/renderer/src/lib/repo-runtime-owner.test.ts
  • src/renderer/src/lib/repo-runtime-owner.ts
  • src/renderer/src/store/slices/repo-host-identity.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-host-identity-routing.test.ts
  • src/renderer/src/store/slices/repos.ts
  • src/renderer/src/store/slices/worktrees.test.ts
  • src/renderer/src/store/slices/worktrees.ts

@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: 1

Caution

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

⚠️ Outside diff range comments (1)
src/renderer/src/store/slices/worktrees.ts (1)

450-469: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Apply host ownership to hydrated session-only purge IDs.

The purge baseline is host-scoped, but this hydration fallback still adds every session-only ID for the bare repo ID. A first authoritative scan for a runtime duplicate can therefore purge sibling local tab/terminal state before that sibling host refreshes.

🐛 Proposed guard
-  if (!state.hasHydratedWorktreePurge) {
+  if (!state.hasHydratedWorktreePurge && matchOptions.unhostedWorktreesMatchHost === true) {
     // Why (`#1158`): hydration can preserve tab keys before worktree metadata exists;
     // the first authoritative scan still needs to reap deleted session-only keys.
     for (const id of getHydratedSessionWorktreeIdsForRepo(state, repoId)) {
       knownIds.add(id)
🧹 Nitpick comments (1)
src/renderer/src/store/slices/worktrees.ts (1)

424-427: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Keep host merges stable in-place.

This removes the refreshed host rows and appends them after sibling-host rows. With duplicate repo IDs, alternating local/runtime refreshes can rewrite array order and bump sortEpoch even when the refreshed payload is unchanged.

♻️ Proposed stable merge
 function mergeWorktreesForHost<T extends { hostId?: ExecutionHostId }>(
   current: readonly T[] | undefined,
   refreshed: readonly T[],
   hostId: ExecutionHostId,
   options?: WorktreeHostMatchOptions
 ): T[] {
-  return [
-    ...(current ?? []).filter((worktree) => !worktreeMatchesHost(worktree, hostId, options)),
-    ...refreshed
-  ]
+  // Why: host-scoped refreshes must not move sibling-host rows and churn sortEpoch.
+  const existing = current ?? []
+  const next: T[] = []
+  let inserted = false
+
+  for (const worktree of existing) {
+    if (worktreeMatchesHost(worktree, hostId, options)) {
+      if (!inserted) {
+        next.push(...refreshed)
+        inserted = true
+      }
+      continue
+    }
+    next.push(worktree)
+  }
+
+  return inserted ? next : [...next, ...refreshed]
 }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 930a52bc-4a11-4292-8555-71b853129e59

📥 Commits

Reviewing files that changed from the base of the PR and between 15e304f and b33f7ab.

📒 Files selected for processing (1)
  • src/renderer/src/store/slices/worktrees.ts

@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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0f640ffc-6912-4500-bcf1-c712b1875070

📥 Commits

Reviewing files that changed from the base of the PR and between b33f7ab and 91778cb.

📒 Files selected for processing (6)
  • src/renderer/src/lib/repo-runtime-owner.ts
  • src/renderer/src/store/slices/repo-host-identity.ts
  • src/renderer/src/store/slices/repo-reorder-host-split.ts
  • src/renderer/src/store/slices/repos-host-identity-routing.test.ts
  • src/renderer/src/store/slices/repos.ts
  • src/renderer/src/store/slices/worktrees.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/renderer/src/store/slices/repo-reorder-host-split.ts
  • src/renderer/src/store/slices/repo-host-identity.ts
  • src/renderer/src/lib/repo-runtime-owner.ts
  • src/renderer/src/store/slices/worktrees.ts

Comment thread src/renderer/src/store/slices/repos.ts Resolved
@brennanb2025
brennanb2025 merged commit 9e88231 into main Jun 23, 2026
1 check passed
@brennanb2025
brennanb2025 deleted the brennanb2025/issue-6032-remote-host-state branch June 23, 2026 22:38
AmethystLiang added a commit that referenced this pull request Jun 24, 2026
* fix: address pr-bug-scan validated finding from #6136

removeProject now also drops lastVisitedAtByWorktreeId entries by repo-id mapping when the repo id is fully removed (no sibling host), catching unhydrated worktree timestamps.

* test: cover unhydrated SSH timestamp cleanup

* Test dropping visit timestamps for removed runtime repos

Verify that removing an unhydrated runtime repository successfully drops
its associated worktree entries from the persisted visit history.

---------

Co-authored-by: orca-bug-scan-bot <[email protected]>
Co-authored-by: Jinjing <[email protected]>
@AmethystLiang AmethystLiang added the orca-remote-server Remote Orca Server / orca serve / paired remote runtime label Jul 22, 2026
@AmethystLiang

Copy link
Copy Markdown
Contributor

looking into it

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix: address pr-bug-scan validated finding from stablyai#6136

removeProject now also drops lastVisitedAtByWorktreeId entries by repo-id mapping when the repo id is fully removed (no sibling host), catching unhydrated worktree timestamps.

* test: cover unhydrated SSH timestamp cleanup

* Test dropping visit timestamps for removed runtime repos

Verify that removing an unhydrated runtime repository successfully drops
its associated worktree entries from the persisted visit history.

---------

Co-authored-by: orca-bug-scan-bot <[email protected]>
Co-authored-by: Jinjing <[email protected]>
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.

2 participants