Skip to content

fix(runtime): register phone tab-list streams when the request arrives - #23045

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/session-tabs-register-at-admission
Sep 28, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/session-tabs-register-at-admission

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​345 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​344
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​143 $\color{#cf222e}{\Huge{\mathbf{−}}}$​78 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​65

ELI5

When you open a worktree on your phone, the phone asks the desktop for a live list of that worktree's tabs. The desktop takes a moment to prepare the first copy of that list. If you left the worktree during that moment, the desktop never heard that you left: once the list was ready it started sending updates anyway, to a phone that had stopped listening, until the phone disconnected. Now the desktop writes the phone's request down the moment it arrives, so leaving during that moment cancels it.

What Changed

Before: session.tabs.subscribe entered the stream in the host's list of open streams only after two waits: restoring structured chat tabs, then building the first tab snapshot. A session.tabs.unsubscribe (or a closed connection) that arrived during those waits found nothing to end. When the waits finished, the stream registered anyway, attached a desktop listener, and kept sending tab updates to a client that had thrown the stream away, until the socket closed. Phones hit this, and so does a desktop window connected to a remote Orca server, which unsubscribes by request id right away and keeps its connection open for a long time. session.tabs.subscribeAll had the same gap: it restored structured tabs before entering its stream, so an unsubscribeAll or a closed connection during that restore also left a stream behind.

After: both streams are entered in the list before their first wait, under the same keys as before (session.tabs:<connection>:<worktree>:<request id> and session.tabs:<connection>:*:<request id>). An unsubscribe, a closed connection, or a newer same-key subscribe that arrives during setup now ends the stream: it attaches no listener and sends no snapshot. subscribe then sends one end; subscribeAll ends the way it already did during setup, silently during the restore and with a client_disconnected error during the snapshot build.

How session.tabs.subscribe does it:

  • Phones and the web client name the worktree as id:<worktree id>, which is exactly the worktree part of the key, so the key is known before any wait. A request that names a worktree some other way (a path or branch) still has to wait for the lookup before it knows its key; it registers as soon as the lookup returns, as before.
  • A released flag is set when the stream ends, and setup checks it after every wait, so a stream ended during setup does nothing more.
  • The request's abort signal (socket close for phones, abort for desktop IPC) now ends the stream too, and a request whose socket was already gone when it started registers nothing. subscribeAll already did this; subscribe did not.
  • If setup fails after the stream was already ended, the error is dropped, so end is never followed by an error. If it fails before that, the stream is removed without an end and the error is reported as before.

An unsubscribe that names no request id (sent by direct-connection phones released before #22943) ends every tab-list stream for the worktree on that connection, after it has looked up the worktree. Now that subscribes register on arrival, that sweep could also end a same-worktree subscribe that arrived during the lookup, which the phone would then treat as a lost stream. The unsubscribe now records the registry's registration version when it is dispatched, as terminal.unsubscribe already does, and the sweep ends only streams registered before it.

For subscribeAll, the structured tab restore moved inside the stream setup, after registration; the stream's existing closed flag already stops a stream ended during setup. The restore helper now returns nothing when there is nothing to restore, so streams that skip the restore start their snapshot on the same tick as before.

Behavior differences: a subscribe stream ended during setup now receives one end; before, nothing could end it during setup, so this case did not exist. A subscribeAll whose restore fails after it was ended reports that error, as its snapshot build already did; the client has dropped the stream by then.

Why

The leak happens because a stream still being set up is not in the list that unsubscribe and connection cleanup search. Entering it when the request arrives removes that gap for every phone version and for relay connections, rather than guarding around it.

A recent phone change holds a direct-connection unsubscribe until the first snapshot arrives, and the relay transport already did the same. That hold only helps phones that have it; old phones still send the unsubscribe immediately, and the host is where the stream is actually set up.

Alternatives considered:

  • A second check after setup that looks for a recorded "phone already left" note. That is a second mechanism next to the stream list, and a closed connection or a same-key replacement during setup still cannot reach it.
  • Resolving every selector to a worktree id before registering. Only an id: selector can be resolved without waiting, and every phone and web client already sends one; resolving other selectors first would still wait before registering, and it would need a new runtime method for no shipped client.
  • Moving the tab-list streams onto the terminal stream's new registration object from fix(runtime): register phone terminal subscriptions when the request arrives #22948. That object also manages phone presence and the terminal process watch, which tab lists do not have, and it is not merged yet. Until the streams share one registration object, each tab-list stream carries its own ended-during-setup handling; once fix(runtime): register phone terminal subscriptions when the request arrives #22948 lands, both tab-list streams could move onto it in a follow-up.

Linked Issue

Part of #22928

Visual Proof

Pending: live QA runs after the review loop

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

New dispatcher tests (src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts) run the session tab methods against the real stream registry (RuntimeSubscriptionRegistry):

  • An unsubscribe during the structured tab restore, during the snapshot build, and (the old-phone form, with no request id) during the snapshot build: no entry is left, no desktop listener is attached, and the stream gets exactly one end. All three fail on main, where the entry is left registered.
  • A connection close during setup leaves no entry and no listener. Fails on main.
  • A request aborted during setup ends the stream with one end and leaves no entry or listener. Fails if the abort listener is removed.
  • A request whose socket was already closed registers nothing. Fails on main, and fails if the "already aborted" branch is removed.
  • A stream ended during setup whose snapshot then fails sends only end, no error. Fails on main (error only) and fails if the post-release error is not dropped.
  • For subscribeAll: an unsubscribeAll or a connection close during the restore leaves no stream and sends no snapshot. Both fail on main.
  • An unsubscribe with no request id spares a same-worktree subscribe that arrives while the unsubscribe is looking up the worktree. Fails without the dispatch-time version capture, and fails without the version filter on the sweep.
  • Unchanged behavior, pinned: snapshot, update, then one end on unsubscribe (and none again on a later connection close); a setup failure sends only the error and leaves no entry; a non-id: selector registers under the resolved worktree; an unsubscribe by request id ends only its own stream when two streams share a worktree on one connection.

Checks run locally: pnpm tc:node, oxlint on the changed files, pnpm run check:code-quality:changed, src/main/runtime/orca-runtime.test.ts, and the session tab, subscription registry, dispatcher and terminal ownership test files (16 files, 169 tests), including the census boundary tests, which pin the subscribeAll snapshot timing.

AI Disclosure

Review

  • Security: no new methods, inputs or permissions; the keys that unsubscribe matches are unchanged.
  • Cross-platform: host-side TypeScript only, with no platform-specific behavior.
  • Remote SSH: tab lists are served by the runtime that owns the worktree, so local and SSH-hosted worktrees behave the same; nothing here reports on remote process state.
  • Mobile: no phone code changes; direct and relay phones of every version get the fix. The phone-side holds of an early unsubscribe keep working and become unnecessary against this host.
  • Backwards compatibility (mixed phone/host versions): no wire change. Old and new phones send the same messages and get the same frames, except that a subscribe stream ended during setup now receives one end, which phones already handle for ended streams. A no-request-id unsubscribe from an older phone no longer ends a subscribe that arrived after it; it does now reliably end a same-worktree stream on that connection that arrived before it and is still in setup, the same as it already did for one that had finished setup.
  • Performance: one abort listener per session.tabs.subscribe, removed when the stream ends; subscribeAll attaches its change listener slightly earlier when a structured tab restore runs.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

session.tabs.unsubscribe still resolves the worktree before cleaning up, and still sweeps the worktree's streams on the connection when no request id is given; the only change is that the sweep skips streams registered after the unsubscribe was dispatched. session.tabs.unsubscribeAll is unchanged.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The session tab inventory subscription now waits for supported structured-tab restoration before collecting the initial inventory. The per-worktree subscription now manages cleanup and release during asynchronous setup, including unsubscribe, socket close, and abort cases. Unsubscribe cleanup uses a registration-version limit. Added tests cover setup failures, subscription frames, registration keys, and cleanup.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to f9a02

A subscribeAll stream closed during restoration may remain logically open without an end frame, though normal client-close paths clean up correctly. This is a low-impact follow-up risk.

Security Architecture Review

Security architecture risk: 🔵 Low · up to f9a02

Registering streams before setup should reduce updates sent after a phone stops listening. The change remains within desktop session-tab subscriptions, but cancellation and compatibility across all client behaviors are not fully established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The observed change is confined to desktop RPC subscription admission and cleanup. Its directly visible effect is on streams keyed to a connection and session-tab worktree, rather than a new cross-service privilege or data-store path.

Trust Boundaries and Controls

  • observed — The handler obtains the worktree ID from an explicit selector before listing, but snapshots still follow paired-device-aware listing. Registry keys separate connections and request IDs; version-bounded prefix cleanup protects registrations admitted after a worktree-wide unsubscribe began.

Resilience and Maintainability Implications

  • observed — Cancellation after registration prevents subsequent per-worktree listing or snapshot emission once restoration returns. An already-aborted per-worktree request may nevertheless start restoration; the prior handler also invoked restoration before checking closure, so this is not established as introduced by the PR.

Hardening Proposals

  • proposed — Consider a generation-aware cleanup contract for optional-ID unsubscribeAll and reused request IDs if clients can exercise those forms. Their unfenced cleanup behavior predates this PR; client usage has not been established.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 9 files. 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: registering phone tab-list streams when the request arrives.
Description check ✅ Passed The description is detailed and covers the user impact, implementation, rationale, alternatives, linked issue, testing, compatibility, and checklist items. The visual proof section remains marked pend…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 40b83b81-6e67-4b64-97ea-146bda085be5

📥 Commits

Reviewing files that changed from the base of the PR and between 02a5594 and d430aeb.

📒 Files selected for processing (4)
  • src/main/runtime/rpc/methods/session-tabs-inventory.ts
  • src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts
  • src/main/runtime/rpc/methods/session-tabs.ts
  • src/main/runtime/rpc/methods/structured-session-tab-restore.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

Comment on lines +245 to +252
// Why: restore after registering, so an unsubscribe or socket close while it runs still finds the stream.
const restoring = restoreStructuredTabsIfSupported(context)
if (restoring) {
await restoring
if (closed) {
return
}
}

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '215,285p' src/main/runtime/rpc/methods/session-tabs-inventory.ts
rg -n 'dispatchStreaming|subscribeSessionTabsInventory|restoreStructuredTabsIfSupported' src/main/runtime/rpc/dispatcher.ts src/main/runtime/rpc/methods/session-tabs.ts src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts

Repository: stablyai/orca

Length of output: 3274


🏁 Script executed:

set -eu
printf '%s\n' '--- dispatcher ---'
sed -n '100,190p' src/main/runtime/rpc/dispatcher.ts
printf '%s\n' '--- subscribe admission test ---'
sed -n '1,240p' src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts
printf '%s\n' '--- restoration helper ---'
rg -n -A100 -B20 'export (async )?function restoreStructuredTabsIfSupported|function restoreStructuredTabsIfSupported|const restoreStructuredTabsIfSupported' src/main/runtime/rpc/methods
printf '%s\n' '--- inventory function and callers ---'
rg -n -A35 -B15 'subscribeSessionTabsInventory|dispatchStreaming\(' src/main/runtime/rpc/methods/session-tabs-inventory.ts src/main/runtime/rpc/methods/session-tabs.ts src/main/runtime/rpc/dispatcher.ts
printf '%s\n' '--- PR diff stat and focused diff ---'
git diff --stat 02a55944347346065453e179e071e64d9ae861dc d430aebea50b0f35e527b5c3c4c05c8823d15fcd -- src/main/runtime/rpc/methods/session-tabs-inventory.ts src/main/runtime/rpc/dispatcher.ts src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts src/main/runtime/rpc/methods/structured-session-tab-restore.ts
git diff --unified=35 02a55944347346065453e179e071e64d9ae861dc d430aebea50b0f35e527b5c3c4c05c8823d15fcd -- src/main/runtime/rpc/methods/session-tabs-inventory.ts src/main/runtime/rpc/dispatcher.ts src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts src/main/runtime/rpc/methods/structured-session-tab-restore.ts

Repository: stablyai/orca

Length of output: 41967


🏁 Script executed:

set -eu
printf '%s\n' '--- streaming dispatcher bindings ---'
rg -n -g '*.ts' 'streamingDispatcher|class .*Streaming|dispatch\(request: RpcRequest|mapDispatcherError|defineStreamingMethod' src/main/runtime/rpc
printf '%s\n' '--- likely dispatcher files ---'
fd -t f -e ts . src/main/runtime/rpc | rg 'dispatch|stream|core'

Repository: stablyai/orca

Length of output: 9128


🏁 Script executed:

set -eu
printf '%s\n' '--- rpc streaming dispatcher ---'
sed -n '1,235p' src/main/runtime/rpc/rpc-streaming-dispatcher.ts
printf '%s\n' '--- relevant streaming tests ---'
rg -n -A35 -B15 'error|abort|closed|end|released|reject|unsubscribe' src/main/runtime/rpc/streaming.test.ts src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts

Repository: stablyai/orca

Length of output: 41789


🏁 Script executed:

set -eu
printf '%s\n' '--- inventory setup and cleanup ---'
sed -n '145,275p' src/main/runtime/rpc/methods/session-tabs-inventory.ts
printf '%s\n' '--- session tab streaming registrations ---'
sed -n '80,115p' src/main/runtime/rpc/methods/session-tabs.ts
sed -n '205,235p' src/main/runtime/rpc/methods/session-tabs.ts
printf '%s\n' '--- registry cleanup semantics ---'
rg -n -A90 -B15 'class RuntimeSubscriptionRegistry|register\(|cleanup\(|cleanupByPrefix|cleanupForConnection' src/main/runtime/runtime-subscription-registry.ts src/main/runtime/runtime-subscription-registry.test.ts

Repository: stablyai/orca

Length of output: 35009


🏁 Script executed:

set -eu
rg -n -A12 -B12 'initialized\s*=' src/main/runtime/rpc/methods/session-tabs-inventory.ts

Repository: stablyai/orca

Length of output: 1799


Suppress restoration errors after subscribeAll is released.

When subscribeAll is released during restoreStructuredTabsIfSupported, the cleanup removes the subscription and sets closed. If restoration then rejects, the inventory catch rethrows the rejection. RpcStreamingDispatcher converts every streaming-handler rejection into an error frame, so the released stream receives a late error.

Suggested fix
  } catch (error) {
+   if (closed) {
+     return
+   }
    runtime.cleanupSubscription(subscriptionId)
    throw error
  }

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '90,125p' src/main/runtime/rpc/methods/session-tabs-inventory.ts
sed -n '225,310p' src/main/runtime/rpc/methods/session-tabs-inventory.ts

Repository: stablyai/orca

Length of output: 3995


🏁 Script executed:

sed -n '1,115p' src/main/runtime/rpc/methods/session-tabs-inventory.ts
sed -n '115,230p' src/main/runtime/rpc/methods/session-tabs-inventory.ts
sed -n '230,325p' src/main/runtime/rpc/methods/session-tabs-inventory.ts
sed -n '220,315p' src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts
rg -n "function restoreStructuredTabsIfSupported|restoreStructuredTabsIfSupported|projectSessionTabsForClient|unsubscribeAll|cleanupSubscription" src/main/runtime/rpc/methods src/main/runtime -g '*.ts' | head -120

Repository: stablyai/orca

Length of output: 27950


🏁 Script executed:

printf '%s\n' '--- inventory cleanup and restore gate ---'
sed -n '115,285p' src/main/runtime/rpc/methods/session-tabs-inventory.ts | nl -ba -v115
printf '%s\n' '--- restoration helper ---'
sed -n '1,100p' src/main/runtime/rpc/methods/structured-session-tab-restore.ts | nl -ba
printf '%s\n' '--- admission release tests ---'
sed -n '245,305p' src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts | nl -ba -v245
printf '%s\n' '--- cleanup registry definitions ---'
rg -n "class .*Subscription|registerSubscriptionCleanup|cleanupSubscription\\(|cleanupByPrefix|cleanupForConnection" src/main -g '*.ts' | head -80

Repository: stablyai/orca

Length of output: 21922


🏁 Script executed:

sed -n '1,190p' src/main/runtime/rpc/subscription-registry-test-double.ts | nl -ba
printf '%s\n' '--- session-tab end-frame tests ---'
rg -n -C 6 "frames\\([^)]*\\).*end|toEqual\\(\\[[^]]*end|type: ['\"]end['\"]|['\"]end['\"]" src/main/runtime/rpc/methods/session-tabs*test.ts src/main/runtime/rpc -g '*session-tabs*test.ts' | head -160
printf '%s\n' '--- current PR diff for the target file ---'
git diff --unified=20 02a55944347346065453e179e071e64d9ae861dc d430aebea50b0f35e527b5c3c4c05c8823d15fcd -- src/main/runtime/rpc/methods/session-tabs-inventory.ts

Repository: stablyai/orca

Length of output: 25912


🏁 Script executed:

sed -n '80,205p' src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts | nl -ba -v80
sed -n '390,435p' src/main/runtime/rpc/methods/session-tabs-inventory-rpc.test.ts | nl -ba -v390

Repository: stablyai/orca

Length of output: 7605


Emit end for release before initialization, but not for failed setup.

A release during restoreStructuredTabsIfSupported(context) runs before initialized becomes true. The current cleanup callback therefore emits no end. If restoration remains pending, the stream never reaches the later closed check.

Do not emit end for cleanup caused only by setup failure. Existing tests require failed setup to report only error. Suppress that cleanup emission and guard the release emission so it occurs once.

Suggested fix
   let initialized = false
   let closed = false
+  let endEmitted = false
+  let suppressEndOnSetupFailure = false
...
       clearBufferedChanges()
       publishedSnapshotsByWorktree.clear()
       deliveredChangeSequenceByWorktree.clear()
-      if (initialized) {
+      if (!suppressEndOnSetupFailure && !endEmitted) {
+        endEmitted = true
         emit({ type: 'end' })
       }
@@
   } catch (error) {
+    suppressEndOnSetupFailure = true
     runtime.cleanupSubscription(subscriptionId)
     throw error
   }

Comment on lines +151 to +159
const initial = await runtime.listMobileSessionTabs(params.worktree, pairedDeviceId)
if (released) {
return
}
if (!subscriptionId) {
register(initial.worktree)
if (released) {
return
}

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '100,222p' src/main/runtime/rpc/methods/session-tabs.ts
sed -n '1,190p' src/main/runtime/runtime-subscription-registry.ts
rg -n 'unsubscribe|abort|session.tabs.subscribe' src/shared/remote-runtime-shared-control-protocol.ts

Repository: stablyai/orca

Length of output: 10540


Prevent late registration for non-ID selectors.

When a non-ID selector is used, session.tabs.subscribe registers its cleanup only after listMobileSessionTabs() resolves. If session.tabs.unsubscribe completes first, it finds no registration. The subscribe continuation then registers the subscription and starts the notification listener after the client has unsubscribed.

Register a cancellation state before the first await, or make the unsubscribe path cancel the pending setup by request ID. The fix must cover non-ID selectors without changing the existing explicit-ID cleanup behavior.

@pullfrog pullfrog 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.

ℹ️ No critical issues — minor suggestions inline.

Reviewed changes

  • Register at admission — session.tabs.subscribe now enters its cleanup entry under the id:-derived key before the restore and snapshot awaits, so an unsubscribe, a socket close, or a newer same-key subscribe during setup ends the stream instead of leaving it registered with a live desktop listener.
  • Release/abort wiring — a released latch, an abort listener attached at registration, and a post-release error drop align subscribe with the terminal and native-chat stream pattern.
  • subscribeAll restore moved inside the stream — the structured-tab restore now runs after registration, and restoreStructuredTabsIfSupported returns undefined when there is nothing to restore so callers skip the await.
  • Tests — a new dispatcher test drives SESSION_TAB_METHODS against the real RuntimeSubscriptionRegistry for the unsubscribe, close, already-aborted, replacement, and setup-failure paths.

ℹ️ subscribeAll is silent when released before its first snapshot

The PR body says a tab-list stream ended during setup now receives one end. session.tabs.subscribe does, but subscribeAll's cleanup only emits end when initialized is true (session-tabs-inventory.ts:234-236), so a release during the newly-added restore ends the stream with no terminal frame. If that asymmetry is deliberate, a word in the comment would help; if not, it can be gated the same way as subscribe while still suppressing it on setup failure.

Technical details
# subscribeAll emits no end before initialization

## Affected sites
- `src/main/runtime/rpc/methods/session-tabs-inventory.ts:234-236` — `if (initialized) emit({ type: 'end' })`
- `src/main/runtime/rpc/methods/session-tabs.ts:128-130` — `subscribe` emits `end` on release regardless of whether a snapshot was sent

## Required outcome
- Decide whether a `subscribeAll` stream released before its `snapshots` frame should send one `end`, and make the cleanup comment state the chosen behavior.

## Open question for the human
- Is the no-end pre-init path intentional, or should `subscribeAll` match `subscribe`?

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +246 to +252
const restoring = restoreStructuredTabsIfSupported(context)
if (restoring) {
await restoring
if (closed) {
return
}
}

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.

session.tabs.subscribe drops a setup error once the stream was released (if (released) return in its catch, session-tabs.ts:192-196). subscribeAll has no equivalent: if closed flips while restoring is pending and the restore then rejects, the catch at line 271 rethrows and the dispatcher emits an error frame to a stream that was already ended. Adding if (closed) return at the top of the catch matches the subscribe behavior and still reports a genuine setup failure.

Technical details
# Suppress a post-release restore error in subscribeAll

## Affected sites
- `src/main/runtime/rpc/methods/session-tabs-inventory.ts:246-252` — the restore now runs after registration, so `closed` can be set during this await
- `src/main/runtime/rpc/methods/session-tabs-inventory.ts:271-274` — the catch rethrows unconditionally
- Contrast: `src/main/runtime/rpc/methods/session-tabs.ts:192-196` — `if (released) return`

## Required outcome
- A restore rejection after the stream was released must not produce an error frame.
- A setup failure before release must still report the error (pinned by the "a failed setup reports only the error" test).

## Suggested approach
- `} catch (error) { if (closed) { return } runtime.cleanupSubscription(subscriptionId); throw error }`

Tab-list subscribes now register when they arrive, so an older phone's
worktree-wide session.tabs.unsubscribe (no request id) could end a same-worktree
subscribe that arrived while the unsubscribe was still resolving the worktree.
Capture the registration version when the unsubscribe is dispatched, as
terminal.unsubscribe already does, and sweep only streams registered by then.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (2)

🟠 Major · Emit end when unsubscribeAll releases setup. · session-tabs.ts:231

src/main/runtime/rpc/methods/session-tabs.ts:231
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Emit end when unsubscribeAll releases setup.

When unsubscribeAll releases subscribeSessionTabsInventory during restoreStructuredTabsIfSupported, cleanup runs before initialized becomes true and emits no end. The streaming dispatcher does not synthesize an end frame. Emit one end for this release phase, while keeping setup-failure cleanup separate. A closed socket cannot receive a wire frame.

🟠 Major · Suppress inventory errors after release. · session-tabs.ts:231

src/main/runtime/rpc/methods/session-tabs.ts:231
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Suppress inventory errors after release.

If restoration rejects after runtime.cleanupSubscription(subscriptionId) sets closed, the catch block still rethrows. The streaming dispatcher then sends an error response for the released subscription. During restoration, initialized is still false, so cleanup does not emit { type: 'end' }.

🐛 Suggested fix
   } catch (error) {
+    if (closed) {
+      return
+    }
     runtime.cleanupSubscription(subscriptionId)
     throw error
   }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 01ef5b6f-b0f1-4abd-ba93-7791300850b9

📥 Commits

Reviewing files that changed from the base of the PR and between d430aeb and 5e3e5d5.

📒 Files selected for processing (7)
  • src/main/runtime/rpc/core.ts
  • src/main/runtime/rpc/dispatcher.ts
  • src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts
  • src/main/runtime/rpc/methods/session-tabs-unsubscribe.test.ts
  • src/main/runtime/rpc/methods/session-tabs.ts
  • src/main/runtime/rpc/rpc-streaming-dispatcher.ts
  • src/main/runtime/runtime-subscription-registry.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.

Comment on lines 212 to +221
@@ -179,17 +217,18 @@ export const SESSION_TAB_METHODS = [
}
runtime.cleanupSubscription(`session.tabs:${connection}:${params.worktree}`)
runtime.cleanupSubscription(`session.tabs:${connection}:${snapshot.worktree}`)
runtime.cleanupSubscriptionsByPrefix(`session.tabs:${connection}:${snapshot.worktree}:`)
// Why: subscribes register on arrival, so spare any that arrived after this unsubscribe.
runtime.cleanupSubscriptionsByPrefix(

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '200,230p' src/main/runtime/rpc/methods/session-tabs.ts
rg -n -C 3 'cleanupSubscriptionIfOwnedByConnection|subscriptionId|unsubscribe' src/main/runtime/rpc/methods/session-tabs-unsubscribe.test.ts src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts src/main/runtime/orca-runtime.ts src/main/runtime/runtime-subscription-registry.ts

Repository: stablyai/orca

Length of output: 27239


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- session-tabs producer and unsubscribe ---'
sed -n '90,135p' src/main/runtime/rpc/methods/session-tabs.ts
sed -n '200,228p' src/main/runtime/rpc/methods/session-tabs.ts
printf '%s\n' '--- dispatcher version capture ---'
sed -n '90,125p' src/main/runtime/rpc/dispatcher.ts
printf '%s\n' '--- runtime registry version-aware APIs ---'
sed -n '1,75p' src/main/runtime/runtime-subscription-registry.ts
printf '%s\n' '--- runtime service exposure ---'
rg -n -C 3 'cleanupIfOwnedByConnection|cleanupSubscriptionsByPrefix|cleanupSubscription\\(' src/main/runtime
printf '%s\n' '--- focused admission tests ---'
sed -n '90,190p' src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts
sed -n '235,285p' src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts
printf '%s\n' '--- unsubscribe tests ---'
sed -n '1,90p' src/main/runtime/rpc/methods/session-tabs-unsubscribe.test.ts

Repository: stablyai/orca

Length of output: 6950


🏁 Script executed:

#!/bin/bash
set -e
rg -n -C 5 'cleanup(IfOwnedByConnection|Subscription|SubscriptionsByPrefix)|register(Owned)?\\(' src/main/runtime/orca-runtime.ts src/main/runtime/runtime-subscription-registry.ts src/main/runtime/rpc/methods/session-tabs.ts
printf '%s\n' '--- same-ID and request-specific tests ---'
rg -n -C 8 'same ID|same id|subscriptionId|request-id unsubscribe|arrives while|during the' src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts src/main/runtime/rpc/methods/session-tabs-unsubscribe.test.ts

Repository: stablyai/orca

Length of output: 294


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- runtime cleanup API declarations and implementations ---'
rg -n -F -C 4 'cleanupSubscription' src/main/runtime
rg -n -F -C 4 'cleanupSubscriptionsByPrefix' src/main/runtime
rg -n -F -C 4 'cleanupIfOwnedByConnection' src/main/runtime
printf '%s\n' '--- request-specific and same-ID tests ---'
rg -n -F -C 10 'request-id unsubscribe' src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts
rg -n -F -C 8 'subscriptionId' src/main/runtime/rpc/methods/session-tabs-unsubscribe.test.ts src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts

Repository: stablyai/orca

Length of output: 45667


Fence request-specific cleanup by the dispatch version.

session.tabs.unsubscribe captures subscriptionRegistrationVersion before awaiting listMobileSessionTabs. A subscription with the same request ID can register after dispatch, but the exact-key runtime.cleanupSubscription call still removes it when the lookup resolves. Use the exposed version-aware method with the original connectionId.

Suggested fix
-        runtime.cleanupSubscription(
-          `session.tabs:${connection}:${snapshot.worktree}:${params.subscriptionId}`
+        runtime.cleanupSubscriptionIfOwnedByConnection(
+          `session.tabs:${connection}:${snapshot.worktree}:${params.subscriptionId}`,
+          connectionId,
+          subscriptionRegistrationVersion
         )
📝 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
if (params.subscriptionId) {
runtime.cleanupSubscriptionIfOwnedByConnection(
`session.tabs:${connection}:${snapshot.worktree}:${params.subscriptionId}`,
connectionId,
subscriptionRegistrationVersion
)
return { unsubscribed: true }
}
runtime.cleanupSubscription(`session.tabs:${connection}:${params.worktree}`)
runtime.cleanupSubscription(`session.tabs:${connection}:${snapshot.worktree}`)
// Why: subscribes register on arrival, so spare any that arrived after this unsubscribe.
runtime.cleanupSubscriptionsByPrefix(

@pullfrog pullfrog 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.

ℹ️ No new issues found in the changes since the last review. The version-fenced worktree-wide unsubscribe is correct and covered by a regression test that fails without it.

Reviewed changes

  • Version-fenced worktree-wide unsubscribe — session.tabs.unsubscribe now receives the registry's subscriptionRegistrationVersion, captured at dispatch, and the no-request-id prefix sweep only ends streams registered at or before that version, so a same-worktree subscribe that arrives (and registers) while the unsubscribe is resolving listMobileSessionTabs is spared.
  • Shared fence predicate — the inlined terminal.unsubscribe check moves into isRegistrationFencedUnsubscribe in core.ts, used by both RpcDispatcher.dispatch and RpcStreamingDispatcher.dispatch so the version is captured synchronously before any await or middleware.
  • cleanupByPrefix accepts throughVersion — the sweep filters entry.version <= throughVersion, matching terminal.unsubscribe's cleanupSubscriptionIfOwnedByConnection fence; the parameter is optional, so existing callers are unaffected.
  • Regression test — a new dispatcher test drives two subscribes plus an old-phone no-request-id unsubscribe against the real RuntimeSubscriptionRegistry; I confirmed it fails (frames(second) gains an end) when the fence is removed.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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

🧹 Nitpick comments (1)
src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts (1)

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

Wait for listing to start before aborting.

session.tabs.subscribe awaits restoreStructuredTabsIfSupported before it calls listMobileSessionTabs. Even when restoration resolves immediately, the await defers the listing call. Wait until the listing mock has been called, then abort while listing.promise remains pending. This exercises the intended cleanup path.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 702b05fc-e967-4a31-a2ad-dce4e61c8c26

📥 Commits

Reviewing files that changed from the base of the PR and between 5e3e5d5 and f9a0218.

📒 Files selected for processing (1)
  • src/main/runtime/rpc/methods/session-tabs-subscribe-admission.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Reviewed and tested. Status: ready for review.

Review. An up-front architecture challenge, a precedent check, readiness checks at the start and the end, and one review round with two independent reviewers, both nits-only. The architecture challenge found one real regression this change introduced, and it was fixed (5e3e5d5). Older phones' worktree-wide tab-list unsubscribe could end a same-worktree re-subscribe that arrived while it was still resolving the worktree. It now spares streams registered after it was dispatched, the same way terminal.unsubscribe does. A test for a request abort during setup was added (f9a0218). The new admission tests fail with the fix reverted (8 of 12).

Testing. Live QA: an iOS simulator paired to an isolated desktop host built from this branch. The phone opened and left the worktree 10 times in quick succession (0.5–0.7 s each). The phone's tab list then reflected a desktop tab being created and closed, and three phone sends each executed. No stuck "Your phone is in control" after leaving; only the usual "left this at phone size" dialog.

Phone tab list after a desktop tab was created:
after-create.png

Three phone sends, each executed:
send2-R45C.png

Desktop after the phone left:
desktop-after-leave.png

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.

1 participant