Skip to content

fix(remote-workspace): keep local tabs when a pulled snapshot reports none for a populated worktree - #12751

Closed
robertnisipeanu wants to merge 4 commits into
stablyai:mainfrom
robertnisipeanu:fix/remote-snapshot-empty-worktree-guard
Closed

robertnisipeanu wants to merge 4 commits into
stablyai:mainfrom
robertnisipeanu:fix/remote-snapshot-empty-worktree-guard

Conversation

@robertnisipeanu

@robertnisipeanu robertnisipeanu commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #12748

A pulled direct-SSH workspace snapshot that carries zero tabs for a worktree the renderer is showing tabs in leaves those tabs in place.

narrowDirectSshReplaceWorktreeIds removes such worktrees from the replace scope: local state wins until the remote reports at least one tab for the worktree. The snapshot carries no tombstones, so "no tabs" is indistinguishable from a regressed or corrupted snapshot — honoring it deletes terminal surfaces the user can see, unrecoverably, while keeping local state leaves surfaces the user can still close.

The narrowed scope drives every step of the apply: the merge (remote per-worktree records are filtered to the scope, so a spread cannot undo the narrowing), replaceWorkspaceKeys for hydrateWorkspaceSession/hydrateTabsSession, and reconnectPersistedTerminals — a protected worktree left in the hydration scope would still get its live tabs reset and swept into PTY reconnect.

mergeDirectSshRemoteWorkspaceSession applies the narrowing itself rather than relying on the caller to have done it. The narrowing predicate depends only on the worktree id and the three session inputs, never on the input set, so applying it twice is a no-op: the caller — which still needs the narrowed set as a value for replaceWorkspaceKeys — pays nothing, and no caller can delete a populated worktree's tabs by handing the merge a wider scope.

Worktrees with tabs on both sides are unaffected; the remote stays authoritative for them.

Bounded regression, not convergence

Single-client this converges: the next push re-exports the protected worktree, and a genuinely emptied worktree replaces once the remote reports any tab for it.

Multi-client it does not. Two clients against one SSH box is the point of a shared snapshot: if client B closes every tab in worktree W while client A still holds them, A protects, A pushes, and B's tabs come back. That repeats until the tabs are closed on the holding client too.

The trade is deliberate — resurrected tabs are visible and one click to close, deleted tabs are silent and permanent — but it is a bounded regression, not convergence. Real convergence needs tombstones plus a monotonic per-scope revision, tracked in #12447.

Testing

pnpm run typecheck:web and npx oxlint are clean; the renderer hook, store, and lib vitest suites pass.

Coverage runs at two levels. remote-workspace-session-merge.test.ts pins the merge, including that it narrows a replace scope handed to it un-narrowed. remote-workspace-snapshot-empty-worktree-guard.test.ts drives applyDirectSshRemoteWorkspaceSnapshot against a real store and asserts on post-apply state — live PTY bindings, pendingReconnectWorktreeIds, and the workspace keys handed to reconnectPersistedTerminals — so the hydration scope is pinned and not only the merge.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change narrows Direct SSH workspace replacement to worktrees with remote tabs or without local tabs. Remote tabs and related metadata are filtered to the narrowed scope. Snapshot application uses this scope for merging, recovery-tab selection, hydration, and terminal reconnection. Tests cover local-state preservation, remote replacement, empty or omitted worktrees, PTY mappings, and independent multi-worktree behavior.

Merge Risk: ⚪ Minimal · up to 30657

The change prevents a zero-tab remote snapshot from deleting visible local tabs. Remaining risk is limited to strengthening the regression test to assert the narrowed replacement scope directly; no actionable merge-blocking product risk remains.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the fix: preserving local tabs when a remote snapshot reports none for a populated worktree.
Description check ✅ Passed The description explains the problem, implementation, scope, linked issue, trade-offs, and testing, but omits most template headings and checklist items.
Linked Issues check ✅ Passed The changes protect populated worktrees and apply the narrowed scope consistently across merging, hydration, and terminal reconnection as required by #12748.
Out of Scope Changes check ✅ Passed The implementation and added tests directly support the linked issue and its snapshot-application requirements, with no unrelated changes identified.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

🧹 Nitpick comments (1)
src/renderer/src/hooks/remote-workspace-session-merge.ts (1)

17-25: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense the rationale comment.

Keep the data-loss rationale. Reduce this comment to one or two non-obvious sentences.

As per coding guidelines, TypeScript comments must be concise, non-obvious, and brief.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f7f16fa4-645f-4d03-9557-51a6eb5cdb33

📥 Commits

Reviewing files that changed from the base of the PR and between eea0bb6 and 9cde77be0af4e9b752d1a9b4f768f3314aa0bdb7.

📒 Files selected for processing (3)
  • src/renderer/src/hooks/remote-workspace-session-merge.test.ts
  • src/renderer/src/hooks/remote-workspace-session-merge.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts

@AmethystLiang
AmethystLiang requested a review from Jinwoo-H August 5, 2026 18:34
@Jinwoo-H

Jinwoo-H commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Reviewed reproduce-first. Verdict: merge with two commits on top. The direction and the implementation are both right — this is a real P0 and this patch fixes it.

Reproduced red on main first

Two levels deliberately, because the issue makes two claims and a merge-level unit can only express one of them. The second describe drives the real applyDirectSshRemoteWorkspaceSnapshot against a real zustand store. On main, tabsByWorktree['repo-a::/remote/work'] comes back undefined — the entire per-worktree record deleted, live PTY binding included.

I tried to find a better design and the field evidence killed it

tabsByWorktreePath can distinguish absent from explicitly [] — closeTab leaves tabsByWorktree[W] = [] rather than deleting the key, and the exporter emits that verbatim. So the narrower fix looked strictly better: treat an explicit [] as a real tombstone, protect only absence, and converge perfectly.

But the poisoned snapshot in #12721 held explicit [] for exactly the destroyed worktrees. Honoring [] would not have fixed the reported failure. Protecting both shapes is correct, and I'd rather record that I checked than have the next person re-litigate it.

Two gaps, both fixed on top

1. The tests don't cover the hydration path this PR fixes. Revert the single replaceWorkspaceKeys line and the P0 is fully back — with all 8 of your tests still green. The test file only ever calls the merge; it never touches applyDirectSshRemoteWorkspaceSnapshot. So the most fragile line in the change is unpinned. Now covered, and mutation-proven.

2. The merge boundary stays individually unsafe. Call mergeDirectSshRemoteWorkspaceSession with an un-narrowed scope and the P0 returns; the only protection is a doc comment asking callers to narrow first. On a data-loss boundary that's caller discipline, not a guarantee. Since narrowing is idempotent, the merge now re-applies it — the real caller pays nothing and the boundary refuses the destructive guess on its own.

Splitting narrowing into an exported pure function was the right factoring, since the caller genuinely needs the narrowed set as a value for replaceWorkspaceKeys. And scopedRemoteRecord is load-bearing — without it the remote's [] spreads straight back over the entry the narrowing just protected.

One thing the PR body overstates

"A genuinely emptied worktree converges once the remote reports any tab for it" is true only for the non-empty case. Multi-client — two laptops against one SSH box, which is the point of the shared snapshot — if client B closes every tab in W while A still holds them, A protects, A pushes, and B's tabs resurrect. That never converges.

I think that's the right trade (visible and one-click recoverable beats silent and permanent), but the honest framing is a bounded regression, not convergence. The real fix is tombstones plus a monotonic per-scope revision, already tracked as #12447.

Sibling paths, named not fixed

The paired remote runtime already does this correctly and is the model to copy: workspace-session-terminal-membership-authority.ts gates host-authoritative membership on an explicit terminalTopologyRevisionByRepoId counter plus terminalSurfaceTombstonesByPaneKey. That is precisely the design direct-SSH lacks.

mergeWorkspaceSessions/mergeHostWorkspaceSessions are the same class but weaker exposure — absence-safe, but an incoming [] still overwrites a populated base. One-shot profile transfer, so it can't self-sustain the way #12721 does.

Folder workspaces are structurally exempt: exactTargetWorktreeIds takes only gitWorktreeIds, so their keys never enter the replace scope. (They also never sync — a separate gap, not this bug.)

Note on CI

Only track-community-pr has run on this. No tests, no typecheck, no lint. Worth getting the real lanes green before merge given what it touches. Happy to push the two commits to this branch — say the word.

@robertnisipeanu

Copy link
Copy Markdown
Contributor Author

Thanks for the reproduce-first review — and for recording the []-as-tombstone investigation rather than just discarding it. The #12721 detail that the poisoned snapshot held explicit [] for exactly the destroyed worktrees is the thing that would have been re-litigated otherwise.

I've pushed both commits myself, so no need to duplicate the work:

test(remote-workspace): cover the snapshot apply path… — drives applyDirectSshRemoteWorkspaceSnapshot against a real store and asserts on post-apply state: the protected worktree keeps its live PTY bindings, stays out of pendingReconnectWorktreeIds, and is absent from the workspace keys handed to reconnectPersistedTerminals, while the worktree the snapshot does carry tabs for still replaces. Reverting the single replaceWorkspaceKeys line fails it, with the merge tests all still green — your point exactly.

fix(remote-workspace): narrow the replace scope inside the merge — mergeDirectSshRemoteWorkspaceSession re-applies the narrowing itself. It is filter idempotence rather than a happy accident: the predicate depends only on (worktreeId, current, remote, liveTabsByWorktree) and never on the input set, so narrow(narrow(X)) === narrow(X) for any X. The caller still computes the narrowed set once because it genuinely needs it as a value for replaceWorkspaceKeys, and pays nothing for the second application.

I also condensed the rationale block above narrowDirectSshReplaceWorktreeIds (CodeRabbit had asked), and corrected the convergence sentence inside it to point at #12447 rather than claim convergence.

On the convergence claim: you're right, and the PR body now frames it as a bounded regression. Your multi-client case holds as stated — A protects, A pushes, B's tabs come back, and nothing in this patch breaks that loop. One refinement rather than a pushback: the loop ends as soon as the tabs are closed on the holding client too, so it is "does not converge on its own" rather than "unrecoverable". That doesn't change the trade or the framing, and #12447 is still the real fix.

On the CodeRabbit thread at remote-workspace-session-merge.ts:52 (keep active selection inside the replacement scope) — I tried the change and then backed it out; details in a reply on that thread. Short version: measured end-to-end, the reported harm doesn't occur, and the one-line version trades a navigation preference for a merge output whose activeTabId names a tab the merged list doesn't contain. Happy to take it as a follow-up if you read it differently.

CI: locally pnpm run typecheck:web and npx oxlint are clean, and the renderer hook/store/lib vitest suites pass. The real lanes still need a maintainer to approve the workflow run on this fork PR.

@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

🧹 Nitpick comments (1)
src/renderer/src/hooks/remote-workspace-snapshot-empty-worktree-guard.test.ts (1)

1-11: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reduce the file header comment.

Keep only the non-obvious reason that this test uses the full snapshot application path. The remaining text repeats the test behavior.

Proposed change
-/**
- * Drives the real snapshot apply against a real store. A pulled snapshot that
- * reports no tabs for a worktree the renderer is showing tabs in must leave that
- * worktree's live terminals untouched, while a worktree the snapshot does carry
- * tabs for still replaces.
- *
- * The merge alone cannot express this: a merge that protects the worktree still
- * loses its live PTY bindings if the worktree stays in the hydration replace
- * scope, so the assertions below read post-apply store state and the scope handed
- * to reconnect rather than the merge result.
- */
+/**
+ * Test full snapshot application because merge-only tests cannot verify
+ * hydration and terminal reconnection scope.
+ */

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0fb680e0-f35b-4c55-8f9b-ed98a7410f7c

📥 Commits

Reviewing files that changed from the base of the PR and between 9cde77be0af4e9b752d1a9b4f768f3314aa0bdb7 and d6a45d7a41142b9abc0cf1e8ec2a1dfab7c0250a.

📒 Files selected for processing (3)
  • src/renderer/src/hooks/remote-workspace-session-merge.test.ts
  • src/renderer/src/hooks/remote-workspace-session-merge.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-empty-worktree-guard.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/hooks/remote-workspace-session-merge.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 Plus

Run ID: bb17a925-fcb8-4205-bab2-32bedc29da0b

📥 Commits

Reviewing files that changed from the base of the PR and between d6a45d7a41142b9abc0cf1e8ec2a1dfab7c0250a and 13798e4a94934c3d4ce13dd358b705abb9b9bfc3.

📒 Files selected for processing (4)
  • new-pr-body.md
  • reply-to-coderabbit-active-selection.md
  • reply-to-jinwoo.md
  • src/renderer/src/hooks/remote-workspace-session-merge.test.ts

Comment thread reply-to-jinwoo.md Outdated

**`test(remote-workspace): cover the snapshot apply path…`** — drives `applyDirectSshRemoteWorkspaceSnapshot` against a real store and asserts on post-apply state: the protected worktree keeps its live PTY bindings, stays out of `pendingReconnectWorktreeIds`, and is absent from the workspace keys handed to `reconnectPersistedTerminals`, while the worktree the snapshot does carry tabs for still replaces. Reverting the single `replaceWorkspaceKeys` line fails it, with the merge tests all still green — your point exactly.

**`fix(remote-workspace): narrow the replace scope inside the merge`** — `mergeDirectSshRemoteWorkspaceSession` re-applies the narrowing itself. It is filter idempotence rather than a happy accident: the predicate depends only on `(worktreeId, current, remote, liveTabsByWorktree)` and never on the input set, so `narrow(narrow(X)) === narrow(X)` for any `X`. The caller still computes the narrowed set once because it genuinely needs it as a value for `replaceWorkspaceKeys`, and pays nothing for the second application.

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.

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Correct the statement about the second narrowing pass.

Idempotence removes the second pass's semantic effect. It does not make the pass free. The caller still incurs filtering and possible allocation costs unless the implementation explicitly short-circuits the operation.

Use “has no additional semantic effect” instead of “pays nothing.”

Suggested wording
- The caller still computes the narrowed set once because it genuinely needs it as a value for `replaceWorkspaceKeys`, and pays nothing for the second application.
+ The caller still computes the narrowed set once because it genuinely needs it as a value for `replaceWorkspaceKeys`; the second application has no additional semantic effect.
📝 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
**`fix(remote-workspace): narrow the replace scope inside the merge`** — `mergeDirectSshRemoteWorkspaceSession` re-applies the narrowing itself. It is filter idempotence rather than a happy accident: the predicate depends only on `(worktreeId, current, remote, liveTabsByWorktree)` and never on the input set, so `narrow(narrow(X)) === narrow(X)` for any `X`. The caller still computes the narrowed set once because it genuinely needs it as a value for `replaceWorkspaceKeys`, and pays nothing for the second application.
**`fix(remote-workspace): narrow the replace scope inside the merge`** — `mergeDirectSshRemoteWorkspaceSession` re-applies the narrowing itself. It is filter idempotence rather than a happy accident: the predicate depends only on `(worktreeId, current, remote, liveTabsByWorktree)` and never on the input set, so `narrow(narrow(X)) === narrow(X)` for any `X`. The caller still computes the narrowed set once because it genuinely needs it as a value for `replaceWorkspaceKeys`; the second application has no additional semantic effect.

robertnisipeanu and others added 4 commits August 15, 2026 01:18
… none for a populated worktree

Co-Authored-By: Claude Fable 5 <[email protected]>
…the remote reports no tabs for

Drives applyDirectSshRemoteWorkspaceSnapshot against a real store and asserts on
post-apply state: the protected worktree keeps its live PTY bindings, stays out
of pendingReconnectWorktreeIds, and is absent from the workspace keys handed to
reconnectPersistedTerminals, while the worktree the snapshot does carry tabs for
still replaces.

The merge-level tests cannot express this. They exercise the merge in isolation,
so a hydration scope that still contains the protected worktree resets its tabs
and sweeps them into PTY reconnect with every merge assertion green.

Co-Authored-By: Claude Fable 5 <[email protected]>
mergeDirectSshRemoteWorkspaceSession narrows the requested replace scope itself
rather than relying on callers to have narrowed it. Narrowing is idempotent, so
the production caller — which still needs the narrowed set as a value for
replaceWorkspaceKeys — is unaffected, and no caller can delete a populated
worktree's tabs by handing the merge a wider scope.

Co-Authored-By: Claude Fable 5 <[email protected]>
@robertnisipeanu
robertnisipeanu force-pushed the fix/remote-snapshot-empty-worktree-guard branch from 13798e4 to 306573a Compare August 14, 2026 23:15
@coderabbitai

coderabbitai Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

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

Run ID: 0ce3a933-3a31-496b-9e1e-a8de7f163ac0

📥 Commits

Reviewing files that changed from the base of the PR and between 19bc1cc and 306573a.

📒 Files selected for processing (4)
  • src/renderer/src/hooks/remote-workspace-session-merge.test.ts
  • src/renderer/src/hooks/remote-workspace-session-merge.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-empty-worktree-guard.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-empty-worktree-guard.test.ts
  • src/renderer/src/hooks/remote-workspace-session-merge.ts

Comment on lines +111 to +119
it('keeps local tabs for an in-scope worktree the remote snapshot omits entirely', () => {
const localTabs = [tab('tab-1', WT)]
const expectedTabs = structuredClone(localTabs)
const current = session({ tabsByWorktree: { [WT]: localTabs } })
const remote = session()

const { merged } = narrowAndMerge(current, remote, new Set([WT]), { [WT]: localTabs })

expect(merged.tabsByWorktree[WT]).toEqual(expectedTabs)

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the narrowed scope for an omitted remote worktree.

This test only checks the final merge result. mergeDirectSshRemoteWorkspaceSession reapplies narrowing internally. If narrowDirectSshReplaceWorktreeIds fails to remove WT, this test can still pass. Capture replaceWorktreeIds and assert that it is empty.

The PR objective requires omitted remote worktree records to preserve local state.

Proposed test change
-    const { merged } = narrowAndMerge(current, remote, new Set([WT]), { [WT]: localTabs })
+    const { merged, replaceWorktreeIds } = narrowAndMerge(current, remote, new Set([WT]), {
+      [WT]: localTabs
+    })
 
+    expect([...replaceWorktreeIds]).toEqual([])
     expect(merged.tabsByWorktree[WT]).toEqual(expectedTabs)
📝 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
it('keeps local tabs for an in-scope worktree the remote snapshot omits entirely', () => {
const localTabs = [tab('tab-1', WT)]
const expectedTabs = structuredClone(localTabs)
const current = session({ tabsByWorktree: { [WT]: localTabs } })
const remote = session()
const { merged } = narrowAndMerge(current, remote, new Set([WT]), { [WT]: localTabs })
expect(merged.tabsByWorktree[WT]).toEqual(expectedTabs)
it('keeps local tabs for an in-scope worktree the remote snapshot omits entirely', () => {
const localTabs = [tab('tab-1', WT)]
const expectedTabs = structuredClone(localTabs)
const current = session({ tabsByWorktree: { [WT]: localTabs } })
const remote = session()
const { merged, replaceWorktreeIds } = narrowAndMerge(current, remote, new Set([WT]), {
[WT]: localTabs
})
expect([...replaceWorktreeIds]).toEqual([])
expect(merged.tabsByWorktree[WT]).toEqual(expectedTabs)
🧰 Tools
🪛 ast-grep (0.45.1)

[warning] 113-113: Enforce overriding default config
Context: session({ tabsByWorktree: { [WT]: localTabs } })
Note: [CWE-1188] Insecure Default Initialization of Resource (default session cookie name not overridden).

(default-session-config-typescript)

@robertnisipeanu

Copy link
Copy Markdown
Contributor Author

Superseded by #14844: the session merge on main now unions the remote snapshot's worktree keys with replace-scope worktrees that hold local tabs, and its host-unknown branch grafts local tabs the snapshot does not carry — so a pulled snapshot reporting zero tabs for a populated worktree no longer erases the local tabs. remote-workspace-session-merge-local-survival.test.ts and remote-workspace-snapshot-local-tab-survival.test.ts pin that behavior.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A pulled remote workspace snapshot with zero tabs for a populated worktree permanently deletes the local tabs

4 participants