Repository navigation
fix(runtime): let the phone end a terminal stream by the request that opened it - #23006
Conversation
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — the host's terminal stream registry now indexes each terminal.subscribe registration by (connectionId, requestId), and terminal.unsubscribe{requestId} releases exactly that registration, with a slot-based fallback for phones that predate the field. I read the full 17-file diff and ran the host registry/admission/buffer tests (52 passed), the two mobile transport suites (26 passed), pnpm tc:node, and oxlint on the changed sources.
- Registry request index (
src/main/runtime/runtime-subscription-registry.ts) —subscriptionsByRequestmaps(connectionId, requestId)to{subscriptionId, version};releaseByRequestre-checks the version before tearing down andremoveRequestIndexcompare-deletes, so a reused or superseded request id can never release a newer live stream. A failed teardown keeps both the entry and its address so a retry still reaches it. - Host unsubscribe branch (
terminal-viewport-methods.ts:86) — a definedrequestIdgoes only throughreleaseSubscriptionByRequestand never falls back to the slot;requestIdis threaded fromterminal-subscribe-method.tsintoregisterTerminalSubscriptionat admission, before the pty wait. - Mobile transports (
rpc-client-stream-registry.ts:214,mobile-relay-rpc-streams.ts:197,227) — both sendrequestIdequal to the subscribe frame id; the relay attaches it after the slot-only sibling check so an older host still sees the unchanged slot. - Wire compatibility (
terminal-viewport-schemas-params.ts:34) —requestIdis optional on a non-strictz.object, so older hosts drop it and older phones keep the slot path. No new method, frame, or capability.
ℹ️ The request-address index is generic, but only terminal subscriptions populate it
releaseSubscriptionByRequest resolves any address in subscriptionsByRequest, yet only registerTerminalSubscription currently passes a requestId to registerOwnedSubscriptionCleanup; structured-agent-session-hold.ts and structured-agent-session-status-stream.ts pass only a connectionId. That is fine for this change — a terminal.unsubscribe{requestId} can today only name a terminal stream, which is the intent — but the method is named and exposed generically, so a future non-terminal handler that forwards ctx.requestId would silently become addressable through terminal.unsubscribe.
Technical details
# Request index is populated by one caller
## Affected sites
- `src/main/runtime/runtime-subscription-registry.ts:79` — `releaseByRequest` looks up `(connectionId, requestId)` with no method/slot constraint.
- `src/main/runtime/rpc/methods/terminal/terminal-subscription-registration.ts:84` — the only 4-arg `registerOwnedSubscriptionCleanup` call (terminal).
- `src/main/runtime/rpc/methods/structured-agent-session-hold.ts:39` and `structured-agent-session-status-stream.ts:27` — pass only `connectionId`, so they never enter the index.
## Required outcome
- None now. If a non-terminal handler ever forwards `ctx.requestId`, decide whether the address should be method-scoped or whether `terminal.unsubscribe` should be renamed to a generic cancel surface.
## Open questions for the human
- Is `releaseSubscriptionByRequest` intended to become a generic per-request cancel, or is it deliberately terminal-scoped and the generic name is incidental?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Reviewed and tested. Status: ready for review, after #22948 and #22939 (see the Merge note in the description). 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 (clean / nits-only). One comment fix was pushed (76a46ea). All four phone/desktop version pairings were analysed: older desktops ignore Testing. Live QA: an iOS simulator paired to an isolated desktop host, with both the host and the phone app built from this branch. 5 normal open / send / leave / return cycles and 10 fast leave/return cycles on a running terminal each executed the phone's command, and the desktop never showed "Your phone is in control". Eight leave attempts on a still-starting terminal left no stuck banner, and desktop typing executed afterwards. New Tab → Terminal works. The emulator can't leave in under 1 s, so the sub-second race itself is covered by the deterministic tests, which fail when the request address is removed. Phone: 10 fast leave/return cycles, each send executed: |
…-unsubscribe-by-request # Conflicts: # src/main/runtime/rpc/methods/terminal/terminal-subscribe-method.ts # src/main/runtime/rpc/methods/terminal/terminal-subscription-registration.test.ts # src/main/runtime/rpc/methods/terminal/terminal-subscription-registration.ts # src/main/runtime/rpc/terminal-subscribe-admission.test.ts
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — re-reviewed the delta since the prior pullfrog review: a single merge commit that rebases this branch onto main.
- Merged
origin/maininto the branch — the base moves from the stackedterminal-subscribe-register-at-admissionbranch tomain; the host feature now relies on #22948 being inmain, which it is. - Resolved the 4 conflicted files —
terminal-subscribe-method.ts,terminal-subscription-registration.tsand its test, andterminal-subscribe-admission.test.ts. The resolution keeps main's registration-object refactor (lifecycle insideregisterTerminalSubscription,args.registration, nowatchSubscriptionLifetimein the legacy runners) and re-threads the subscriberequestIdthrough it. - Retained the request-address index, host unsubscribe branch, mobile transports, and wire schema unchanged — behavior is identical to the previously approved feature.
- Updated the relay sibling-check test — the
#22939expectation now includesrequestId, matching the slot-firsthasLiveOwnercheck in the merged relay code.
Verification: git diff 9795563(main)..5f8ba58 restricted to the four conflicted files shows only the requestId additions, and no conflict markers remain anywhere. Host registry/admission/buffer tests (52) and mobile transport suites (26) pass; pnpm tc:node is clean.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (2)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughTerminal unsubscribe requests can now identify the original terminal subscribe request. Mobile clients include that ID when cancelling a terminal stream. The runtime associates request IDs with subscription registrations and releases the matching registration when an addressed unsubscribe arrives. Unsubscribes without a request ID continue to use slot-based cleanup. Tests cover replacement streams, pending subscriptions, reconnect replay, and registry cleanup. Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to Terminal cancellation now identifies the originating subscribe request while retaining legacy cleanup behavior. No unresolved merge-blocking risk is established. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to On updated clients and desktops, a terminal stop request is limited to the subscription opened by the named request on that connection. No new cross-connection access path was identified. Older desktops retain the earlier slot-based behavior, and deployment coverage remains uncertain. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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 |
…-unsubscribe-by-request # Conflicts: # src/main/runtime/rpc/dispatcher.ts
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — re-reviewed the delta since the prior pullfrog review: a single merge commit that folds origin/main (now at bc7a17fe, including #23045) back into this branch.
- Merged
origin/maininto the branch — the merge's first parent is the previously reviewed5f8ba58, and its second parent isbc7a17fe(#23045, "register phone tab-list streams when the request arrives"). - Adopted
#23045's shared unsubscribe-fence helper — the conflict at the twosubscriptionRegistrationVersionsites (dispatcher.ts:114,rpc-streaming-dispatcher.ts:95) now callsisRegistrationFencedUnsubscribe(request.method)(core.ts:235) instead of the branch's terminal-only condition. That keeps the branch'sCOMPAT(terminal request-addressed unsubscribe)comment while preserving main's fence forsession.tabs.unsubscribe; resolving the other way would have silently dropped it. - No other PR-own changes — the range-diff
5f8ba58..268be0bshows only those two hunks; the request-address index, the host unsubscribe branch, the mobile transports, and the wire schema are unchanged from the previously approved feature.
Verification: host registry/admission/buffer tests (52), session-tabs admission/unsubscribe plus streaming tests (26), and the two mobile transport suites (35) pass; pnpm tc:node is clean; no conflict markers remain.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏




ELI5
When you leave a terminal on your phone, the phone tells the desktop "stop streaming terminal X to me". But the phone may have opened terminal X more than once in quick succession (for example when moving between screens), and the desktop could not tell which opening the "stop" was about. A late "stop" for an old opening could end the new one, leaving your phone terminal frozen until you reopened it. Now the phone says "stop the stream I opened with request 42", and the desktop ends exactly that one.
What Changed
Before:
terminal.unsubscribenamed the stream by its slot, which is the terminal plus the phone's id. That slot is the same for every time the phone opens that terminal. If the phone opened a new stream for the slot and then closed the old one, and the old one's stop message reached the desktop after the new stream had registered, the desktop ended the new stream. The phone terminal then stopped updating until it was reopened. The same mix-up let a stop message sent after the desktop had already ended a stream end a newer stream for the same slot.After: the phone adds
requestIdtoterminal.unsubscribe, set to the id of theterminal.subscriberequest that opened the stream. A desktop with this change ends only the stream that request opened. If that request already ended, was replaced, or never registered, the stop does nothing, and it never falls back to the slot. The slot fields are still sent, so a desktop without this change ignores the new field and behaves exactly as today.The mechanism:
releaseByRequestlooks up the registration and releases it through the existing version-checked release, so a request that has since been replaced is a no-op.terminal.unsubscribewithrequestIdgoes only through that path. WithoutrequestIdit takes the unchanged slot path, including the fix(mobile): keep terminal input working when reopening worktrees #22505 ordering check. Both of those are marked as compatibility code for phones that predate this field.requestIdequal to the frame id they sent the subscribe with. On relay, the check that skips an unsubscribe when another stream for the same slot is still open compares the slot only;requestIdis added after that decision. Otherwise the check would never match against a desktop without this change, and it would end the other stream.Why
The bug class exists because the phone ends a stream by naming what it watches rather than the request that created it. Each earlier fix (#14992, #18926, #22505) added a guard around the slot for one ordering. Naming the request removes the ambiguity for every ordering at once.
Alternatives considered:
requestId. Not needed: an older desktop drops the unknown field and uses the slot, which is today's behavior, and the relay sibling check stays slot-based for exactly that case.The registry keeps its "one live stream per terminal per phone" replacement rule. That is what lets a phone that reconnects on a new socket immediately take over from a half-open old socket instead of waiting for the heartbeat to reap it.
Linked Issue
Part of #22928
Builds on #22948 (merged), which registers terminal subscriptions when the request arrives. This PR's host part depends on it; the branch now targets main.
Merge note: land this after #22939, or in the same phone release. Without #22939, a relay phone that closes the newer of two streams for one terminal while the older one's
endis still arriving sends no stop, because the relay sees the older stream as a live sibling. The older stream's own stop then names its already-replaced request and does nothing, so the newer stream keeps the desktop in phone control until the connection closes. On main that stale stop happened to end the newer stream. #22939's directional sibling check sends the right stop in that case.Merge note (tests): once this and #22939 are both on one branch, #22939's relay test that orders same-slot terminal siblings expects the terminal unsubscribe params without
requestId, so it fails as written. Update that expectation to includerequestIdequal to the stream's frame id. The behaviour it pins (the newer sibling suppresses the older one's stop) is unchanged.Both PRs change
sendUnsubscribeand its terminal call incancel()inmobile/src/transport/mobile-relay-rpc-streams.ts, and both add tests at the same spots inmobile-relay-rpc-stream-cancellation.test.tsandrpc-client-stream-registry.test.ts(keep both sides of those). Resolve the relay code by keeping #22939'shasNewerSlotOwner(unsubscribe, sendOrder)check first and addingrequestIdto the params only when building the frame after that check, so the slot comparison never seesrequestId. The signature becomessendUnsubscribe(unsubscribe, sendOrder, terminalRequestId?), the terminal call becomessendUnsubscribe(byParams, stream.sendOrder, id), andStreamUnsubscribe.paramsstaysRecord<string, unknown>.Visual Proof
Pending: live QA runs after the review loop
Testing
Dispatcher-level tests (
src/main/runtime/rpc/terminal-subscribe-admission.test.ts):endis sent. Fails if the registration does not record its request id.requestIdand the slot path ends the stream as today.Registry unit tests (
runtime-subscription-registry.test.ts): release by request; a replaced request is a no-op; no index growth across 50 replace and release cycles; a reused request id (desktop IPC) keeps the newer owner after the old teardown settles; a failed teardown keeps the index entry so a retry works; nothing is indexed without both ids.Phone tests: direct and relay both send
requestIdequal to the subscribe's frame id with the slot fields kept; on relay, a live newer stream for the same slot still suppresses the old stream's unsubscribe.Checks run locally:
pnpm tc:node, mobiletsc --noEmit,oxlinton the changed files,pnpm run check:code-quality:changed, the host RPC tests plusorca-runtime.test.ts(310 files), the mobile transport, web shell, terminal, session and recording tests (512 files), and the cross-version terminal wire suite.AI Disclosure
Review
requestIdonly selects among registrations on the caller's own connection, so a phone cannot end another socket's stream; there is no new method or permission.Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
A newer stream that the desktop rejects during parameter validation can still leave an older stream running on relay, as it can on main today. After #22948 this needs a subscribe that fails schema validation. If it is ever observed, the fix is for the desktop to echo the request on
subscribed.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)