Skip to content

fix(mobile): keep a terminal lease alive when the handle lookup fails - #15463

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/lease-survives-stale-handle
Aug 19, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/lease-survives-stale-handle

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​266 $\color{#cf222e}{\Huge{\mathbf{−}}}$​34 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​232
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​114 $\color{#cf222e}{\Huge{\mathbf{−}}}$​17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​97

ELI5

When the phone holds a terminal open, the desktop watches that terminal for "did it exit?". If the desktop momentarily can't look the terminal up — which happens on an ordinary renderer reload — it was treating that as "the terminal died" and telling the phone so. The phone believes it, retries three times, then gives up and locks the message box on "Waiting for terminal…" until you force-quit the app. This makes the desktop require actual proof before declaring a terminal dead.

What Changed

  • All three terminal.subscribe branches wired the exit-waiter's rejection straight to teardown: .catch(() => registration.releaseIfCurrent()).
  • They now go through releaseLeaseOnWaitFailure, which retires only when the socket aborted (this connection is going away) or isLeafPtyProvenAbsent(ptyId) says the process is gone.
  • isLeafPtyProvenAbsent becomes public so the RPC layer can use the runtime's existing proven-absence predicate rather than inventing a second one.
  • A real exit resolves and still retires through the untouched .then leg.

Why

waitForTerminal(handle, { condition: 'exit' }) rejects with terminal_handle_stale whenever getLiveLeafForHandle can't resolve the handle. The loudest source is:

if (record.rendererGraphEpoch !== this.rendererGraphEpoch) throw new Error('terminal_handle_stale')

Every renderer graph reload invalidates handles issued before it — on panes whose PTY is perfectly alive. The old wiring turned that into emit({ type: 'end' }) on a live lease.

Mobile reads end as "PTY gone", rearms, and after MAX_REARM_ATTEMPTS = 3 deliberately stops — "Give up after a few tries and leave the composer honestly locked." Recovery then requires a replacement handle. A live PTY keeps its handle, so no replacement ever arrives and the pane stays dead: spinner, empty transcript, composer reading "Waiting for terminal…", on both the chat and terminal surfaces.

Note condition: 'exit' has no timeout (effectiveTimeoutMs = 0), so slowness alone cannot fire this. Load matters only because it causes the renderer churn that bumps the graph epoch.

This is host-side on purpose: mobile 0.0.44 is in App Store review and can't be patched, and the 3-strikes give-up lives in the shipped client.

Linked Issue

Fixes #

Visual Proof

Reproduced live: shipped 0.0.44 client (built from 64de8dd637) on a paired iOS Simulator over LAN, against an isolated Electron host. The handle lookup was faulted behind a marker file so it could be lifted without restarting.

repro-waiting-for-terminal-locked.png

  • Under fault: 7 × EMIT end for one handle. Composer flipped to "Waiting for terminal…", transcript empty, centre spinner.
  • Fault lifted — PTY fully resolvable, handle unchanged — still LOCKED at t+97s. It does not self-heal.
  • Lock is scoped to the affected handle; sibling terminals stayed usable.
  • Workaround for affected users today: background the app and reopen it. Confirmed to recover.

Testing

src/main/runtime/rpc/terminal-lease-stale-handle-survival.test.ts drives the real dispatcher and TERMINAL_METHODS through a lease-only subscribe:

  1. Stale-handle rejection keeps the lease — no end, no handleMobileUnsubscribe.
  2. Proven-absent retires the lease — same rejection, but the provider says the process is gone, so it still tears down (preserves the fix(runtime): tear down terminal subscriptions only through their owning registration #14992 property).
  3. A real exit still retires — the .then leg is untouched, so a dead pane can't hold the mobile input floor forever.

Case 1 verified RED before the fix, with exactly the reported wire pattern:

AssertionError: expected [ 'subscribed', 'end' ] to not include 'end'

Regression: full src/main/runtime/rpc/ suite — 170 files, 1473 passed, 1 skipped. oxlint clean.

Platforms: macOS, local PTY, LAN mobile transport. Not exercised on Windows/Linux, SSH, or Relay — the change is transport-agnostic and sits in the shared subscribe path.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Claude Opus 4.5 (Claude Code) did the investigation, live repro, fix, and tests.

Review

Please look hardest here: this narrows a behavior #14992 pinned. Its test "tears down the current owner when the terminal handle goes stale" asserted that a stale handle retires the owner. That is now "…when the handle is stale and the PTY is proven absent". The ownership property #14992 cared about is unchanged — once absence is proven, the owning registration is still what retires — but the epistemics changed, and the test was updated rather than deleted. If that trade is wrong, this is the line to push on.

Second-order risk: when a handle is stale and liveness cannot be probed, isLeafPtyProvenAbsent returns false, so the lease is now retained until the socket closes. That is a bounded retention (the connection owns it) traded against a permanent client lock.

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

  • Backwards compatibility: no wire shape, opcode, or field changes — this removes a spurious end frame on an existing path. Fixes already-installed 0.0.44 clients with no new build. Per docs/reference/remote-wire-compatibility.md this is Rule 3 in the safe direction: the host stops sending a frame that misrepresented state.
  • Performance: the guard runs only on the rejection leg, which previously did unconditional teardown. isLeafPtyProvenAbsent is cached/TTL'd and short-circuits on the controller's synchronous inventory.
  • Not related to fix(mobile): push the materialized handle to a pending-handle terminal (STA-4256) #15355. That PR closes a restore-path publication gap; this is the P0.
  • Remote SSH / folder workspaces: shared subscribe path, opaque handle/pty identities. Not separately exercised.
  • Security: no new data crosses the wire.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • 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)
    • oxlint and the src/main/runtime/rpc/ suite pass locally. Full pnpm typecheck / pnpm build left to CI.

Author

  • X / Twitter: @BrennanKB5

`waitForTerminal(..., 'exit')` rejects with `terminal_handle_stale` whenever the
handle cannot be resolved right now. The loudest source is
`record.rendererGraphEpoch !== this.rendererGraphEpoch` — every renderer graph
reload invalidates handles issued before it, on panes whose PTY is untouched.

All three terminal.subscribe branches wired that rejection straight to teardown
(`.catch(() => registration.releaseIfCurrent())`), so the host retired a live
lease and emitted `end`. Mobile reads `end` as "PTY gone" and rearms; after
MAX_REARM_ATTEMPTS = 3 it stops and leaves the composer on "Waiting for
terminal…", recovering only when a replacement handle arrives. A live PTY keeps
its handle, so no replacement ever comes: the pane is dead until the app is
backgrounded and reopened.

Demand proof instead. Retire on abort (this socket is going away) or when
isLeafPtyProvenAbsent says the process is gone; a real exit still resolves and
retires through the .then leg. Absence must be proven, never inferred from a
lookup that failed.

Reproduced live: a paired 0.0.44 client over LAN, fault injected on the handle
lookup, composer locked on "Waiting for terminal…" and STILL locked 97s after
the fault was lifted with the PTY alive and the handle unchanged.

Narrows one behavior #14992 pinned: a stale handle alone no longer retires the
owner. The ownership property is unchanged — once absence is proven, the owning
registration is still what retires. That test is updated, not deleted.
@coderabbitai

coderabbitai Bot commented Aug 19, 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: f4ea068a-0541-48c8-a5fe-18b061a920ff

📥 Commits

Reviewing files that changed from the base of the PR and between f774bd8 and 2a78919.

📒 Files selected for processing (11)
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-multiplex-test-harness.ts
  • src/main/runtime/rpc/terminal-output-batching.test.ts
  • src/main/runtime/rpc/terminal-provider-snapshot-sequence.test.ts
  • src/main/runtime/rpc/terminal-subscribe-blank-mount.test.ts
  • src/main/runtime/rpc/terminal-subscribe-buffer.test.ts
  • src/main/runtime/rpc/terminal-subscribe-mount-replay.test.ts
  • src/main/runtime/rpc/terminal-subscribe-ownership.test.ts
  • src/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.ts
  • src/main/runtime/rpc/terminal-subscribe-renderer-recovery-output.test.ts
  • src/main/runtime/terminal-subscribe-exit-waiter-leak.test.ts

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


📝 Walkthrough

Walkthrough

The runtime now provides subscribeToPtyExit with listener tracking, immediate handling for exited PTYs, race checks, and teardown notifications. Terminal subscriptions use it to release registrations on PTY exit or connection abort across lease-only, legacy JSON, and binary paths. Tests cover listener cleanup, stale-handle survival, already-exited PTYs, and streaming behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly identifies the mobile terminal lease issue addressed by the pull request.
Description check ✅ Passed The description covers the change, rationale, testing, visual proof, risks, and checklist; the linked issue remains unspecified.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

🧹 Nitpick comments (1)
src/main/runtime/rpc/methods/terminal.ts (1)

324-337: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten the new comments and correct the helper description.

The helper comment says cleanup occurs only when the socket closes, but lines 348-352 also release on proven PTY absence. Keep the non-obvious release conditions. Remove the incident narrative.

  • src/main/runtime/rpc/methods/terminal.ts#L324-L337: Replace this block with one concise comment that states both release conditions.
  • src/main/runtime/rpc/terminal-lease-stale-handle-survival.test.ts#L1-L10: Remove the incident narrative. The test name already states the scenario.
  • src/main/runtime/rpc/terminal-subscribe-ownership.test.ts#L111-L114: Reduce this block to one concise statement of the proven-absence condition.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7fffc644-5030-4c9f-a589-a83c44e2f1e9

📥 Commits

Reviewing files that changed from the base of the PR and between 391385f and 8a56c66.

📒 Files selected for processing (4)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-lease-stale-handle-survival.test.ts
  • src/main/runtime/rpc/terminal-subscribe-ownership.test.ts

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

@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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: df161547-47dc-439a-8ef8-a574e06fdf06

📥 Commits

Reviewing files that changed from the base of the PR and between 8a56c66 and f774bd8.

📒 Files selected for processing (7)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/streaming.test.ts
  • src/main/runtime/rpc/terminal-lease-stale-handle-survival.test.ts
  • src/main/runtime/rpc/terminal-subscribe-lease-only.test.ts
  • src/main/runtime/rpc/terminal-subscribe-ownership.test.ts
  • src/main/runtime/terminal-pty-exit-waiter.test.ts

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

Comment on lines +35226 to +35242
private isPtyKnownExited(ptyId: string): boolean {
const pty = this.ptysById.get(ptyId)
if (pty) {
return !pty.connected
}
return this.getLeavesForPty(ptyId).some((leaf) => getTerminalState(leaf) === 'exited')
}

private notifyPtyExitListeners(ptyId: string): void {
const listeners = this.ptyExitListenersByPtyId.get(ptyId)
if (!listeners) {
return
}
this.ptyExitListenersByPtyId.delete(ptyId)
notifyRuntimeListeners(listeners, (listener) => listener(), 'pty-exit')
}

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Notify exit listeners on every PTY disconnect transition.

These reconciliation paths set pty.connected = false without notifying existing exit listeners. Because the subscription lifetime has no timeout, listeners waiting through these transitions can remain registered indefinitely, including after record pruning. Route every transition to connected = false through a notifier, or call notifyPtyExitListeners(ptyId) after updating the state.

📍 Affects 1 file
  • src/main/runtime/orca-runtime.ts#L35226-L35242 (this comment)
  • src/main/runtime/orca-runtime.ts#L15084-L15089

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Live validation — commit f774bd8ef5

Isolated Electron identity: Orca: brennanb2025/lease-survives-stale-handle / worktree fix-mobile-send-dead-0044 (window.api.app.getIdentity()). iOS Simulator iPhone 17 Pro (iOS 26.5) paired to that host (Host 72). Throwaway Linux Docker SSH target on 127.0.0.1:2222 with bundled demo-project; relay linux-arm64 deployed (pnpm build:relay first).

What was exercised

  • Mobile terminal.subscribe against a live local PTY: composer stayed Live input, transcript showed ORCA_LEASE_LOCAL_ALIVE. Desktop showed Your phone is in control (lease held).
  • Real PTY exit from the phone: tab retired (0 tabs), composer Type a command…, not “Waiting for terminal…”.
  • SSH remote PTY via relay: root@…:/work/demo-project, remote marker ORCA_SSH_PTY_ALIVE, mobile subscribed to the same remote tabs with live input.

Screenshots inspected; no pairing codes, QR payloads, or device tokens.

Electron

electron-app-loaded.png
electron-local-terminal-alive.png
electron-local-terminal-exited.png
electron-ssh-terminal-alive.png

iOS Simulator

ios-app-loaded-paired.png
ios-terminal-subscribed-live.png
ios-terminal-exited-no-lock.png
ios-ssh-terminal-subscribed.png

Residual gaps

  • Did not inject a live terminal_handle_stale renderer-graph-epoch fault (that path is covered by terminal-lease-stale-handle-survival.test.ts). Live run proves subscribe + real-exit retirement, not the stale-lookup-without-absence case.
  • GitHub clone of stablyai/demo-project was blocked; used a local git bundle instead.

…nously

The runtime doubles for terminal.subscribe never stubbed subscribeToPtyExit,
so the new lifetime watcher threw and killed every subscription under test.

Also return early when the watcher releases synchronously: cleanup had already
run, so the stream handlers, view subscribers, and mobile presence registered
afterwards were never torn down.
@brennanb2025
brennanb2025 merged commit 9b8dbd8 into main Aug 19, 2026
46 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
…stablyai#15463)

* fix(mobile): keep a terminal lease alive when the handle lookup fails

`waitForTerminal(..., 'exit')` rejects with `terminal_handle_stale` whenever the
handle cannot be resolved right now. The loudest source is
`record.rendererGraphEpoch !== this.rendererGraphEpoch` — every renderer graph
reload invalidates handles issued before it, on panes whose PTY is untouched.

All three terminal.subscribe branches wired that rejection straight to teardown
(`.catch(() => registration.releaseIfCurrent())`), so the host retired a live
lease and emitted `end`. Mobile reads `end` as "PTY gone" and rearms; after
MAX_REARM_ATTEMPTS = 3 it stops and leaves the composer on "Waiting for
terminal…", recovering only when a replacement handle arrives. A live PTY keeps
its handle, so no replacement ever comes: the pane is dead until the app is
backgrounded and reopened.

Demand proof instead. Retire on abort (this socket is going away) or when
isLeafPtyProvenAbsent says the process is gone; a real exit still resolves and
retires through the .then leg. Absence must be proven, never inferred from a
lookup that failed.

Reproduced live: a paired 0.0.44 client over LAN, fault injected on the handle
lookup, composer locked on "Waiting for terminal…" and STILL locked 97s after
the fault was lifted with the PTY alive and the handle unchanged.

Narrows one behavior stablyai#14992 pinned: a stale handle alone no longer retires the
owner. The ownership property is unchanged — once absence is proven, the owning
registration is still what retires. That test is updated, not deleted.

* fix(mobile): observe PTY exit independent of stale handles

* fix(mobile): stop subscribe setup when an exited pty releases synchronously

The runtime doubles for terminal.subscribe never stubbed subscribeToPtyExit,
so the new lifetime watcher threw and killed every subscription under test.

Also return early when the watcher releases synchronously: cleanup had already
run, so the stream handlers, view subscribers, and mobile presence registered
afterwards were never torn down.
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
…stablyai#15463)

* fix(mobile): keep a terminal lease alive when the handle lookup fails

`waitForTerminal(..., 'exit')` rejects with `terminal_handle_stale` whenever the
handle cannot be resolved right now. The loudest source is
`record.rendererGraphEpoch !== this.rendererGraphEpoch` — every renderer graph
reload invalidates handles issued before it, on panes whose PTY is untouched.

All three terminal.subscribe branches wired that rejection straight to teardown
(`.catch(() => registration.releaseIfCurrent())`), so the host retired a live
lease and emitted `end`. Mobile reads `end` as "PTY gone" and rearms; after
MAX_REARM_ATTEMPTS = 3 it stops and leaves the composer on "Waiting for
terminal…", recovering only when a replacement handle arrives. A live PTY keeps
its handle, so no replacement ever comes: the pane is dead until the app is
backgrounded and reopened.

Demand proof instead. Retire on abort (this socket is going away) or when
isLeafPtyProvenAbsent says the process is gone; a real exit still resolves and
retires through the .then leg. Absence must be proven, never inferred from a
lookup that failed.

Reproduced live: a paired 0.0.44 client over LAN, fault injected on the handle
lookup, composer locked on "Waiting for terminal…" and STILL locked 97s after
the fault was lifted with the PTY alive and the handle unchanged.

Narrows one behavior stablyai#14992 pinned: a stale handle alone no longer retires the
owner. The ownership property is unchanged — once absence is proven, the owning
registration is still what retires. That test is updated, not deleted.

* fix(mobile): observe PTY exit independent of stale handles

* fix(mobile): stop subscribe setup when an exited pty releases synchronously

The runtime doubles for terminal.subscribe never stubbed subscribeToPtyExit,
so the new lifetime watcher threw and killed every subscription under test.

Also return early when the watcher releases synchronously: cleanup had already
run, so the stream handlers, view subscribers, and mobile presence registered
afterwards were never torn down.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…stablyai#15463)

* fix(mobile): keep a terminal lease alive when the handle lookup fails

`waitForTerminal(..., 'exit')` rejects with `terminal_handle_stale` whenever the
handle cannot be resolved right now. The loudest source is
`record.rendererGraphEpoch !== this.rendererGraphEpoch` — every renderer graph
reload invalidates handles issued before it, on panes whose PTY is untouched.

All three terminal.subscribe branches wired that rejection straight to teardown
(`.catch(() => registration.releaseIfCurrent())`), so the host retired a live
lease and emitted `end`. Mobile reads `end` as "PTY gone" and rearms; after
MAX_REARM_ATTEMPTS = 3 it stops and leaves the composer on "Waiting for
terminal…", recovering only when a replacement handle arrives. A live PTY keeps
its handle, so no replacement ever comes: the pane is dead until the app is
backgrounded and reopened.

Demand proof instead. Retire on abort (this socket is going away) or when
isLeafPtyProvenAbsent says the process is gone; a real exit still resolves and
retires through the .then leg. Absence must be proven, never inferred from a
lookup that failed.

Reproduced live: a paired 0.0.44 client over LAN, fault injected on the handle
lookup, composer locked on "Waiting for terminal…" and STILL locked 97s after
the fault was lifted with the PTY alive and the handle unchanged.

Narrows one behavior stablyai#14992 pinned: a stale handle alone no longer retires the
owner. The ownership property is unchanged — once absence is proven, the owning
registration is still what retires. That test is updated, not deleted.

* fix(mobile): observe PTY exit independent of stale handles

* fix(mobile): stop subscribe setup when an exited pty releases synchronously

The runtime doubles for terminal.subscribe never stubbed subscribeToPtyExit,
so the new lifetime watcher threw and killed every subscription under test.

Also return early when the watcher releases synchronously: cleanup had already
run, so the stream handlers, view subscribers, and mobile presence registered
afterwards were never torn down.
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