Repository navigation
Conversation
…a slow link Two producer paths in the relay still destroyed a client's sink over a transiently-full write queue instead of applying PTY backpressure: - `RelayDispatcher.projectToClients` closed any subscriber whose producer queue was momentarily full, and still reported the projection as delivered, so the PTY was never paused. - The `pty.replay` branch of `notify()` routed replay to the fatal control lane, so a workspace restoring many terminals over a slow link killed the link — and reattach regenerated the same replay, looping forever. Both now back-pressure: a full queue fails the projection so the producer pauses the native PTY and republishes the memoized span on drain, and a frame no sink can ever admit is shed with one log line per generation rather than closing the connection. `RelayPtySourcePublication.publish` now pumps the source sender even when the legacy projection is rejected, so a stalled legacy mirror cannot starve the flow-controlled V1 owner's credited stream. `PtyHandler` also guards the publish window: the pty's queue is lifted out of `pendingOutputByPty` during a publish, so a capacity callback re-entering from the sink could previously let `pty.exit` overtake still-pending output. Closes #12041 Co-authored-by: Orca <[email protected]>
📝 WalkthroughWalkthroughThe relay dispatcher now uses role-aware PTY projection. Owners share backpressure capacity, while mirrors receive best-effort delivery and remain connected when frames are dropped. Replay overflow is logged without closing clients. PTY output publication continues owner delivery after legacy projection failure. PTY exits wait for active output publication and retry refused projections. Tests cover queue saturation, retries, logging, client retention, and output-before-exit ordering. 🚥 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 |
…used Review follow-up on the back-pressure change: - A refused projection pauses the PTY dispatcher-wide, and nothing else on the daemon reaps a subscriber that never drains: the writer only closes on a write *error*, and a peer that is alive but not reading never raises one. Arm a bounded reap when a projection is refused — a non-primary sink that settles zero bytes for a full 30s window is detached (it reconnects and replays) so the other viewers' terminals resume. The primary link, the one #12041 is about, still back-pressures forever. - `projectToClients` encoded the frame before filtering, so the common single-owner case (no legacy projection target at all) paid a full JSON.stringify plus two Buffer copies per span and threw them away. Co-authored-by: Orca <[email protected]>
…tall timer Co-authored-by: Orca <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/relay/dispatcher.ts (1)
538-542: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider a control-lane-specific drop message for
pty.replay.This rejection comes from the control queue.
logDroppedProducerNotificationclassifies the drop againstclient.writer.producerFrameCapacityand prints "producer queue full" or "> producer frame capacity". The line then names the wrong lane, which slows diagnosis of replay loss.An explicit reason argument keeps the existing rate limiting and reports the correct lane.
src/relay/pty-handler.ts (1)
1002-1008: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueConsider a depth counter instead of a
Setfor publish re-entrancy.
publishingOutputPtysis aSet, so it cannot represent nested publishes for the same id. IfflushPtyOutputis ever re-entered synchronously for the same id, the innerfinallydeletes the id while the outer publish is still running, andpublishPendingExitregains the window this guard closes.No synchronous re-entrant path exists today: every capacity fan-out reaches
flushPtyOutputthroughscheduleOutputFlush, which defers to a timer. AMap<string, number>depth counter would keep the guard correct if that changes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: dd9eb21e-c2e2-4d7a-a82d-cdc05f9a5726
📒 Files selected for processing (10)
src/relay/dispatcher-capacity-degradation.test.tssrc/relay/dispatcher-slow-client.test.tssrc/relay/dispatcher.tssrc/relay/pty-handler-source-publication.test.tssrc/relay/pty-handler.tssrc/relay/relay-pty-source-exit-publication.test.tssrc/relay/relay-pty-source-exit-publication.tssrc/relay/relay-pty-source-output.tssrc/relay/relay-pty-source-publication.test.tssrc/relay/relay-pty-source-publication.ts
| const ordered = writes | ||
| .map(notification) | ||
| .filter( | ||
| (frame): frame is Notification => | ||
| frame?.method === 'pty.data' || frame?.method === 'pty.exit' | ||
| ) | ||
| .map((frame) => frame.method) | ||
| expect(ordered.indexOf('pty.data')).toBeGreaterThanOrEqual(0) | ||
| expect(ordered.indexOf('pty.data')).toBeLessThan(ordered.lastIndexOf('pty.exit')) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Tighten the ordering assertion to the first pty.exit.
Line 709 compares the first pty.data against lastIndexOf('pty.exit'). If a pty.exit frame were emitted before the data frame and a second one after, the assertion would still pass. The regression under test is exactly an exit that overtakes output.
Use indexOf('pty.exit') so the assertion fails on any exit that precedes the first data frame.
💚 Proposed fix for the ordering assertion
expect(ordered.indexOf('pty.data')).toBeGreaterThanOrEqual(0)
- expect(ordered.indexOf('pty.data')).toBeLessThan(ordered.lastIndexOf('pty.exit'))
+ expect(ordered.indexOf('pty.exit')).toBeGreaterThanOrEqual(0)
+ expect(ordered.indexOf('pty.data')).toBeLessThan(ordered.indexOf('pty.exit'))📝 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.
| const ordered = writes | |
| .map(notification) | |
| .filter( | |
| (frame): frame is Notification => | |
| frame?.method === 'pty.data' || frame?.method === 'pty.exit' | |
| ) | |
| .map((frame) => frame.method) | |
| expect(ordered.indexOf('pty.data')).toBeGreaterThanOrEqual(0) | |
| expect(ordered.indexOf('pty.data')).toBeLessThan(ordered.lastIndexOf('pty.exit')) | |
| const ordered = writes | |
| .map(notification) | |
| .filter( | |
| (frame): frame is Notification => | |
| frame?.method === 'pty.data' || frame?.method === 'pty.exit' | |
| ) | |
| .map((frame) => frame.method) | |
| expect(ordered.indexOf('pty.data')).toBeGreaterThanOrEqual(0) | |
| expect(ordered.indexOf('pty.exit')).toBeGreaterThanOrEqual(0) | |
| expect(ordered.indexOf('pty.data')).toBeLessThan(ordered.indexOf('pty.exit')) |
…minal Shedding the frame left the mirror's retained leases above the relay-wide low-water mark with nothing left to release them, so `legacyRetentionBelowLowWater` never cleared, `PtyHandler.maybeResumePtyOutput` early-returned and every paused PTY on the host stayed paused forever. Trading #12041's disconnect for an unbounded global stall is strictly worse, so a mirror that cannot admit a projection is closed again (main's behaviour) and recovers by reconnecting. Owners still back-pressure — that is the actual #12041 fix. Also name the control lane in the dropped-`pty.replay` diagnostic; it was classified against the unrelated producer frame bound.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/relay/relay-pty-source-publication.test.ts (1)
327-330: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAssert delivery to unaffected clients.
The assertion at Line 330 proves that only
saturatedIddetached. It does not prove that the V1 owner or healthy subscriber received thepty.dataframe. Thepublishresult at Line 328 is also insufficient because the dispatcher returnstrueafter closing a saturated mirror when owner admission succeeds.Add write assertions for the V1 owner and healthy subscriber.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f6be19c7-1134-482f-822f-11815f53a70a
📒 Files selected for processing (4)
src/relay/dispatcher-slow-client.test.tssrc/relay/dispatcher.tssrc/relay/pty-handler-source-publication.test.tssrc/relay/relay-pty-source-publication.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/relay/dispatcher-slow-client.test.ts
Converting to draft — not ready to mergeThis targets a real, reproduced bug (#12041), but after three adversarial review rounds it still carries blocking findings. Each round's fix has surfaced another, and the current shape may be worse than the bug it fixes. CI is green (41 checks). The problem is behavioural, not a failing test. The core objectionThe change stops a saturated non-owner client from being closed, and the stall reaper was removed — so nothing evicts it. But its retained bytes still count toward the relay-wide gate Net effect: one permanently stalled subscriber can wedge every PTY for every viewer, indefinitely. Before this change the projection closed that client, which released the gate and let the relay self-heal within one frame. A reviewer reproduced this with a scratch test on the branch. Trading "one slow client disconnects sessions" for "one slow client silently wedges all terminals" is not a good trade, and it is the kind of regression that would be very hard to diagnose in the field. What I think the right shape isA saturated non-owner client must still be evicted, or have its leases released, on a bounded timeline so the relay-wide gate can clear. Keeping the pre-PR close for non-owner clients, plus a narrower fix aimed at #12041's actual trigger, is probably both smaller and safer than the current design. The reproduction and diagnosis are solid and worth keeping. I'm marking this draft rather than iterating further because the remaining work is a design decision about relay backpressure semantics that deserves a maintainer's call, not another remediation round. |
|
SSH still works: Orca connects to the host over SSH and routes workspace operations through the managed remote Orca server (orcad). These merges remove the legacy SSH relay, not SSH support. Closing as obsolete after the merged SSH relay retirement in #27214 and #27215. This PR concerns the SSH relay PTY attach, recovery, replay, or lease lifecycle. #27214 removed the desktop relay connection/fallback path; #27215 deleted the SSH relay server, deployment assets, and relay-only tests. SSH hosts now use the managed Orca server (orcad), and unsupported hosts fail explicitly, so this relay-specific work is no longer planned. This closes the proposed relay implementation; it does not claim that any independent local, WSL, or managed-server behavior was fixed. |
Summary
Two producer paths in the relay treated "this client's write queue is momentarily full" as a fatal protocol error and destroyed the client's sink. Over a high-latency SSH link (the reporter's ~268 ms Local↔VPS hop) Claude Code's full-screen redraws outrun the client's drain rate, so the bound is hit on nearly every interaction: the link dies, the app reconnects, the same output and replay are regenerated, and the loop repeats.
RelayDispatcher.projectToClients(src/relay/dispatcher.ts) calledcloseClient(..., 'Relay PTY subscriber projection capacity exceeded')wheneverpublishToClientreturned false — which happens purely for a transiently-full producer queue. It now classifies each projection target instead, via the newLegacyProjectionRole:owner— a legacy session owner (deliveryMode === 'legacy-owner'), for which the projection is the only delivery lane. This is the [Bug]: SSH disconnected between Local and VPS when trying to use claude code cli only after latest release v1.4.163 #12041 fix. A full queue now fails the whole projection, soRelayPtySourcePublication.publishreturns false,PtyHandler.flushPtyOutputpauses the native PTY, and the byte-identical memoized span is republished once the sink drains. Only a frame larger than that sink'sproducerFrameCapacityis shed, because retrying it forever would wedge the PTY.mirror— every other target: agent hooks,orcaCLI processes, a second window, a reconnecting client in the window before itspty.openClientcompletes. A mirror never back-pressures the native PTY (that keeps feat(ssh): bound relay PTY output end to end #11005's per-client isolation), but a mirror that cannot admit a frame it is offered is still closed, exactly as onmain. See "Why a mirror is closed rather than shed" below — an earlier revision of this branch shed the frame instead and that turned [Bug]: SSH disconnected between Local and VPS when trying to use claude code cli only after latest release v1.4.163 #12041's disconnect into a permanent, relay-wide stall.projectToClientsreturns before the mirror loop runs, so a saturated mirror is not visited on that frame.)projectPtyExitToLegacyClientsfollows the same rule: held for retry for an owner, close for a saturated mirror, so no pane is left rendering a process that already exited.pty.replaybranch ofnotify()deliberately routed replay to thecontrollane, where overflow closes the writer. WithREPLAY_BUFFER_MAXat 100 KiB per PTY and a workspace restoring many terminals, the cumulative undrained replays blew the 1 MiB control bound and destroyed the connection — and reattach regenerated the very same replays. It now enqueues withcontrolOverflow: 'reject'and logs a single dropped-replay line naming the control lane; the pane restores without scrollback and live output repaints it.Two supporting changes keep the new backpressure from breaking neighbouring guarantees:
RelayPtySourcePublication.publishnow callssender.pump(record)even when the legacy projection is rejected. The span is already in the source ledger, so without this a stalled legacy owner would freeze the flow-controlled V1 owner's credited send loop — exactly the isolation feat(ssh): bound relay PTY output end to end #11005 built the source lane for.PtyHandlertracks the ptys currently inside a publish.flushPendingOutputlifts a pty's queue out ofpendingOutputByPtyand drains a captured copy, so during the publish the map is transiently empty; a capacity callback re-entering from the sink would read "no pending output" and letpty.exitovertake a span that is about to be re-queued.publishPendingExitnow also checks the in-publish set.The exact error string the reporter quoted (
Relay response exceeds the bounded 2097152-byte legacy lane) came fromsendResponsein v1.4.163 and was already removed by #11999; only the two paths above survived onmain.Why a mirror is closed rather than shed
A revision of this branch shed the frame for a saturated mirror and closed nobody. That is a worse bug than #12041, and it was reproduced before being reverted:
LegacyRelayPublicationLedgerlease per target, released only when that sink settles the write. A mirror that never drains holds up toLEGACY_CLIENT_RETAINED_BYTES_HIGH(2 MiB), well above the 1 MiBLEGACY_CLIENT_RETAINED_BYTES_LOWmark.RelayDispatcher.legacyRetentionBelowLowWaterispublicationLedger.belowLowWater(activeClientKeys()), so one such mirror pins it tofalsefor the whole relay.PtyHandler.maybeResumePtyOutput(src/relay/pty-handler.ts:1172) early-returns while that gate isfalse, and line 1184 holds the onlypty.resume()call in the handler. So every paused PTY on the host — including terminals with a perfectly healthy owner — stayed paused forever, andnotifyLegacyCapacity(false)never fired.DispatcherClientWriter.handleWriteSettlementnever fires, and the stall timer this branch briefly had was correctly deleted for judging healthy peers.Closing bounds it on the frame the mirror is offered and cannot admit:
closeClientreleases every queued and in-flight entry (DispatcherClientWriter.close→releaseEntry→ the lease'srelease), drops the client key out ofactiveClientKeys(), and forces a capacity fan-out — so the relay recovers on that frame. The mirror reconnects and reopens the pty, which replays it. Regression test:dispatcher-slow-client.test.ts→ "releases the relay-wide legacy gate when a mirror can never drain".This is where the branch is still wrong, and why it is a draft. Recovery is conditional on another frame actually being projected to that mirror, and two reachable states prevent that:
false, every PTY is paused and produces no output, so no projection is generated and nothing evicts the client that is holding the gate down (the mirror loop atsrc/relay/dispatcher.ts:1185is only reached from a live projection).tryNotifyPtyDataToClient, agent-hook notifies, responses), andprojectToClientsreturns atsrc/relay/dispatcher.ts:1177whenever an owner back-pressures — so the mirror loop that would close it never runs on those frames.Both leave a saturated non-owner attached with up to 2 MiB of retained leases and no bounded path to release them. See the AI Review Report.
Scope against #12041
Issue #12041 reports two problems. This PR targets Problem 2 only (the Claude Code session dropping into a reconnect loop on any interaction), and only the close-instead-of-backpressure class of it. It does not fix Problem 1 (the Claude Code prompt input auto-indenting / inserting line breaks on its own), which is an input-path regression the reporter explicitly filed as separate and which nothing here touches. #12041 therefore stays open for Problem 1 — this PR is deliberately not marked
Closes #12041. It is also not merge-ready for Problem 2 in its current shape.Relates to #12041.
ELI5
Your terminal on the server can produce text much faster than a slow internet connection can carry it. When the outgoing pipe filled up, the server decided something had gone badly wrong and hung up the connection. Reconnecting made the server resend all the same text, which filled the pipe again, which hung up again — a loop you can't escape. Now, if the pipe belongs to the window that owns the terminal, the server just pauses the terminal for a moment and waits for the pipe to empty instead of hanging up. A bystander watcher (a second window, a CLI tool, a hook) that has completely stopped reading is dropped the next time the server tries to send it something, because leaving it attached would freeze every terminal on the machine. The unfinished part: if all the terminals are already paused because of that watcher, the server never tries to send it anything again, so it never gets dropped and the terminals stay frozen. That is the open objection.
Fix proof
The pre-fix behaviour is the behaviour the pre-existing tests this PR changes used to assert:
dispatcher-capacity-degradation.test.ts"closes the client when pty.replay overflows the control queue" assertedprimary.closes === 1onmain— that is the replay path killing a link the reconnect would immediately regenerate.projectToClientsonmainclosed every target that could not admit the frame, session owner included; that is the line the newownerrole replaces.The new permanent regression suite is
src/relay/dispatcher-slow-client.test.ts. Re-run for this description on the PR head (macOS,npx vitest run --config config/vitest.config.ts src/relay/dispatcher-slow-client.test.ts):Three of those twelve fail against the previous revision of this branch (
9dad5c75b, the one that shed a mirror's frame and closed nobody):and so do the two neighbouring suites that assert the same contract end to end — re-verified by running the three suites against
9dad5c75b's sources:Tests 5 failed | 36 passed (41).No test covers the two states in "Why a mirror is closed rather than shed" where no frame is ever projected to the saturated mirror; those are open findings B1/B2, not proven-fixed cases.
No test regressions
Whole relay suite (contains every file touched, plus
dispatcher.test.ts,dispatcher-capacity-degradation.test.ts,dispatcher-client-writer.test.ts,dispatcher-frame-guard-regressions.test.ts,pty-handler*.test.ts,relay-pty-source-*.test.ts,legacy-relay-publication-ledger.test.tsand the two backpressure integration suites):Every suite outside
src/relaythat imports the relay dispatcher or pty handler:pnpm run typecheck:node,typecheck:cli,typecheck:web,oxlint, the native-plugin and type-aware oxlint configs with--deny-warnings, andcheck:max-lines-ratchetare all clean, and PR CI is green (41 passed, 1 skipped). Green tests do not clear this branch — the open findings are behavioural states no suite exercises.Pre-existing tests that encoded the old behaviour and were deliberately changed:
dispatcher-capacity-degradation.test.ts"closes the client when pty.replay overflows the control queue" -> now asserts no close plus exactly one[relay] Dropped pty.replay (…B, control queue full)line.Tests that were changed by an earlier revision of this branch and have been restored to their
mainassertions, because that revision's shed-instead-of-close is the wedge described above:pty-handler-source-publication.test.ts"keeps the native PTY and V1 owner live when one subscriber saturates" — the saturated subscriber is detached; the native PTY is not paused; the healthy mirror and the V1 owner are served.relay-pty-source-publication.test.ts"detaches only a saturated subscriber while the V1 owner stays live".dispatcher-capacity-degradation.test.ts"still closes on protocol-critical control queue overflow" stays green:notifyClientkeeps the defaultclose-client.Trade-offs
legacy-owner(a client that completedpty.openClientas session owner but withoutoutputFlowControl) has no second delivery lane, so a full queue there pauses the native PTY until it drains — and becauselegacyRetentionBelowLowWateris a relay-wide aggregate, that pause is shared by other PTYs on the host. That is the same all-or-nothing contracttryNotifyPtyData— the non-source path used for every PTY without a V1 consumer session — has always had onmain. It is not reliably bounded:handleLegacyCapacityresumes on drain, and a socket that errors is closed byDispatcherClientWriter.handleWriteSettlement(or detached by thesock.on('close')handler inrelay.ts), but a peer that simply stops reading — a zero-window TCP receiver, a suspended VM — never errors and is never evicted. Narrowing the aggregate to per-PTY scope is a separate change and is deliberately not attempted here. This is open finding B3.main, but no longer unconditional in timing — see B1/B2). An agent hook ororcaCLI process that stops reading loses its relay connection and reconnects. That is not the failure [Bug]: SSH disconnected between Local and VPS when trying to use claude code cli only after latest release v1.4.163 #12041 reports — the reporter's client is the session owner — and the alternative (unconditional shedding) provably wedges every terminal on the host.producerFrameCapacityis shed, not retried. Untransformed spans are pre-sized bymaxLegacyPtyDataCharsso this is only reachable for a transformed ingress emission. Retrying is impossible (it can never be admitted) and closing produces the [Bug]: SSH disconnected between Local and VPS when trying to use claude code cli only after latest release v1.4.163 #12041 loop verbatim: reconnect, replay, regenerate the same oversized frame, close. It is logged once per method per client generation.pty.replaythe control queue cannot admit is dropped, so that pane restores without scrollback until new output repaints it. Only reachable by clients older than feat(ssh): persist and auto-restore SSH sessions across app restarts #1026 — every current client passessuppressReplayNotification: trueand takes the response path instead.There is deliberately no timer that reaps a stalled peer. An earlier revision of this branch had one; it judged a peer by "retains producer bytes and settled nothing since arming", which is true of any socket that merely has a frame in flight, and its single global one-shot timer could judge a freshly-armed peer over as little as 1 ms. Closing a healthy client is precisely the disconnect #12041 is about, so the mechanism was removed rather than tuned —
dispatcher-slow-client.test.ts→ "never closes a peer that is merely mid-write while another target back-pressures" locks that in. Removing it without replacing it is the gap: with eviction event-driven on a projected frame, a client that is never offered another frame is never evicted, so nothing bounds the ledger on a timeline. A correctly-scoped bounded release (or per-PTY gate scoping) is the design decision this draft is waiting on.Cross-platform
All edits are in the host-side relay bundle: plain Node, no Electron, no DOM, no keyboard handling or accelerators, no
metaKey, no filesystem paths, no shell invocation, no git subcommand (so the Git 2.25 baseline andGitCapabilityCacherules do not apply) and no provider-specific surface, so GitHub/GitLab parity is untouched. Behaviour changes identically for macOS, Linux and Windows clients and for native, WSL and SSH hosts — the reporter's Windows-client/Linux-VPS pairing sits inside that matrix. All of it was only executed on macOS (see limitations).One platform-adjacent detail the fix depends on and that is already handled:
producerFrameCapacityderives from the sink'swritableHighWaterMark(src/relay/dispatcher-writer-sink.ts), which differs between a Windows named-pipe stdout, a POSIX pipe and a forwarded socket. The shed branch keys off that per-sink value rather than a constant, and an infinite or unknown high-water mark falls back toMAX_SAFE_INTEGER, so the shed path is never taken spuriously.SSH-remote is the primary case, not an afterthought: the defect only manifests when the client drains slower than the host produces, and reconnect is explicitly in scope —
setWritebuilds a fresh writer with an empty queue, and during the window before the reconnected client completespty.openClientit is classifiedsubscriber, so it is amirror; reaching a mirror close from that fresh, empty queue requires 2 MiB of undrainedpty.datainside a singleopenClientround trip.Folder workspaces vs git worktrees are irrelevant here: nothing inspects repositories, worktrees or git state; this is per-PTY output routing only.
Performance
Slightly positive on the hot path.
projectToClientspreviously re-encoded the frame once per target client (it calledpublishToClientwithout the already-existingestimatedBytesargument); it now encodes once and threads the size through both that argument and the new optionalestimatedBytesparameter ontryPublishToClients, and still returns before encoding at all when there is no projection target (the norm — a flow-controlled owner is excluded from the mirror). Added cost is one classifier call per client per frame (a map lookup that the previousmatchesClientpredicate already did) plus oneSet.add/Set.deleteper publish inPtyHandler.sender.pumpon the rejected path early-returns on its existing activating/sending/turnScheduled/restoreRequired/rotationPending guards when there is nothing to do. Thepty.replaychange removes work (no second enqueue attempt). No timers, polling, IPC or renders are added. Steady state on a healthy link is byte-identical. The pathological state in the open findings is not a throughput cost but a full stop: paused PTYs produce nothing.Security
No change. No IPC surface added or altered, no command execution, no path handling, no authentication or authorization logic touched, and no wire-format change —
pty.replaystill travels on the control lane, only its overflow disposition changed. The only new observable output is a stderr diagnostic that logs a method name and byte count, both already logged by the neighbouringlogDroppedProducerNotificationcallers, and is rate-limited to one line per method per drop reason per client generation with a 64-key cap (DROPPED_NOTIFICATION_LOG_KEY_LIMIT). The owner/mirror split reads the existingSshPtyConsumerSessionAdapter.deliveryModegrant, so it cannot grant a client any capability it did not already hold.Availability is a different matter: the open findings are a denial-of-service-shaped failure mode (one non-reading local or remote peer stalling every terminal on the host), which is part of why this is a draft.
Honest limitations
mainand no longer does for a session owner. The exact string the reporter quoted was already fixed by fix(ssh, relay): keep remote sessions alive through reconnects and backpressure #11999 before this PR, so I cannot prove these two paths were the only remaining trigger for their session.legacy-ownergating other PTYs through the relay-widelegacyRetentionBelowLowWateraggregate — is pre-existing onmainand is not fixed here.AI Review Report
Reviewed by independent subagents in a loop across two hostile lenses — correctness/regressions and cross-platform + remote + performance.
Round 1 raised two findings, both confirmed and both addressed:
src/relay/dispatcher-projection-stall.ts— the stall window is a single global one-shot timer, and thestalledprobe is true for any sink with an un-settled frame in flight, so a healthy peer could be judged over ~1 ms and closed. Confirmed. The file was deleted; the projection path owns no timer. (Deleting it without a bounded replacement is what left findings B1–B3 open.)src/relay/dispatcher.ts— the all-or-nothing projection lets a single saturated non-owner client pause the native PTY for every viewer, reverting feat(ssh): bound relay PTY output end to end #11005's per-client isolation. Confirmed. Addressed by theowner/mirrorsplit: only a session owner can back-pressure.Round 2 declared the branch clean. That verdict was wrong, and round 3 found why:
src/relay/dispatcher.ts— the round-2 fix for the second finding shed a mirror's frame instead of closing it, and the stall reaper had been deleted, so nothing evicted a saturated mirror at all. Its retained ledger leases pinnedlegacyRetentionBelowLowWatertofalse,PtyHandler.maybeResumePtyOutputearly-returned, and every paused PTY on the host stayed paused forever. Confirmed by reproduction against both revisions (the pre-PR code recovers because it closes the mirror; the shed revision never recovers). Addressed by restoring the close for mirrors only — see "Why a mirror is closed rather than shed" — and locked in by a regression test that asserts the relay-wide gate clears. The restoration is only partial; see B1/B2.src/relay/dispatcher.ts— the dropped-pty.replaydiagnostic was classified againstproducerFrameCapacity, but the rejection comes from the control lane, so the one line an operator gets for silent scrollback loss named the wrong limit. Confirmed and fixed.logDroppedProducerNotificationnow takes the lane and printscontrol queue full.Open blocking findings (why this is a draft)
src/relay/dispatcher.ts:1185) runs only inside a live projection. Once that mirror's retained leases holdlegacyRetentionBelowLowWaterfalse,PtyHandler.maybeResumePtyOutput(src/relay/pty-handler.ts:1172) early-returns and line 1184 — the onlypty.resume()in the handler — never fires, so every paused PTY produces nothing, so no projection is generated, so the client is never evicted. Self-sustaining wedge of every PTY for every viewer.src/relay/dispatcher.ts:1177returns false as soon as any owner cannot admit the frame, so a mirror saturated via a non-projection path (tryNotifyPtyDataToClient, agent-hook notifies, responses) is not visited and not closed while an owner is back-pressured — and its retained bytes are exactly what keeps the relay-wide gate closed for that owner's PTY too.legacy-owneris never evicted at all, and gates the whole relay. Trade-off 1. A peer that stops reading without erroring never reacheshandleWriteSettlement, so nothing bounds how long it holdslegacyRetentionBelowLowWaterfalse for every other PTY on the host. Pre-existing onmainfortryNotifyPtyData, but this PR extends the same all-or-nothing contract to the projection path, so it is now reachable from more places.The shape the reviewer proposes: a saturated non-owner must be evicted, or have its leases released, on a bounded timeline so the relay-wide gate can clear — or the gate must be narrowed from a relay-wide aggregate to per-PTY scope. Keeping the pre-PR close for non-owner clients plus a narrower fix aimed at #12041's actual trigger is probably both smaller and safer than the current design. That is a maintainer's call on relay backpressure semantics, not another remediation round.
Non-blocking note
LegacyProjectionRoleandlegacyProjectionRoleboth carry doc comments; the shortfall is in the untouched neighbours the check samples.Made with Orca 🐋