Skip to content

fix(runtime): tear down terminal subscriptions only through their owning registration - #14992

Merged
brennanb2025 merged 6 commits into
mainfrom
brennanb2025/sta-4510-subscription-ownership
Aug 17, 2026
Merged

brennanb2025 merged 6 commits into
mainfrom
brennanb2025/sta-4510-subscription-ownership

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 19 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​686 $\color{#cf222e}{\Huge{\mathbf{−}}}$​335 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​351
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​279 $\color{#cf222e}{\Huge{\mathbf{−}}}$​28 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​251

ELI5

The server files each terminal subscription's "how to shut this down" routine under a name like terminal-1:your-phone. That name never changes, so when your phone reconnects it correctly replaces the old entry — but the old, dying connection is still holding that name written on a scrap of paper. When it finally times out it says "shut down terminal-1:your-phone", and the server obediently shuts down whatever is filed under that name right now — your live stream. Output stops, silently, forever.

This PR makes teardown act on a registration you own, not on a string you happen to hold.

What Changed

  • registerOwnedSubscriptionCleanup (new) returns a SubscriptionRegistration handle. releaseIfCurrent() no-ops once the id has been rebound to a newer subscriber. The existing registerSubscriptionCleanup is untouched, so the seven other feature areas that use it are unaffected.
  • One internal primitive cleanupOwnedSubscription(id, expectedCleanup) does a synchronous ownership check and then delegates to cleanupSubscriptionAndWait, preserving the in-flight join, the retain-on-failure, and the retrySubscriptionCleanupAfter contract rather than bypassing them.
  • All 12 teardown call sites across the three terminal.subscribe branches now route through the handle. Six are exit-waiter settlements; the other six are stale async continuations (a subscribe/snapshot resuming after a rebind).
  • Register-time eviction now targets the owner it captured instead of re-resolving the key — correct before only because the map still held the old closure at that instant.
  • terminal.unsubscribe gains the same rule via connectionId, matching the runtime.clientEvents.unsubscribe precedent (client-events.ts:60-67), the only unsubscribe handler that already checked ownership. Scoped to socket clients: a connection-less caller (the local unix-socket dispatch path, gated by the 0o600 metadata token) keeps unconditional teardown authority.

Why

terminal.subscribe keys teardown on ${terminal}:${clientId}. clientId is the paired device token, stable for the install, and the mobile client re-sends terminal.subscribe on every reconnect with no preceding unsubscribe — so the same key legitimately changes owner. cleanupSubscriptionAndWait then invokes whichever cleanup currently owns that key; its existing generation check guards only the map deletion, never the invocation.

The teardown-by-key pattern is old and was harmless. #7490 made it reachable by binding the exit-waiter to the per-socket abort signal to fix an unrelated waiter leak — after which .catch fires on every socket close, which is exactly the reconnect path. Before that it could only fire on terminal_handle_stale / timeout, where teardown is correct. Notably #7490's own description explains that the multiplex branch is safe because of its streams.get(streamId) !== stream identity check; the subscribe branches had no equivalent.

Two sibling paths in this codebase were already generation-guarded — cleanupSubscriptionsForConnection (orca-runtime.ts:13806) and multiplex (terminal.ts:2849). This brings the subscribe branches in line rather than inventing a new mechanism.

terminal.unsubscribe is included because it is an active path to the same freeze, not speculative hardening: make-before-break relay migration subscribes on the new session first, then disposes the old physical subscription, which sends terminal.unsubscribe over the old socket after the new one has already rebound the id. Its params are also fully client-controlled, so today any authenticated socket connection can retire another device's subscription by naming it. (The connection-less local dispatch path retains that power by design — it is a higher trust tier, not an oversight.)

Linked Issue

Fixes #14843

Visual Proof

N/A — no UI change. The user-visible effect is that a mobile terminal keeps streaming across a reconnect instead of freezing; there is no rendered surface that differs.

Testing

Server-side, deterministic. terminal-subscribe-reconnect-rebind.test.ts drives the real RpcDispatcher and TERMINAL_METHODS through the binary-stream branch (the one carrying mobile TUI traffic) against a faithful port of the runtime subscription registry, and models waitForTerminal's real abort semantics. Verified RED before / GREEN after / RED again on revert.

Every guard is mutation-verified — each was individually reverted and confirmed to turn a specific test red:

mutation caught by
ownership check removed from the runtime primitive orca-runtime.test.ts — "releases an owned subscription only while its registration still owns the id"
connection-ownership guard removed orca-runtime.test.ts — "refuses an unsubscribe from a connection that no longer owns"
all 12 releaseIfCurrent() reverted to keyed teardown rebind regression + lease-only continuation + legacy-JSON continuation (one per branch)
unsubscribe handler reverted to keyed teardown terminal-subscribe-ownership.test.ts — stale-connection case

This mattered: my first mutation attempt did not fail, because the test double reimplements the guard and those tests only pin terminal.ts's routing. The runtime primitive tests were added specifically to close that gap.

Also replaced the ad-hoc Map stubs in 14 test files with a shared faithful createSubscriptionRegistryDouble(). Those stubs never evicted the prior generation, which is why no existing test could catch this bug class.

  • Targeted suites: 23 files / 105 tests pass, including the exit-waiter-leak guard from fix(runtime): release terminal.subscribe exit-waiters on teardown #7490.

  • orca-runtime.test.ts: 1164 pass.

  • pnpm tc exit 0; oxfmt + oxlint clean.

  • Platforms: logic is platform-independent server code; not separately exercised per-OS. Not device-verified — see Notes.

  • I manually tested these changes locally

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

Review

Agent skill upstream boundary

  • Not applicable.

Notes

  • Not device-verified. The mechanism is proven deterministically at the server level, and the reporter's serve log (two terminal.subscribe, two snapshots, then silence) matches it, but I did not reproduce on a physical phone. Attribution is strong-by-inference, not confirmed end-to-end.
  • The issue title is stale. It blames relay pty.data flow control. That RCA is falsified: mobile never speaks the relay pty protocol (zero hits for pty.ackData / outputFlowControl under mobile/), and the relay credit ledger defers rather than drops. Worth retitling so the next reader does not re-derive it.
  • Behavior surfaced, not changed. terminal-subscribe-buffer.test.ts previously asserted no messages on the abort-during-snapshot path — but only because its stub was inert and never ran the cleanup. A faithful registry runs it, and the cleanup emits end, which production always did. The assertion now records reality. Raises a fair question about whether emits should be suppressed after signal abort; not changed here.
  • Backwards compatibility: server-only, no wire change, works with every shipped client. Old clients keep sending the same unsubscribe; it is now ignored when it does not own the subscription.
  • Timing note: a non-owning unsubscribe now defers teardown to the dead socket's sweep — worst case ~45s via the host heartbeat. Acceptable, since the alternative is killing the wrong stream.
  • Remote/SSH: unaffected; this is the desktop→phone hop, independent of the relay host→desktop credit window.
  • Supersedes fix(relay): stale exit-waiter must not kill the rebound terminal stream #14923, which diagnosed the same mechanism. That PR's guard is sound as far as it goes; this one moves the invariant into the API instead of re-deriving a guard at three call sites, covers the six non-waiter teardown sites, and includes terminal.unsubscribe. Its regression test never reaches the binary-stream branch — its params set mobileInputLeaseOnly: 1, so the handler returns from the lease-only branch first.
  • A lease-only presence guard was tried and reverted. fix(runtime): keep a superseded lease-only subscribe from releasing live mobile presence #14993 proposed gating the compensating handleMobileUnsubscribe on the registration still being current. Review showed that predicate is always false when closed is true — either our own cleanup ran (the map entry is already deleted) or a rebind replaced it — so the guard made a real compensation unreachable rather than scoping it. The scenario it targeted is also not reachable: lease-only passes no viewport, and both !viewport paths return with no await. Reverted; fix(runtime): keep a superseded lease-only subscribe from releasing live mobile presence #14993 closed. SubscriptionRegistration exposes only releaseIfCurrent().
  • Three review passes ran on this PR. Passes 1 and 2 each found real defects, including one I introduced while fixing the previous pass.

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)

Author

  • X / Twitter: @BrennanKB5

@coderabbitai

coderabbitai Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The runtime now supports generation-aware subscription registrations and connection-scoped cleanup. Terminal lease-only, JSON, and binary subscriptions use guarded cleanup during exit, abort, disconnect, and setup failures. Terminal unsubscribe checks connection ownership. A shared subscription registry test double replaces local cleanup maps across terminal tests. New tests cover stale cleanup, rebinding, reconnects, ownership checks, retries, and connectionless cleanup.

Merge Risk: 🔵 Low · up to 6cdef

This change prevents stale terminal connections from tearing down newer streams. It is generally mergeable, but the current head retains a minor test-assertion gap, timing-sensitive reconnect tests, and a misleading cleanup contract that should receive explicit owner follow-up.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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
Title check ✅ Passed The title clearly and concisely describes the ownership-based terminal subscription teardown fix.
Description check ✅ Passed The description covers the required sections, explains the change and rationale, links issue #14843, documents testing, and addresses compatibility and risk considerations.
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: 2

🧹 Nitpick comments (4)
src/main/runtime/rpc/subscription-registry-test-double.ts (1)

140-156: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

byConnection rarely drops the connection key.

cleanupSubscription retires an entry only after its cleanup promise resolves. The loop is synchronous, so set.size is still non-zero at Line 153 for every asynchronously retired id. The check therefore almost never fires. removeIndex still deletes the empty set later, so behavior is correct. Consider removing the check to avoid implying synchronous retirement.

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

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

Replace the fixed flush() delay with vi.waitFor for the positive assertions.

flush waits a fixed 20 ms on real timers. The negative assertions in the rebind tests tolerate this, because a short wait only makes them pass. The positive assertions do not. Lines 106, 107 and 123 require the teardown to complete inside 20 ms, and Line 216 requires the rebind to complete inside 20 ms. A loaded CI machine can exceed that and produce a flaky failure. vi.waitFor is already used in this file and polls until the condition holds.

♻️ Proposed change for the abort test
     conn.abort()
-    await flush()
-
-    expect(registry.peekCleanup(SUBSCRIPTION_ID)).toBeUndefined()
-    expect(runtime.handleMobileUnsubscribe).toHaveBeenCalledWith('pty-1', 'phone-1')
+    await vi.waitFor(() => expect(registry.peekCleanup(SUBSCRIPTION_ID)).toBeUndefined())
+    expect(runtime.handleMobileUnsubscribe).toHaveBeenCalledWith('pty-1', 'phone-1')

Also applies to: 103-107, 120-123, 215-217

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

12-117: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the shared subscription registry double.

This local registry does not join concurrent cleanup for the same owner. It also lets synchronous cleanup errors escape. The shared double models both runtime behaviors.

Replace createSubscriptionRegistry() with createSubscriptionRegistryDouble() from ./subscription-registry-test-double.

src/main/runtime/orca-runtime.ts (1)

13737-13755: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Describe the return value as cleanup initiation.

cleanupSubscription starts cleanupSubscriptionAndWait without awaiting it. Therefore, true reports that cleanup was requested for an authorized owner, not that teardown completed. Update the docstring. Keep the unconditional no-connectionId behavior for in-process callers.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 36bde7d8-81ce-42f8-829c-486b05171c18

📥 Commits

Reviewing files that changed from the base of the PR and between 96b03ba and 3ae6460.

📒 Files selected for processing (21)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/subscription-registry-test-double.ts
  • src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts
  • src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts
  • src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts
  • src/main/runtime/rpc/terminal-multiplex-input-write-rejection.test.ts
  • src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts
  • src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts
  • src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts
  • src/main/runtime/rpc/terminal-multiplex-source-range-admission.test.ts
  • src/main/runtime/rpc/terminal-multiplex-test-harness.ts
  • src/main/runtime/rpc/terminal-output-batching.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-lease-only.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

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

Comment on lines +199 to +205
await new Promise((resolve) => setTimeout(resolve, 50))
framesB.length = 0
liveListener('before\r\n', { seq: 1, rawLength: 8 })
await new Promise((resolve) => setTimeout(resolve, 50))
expect(
framesB.some((b) => decodeTerminalStreamFrame(b)?.opcode === TerminalStreamOpcode.Output)
).toBe(true)

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 | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu
file="src/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.ts"
printf '%s\n' "== file outline =="
ast-grep outline "$file" --lang typescript || true
printf '%s\n' "== target test sections =="
sed -n '1,260p' "$file"
printf '%s\n' "== waitFor usage in nearby tests =="
rg -n -C 3 'vi\.waitFor|setTimeout|liveListener|frames[AB]' "$file"

Repository: stablyai/orca

Length of output: 10389


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' "== terminal subscription implementation =="
rg -n -C 6 'subscribeToTerminalData|TerminalStreamOpcode\.Output|sendBinary|dispatchStreaming|terminal\.subscribe|terminal.subscribe' src/main/runtime src/main -g '*.ts' | head -n 400
printf '%s\n' "== package and Vitest configuration =="
rg -n -C 3 'waitFor|testTimeout|fakeTimers|vitest' package.json vitest.config.* src -g '*.ts' -g '*.json' 2>/dev/null | head -n 250
printf '%s\n' "== related terminal streaming tests =="
rg -n -C 5 'decodeTerminalStreamFrame|TerminalStreamOpcode\.Output|subscribeToTerminalData' src -g '*test.ts' -g '*spec.ts' | head -n 400

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' "== terminal method definitions =="
rg -n -C 12 'terminal\.subscribe|subscribe.*terminal|subscribeToTerminalData|TerminalStreamOpcode\.Output' src/main/runtime/rpc/methods src/main/runtime/rpc/dispatcher.ts src/main/runtime/runtime-rpc.ts src/main/runtime/orca-runtime.ts -g '*.ts' | head -n 500
printf '%s\n' "== exact dispatchStreaming implementation =="
rg -n -C 20 'dispatchStreaming' src/main/runtime/rpc/dispatcher.ts src/main/runtime/rpc -g '*.ts' | head -n 350
printf '%s\n' "== focused streaming tests =="
rg -l 'terminal.subscribe|subscribeToTerminalData|decodeTerminalStreamFrame' src/main/runtime -g '*test.ts' | sort

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' "== terminal.subscribe handler =="
sed -n '2880,3335p' src/main/runtime/rpc/methods/terminal.ts
printf '%s\n' "== output batcher definition and timing constants =="
rg -n -C 10 'function createTerminalOutputBatcher|const createTerminalOutputBatcher|createTerminalOutputBatcher|TERMINAL_OUTPUT' src/main/runtime/rpc src/main -g '*.ts' | head -n 350
printf '%s\n' "== reconnect test full numbered section =="
sed -n '160,235p' src/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.ts

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' "== binary subscribe setup after listener registration =="
sed -n '3290,3435p' src/main/runtime/rpc/methods/terminal.ts
printf '%s\n' "== batcher implementation only =="
sed -n '176,280p' src/main/runtime/rpc/methods/terminal.ts
printf '%s\n' "== test lines with numbers =="
nl -ba src/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.ts | sed -n '175,230p'

Repository: stablyai/orca

Length of output: 9990


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' "== binary subscribe buffering finalization =="
sed -n '3430,3575p' src/main/runtime/rpc/methods/terminal.ts
printf '%s\n' "== terminal subscribe test patterns for setup/output waits =="
rg -n -C 8 'waitFor\(\(\) => \{|frames.*length|Output.*toBe|type: .subscribed|type: .data' src/main/runtime/rpc/*test.ts | head -n 450
printf '%s\n' "== relevant source and test timing facts =="
python3 - <<'PY'
from pathlib import Path
source = Path("src/main/runtime/rpc/methods/terminal.ts").read_text()
test = Path("src/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.ts").read_text()
print("batch_flush_ms:", source.split("const TERMINAL_OUTPUT_FLUSH_MS = ", 1)[1].splitlines()[0])
print("batcher_uses_timeout:", "timer = setTimeout(flush, TERMINAL_OUTPUT_FLUSH_MS)" in source)
for text in ("setTimeout(resolve, 50)", "setTimeout(resolve, 20)", "framesB.length = 0"):
    print(repr(text), "count:", test.count(text))
PY

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu
python3 - <<'PY'
from pathlib import Path
source = Path("src/main/runtime/rpc/methods/terminal.ts").read_text()
test = Path("src/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.ts").read_text()

def section(text, start, end):
    a = text.index(start)
    b = text.index(end, a)
    return text[a:b]

batcher = section(source, "function createTerminalOutputBatcher", "function ")
binary = section(source, "const unsubscribeStreamData = runtime.subscribeToTerminalData", "await streamClosed")

facts = {
    "flush_delay_ms": int(source.split("const TERMINAL_OUTPUT_FLUSH_MS = ", 1)[1].splitlines()[0]),
    "batcher_schedules_timeout": "timer = setTimeout(flush, TERMINAL_OUTPUT_FLUSH_MS)" in batcher,
    "listener_registered_while_buffering": "let buffering = true" in source and "if (buffering)" in binary,
    "buffering_ends_after_snapshot": binary.find("buffering = false") > binary.find("sendSnapshotFrames"),
    "fixed_post_listener_delays": test.count("setTimeout(resolve, 50)") + test.count("setTimeout(resolve, 20)"),
    "clears_frames_before_live_output": "framesB.length = 0\n    liveListener('before" in test,
}
for key, value in facts.items():
    print(f"{key}={value}")
assert facts["flush_delay_ms"] == 5
assert facts["batcher_schedules_timeout"]
assert facts["listener_registered_while_buffering"]
assert facts["buffering_ends_after_snapshot"]
assert facts["fixed_post_listener_delays"] == 3
PY

Repository: stablyai/orca

Length of output: 433


🏁 Script executed:

#!/bin/bash
set -eu
python3 - <<'PY'
from pathlib import Path

source = Path("src/main/runtime/rpc/methods/terminal.ts").read_text()
test = Path("src/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.ts").read_text()

batcher_start = source.index("function createTerminalOutputBatcher")
batcher_end = source.index("const REQUESTED_SNAPSHOT_BYTE_BUDGET")
batcher = source[batcher_start:batcher_end]

subscribe_start = source.index("name: 'terminal.subscribe'")
subscribe_end = source.index("name: 'terminal.unsubscribe'", subscribe_start)
subscribe = source[subscribe_start:subscribe_end]

facts = {
    "flush_delay_ms": int(source.split("const TERMINAL_OUTPUT_FLUSH_MS = ", 1)[1].splitlines()[0]),
    "batcher_schedules_timeout": "timer = setTimeout(flush, TERMINAL_OUTPUT_FLUSH_MS)" in batcher,
    "listener_registered_while_buffering": "let buffering = true" in subscribe
        and "const unsubscribeStreamData = runtime.subscribeToTerminalData" in subscribe
        and "if (buffering)" in subscribe,
    "buffering_ends_after_snapshot": subscribe.find("buffering = false") > subscribe.find("sendSnapshotFrames"),
    "fixed_delays": [
        line.strip() for line in test.splitlines()
        if "setTimeout(resolve" in line
    ],
    "clears_before_live_output": "framesB.length = 0" in test
        and "liveListener('before" in test,
}
for key, value in facts.items():
    print(f"{key}={value}")
assert facts["flush_delay_ms"] == 5
assert facts["batcher_schedules_timeout"]
assert facts["listener_registered_while_buffering"]
assert facts["buffering_ends_after_snapshot"]
assert len(facts["fixed_delays"]) == 4
assert facts["clears_before_live_output"]
PY

Repository: stablyai/orca

Length of output: 645


🏁 Script executed:

#!/bin/bash
set -eu
python3 - <<'PY'
from pathlib import Path

source = Path("src/main/runtime/rpc/methods/terminal.ts").read_text()
test = Path("src/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.ts").read_text()

assert "const TERMINAL_OUTPUT_FLUSH_MS = 5" in source
assert "timer = setTimeout(flush, TERMINAL_OUTPUT_FLUSH_MS)" in source
subscribe_start = source.index("name: 'terminal.subscribe'")
subscribe_end = source.index("name: 'terminal.unsubscribe'", subscribe_start)
subscribe = source[subscribe_start:subscribe_end]
assert subscribe.index("const unsubscribeStreamData = runtime.subscribeToTerminalData") < subscribe.index("buffering = false")
assert subscribe.index("sendSnapshotFrames") < subscribe.index("buffering = false")
delays = [line.strip() for line in test.splitlines() if "setTimeout(resolve" in line]
print("batch_flush_ms=5")
print("listener_registered_before_buffering_end=True")
print("snapshot_before_buffering_end=True")
print("fixed_delays=", delays)
assert len(delays) == 4
assert "framesB.length = 0" in test
PY

Repository: stablyai/orca

Length of output: 499


Replace fixed sleeps with condition-based waits. Wait for the second stream’s SnapshotEnd frame before clearing framesB. After each liveListener call, use vi.waitFor and assert the decoded output contains the expected payload (before\r\n or after\r\n), not only an Output opcode.

…ing registration

A terminal.subscribe teardown was keyed on `${terminal}:${clientId}`, which is
stable across reconnects. cleanupSubscription invokes whichever cleanup currently
owns that key, so after a mobile reconnect rebound the id, a late teardown from the
dead connection killed the replacement stream and the terminal froze (STA-4510).

Add registerOwnedSubscriptionCleanup, returning a registration handle whose
releaseIfCurrent no-ops once the id has been rebound, and route all 12 teardown
call sites in the three terminal.subscribe branches through it. Register-time
eviction now also targets the owner it captured rather than re-resolving the key.

terminal.unsubscribe gains the same ownership rule via connectionId, matching the
runtime.clientEvents.unsubscribe precedent: make-before-break migration sends the
unsubscribe over the old session after the new one has already rebound the id.

The teardown-by-key pattern predates the bug; #7490 made it reachable by binding
the exit-waiter to the per-socket abort signal, so every socket close now runs it.

Tests use a faithful subscription-registry double; the ad-hoc Map stubs they
replace never evicted the prior generation, which is why no test caught this.
…ul registry

streaming.test.ts and terminal-provider-snapshot-sequence.test.ts still stubbed
registerSubscriptionCleanup only, so terminal.subscribe's owned registration was
undefined and teardown never fired. Assert the registration is retired rather than
spying on cleanupSubscription, which the owned path now calls internally.
…d registry double

Review findings on this PR:

- The lease-only branch's compensating handleMobileUnsubscribe ran unconditionally
  after a rebind. Presence is keyed (ptyId, clientId) with no refcount and `closed`
  is exactly the post-rebind state, so a superseded handler deleted the replacement
  subscriber's presence. Gate it on the registration still being current. This also
  gives SubscriptionRegistration.isCurrent its production caller.

- The STA-4510 regression test hand-rolled a second registry copy that diverged from
  the shared double (no try/catch around cleanup, no in-flight join). Import the
  shared double instead, so the test proving the bug uses the same fidelity as the
  rest of the suite.

- cleanupSubscriptionIfOwnedByConnection treats an absent connectionId as authority.
  That is the connection-less local unix-socket path, not an oversight; say so.
…compensation

Review pass 2 showed the guard added in the previous commit was wrong.

registration.isCurrent() is always false whenever `closed` is true: either our own
cleanup ran, in which case cleanupSubscriptionAndWait already deleted the map entry,
or a rebind replaced it. So the guard did not distinguish the two cases — it made the
compensating handleMobileUnsubscribe unreachable, which is precisely the
resurrect-after-cleanup case that line exists to handle.

The scenario the guard was meant to fix is also not reachable: the lease-only call
passes no viewport, and both !viewport paths in handleMobileSubscribeInternal return
with no await, so the subscribe resolves in microtasks and a socket close cannot win it.

Revert the guard, and drop SubscriptionRegistration.isCurrent with it — it had no
remaining production caller and shipping unused runtime API invites exactly this.

Also from review:
- cleanupSubscriptionIfOwnedByConnection reported false for an id with no registration,
  conflating 'refused, another connection owns it' with 'already gone'. Report true.
- Note on the registry double that it mirrors production and can drift; the runtime
  tests pin real behavior, the doubles only pin routing.
…t-double parity

Review pass 3:

- The registry test double omitted production's 'unregistered id is already gone'
  early-out, so it returned refused where production returns gone. The legacy
  terminal.unsubscribe path reaches that branch with a never-registered bare id, so a
  routing test would have locked in the inverse of production.
- terminal.unsubscribe ORed the bare-id and composite results. Registrations always use
  the composite, so the bare id reported 'already gone' and masked a real ownership
  refusal: a stale connection was correctly refused but told unsubscribed: true. The
  composite answer is authoritative when we try it.
- Pin why the lease-only compensating handleMobileUnsubscribe is deliberately unguarded:
  it is safe only because that call passes no viewport and returns with no await.
- Cover the no-registration branch, which had no test.
…ardown

Review pass 4 disproved the previous commit's rationale. A clientless legacy-JSON
stream registers under the bare terminal id, not the composite, so either call in
terminal.unsubscribe can be the real teardown. Overwriting reported false after a
destructive success; the earlier OR reported true after a refusal. AND over the calls
that actually ran is the honest aggregate: false needs a genuine refusal.

Tests:
- cover the bare-id path, which the ownership tests never exercised
- pin the microtask invariant the unguarded lease-only compensation depends on. The
  first version of that test was vacuous: it raced two setTimeout(0) timers, and the
  earlier-registered one always won, so it passed with an await injected. It now drains
  microtasks only and goes red under that mutation.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/sta-4510-subscription-ownership branch from 08a2744 to 6cdefc9 Compare August 17, 2026 06:29
@coderabbitai

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@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: 60f6defd-54bb-4191-ad25-15201b54b434

📥 Commits

Reviewing files that changed from the base of the PR and between 2fdaa10 and 6cdefc9.

📒 Files selected for processing (23)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/streaming.test.ts
  • src/main/runtime/rpc/subscription-registry-test-double.ts
  • src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts
  • src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts
  • src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts
  • src/main/runtime/rpc/terminal-multiplex-input-write-rejection.test.ts
  • src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts
  • src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts
  • src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts
  • src/main/runtime/rpc/terminal-multiplex-source-range-admission.test.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-lease-only.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
🚧 Files skipped from review as they are similar to previous changes (22)
  • src/main/runtime/rpc/terminal-multiplex-source-range-admission.test.ts
  • src/main/runtime/rpc/terminal-subscribe-lease-only.test.ts
  • src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts
  • src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts
  • src/main/runtime/rpc/terminal-subscribe-blank-mount.test.ts
  • src/main/runtime/rpc/terminal-output-batching.test.ts
  • src/main/runtime/rpc/subscription-registry-test-double.ts
  • src/main/runtime/rpc/terminal-multiplex-test-harness.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/rpc/terminal-provider-snapshot-sequence.test.ts
  • src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts
  • src/main/runtime/rpc/terminal-subscribe-mount-replay.test.ts
  • src/main/runtime/rpc/streaming.test.ts
  • src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts
  • src/main/runtime/rpc/terminal-subscribe-buffer.test.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts
  • src/main/runtime/rpc/terminal-multiplex-input-write-rejection.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts
  • src/main/runtime/rpc/terminal-subscribe-ownership.test.ts

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

Comment on lines +34845 to +34848
// The stale registration must not reach the replacement that now owns the id.
oldRegistration.releaseIfCurrent()
await new Promise((resolve) => setTimeout(resolve, 0))
expect(replacementCleanup).not.toHaveBeenCalled()

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert that stale release does not invoke its captured cleanup.

Line 34846 only verifies that replacementCleanup is not called. A stale releaseIfCurrent() implementation could invoke oldCleanup again and still pass. Assert that oldCleanup remains called once after the stale release.

Proposed test change
     oldRegistration.releaseIfCurrent()
     await new Promise((resolve) => setTimeout(resolve, 0))
+    expect(oldCleanup).toHaveBeenCalledTimes(1)
     expect(replacementCleanup).not.toHaveBeenCalled()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// The stale registration must not reach the replacement that now owns the id.
oldRegistration.releaseIfCurrent()
await new Promise((resolve) => setTimeout(resolve, 0))
expect(replacementCleanup).not.toHaveBeenCalled()
// The stale registration must not reach the replacement that now owns the id.
oldRegistration.releaseIfCurrent()
await new Promise((resolve) => setTimeout(resolve, 0))
expect(oldCleanup).toHaveBeenCalledTimes(1)
expect(replacementCleanup).not.toHaveBeenCalled()

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review-loop verdict: clean / ready

Changes

No additional source changes were needed in this review loop; the reviewed and pushed head remains 6cdefc95d1. The PR makes terminal subscription teardown registration-owned: stale continuations and exit waiters release only the captured registration, registration-time replacement disposes the captured prior owner, and terminal.unsubscribe refuses teardown from a connection that no longer owns the subscription.

The private implementation-precedent review supports this shape: capture the exact owner or generation, fence late cleanup on that captured identity, and dispose the captured previous owner instead of rereading a mutable keyed slot. The resulting Orca implementation is focused, O(1), and does not change the remote wire contract, persisted state, or provider-specific behavior.

Verification

  • Full affected runtime run with the required config: src/main/runtime/rpc plus src/main/runtime/orca-runtime.test.ts — 160 files, 2,548 passed, 2 skipped.
  • All changed tests — 19 files, 1,268 passed, 1 skipped.
  • Full pnpm tc passed.
  • Direct native and type-aware lint, formatting check, max-lines ratchet, and git diff --check passed.
  • Remote head matches local head; the branch is mergeable with the two newer origin/main commits and has no synthetic-merge conflict.
  • GitHub currently reports 43 successful checks, one expected skipped E2E check, and one queued verify check.

Readiness

Opening readiness found no P0/P1 and raised one P2 candidate: the new ownership oracles are not explicitly named in config/reliability-gates.jsonc. The senior review pass and closing readiness audit both returned clean with no proven P0/P1/P2 code issue, treating that manifest inclusion as a non-blocking coverage residual rather than a defect in this focused fix. Closing review also found no security, performance/resource, backward-compatibility, cross-platform, SSH/relay, or folder-workspace regression.

QA / visual proof

There is no meaningful rendered proof for this server-side ownership race: no renderer, mobile UI, or wire-schema file changed, and a screenshot of a generic terminal would not prove that the rebound stream survives stale socket teardown. The QA agent therefore did not manufacture or upload screenshots; it ran 40 focused reconnect/ownership/subscribe/streaming tests successfully instead.

A genuine paired-device reconnect or half-open-socket run against a branch-built desktop runtime remains unverified. orca emulator could not exercise that flow in this session, so mobile QA is reported as blocked rather than substituted with unrelated UI interaction.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Mobile emulator QA — real phone client on a branch-built runtime

Verdict: blocked at the reproduction step, with a measured reason. The rig ran end to end; the negative control did not freeze, and a socket measurement shows why.

Rig

Orca Mobile dev client (JS bundle 0.0.44 built from this branch via Metro) on an iOS Simulator, LAN-paired to a runtime from pnpm dev at head 6cdefc95d1, in an isolated profile (window.api.repos.list() → [] proved on first attach). Terminal created from the phone, running an alternate-screen TUI that repaints a monotonic TICK + wall clock every second. All phone interaction via orca emulator; frames read from the emulator helper's own MJPEG stream.

1. Branch build — passes

01:39:01 TICK 6 → home (backgrounded ~88 s) → 01:40:44 foregrounded → 01:40:55 TICK 111, and 01:41:24 TICK 140. The TIME line matches the capture wall clock each time, so these are live frames, not a restored snapshot.

before
after reconnect
still advancing

2. Negative control — pre-fix build passes too

Same rig, only orca-runtime.ts and rpc/methods/terminal.ts reverted to merge base 2fdaa10fd1 (grep -c for the three new symbols → 0). 01:43:25 TICK 8 → backgrounded ~76 s → 01:45:05 TICK 102, live. It recovered exactly like the fixed build.

pre-fix before
pre-fix after reconnect

3. Four triggers, none reproduce pre-fix

Trigger Pre-fix result
background 76 s → foreground recovered, live
background 4 s → foreground recovered, live (TICK 177)
9× rapid leave/re-enter session (subscribe/unsubscribe churn on the same ${terminal}:${clientId}) recovered, live (TICK 420)
SIGSTOP the runtime 60 s, past the client's ~44 s watchdog, then SIGCONT recovered, live (TICK 557)

4. Why — the measurement

This PR guards a make-before-break race: a stale teardown from a superseded connection killing the replacement that rebound the same stable id. That needs the client to re-subscribe on a second connection while the host still holds the first. Sampling the runtime's port once per second across a full background/foreground cycle:

45 samples, every one: client_conns=1

The count never reached 2 — no overlap window — and it never dropped to 0, not even while backgrounded: on the Simulator the process keeps its TCP connection through suspension, so the client never re-dials and never re-subscribes. Backgrounding a simulator is not a reconnect.

5. Where the real proof lives

A physical iOS device (real suspension kills the socket) or the Wi-Fi → cellular handoff that connection-revival-triggers.ts treats as the make-before-break case. A silent packet drop on the runtime port would also do it, but that needs sudo pfctl on the host and was not attempted.

Read as: this run shows the branch does not regress a phone-watched TUI across app resume, and shows by measurement that the emulator cannot exercise the defect. The unit tests in this PR remain the evidence for the fix itself; the end-to-end proof should go to a physical device.

Worktree restored exactly — git diff HEAD and git diff --cached HEAD both empty, HEAD still 6cdefc95d1.

@brennanb2025
brennanb2025 merged commit 8cd3383 into main Aug 17, 2026
45 checks passed
brennanb2025 added a commit that referenced this pull request Aug 19, 2026
…#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 #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.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
…ing registration (stablyai#14992)

* fix(runtime): tear down terminal subscriptions only through their owning registration

A terminal.subscribe teardown was keyed on `${terminal}:${clientId}`, which is
stable across reconnects. cleanupSubscription invokes whichever cleanup currently
owns that key, so after a mobile reconnect rebound the id, a late teardown from the
dead connection killed the replacement stream and the terminal froze (STA-4510).

Add registerOwnedSubscriptionCleanup, returning a registration handle whose
releaseIfCurrent no-ops once the id has been rebound, and route all 12 teardown
call sites in the three terminal.subscribe branches through it. Register-time
eviction now also targets the owner it captured rather than re-resolving the key.

terminal.unsubscribe gains the same ownership rule via connectionId, matching the
runtime.clientEvents.unsubscribe precedent: make-before-break migration sends the
unsubscribe over the old session after the new one has already rebound the id.

The teardown-by-key pattern predates the bug; stablyai#7490 made it reachable by binding
the exit-waiter to the per-socket abort signal, so every socket close now runs it.

Tests use a faithful subscription-registry double; the ad-hoc Map stubs they
replace never evicted the prior generation, which is why no test caught this.

* test(runtime): migrate the remaining subscription stubs to the faithful registry

streaming.test.ts and terminal-provider-snapshot-sequence.test.ts still stubbed
registerSubscriptionCleanup only, so terminal.subscribe's owned registration was
undefined and teardown never fired. Assert the registration is retired rather than
spying on cleanupSubscription, which the owned path now calls internally.

* fix(runtime): guard the lease-only presence release and use the shared registry double

Review findings on this PR:

- The lease-only branch's compensating handleMobileUnsubscribe ran unconditionally
  after a rebind. Presence is keyed (ptyId, clientId) with no refcount and `closed`
  is exactly the post-rebind state, so a superseded handler deleted the replacement
  subscriber's presence. Gate it on the registration still being current. This also
  gives SubscriptionRegistration.isCurrent its production caller.

- The STA-4510 regression test hand-rolled a second registry copy that diverged from
  the shared double (no try/catch around cleanup, no in-flight join). Import the
  shared double instead, so the test proving the bug uses the same fidelity as the
  rest of the suite.

- cleanupSubscriptionIfOwnedByConnection treats an absent connectionId as authority.
  That is the connection-less local unix-socket path, not an oversight; say so.

* fix(runtime): drop the lease-only presence guard; it disabled a real compensation

Review pass 2 showed the guard added in the previous commit was wrong.

registration.isCurrent() is always false whenever `closed` is true: either our own
cleanup ran, in which case cleanupSubscriptionAndWait already deleted the map entry,
or a rebind replaced it. So the guard did not distinguish the two cases — it made the
compensating handleMobileUnsubscribe unreachable, which is precisely the
resurrect-after-cleanup case that line exists to handle.

The scenario the guard was meant to fix is also not reachable: the lease-only call
passes no viewport, and both !viewport paths in handleMobileSubscribeInternal return
with no await, so the subscribe resolves in microtasks and a socket close cannot win it.

Revert the guard, and drop SubscriptionRegistration.isCurrent with it — it had no
remaining production caller and shipping unused runtime API invites exactly this.

Also from review:
- cleanupSubscriptionIfOwnedByConnection reported false for an id with no registration,
  conflating 'refused, another connection owns it' with 'already gone'. Report true.
- Note on the registry double that it mirrors production and can drift; the runtime
  tests pin real behavior, the doubles only pin routing.

* fix(runtime): make the unsubscribe refusal observable and restore test-double parity

Review pass 3:

- The registry test double omitted production's 'unregistered id is already gone'
  early-out, so it returned refused where production returns gone. The legacy
  terminal.unsubscribe path reaches that branch with a never-registered bare id, so a
  routing test would have locked in the inverse of production.
- terminal.unsubscribe ORed the bare-id and composite results. Registrations always use
  the composite, so the bare id reported 'already gone' and masked a real ownership
  refusal: a stale connection was correctly refused but told unsubscribed: true. The
  composite answer is authoritative when we try it.
- Pin why the lease-only compensating handleMobileUnsubscribe is deliberately unguarded:
  it is safe only because that call passes no viewport and returns with no await.
- Cover the no-registration branch, which had no test.

* fix(runtime): report an unsubscribe refusal without masking a real teardown

Review pass 4 disproved the previous commit's rationale. A clientless legacy-JSON
stream registers under the bare terminal id, not the composite, so either call in
terminal.unsubscribe can be the real teardown. Overwriting reported false after a
destructive success; the earlier OR reported true after a refusal. AND over the calls
that actually ran is the honest aggregate: false needs a genuine refusal.

Tests:
- cover the bare-id path, which the ownership tests never exercised
- pin the microtask invariant the unguarded lease-only compensation depends on. The
  first version of that test was vacuous: it raced two setTimeout(0) timers, and the
  earlier-registered one always won, so it passed with an await injected. It now drains
  microtasks only and goes red under that mutation.
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
…ing registration (stablyai#14992)

* fix(runtime): tear down terminal subscriptions only through their owning registration

A terminal.subscribe teardown was keyed on `${terminal}:${clientId}`, which is
stable across reconnects. cleanupSubscription invokes whichever cleanup currently
owns that key, so after a mobile reconnect rebound the id, a late teardown from the
dead connection killed the replacement stream and the terminal froze (STA-4510).

Add registerOwnedSubscriptionCleanup, returning a registration handle whose
releaseIfCurrent no-ops once the id has been rebound, and route all 12 teardown
call sites in the three terminal.subscribe branches through it. Register-time
eviction now also targets the owner it captured rather than re-resolving the key.

terminal.unsubscribe gains the same ownership rule via connectionId, matching the
runtime.clientEvents.unsubscribe precedent: make-before-break migration sends the
unsubscribe over the old session after the new one has already rebound the id.

The teardown-by-key pattern predates the bug; stablyai#7490 made it reachable by binding
the exit-waiter to the per-socket abort signal, so every socket close now runs it.

Tests use a faithful subscription-registry double; the ad-hoc Map stubs they
replace never evicted the prior generation, which is why no test caught this.

* test(runtime): migrate the remaining subscription stubs to the faithful registry

streaming.test.ts and terminal-provider-snapshot-sequence.test.ts still stubbed
registerSubscriptionCleanup only, so terminal.subscribe's owned registration was
undefined and teardown never fired. Assert the registration is retired rather than
spying on cleanupSubscription, which the owned path now calls internally.

* fix(runtime): guard the lease-only presence release and use the shared registry double

Review findings on this PR:

- The lease-only branch's compensating handleMobileUnsubscribe ran unconditionally
  after a rebind. Presence is keyed (ptyId, clientId) with no refcount and `closed`
  is exactly the post-rebind state, so a superseded handler deleted the replacement
  subscriber's presence. Gate it on the registration still being current. This also
  gives SubscriptionRegistration.isCurrent its production caller.

- The STA-4510 regression test hand-rolled a second registry copy that diverged from
  the shared double (no try/catch around cleanup, no in-flight join). Import the
  shared double instead, so the test proving the bug uses the same fidelity as the
  rest of the suite.

- cleanupSubscriptionIfOwnedByConnection treats an absent connectionId as authority.
  That is the connection-less local unix-socket path, not an oversight; say so.

* fix(runtime): drop the lease-only presence guard; it disabled a real compensation

Review pass 2 showed the guard added in the previous commit was wrong.

registration.isCurrent() is always false whenever `closed` is true: either our own
cleanup ran, in which case cleanupSubscriptionAndWait already deleted the map entry,
or a rebind replaced it. So the guard did not distinguish the two cases — it made the
compensating handleMobileUnsubscribe unreachable, which is precisely the
resurrect-after-cleanup case that line exists to handle.

The scenario the guard was meant to fix is also not reachable: the lease-only call
passes no viewport, and both !viewport paths in handleMobileSubscribeInternal return
with no await, so the subscribe resolves in microtasks and a socket close cannot win it.

Revert the guard, and drop SubscriptionRegistration.isCurrent with it — it had no
remaining production caller and shipping unused runtime API invites exactly this.

Also from review:
- cleanupSubscriptionIfOwnedByConnection reported false for an id with no registration,
  conflating 'refused, another connection owns it' with 'already gone'. Report true.
- Note on the registry double that it mirrors production and can drift; the runtime
  tests pin real behavior, the doubles only pin routing.

* fix(runtime): make the unsubscribe refusal observable and restore test-double parity

Review pass 3:

- The registry test double omitted production's 'unregistered id is already gone'
  early-out, so it returned refused where production returns gone. The legacy
  terminal.unsubscribe path reaches that branch with a never-registered bare id, so a
  routing test would have locked in the inverse of production.
- terminal.unsubscribe ORed the bare-id and composite results. Registrations always use
  the composite, so the bare id reported 'already gone' and masked a real ownership
  refusal: a stale connection was correctly refused but told unsubscribed: true. The
  composite answer is authoritative when we try it.
- Pin why the lease-only compensating handleMobileUnsubscribe is deliberately unguarded:
  it is safe only because that call passes no viewport and returns with no await.
- Cover the no-registration branch, which had no test.

* fix(runtime): report an unsubscribe refusal without masking a real teardown

Review pass 4 disproved the previous commit's rationale. A clientless legacy-JSON
stream registers under the bare terminal id, not the composite, so either call in
terminal.unsubscribe can be the real teardown. Overwriting reported false after a
destructive success; the earlier OR reported true after a refusal. AND over the calls
that actually ran is the honest aggregate: false needs a genuine refusal.

Tests:
- cover the bare-id path, which the ownership tests never exercised
- pin the microtask invariant the unguarded lease-only compensation depends on. The
  first version of that test was vacuous: it raced two setTimeout(0) timers, and the
  earlier-registered one always won, so it passed with an await injected. It now drains
  microtasks only and goes red under that mutation.
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.

[Bug]: Orca Mobile terminal freezes on reconnect (stale teardown kills the rebound terminal.subscribe stream)

1 participant