Skip to content

fix(relay): stale exit-waiter must not kill the rebound terminal stream - #14923

Closed
Haiagari wants to merge 3 commits into
stablyai:mainfrom
Haiagari:fix/terminal-exit-waiter-rebind
Closed

Haiagari wants to merge 3 commits into
stablyai:mainfrom
Haiagari:fix/terminal-exit-waiter-rebind

Conversation

@Haiagari

Copy link
Copy Markdown

Problem

Fullscreen TUIs (nvim, opencode, claude) freeze on Orca Mobile after a reconnect. The serve log shows two terminal.subscribe streams (streamId 1 and 2) for the same terminal, then no further live output.

Root cause

On mobile reconnect, the RPC client re-sends terminal.subscribe, rebinding the composite subscription id `${terminal}:${clientId}` to a newer stream and tearing down the old one (registerSubscriptionCleanup runs the previous cleanup before overwriting).

The old connection's exit-waiter is bound to its own AbortSignal:

void runtime
  .waitForTerminal(params.terminal, { condition: 'exit', signal })
  .then(() => runtime.cleanupSubscription(subscriptionId))
  .catch(() => runtime.cleanupSubscription(subscriptionId))

When the old socket finally dies (detected after the reconnect has already rebound the id), the stale exit-waiter fires cleanupSubscription(id) — which now points at the live replacement stream — closing it. Live output stops forever: the mobile terminal is frozen.

Fix

Guard every exit-waiter to its own cleanup generation. Only tear down when the subscription id still owns the cleanup that waiter registered:

  • OrcaRuntimeService.getSubscriptionCleanup(subscriptionId) exposes the currently-registered cleanup.
  • Each of the three terminal.subscribe branches (binary stream, legacy JSON, lease-only) captures its own cleanup and routes the exit-waiter through cleanupOwnIfCurrent, which no-ops when the id was rebound to a newer stream.

Tests

terminal-subscribe-reconnect-exit-waiter.test.ts reproduces the reconnect sequence (subscribe → reconnect rebind → old connection aborts) and asserts the live stream survives the stale waiter.

Verified: 182 terminal-subscribe/multiplex/presence tests pass; terminal.ts and orca-runtime.ts typecheck clean.

On mobile reconnect the client re-sends terminal.subscribe, rebinding the
composite `terminal:clientId` id to a newer stream and tearing down the old
one. The old connection's exit-waiter (bound to its AbortSignal) then fires
`cleanupSubscription(id)`, which now points at the live replacement stream —
killing it and freezing the mobile terminal output.

Guard every exit-waiter to its own cleanup generation: only tear down when
the id still owns the cleanup it registered.
@coderabbitai

coderabbitai Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 24ec5502-9595-488c-b891-93a1964381c2

📥 Commits

Reviewing files that changed from the base of the PR and between 56da432 and f8fc045.

📒 Files selected for processing (1)
  • src/main/runtime/rpc/terminal-subscribe-reconnect-exit-waiter.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/rpc/terminal-subscribe-reconnect-exit-waiter.test.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

The change adds a public accessor for subscription cleanup callbacks. Terminal subscriptions now register named cleanup callbacks and verify callback ownership before exit-waiters, abort paths, exceptions, and setup failures perform cleanup. Mobile input-lease, legacy JSON, and binary subscriptions retain their existing teardown behavior. Regression tests verify reconnect rebinding and protection against stale cleanup.

Merge Risk: 🟡 Moderate · up to f8fc0

The change prevents stale reconnect cleanup from closing the replacement terminal stream, but the regression test may finish before that cleanup path completes and therefore could pass without proving the live stream survives. Merge readiness remains moderate until the test waits for completion or this bounded risk is explicitly accepted.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, root cause, fix, and tests, but it omits required template sections including Linked Issue, Visual Proof, Review, and Checklist. Add the required Linked Issue, Visual Proof or N/A statement, Review, Checklist, and AI Disclosure sections, and complete the testing checklist.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the stale exit-waiter bug and its effect on rebound terminal streams.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: af5dddc5-f6b9-4fb5-bc0e-cc963369665d

📥 Commits

Reviewing files that changed from the base of the PR and between 516a269 and bd91d95.

📒 Files selected for processing (3)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-subscribe-reconnect-exit-waiter.test.ts

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

A rebind tears down the old cleanup, but a pre-reconnect setup continuation
(error path or abort early-return) can still call cleanupSubscription(id),
which now resolves to the live replacement stream. Route all of them through
cleanupOwnIfCurrent so only the id's current owner tears down.

@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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2ce434fb-b7c5-4d60-b893-89217cc57932

📥 Commits

Reviewing files that changed from the base of the PR and between bd91d95 and 56da432.

📒 Files selected for processing (3)
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-subscribe-buffer.test.ts
  • src/main/runtime/rpc/terminal-subscribe-reconnect-exit-waiter.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/rpc/methods/terminal.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 8 remain after this review.

…test.ts

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks for this — your diagnosis is correct, and the serve-log evidence (two terminal.subscribe, two snapshots, then silence) is what pinned the mechanism. I've opened #14992 building on it, and credited the diagnosis there.

Leaving this open until #14992 actually merges, so the bug isn't left unfixed if mine stalls.

Why a separate PR rather than iterating here:

  1. The invariant moved into the API. Instead of getSubscriptionCleanup() plus a guard re-derived at three call sites, registerOwnedSubscriptionCleanup returns a handle whose releaseIfCurrent() no-ops after a rebind. Same generation-token idea — closure identity — but a future keyed teardown can't reopen the hole.

  2. Six more call sites. Only six of the twelve are exit-waiter settlements. The others are stale async continuations (2981, 2988, 3039, 3045, 3098, 3717) — a handleMobileSubscribe or snapshot resuming after a rebind. A patch guarding only the .then/.catch pairs passes every waiter test while those stay broken; I confirmed that by mutation.

  3. The regression test doesn't reach the affected branch. Both cases here send capabilities: { terminalBinaryStream: 1, mobileInputLeaseOnly: 1 }, and terminal.ts:2939-2940 makes mobileInputLeaseOnly true — so the handler returns from the lease-only branch at 2994. The binary-stream branch carrying the frozen TUI in your own repro is never exercised. Relatedly, the fake's registerSubscriptionCleanup calls existing() directly instead of routing through cleanupSubscription, which is the only reason expect(cleanupSubscription).not.toHaveBeenCalled() passes.

  4. terminal.unsubscribe is an active path to the same freeze. Make-before-break relay migration (stable-logical-rpc-client.ts:246-252) subscribes on the new session first, then disposes the old physical subscription — sending terminal.unsubscribe over the old socket after the id was already rebound. Unguarded, that kills the successor even with the exit-waiters fixed.

Two smaller things worth knowing: runtime.getSubscriptionCleanup(...) is called without optional chaining, so any stub-based suite lacking it throws once a cleanup path fires (this PR patches terminal-subscribe-buffer.test.ts for exactly that; others were latent). And CI never ran here — both workflows are sitting at action_required, so nothing was verified outside your machine.

One thing I'd have missed without your write-up: that the rebind is what makes the stale waiter dangerous, rather than the waiter leaking. That framing is what made the fix obvious.

@Haiagari Haiagari closed this by deleting the head repository Aug 17, 2026
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