Repository navigation
fix(runtime): tear down terminal subscriptions only through their owning registration - #14992
Conversation
📝 WalkthroughWalkthroughThe 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 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)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
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
byConnectionrarely drops the connection key.
cleanupSubscriptionretires an entry only after its cleanup promise resolves. The loop is synchronous, soset.sizeis still non-zero at Line 153 for every asynchronously retired id. The check therefore almost never fires.removeIndexstill 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 winReplace the fixed
flush()delay withvi.waitForfor the positive assertions.
flushwaits 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.waitForis 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 winUse 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()withcreateSubscriptionRegistryDouble()from./subscription-registry-test-double.src/main/runtime/orca-runtime.ts (1)
13737-13755: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winDescribe the return value as cleanup initiation.
cleanupSubscriptionstartscleanupSubscriptionAndWaitwithout awaiting it. Therefore,truereports that cleanup was requested for an authorized owner, not that teardown completed. Update the docstring. Keep the unconditional no-connectionIdbehavior 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
📒 Files selected for processing (21)
src/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/terminal.tssrc/main/runtime/rpc/subscription-registry-test-double.tssrc/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.tssrc/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.tssrc/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.tssrc/main/runtime/rpc/terminal-multiplex-input-write-rejection.test.tssrc/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.tssrc/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.tssrc/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.tssrc/main/runtime/rpc/terminal-multiplex-source-range-admission.test.tssrc/main/runtime/rpc/terminal-multiplex-test-harness.tssrc/main/runtime/rpc/terminal-output-batching.test.tssrc/main/runtime/rpc/terminal-subscribe-blank-mount.test.tssrc/main/runtime/rpc/terminal-subscribe-buffer.test.tssrc/main/runtime/rpc/terminal-subscribe-lease-only.test.tssrc/main/runtime/rpc/terminal-subscribe-mount-replay.test.tssrc/main/runtime/rpc/terminal-subscribe-ownership.test.tssrc/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.tssrc/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.
| 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) |
There was a problem hiding this comment.
🩺 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 400Repository: 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' | sortRepository: 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.tsRepository: 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))
PYRepository: 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
PYRepository: 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"]
PYRepository: 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
PYRepository: 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.
08a2744 to
6cdefc9
Compare
|
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. |
There was a problem hiding this comment.
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
📒 Files selected for processing (23)
src/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/terminal.tssrc/main/runtime/rpc/streaming.test.tssrc/main/runtime/rpc/subscription-registry-test-double.tssrc/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.tssrc/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.tssrc/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.tssrc/main/runtime/rpc/terminal-multiplex-input-write-rejection.test.tssrc/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.tssrc/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.tssrc/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.tssrc/main/runtime/rpc/terminal-multiplex-source-range-admission.test.tssrc/main/runtime/rpc/terminal-multiplex-test-harness.tssrc/main/runtime/rpc/terminal-output-batching.test.tssrc/main/runtime/rpc/terminal-provider-snapshot-sequence.test.tssrc/main/runtime/rpc/terminal-subscribe-blank-mount.test.tssrc/main/runtime/rpc/terminal-subscribe-buffer.test.tssrc/main/runtime/rpc/terminal-subscribe-lease-only.test.tssrc/main/runtime/rpc/terminal-subscribe-mount-replay.test.tssrc/main/runtime/rpc/terminal-subscribe-ownership.test.tssrc/main/runtime/rpc/terminal-subscribe-reconnect-rebind.test.tssrc/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.
| // 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() |
There was a problem hiding this comment.
🎯 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.
| // 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() |
Review-loop verdict: clean / readyChangesNo additional source changes were needed in this review loop; the reviewed and pushed head remains 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
ReadinessOpening readiness found no P0/P1 and raised one P2 candidate: the new ownership oracles are not explicitly named in QA / visual proofThere 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. |
Mobile emulator QA — real phone client on a branch-built runtimeVerdict: 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. RigOrca Mobile dev client (JS bundle 0.0.44 built from this branch via Metro) on an iOS Simulator, LAN-paired to a runtime from 1. Branch build — passes
2. Negative control — pre-fix build passes tooSame rig, only 3. Four triggers, none reproduce pre-fix
4. Why — the measurementThis 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: 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 livesA physical iOS device (real suspension kills the socket) or the Wi-Fi → cellular handoff that 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 — |
…#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.
…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.
…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.
…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.
…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.
…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.





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 downterminal-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 aSubscriptionRegistrationhandle.releaseIfCurrent()no-ops once the id has been rebound to a newer subscriber. The existingregisterSubscriptionCleanupis untouched, so the seven other feature areas that use it are unaffected.cleanupOwnedSubscription(id, expectedCleanup)does a synchronous ownership check and then delegates tocleanupSubscriptionAndWait, preserving the in-flight join, the retain-on-failure, and theretrySubscriptionCleanupAftercontract rather than bypassing them.terminal.subscribebranches now route through the handle. Six are exit-waiter settlements; the other six are stale async continuations (a subscribe/snapshot resuming after a rebind).terminal.unsubscribegains the same rule viaconnectionId, matching theruntime.clientEvents.unsubscribeprecedent (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.subscribekeys teardown on${terminal}:${clientId}.clientIdis the paired device token, stable for the install, and the mobile client re-sendsterminal.subscribeon every reconnect with no preceding unsubscribe — so the same key legitimately changes owner.cleanupSubscriptionAndWaitthen 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
.catchfires on every socket close, which is exactly the reconnect path. Before that it could only fire onterminal_handle_stale/timeout, where teardown is correct. Notably #7490's own description explains that the multiplex branch is safe because of itsstreams.get(streamId) !== streamidentity 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.unsubscribeis 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 sendsterminal.unsubscribeover 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.tsdrives the realRpcDispatcherandTERMINAL_METHODSthrough the binary-stream branch (the one carrying mobile TUI traffic) against a faithful port of the runtime subscription registry, and modelswaitForTerminal'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:
orca-runtime.test.ts— "releases an owned subscription only while its registration still owns the id"orca-runtime.test.ts— "refuses an unsubscribe from a connection that no longer owns"releaseIfCurrent()reverted to keyed teardownterminal-subscribe-ownership.test.ts— stale-connection caseThis 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
Mapstubs in 14 test files with a shared faithfulcreateSubscriptionRegistryDouble(). 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 tcexit 0;oxfmt+oxlintclean.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
Notes
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.pty.dataflow control. That RCA is falsified: mobile never speaks the relay pty protocol (zero hits forpty.ackData/outputFlowControlundermobile/), and the relay credit ledger defers rather than drops. Worth retitling so the next reader does not re-derive it.terminal-subscribe-buffer.test.tspreviously 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 emitsend, 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.terminal.unsubscribe. Its regression test never reaches the binary-stream branch — its params setmobileInputLeaseOnly: 1, so the handler returns from the lease-only branch first.handleMobileUnsubscribeon the registration still being current. Review showed that predicate is always false whenclosedis 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!viewportpaths return with noawait. Reverted; fix(runtime): keep a superseded lease-only subscribe from releasing live mobile presence #14993 closed.SubscriptionRegistrationexposes onlyreleaseIfCurrent().Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)Author