Skip to content

fix(remote-workspace): stop stale snapshot applies from erasing freshly created terminal tabs - #13013

Closed
robertnisipeanu wants to merge 24 commits into
stablyai:mainfrom
robertnisipeanu:fix/remote-session-write-loss
Closed

robertnisipeanu wants to merge 24 commits into
stablyai:mainfrom
robertnisipeanu:fix/remote-session-write-loss

Conversation

@robertnisipeanu

Copy link
Copy Markdown
Contributor

Problem

A terminal tab created around a direct-SSH remote-workspace snapshot apply can be permanently lost:

  1. createSessionWriteSubscriber drops its pending write while an apply suppresses persistence (pendingChangedFields.clear()), so the tab never reaches the remote session store — the suppression window can last up to 30s of terminal reconnects plus a 1s trailing window.
  2. The apply then replaces the worktree's tab list from the snapshot, which was fetched before the tab existed. mergeDirectSshRemoteWorkspaceSession iterates only remote.tabsByWorktree, so a local-only tab cannot survive it.
  3. Local state now matches the snapshot byte-for-byte, so the next push no-ops via remoteWorkspaceSessionMatchesSnapshot — the remote store never learns the tab existed.

The tab's pty keeps running unreachable on the host, and any sleeping-agent record for the tab is stranded against a tab id that no longer exists. Observed in production: an agent launched into a fresh tab moments before a wake-refresh apply; the tab was erased within seconds while its claude process kept running on the host.

Fix

  • Hold suppressed writes instead of dropping them. The subscriber's flush retries at the debounce cadence until suppression lifts, bounded by a 60s hold ceiling so back-to-back applies (or a misbehaving remote streaming new snapshot revisions) cannot starve local persistence indefinitely. Past the ceiling the write proceeds; the payload is rebuilt from the current store, which is always self-consistent.
  • Graft live local tabs into a stale snapshot before the merge. A snapshot whose in-scope tab lists are missing a tab that is live locally — mid-reattach per the recovery ledger, or with an attached pty per ptyIdsByTabId — predates the session write that created that tab. The tab is appended to the snapshot's list for its worktree and added to the merge's preserve set, so its layout and session ids survive. Remote-only tabs from other clients still apply unchanged, and tabs without a live pty are still removed when the remote store says so — this cannot resurrect tabs deleted on another device.

Tests

  • Subscriber: held write lands after suppression lifts (suppressed at schedule time and mid-debounce); force-flush once the 60s ceiling passes.
  • staleDirectSshSnapshotTabIds and graftLocalTabsIntoRemoteSession unit tests.
  • Integration (target-sync): a live local tab omitted by an incoming snapshot survives the merge, with its layout, alongside the snapshot's remote-only tab.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Aug 7, 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

The changes add direct SSH tab observation and authority validation across the main process, preload bridge, and renderer. The main process retains bounded tab intents, reconciles snapshots, and acknowledges patch results. The renderer preserves local tab additions and deletions during snapshot application. Session writes remain pending during suppression and flush after readiness or a bounded deadline. Tests cover ownership, ordering, retention, scale, persistence, and end-to-end snapshot races.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, fix, and tests, but it omits required sections such as Linked Issue, Visual Proof, Review, and Checklist. Add all required template sections, include a linked issue, provide visual proof or N/A with a reason, and complete testing and review checklists.
Docstring Coverage ⚠️ Warning Docstring coverage is 2.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary fix: preventing stale remote-workspace snapshots from erasing newly created terminal tabs.
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.

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-snapshot-apply.ts (1)

78-84: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense the new rationale comments.

Keep each comment to one concise statement of the non-obvious reason.

  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts#L78-L84: Reduce the stale-snapshot rationale to one line.
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts#L101-L106: Reduce the graft-and-merge rationale to one line.
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts#L165-L167: Reduce the recovery and live-PTY distinction to one line.

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 527bd11a-3c5a-4c91-9235-7246a9c00c4d

📥 Commits

Reviewing files that changed from the base of the PR and between f057cbc and 587ea496d48b60f9c9473f47092f1246e66687eb.

📒 Files selected for processing (5)
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.test.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts
  • src/renderer/src/hooks/remote-workspace-target-sync.test.ts
  • src/renderer/src/lib/session-write-subscriber.test.ts
  • src/renderer/src/lib/session-write-subscriber.ts

@AmethystLiang
AmethystLiang requested a review from OrcaWin August 7, 2026 16:48
@Jinwoo-H
Jinwoo-H force-pushed the fix/remote-session-write-loss branch from 587ea49 to b425e87 Compare August 10, 2026 23:30
@coderabbitai

coderabbitai Bot commented Aug 10, 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: 12

🧹 Nitpick comments (9)
tests/e2e/helpers/remote-workspace-snapshot-request-barrier.ts (1)

15-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract a shared invoke-handler barrier helper.

Both barrier files duplicate installation, state management, release, and restoration for different channels. Parameterize the helper with the channel name and request predicate while preserving each barrier’s capture timing.

tests/e2e/global-teardown.ts (1)

28-33: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Strip trailing carriage returns from parsed worktree paths.

Line 28 splits only on \n. If the Git output uses CRLF on Windows, worktreePath keeps a trailing \r. path.basename then returns a name ending in \r, the prefix check at line 36 still matches, and rmSync targets a nonexistent path. The removal then fails silently because force: true suppresses the error.

The repository requires cleanup scripts to work on macOS, Linux, and Windows, so normalize the line ending.

♻️ Proposed change
-      for (const line of worktreeList.split('\n')) {
+      for (const rawLine of worktreeList.split('\n')) {
+        const line = rawLine.replace(/\r$/, '')
         if (!line.startsWith('worktree ')) {
           continue
         }

Source: Coding guidelines

src/main/ipc/remote-workspace-tab-intent-reconciliation.ts (1)

111-115: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Avoid creating an empty worktree-path key for a no-op absent intent.

If tabsByWorktreePath has no key for worktree.worktreePath, tabs is [] and line 113 writes an empty array under a key the remote snapshot never had. The reconciled snapshot then carries a path entry that the remote session does not carry. sessionMatchesTabObservation compares path sets by exact size and membership, so the extra key can make a later full-snapshot match fail.

Skip the assignment when the removal changes nothing.

♻️ Proposed guard
     } else if (intent.presence === 'absent' && !currentTab) {
       const remaining = tabs.filter((tab) => !remoteTabIdentityMatches(tab, intent.tab.tab))
-      reconciled.session.tabsByWorktreePath[worktree.worktreePath] = remaining
+      if (remaining.length !== tabs.length) {
+        reconciled.session.tabsByWorktreePath[worktree.worktreePath] = remaining
+      }
src/main/ipc/remote-workspace-tab-intent-retention.ts (1)

22-24: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Compute the intent byte sizes once per retain call.

retain calls intentBytes up to four times: lines 60, 61, 66, and 67. Each call runs JSON.stringify(intent) over the whole intent, which embeds the observed tab and its optional layout. layout.buffersByLeafId can hold serialized terminal buffers up to the per-target observation bound. The renderer sends observations on every tab change, and RemoteWorkspaceTabIntentStore.observe calls retain once per changed tab slot. The repeated serialization runs on the main process thread.

Hoist the two sizes into locals.

⚡ Proposed change
     const previous = state.intents.get(slot)
+    const previousBytes = previous ? intentBytes(slot, previous) : 0
+    const nextBytes = intentBytes(slot, intent)
-    const retainedBytes =
-      state.retainedIntentBytes -
-      (previous ? intentBytes(slot, previous) : 0) +
-      intentBytes(slot, intent)
+    const retainedBytes = state.retainedIntentBytes - previousBytes + nextBytes
     if (
       state.intents.size + (previous ? 0 : 1) > MAX_REMOTE_WORKSPACE_TAB_INTENTS_PER_TARGET ||
       retainedBytes > MAX_REMOTE_WORKSPACE_TAB_INTENT_BYTES_PER_TARGET ||
-      this.retainedBytes -
-        (previous ? intentBytes(slot, previous) : 0) +
-        intentBytes(slot, intent) >
-        MAX_REMOTE_WORKSPACE_TAB_RETAINED_BYTES
+      this.retainedBytes - previousBytes + nextBytes > MAX_REMOTE_WORKSPACE_TAB_RETAINED_BYTES
     ) {

Also applies to: 58-72

src/main/ipc/remote-workspace.ts (1)

596-618: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Guard args before reading rendererGeneration.

Line 597 casts args and line 601 reads input.rendererGeneration. Line 609 and line 613 do the same. If a caller invokes the channel with no payload, args is undefined and the property read throws a TypeError. ipcMain.handle converts the throw into a rejected invoke promise, so the renderer call fails instead of becoming a no-op.

Line 585 already uses optional chaining for the same field on remoteWorkspace:observeTabState. Apply the same handling here.

🛡️ Proposed guard
   ipcMain.handle('remoteWorkspace:forgetTabState', (event, args) => {
-    const input = args as { rendererGeneration?: number; targetId?: string }
+    const input = (args ?? {}) as { rendererGeneration?: number; targetId?: string }
     const authority = remoteWorkspaceTabObservationOwners.resolve(
       event.sender,
       event.processId,
       input.rendererGeneration
     )
     if (isMainRenderer(event) && authority && input.targetId) {
       remoteWorkspaceTabIntents.forgetTarget(input.targetId, authority)
     }
   })
 
   ipcMain.handle('remoteWorkspace:forgetAllTabState', (event, args) => {
-    const input = args as { rendererGeneration?: number }
+    const input = (args ?? {}) as { rendererGeneration?: number }
src/main/ipc/remote-workspace-tab-intent-store.test.ts (1)

421-478: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Derive the over-capacity target id from the constant.

The loop at line 425 runs to MAX_REMOTE_WORKSPACE_TAB_INTENT_TARGETS, but lines 443-476 hardcode 'target-65' and 'worktree-65'. The same pattern appears at lines 502-510, 558-568, 614-627, and 701-734. The literals assume the constant equals 64.

If the constant changes, these tests keep passing but stop exercising the over-capacity path. They would instead operate on an already-retained target.

Bind the id to the constant.

♻️ Proposed change
+const OVER_CAPACITY_TARGET = `target-${MAX_REMOTE_WORKSPACE_TAB_INTENT_TARGETS + 1}`
+const OVER_CAPACITY_WORKTREE = `worktree-${MAX_REMOTE_WORKSPACE_TAB_INTENT_TARGETS + 1}`
src/main/ipc/remote-workspace-tab-observation-owner.ts (1)

75-78: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reset the owner registry and the intent store together in tests.

resetForTests sets nextGeneration = 0, so later start calls reissue generation numbers that were already handed out. The new WeakMap prevents stale lease resolution inside this registry. However, RemoteWorkspaceTabIntentStore and RemoteWorkspaceUntrackedIntentFences hold copied authority objects that keep the old generation numbers. A test that resets only this registry can produce an authority that compares equal to retained state.

Document or enforce that callers reset all three together.

src/main/ipc/remote-workspace-tab-intent-store.ts (1)

241-254: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Copy state.authority into the capture.

Line 252 stores a live reference to state.authority. Today observe at line 119 reassigns the field with a new object rather than mutating it, so the capture stays stable and acknowledgePatch compares the intended values. The invariant is implicit. A future in-place mutation of state.authority would silently make every outstanding capture compare equal.

Copy the value, as RemoteWorkspaceUntrackedIntentFences.capture already does at line 67 of remote-workspace-untracked-intent-fences.ts.

♻️ Proposed change
-      tracked: { authority: state.authority, lifecycle: state.lifecycle },
+      tracked: { authority: { ...state.authority }, lifecycle: state.lifecycle },
src/main/ipc/remote-workspace-tab-intent-retention.test.ts (1)

95-107: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The aggregate-budget assertion sits close to the boundary.

Line 95 sets layoutBytes to one tenth of MAX_REMOTE_WORKSPACE_TAB_RETAINED_BYTES. Each of the five targets retains the layout twice: once in the observed worktree baseline and once in the derived intent. That is about one fifth of the budget per target, so five targets land near the limit exactly.

Line 107 expects target-4 to overflow. A small change to per-intent serialization overhead can move the crossing point and flip this assertion. Widen the margin, for example by using MAX_REMOTE_WORKSPACE_TAB_RETAINED_BYTES / 4, so the overflow point is unambiguous.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: be03c2f8-d450-4e56-b11a-7749803538ec

📥 Commits

Reviewing files that changed from the base of the PR and between a70291a and b425e87eb9710d14a090f6cf8ece8b1cde8b8c5a.

📒 Files selected for processing (44)
  • config/reliability-gates.jsonc
  • src/main/ipc/pty-process-incarnation-registry.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/remote-workspace-patch-queue.test.ts
  • src/main/ipc/remote-workspace-tab-intent-reconciliation.ts
  • src/main/ipc/remote-workspace-tab-intent-retention.test.ts
  • src/main/ipc/remote-workspace-tab-intent-retention.ts
  • src/main/ipc/remote-workspace-tab-intent-store.test.ts
  • src/main/ipc/remote-workspace-tab-intent-store.ts
  • src/main/ipc/remote-workspace-tab-intent-types.ts
  • src/main/ipc/remote-workspace-tab-observation-bounds.ts
  • src/main/ipc/remote-workspace-tab-observation-owner.test.ts
  • src/main/ipc/remote-workspace-tab-observation-owner.ts
  • src/main/ipc/remote-workspace-untracked-intent-fences.ts
  • src/main/ipc/remote-workspace.test.ts
  • src/main/ipc/remote-workspace.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/App.tsx
  • src/renderer/src/hooks/direct-ssh-tab-intent-observer.test.ts
  • src/renderer/src/hooks/direct-ssh-tab-intent-observer.ts
  • src/renderer/src/hooks/direct-ssh-tab-observation-scope.ts
  • src/renderer/src/hooks/direct-ssh-tab-process-inputs.ts
  • src/renderer/src/hooks/remote-workspace-bidirectional-race-oracle.test.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.test.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-duplicate-tab-repair.test.ts
  • src/renderer/src/hooks/remote-workspace-tab-presence-reconciliation.ts
  • src/renderer/src/hooks/remote-workspace-target-sync.test.ts
  • src/renderer/src/hooks/remote-workspace-target-sync.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/lib/direct-ssh-target-scope-types.ts
  • src/renderer/src/lib/direct-ssh-target-scope.test.ts
  • src/renderer/src/lib/direct-ssh-target-scope.ts
  • src/renderer/src/lib/direct-ssh-worktree-owner-evidence.ts
  • src/renderer/src/lib/session-write-subscriber.test.ts
  • src/renderer/src/lib/session-write-subscriber.ts
  • src/shared/remote-workspace-types.ts
  • tests/e2e/global-setup.ts
  • tests/e2e/global-teardown.ts
  • tests/e2e/helpers/remote-workspace-snapshot-request-barrier.ts
  • tests/e2e/remote-workspace-tab-observation-scale.spec.ts
  • tests/e2e/ssh-remote-workspace-snapshot-race.spec.ts
  • tests/playwright.config.ts

customTitle: null,
color: null,
sortOrder: 0,
createdAt: Number(id.split('-').at(-1))

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

tab('tab-recovered', …) produces createdAt: NaN.

Line 26 derives createdAt from the trailing id segment. For tab-0 through tab-7 this yields 0–7. For tab-recovered at line 125 it yields Number('recovered'), which is NaN.

The test still passes. The observation at line 124-127 is authoritative: true, so observe replaces the baseline and derives no intents, and NaN never reaches remoteWorkspaceTabSlotKey. The fixture is still wrong, and it will produce a slot key of null for the createdAt position if this test is extended to a non-authoritative observation.

Give the helper an explicit createdAt parameter.

🐛 Proposed fix
-function tab(id: string, layoutBytes: number): RemoteWorkspaceObservedTab {
+function tab(id: string, layoutBytes: number, createdAt = 0): RemoteWorkspaceObservedTab {
   return {
     processIdentity: `process-${id}`,
     tab: {
       id,
       worktreePath: '/remote/work',
       ptyId: `pty-${id}`,
       title: id,
       customTitle: null,
       color: null,
       sortOrder: 0,
-      createdAt: Number(id.split('-').at(-1))
+      createdAt
     },

Then pass the index at the call sites, for example tab(\tab-${index}`, layoutBytes, index)at line 64 and line 103, andtab('tab-recovered', 1_024, 99)` at line 125.

Also applies to: 124-127

Comment on lines +34 to +36
if (!this.overflowAuthority || this.canReplace(this.overflowAuthority, authority)) {
this.overflowAuthority = { ...authority }
}

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

overflowAuthority is sticky and blocks every untracked target until renderer teardown.

record sets overflowAuthority when the target map is full. blocks(targetId) then returns true for every targetId that has no tracked fence, because the check is this.overflowAuthority !== null and is not scoped to a target.

No method clears overflowAuthority for the same authority except forgetAll and reset. acknowledge, clear, and forget leave it set. So one overflow event permanently blocks RemoteWorkspaceTabIntentStore.reconcile (line 216-218 of remote-workspace-tab-intent-store.ts) for all untracked targets for the remaining lifetime of that renderer generation, even after the target map drops below MAX_REMOTE_WORKSPACE_UNTRACKED_INTENT_TARGETS.

Add a recovery path. One option: track the overflowed target ids in a bounded set and clear overflowAuthority when that set is acknowledged or when capacity frees up.

🩹 Sketch of a bounded recovery path
   private overflowAuthority: RemoteWorkspaceTabObservationAuthority | null = null
+  private overflowCount = 0
@@
     if (!this.overflowAuthority || this.canReplace(this.overflowAuthority, authority)) {
       this.overflowAuthority = { ...authority }
+      this.overflowCount += 1
     }
   }
@@
   clear(targetId: string): void {
     this.targets.delete(targetId)
+    this.releaseOverflowIfDrained()
   }
@@
   acknowledge(targetId: string, capture: RemoteWorkspaceUntrackedIntentFence | null): void {
@@
       this.targets.delete(targetId)
+      this.releaseOverflowIfDrained()
     }
   }
+
+  private releaseOverflowIfDrained(): void {
+    if (this.targets.size === 0) {
+      this.overflowAuthority = null
+      this.overflowCount = 0
+    }
+  }

Also applies to: 61-63

Comment on lines +620 to +629
ipcMain.handle('remoteWorkspace:flushTabState', () => undefined)

ipcMain.handle(
'remoteWorkspace:reconcileSnapshot',
(
_event,
args: { targetId: string; snapshot: RemoteWorkspaceSnapshot }
): RemoteWorkspaceSnapshot | null =>
remoteWorkspaceTabIntents.reconcile(args.targetId, args.snapshot)
)

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

remoteWorkspace:reconcileSnapshot accepts any sender and any payload. The handler is the only tab-state channel added in this change that omits the isMainRenderer(event) gate used at lines 573, 587, 603, and 615, and it reads args.targetId and args.snapshot without validation. Any webContents that reaches the channel can probe the main renderer's retained tab-intent state for an arbitrary targetId, and an omitted payload throws a TypeError. The test call site depends on that missing gate.

  • src/main/ipc/remote-workspace.ts#L620-L629: add the isMainRenderer(event) check and validate that args.targetId is a string and args.snapshot is present; return null otherwise.
  • src/main/ipc/remote-workspace-patch-queue.test.ts#L355-L370: replace the null event argument at lines 357 and 366 with mainEvent so the handler passes the sender check.
📍 Affects 2 files
  • src/main/ipc/remote-workspace.ts#L620-L629 (this comment)
  • src/main/ipc/remote-workspace-patch-queue.test.ts#L355-L370

Comment thread src/renderer/src/hooks/useIpcEvents.ts Resolved
Comment on lines +76 to +87
await app.evaluate(async () => {
const state = (
globalThis as typeof globalThis & {
__remoteWorkspaceSnapshotRequestBarrier?: BarrierState
}
).__remoteWorkspaceSnapshotRequestBarrier
if (state && !state.released) {
state.released = true
state.release()
}
await state?.handlerReturned
})

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard the handlerReturned await on captured.

handlerReturned resolves only inside the replacement handler, after a matching request reaches the barrier. If no request for state.targetId was ever captured, release() resolves nothing and line 86 waits forever. The test then fails on an opaque Playwright timeout instead of a clear assertion.

restoreRemoteWorkspaceSnapshotRequestHandler does not have this problem because it never awaits handlerReturned.

🛡️ Proposed fix to avoid an unbounded wait
     if (state && !state.released) {
       state.released = true
       state.release()
     }
-    await state?.handlerReturned
+    if (state?.captured) {
+      await state.handlerReturned
+    }
📝 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
await app.evaluate(async () => {
const state = (
globalThis as typeof globalThis & {
__remoteWorkspaceSnapshotRequestBarrier?: BarrierState
}
).__remoteWorkspaceSnapshotRequestBarrier
if (state && !state.released) {
state.released = true
state.release()
}
await state?.handlerReturned
})
await app.evaluate(async () => {
const state = (
globalThis as typeof globalThis & {
__remoteWorkspaceSnapshotRequestBarrier?: BarrierState
}
).__remoteWorkspaceSnapshotRequestBarrier
if (state && !state.released) {
state.released = true
state.release()
}
if (state?.captured) {
await state.handlerReturned
}
})

Comment on lines +76 to +82
await api.forgetTabState({ rendererGeneration: generation, targetId: 'target-999' })
await observe('target-1000', [existing])
await observe('target-1000', [existing, created])
const unrelatedMutation = await api.reconcileSnapshot({
targetId: 'target-1000',
snapshot: snapshot(3, [existing])
})

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect forgetTabState and admission/eviction semantics to confirm the cleanup step is inert here.
set -euo pipefail

rg -n -C8 'forgetTabState' -g '!**/node_modules/**'
ast-grep run --pattern 'forget($$$) { $$$ }' --lang typescript src/main/ipc/remote-workspace-tab-intent-store.ts
rg -n -C10 'evictBaseline' src/main/ipc/ -g '*.ts'

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

set -euo pipefail

printf '%s\n' '--- candidate files ---'
git ls-files | rg 'remote-workspace-tab-observation-scale\.spec\.ts|remote-workspace-tab-intent-store|reliability-gates\.jsonc'

printf '%s\n' '--- test context ---'
test_file="$(git ls-files | rg '(^|/)remote-workspace-tab-observation-scale\.spec\.ts$' | head -n1)"
if [ -n "${test_file}" ]; then
  sed -n '45,100p' "$test_file"
fi

printf '%s\n' '--- forgetTabState references ---'
rg -n -C10 'forgetTabState|forgetTab|evictBaseline|admission|readmission' tests src config -g '*.{ts,tsx,js,jsx,json,jsonc}' || true

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

set -euo pipefail

test_file="$(git ls-files '*remote-workspace-tab-observation-scale.spec.ts')"
printf '%s\n' "$test_file"
sed -n '1,120p' "$test_file"

printf '%s\n' '--- exact implementation and test references ---'
rg -n -C6 'forgetTabState' "$test_file" src tests config -g '*.{ts,tsx,js,jsx,json,jsonc}' | head -n 240

printf '%s\n' '--- relevant filenames ---'
git ls-files | rg 'remote-workspace-tab|reliability-gates'

Repository: stablyai/orca

Length of output: 19880


🏁 Script executed:

set -euo pipefail

printf '%s\n' '--- IPC handler ---'
sed -n '570,625p' src/main/ipc/remote-workspace.ts

printf '%s\n' '--- store outline ---'
ast-grep outline src/main/ipc/remote-workspace-tab-intent-store.ts

printf '%s\n' '--- store implementation ---'
sed -n '1,280p' src/main/ipc/remote-workspace-tab-intent-store.ts

printf '%s\n' '--- retention implementation ---'
sed -n '1,320p' src/main/ipc/remote-workspace-tab-intent-retention.ts

printf '%s\n' '--- scale-related tests and gate entry ---'
rg -n -C8 'remote-workspace-tab-observation-scale|target-65|target-999|target-1000|scoped|cleanup|readmission' config/reliability-gates.jsonc tests/e2e src/main/ipc/remote-workspace-tab-intent-*.test.ts

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

set -euo pipefail

printf '%s\n' '--- IPC forget handler ---'
sed -n '596,620p' src/main/ipc/remote-workspace.ts

printf '%s\n' '--- intent store ---'
wc -l src/main/ipc/remote-workspace-tab-intent-store.ts
sed -n '1,260p' src/main/ipc/remote-workspace-tab-intent-store.ts

printf '%s\n' '--- retention ---'
wc -l src/main/ipc/remote-workspace-tab-intent-retention.ts
sed -n '1,260p' src/main/ipc/remote-workspace-tab-intent-retention.ts

printf '%s\n' '--- gate references only ---'
rg -n -C5 'remote-workspace-tab-observation-scale|scoped-cleanup|readmission|target-65|target-999|target-1000' config/reliability-gates.jsonc

Repository: stablyai/orca

Length of output: 28223


🏁 Script executed:

set -euo pipefail

printf '%s\n' '--- unit coverage for cleanup and readmission ---'
rg -n -C12 'readmission|post-forget|forgetTarget|explicit cleanup|connection-only observations' \
  src/main/ipc/remote-workspace-tab-intent-store.test.ts \
  src/main/ipc/remote-workspace-tab-intent-retention.test.ts

printf '%s\n' '--- standalone admission check for the E2E sequence ---'
python3 - <<'PY'
MAX_TARGETS = 64
targets = set()

def authoritative_observe(target):
    if target not in targets:
        if len(targets) >= MAX_TARGETS:
            # Every target created by this sequence has an empty baseline,
            # except target-65, which has a pending intent.
            candidates = sorted(t for t in targets if t != "target-65")
            if not candidates:
                return False
            targets.remove(candidates[0])
        targets.add(target)
    return True

for i in range(1, 65):
    assert authoritative_observe(f"target-{i}")
assert authoritative_observe("target-65")
pending = {"target-65"}
for i in range(66, 1001):
    assert authoritative_observe(f"target-{i}")
    assert len(targets) == MAX_TARGETS

before = "target-1000" in targets
forget999_removed = "target-999" in targets
targets.remove("target-999")
observe1000_is_existing = "target-1000" in targets
print({
    "target_1000_tracked_before_cleanup": before,
    "target_999_was_tracked": forget999_removed,
    "target_1000_observation_requests_admission": not observe1000_is_existing,
    "tracked_target_count_after_forget": len(targets),
})
PY

Repository: stablyai/orca

Length of output: 18153


Scope cleanup to target-1000 or remove it. target-1000 is already tracked before the cleanup call, so forgetting target-999 does not affect the following observations or reconciliation. Use target-1000 to cover cleanup followed by readmission.

Comment on lines +114 to +115
target = startDockerSshRelayTarget(testInfo)
registerPostElectronShutdownCleanup(async () => cleanupDockerSshRelayTarget(target))

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Capture the target value for the post-shutdown cleanup.

The cleanup closure reads the target variable, not its value. Line 221 sets target = null before the post-Electron-shutdown cleanup runs. The deferred cleanup therefore always receives null, and the safety net cannot remove the Docker container if the in-finally cleanup at line 220 does not complete.

Also, line 220 is the only step in finally without error suppression. If cleanupDockerSshRelayTarget throws there, it masks the original test failure and skips line 221.

🧹 Proposed fix
-    target = startDockerSshRelayTarget(testInfo)
-    registerPostElectronShutdownCleanup(async () => cleanupDockerSshRelayTarget(target))
+    const startedTarget = startDockerSshRelayTarget(testInfo)
+    target = startedTarget
+    registerPostElectronShutdownCleanup(async () => cleanupDockerSshRelayTarget(startedTarget))

Apply this diff in the finally block:

-    cleanupDockerSshRelayTarget(target)
-    target = null
+    try {
+      cleanupDockerSshRelayTarget(target)
+    } catch {
+      // Best-effort cleanup; the post-shutdown hook retries.
+    }
+    target = 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
target = startDockerSshRelayTarget(testInfo)
registerPostElectronShutdownCleanup(async () => cleanupDockerSshRelayTarget(target))
const startedTarget = startDockerSshRelayTarget(testInfo)
target = startedTarget
registerPostElectronShutdownCleanup(async () => cleanupDockerSshRelayTarget(startedTarget))

robertnisipeanu and others added 22 commits August 15, 2026 01:25
…ly created terminal tabs

A terminal tab created around a direct-SSH snapshot apply could be permanently
lost: the session-write subscriber dropped its pending write during the apply's
suppression window, so the remote store never learned the tab existed, and the
applied snapshot (fetched before the tab was created) replaced the worktree's
tab list without it — leaving the tab's pty running unreachable on the host,
with any sleeping-agent record for it stranded against a tab id that no longer
exists.

Three changes close this:
- The session-write subscriber holds suppressed writes and retries until the
  suppression lifts instead of clearing the pending field set, so a tab created
  during an apply still reaches the local session and the remote push. A 60s
  hold ceiling bounds the retry: past it the write proceeds, so back-to-back
  applies (or a misbehaving remote streaming snapshot revisions) cannot starve
  local persistence indefinitely.
- A snapshot whose in-scope tab lists are missing a tab that is live locally —
  mid-reattach per the recovery ledger, or with an attached pty per
  ptyIdsByTabId — is treated as predating that tab: the tab is grafted into the
  snapshot's tab list for its worktree before the merge, and its id joins the
  merge's preserve set so its layout and session ids survive. Remote-only tabs
  from other clients still apply unchanged, and tabs without a live pty are
  still removed when the remote store says so.
- The stale-tab detection and the graft are exported as pure helpers with unit
  tests, plus an integration test covering a live local tab omitted by an
  incoming snapshot alongside a remote-only tab.

Co-Authored-By: Claude Fable 5 <[email protected]>
This reverts commit 5e23ca40978cd91c475f2c261ba5ee8ccdf597d0.
This reverts commit 52900bdadaa379568735e00ec7ff910b17a3215c.
@robertnisipeanu
robertnisipeanu force-pushed the fix/remote-session-write-loss branch from 0a88168 to 4f4a085 Compare August 14, 2026 23:16
@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

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

70-121: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Extend the direct-SSH retention test.

remote-workspace-target-sync.test.ts asserts the tab and terminalLayoutsByTabId, but not remoteSessionIdsByTabId. Add an assertion that fresh-tab retains ssh:target-a@@pty-fresh after snapshot hydration.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c43bf280-aef6-40b0-9569-7a74b8f7780f

📥 Commits

Reviewing files that changed from the base of the PR and between 19bc1cc and 4f4a085.

📒 Files selected for processing (43)
  • config/reliability-gates.jsonc
  • src/main/ipc/pty-process-incarnation-registry.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/remote-workspace-patch-queue.test.ts
  • src/main/ipc/remote-workspace-tab-intent-reconciliation.ts
  • src/main/ipc/remote-workspace-tab-intent-retention.test.ts
  • src/main/ipc/remote-workspace-tab-intent-retention.ts
  • src/main/ipc/remote-workspace-tab-intent-store.test.ts
  • src/main/ipc/remote-workspace-tab-intent-store.ts
  • src/main/ipc/remote-workspace-tab-intent-types.ts
  • src/main/ipc/remote-workspace-tab-observation-bounds.ts
  • src/main/ipc/remote-workspace-tab-observation-owner.test.ts
  • src/main/ipc/remote-workspace-tab-observation-owner.ts
  • src/main/ipc/remote-workspace-untracked-intent-fences.ts
  • src/main/ipc/remote-workspace.test.ts
  • src/main/ipc/remote-workspace.ts
  • src/preload/api/workspace-session-api.ts
  • src/preload/index.ts
  • src/renderer/src/App.tsx
  • src/renderer/src/hooks/direct-ssh-tab-intent-observer.test.ts
  • src/renderer/src/hooks/direct-ssh-tab-intent-observer.ts
  • src/renderer/src/hooks/direct-ssh-tab-observation-scope.ts
  • src/renderer/src/hooks/direct-ssh-tab-process-inputs.ts
  • src/renderer/src/hooks/ipc-events-test-harness.ts
  • src/renderer/src/hooks/remote-workspace-bidirectional-race-oracle.test.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.test.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-duplicate-tab-repair.test.ts
  • src/renderer/src/hooks/remote-workspace-tab-presence-reconciliation.ts
  • src/renderer/src/hooks/remote-workspace-target-sync.test.ts
  • src/renderer/src/hooks/remote-workspace-target-sync.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/lib/direct-ssh-target-scope-types.ts
  • src/renderer/src/lib/direct-ssh-target-scope.test.ts
  • src/renderer/src/lib/direct-ssh-target-scope.ts
  • src/renderer/src/lib/direct-ssh-worktree-owner-evidence.ts
  • src/renderer/src/lib/session-write-subscriber.test.ts
  • src/renderer/src/lib/session-write-subscriber.ts
  • src/shared/remote-workspace-types.ts
  • tests/e2e/global-teardown.ts
  • tests/e2e/helpers/remote-workspace-snapshot-request-barrier.ts
  • tests/e2e/remote-workspace-tab-observation-scale.spec.ts
  • tests/e2e/ssh-remote-workspace-snapshot-race.spec.ts
🚧 Files skipped from review as they are similar to previous changes (38)
  • src/main/ipc/remote-workspace-tab-intent-retention.test.ts
  • src/main/ipc/remote-workspace-tab-observation-owner.test.ts
  • src/preload/index.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-duplicate-tab-repair.test.ts
  • src/main/ipc/remote-workspace-tab-intent-store.test.ts
  • tests/e2e/helpers/remote-workspace-snapshot-request-barrier.ts
  • src/renderer/src/lib/direct-ssh-target-scope.test.ts
  • tests/e2e/global-teardown.ts
  • src/renderer/src/hooks/direct-ssh-tab-intent-observer.test.ts
  • src/renderer/src/hooks/remote-workspace-tab-presence-reconciliation.ts
  • tests/e2e/remote-workspace-tab-observation-scale.spec.ts
  • src/renderer/src/lib/session-write-subscriber.test.ts
  • config/reliability-gates.jsonc
  • src/renderer/src/lib/direct-ssh-target-scope-types.ts
  • src/main/ipc/pty-process-incarnation-registry.ts
  • src/main/ipc/remote-workspace.test.ts
  • src/main/ipc/remote-workspace-tab-intent-types.ts
  • src/main/ipc/remote-workspace-patch-queue.test.ts
  • src/renderer/src/hooks/remote-workspace-target-sync.test.ts
  • src/main/ipc/remote-workspace-untracked-intent-fences.ts
  • src/renderer/src/lib/direct-ssh-target-scope.ts
  • src/renderer/src/lib/direct-ssh-worktree-owner-evidence.ts
  • src/renderer/src/hooks/remote-workspace-bidirectional-race-oracle.test.ts
  • src/main/ipc/remote-workspace-tab-intent-retention.ts
  • src/renderer/src/App.tsx
  • src/main/ipc/remote-workspace-tab-observation-owner.ts
  • src/renderer/src/hooks/remote-workspace-snapshot-apply.ts
  • src/renderer/src/hooks/direct-ssh-tab-process-inputs.ts
  • src/main/ipc/remote-workspace-tab-intent-reconciliation.ts
  • src/renderer/src/hooks/ipc-events-test-harness.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/main/ipc/remote-workspace-tab-intent-store.ts
  • src/main/ipc/remote-workspace.ts
  • src/main/ipc/remote-workspace-tab-observation-bounds.ts
  • src/main/ipc/pty.ts
  • src/renderer/src/hooks/direct-ssh-tab-intent-observer.ts
  • src/renderer/src/hooks/direct-ssh-tab-observation-scope.ts
  • src/renderer/src/hooks/remote-workspace-target-sync.ts

Comment on lines +82 to +86
const status = Object.values(state.remoteWorkspaceSyncStatusByTargetId).find(
(entry) => entry.phase === 'synced' && entry.direction === 'pull'
)
if (freshTabId && status) {
stop()

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 | 🟠 Major | ⚡ Quick win

Wait for the delayed target pull to complete.

find() accepts a retained synced pull status from any target. It can set done when the new tab appears, before line 160 releases the snapshot barrier. Line 161 can then pass without observing completion of the delayed pull.

Track remote.targetId in installMutationChurn. Require an in-flight pull for that target and a later synced transition after the barrier release.

The tab-intent capture rides remote-workspace-relay-sync.ts, the shared store
instance lives in remote-workspace-tab-intent-store.ts, the observation and
reconcile handlers stay in remote-workspace.ts, and the session-write
subscriber wiring moves to app-shell/use-app-session-persistence.ts (stablyai#14607
decomposed App.tsx). A live pre-request tab that a newer snapshot omits now
survives the merge (stablyai#14844); the ledger continues to discriminate deliberate
closes from never-uploaded creations at the apply boundary.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AqNqAZQTwmAkwGcHj5TYXk
@Jinwoo-H

Copy link
Copy Markdown
Contributor

Thanks @robertnisipeanu for the remote snapshot-erasure diagnosis and regression coverage. Completed issue #12748 and merged fix #14844 now own this behavior on current main, including the zero-tab union/graft case. We will retain your contribution as historical credit and request no rebase, retest, or other follow-up. Closing this superseded branch.

@Jinwoo-H Jinwoo-H closed this Aug 31, 2026
@Jinwoo-H

Copy link
Copy Markdown
Contributor

Additional supersession context: newer merged fixes #16956 and #16546 also cover unplaceable host tabs and host-authoritative empty inventories. The owner path remains #12748/#14844 plus these current-main fixes.

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.

5 participants