Skip to content

fix(terminal): require a proven exit before retiring a subscription's lease - #15470

Merged
brennanb2025 merged 1 commit into
mainfrom
brennanb2025/fix-terminal-stale-handle-teardown
Aug 20, 2026
Merged

brennanb2025 merged 1 commit into
mainfrom
brennanb2025/fix-terminal-stale-handle-teardown

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​172 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​172
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3

What changed

One predicate. isPtyKnownExited treated a PTY record as exited whenever connected was false:

private isPtyKnownExited(ptyId: string): boolean {
  const pty = this.ptysById.get(ptyId)
  if (pty) {
    return !pty.connected                                                    // infers
  }
  return this.getLeavesForPty(ptyId).some((l) => getTerminalState(l) === 'exited')  // proves
}

The leaf fallback demands proof — getTerminalState returns 'exited' only once lastExitCode is set. The PTY path infers it from disconnection, and that is the path that runs whenever a record exists. This makes both demand the same proof, reusing the runtime's existing three-valued discriminator.

Why it matters

onPtyExit is the only writer of lastExitCode. The liveness sweep clears connected with no exit code for every PTY behind a dropped relay, so that state means "lost the connection to a process that may still be running on the host" — not "the process exited".

Reading it as an exit makes subscribeToPtyExit fire its listener synchronously at subscribe time. watchSubscriptionLifetime then retires the lease and emits end for a live terminal. 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 — which never comes, because the PTY is alive and its handle is unchanged.

This is the residual cause of the 0.0.44 permanent composer lock. A separate session reproduced that symptom independently, and the mechanism matches exactly: lease retired, end emitted, three rearms, locked.

After the change 'unknown' keeps watching, the later real exit still fires the listener, and a subscription that outlives its PTY stays bounded by the connection abort that watchSubscriptionLifetime already registers.

Scope

Both callers are inside subscribeToPtyExit — the subscribe-time fast path and the registration-race re-check. Both want proven-exited, so neither changes shape, and the predicate is private with no other callers. Nothing in #15463 is reverted or restructured.

Retraction of the original framing

This PR previously proposed a different fix: a re-arm loop with 250ms→30s backoff wrapped around waitForTerminal(..., { condition: 'exit' }), plus handle rebinding through a new resolveTerminalExitWatch. That approach is withdrawn.

#15463 landed on main during review and fixes the same underlying defect by a better mechanism — watchSubscriptionLifetime subscribing on the stable ptyId and notified from onPtyExit, with no polling, no backoff, and no handle re-resolution. It deleted all three waitForTerminal(params.terminal, { condition: 'exit' }).then/.catch(releaseIfCurrent) call sites this PR used to rewrite, so the original change targeted code that no longer exists; carrying it forward would have reverted the better fix.

What survives is the one finding #15463 did not cover: that !connected is not proof of exit. #15463's own commit message states "absence must be proven, never inferred" — this completes that principle on the path it missed.

Tests

Three new cases in terminal-pty-exit-waiter.test.ts against the real runtime, pinning both directions:

  • disconnected with lastExitCode still null — the listener must not fire, and the subscription stays registered
  • the host returns and onPtyExit lands — the listener does fire, so subscribing during the outage costs nothing
  • disconnected with an exit code — fires immediately, unchanged

Both must-change cases fail against unfixed main (2 failed | 4 passed); the third passes either way as a regression guard.

terminal-subscribe-relay-drop-lease-survival.test.ts carries it to the wire across all three terminal.subscribe branches (lease-only, legacy JSON, binary). The existing stale-handle suite doubles subscribeToPtyExit, so it pins the wiring but not the predicate; this one delegates that single call to a real OrcaRuntimeService and asserts no end is emitted for a relay-dropped PTY, then that end does arrive once the real exit lands.

Verification

  • src/main/runtime — 370 files, 4664 passed, 9 skipped, 0 failed
  • typecheck:node — exit 0, proven non-vacuous (injected a TS2322 into the new test file, exit 1 naming that file, restored, exit 0)
  • oxfmt and oxlint — clean

@coderabbitai

coderabbitai Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: 56d24e17-d5c7-4b9d-9cd8-cf5baa88d594

📥 Commits

Reviewing files that changed from the base of the PR and between 1c71a2d9ae657a21fb3cdb3d150e372f18a980a6 and 76bd0b4.

📒 Files selected for processing (1)
  • src/main/runtime/orca-runtime.ts

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


📝 Walkthrough

Walkthrough

PTY exit detection now requires an explicit exited terminal state. Disconnected PTYs without exit evidence remain watchable. Tests cover exit-waiter behavior and relay drops for lease-only, legacy JSON, and binary subscriptions. Cleanup and termination occur after a real PTY exit is reported.

Merge Risk: 🟠 High · up to 76bd0

The change prevents a relay disconnect from being treated as proof that a terminal exited, but the current head still has runtime paths that can expose stale exit state or strand subscribers after disconnected-record cleanup, along with test subscriptions that may leak across cases. These create concrete correctness and availability risks, so the PR should not merge until they are addressed or explicitly accepted.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change, rationale, scope, tests, and verification, but omits required template sections including Linked Issue, Visual Proof, checklist, and review details. Add the required template sections, include the linked issue, provide Visual Proof or N/A with a reason, and complete the checklist and review details.
Docstring Coverage ⚠️ Warning Docstring coverage is 24.14% which is insufficient. The required threshold is 80.00%. 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 and concisely describes the main change: requiring proven PTY exit state before retiring a subscription lease.
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.
✨ 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 702c17fd-5220-41b3-94ea-16a583181950

📥 Commits

Reviewing files that changed from the base of the PR and between 4fc8b65 and d3099d7.

📒 Files selected for processing (4)
  • src/main/runtime/rpc/methods/terminal-subscription-exit-release.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-subscribe-ownership.test.ts
  • src/main/runtime/rpc/terminal-subscribe-stale-handle-teardown.test.ts

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

@brennanb2025
brennanb2025 force-pushed the brennanb2025/fix-terminal-stale-handle-teardown branch from d3099d7 to ae2c890 Compare August 19, 2026 20:28

@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

🧹 Nitpick comments (4)
src/main/runtime/rpc/methods/terminal-subscription-exit-release.ts (1)

3-6: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the lifecycle rationale comments.

Keep each rationale comment to one concise line. Move detailed renderer and graph behavior to nearby documentation if it must remain recorded.

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

Also applies to: 68-73, 109-111

Source: Coding guidelines

src/main/runtime/rpc/terminal-subscribe-ownership.test.ts (1)

136-147: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

The 300 ms wait duplicates the helper's backoff constant.

flush(300) must exceed the first retry delay for this assertion to be meaningful. That delay lives in terminal-subscription-exit-release.ts. If the base delay grows, this test still passes but no longer proves that the re-arm was cancelled.

Export the base delay from the helper and derive the wait from it, or drive the retry with fake timers so the assertion is deterministic.

src/main/runtime/rpc/terminal-subscribe-stale-handle-teardown.test.ts (1)

240-285: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Close the harness in the last three tests.

The tests at Line 240, Line 263, and Line 278 never call harness.close(). The connection abort signal therefore never fires, so the subscription cleanup and the exit-release stop() never run. In the re-arm test the stub resolveTerminalExitWatch returns 'pending' forever, so a retry loop can survive into later tests in this file.

Add harness.close() at the end of each test, as the earlier tests do.

♻️ Proposed cleanup
     await vi.waitFor(() => expect(harness.jsonTypes()).toContain('end'))
+    harness.close()
   })
src/main/runtime/rpc/methods/terminal-subscription-exit-release.test.ts (1)

42-45: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Restore mocks before restoring real timers. Because setTimeoutSpy captures Vitest’s fake timer, run vi.restoreAllMocks() before vi.useRealTimers() to prevent the fake setTimeout from leaking into later tests.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 14e1631b-5d2d-4609-8446-a91e4927430e

📥 Commits

Reviewing files that changed from the base of the PR and between d3099d7 and ae2c89050ef3fb7c0f944b14eea467b4904fd6b5.

📒 Files selected for processing (6)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal-subscription-exit-release.test.ts
  • src/main/runtime/rpc/methods/terminal-subscription-exit-release.ts
  • src/main/runtime/rpc/terminal-exit-waiter-graph-churn.test.ts
  • src/main/runtime/rpc/terminal-subscribe-ownership.test.ts
  • src/main/runtime/rpc/terminal-subscribe-stale-handle-teardown.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 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.

🧹 Nitpick comments (1)
src/main/runtime/rpc/methods/terminal-subscription-exit-release.ts (1)

70-84: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reduce the explanatory comments.

The new comments restate nearby control flow and span multiple lines. Keep only a brief sentence for non-obvious rationale.

  • src/main/runtime/rpc/methods/terminal-subscription-exit-release.ts#L70-L84: condense the handle-rebinding rationale.
  • src/main/runtime/rpc/methods/terminal-subscription-exit-release.ts#L98-L102: condense the backoff rationale.
  • src/main/runtime/rpc/terminal-exit-waiter-graph-churn.test.ts#L284-L285: remove the explanation of the assertion path.
  • src/main/runtime/rpc/terminal-exit-waiter-graph-churn.test.ts#L292-L294: remove the explanation duplicated by the test setup and name.

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: 5c2236f0-b809-49af-98b9-53197080a83e

📥 Commits

Reviewing files that changed from the base of the PR and between ae2c89050ef3fb7c0f944b14eea467b4904fd6b5 and e7319a1dc8e4ad70ebc89701eb527fd091dce486.

📒 Files selected for processing (6)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal-subscription-exit-release.test.ts
  • src/main/runtime/rpc/methods/terminal-subscription-exit-release.ts
  • src/main/runtime/rpc/terminal-exit-waiter-graph-churn.test.ts
  • src/main/runtime/rpc/terminal-subscribe-ownership.test.ts
  • src/main/runtime/rpc/terminal-subscribe-stale-handle-teardown.test.ts

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

@brennanb2025
brennanb2025 force-pushed the brennanb2025/fix-terminal-stale-handle-teardown branch from 60fe8c9 to 83fbc19 Compare August 19, 2026 21:47
@brennanb2025 brennanb2025 changed the title fix(terminal): keep a live subscription when the terminal handle goes stale fix(terminal): require a proven exit before retiring a subscription's lease Aug 19, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review loop — summary (posting for the record; never landed on the PR)

This PR went through a high-effort review loop plus an adversarial pass. The findings materially changed it, and finally superseded its original approach entirely.

Three defects found in the original fix

  1. The same-id re-arm was inert. beginGraphReload's retainedHandles set includes handleByPtyIncarnation — the very map the fix cited as preserving the handle id. So the two conditions are mutually exclusive: preserved ⇒ retained ⇒ the waiter is never rejected, so no re-arm happens; rejected ⇒ not retained ⇒ the id is re-minted and the re-arm binds a dead one. The fix traded a spurious teardown for no teardown.
  2. A dropped SSH relay blanked a live remote terminal. The watcher released on any resolution, but waitForTerminal resolves on !pty.connected with no exit code — the mirror image of the original defect, on the .then leg.
  3. A stranded watcher when one PTY is mirrored across panes (resolveTerminalExitWatch held out for a single leaf).

Then main superseded the whole approach

#15463 landed and fixes the same defect by a better mechanism — watchSubscriptionLifetime + subscribeToPtyExit, keyed on the stable ptyId and notified from onPtyExit. It deleted all three waitForTerminal(...).catch(releaseIfCurrent) call sites this PR rewrote, so keeping the original shape would have reverted main's fix.

What this PR is now

Reshaped to the residual defect #15463 shipped with. isPtyKnownExited inferred exit from !pty.connected while its own leaf fallback in the same function demanded a proven 'exited'. A relay drop clears connected with no exit code, so the lease is retired and end emitted for a process still running on the host — the residual cause of the 0.0.44 "Waiting for terminal…" permanent composer lock. #15463's own commit message says "absence must be proven, never inferred"; the pty path inferred.

Now 4 production lines, with both directions pinned against the real runtime.

Evidence is unit-level; no hardware QA had been possible at the time. Being addressed separately.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

QA evidence for PR #15470

Frame-level capture of terminal.subscribe against a fault-injected dropped-relay PTY (connected=false, lastExitCode=null, process still recorded). Not a device capture. The visible 0.0.44 composer lock lives on the phone; this run did not pair a simulator.

Isolation (required)

Two isolated pn dev instances, each with ORCA_DEV_USER_DATA_PATH, ORCA_DEV_INSTANCE_KEY, and redirected HOME. Proven with window.api.repos.list() → [] before any repo was added. Playwright over CDP only (no computer-use).

Role Commit Instance label userData repos.list() at boot
BEFORE 0a853a5c0d (main) qa-15470-before-main /tmp/orca-qa-15470-profile.QngCEP []
AFTER 83fbc19273 (this PR) qa-15470-after-pr /tmp/orca-qa-15470-after-profile.L9rHxP []

BEFORE boot (empty profile):

01-before-isolated-empty.png

AFTER boot (empty profile):

03-after-isolated-empty.png

What was staged vs observed

Staged (said so): after creating a real PTY through terminal.create on the isolated host, the main-process inspector flipped pty.connected = false and left lastExitCode === null. That is the liveness-sweep / dropped-relay record: connection lost, no death certificate, process may still be running. onPtyExit was not called for the defect case.

Observed: a mobile-style lease-only terminal.subscribe over the instance's local-only pairing websocket (connectionMode: 'local-only').

This is the subscribe-time fast path inside watchSubscriptionLifetime → isPtyKnownExited. It is the path that retires the lease and emits end for a live terminal.

Defect (BEFORE, unfixed main)

Workspace qa-15470-term existed in the isolated app; the PTY itself was created via runtime RPC (headless, no desktop tab mount). Isolation screenshot after adding the fixture repo:

02-before-workspace-terminal.png

Injected drop, then subscribe. First (and only) frame at 21ms was end. subscribed was never emitted — the already-exited fast path runs cleanup before the handler can ack.

{
  "runtimeId": "13cbb9da-4bf3-4f04-8928-85b8e9cbfb49",
  "handle": "term_191cc7e7-8c93-47d4-bd01-a841ec0f9b73",
  "types": ["end"],
  "emittedSubscribed": false,
  "emittedEnd": true,
  "t_ms": 21
}

That matches the 0.0.44 lock mechanism: mobile treats end as “PTY gone”, rearms three times against the same still-listed handle, then leaves the composer on “Waiting for terminal…”.

Fix (AFTER, this PR)

Same injection on 83fbc19273. Isolation screenshot after adding the fixture repo:

04-after-workspace.png

Hold 1 — drop only, 8s, no onPtyExit: subscribed at 28ms, no end for the full hold.

{
  "runtimeId": "bb697e1b-47e5-44bb-9c32-4951b7780dc1",
  "handle": "term_a8df3308-9fc0-4711-97d2-cae0bfc72664",
  "types": ["subscribed"],
  "emittedSubscribed": true,
  "emittedEnd": false,
  "hold_ms": 8000
}

Hold 2 — same drop, then genuine onPtyExit(ptyId, 0): subscribed at 48ms, end at 1757ms after lastExitCode became 0.

{
  "types": ["subscribed", "end"],
  "emittedSubscribed": true,
  "emittedEnd": true,
  "t_subscribed_ms": 48,
  "t_end_ms": 1757,
  "lastExitCode_after_onPtyExit": 0
}

The lease survives the inferred disconnect. A proven host exit still retires it.

Side-by-side

05-frame-before-after.png

What this run did not capture

  • No simulator / phone pairing. Orca Mobile is installed on a booted iPhone 17 Pro sim, but this evidence is host RPC frames, not the native-chat composer. I did not open orca://pair?… on a device and did not photograph “Waiting for terminal…”.
  • No real Relay drop. The disconnected-without-exit state was injected on a local PTY (inspector write of connected=false). That is the same record the liveness sweep writes for every PTY of a dropped relay; it is not a live SSH/relay outage.
  • Desktop screenshots of empty/workspace chrome prove isolation and the fixture, not the defect. The defect evidence is the frame log.

Method notes

  • Desktop UI: Playwright CDP against the isolated instances only.
  • Main-process OrcaRuntimeService was pinned via a one-shot breakpoint on runtime:getStatus (runtime$1 captured to globalThis.__qaRuntime), then pty.connected was flipped. Production code was not modified.
  • Subscribe used lease-only mobile capabilities (terminalBinaryStream: 1, mobileInputLeaseOnly: 1) because that is the native-chat input-floor path that rearms on end.

@brennanb2025
brennanb2025 force-pushed the brennanb2025/fix-terminal-stale-handle-teardown branch from 83fbc19 to 1c71a2d Compare August 19, 2026 23:13

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/main/runtime/orca-runtime.ts (3)

35321-35340: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

dropDisconnectedPtyRecord never notifies subscribeToPtyExit listeners, so a pruned disconnected PTY can strand its subscription forever.

dropDisconnectedPtyRecord (called from pruneDisconnectedPtyRecords when more than DISCONNECTED_PTY_RECORD_MAX disconnected records accumulate) calls this.advancePtyLifecycleGeneration(ptyId) but does not call this.notifyPtyExitListeners(ptyId). After pruning, this.ptysById.get(ptyId) returns undefined and this.getLeavesForPty(ptyId) returns an empty array, so isPtyKnownExited(ptyId) returns false forever for that id — the PTY record is gone, but the runtime never proves it exited.

subscribeToPtyExit's post-registration recheck only compares the lifecycle generation snapshot taken at call time; it does not subscribe to future generation changes, so bumping the generation in dropDisconnectedPtyRecord does not itself wake any listener already registered. Any consumer with no AbortSignal (for example watchSubscriptionLifetime in terminal.ts, whose only teardown path besides the signal is this exit callback) keeps its subscription registered indefinitely once its PTY is pruned this way.

Call this.notifyPtyExitListeners(ptyId) inside dropDisconnectedPtyRecord, alongside the existing advancePtyLifecycleGeneration(ptyId) call, so listeners waiting on a since-pruned PTY are released.

🔒️ Proposed fix
 private dropDisconnectedPtyRecord(ptyId: string): void {
   // Why: pruning can remove a PTY without the normal exit callback.
   this.advancePtyLifecycleGeneration(ptyId)
+  this.notifyPtyExitListeners(ptyId)
   this.pairedRendererSessionOwnedPtyIds.delete(ptyId)
   this.ptysById.delete(ptyId)
   ...

15183-15183: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Move notifyPtyExitListeners after the PTY record is marked exited.

this.notifyPtyExitListeners(ptyId) runs immediately after advancePtyLifecycleGeneration(ptyId), but pty.connected = false and pty.lastExitCode = exitCode are not set until much later in onPtyExit (in the if (pty) { ... } block near the end of the function). Between these two points, isPtyKnownExited(ptyId) still returns false for this PTY.

A listener registered through subscribeToPtyExit is documented and expected to fire only when the exit is confirmed. If a listener callback queries PTY state synchronously (directly or through a nested call), it observes the PTY as still connected and not exited, even though the exit notification just fired. Move the notifyPtyExitListeners(ptyId) call to after the block that sets pty.connected, pty.lastExitCode, and pty.lastExitCause, so the invariant "exit notified implies isPtyKnownExited is true" holds for every current and future consumer of subscribeToPtyExit.

🐛 Proposed fix outline
     this.advancePtyLifecycleGeneration(ptyId)
-    this.notifyPtyExitListeners(ptyId)
     const exactSurfaceByKey = new Map<...>()
     ...
     if (pty) {
       pty.connected = false
       pty.runtimeSessionOwned = false
       this.setPairedRendererSessionOwnership(pty.ptyId, false)
       pty.disconnectedAt = Date.now()
       pty.lastExitCode = exitCode
       pty.lastExitCause = exitCause
+      this.notifyPtyExitListeners(ptyId)
       ...
     }

7621-7713: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Treat a missing tabsByWorktree[worktreeId] entry as an empty list. The close helper writes [], but hydration and session cleanup can delete the entry. Returning early can retain ownership for retired renderer tabs.

🧹 Nitpick comments (2)
src/main/runtime/terminal-pty-exit-waiter.test.ts (1)

61-64: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reduce this comment to one sentence.

Keep the reason for the test. Remove the phone retry and UI behavior details.

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

Proposed change
-// Why: the liveness sweep clears `connected` with no exit code for every PTY behind a
-// dropped relay, so a record in that state is a lost connection to a process that may
-// still be running. Reading it as an exit retires a live lease and emits `end`, which the
-// phone rearms against three times and then locks the composer on "Waiting for terminal…".
+// A disconnected PTY has no confirmed exit, so its subscription must remain active.

Source: Coding guidelines

src/main/runtime/rpc/terminal-subscribe-relay-drop-lease-survival.test.ts (1)

1-3: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reduce this comment to one sentence.

State only why this test uses the real PTY exit predicate.

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

Proposed change
-// Why: the stale-handle survival suite doubles subscribeToPtyExit, so it pins the wiring but
-// not the predicate that decides whether a PTY counts as exited. This wires that one call to
-// a real OrcaRuntimeService, because a relay drop reaches the phone through the predicate.
+// Use the real PTY exit predicate because relay loss reaches `terminal.subscribe` through it.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d3ff371b-871d-4f87-a683-32505d9901b1

📥 Commits

Reviewing files that changed from the base of the PR and between e7319a1dc8e4ad70ebc89701eb527fd091dce486 and 1c71a2d9ae657a21fb3cdb3d150e372f18a980a6.

📒 Files selected for processing (3)
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/terminal-subscribe-relay-drop-lease-survival.test.ts
  • src/main/runtime/terminal-pty-exit-waiter.test.ts

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

… lease

isPtyKnownExited read a PTY record as exited whenever `connected` was false:

  if (pty) { return !pty.connected }

Its own leaf fallback, one line below, demands getTerminalState(leaf) === 'exited',
which is only true once lastExitCode is set. So the same function proves absence on
one path and infers it on the other, and the inferring path is the one that runs
whenever a record exists.

onPtyExit is the only writer of lastExitCode. The liveness sweep clears `connected`
with no exit code for every PTY behind a dropped relay, so that state is a lost
connection to a process that may still be running on the host — not an exit. Reading
it as one makes subscribeToPtyExit fire its listener synchronously at subscribe time,
which retires the lease and emits `end` for a live terminal. Mobile reads `end` as
"PTY gone" and rearms; after three attempts it stops and leaves the composer on
"Waiting for terminal…", which is where the 0.0.44 permanent lock comes from.

Use the runtime's existing three-valued discriminator so both paths demand the same
proof. 'unknown' now keeps watching, and the later real exit still fires the listener;
a subscription that outlives its PTY is still bounded by the connection abort.

Both callers are in subscribeToPtyExit — the subscribe-time fast path and the
registration-race re-check — and both want proven-exited, so neither changes shape.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/fix-terminal-stale-handle-teardown branch from 1c71a2d to 76bd0b4 Compare August 19, 2026 23:53
@brennanb2025
brennanb2025 merged commit 59c5624 into main Aug 20, 2026
46 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
… lease (stablyai#15470)

isPtyKnownExited read a PTY record as exited whenever `connected` was false:

  if (pty) { return !pty.connected }

Its own leaf fallback, one line below, demands getTerminalState(leaf) === 'exited',
which is only true once lastExitCode is set. So the same function proves absence on
one path and infers it on the other, and the inferring path is the one that runs
whenever a record exists.

onPtyExit is the only writer of lastExitCode. The liveness sweep clears `connected`
with no exit code for every PTY behind a dropped relay, so that state is a lost
connection to a process that may still be running on the host — not an exit. Reading
it as one makes subscribeToPtyExit fire its listener synchronously at subscribe time,
which retires the lease and emits `end` for a live terminal. Mobile reads `end` as
"PTY gone" and rearms; after three attempts it stops and leaves the composer on
"Waiting for terminal…", which is where the 0.0.44 permanent lock comes from.

Use the runtime's existing three-valued discriminator so both paths demand the same
proof. 'unknown' now keeps watching, and the later real exit still fires the listener;
a subscription that outlives its PTY is still bounded by the connection abort.

Both callers are in subscribeToPtyExit — the subscribe-time fast path and the
registration-race re-check — and both want proven-exited, so neither changes shape.
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
… lease (stablyai#15470)

isPtyKnownExited read a PTY record as exited whenever `connected` was false:

  if (pty) { return !pty.connected }

Its own leaf fallback, one line below, demands getTerminalState(leaf) === 'exited',
which is only true once lastExitCode is set. So the same function proves absence on
one path and infers it on the other, and the inferring path is the one that runs
whenever a record exists.

onPtyExit is the only writer of lastExitCode. The liveness sweep clears `connected`
with no exit code for every PTY behind a dropped relay, so that state is a lost
connection to a process that may still be running on the host — not an exit. Reading
it as one makes subscribeToPtyExit fire its listener synchronously at subscribe time,
which retires the lease and emits `end` for a live terminal. Mobile reads `end` as
"PTY gone" and rearms; after three attempts it stops and leaves the composer on
"Waiting for terminal…", which is where the 0.0.44 permanent lock comes from.

Use the runtime's existing three-valued discriminator so both paths demand the same
proof. 'unknown' now keeps watching, and the later real exit still fires the listener;
a subscription that outlives its PTY is still bounded by the connection abort.

Both callers are in subscribeToPtyExit — the subscribe-time fast path and the
registration-race re-check — and both want proven-exited, so neither changes shape.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… lease (stablyai#15470)

isPtyKnownExited read a PTY record as exited whenever `connected` was false:

  if (pty) { return !pty.connected }

Its own leaf fallback, one line below, demands getTerminalState(leaf) === 'exited',
which is only true once lastExitCode is set. So the same function proves absence on
one path and infers it on the other, and the inferring path is the one that runs
whenever a record exists.

onPtyExit is the only writer of lastExitCode. The liveness sweep clears `connected`
with no exit code for every PTY behind a dropped relay, so that state is a lost
connection to a process that may still be running on the host — not an exit. Reading
it as one makes subscribeToPtyExit fire its listener synchronously at subscribe time,
which retires the lease and emits `end` for a live terminal. Mobile reads `end` as
"PTY gone" and rearms; after three attempts it stops and leaves the composer on
"Waiting for terminal…", which is where the 0.0.44 permanent lock comes from.

Use the runtime's existing three-valued discriminator so both paths demand the same
proof. 'unknown' now keeps watching, and the later real exit still fires the listener;
a subscription that outlives its PTY is still bounded by the connection abort.

Both callers are in subscribeToPtyExit — the subscribe-time fast path and the
registration-race re-check — and both want proven-exited, so neither changes shape.
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