Skip to content

fix(mobile): keep terminal input working when reopening worktrees - #22505

Merged
brennanb2025 merged 1 commit into
stablyai:mainfrom
shaharmor:fix/mobile-terminal-unsubscribe-generation
Sep 25, 2026
Merged

brennanb2025 merged 1 commit into
stablyai:mainfrom
shaharmor:fix/mobile-terminal-unsubscribe-generation

Conversation

@shaharmor

Copy link
Copy Markdown
Contributor

ELI5

Returning to a worktree on mobile could leave both Live typing and the regular Send button unusable until you tapped the terminal tab. This prevents an older terminal disconnect request from closing the subscription that just replaced it.

What Changed

The host captures the current subscription version before request processing can pause. An unsubscribe cannot remove a subscription registered after that point, even when both use the same connection. Cleanup completion and retries also stay attached to their own registration, including when a callback is reused.

Why

A live trace from mobile 0.0.51 connected to the macOS host established the actual failure:

Order Observed event
1 An unsubscribe request arrived for the old subscription.
2 A replacement subscription registered before the unsubscribe handler ran.
3 The delayed handler removed the replacement because its connection still matched.
4 Fourteen sends, including a buffered send, failed with mobile_input_floor_unavailable.
5 Tapping the tab opened a fresh subscription; buffered sending and Live typing succeeded.

Fixing ownership on the host addresses the cause rather than adding another focus workaround or delaying mobile sends. The request format is unchanged, so this does not require a coordinated mobile update.

Linked Issue

Reported directly; no issue number was supplied.

Related: #16239

Visual Proof

No screenshots or video were captured. The user reproduced the failure and header-tap recovery while temporary, non-pausing host logpoints recorded anonymous subscription metadata. The capture recorded no terminal text or credentials, and the debugger was closed afterward. This is evidence of the original failure, not a claim of fixed-build phone validation; that remains outstanding.

Testing

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • The initial regression failed for both normal terminal and lease-only subscriptions before the fix.

  • Focused Vitest selection: 15 files passed, 78 tests passed on macOS using the cached repository dependency versions.

  • The regression exercises the real subscription registry across unary/streaming dispatch and both current and legacy unsubscribe IDs. Other cases cover malformed requests, missing targets, different connections, unrelated registrations, and reused cleanup callbacks.

  • Focused registry typecheck, formatting, git diff --check, and the max-lines ratchet passed.

  • Code quality, casting, focused plugins, type-aware lint, and React Doctor scans reported zero new findings.

  • Full node typecheck and broader runtime/mobile integration suites were blocked by the incomplete local dependency install, including Electron, @streamparser/json, and tldts. The complete changed-code gate was blocked by the missing @shadcn/lint plugin. Full build and fixed-build phone validation were not run.

Core regression command after installing dependencies:

pnpm test src/main/runtime/rpc/terminal-subscribe-ownership.test.ts src/main/runtime/runtime-subscription-registry.test.ts

AI Disclosure

GPT-6 Astra through the Pi coding-agent harness assisted with diagnosis, implementation, tests, and manual diff review. The user performed the live phone reproduction.

Review

Manually reviewed request ordering, connection ownership, cleanup/retry lifetime, and old-client compatibility. The fix adds no new wire fields or client-controlled authority. Independent model review was not run.

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 version check is host-local and constant-time. No OS-specific behavior or SSH execution routing changes; folder workspaces and git worktrees use the same path. Linux, Windows, and SSH were considered but not exercised locally. The running installed app was not patched or replaced.

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)

Capture the subscription registration version before RPC dispatch yields so an older unsubscribe cannot retire a replacement on the same connection. Bind cleanup completion and retries to their registration, including when callback functions are reused.

Cover the live-trace ordering across unary and streaming dispatch, binary and lease-only subscriptions, and legacy unsubscribe IDs.

@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 PR fences a delayed terminal.unsubscribe so it cannot retire a subscription registered after the request was admitted, fixing the mobile case where returning to a worktree left Live typing and Send dead until the terminal tab was tapped.

  • Registry entries carry a monotonic version — RuntimeSubscriptionRegistry.cleanups now stores { cleanup, version }, getRegistrationVersion() is exposed on the command surface, and ownership (registerOwned/cleanupOwned, in-flight joins) is keyed by entry identity instead of the cleanup function reference.
  • Version captured at admission — both RpcDispatcher.dispatch and RpcStreamingDispatcher.dispatch snapshot subscriptionRegistrationVersion for terminal.unsubscribe before any middleware/handler await, plumbed through RpcContext.
  • Fence in cleanup — cleanupIfOwnedByConnection(id, connectionId?, throughVersion?) returns false when the current entry's version is newer than throughVersion; the connection check is now connectionId && …, preserving the unconditional-teardown path for falsy connectionId.
  • retryAfter pinned to its registration — no longer retries a replacement that reused the same callback.
  • Tests — new runtime-subscription-registry.test.ts, plus a race regression and a malformed-params test in terminal-subscribe-ownership.test.ts; the shared test double mirrors the production changes.

I verified the fence direction and admission points against both dispatchers, traced the reused-callback and retry paths through the existing mobile-creation-and-orchestration.spec.ts cases, and ran the two focused test files (27 tests passing). The regression test fails without the fix: the delayed handler would otherwise clean the replacement and report unsubscribed: true. The request format and wire contract are unchanged, so no coordinated mobile release is needed.

ℹ️ Fixed-build phone validation is still outstanding

The failure and the header-tap recovery were established from host logpoints, and the fix is covered by unit tests, but the author notes the fixed build has not yet been exercised on a phone. That is the one remaining end-to-end check for a user-facing mobile regression; nothing in the diff blocks it.

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

@coderabbitai

coderabbitai Bot commented Sep 23, 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: b0f96bf3-b2e2-4a62-8118-8b0dcefc03bd

📥 Commits

Reviewing files that changed from the base of the PR and between dac82f6 and 808b8f0.

📒 Files selected for processing (9)
  • src/main/runtime/rpc/core.ts
  • src/main/runtime/rpc/dispatcher.ts
  • src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts
  • src/main/runtime/rpc/rpc-streaming-dispatcher.ts
  • src/main/runtime/rpc/subscription-registry-test-double.ts
  • src/main/runtime/rpc/terminal-subscribe-ownership.test.ts
  • src/main/runtime/runtime-service-command-surface.ts
  • src/main/runtime/runtime-subscription-registry.test.ts
  • src/main/runtime/runtime-subscription-registry.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

The subscription registry now assigns a version to each registration and uses it to guard cleanup, ownership release, and retry behavior. Unary and streaming RPC dispatch capture the current registration version for terminal.unsubscribe and pass it to the handler. The handler supplies that version to subscription cleanup. Tests cover registry replacement and retry cases, unsubscribe behavior during replacement, and rejection of malformed parameters.

Merge Risk: ⚪ Minimal · up to 808b8

No identified issue blocks this change from merging after normal checks.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the user impact, root cause, implementation, tests, limitations, and compatibility considerations. However, the required linked issue is not provided in the expected Fixes for… Add the issue reference using the repository's required Fixes # format. Attach before-and-after screenshots or a video showing the interaction change. Also document CI coverage or update the checklist after the required validation completes…
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 3 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: keeping terminal input working when reopening worktrees on mobile.
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.
Full details: Description check

Explanation

The description explains the user impact, root cause, implementation, tests, limitations, and compatibility considerations. However, the required linked issue is not provided in the expected Fixes format, and the required visual proof for this interaction change is missing.

Resolution

Add the issue reference using the repository's required Fixes # format. Attach before-and-after screenshots or a video showing the interaction change. Also document CI coverage or update the checklist after the required validation completes if local checks remain blocked by dependencies or plugins.

  • Fix all pre-merge checks with AI

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.

@shaharmor

Copy link
Copy Markdown
Contributor Author

Thanks for checking the PR. A few clarifications on the metadata and documentation requests:

Add the issue reference using the repository's required Fixes # format.

This bug was reported directly, without a GitHub issue number. #16239 is the related earlier PR, not an issue this change should close. I’ve kept the neutral Related: reference rather than adding an inaccurate closing reference.

Write docstrings for the functions missing them to satisfy the coverage threshold.

I’m following the repository’s concise, non-obvious-comments policy. The important requirement—capturing the subscription version before dispatch can yield—is already documented at the dispatch site and in RpcContext. I haven’t added boilerplate docstrings solely to meet a coverage percentage.

Also document CI coverage or update the checklist after the required validation completes if local checks remain blocked by dependencies or plugins.

The Testing section already records the 78 passing focused tests and the local dependency blockers, and the full-validation checkboxes remain unchecked. The current PR Checks, Mobile Checks, Computer-use e2e, and PR test LoC runs all show action_required. The successful tracking/review checks do not establish that the full lint, typecheck, test, or build checks passed, so I have not marked those complete.

@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks @shaharmor. I reviewed and tested this, and it's good to go as-is. I didn't need to push any changes.

Review

  • The root cause is confirmed. When the phone reopens a terminal, it sends terminal.unsubscribe for the old stream and then terminal.subscribe for the new one, both with the same <terminal>:<clientId> id. The unsubscribe passes through async dispatcher middleware before its handler runs, but the subscribe registers straight away, so the late unsubscribe removed the replacement. Snapshotting the registration version before any await, and refusing to retire newer entries, removes that ordering hazard at its source. Nothing sent between phone and host changes, so phones already in the field get the fix.
  • Several independent review rounds found no correctness, regression, or performance issues. The dispatcher and registry tests fail with the fence disabled and pass with it. The wider runtime suite passes, and typecheck and lint are clean.

Testing: I paired an iOS simulator with a host built from this branch and ran 13 leave-and-return cycles: going back, switching worktrees, and relaunching the app. In each cycle I sent a line with Send and a line with Live typing right after returning, without tapping the terminal tab. Every line reached the desktop terminal, and no send errors appeared. The simulator's fast local connection never hit the race even with the fix reverted, so the proof of the fix itself comes from your device trace plus the tests. The simulator runs show no regressions.

Send works right after going back to the worktree and returning:

after-return-back-send-button-succeeds.png

Send and Live typing across the final return cycles:

final-after-restore-return-send-and-live-succeed.png

Possible follow-ups, not blocking and not caused by this PR:

  • An unsubscribe that arrives while its subscribe is still waiting for the terminal process to start can leave the late subscription running until the socket closes.
  • session.tabs.unsubscribe from older clients has the same kind of ordering race.
  • Terminal subscriptions are still identified by (terminal, client). Longer term, the host could assign each subscription its own id that clients unsubscribe by, so an unsubscribe can only ever name its own registration. That needs a negotiated phone/host change, and this host-side fix would still be needed for older phones.

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.

2 participants