Skip to content

fix(runtime): register phone terminal subscriptions when the request arrives - #22948

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/terminal-subscribe-register-at-admission
Sep 27, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/terminal-subscribe-register-at-admission

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​571 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​567
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​336 $\color{#cf222e}{\Huge{\mathbf{−}}}$​303 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​33

ELI5

When you open a terminal on your phone, the desktop sometimes has to wait a moment for that terminal to start. If you left the terminal during that wait, the desktop never heard that you left. Once the terminal started, the desktop acted as if the phone was still in control: it showed the "phone in control" banner and ignored your desktop typing until you pressed Take back. Now the desktop writes the phone's request down the moment it arrives, so leaving during the wait cancels it.

What Changed

Before: a phone's terminal stream was only written into the host's list of open streams after the terminal's process was ready, which can take up to 10 seconds for a tab that has not started yet. A "stop streaming" message that arrived during that wait found nothing to stop. When the process came up, the stream started anyway: the desktop switched to phone control (banner shown, desktop keystrokes and terminal query replies dropped), output streamed to a phone that was no longer listening, and the automatic size restore never ran. It stayed that way until the phone disconnected, re-opened the same terminal, the process exited, or the user pressed Take back. The same gap caused a second bug after a host restart: the phone replays its streams, then closes and re-opens one, and the stale replayed request could start late and knock out the fresh one.

After: every terminal.subscribe is entered in the host's stream list before it waits for anything, under the same key as before (terminal plus phone id). A stop message or a newer request for the same terminal from the same phone can now end a request that is still waiting, alongside a closed connection or a desktop IPC abort, which already cancelled the wait. When it ends, it sends one end, and its late process never starts the stream.

The mechanism is a new registration object (terminal-subscription-registration.ts) that owns everything the stream has to undo, so every way of ending it goes through one idempotent release:

  • A request-abort listener is installed when the request arrives, and it is removed on release, because desktop IPC signals outlive the request. A request whose signal is already aborted (a connection that already closed) is released on arrival without entering the stream list, so it cannot knock out the live stream for the same terminal.
  • It watches for the process exiting, which is now set up once in the handler instead of in each of the three stream variants.
  • Phone presence is recorded immediately before the phone subscribe call, which sets the phone driver before it awaits the resize. A release at any point after that removes the presence; a release before it adds none.
  • Release runs the stream's teardown, then removes phone presence in its own finally, then aborts the registration's signal in an outer finally. A failing teardown can therefore neither leave the phone in control nor leave the pty wait running.
  • The handler re-checks the registration after every await. If the request fails after something already ended the stream, the error is dropped, so an end is never followed by an error. If it fails before that, the stream is released without an end and the error is reported as before.
  • A terminal whose process never appears still gets its scrollback preview (subscribed with no stream id) followed by exactly one end.

One deliberate behavior change: the "binary stream required" check for phones now runs before the request is entered, so a request that can never stream cannot knock out a live stream for the same terminal. As a result, a phone build that predates binary terminal streaming, opening a terminal whose process never started, now gets the binary_terminal_stream_required error instead of a scrollback preview and end. Those builds already got that error for every running terminal, so they cannot use terminal streaming either way.

Why

The bug happens because a waiting request is not addressable: nothing about it is recorded until setup finishes. Entering it at admission removes the window instead of guarding it. The existing "one live stream per terminal per phone" replacement rule and the #22505 ordering check apply to waiting requests unchanged.

Alternatives considered:

  • A guard after the wait that checks whether the phone had asked to stop. That adds a second mechanism beside the stream list, and a same-terminal replacement still could not reach the request while it waits.
  • Having the host assign an id and send it to the phone in a new early frame. That id goes stale when the phone replays its streams after a reconnect, resets when the host restarts, and a new frame needs capability negotiation with older phones.
  • Cancelling through the per-connection dispatch abort controllers. Those end when dispatch settles, and many streaming handlers return right after setup, so this would only work for handlers that stay open.

This change is host-only and changes nothing on the wire, so every phone version gets the fix. A follow-up can let newer phones stop a stream by the request that created it rather than by terminal key; the registration introduced here is the thing that follow-up will address.

Linked Issue

Fixes #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-level tests (src/main/runtime/rpc/terminal-subscribe-admission.test.ts), using a pty wait that honors its abort signal the way the runtime does:

  • Stop while the process is still starting, then the process comes up: no stream entry, no phone subscribe, one end. The same flow on the real runtime service (only handle lookup, the pty wait, the scrollback read, tab mounting and the pty controller are doubled) leaves the desktop driver idle and no phone-fit size override. Both fail on main: the first leaves the stream entered, the second leaves the driver mobile.
  • A waiting request replaced by a newer one for the same terminal: the old one gets one end and never subscribes the phone. Fails on main: the phone subscribe runs twice.
  • The phone leaves while the phone-fit resize is in flight (real runtime): the driver ends idle. Passes on main, where the stream was already entered by then; it fails if presence is recorded after the resize instead of before.
  • A request abort while waiting: no entry and nothing set up after the process arrives. Main already cancels the wait with the request signal, so only the end differs there; it fails if the abort listener is not installed at admission.
  • The stream is stopped, then the phone subscribe call rejects: only end is sent, no error. Fails on main, which sends end and then an error.
  • A failure before anything ended the stream: the error only, no end, and phone presence removed.
  • Existing behavior, pinned: a terminal whose process never starts gets a preview then one end; the desktop IPC signal is released and its listener removed.
  • The deliberate behavior change: an older phone without binary streaming gets the new error for a terminal whose process never started, and leaves the live stream alone. Fails on main, which sends a preview.

Unit tests for the registration object (terminal-subscription-registration.test.ts): teardown runs once when it re-enters release, a teardown set after release runs immediately, an already-aborted request is released without taking the stream's slot, a throwing teardown still removes presence and aborts, no presence is added after release, silent release, and process-exit release.

Updated tests: the shared terminal test stubs now provide the stream registry, because every request now registers; one ownership test now asserts that the abort listener is removed instead of never added; a desktop pty wait now receives the registration's signal; and a request aborted while waiting now ends with end.

Checks run locally: pnpm tc:node, oxlint on the changed files, pnpm run check:code-quality:changed, the terminal RPC test files (56 files, 360 tests), and src/main/runtime/orca-runtime.test.ts (1307 tests).

AI Disclosure

Review

  • Security: no new inputs, methods or permissions; a request that fails validation can no longer end another stream.
  • Cross-platform: host-side TypeScript only, with no platform-specific behavior.
  • Remote SSH: the change lives in the runtime that serves the phone, so local and SSH-hosted terminals behave the same; process-exit handling still uses the existing live / unverifiable / exited verdicts.
  • Mobile: no phone code changes; every phone version gets the fix. The only visible difference is that a phone build predating binary streaming gets an error, instead of a preview, for a terminal whose process never started.
  • Backwards compatibility (mixed phone/host versions): no new messages or fields. Frame sequences change in three cases: a request cancelled while waiting now receives one end; a stream that was ended and then fails setup gets only end, no error; and a phone build predating binary streaming gets an error instead of a preview for a terminal whose process never started. Current phones already drop an end for a stream they stopped. Because the request is entered on arrival, a newer request for the same terminal from the same phone now ends the older stream when it arrives rather than once its process is ready, and a request with no phone id (keyed by terminal alone) does the same for a terminal whose process never started.
  • Performance: one extra abort controller and one abort listener per terminal subscribe, both released with the stream.

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

The registration records the connection id, because the stream list already uses it to clean up when a connection closes. It does not record the request id yet: nothing in this change would read it, and the follow-up that lets phones stop a stream by request id adds it along with its lookup.

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 25, 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: 77baea5b-4f39-4d34-a705-ed35420cabde

📥 Commits

Reviewing files that changed from the base of the PR and between 018ce01 and 70222ed.

📒 Files selected for processing (2)
  • src/main/runtime/rpc/methods/terminal/terminal-subscription-registration.test.ts
  • src/main/runtime/rpc/methods/terminal/terminal-subscription-registration.ts

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


📝 Walkthrough

Walkthrough

Terminal subscriptions are now registered before PTY waits. A shared registration manages request cancellation, PTY-exit release, teardown, and mobile presence. The legacy lease, JSON, and binary runners use this registration for lifecycle handling. New and updated tests cover registration cleanup, pending waits, aborts, replacement, and failure cases.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 70222

The examined cancellation and phone-presence paths do not leave a stale subscription or phone control. No identified issue blocks merging after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 70222

The new lifecycle appears to close the gap where a phone could leave while its terminal was starting yet remain in control afterward. No new terminal access path or weakened control was identified. Some surrounding authorization and failure behavior remains outside the reviewed source.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — A lifecycle error here could affect the desktop terminal’s mobile-control and output-stream state for a subscribing client. The reviewed change is within the desktop runtime; no changed cross-service dependency edge was identified.

Trust Boundaries and Controls

  • inferred — The registration manages stream lifetime rather than directly reading or writing a PTY. Terminal resolution remains in its caller, and owned-registry release is intended to prevent a stale registration from releasing its replacement; transport-level authorization was not independently verified.

Resilience and Maintainability Implications

  • observed — Mobile presence is recorded before asynchronous subscribe setup, allowing a release during that setup to invoke mobile unsubscribe; the internal behavior if those mobile-presence operations fail was not established by the hydrated source.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 13 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 The PR satisfies the relevant coding objective in [#22928]. terminal.subscribe creates a registration before the PTY wait. The registration handles unsubscribe, same-slot replacement, request abort,…
Out of Scope Changes check ✅ Passed The changes stay within the terminal subscription lifecycle scope of [#22928]. The registration object, runner updates, teardown behavior, and automated tests directly support admission-time registrat…
Title check ✅ Passed The title clearly and concisely describes the main change: registering phone terminal subscriptions when requests arrive.
Description check ✅ Passed The description is comprehensive and covers the required explanation, motivation, linked issue, implementation, compatibility considerations, and testing. Visual proof remains pending, and the full re…
  • 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.

@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 — this run reviewed the complete diff (13 files, one commit 018ce01) against main.

  • Admission-time registration — every terminal.subscribe now enters the host subscription registry before the PTY wait, through a new TerminalSubscriptionRegistration object that owns teardown, phone presence, the PTY-exit observer, and the request-abort listener.
  • Handler re-checks — terminal-subscribe-method.ts re-checks registration.released after each await, routes registration.signal into the PTY wait and the runners, suppresses an error frame once something already ended the stream, and releases in finally.
  • Runners refactored — the legacy lease, JSON, and binary runners move to setTeardown/addMobilePresence; phone-presence teardown is centralized in the registration, so the binary teardown no longer unsubscribes mobile.
  • Deliberate behavior changes — the mobile binary_terminal_stream_required check now runs before admission, and a request released while pending receives exactly one end.

I traced the two riskiest properties directly and with two independent falsification passes: (1) no interleaving of replacement cleanup, request abort, PTY exit, connection cleanup, or runner error produces two end frames or an error-after-end (the released/ended latches plus the registry wrapper's finally { end() } cover it; the only no-end release is the intentional releaseSilently + rethrow); (2) no reachable path leaves the driver mobile after release, because the subscriber record is inserted synchronously before the first enqueueLayout await and replacement cleanup runs before the new registration records presence. The terminal.unsubscribe version fence is unaffected by the earlier registration bump. The added tests pin exact frame sequences and real-runtime driver state, so they can genuinely fail on the pre-fix behavior.

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

@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 — incremental delta since the prior pullfrog review (018ce01 → 70222ed, one commit, two files).

  • Already-aborted requests skip the slot — terminal-subscription-registration.ts now sets registryEntry = null when requestSignal?.aborted, so it never calls registerOwnedSubscriptionCleanup (which would evict a live stream under the same key) and instead calls releaseOnce() directly.
  • No end on arrival — the pre-aborted registration releases without emitting end, matching the handler's existing early return for an aborted signal.
  • release made optional — release() is now registryEntry?.releaseIfCurrent(), a no-op in the pre-aborted path where releaseOnce() already ran.
  • Regression test strengthened — the unit test now seeds a live entry in a shared registry and asserts it survives (and can still be cleaned up), which fails on the parent commit where register evicts it.

I traced the new branch: with registryEntry === null, releaseOnce() flips the released latch, aborts the controller, and leaves teardown/presence untouched, so a later setTeardown still runs immediately and addMobilePresence/releaseOnPtyExit stay inert. Ran the unit file locally: 7/7 pass.

One observation, no action needed: the new guard is not reachable through its only caller — terminal-subscribe-method.ts:28 already returns for signal?.aborted before registration, with no await between that check and the call. So this commit hardens the object's exported contract rather than changing production behavior (the tests exercise it directly). Keeping it as defense-in-depth is reasonable.

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.

Review. An up-front architecture challenge, a precedent check, readiness checks at the start and the end, and two review rounds with two independent reviewers each. Both rounds came back nits-only. One fix was pushed during review (70222ed): a subscribe that arrived after its connection had already closed could end the live stream for the same terminal before releasing itself. It is now released on arrival without taking that stream's place. The full runtime RPC suite passes on this branch and on its base.

Testing. The fix is proven by a deterministic test on the real runtime service: a phone subscribe that is still waiting for its terminal, followed by an unsubscribe, leaves the desktop driver idle. On main it stays mobile ("Your phone is in control"). Live QA: an iOS simulator paired to an isolated desktop host built from this branch, with the phone app on main. The race window is sub-second, and the emulator's taps take at least 2 s, so live attempts can't hit it on either build (8 attempts each on main and on this branch, with no stuck banner on either). What the live run does show is no regression: after every leave, desktop typing executes and the control banner is absent. Phone Live input sends kept executing on this host.

Desktop after the phone left (typed echo R2P8 ran, no control banner):
pr-attempt-8-desktop.png

Phone sends on this host:
live-5.png

Stacked follow-up: #23006 (unsubscribe by request id), then #23058.

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.

Mobile: leaving a still-starting terminal can leave the desktop stuck in "Your phone is in control"

1 participant