Skip to content

fix(runtime): let the phone end a terminal stream by the request that opened it - #23006

Merged
brennanb2025 merged 6 commits into
mainfrom
brennanb2025/terminal-unsubscribe-by-request
Sep 28, 2026
Merged

brennanb2025 merged 6 commits into
mainfrom
brennanb2025/terminal-unsubscribe-by-request

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​373 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​371
Prod 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​133 $\color{#cf222e}{\Huge{\mathbf{−}}}$​21 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​112

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.unsubscribe named 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 requestId to terminal.unsubscribe, set to the id of the terminal.subscribe request 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:

  • The host's stream registry keeps an index from (connection id, request id) to the registration that request created. The terminal subscription registration (added in fix(runtime): register phone terminal subscriptions when the request arrives #22948 at request arrival) now passes its request id, so a request is addressable from the moment it arrives, including while it still waits for its terminal process.
  • Only a registration with both a connection id and a request id enters the index. Some desktop-local sockets have no connection id, and a bare request id is not unique across sockets.
  • A newer registration with the same address takes the index entry. The desktop IPC path reuses a subscription id as its request id after aborting the previous subscription.
  • Index entries are removed compare-and-delete: only if the index still points at that exact registration. This happens at the two places a registration leaves the registry, when a same-slot registration replaces it and when its own teardown completes. A failed teardown keeps both the registration and its index entry, so a retry still reaches it.
  • releaseByRequest looks 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.unsubscribe with requestId goes only through that path. Without requestId it 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.
  • On the phone, both transports (direct and relay) add requestId equal 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; requestId is 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:

  • Having the desktop assign an id and send it in a new early frame. That id goes stale when the phone replays its streams after a reconnect, resets when the desktop restarts, and a new frame needs capability negotiation with older phones.
  • Cancelling through the per-socket dispatch abort controllers keyed by request id. Those end when dispatch settles, and many streaming handlers return right after setup, so it would only work for some handlers.
  • A generic cancel method for any request. It needs a new allowlisted method, capability probing on the phone, and cancellation support in every handler. The registry lookup added here can back such a method later.
  • Advertising a host capability so the phone knows whether the desktop understands 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 end is 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 include requestId equal to the stream's frame id. The behaviour it pins (the newer sibling suppresses the older one's stop) is unchanged.

Both PRs change sendUnsubscribe and its terminal call in cancel() in mobile/src/transport/mobile-relay-rpc-streams.ts, and both add tests at the same spots in mobile-relay-rpc-stream-cancellation.test.ts and rpc-client-stream-registry.test.ts (keep both sides of those). Resolve the relay code by keeping #22939's hasNewerSlotOwner(unsubscribe, sendOrder) check first and adding requestId to the params only when building the frame after that check, so the slot comparison never sees requestId. The signature becomes sendUnsubscribe(unsubscribe, sendOrder, terminalRequestId?), the terminal call becomes sendUnsubscribe(byParams, stream.sendOrder, id), and StreamUnsubscribe.params stays Record<string, unknown>.

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

Dispatcher-level tests (src/main/runtime/rpc/terminal-subscribe-admission.test.ts):

  • The phone opens a new stream for the slot on the same connection, then the old request's unsubscribe arrives: the new stream keeps running. Fails without this change, where the slot unsubscribe ends the new stream.
  • A subscribe still waiting for its terminal process is ended by its request id (real runtime service): the desktop driver stays idle, no phone-fit size is left behind, and one end is sent. Fails if the registration does not record its request id.
  • An unknown request id, the unsubscribe's own id, and the id of a non-terminal stream on the same connection are all no-ops that leave the live terminal stream running.
  • A socket without a connection id: no-op.
  • A desktop without this change: its schema drops requestId and the slot path ends the stream as today.
  • A subscribe and its unsubscribe dispatched back to back on one connection: the registration always happens first, and nothing is left behind.
  • Half-open socket: the phone replays its subscribe on a new socket, then leaves; the desktop driver goes idle, and the old socket's later close finds nothing of its own.

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 requestId equal 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, mobile tsc --noEmit, oxlint on the changed files, pnpm run check:code-quality:changed, the host RPC tests plus orca-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

  • Security: requestId only 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.
  • Cross-platform: TypeScript on the host and phone only, with no platform-specific behavior.
  • Remote SSH: unaffected; this is the phone-to-desktop runtime channel, and the registry lives on the desktop that owns the terminal.
  • Mobile: both phone transports send the new field; the relay's same-slot sibling check still compares the slot only.
  • Backwards compatibility: new phone with old desktop drops the field and uses the slot as today; old phone with new desktop uses the unchanged slot path and ordering check; no new frame, method or capability.
  • Performance: one map entry per live terminal subscription, removed with it; one lookup per unsubscribe.

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

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

  • 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)

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

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) — subscriptionsByRequest maps (connectionId, requestId) to {subscriptionId, version}; releaseByRequest re-checks the version before tearing down and removeRequestIndex compare-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 defined requestId goes only through releaseSubscriptionByRequest and never falls back to the slot; requestId is threaded from terminal-subscribe-method.ts into registerTerminalSubscription at admission, before the pty wait.
  • Mobile transports (rpc-client-stream-registry.ts:214, mobile-relay-rpc-streams.ts:197,227) — both send requestId equal 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) — requestId is optional on a non-strict z.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?

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

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 requestId, and the relay sibling check never compares it. The one ordering constraint: this PR's phone change must land after #22939 or in the same phone release.

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:
send-R06F10-phone.png

Desktop after a leave (typing executes, no control banner):
attempt-8-desktop.png

New Tab → Terminal on this build:
new-tab-terminal-created.png

…-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
@brennanb2025
brennanb2025 changed the base branch from brennanb2025/terminal-subscribe-register-at-admission to main September 27, 2026 20:11

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

Reviewed changes — re-reviewed the delta since the prior pullfrog review: a single merge commit that rebases this branch onto main.

  • Merged origin/main into the branch — the base moves from the stacked terminal-subscribe-register-at-admission branch to main; the host feature now relies on #22948 being in main, which it is.
  • Resolved the 4 conflicted files — terminal-subscribe-method.ts, terminal-subscription-registration.ts and its test, and terminal-subscribe-admission.test.ts. The resolution keeps main's registration-object refactor (lifecycle inside registerTerminalSubscription, args.registration, no watchSubscriptionLifetime in the legacy runners) and re-threads the subscribe requestId through 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 #22939 expectation now includes requestId, matching the slot-first hasLiveOwner check 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.

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

@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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 configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 104bd887-9c3e-4b49-b4ca-dac4c539ddac

📥 Commits

Reviewing files that changed from the base of the PR and between 5f8ba58 and 268be0b.

📒 Files selected for processing (4)
  • mobile/src/transport/rpc-client-stream-registry.ts
  • src/main/runtime/rpc/dispatcher.ts
  • src/main/runtime/rpc/rpc-streaming-dispatcher.ts
  • src/main/runtime/runtime-subscription-registry.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/runtime/rpc/rpc-streaming-dispatcher.ts
  • src/main/runtime/rpc/dispatcher.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.


📝 Walkthrough

Walkthrough

Terminal 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 268be

Terminal cancellation now identifies the originating subscribe request while retaining legacy cleanup behavior. No unresolved merge-blocking risk is established.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 268be

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
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The new cancellation authority is bounded to registrations indexed on the caller’s connection; the reviewed lookup does not provide a cross-connection terminal release path.

Trust Boundaries and Controls

  • observed — The desktop supplies connectionId from RPC context rather than from unsubscribe parameters; request-addressed release requires that identity and does not fall back to a client-supplied slot.

Resilience and Maintainability Implications

  • observed — The mobile relay checks for a live sibling before sending terminal unsubscribe, including when a desktop would still interpret the message by slot. Runtime cleanup retains an address after failure so the same request can retry.

Hardening Proposals

  • proposed — Document or enforce request-ID uniqueness for the lifetime of a connection if callers beyond the reviewed mobile senders can reuse IDs: the registry intentionally assigns a reused address to its newest registration, so the address alone cannot distinguish two generations.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 17 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main change: allowing phones to end terminal streams by the request that opened them.
Description check ✅ Passed The description is complete and closely follows the required template. It explains the user impact, implementation, rationale, compatibility, testing, review considerations, and linked issues. Visual …
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.
  • 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.

…-unsubscribe-by-request

# Conflicts:
#	src/main/runtime/rpc/dispatcher.ts

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

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/main into the branch — the merge's first parent is the previously reviewed 5f8ba58, and its second parent is bc7a17fe (#23045, "register phone tab-list streams when the request arrives").
  • Adopted #23045's shared unsubscribe-fence helper — the conflict at the two subscriptionRegistrationVersion sites (dispatcher.ts:114, rpc-streaming-dispatcher.ts:95) now calls isRegistrationFencedUnsubscribe(request.method) (core.ts:235) instead of the branch's terminal-only condition. That keeps the branch's COMPAT(terminal request-addressed unsubscribe) comment while preserving main's fence for session.tabs.unsubscribe; resolving the other way would have silently dropped it.
  • No other PR-own changes — the range-diff 5f8ba58..268be0b shows 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.

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

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