Repository navigation
Conversation
- 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>
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
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 valueRename the set to match the new key shape.
The set now stores
${environmentId}\0${worktreeId}keys, but the name still saysByWorktree. A reader can assume worktree-only keys and add a lookup with a bare worktree id. Deleting entries duringfor...ofover aSetis safe, soclearWebRuntimeWakeTerminalRespawnForEnvironmentneeds 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 valueSkip the warning after disposal in
onError.Every other callback in this synchronizer checks
disposedbefore it logs.onErrordoes 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 winAdd 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 toENV. The browser case at Lines 4049-4055 pins the environment throughremoteBrowserPageHandlesByPageId; 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 onwebSessionMirrorHasHostTabsinsrc/renderer/src/runtime/web-session-tabs-sync.ts.src/renderer/src/runtime/web-runtime-session.ts (1)
996-1015: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMatch the RPC error code instead of the message text.
RuntimeRpcCallErroralready exposeserror.code, andmapRuntimeErrorpreservesterminal_tab_pinnedandterminal_tab_not_foundas their own structured codes. Use that code inshowWebRuntimeSessionUserCloseFailureToast; keep message substring matching only as a fallback. Also update the existing close-toast tests to covercode: 'terminal_tab_pinned'andcode: 'terminal_tab_not_found'.src/main/runtime/mobile-session-tabs-publication.ts (1)
10-13: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCondense 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 winAssert 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
snapshotVersionon 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
📒 Files selected for processing (24)
src/main/runtime/mobile-session-tabs-publication.test.tssrc/main/runtime/mobile-session-tabs-publication.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/session-tabs.test.tssrc/main/runtime/session-tab-close-tombstones.test.tssrc/main/runtime/session-tab-close-tombstones.tssrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/lib/launch-agent-in-new-tab-web-runtime.test.tssrc/renderer/src/lib/launch-agent-web-host-tab.test.tssrc/renderer/src/lib/launch-agent-web-host-tab.tssrc/renderer/src/lib/worktree-activation.tssrc/renderer/src/runtime/web-agent-session-handoff.tssrc/renderer/src/runtime/web-runtime-session.test.tssrc/renderer/src/runtime/web-runtime-session.tssrc/renderer/src/runtime/web-runtime-wake-terminal-respawn.test.tssrc/renderer/src/runtime/web-runtime-wake-terminal-respawn.tssrc/renderer/src/runtime/web-session-close-intent.test.tssrc/renderer/src/runtime/web-session-close-intent.tssrc/renderer/src/runtime/web-session-tabs-sync.test.tssrc/renderer/src/runtime/web-session-tabs-sync.tssrc/renderer/src/runtime/web-session-terminal-orphan-recovery.test.tssrc/renderer/src/runtime/web-session-terminal-orphan-recovery.tssrc/shared/runtime-types.ts
| const fresh = `${mintPrefix}:${Date.now().toString(36)}` | ||
| this.mintedEpochByWorktree.set(worktreeId, fresh) | ||
| return fresh |
There was a problem hiding this comment.
🗄️ 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 asrandomUUID(), tofresh.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.
| 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 |
| 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
| if ((state.tabsByWorktree[worktreeId] ?? []).some((tab) => isWebTerminalSurfaceTabId(tab.id))) { | ||
| return true | ||
| } |
There was a problem hiding this comment.
🗄️ 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 throughstate.ptyIdsByTabIdand the environment-encoded remote PTY id, and count only tabs owned byenvironmentId.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 assertsshouldApplyWebSessionTabsSnapshotreturnstrue.
📍 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
| 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) | ||
| }) | ||
| } |
There was a problem hiding this comment.
🩺 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=tsRepository: 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 }))
}
}
JSRepository: 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.
| 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 SummaryThis PR fixes a suite of timing-dependent race conditions that made remote
Confidence Score: 5/5Safe 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).
|
| 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})"
Reviews (2): Last reviewed commit: "fix(runtime): reattach daemon PTY stream..." | Re-trigger Greptile
| /** 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 | ||
| } | ||
| } |
There was a problem hiding this comment.
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>
|
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. |
Problem
When a client is attached to a remote orca server (
orca serveover 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.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)
snapshotVersionframes — a differentpublicationEpochalways applies (web-session-tabs-sync.ts), by design assuming one epoch per host boot (as desktop mode does). The headless server minted a freshheadless:${Date.now()}epoch on nearly every mutation (10 sites) plusheadless-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, butsession.tabs.listresults apply outside it, so a delayed push frame regularly landed after a newer list result and authoritatively culled fresh tabs.mobileSessionTabsByWorktreeentry 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 anexisting.tabs.length>0skip — subset lock-in.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.${epoch}:client-navigation, butsession.tabs.closeLifecyclecompared 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).launchAgenttab 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.{closed:true}; unbound daemon PTYs escaped the kill scope ("hidden, not closed").ready, but the daemon only streams a session's output to the process that last rancreateOrAttach— 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 monotonicsnapshotVersionacross 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 carryhydrationPending: trueuntil 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. NewSessionTabCloseTombstoneStore(30s TTL) records every successful close;recentlyClosedTabIdsrides every published snapshot,terminal.listhides 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).closeLifecyclenormalizes a trailing:client-navigationbefore the stale-publication comparison. The notifier-less close branch throwsrenderer_unavailableinstead of faking success.Client —
session.tabs.listresults 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;hydrationPendingframes (and'none'-epoch empties from older servers, including their:client-navigationprojections) 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 hostterminal.closefor pruned local tabs.Server, host restart —
session.tabs.activatenow re-materializes areadytab 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 omitsequntil 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
readytab vs spawn-free activation while attached; seq omitted while unanchored vs translated once synced). All touched suites pluspnpm run typecheckare green after each commit.Real-world verification
Deployed on the original repro environment:
orca serverunning 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