Skip to content

fix(runtime): stabilize remote session-tab sync across server and client - #11939

Closed
Him188 wants to merge 2 commits into
stablyai:mainfrom
Him188:fix/remote-session-tabs-sync-stability
Closed

Him188 wants to merge 2 commits into
stablyai:mainfrom
Him188:fix/remote-session-tabs-sync-stability

Conversation

@Him188

@Him188 Him188 commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When a client is attached to a remote orca server (orca serve over the pairing relay), session-tab management is unreliable in ways local desktop use never shows. All of the symptoms below are timing-dependent, so they reproduce intermittently rather than on demand, and they get markedly worse the busier the server is (more session activity means more snapshot publications in flight, which widens every race window) and the more devices are paired. Reproduced on a macOS headless serve host with one and with two paired desktop clients.

  • Creating a session can bump an existing tab off the strip. Launching a new session sometimes removes the last tab in the worktree. The removed tab is not closed: its agent/PTY keeps running server-side and keeps consuming resources — it has just vanished from the client's mirror, invisibly, with no UI path to bring it back until some unrelated mutation forces a fresh snapshot of that worktree.
  • Switching worktrees flickers or wipes the session list. Activating a worktree sometimes shows its sessions for a moment and then removes all of them; other times only a subset (in practice the serve/SSH-owned terminals) ever appears, and the remaining sessions never materialize even though they are alive on the host.
  • Closed sessions come back. Closing a tab looks successful, but after restarting the local client (server untouched) — or sometimes merely re-activating the worktree — the closed tab is back, its session still running on the host. In the worst variants the close never happened server-side at all, and the client showed no indication of the failure.
  • Multiple devices amplify everything. With two clients attached, closing a tab on one device can freeze the other device's view of that worktree — it silently drops every subsequent snapshot until an unrelated publication lands — and in one deterministic case (a PTY left unbound by a failed post-restart surface restore) a close performed on one device is later resurrected for every device.

The common thread: the client mirrors host session-tab snapshots, and each mechanism meant to keep that mirror consistent — publication-epoch freshness gating, close intents, terminal orphan recovery — assumes conditions the remote/headless path does not actually provide.

Root causes (each traced end-to-end in code)

  1. The client freshness gate is vacuous against headless servers. The gate rejects only same-epoch, non-increasing snapshotVersion frames — a different publicationEpoch always applies (web-session-tabs-sync.ts), by design assuming one epoch per host boot (as desktop mode does). The headless server minted a fresh headless:${Date.now()} epoch on nearly every mutation (10 sites) plus headless-hydrated: and :headless-merge: variants, so every in-flight frame was "a new generation" and whichever applied last won. Subscription frames serialize through the orphan-recovery chain, but session.tabs.list results apply outside it, so a delayed push frame regularly landed after a newer list result and authoritatively culled fresh tabs.
  2. Not-yet-hydrated worktrees are served as authoritative-empty. A missing mobileSessionTabsByWorktree entry fabricates {publicationEpoch:'none', tabs:[]}, which the worktree-activation list path applied with no guard — full wipe until the next real publication. Separately, the runtime-owned (serve/SSH-only) hydrate seeds a subset entry that permanently blocks the full rebuild via an existing.tabs.length>0 skip — subset lock-in.
  3. User closes are fire-and-forget with volatile guards. Close intents are in-memory with a 10s TTL; a failed close RPC only console.warns, and restart re-lists the host-authoritative snapshot, deterministically re-materializing the tab. One environment's reconnect also wiped every environment's freshness floors and intents.
  4. No cross-device close tombstone. After device A closes a tab, device B's orphan recovery sees a still-dying PTY absent from the snapshot and drops every frame for that worktree; a PTY already unbound at close time (failed post-restart restore) escapes the kill entirely and gets re-adopted, resurrecting the closed session fleet-wide.
  5. Per-client navigation projection corrupts the epoch echo. Projected snapshots carry ${epoch}:client-navigation, but session.tabs.closeLifecycle compared the client's echo against the raw epoch with !==, so any projected echo was refused 'stale-publication' and triggered a cluster republish (latent at HEAD; live with older clients).
  6. QuickLaunch's stale-tab prune closes live provisional tabs. It force-closed every local-UUID launchAgent tab pre- and post-create with no liveness/handoff check — hibernation-resumed provisional tabs (appended last in the strip) matched, and with a bound handle the close killed the host session: the one path where creating a session literally destroys a neighbor.
  7. Some server close paths ack without closing. A headed hub with its window closed no-ops markdown/file closes but returns {closed:true}; unbound daemon PTYs escaped the kill scope ("hidden, not closed").
  8. After a host restart, restored tabs never reattach the daemon output stream, and provider snapshots leak a foreign sequence domain. The boot inventory restores session-tab records as ready, but the daemon only streams a session's output to the process that last ran createOrAttach — and nothing in the new serve process ever does (headless serve has no renderer, so the renderer spawn/reattach paths that normally do this are unreachable). Subscribers get correct snapshots and zero live bytes: typing executes, but output only appears when a tab switch refetches a snapshot. Compounding it, provider buffer snapshots translated their seq with a defaulted-to-0 offset, publishing the daemon's cumulative counter while live frames carry the boot-local counter reset at startup — so even once a spawn path did attach, the client dedupe baseline armed from the snapshot's foreign seq silently dropped every live frame as already-covered, re-poisoning itself on each snapshot refetch.

Fixes

Server — new MobileSessionTabsPublicationClock (mobile-session-tabs-publication.ts): one stable epoch per worktree per boot, strictly monotonic snapshotVersion across all publish sites (mutations, hydration, merge, recovery); the :headless-merge: epoch flip becomes a boot-stable merge signature riding version bumps. Missing-entry results now carry hydrationPending: true until a full hydrate (or renderer batch, which is hydration on a headed hub) covers the worktree; the full hydrate rebuilds over runtime-owned-seeded subset entries, preserving live runtime-owned bindings. New SessionTabCloseTombstoneStore (30s TTL) records every successful close; recentlyClosedTabIds rides every published snapshot, terminal.list hides tombstoned PTYs, adoption refuses them, and the unbound-PTY kill scope widens to persisted bindings corroborated by pane incarnations (positive incarnation mismatch is never killed). closeLifecycle normalizes a trailing :client-navigation before the stale-publication comparison. The notifier-less close branch throws renderer_unavailable instead of faking success.

Client — session.tabs.list results now apply through the same per-worktree serialized chain as subscription frames (gaining its orphan-recovery protection); the post-create refresh uses the after-current-in-flight variant; the agent-handoff confirm only arms when the confirm list actually contains the host tab. Failed user closes recover visibly (accept-replay + refresh + toast) instead of silently diverging; sync tracking, intents, and wake-respawn guards are scoped per environment; hydrationPending frames (and 'none'-epoch empties from older servers, including their :client-navigation projections) never clear a non-empty mirror; tombstone-covered candidates let post-close frames apply instead of freezing the worktree. QuickLaunch's prune skips tabs with a recorded handoff or pending create, only prunes tabs that existed before the operation, and never fires host terminal.close for pruned local tabs.

Server, host restart — session.tabs.activate now re-materializes a ready tab whose PTY has no provider attachment this boot (ptyController.hasPty(...) === false), which reattaches the daemon output stream and runs the provider sequence sync as one operation through the existing spawn pipeline. Provider buffer snapshots omit seq until a sequence sync has anchored the provider offset for this boot — clients already treat a seq-less snapshot as baseline-clearing, so live frames flow instead of being dropped against a foreign-domain watermark — and the provider visible-state cache watermarks with the pre-capture boot-local counter so a raced byte invalidates it instead of the foreign seq pinning it fresh forever.

Compatibility

Both new protocol fields (hydrationPending, recentlyClosedTabIds) are optional: old clients ignore them (no worse than today), new clients degrade to current behavior against old servers. The stable-epoch change makes old clients' existing gate work correctly rather than requiring anything of them.

Tests

Each mechanism has regression coverage: publication-clock unit tests (stable epoch, monotonic versions across interleaved sources, reboot behavior), runtime-level epoch-stability sweeps across mutation entry points, hydrationPending/subset-rebuild/authoritative-empty cases, tombstone store + publish + list-hiding + adoption-refusal + unbound-PTY kill, projected-epoch closeLifecycle acceptance, client apply-ordering/serialization, close-failure recovery, per-environment isolation, QuickLaunch prune scenarios, and the host-restart cases (re-materialize on a detached ready tab vs spawn-free activation while attached; seq omitted while unanchored vs translated once synced). All touched suites plus pnpm run typecheck are green after each commit.

Real-world verification

Deployed on the original repro environment: orca serve running on a Mac mini (M4), with a MacBook attached to it remotely over the pairing relay. With this branch on both ends, the session-loss symptoms no longer reproduce — creating sessions does not bump existing tabs, worktree switching shows the full session list without flicker or wipes, and closed sessions stay closed across local client restarts. Continued use surfaced the host-restart defect (root cause 8): with sessions now surviving a restart of both ends, the restored terminals executed input but rendered no live output until a tab switch. That fix is included in this branch and was verified in the same environment.

🤖 Generated with Claude Code

- Mint one publication epoch per boot with strictly monotonic snapshot
  versions (MobileSessionTabsPublicationClock); stop per-mutation epoch
  flips that made the client freshness gate vacuous
- Mark not-yet-hydrated worktree lists hydrationPending so clients keep
  their mirror; let full hydration rebuild runtime-owned-seeded subsets
- Add close tombstones (recentlyClosedTabIds) so other devices treat
  dying PTYs as closed instead of dropping frames or re-adopting them;
  widen the unbound-PTY kill scope with incarnation corroboration
- Normalize client-echoed ':client-navigation' epochs in closeLifecycle
- Recover visibly from failed user closes (restore + toast) instead of
  silently diverging; split sync tracking per environment
- Make the QuickLaunch stale-tab prune skip provisional handoff tabs and
  never fire host terminal.close for pruned local tabs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@Him188
Him188 marked this pull request as ready for review August 1, 2026 12:25
@Him188
Him188 requested a review from brennanb2025 as a code owner August 1, 2026 12:25
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The runtime adds boot-stable publication epochs, strictly increasing snapshot versions, hydration metadata, and close tombstones for tabs and PTYs. Close handling validates renderer routes and PTY ownership. The renderer adds orphan recovery, safer handoff confirmation, provisional-tab preservation, close-failure recovery, environment-scoped respawn guards, TTL-based close intents, and per-environment session-tab synchronization. Tests cover these runtime and renderer behaviors.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% 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
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.
Title check ✅ Passed The title clearly and concisely describes the primary change: stabilizing runtime session-tab synchronization across server and client.
Description check ✅ Passed The description clearly covers the problem, root causes, fixes, compatibility, tests, and real-world verification, so it is substantially complete.

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

🧹 Nitpick comments (6)
src/renderer/src/runtime/web-runtime-wake-terminal-respawn.ts (1)

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

Rename the set to match the new key shape.

The set now stores ${environmentId}\0${worktreeId} keys, but the name still says ByWorktree. A reader can assume worktree-only keys and add a lookup with a bare worktree id. Deleting entries during for...of over a Set is safe, so clearWebRuntimeWakeTerminalRespawnForEnvironment needs no other change.

♻️ Proposed rename
-const wakeTerminalRespawnInFlightByWorktree = new Set<string>()
+const wakeTerminalRespawnInFlightByEnvironmentWorktree = new Set<string>()

Update the five references in this file accordingly.

Also applies to: 39-46

src/renderer/src/runtime/web-session-tabs-sync.ts (1)

2739-2915: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Skip the warning after disposal in onError.

Every other callback in this synchronizer checks disposed before it logs. onError does not. A late transport error after unsubscribe then logs for an environment that no longer syncs.

♻️ Proposed change
         onError: (error) => {
+          if (disposed) {
+            return
+          }
           console.warn('[web-session-tabs-sync] global subscription error:', error.message)
         }
src/renderer/src/runtime/web-session-tabs-sync.test.ts (1)

3990-4017: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add an environment-scoping case for the terminal mirror veto.

This test proves a mirrored terminal tab vetoes a fabricated empty frame for ENV. It does not prove the veto is scoped to ENV. The browser case at Lines 4049-4055 pins the environment through remoteBrowserPageHandlesByPageId; the terminal case has no equivalent assertion. Add a case that passes a different environment id and asserts the frame still applies. That case documents the intended scope and fails if the terminal branch stays environment-blind. See the related comment on webSessionMirrorHasHostTabs in src/renderer/src/runtime/web-session-tabs-sync.ts.

src/renderer/src/runtime/web-runtime-session.ts (1)

996-1015: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Match the RPC error code instead of the message text.

RuntimeRpcCallError already exposes error.code, and mapRuntimeError preserves terminal_tab_pinned and terminal_tab_not_found as their own structured codes. Use that code in showWebRuntimeSessionUserCloseFailureToast; keep message substring matching only as a fallback. Also update the existing close-toast tests to cover code: 'terminal_tab_pinned' and code: 'terminal_tab_not_found'.

src/main/runtime/mobile-session-tabs-publication.ts (1)

10-13: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense the explanatory comments.

Keep one concise sentence for each non-obvious ordering invariant. Remove implementation walkthrough details.

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

Also applies to: 20-27, 29-31, 47-50, 64-65, 73-74

Source: Coding guidelines

src/main/runtime/orca-runtime.test.ts (1)

27279-27284: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the version stability this block claims.

The comment states that a later full hydrate skips and the snapshot stays stable, but the test only compares parent ids. A repeated rebuild that bumps snapshotVersion on every list call would still pass. Assert the version too.

♻️ Proposed assertion
     const again = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`)
     expect(again.tabs.map((tab) => (tab.type === 'terminal' ? tab.parentTabId : tab.id))).toEqual(
       fullParentIds
     )
+    expect(again.publicationEpoch).toBe(full.publicationEpoch)
+    expect(again.snapshotVersion).toBe(full.snapshotVersion)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 738b9ddb-6381-4515-8836-329e1c40d7e4

📥 Commits

Reviewing files that changed from the base of the PR and between 16c5526 and 014e07d.

📒 Files selected for processing (24)
  • src/main/runtime/mobile-session-tabs-publication.test.ts
  • src/main/runtime/mobile-session-tabs-publication.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/session-tabs.test.ts
  • src/main/runtime/session-tab-close-tombstones.test.ts
  • src/main/runtime/session-tab-close-tombstones.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/lib/launch-agent-in-new-tab-web-runtime.test.ts
  • src/renderer/src/lib/launch-agent-web-host-tab.test.ts
  • src/renderer/src/lib/launch-agent-web-host-tab.ts
  • src/renderer/src/lib/worktree-activation.ts
  • src/renderer/src/runtime/web-agent-session-handoff.ts
  • src/renderer/src/runtime/web-runtime-session.test.ts
  • src/renderer/src/runtime/web-runtime-session.ts
  • src/renderer/src/runtime/web-runtime-wake-terminal-respawn.test.ts
  • src/renderer/src/runtime/web-runtime-wake-terminal-respawn.ts
  • src/renderer/src/runtime/web-session-close-intent.test.ts
  • src/renderer/src/runtime/web-session-close-intent.ts
  • src/renderer/src/runtime/web-session-tabs-sync.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts
  • src/renderer/src/runtime/web-session-terminal-orphan-recovery.test.ts
  • src/renderer/src/runtime/web-session-terminal-orphan-recovery.ts
  • src/shared/runtime-types.ts

Comment on lines +59 to +61
const fresh = `${mintPrefix}:${Date.now().toString(36)}`
this.mintedEpochByWorktree.set(worktreeId, fresh)
return fresh

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Make the boot epoch unique when timestamps match.

Date.now() has millisecond precision. Two boots in the same millisecond receive the same publicationEpoch and both start at version 1. A client with a higher version from the first boot can reject all snapshots from the second boot as stale.

  • src/main/runtime/mobile-session-tabs-publication.ts#L59-L61: append a random boot identifier, such as randomUUID(), to fresh.
  • src/main/runtime/mobile-session-tabs-publication.test.ts#L83-L91: create both clocks at the same fake time and assert that their epochs differ.
Proposed fix
-    const fresh = `${mintPrefix}:${Date.now().toString(36)}`
+    const fresh = `${mintPrefix}:${Date.now().toString(36)}:${randomUUID()}`
     vi.setSystemTime(new Date('2026-01-01T00:00:00Z'))
     const boot1 = new MobileSessionTabsPublicationClock().next(WORKTREE)
-    vi.setSystemTime(new Date('2026-01-01T00:00:01Z'))
     const boot2 = new MobileSessionTabsPublicationClock().next(WORKTREE)
📝 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
const fresh = `${mintPrefix}:${Date.now().toString(36)}`
this.mintedEpochByWorktree.set(worktreeId, fresh)
return fresh
const fresh = `${mintPrefix}:${Date.now().toString(36)}:${randomUUID()}`
this.mintedEpochByWorktree.set(worktreeId, fresh)
return fresh
Suggested change
const fresh = `${mintPrefix}:${Date.now().toString(36)}`
this.mintedEpochByWorktree.set(worktreeId, fresh)
return fresh
it('mints a fresh epoch per boot', () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'))
const boot1 = new MobileSessionTabsPublicationClock().next(WORKTREE)
const boot2 = new MobileSessionTabsPublicationClock().next(WORKTREE)
expect(boot2.publicationEpoch).not.toBe(boot1.publicationEpoch)
// A rebooted host starts a new same-epoch ordering domain from version 1.
expect(boot2.snapshotVersion).toBe(1)
📍 Affects 2 files
  • src/main/runtime/mobile-session-tabs-publication.ts#L59-L61 (this comment)
  • src/main/runtime/mobile-session-tabs-publication.test.ts#L83-L91

Comment on lines +229 to +231
if ((state.tabsByWorktree[worktreeId] ?? []).some((tab) => isWebTerminalSurfaceTabId(tab.id))) {
return true
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

The terminal-mirror veto is environment-blind. webSessionMirrorHasHostTabs filters editor mirrors and browser mirrors by environmentId, but the terminal branch accepts any mirrored host surface tab. One root cause produces both a correctness risk and a coverage gap.

  • src/renderer/src/runtime/web-session-tabs-sync.ts#L229-L231: resolve the owning environment for each mirrored terminal tab, for example through state.ptyIdsByTabId and the environment-encoded remote PTY id, and count only tabs owned by environmentId.
  • src/renderer/src/runtime/web-session-tabs-sync.test.ts#L3990-L4017: add a case that passes a different environment id with the same mirrored terminal tab and asserts shouldApplyWebSessionTabsSnapshot returns true.
📍 Affects 2 files
  • src/renderer/src/runtime/web-session-tabs-sync.ts#L229-L231 (this comment)
  • src/renderer/src/runtime/web-session-tabs-sync.test.ts#L3990-L4017

Comment on lines +2926 to +2941
for (const entryKey of runtimeSessionMirrorEnvironmentKey.split('\u0000')) {
const [environmentId = '', , , rawRevision = ''] = entryKey.split('\u0001')
if (
!environmentId.trim() ||
!shouldSyncAllRuntimeSessionTabs({
activeRuntimeEnvironmentId: environmentId,
workspaceSessionReady
})
) {
continue
}
nextEntriesByKey.set(entryKey, {
environmentId,
expectedEnvironmentPairingRevision: rawRevision === '' ? undefined : Number(rawRevision)
})
}

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect the reachable mirror target shape and pairingRevision typing.
set -euo pipefail

rg -n -C15 'export function getReachableRuntimeSessionMirrorTargets' src
rg -n -C3 'pairingRevision\??:' src --type=ts

Repository: stablyai/orca

Length of output: 37425


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Inspect the affected synchronization block and producer locations.
sed -n '2860,2968p' src/renderer/src/runtime/web-session-tabs-sync.ts

# 2) Inspect the only deterministic key-producer location from the initial search.
sed -n '30,52p' src/renderer/src/lib/runtime-session-mirror-targets.ts

# 3) Programmatically model the parsed revision behavior for representative keys.
node - <<'JS'
const keys = [
  'env-id\u0001\u0001\u000110',
  'env-id\u0001\u0001\u0001',
  'env-id\u0001\u0001\u0001undefined',
  'env-id\u0001\u0001\u0001NaN',
]
for (const key of keys) {
  const [environmentId = '', , , rawRevision = ''] = key.split('\u0001')
  const current = rawRevision === '' ? undefined : Number(rawRevision)
  const proposed = rawRevision === '' || !Number.isFinite(Number(rawRevision)) ? undefined : Number(rawRevision)
  console.log(JSON.stringify({ key, rawRevision, current, proposed }))
  if (current !== current) {
    console.log(JSON.stringify({ currentNotEqualsCurrent: true }))
  } else {
    console.log(JSON.stringify({ currentEqualsCurrent: true }))
  }
}
JS

Repository: stablyai/orca

Length of output: 5435


Guard invalid pairing revisions before subscribing.

The key is formatted from pairingRevision ?? environment.createdAt, but malformed stored keys can still put undefined/non-finite values into expectedEnvironmentPairingRevision. Keep the same handling as an absent revision; otherwise every later revision comparison fails and sync stops updating for that environment.

🛡️ Proposed guard
-      nextEntriesByKey.set(entryKey, {
-        environmentId,
-        expectedEnvironmentPairingRevision: rawRevision === '' ? undefined : Number(rawRevision)
-      })
+      const parsedRevision = Number(rawRevision)
+      nextEntriesByKey.set(entryKey, {
+        environmentId,
+        expectedEnvironmentPairingRevision:
+          rawRevision === '' || !Number.isFinite(parsedRevision) ? undefined : parsedRevision
+      })
📝 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
for (const entryKey of runtimeSessionMirrorEnvironmentKey.split('\u0000')) {
const [environmentId = '', , , rawRevision = ''] = entryKey.split('\u0001')
if (
!environmentId.trim() ||
!shouldSyncAllRuntimeSessionTabs({
activeRuntimeEnvironmentId: environmentId,
workspaceSessionReady
})
) {
continue
}
nextEntriesByKey.set(entryKey, {
environmentId,
expectedEnvironmentPairingRevision: rawRevision === '' ? undefined : Number(rawRevision)
})
}
for (const entryKey of runtimeSessionMirrorEnvironmentKey.split('\u0000')) {
const [environmentId = '', , , rawRevision = ''] = entryKey.split('\u0001')
if (
!environmentId.trim() ||
!shouldSyncAllRuntimeSessionTabs({
activeRuntimeEnvironmentId: environmentId,
workspaceSessionReady
})
) {
continue
}
const parsedRevision = Number(rawRevision)
nextEntriesByKey.set(entryKey, {
environmentId,
expectedEnvironmentPairingRevision:
rawRevision === '' || !Number.isFinite(parsedRevision) ? undefined : parsedRevision
})
}

@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a suite of timing-dependent race conditions that made remote orca serve session-tab management unreliable: tabs vanishing after creation, worktree switches wiping the session list, closed tabs resurrecting after reconnect, and multi-device divergence.

  • Server: Replaces per-mutation epoch minting with MobileSessionTabsPublicationClock (one stable epoch per worktree per boot, strictly-monotonic versions), adds SessionTabCloseTombstoneStore (30 s TTL) to prevent other devices from re-adopting dying PTYs, adds hydrationPending flag on unhydrated fabricated-empty snapshots, and throws renderer_unavailable instead of silently acking closes with no renderer route.
  • Client: Routes session.tabs.list results through the same per-worktree serialized orphan-recovery chain as subscription frames, scopes wake-respawn and close-intent tracking per environment (not globally), guards the agent-handoff confirm behind host-tab presence, and shows a toast on close failure instead of silently diverging.
  • QuickLaunch: Pre-create prune now skips tabs with a recorded handoff or pending create, and the post-create prune is bounded to tabs that existed before the operation; remoteCloseOwnedByHost prevents the prune from firing terminal.close at a live host session.

Confidence Score: 5/5

Safe to merge — all changes are carefully scoped to the remote session-tab sync path, protocol additions are backward-compatible optional fields, and the two new core classes have dedicated unit tests.

Every mechanism patched has a clear root-cause comment, a matching regression test, and real-world verification on the original repro environment. The publication clock and tombstone store are new, self-contained classes with narrow interfaces. Protocol additions (hydrationPending, recentlyClosedTabIds) are optional, so old clients and old servers degrade gracefully. The close-intent sweep change (TTL-based instead of host-confirmed-absence) is strictly safer. Per-environment isolation for wake-respawn and intent tracking eliminates the cross-environment interference that caused multi-device freezes. No existing public API signatures are broken.

Files Needing Attention: No files require special attention. The large orca-runtime.ts changes are well-commented and each mutation site follows the same pattern (replacing inline Date.now() epoch minting and + 1 version bumps with clock calls).

Important Files Changed

Filename Overview
src/main/runtime/mobile-session-tabs-publication.ts New file: MobileSessionTabsPublicationClock ensures one stable epoch per worktree per boot with strictly-monotonic versions across all publish sites; normalizeClientEchoedPublicationEpoch fixes projected-epoch close refusals.
src/main/runtime/session-tab-close-tombstones.ts New file: SessionTabCloseTombstoneStore with 30 s TTL; lazy sweep on access; correctly handles safe Map deletion during iteration.
src/main/runtime/orca-runtime.ts Integrates publication clock, tombstone store, hydrationPending flag, runtimeOwnedSeeded tracking, unbound-daemon-PTY kill scope widening, and renderer_unavailable error; also fixes provider seq domain isolation for unsynced snapshots.
src/renderer/src/runtime/web-session-tabs-sync.ts Per-environment sync lifecycle refactored from a monolithic useEffect into reconcileWebSessionMirrorEnvironmentSync with per-entry disposers; close intents swept by TTL instead of host-confirmed absence; hydrationPending and none-epoch guards added; wake-respawn keys scoped per environment.
src/renderer/src/runtime/web-runtime-session.ts list results now route through orphan-recovery serialized chain; post-create refresh uses listAfterCurrentInFlight; handoff confirm gated on host-tab presence; close failures show user-visible toast with refresh.
src/renderer/src/lib/launch-agent-web-host-tab.ts QuickLaunch prune now skips mid-launch tabs (handoff/pending/resume), bounds post-create prune to pre-create survivors, and uses remoteCloseOwnedByHost to avoid firing terminal.close for pruned local tabs.
src/renderer/src/runtime/web-runtime-wake-terminal-respawn.ts Wake-respawn in-flight guards keyed by environmentId+worktreeId instead of worktreeId alone; clearAllWebRuntimeWakeTerminalRespawn replaced with per-environment clear to avoid cross-environment interference.
src/renderer/src/runtime/web-session-close-intent.ts reconcileWebSessionCloseIntents replaced by sweepExpiredWebSessionCloseIntents: intents now expire strictly by TTL rather than host-confirmed absence, preventing a delayed pre-close frame from prematurely clearing the suppression.
src/renderer/src/runtime/web-session-terminal-orphan-recovery.ts Tombstoned host tabs excluded from orphan candidates so dying PTYs after a cross-device close do not stall the recovery chain.
src/shared/runtime-types.ts Adds optional hydrationPending and recentlyClosedTabIds fields to RuntimeMobileSessionTabsResult; both are backward-compatible: old clients ignore them.

Sequence Diagram

sequenceDiagram
    participant Server as OrcaRuntimeService (Server)
    participant Clock as MobileSessionTabsPublicationClock
    participant Tombstone as SessionTabCloseTombstoneStore
    participant Client as WebSessionTabsSync (Client)

    Note over Server,Client: Session Tab Creation
    Server->>Clock: next(worktreeId, existing)
    Clock-->>Server: "{epoch: stable-boot-epoch, version: N}"
    Server->>Client: "snapshot {epoch, version:N, tabs:[...]}"
    Client->>Client: recoverWebSessionTerminalOrphansBeforeApply()
    Client->>Client: applyFreshWebSessionTabsSnapshot()

    Note over Server,Client: Session Tab Close
    Server->>Tombstone: record(worktreeId, hostTabId, ptyIds)
    Server->>Clock: next(worktreeId, snapshot)
    Clock-->>Server: "{epoch: stable-boot-epoch, version: N+1}"
    Server->>Client: "snapshot {epoch, version:N+1, recentlyClosedTabIds:[id]}"
    Client->>Client: orphan recovery skips tombstoned PTYs
    Client->>Client: applyFreshWebSessionTabsSnapshot()

    Note over Server,Client: Close Failure Recovery
    Client->>Server: session.tabs.closeLifecycle(tabId)
    Server-->>Client: error: renderer_unavailable
    Client->>Client: acceptReplayedWebSessionTabsSnapshot()
    Client->>Client: refreshWebRuntimeSessionTabsSnapshot()
    Client->>Client: showWebRuntimeSessionUserCloseFailureToast()

    Note over Server,Client: Hydration Pending Guard
    Server->>Client: "snapshot {epoch:'none', hydrationPending:true, tabs:[]}"
    Client->>Client: shouldApplyWebSessionTabsSnapshot() returns false

    Note over Server,Client: Per-Environment Isolation
    Client->>Client: reconcileWebSessionMirrorEnvironmentSync()
    Client->>Client: clearWebRuntimeWakeTerminalRespawnForEnvironment(envId)
    Client->>Client: "clearWebSessionCloseIntentsForOwner({envId, pairingRevision})"
Loading

Reviews (2): Last reviewed commit: "fix(runtime): reattach daemon PTY stream..." | Re-trigger Greptile

Comment on lines +47 to +58
/** Environment-agnostic lookup: callers that only know the worktree (e.g. the
* QuickLaunch prune) must still treat a handed-off provisional tab as live. */
export function hasWebAgentSessionHandoffForProvisionalTab(
worktreeId: string,
provisionalTabId: string
): boolean {
const suffix = `\0${worktreeId}\0${provisionalTabId}`
for (const key of handoffByProvisionalTab.keys()) {
if (key.endsWith(suffix)) {
return true
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 O(n) suffix scan over all handoff keys

hasWebAgentSessionHandoffForProvisionalTab iterates over every key in handoffByProvisionalTab using key.endsWith(suffix). It's called twice per launchAgentInWebHostTab (pre-create and post-create prune). In practice the map stays small, but if many concurrent launches accumulate unflushed entries it would grow linearly. A reverse lookup — a Set<string> keyed on ${worktreeId}\0${provisionalTabId} — alongside the primary map would make this O(1).

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

…er host restart

After a serve restart the boot inventory restores session-tab records as
'ready', but the daemon only streams output to the process that last ran
createOrAttach — so restored tabs delivered snapshots with zero live
bytes until some spawn path fired. Activation now re-materializes a
ready tab whose PTY has no provider attachment this boot, which
reattaches the stream and runs the provider sequence sync in one step.

Provider buffer snapshots also no longer fabricate a seq from the
provider's cumulative domain when no sequence sync has run this boot;
an unanchored seq poisoned client dedupe baselines into silently
dropping every live frame (output frozen until a tab switch refetched a
snapshot, re-poisoning the baseline).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@Jinwoo-H

Copy link
Copy Markdown
Contributor

Thanks @Him188 for the broad remote session-tab synchronization investigation. The underlying cases are now covered by the merged owner fixes #16546, #16748, #16750, #16751, #16956, #16969, and #17064. We are retaining your contribution as historical credit; no contributor follow-up is requested. Closing this superseded branch.

@Jinwoo-H Jinwoo-H closed this Aug 31, 2026
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