Skip to content

Keep the SSH connection alive when a terminal outruns a slow link - #12220

Closed
nwparker wants to merge 5 commits into
mainfrom
nwparker/bugbash-12041
Closed

nwparker wants to merge 5 commits into
mainfrom
nwparker/bugbash-12041

Conversation

@nwparker

@nwparker nwparker commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Draft — not ready to merge

Three adversarial review rounds each fixed a finding and surfaced another, and three blocking findings are still open (see the conversion comment and the AI Review Report at the bottom). CI is green — 41 checks pass, 1 skipped — so the objection is behavioural, not a failing test.

Short version: eviction of a saturated non-owner client is event-driven on a projected frame, but the condition that makes eviction necessary (its retained bytes hold legacyRetentionBelowLowWater false) is also the condition that stops PTYs resuming and therefore stops projections being produced. src/relay/pty-handler.ts:1184 is the only pty.resume() in the handler and it sits behind that relay-wide gate. So a permanently stalled subscriber can wedge every PTY for every viewer with nothing on a bounded timeline to release it. The reproduction and diagnosis below are solid and worth keeping; the remaining work is a design decision about relay backpressure semantics.

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) called closeClient(..., 'Relay PTY subscriber projection capacity exceeded') whenever publishToClient returned false — which happens purely for a transiently-full producer queue. It now classifies each projection target instead, via the new LegacyProjectionRole:
    • 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, so RelayPtySourcePublication.publish returns false, PtyHandler.flushPtyOutput pauses the native PTY, and the byte-identical memoized span is republished once the sink drains. Only a frame larger than that sink's producerFrameCapacity is shed, because retrying it forever would wedge the PTY.
    • mirror — every other target: agent hooks, orca CLI processes, a second window, a reconnecting client in the window before its pty.openClient completes. 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 on main. 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.
    • Mirrors are published only after the owners commit, so a back-pressured span that is later retried never reaches a mirror twice. (This ordering is also part of open finding B2 below: when an owner back-pressures, projectToClients returns before the mirror loop runs, so a saturated mirror is not visited on that frame.)
    • projectPtyExitToLegacyClients follows 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.
  • The pty.replay branch of notify() deliberately routed replay to the control lane, where overflow closes the writer. With REPLAY_BUFFER_MAX at 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 with controlOverflow: '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.publish now calls sender.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.
  • PtyHandler tracks the ptys currently inside a publish. flushPendingOutput lifts a pty's queue out of pendingOutputByPty and 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 let pty.exit overtake a span that is about to be re-queued. publishPendingExit now also checks the in-publish set.

The exact error string the reporter quoted (Relay response exceeds the bounded 2097152-byte legacy lane) came from sendResponse in v1.4.163 and was already removed by #11999; only the two paths above survived on main.

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:

  • Every projected frame reserves a LegacyRelayPublicationLedger lease per target, released only when that sink settles the write. A mirror that never drains holds up to LEGACY_CLIENT_RETAINED_BYTES_HIGH (2 MiB), well above the 1 MiB LEGACY_CLIENT_RETAINED_BYTES_LOW mark.
  • RelayDispatcher.legacyRetentionBelowLowWater is publicationLedger.belowLowWater(activeClientKeys()), so one such mirror pins it to false for the whole relay.
  • PtyHandler.maybeResumePtyOutput (src/relay/pty-handler.ts:1172) early-returns while that gate is false, and line 1184 holds the only pty.resume() call in the handler. So every paused PTY on the host — including terminals with a perfectly healthy owner — stayed paused forever, and notifyLegacyCapacity(false) never fired.
  • With shedding, nothing else evicted that client: it never errors (it just does not read), so DispatcherClientWriter.handleWriteSettlement never 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: closeClient releases every queued and in-flight entry (DispatcherClientWriter.close → releaseEntry → the lease's release), drops the client key out of activeClientKeys(), 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:

  • If the relay-wide gate is already 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 at src/relay/dispatcher.ts:1185 is only reached from a live projection).
  • A mirror's producer queue can also fill from non-projection paths (tryNotifyPtyDataToClient, agent-hook notifies, responses), and projectToClients returns at src/relay/dispatcher.ts:1177 whenever 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" asserted primary.closes === 1 on main — that is the replay path killing a link the reconnect would immediately regenerate.
  • projectToClients on main closed every target that could not admit the frame, session owner included; that is the line the new owner role 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):

 Test Files  1 passed (1)
      Tests  12 passed (12)

Three of those twelve fail against the previous revision of this branch (9dad5c75b, the one that shed a mirror's frame and closed nobody):

 × closes a saturated mirror instead of pausing the PTY for every other viewer
 × releases the relay-wide legacy gate when a mirror can never drain
     AssertionError: expected false to be true   (dispatcher.legacyRetentionBelowLowWater)
 × logs one dropped-replay line per generation however many panes are stranded

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

 × relay-pty-source-publication.test.ts   > detaches only a saturated subscriber while the V1 owner stays live
 × pty-handler-source-publication.test.ts > keeps the native PTY and V1 owner live when one subscriber saturates

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.ts and the two backpressure integration suites):

 Test Files  103 passed (103)
      Tests  1232 passed (1232)

Every suite outside src/relay that imports the relay dispatcher or pty handler:

 src/main/plugins/plugin-host-conformance.test.ts
 src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
 src/main/agent-hooks/wsl-hook-relay-manager.test.ts
 Test Files  3 passed (3)
      Tests  36 passed (36)

pnpm run typecheck:node, typecheck:cli, typecheck:web, oxlint, the native-plugin and type-aware oxlint configs with --deny-warnings, and check:max-lines-ratchet are 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 main assertions, 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: notifyClient keeps the default close-client.

Trade-offs

  1. A session owner still back-pressures every viewer, and its retention still gates the relay. A legacy-owner (a client that completed pty.openClient as session owner but without outputFlowControl) has no second delivery lane, so a full queue there pauses the native PTY until it drains — and because legacyRetentionBelowLowWater is a relay-wide aggregate, that pause is shared by other PTYs on the host. That is the same all-or-nothing contract tryNotifyPtyData — the non-source path used for every PTY without a V1 consumer session — has always had on main. It is not reliably bounded: handleLegacyCapacity resumes on drain, and a socket that errors is closed by DispatcherClientWriter.handleWriteSettlement (or detached by the sock.on('close') handler in relay.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.
  2. A saturated bystander is disconnected on the next frame projected to it (same disposition as main, but no longer unconditional in timing — see B1/B2). An agent hook or orca CLI 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.
  3. A frame larger than the owner sink's producerFrameCapacity is shed, not retried. Untransformed spans are pre-sized by maxLegacyPtyDataChars so 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.
  4. A pty.replay the 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 passes suppressReplayNotification: true and 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 and GitCapabilityCache rules 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: producerFrameCapacity derives from the sink's writableHighWaterMark (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 to MAX_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 — setWrite builds a fresh writer with an empty queue, and during the window before the reconnected client completes pty.openClient it is classified subscriber, so it is a mirror; reaching a mirror close from that fresh, empty queue requires 2 MiB of undrained pty.data inside a single openClient round 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. projectToClients previously re-encoded the frame once per target client (it called publishToClient without the already-existing estimatedBytes argument); it now encodes once and threads the size through both that argument and the new optional estimatedBytes parameter on tryPublishToClients, 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 previous matchesClient predicate already did) plus one Set.add/Set.delete per publish in PtyHandler.

sender.pump on the rejected path early-returns on its existing activating/sending/turnScheduled/restoreRequired/rotationPending guards when there is nothing to do. The pty.replay change 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.replay still 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 neighbouring logDroppedProducerNotification callers, 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 existing SshPtyConsumerSessionAdapter.deliveryMode grant, 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

AI Review Report

Reviewed by independent subagents in a loop across two hostile lenses — correctness/regressions and cross-platform + remote + performance.

  • Review loop count: 3 round(s)
  • Final verdict: OUTSTANDING FINDINGS — DRAFT, NOT READY. 3 blocking findings open, 1 non-blocking note recorded.

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 the stalled probe 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 the owner / mirror split: 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 pinned legacyRetentionBelowLowWater to false, PtyHandler.maybeResumePtyOutput early-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.replay diagnostic was classified against producerFrameCapacity, 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. logDroppedProducerNotification now takes the lane and prints control queue full.

Open blocking findings (why this is a draft)

  • B1 — a saturated mirror is only evicted if another frame is projected to it. The mirror loop that closes it (src/relay/dispatcher.ts:1185) runs only inside a live projection. Once that mirror's retained leases hold legacyRetentionBelowLowWater false, PtyHandler.maybeResumePtyOutput (src/relay/pty-handler.ts:1172) early-returns and line 1184 — the only pty.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.
  • B2 — the owner back-pressure path returns before the mirror loop. src/relay/dispatcher.ts:1177 returns 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.
  • B3 — a stalled legacy-owner is never evicted at all, and gates the whole relay. Trade-off 1. A peer that stops reading without erroring never reaches handleWriteSettlement, so nothing bounds how long it holds legacyRetentionBelowLowWater false for every other PTY on the host. Pre-existing on main for tryNotifyPtyData, 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

  • CodeRabbit pre-merge check: docstring coverage 20.00% against an 80.00% threshold. Not blocking — the new exported LegacyProjectionRole and legacyProjectionRole both carry doc comments; the shortfall is in the untouched neighbours the check samples.

Made with Orca 🐋

…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]>
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: keeping SSH terminal sessions alive when slow clients cannot drain output quickly.
Description check ✅ Passed The description covers the change, testing, review findings, cross-platform scope, security, trade-offs, limitations, and explicitly states that the PR is draft.
✨ 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.

…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]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/relay/dispatcher.ts (1)

538-542: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider a control-lane-specific drop message for pty.replay.

This rejection comes from the control queue. logDroppedProducerNotification classifies the drop against client.writer.producerFrameCapacity and 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 value

Consider a depth counter instead of a Set for publish re-entrancy.

publishingOutputPtys is a Set, so it cannot represent nested publishes for the same id. If flushPtyOutput is ever re-entered synchronously for the same id, the inner finally deletes the id while the outer publish is still running, and publishPendingExit regains the window this guard closes.

No synchronous re-entrant path exists today: every capacity fan-out reaches flushPtyOutput through scheduleOutputFlush, which defers to a timer. A Map<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

📥 Commits

Reviewing files that changed from the base of the PR and between c9a37f5 and 9dad5c7.

📒 Files selected for processing (10)
  • src/relay/dispatcher-capacity-degradation.test.ts
  • src/relay/dispatcher-slow-client.test.ts
  • src/relay/dispatcher.ts
  • src/relay/pty-handler-source-publication.test.ts
  • src/relay/pty-handler.ts
  • src/relay/relay-pty-source-exit-publication.test.ts
  • src/relay/relay-pty-source-exit-publication.ts
  • src/relay/relay-pty-source-output.ts
  • src/relay/relay-pty-source-publication.test.ts
  • src/relay/relay-pty-source-publication.ts

Comment on lines +701 to +709
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'))

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

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.

Suggested change
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/relay/relay-pty-source-publication.test.ts (1)

327-330: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert delivery to unaffected clients.

The assertion at Line 330 proves that only saturatedId detached. It does not prove that the V1 owner or healthy subscriber received the pty.data frame. The publish result at Line 328 is also insufficient because the dispatcher returns true after 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9dad5c7 and 79e08df.

📒 Files selected for processing (4)
  • src/relay/dispatcher-slow-client.test.ts
  • src/relay/dispatcher.ts
  • src/relay/pty-handler-source-publication.test.ts
  • src/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

@nwparker

nwparker commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Converting to draft — not ready to merge

This 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 objection

The 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 legacyRetentionBelowLowWater, so notifyLegacyCapacity(false) never fires and PtyHandler.maybeResumePtyOutput early-returns. Line 1184 is the only pty.resume() call in the handler.

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 is

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

@nwparker
nwparker marked this pull request as draft August 3, 2026 09:00
@OrcaWin

OrcaWin commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

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.

@OrcaWin OrcaWin closed this Oct 11, 2026
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.

2 participants