Repository navigation
feat(ssh): bound relay PTY output end to end - #11005
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a design plan for bounded SSH relay PTY output backpressure, and implements it end-to-end: bounded frame decoding and multiplexer/writer backpressure, relay-side PTY source-credit ledgers/scheduling/publication and consumer-session adapter, main-process bounded output intake with legacy projection ledger, model admission, source obligations/coordinator, remote source-range consumers, and ACK coalescing, provider/notification-routing changes for source activation and recovery, SSH relay session recovery/reattach orchestration with a new per-target source-credit rollout module, deploy/launcher credential-file plumbing, runtime terminal-multiplex source-range ledger support, renderer ACK negotiation, shared contracts/validation, settings UI and persistence for the per-target opt-in, updated reliability gates, and new unit/integration/e2e tests. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
📝 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: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 17daf58b-f58c-441f-ada1-48b27facaaca
📒 Files selected for processing (1)
docs/plans/2026-07-27-ssh-relay-pty-backpressure.md
a7c6e40 to
e13c740
Compare
161b173 to
118d1b4
Compare
|
Too many files changed for review. ( Bypass the limit by tagging |
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: f4c2b48b-3a2c-44ab-8bde-38e5516af145
📥 Commits
Reviewing files that changed from the base of the PR and between a7c6e40 and 118d1b4e445a2e3db3007a45d53fd0beb63756b2.
📒 Files selected for processing (4)
config/reliability-gates.jsoncdocs/plans/2026-07-27-ssh-relay-pty-backpressure.mdsrc/main/agent-hooks/wsl-hook-relay-sentinel.test.tssrc/main/agent-hooks/wsl-hook-relay-sentinel.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- docs/plans/2026-07-27-ssh-relay-pty-backpressure.md
118d1b4 to
db167ea
Compare
There was a problem hiding this comment.
Actionable comments posted: 17
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts (1)
903-924: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winUse encoded source-frame bytes for source-range ACKs, not JSON payload size.
TerminalSourceRangeLedgerresolves ACK settlement againstencodedEndByte, which is the byte count passed throughprepareAccept/accept. ForOutputSpan, that count should match the encoded frame bytes admitted by the server, notframe.payload.byteLength; accumulating rawspan.rawLengthand the JSON frame bytes separately will misalignsourceAckedEndBytewith the server-side ACK watermark.
🟡 Minor comments (11)
src/relay/relay.ts-170-182 (1)
170-182: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winWrap the credential read so a missing/unreadable file yields the intended error.
readFileSyncthrows a rawENOENT/EACCESbefore theuncaughtException/unhandledRejectionhandlers are installed later inmain, so startup fails with an opaque stack instead of the "missing or invalid" message this function is clearly trying to produce.🛡️ Proposed fix
- const credential = readFileSync(credentialFile, 'utf8').trim() + let credential: string + try { + credential = readFileSync(credentialFile, 'utf8').trim() + } catch { + throw new Error('Relay endpoint credential is missing or invalid') + }src/relay/pty-source-credit-record.ts-205-234 (1)
205-234: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winMutate
oldonly after the replacement is fully built.Lines 218-222 advance
old.sentEndSu/ clearold.attemptedEndSubefore the span reconstruction at Lines 226-229, which can still throw (sliceAtSourceStartrejects an indivisible span whose start precedesacceptedSourceEndSu). On that throwRelayPtySourceCreditLedger.rotateaborts with the old record left mutated and no replacement registered, so the delivery's checkpoint bookkeeping is silently corrupted. Building the spans first keeps rotation atomic.🛡️ Proposed reordering
- if (acceptedSourceEndSu > old.sentEndSu) { - old.sentEndSu = acceptedSourceEndSu - old.sentBoundaries.add(acceptedSourceEndSu) - } - old.attemptedEndSu = null const replacement = createDeliveryRecord(newIdentity, windowSu, acceptedSourceEndSu) replacement.state = old.state === 'sealed-unsettled' ? 'sealed-unsettled' : 'active' replacement.receivedEndSu = old.receivedEndSu replacement.spans = old.spans .filter((span) => span.sourceEndSu > acceptedSourceEndSu) .map((span) => sliceAtSourceStart(span, Math.max(span.sourceStartSu, acceptedSourceEndSu))) .map((span) => Object.freeze({ ...span, ...replacement.identity })) replacement.retainedDataBytes = replacement.spans.reduce( (bytes, span) => bytes + chargedPtyRetainedStringBytes(span.data), 0 ) + if (acceptedSourceEndSu > old.sentEndSu) { + old.sentEndSu = acceptedSourceEndSu + old.sentBoundaries.add(acceptedSourceEndSu) + } + old.attemptedEndSu = null return replacementsrc/main/ipc/ssh-pty-output-intake.ts-138-160 (1)
138-160: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winRelease the
modelsource obligation on model-admission failure.The projection transfer settles the
desktopconsumer, but afterreceipt.then(...).catch(...)the source span’smodelobligation remains outstanding inssh_exit_delivery_canceled, because that branch skipscloseProviderand the source generation is only closed via the exit deadline. Add cancellation-path cleanup that settles/closes themodelobligation forsourceReservationbefore rethrowing.src/main/ipc/ssh-pty-output-intake.test.ts-514-596 (1)
514-596: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winThese two exit-deadline tests race the wall clock.
exitBarrierMs: 1withexitCancellationProofMs: 10/100on real timers makes the outcome depend on how fast the event loop turns. On a loaded CI runner the 100ms proof window in the second test can elapse beforecancelSourceDeliverysettles, flippingexpect(closeProvider).not.toHaveBeenCalled(). Considervi.useFakeTimers()with explicitadvanceTimersByTimeAsync, or widen the proof window well beyond scheduling jitter.src/main/ipc/ssh-pty-output-intake-registry.ts-54-56 (1)
54-56: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winPublisher maps are never pruned on generation close.
closeSshPtyOutputGenerationtears down intake state for a generation but leaves that generation's entries insourceAckPublishers/sourceCancellationPublishers. If a session ends without its uninstaller running (crash, error path between install and cleanup), the closures — and everything they capture, including the SSH session — stay referenced for the process lifetime, one entry per generation.🧹 Suggested cleanup
export function closeSshPtyOutputGeneration(providerGeneration: number, reason: string): void { installedIntake?.closeGeneration(providerGeneration, reason) + sourceAckPublishers.delete(providerGeneration) + sourceCancellationPublishers.delete(providerGeneration) }src/main/ipc/pty.test.ts-11517-11527 (1)
11517-11527: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winThese negative assertions can't fail the way the test name implies.
Data for
source-credit-ptyis injected throughacceptSshPtyOutputData, never throughprovider.emitData, sopauseProducer('source-credit-pty')could never be called regardless of whether the bounded source-credit path is wired at all — the test would still pass ifruntime.acceptPtyDataBoundedwere never invoked. Line 11527'snot.toHaveBeenCalledWith('unrelated-pty')is unconditionally true since no such PTY exists.Add a positive assertion that the bounded lane actually ran, so the test fails if the wiring regresses:
💚 Suggested strengthening
expect(getPtyRendererDeliveryDebugSnapshot()).toMatchObject({ pendingPtyCount: 1, pendingChars: 0 }) + expect(runtime.acceptPtyDataBounded).toHaveBeenCalledTimes(17) expect(provider.pauseProducer).not.toHaveBeenCalledWith('source-credit-pty') expect(provider.resumeProducer).not.toHaveBeenCalledWith('source-credit-pty')src/shared/pty-source-credit-validation.ts-28-46 (1)
28-46: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winValidate emitted text against the display range.
A transformed span can pass with
data: "x"and a much largerdisplayEnd - displayStart. That publishes source metadata that cannot describe the delivered output, breaking downstream range/ACK accounting. Requiredatato be a string and require its length to equal the display interval.Proposed fix
export function assertPtySourceSpan(span: PtySourceSpan): void { assertPtySourceIdentity(span) + if (typeof span.data !== 'string') { + throw new Error('PTY source span data must be a string') + } if (!span.spanId) { throw new Error('spanId is required') } @@ if (!span.transform.transformed && span.data.length !== span.transform.rawLengthSu) { throw new Error('Untransformed PTY source span length is invalid') } + if (span.data.length !== span.displayEnd - span.displayStart) { + throw new Error('PTY source span display length is invalid') + }config/reliability-gates.jsonc-3117-3154 (1)
3117-3154: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winRegister the two new multiplexer transport tests in this gate.
src/main/ssh/ssh-channel-multiplexer-backpressure.test.tsandsrc/main/ssh/ssh-channel-multiplexer-settlement.test.tsare added by this cohort (decoder pause/resume, ordered dispatch across continuations, write-settlement semantics) but appear in neithercommandsnortestFiles, so the gate can pass without exercising them. The related invariant text at Line 3106 explicitly covers writer settlement and read pause/resume.🧪 Suggested registration
- "pnpm exec vitest run --config config/vitest.config.ts src/shared/pty-consumer-session.test.ts src/main/ipc/ssh-pty-output-intake.test.ts src/main/ipc/ssh-pty-remote-source-range-consumers.test.ts src/main/runtime/rpc/terminal-multiplex.test.ts src/main/ssh/ssh-multiplexer-transport-writer.test.ts src/main/ssh/ssh-channel-multiplexer.test.ts src/main/ssh/ssh-pty-source-credit-rollout.test.ts src/main/ssh/ssh-relay-deploy.test.ts src/relay/dispatcher-client-writer.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/shared/pty-consumer-session.test.ts src/main/ipc/ssh-pty-output-intake.test.ts src/main/ipc/ssh-pty-remote-source-range-consumers.test.ts src/main/runtime/rpc/terminal-multiplex.test.ts src/main/ssh/ssh-multiplexer-transport-writer.test.ts src/main/ssh/ssh-channel-multiplexer.test.ts src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts src/main/ssh/ssh-channel-multiplexer-settlement.test.ts src/main/ssh/ssh-pty-source-credit-rollout.test.ts src/main/ssh/ssh-relay-deploy.test.ts src/relay/dispatcher-client-writer.test.ts --reporter=dot",Add the matching
testFilesentries (and anassertionRefsblock describing them as deterministic transport coverage, not live evidence).src/main/ssh/ssh-multiplexer-transport-writer.ts-147-188 (1)
147-188: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winA drain observed during an accepted write can leave the writer stuck saturated.
handleDraindefers todrainObservedDuringWritewheneverwritingis true, but that flag is only consulted on theaccepted === falsebranch. If a drain lands during a write that returnstrue— e.g. the liveness bypass at Line 92 issued whilesaturatedis already true — the saturation flag is never cleared and no furtherdrainwill be emitted, sopump()never resumes the queued lanes. The hostile-transport test atssh-multiplexer-transport-writer.test.tsLines 193-219 exercises the synchronous-drain shape but only on thewrite(false)path.🐛 Proposed fix
if (accepted === false) { if (!this.transport.onDrain) { throw new Error('Multiplexer transport returned write(false) without drain support') } this.setSaturated(!this.drainObservedDuringWrite) if (this.transport.supportsWriteSettlement !== true && this.saturated) { this.settleOnDrain.add(entry) } else if (this.transport.supportsWriteSettlement !== true) { this.handleWriteSettlement(entry, { ok: true }) } - } else if (this.transport.supportsWriteSettlement !== true) { - this.handleWriteSettlement(entry, { ok: true }) + } else { + if (this.drainObservedDuringWrite) { + this.handleDrain() + } + if (this.transport.supportsWriteSettlement !== true) { + this.handleWriteSettlement(entry, { ok: true }) + } }src/relay/dispatcher.ts-408-411 (1)
408-411: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
pty.replayadmission failure is silently dropped.Every other branch in
notifycloses the client when publication capacity is exceeded, but thepty.replaypath ignores theenqueueFrameboolean. If the control lane is at its bound, the client loses replay content with no error and no reconnect signal — the terminal just shows a gap. Either close the client on failure or surface it to the caller.🐛 Proposed fix
if (method === 'pty.replay') { - this.enqueueFrame(client, msg, 'control') + if (!this.enqueueFrame(client, msg, 'control')) { + this.closeClient( + client, + new Error('Relay replay publication capacity exceeded'), + client !== this.primaryClient + ) + } continue }src/relay/relay-frame-decoder.ts-53-66 (1)
53-66: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winCopy non-Buffer frames before retaining them.
Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)keeps the Uint8Array backing store alive inthis.chunks, so a caller that reuses a recycled read buffer can corrupt data still queued for continuation. Since frames are retained across scheduled turns, copy this path instead of sharing the caller’s buffer.
🧹 Nitpick comments (36)
src/relay/relay-pty-source-send-scheduler.ts (1)
76-96: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win
rotationPendinghas no self-release path.
waitForPendingSendlatchesrecord.rotationPending = trueand onlyreleaseRotationFence(driven by a subsequentactivatecall) clears it. Any caller that awaits the fence but doesn't reachactivateleaves the delivery permanently unpumpable. TodayPtyHandler.attachalways callsactivate, so this is a contract constraint rather than a live bug — worth a one-line comment on the method documenting that callers must always follow up withactivate.src/relay/relay.ts (1)
278-281: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winUnbounded
waitForIdleon socket close can hang the bridge process.Exit was previously immediate on
close; now it depends on the writer settling. If stdout is wedged (peer gone, no drain, no write callback),--connectnever exits and the relay's grace window doesn't start. Consider racing a short timeout.♻️ Suggested guard
sock.on('close', async () => { - await stdoutWriter.waitForIdle() + await Promise.race([ + stdoutWriter.waitForIdle(), + new Promise((resolve) => setTimeout(resolve, 2_000).unref?.()) + ]) process.exit(0) })src/relay/ssh-pty-consumer-session-adapter.ts (1)
76-96: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
sourceCreditEnableddefaults totrue, inverting the rollout gate for any caller that omits it.The feature is meant to be off unless
--pty-source-credit-v1/ORCA_SSH_PTY_SOURCE_CREDIT_V1is latched.relay.tspasses the flag explicitly, but the default makes every other construction site (tests, future callers) advertiseoutputFlowControlcapabilities. Defaulting tofalsekeeps the fail-safe direction aligned with the gate.src/relay/pty-handler.ts (1)
1052-1066: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueDon’t gate source-credit output resumes on the legacy retention ledger.
legacyRetentionBelowLowWateronly checks legacy client retention, while source-credit delivery usessourcePublication/onCreditAvailable. If this path must never resume source-credit-only PTYs despite source capacity, add a one-line note; otherwise gate resume bysourcePublicationavailability/capacity.src/relay/pty-source-replay-index.ts (1)
133-138: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win
output.read()on every append makes retention accounting O(n) per span.
read()materializes the whole retained buffer just to obtain its length, andevictUnmappedPrefixruns on eachappend. On a hot PTY output path with many small spans this degrades to quadratic work plus large transient string allocations.Prefer tracking retained length directly (or exposing a
length/sizeaccessor onRecentPtyOutputBuffer) instead of reading the full buffer.src/relay/ssh-pty-source-credit-adapter.ts (1)
166-181: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider surfacing non-stale ACK rejections.
The blanket
catchtreats a protocol-violating ACK (e.g. an in-frame cumulative boundary) identically to a benign stale one, so peer bugs on this path are invisible. A debug-level log or a counter would make flow-control regressions diagnosable without changing behavior.src/main/ipc/ssh-pty-remote-source-range-consumers.ts (2)
14-18: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCentralize the
remote:consumer-id encoding.The prefix is constructed in three places (
remoteConsumerId,requiredConsumers, and thetrackSpanmembership test). A single primitive taking a bareconsumerIdkeeps the wire format in one spot and letsremoteConsumerIddelegate to it.♻️ Proposed refactor
+function remoteConsumerIdFor(consumerId: string): SshPtySourceConsumerId { + return `remote:${consumerId}` +} + function remoteConsumerId( identity: RemoteTerminalSourceRangeStreamIdentity ): SshPtySourceConsumerId { - return `remote:${identity.consumerId}` + return remoteConsumerIdFor(identity.consumerId) }requiredConsumers(ptyId: string): readonly SshPtySourceConsumerId[] { return Object.freeze( - Array.from(this.consumersByPty.get(ptyId)?.keys() ?? []).map( - (consumerId) => `remote:${consumerId}` as const - ) + Array.from(this.consumersByPty.get(ptyId)?.keys() ?? []).map(remoteConsumerIdFor) ) }for (const [consumerId, state] of this.consumersByPty.get(ptyId) ?? []) { - if (requiredConsumers.includes(`remote:${consumerId}`)) { + if (requiredConsumers.includes(remoteConsumerIdFor(consumerId))) {Also applies to: 58-64, 75-76
236-239: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRedundant union in
spanIds.The second term is filtered to spans already in
state.spans, so it can never contribute an id beyondstate.spans.keys(). Either drop it or, if the intent was to restrict cancellation to the suppliedrangeswhen non-empty, make that explicit — as written therangesargument has no effect on which spans are canceled.♻️ Simplification
- const spanIds = new Set([ - ...state.spans.keys(), - ...uniqueSpanIds(ranges).filter((spanId) => state.spans.has(spanId)) - ]) + const spanIds = new Set(state.spans.keys())src/relay/pty-source-credit-ledger.ts (1)
120-162: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify the reservation-length resolution.
After the
=== nullearly return,reservedLengthSuisnumber | undefined, so the??fallback at Line 146 is the only path that usesMath.min(remainingWindowSu, maxSourceSu). ReadingreservedLengthSutwice for that obscures intent; also consider hoisting the16 * 1024default into a named constant next to the scheduler'sPTY_SOURCE_SCHEDULER_MAX_SU.♻️ Suggested clarification
- const reservedLengthSu = reservedPtySourceSendLength(record, remainingWindowSu, maxSourceSu) - if (reservedLengthSu === null) { - return null - } - const available = reservedLengthSu ?? Math.min(remainingWindowSu, maxSourceSu) + const reservedLengthSu = reservedPtySourceSendLength(record, remainingWindowSu, maxSourceSu) + if (reservedLengthSu === null) { + return null + } + // undefined => no reserved ACK boundary; fall back to the full available window. + const available = reservedLengthSu === undefined + ? Math.min(remainingWindowSu, maxSourceSu) + : reservedLengthSusrc/relay/pty-source-credit-record.ts (1)
134-148: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMove the
endOffset > 0guard ahead of thecharCodeAtreads.
trailing/followingare read before the bounds guard; withmaxSourceSu === 0this reads index-1. Harmless today (NaNcomparisons short-circuit and the throw at Line 146 catches it) but the guard placement is misleading.src/relay/relay-handshake.ts (1)
144-151: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winCompare the endpoint credential in constant time.
!==on the shared secret leaks length/prefix timing. The exposure is limited (each mismatch destroys the socket, transport is SSH-tunneled), buttimingSafeEqualover hashed buffers is cheap here and avoids the question entirely.🔒️ Proposed fix
+import { createHash, timingSafeEqual } from 'node:crypto' + +function sameCredential(expected: string, received: string | undefined): boolean { + const digest = (value: string): Buffer => createHash('sha256').update(value, 'utf8').digest() + return received !== undefined && timingSafeEqual(digest(expected), digest(received)) +}- if ( - endpointCredential !== undefined && - ('endpointCredential' in msg ? msg.endpointCredential : undefined) !== endpointCredential - ) { + if ( + endpointCredential !== undefined && + !sameCredential(endpointCredential, 'endpointCredential' in msg ? msg.endpointCredential : undefined) + ) {src/relay/relay-pty-source-recovery-completion.ts (1)
5-16: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse
onceSinkSettlementinstead of redefining it.
relay-pty-source-send-scheduleralready exportsonceSinkSettlementwith identical semantics (it's imported bysrc/relay/relay-pty-source-exit-publication.ts). Dropping this local copy keeps one settle-once contract.♻️ Proposed change
-import type { RelayDispatcher, SinkWriteSettlement } from './dispatcher' -import type { RelayPtySourceDeliveryRecord } from './relay-pty-source-send-scheduler' +import type { RelayDispatcher } from './dispatcher' +import { + onceSinkSettlement, + type RelayPtySourceDeliveryRecord +} from './relay-pty-source-send-scheduler' import type { SshPtyConsumerSessionAdapter } from './ssh-pty-consumer-session-adapter' - -function onceSettlement( - callback: (result: SinkWriteSettlement) => void -): (result: SinkWriteSettlement) => void { - let settled = false - return (result) => { - if (settled) { - return - } - settled = true - callback(result) - } -}- const settle = onceSettlement((result) => { + const settle = onceSinkSettlement((result) => {Check for an import cycle first —
relay-pty-source-send-schedulerimports this module.src/main/ipc/ssh-pty-model-admission-limits.ts (1)
31-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDerive global low watermarks from the resolved highs.
perPtyLow*correctly derives from the resolved high values, butglobalLow*fall back to absolute constants. A caller that lowers onlyglobalHighBytes(e.g. to 16 MiB) ends up withglobalLowBytes(48 MiB) above the high mark, soisBelowGlobalLowWatermark()inssh-pty-model-admission.tsis always true and global resume gating silently disappears.♻️ Proposed fix
+ const globalHighSourceUnits = options.globalHighSourceUnits ?? DEFAULT_GLOBAL_HIGH_SOURCE_UNITS + const globalHighBytes = options.globalHighBytes ?? DEFAULT_GLOBAL_HIGH_BYTES return { perPtyHighSourceUnits, perPtyHighBytes, perPtyLowSourceUnits: options.perPtyLowSourceUnits ?? Math.floor(perPtyHighSourceUnits / 2), perPtyLowBytes: options.perPtyLowBytes ?? Math.floor(perPtyHighBytes / 2), - globalHighSourceUnits: options.globalHighSourceUnits ?? DEFAULT_GLOBAL_HIGH_SOURCE_UNITS, - globalHighBytes: options.globalHighBytes ?? DEFAULT_GLOBAL_HIGH_BYTES, - globalLowSourceUnits: options.globalLowSourceUnits ?? 8 * 1024 * 1024, - globalLowBytes: options.globalLowBytes ?? 48 * 1024 * 1024, + globalHighSourceUnits, + globalHighBytes, + globalLowSourceUnits: + options.globalLowSourceUnits ?? Math.min(8 * 1024 * 1024, Math.floor(globalHighSourceUnits / 2)), + globalLowBytes: options.globalLowBytes ?? Math.min(48 * 1024 * 1024, Math.floor(globalHighBytes / 2)),src/main/ipc/ssh-pty-model-admission-pressure.ts (1)
140-144: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winProvider-hook error handling is asymmetric and silent.
resume()swallows everyresumeProviderfailure with a barecatch {}(no log, no metric), whilepauseProviderat Line 54 is unguarded — a throw there escapesadmit()into theaccept()promise executor and rejects the frame instead of taking the intended pressure/close path. Consider guardingpauseProvider(treat a throw as "not paused") and at least logging in theresumecatch.src/main/ipc/ssh-pty-legacy-projection-publication.ts (1)
60-99: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winNotify after state mutation.
onSettledat Line 85 runs beforerecord.settledAccountingis advanced and before reclamation; a throwing or re-entrant callback leaves the record half-settled. Move the callback after the counters are updated (and afterreclaimProjectionRecord, or collect callbacks and fire them at the end).src/main/ipc/ssh-pty-source-ack-coalescer.ts (1)
91-111: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winNo watchdog if
publishnever settles.Once
inFlightis set,requestFlushshort-circuits and every subsequent ACK stays pending indefinitely if the transport'sonSettledis never invoked (dropped channel, swallowed callback). Since ACKs gate source credit, that stalls the whole PTY stream rather than failing fast. Consider a settle deadline that fails the batch so members can retry.src/main/ipc/ssh-pty-source-obligation-coordinator.test.ts (1)
119-136: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider covering
whenTerminalrejection on dispose/closeGeneration.
disposeandcloseGenerationreject outstanding terminal waiters; without a test, an accidental regression there surfaces as unhandled promise rejections in production rather than a failing spec.src/main/ipc/ssh-pty-output-intake-contract.ts (1)
28-36: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the source-span shape into one exported type.
This inline
sourceobject is structurally identical to thesourcefield ofSshPtyLegacyProjectionLedger.reserve(...)args (src/main/ipc/ssh-pty-legacy-projection.tslines 62-70). Since the intake forwards the event'ssourcestraight intoreserve, the two can silently diverge (e.g. a new field added on one side only) without a type error.♻️ Suggested shared type
+export type SshPtySourceSpanRef = Readonly<{ + relayPtyId?: string + spanId: string + clientGeneration: number + ownerGeneration: number + deliveryToken: string + sourceStartSu: number + sourceEndSu: number +}> + export type SshPtyOutputDataEvent = Readonly<{ id: string data: string providerGeneration: number ptyIncarnation: string rawLength: number transformed: boolean sequence?: number - source?: Readonly<{ - relayPtyId?: string - spanId: string - clientGeneration: number - ownerGeneration: number - deliveryToken: string - sourceStartSu: number - sourceEndSu: number - }> + source?: SshPtySourceSpanRef }>Then have
reserve'ssourcereference the same type.src/main/ipc/pty.ts (1)
3139-3159: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMove
hasPtyDeliveryPauseAdapter,providerGeneration, andcloseOutputIntakeonto the provider contract.These three inline structural casts bypass the type system: a rename on the SSH provider silently degrades to a no-op pause, an unmatched generation, or a skipped intake close, with no compile error. Declaring them as optional members on
IPtyProvider(or the SSH provider contract added in this stack) keeps the capability checks honest.src/main/ipc/ssh.test.ts (2)
352-356: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse
createRelayLaunchResult()here.This inline fixture duplicates the helper at Line 296-300 — this diff had to add
serverBuildIdto both, which is exactly the drift the helper exists to prevent.♻️ Proposed fix
- mockDeployAndLaunchRelay.mockReset().mockResolvedValue({ - transport: { write: vi.fn(), onData: vi.fn(), onClose: vi.fn() }, - platform: 'linux-x64', - serverBuildId: relayBuildId - }) + mockDeployAndLaunchRelay.mockReset().mockResolvedValue(createRelayLaunchResult())
1549-1554: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winThese assertions don't prove the refresh.
mockAcceptSshPtyOutputData/Exitare not cleared between the first and second window in this test, sotoHaveBeenCalledWithis satisfied by calls made before the refresh. The renderer assertion below is correctly scoped tosecondWindow, but the output-authority half — the thing the renamed title now claims to cover — is not.Use
toHaveBeenLastCalledWith, or clear the intake mocks after the first window's activity and before re-injecting.src/main/providers/ssh-pty-session-reattach.ts (1)
157-169: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate activation-equality helper.
sameSourceActivationhere is field-for-field identical tosameReceivingActivationinsrc/main/providers/ssh-pty-notification-routing.ts(Lines 193-205). Since both compare the sharedPtySourceReceivingActivationcontract, exporting a single helper fromsrc/shared/pty-source-receiving-activation.tskeeps the two staleness/identity checks from drifting if the contract gains a field.src/main/runtime/rpc/terminal-source-range-ledger.test.ts (1)
226-233: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAssert the connection cap via the exported constant.
Line 233 hardcodes
16 * 1024 * 1024, which silently duplicatesTERMINAL_SOURCE_RANGE_CONNECTION_MAX_BYTESfromterminal-source-range-registry.ts. Referencing the constant (or8 * TERMINAL_SOURCE_RANGE_STREAM_MAX_BYTES) also makes the "8 saturated streams fill the connection budget" assumption of this test explicit.src/main/runtime/rpc/terminal-multiplex.test.ts (1)
142-160: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReuse
sendDesktopSourceRangeSubscribefor the inline subscribe frames.The exact same
Subscribeframe withcapabilities: { ackOutput: 1, ackOutputSourceRanges: 1 }is rebuilt inline at Lines 330-344, 456-470, 559-573, and 618-632 despite the helper existing at Line 142.Also applies to: 330-344
src/main/runtime/rpc/terminal-output-frame-source-ranges.test.ts (1)
80-95: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a case that actually exercises the indivisible-split throw.
This test only covers the early-return path where the whole range passes through untouched. The
terminal_source_range_indivisible_spliterror atterminal-output-frame-chunks.tsLine 193 (a non-splittable range straddling a chunk boundary) is currently untested.src/main/ssh/ssh-relay-session-incarnation.test.ts (1)
19-26: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueIntake-registry mock factories drifted from the module's export surface. Both suites stub
../ipc/ssh-pty-output-intake-registrywithoutinstallSshPtySourceCancellationPublisherandapplySshPtySourceCancellationProof, whichssh-relay-session.tsnow imports; they pass only because neither suite negotiatesoutputFlowControl.
src/main/ssh/ssh-relay-session-incarnation.test.ts#L19-L26: add both stubs to the factory, matchingssh-relay-session-recovery-races.test.ts.src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts#L19-L26: add the same two stubs.src/main/ssh/ssh-relay-session.ts (1)
844-850: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value
(error as { code?: unknown }).codethrows if a nullish value is rejected.
openSshPtyConsumerSessionrejecting withundefined/null(e.g. from a mock or areject()with no arg) turns the recovery-retry path into aTypeErrorthat masks the original failure.🛡️ Suggested guard
- if ( - !previousOwner || - (error as { code?: unknown }).code !== PTY_CONSUMER_STALE_OWNER_RECOVERY_ERROR - ) { + if ( + !previousOwner || + (error as { code?: unknown } | null | undefined)?.code !== + PTY_CONSUMER_STALE_OWNER_RECOVERY_ERROR + ) { throw error }src/main/ssh/ssh-relay-session.test.ts (1)
23-26: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the stale mocked
SSHC_PTY_SOURCE_WINDOW_SUexport.
ssh-relay-session.tsimports and passesDEFAULT_PTY_SOURCE_WINDOW_SUfromsrc/shared/pty-source-credit-contract.ts, andSSH_PTY_SOURCE_WINDOW_SUis no longer consumed elsewhere, so this export can be removed from thevi.mockfixture.src/main/runtime/rpc/methods/terminal.ts (1)
1908-1914: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winNon-
acceptedledger results are dropped without a trace.A stale/mismatched
streamGenerationor rejected ack silently stops replenishing the window, which is indistinguishable from an idle stream during debugging. A log or stream error on the rejected branch would make the stall diagnosable.src/main/ssh/relay-frame-decoder.ts (1)
8-9: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSplit the comma-chained
export constinto separate declarations.
FRAME_DECODER_MAX_TURN_MS = 4,reads like a stray trailing comma and hides a second exported constant on the continuation line.♻️ Proposed change
-export const FRAME_DECODER_MAX_TURN_MS = 4, - FRAME_DECODER_MAX_RETAINED_BYTES = MAX_MESSAGE_SIZE + HEADER_LENGTH + 1024 * 1024 +export const FRAME_DECODER_MAX_TURN_MS = 4 +export const FRAME_DECODER_MAX_RETAINED_BYTES = + MAX_MESSAGE_SIZE + HEADER_LENGTH + 1024 * 1024src/main/ssh/ssh-channel-multiplexer-settlement.test.ts (1)
54-69: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDispose the multiplexer at the end of this test.
The constructor starts a
setIntervalhealth timer and these tests use real timers, so this case leaves a live interval (plus its transport closure) behind for the rest of the run. The other cases either dispose explicitly or are disposed by the failure path.🧹 Proposed cleanup
expect(settled).toHaveBeenCalledOnce() expect(settled).toHaveBeenCalledWith({ ok: true }) + mux.dispose() })src/main/ssh/ssh-channel-multiplexer.ts (1)
550-575: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winConsider bounding how long
writerSaturatedmay suppress dead-link detection.
decoderReadPausedself-clears on the next scheduler turn, butwriterSaturatedonly clears on a transportdrain. Against a black-hole peer whose send buffer stays full, the health check returns early on every tick, so the mux never declares the link dead and never triggers reconnect until the OS socket layer eventually errors out (which can be many minutes). A saturation-start timestamp with a generous grace window would keep the false-death fix while retaining an upper bound.src/main/ssh/ssh-multiplexer-transport-writer.ts (1)
221-252: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueFold the
livenesslane into the control accounting explicitly.
retain/release/admissionErrorall treatlivenessas "not ordinary" and therefore charge it tocontrolBytes/controlFrames, which is correct but only implicitly. An explicit lane→bucket mapping helper would make the reserve semantics obvious and prevent a future fourth lane from silently landing in the control reserve.src/main/ssh/relay-protocol-backpressure.test.ts (1)
161-189: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSuite diverges from the relay copy: missing the oversized-payload resync case.
src/relay/protocol-backpressure.test.tsadditionally covers "resynchronizes after an oversized payload across bounded discard turns" (multi-turn discard + subsequent valid frame). Since both decoders are duplicated implementations kept in lockstep, mirroring that case here would keep the SSH-side decoder honest about incremental discard across scheduled turns.src/relay/dispatcher.ts (1)
190-216: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winBinary search fully encodes the frame on every probe.
estimateFrameBytescallsencodeJsonRpcFrame, which serializes and allocates the whole frame. For a 128 KiB PTY chunk this is ~17 full serializations per call on the output hot path. Since the only variable part is the JSON-escapeddataslice, consider computing the empty-frame byte cost once (asproducerDataBudgetalready does) and deriving the character bound from it, falling back to the search only when escaping makes the estimate ambiguous.src/relay/dispatcher-client-writer.ts (1)
254-287: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSubtle synchronous drain reentrancy — worth documenting.
armDrain()can triggerhandleDrain()synchronously whenwaitWriteDraininvokes its callback immediately (e.g. a sink whose drain fires inline rather than on a future tick). In that casehandleDrainruns whilearmDrainis still mid-execution andthis.drainArmed/this.saturatedget flipped back beforearmDrain's own post-registration branching runs, relying on theif (this.drainArmed)check to pick the right branch. This is exercised and passes (see the "settles callback-less saturated writes when drain fires during registration" test), but the control flow is easy to break with future edits since nothing calls this out.A short inline comment noting that
waitWriteDrainmay invoke its callback synchronously, and that this reentrancy is intentionally handled via thedrainArmedflag check, would help future maintainers avoid regressing this path.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 4c9b1dac-12aa-4903-9e85-9b053452fe03
📥 Commits
Reviewing files that changed from the base of the PR and between 118d1b4e445a2e3db3007a45d53fd0beb63756b2 and db167ea.
📒 Files selected for processing (165)
config/reliability-gates.jsoncdocs/plans/2026-07-27-ssh-relay-pty-backpressure.mdsrc/main/agent-hooks/wsl-hook-relay-sentinel.test.tssrc/main/agent-hooks/wsl-hook-relay-sentinel.tssrc/main/ipc/pty-pending-data-drain-contract.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/ipc/ssh-pty-legacy-projection-publication.tssrc/main/ipc/ssh-pty-legacy-projection-record.tssrc/main/ipc/ssh-pty-legacy-projection.test.tssrc/main/ipc/ssh-pty-legacy-projection.tssrc/main/ipc/ssh-pty-model-admission-contract.tssrc/main/ipc/ssh-pty-model-admission-entry.tssrc/main/ipc/ssh-pty-model-admission-limits.tssrc/main/ipc/ssh-pty-model-admission-pressure.tssrc/main/ipc/ssh-pty-model-admission.test.tssrc/main/ipc/ssh-pty-model-admission.tssrc/main/ipc/ssh-pty-output-exit-deadline.tssrc/main/ipc/ssh-pty-output-exit.tssrc/main/ipc/ssh-pty-output-generation-guard.tssrc/main/ipc/ssh-pty-output-intake-contract.tssrc/main/ipc/ssh-pty-output-intake-registry.tssrc/main/ipc/ssh-pty-output-intake-validation.tssrc/main/ipc/ssh-pty-output-intake.test.tssrc/main/ipc/ssh-pty-output-intake.tssrc/main/ipc/ssh-pty-output-source-obligations.tssrc/main/ipc/ssh-pty-projection-terminality.tssrc/main/ipc/ssh-pty-remote-source-range-consumers.test.tssrc/main/ipc/ssh-pty-remote-source-range-consumers.tssrc/main/ipc/ssh-pty-remote-source-range-replacement.tssrc/main/ipc/ssh-pty-source-ack-coalescer.test.tssrc/main/ipc/ssh-pty-source-ack-coalescer.tssrc/main/ipc/ssh-pty-source-ack-publication.tssrc/main/ipc/ssh-pty-source-ack-session-contract.test.tssrc/main/ipc/ssh-pty-source-obligation-contract.tssrc/main/ipc/ssh-pty-source-obligation-coordinator.test.tssrc/main/ipc/ssh-pty-source-obligation-coordinator.tssrc/main/ipc/ssh-pty-source-obligation-ledger.test.tssrc/main/ipc/ssh-pty-source-obligation-ledger.tssrc/main/ipc/ssh-pty-source-obligation-state.tssrc/main/ipc/ssh-pty-source-obligation-transitions.tssrc/main/ipc/ssh.test.tssrc/main/ipc/ssh.tssrc/main/providers/pty-spawn-result.tssrc/main/providers/ssh-agent-session-create-operation.tssrc/main/providers/ssh-pty-notification-routing.test.tssrc/main/providers/ssh-pty-notification-routing.tssrc/main/providers/ssh-pty-provider-agent-session-create-operation.test.tssrc/main/providers/ssh-pty-provider-contract.tssrc/main/providers/ssh-pty-provider-exit-race.test.tssrc/main/providers/ssh-pty-provider-output-state.tssrc/main/providers/ssh-pty-provider-process-events.test.tssrc/main/providers/ssh-pty-provider.test.tssrc/main/providers/ssh-pty-provider.tssrc/main/providers/ssh-pty-session-reattach.tssrc/main/providers/ssh-pty-source-frame.tssrc/main/providers/ssh-pty-spawn-env.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/remote-terminal-source-range-consumer.tssrc/main/runtime/rpc/methods/terminal.tssrc/main/runtime/rpc/terminal-multiplex.test.tssrc/main/runtime/rpc/terminal-output-frame-chunks-equivalence.test.tssrc/main/runtime/rpc/terminal-output-frame-chunks.tssrc/main/runtime/rpc/terminal-output-frame-source-ranges.test.tssrc/main/runtime/rpc/terminal-source-range-ledger.test.tssrc/main/runtime/rpc/terminal-source-range-ledger.tssrc/main/runtime/rpc/terminal-source-range-registry.tssrc/main/runtime/rpc/terminal-source-range-validation.tssrc/main/ssh/relay-frame-decoder.tssrc/main/ssh/relay-protocol-backpressure.test.tssrc/main/ssh/relay-protocol.tssrc/main/ssh/ssh-channel-multiplexer-backpressure.test.tssrc/main/ssh/ssh-channel-multiplexer-settlement.test.tssrc/main/ssh/ssh-channel-multiplexer.test.tssrc/main/ssh/ssh-channel-multiplexer.tssrc/main/ssh/ssh-multiplexer-transport-writer.test.tssrc/main/ssh/ssh-multiplexer-transport-writer.tssrc/main/ssh/ssh-pty-consumer-session.test.tssrc/main/ssh/ssh-pty-consumer-session.tssrc/main/ssh/ssh-pty-recovery-retention-budget.test.tssrc/main/ssh/ssh-pty-recovery-retention-budget.tssrc/main/ssh/ssh-pty-source-credit-rollout.test.tssrc/main/ssh/ssh-pty-source-credit-rollout.tssrc/main/ssh/ssh-relay-deploy-helpers.test.tssrc/main/ssh/ssh-relay-deploy-helpers.tssrc/main/ssh/ssh-relay-deploy.test.tssrc/main/ssh/ssh-relay-deploy.tssrc/main/ssh/ssh-relay-gc-retry.test.tssrc/main/ssh/ssh-relay-native-deps-install.test.tssrc/main/ssh/ssh-relay-session-agent-hooks.integration.test.tssrc/main/ssh/ssh-relay-session-data-delivery.test.tssrc/main/ssh/ssh-relay-session-incarnation.test.tssrc/main/ssh/ssh-relay-session-reconnect-incarnation.test.tssrc/main/ssh/ssh-relay-session-recovery-races.test.tssrc/main/ssh/ssh-relay-session-terminal-error.test.tssrc/main/ssh/ssh-relay-session.test.tssrc/main/ssh/ssh-relay-session.tssrc/main/ssh/ssh-relay-sftp-namespace-install.test.tssrc/main/ssh/ssh-remote-cli-launcher.test.tssrc/main/ssh/ssh-remote-cli-launcher.tssrc/relay/dispatcher-client-writer.test.tssrc/relay/dispatcher-client-writer.tssrc/relay/dispatcher-writer-admission.tssrc/relay/dispatcher-writer-lane-scheduler.tssrc/relay/dispatcher-writer-sink.tssrc/relay/dispatcher.test.tssrc/relay/dispatcher.tssrc/relay/fs-stream-pty-echo-backpressure.integration.test.tssrc/relay/git-response-pty-echo-backpressure.integration.test.tssrc/relay/git-response-stream.tssrc/relay/legacy-relay-publication-ledger.test.tssrc/relay/legacy-relay-publication-ledger.tssrc/relay/protocol-backpressure.test.tssrc/relay/protocol.tssrc/relay/pty-handler-output-drain-differential.test.tssrc/relay/pty-handler-source-publication.test.tssrc/relay/pty-handler.test.tssrc/relay/pty-handler.tssrc/relay/pty-source-cancellation-index.tssrc/relay/pty-source-credit-ledger.test.tssrc/relay/pty-source-credit-ledger.tssrc/relay/pty-source-credit-limits.tssrc/relay/pty-source-credit-record.tssrc/relay/pty-source-credit-scheduler.test.tssrc/relay/pty-source-credit-scheduler.tssrc/relay/pty-source-credit-settlement.tssrc/relay/pty-source-delivery-ownership.tssrc/relay/pty-source-replay-index.test.tssrc/relay/pty-source-replay-index.tssrc/relay/relay-frame-decoder.tssrc/relay/relay-handshake-roundtrip.test.tssrc/relay/relay-handshake.tssrc/relay/relay-pty-source-activation.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.tssrc/relay/relay-pty-source-recovery-completion.test.tssrc/relay/relay-pty-source-recovery-completion.tssrc/relay/relay-pty-source-recovery-interleavings.test.tssrc/relay/relay-pty-source-send-scheduler.tssrc/relay/relay-watcher-event-emitter.test.tssrc/relay/relay-watcher-event-emitter.tssrc/relay/relay.tssrc/relay/ssh-pty-consumer-session-adapter.test.tssrc/relay/ssh-pty-consumer-session-adapter.tssrc/relay/ssh-pty-source-credit-adapter.test.tssrc/relay/ssh-pty-source-credit-adapter.tssrc/relay/wsl-agent-hook-relay.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.tssrc/renderer/src/runtime/remote-runtime-terminal-multiplexer.tssrc/renderer/src/runtime/runtime-terminal-stream.test.tssrc/shared/pty-consumer-session-contract.tssrc/shared/pty-consumer-session.test.tssrc/shared/pty-consumer-session.tssrc/shared/pty-retained-string-memory.tssrc/shared/pty-source-credit-contract.tssrc/shared/pty-source-credit-validation.tssrc/shared/pty-source-receiving-activation.tssrc/shared/pty-source-recovery-contract.tssrc/shared/relay-frame-decoder-contract.tssrc/shared/terminal-output-source-range.tstests/e2e/helpers/remote-terminal-source-range-contract-fixture.tstests/e2e/helpers/remote-terminal-source-range-contract-fixture.unit.test.tstests/e2e/ssh-docker-relay-perf.spec.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/agent-hooks/wsl-hook-relay-sentinel.ts
- src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts
- docs/plans/2026-07-27-ssh-relay-pty-backpressure.md
db167ea to
5f7330b
Compare
|
Final implementation head is The final architecture/lifecycle review is clean, the final transport review's only stale-provenance finding is closed, all 17 prior major threads have exact fix/test replies, and the fresh four-case Docker OpenSSH/deployed-relay gate passed.
Human architecture/terminal review remains requested from @nwparker. Please do not merge until fresh CI and normal maintainer review are complete. |
|
✅ Action performedReview finished.
|
|
✅ Action performedReview finished.
|
|
Final validation checkpoint: current PR head is |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (9)
src/main/ipc/ssh-pty-output-exit-deadline.test.ts (1)
121-154: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider covering the cancellation-proof timeout path.
Both tests exercise resolved or fenced cancellations. The
exitCancellationProofMsdeadline (which rejects withssh_source_cancellation_proof_timeoutand triggerscloseProvider('ssh-exit-cancellation-proof-failed')) is never reached — advancing past 100ms with the pendingcancellationpromise would cover it cheaply since fake timers are already in place.src/main/ipc/ssh-pty-output-intake.ts (1)
158-173: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueRejection handler dereferences
errorwithout a null guard.If a dependency rejects with
undefined/null(e.g. a barePromise.reject()fromacceptModel's completion), Line 165 throws aTypeErrorthat replaces the original rejection and skips thecloseProviderdecision entirely.🛡️ Proposed guard
- const code = (error as { code?: unknown }).code + const code = (error as { code?: unknown } | null | undefined)?.codesrc/main/providers/ssh-pty-notification-routing.ts (1)
110-128: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winUnbounded
pty.cancelDeliveryfan-out on repeated malformed/non-admitted frames.Every malformed or rejected frame issues its own cancel request for the same
(relayPtyId, deliveryToken). A misbehaving or out-of-sync relay streaming such frames turns each one into an outbound RPC. Consider deduping per delivery token (e.g., a short-lived set of already-canceled tokens) so at most one cancel is in flight per delivery.src/main/ssh/ssh-relay-session-data-delivery.test.ts (1)
130-135: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCollapse the four repeated dynamic imports of the same module.
../ipc/ssh-pty-output-intake-registryis imported four times for four named exports; one destructuring import is clearer.♻️ Proposed consolidation
-const { closeSshPtyOutputGeneration } = await import('../ipc/ssh-pty-output-intake-registry') -const { applySshPtySourceCancellationProof } = await import('../ipc/ssh-pty-output-intake-registry') -const { applySshPtySourceRecoveryCancellationProof } = - await import('../ipc/ssh-pty-output-intake-registry') -const { getSshPtyAcceptedSourceCheckpoints } = await import('../ipc/ssh-pty-output-intake-registry') -const { installSshPtySourceAckPublisher } = await import('../ipc/ssh-pty-output-intake-registry') +const { + applySshPtySourceCancellationProof, + applySshPtySourceRecoveryCancellationProof, + closeSshPtyOutputGeneration, + getSshPtyAcceptedSourceCheckpoints, + installSshPtySourceAckPublisher +} = await import('../ipc/ssh-pty-output-intake-registry')src/main/ssh/ssh-relay-session-recovery-races.test.ts (1)
528-533: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDerive the over-capacity payload size from the shared limit constant.
2 * 1024 * 1024 + 1hardcodes the admission capacity threshold. If that limit moves, this test stops exercising the capacity-rejection path it names. Importing the constant (asterminal-source-range-ledger.test.tsdoes withTERMINAL_SOURCE_RANGE_STREAM_MAX_BYTES) keeps them in lockstep.src/main/runtime/rpc/terminal-source-range-ledger.test.ts (1)
317-321: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExpress the aggregate bound in terms of the imported per-stream constant.
Line 321 hardcodes
16 * 1024 * 1024, which silently encodesTERMINAL_SOURCE_RANGE_STREAM_MAX_BYTES === 2 MiB. Deriving it keeps the assertion meaningful if the per-stream cap moves.♻️ Proposed change
- expect(registry.getDebugSnapshot().retainedBytes).toBe(16 * 1024 * 1024) + expect(registry.getDebugSnapshot().retainedBytes).toBe( + 8 * TERMINAL_SOURCE_RANGE_STREAM_MAX_BYTES + )src/main/ssh/ssh-multiplexer-writer-lane-scheduler.ts (1)
18-29: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winConsumed slots are never released while a lane stays non-empty.
shiftonly truncates whenheadreachesentries.length. A lane that stays continuously backlogged (the saturated-writer case this scheduler exists for) keeps growingentrieswhile the leadingheadslots still hold references to already-written frames, so those frames can't be collected. Null the consumed slot and/or compact onceheadpasses a threshold.♻️ Proposed compaction
function shift<T>(queue: LaneQueue<T>): T | undefined { const entry = queue.entries[queue.head] if (entry === undefined) { return undefined } + queue.entries[queue.head] = undefined as unknown as T queue.head += 1 if (queue.head === queue.entries.length) { queue.entries.length = 0 queue.head = 0 + } else if (queue.head >= 1024 && queue.head * 2 >= queue.entries.length) { + queue.entries = queue.entries.slice(queue.head) + queue.head = 0 } return entry }(Requires dropping
readonlyon theentriesfield or mutating viasplice.)src/shared/relay-frame-buffer.ts (1)
25-39: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAdd bounds guards to
peek/take/discard.All three dereference
this.chunks[0]without checkingcount <= this.bytes. Today's decoder callers always pre-checklength, but an over-request from a future caller yieldsCannot read properties of undefined (reading 'length'), anddiscardadditionally drivesthis.bytesnegative — which silently breaks every subsequentlengthcheck instead of failing fast. A single guard per method makes the contract explicit for this shared primitive.🛡️ Proposed guards
peek(count: number): Buffer { + if (count > this.bytes) { + throw new RangeError(`RelayFrameBuffer.peek(${count}) exceeds ${this.bytes} buffered bytes`) + } const first = this.chunks[0]take(count: number): Buffer { + if (count > this.bytes) { + throw new RangeError(`RelayFrameBuffer.take(${count}) exceeds ${this.bytes} buffered bytes`) + } const first = this.chunks[0]discard(count: number): void { + if (count > this.bytes) { + throw new RangeError( + `RelayFrameBuffer.discard(${count}) exceeds ${this.bytes} buffered bytes` + ) + } let remaining = countAlso applies to: 41-68, 70-83
src/relay/relay-handshake-roundtrip.test.ts (1)
127-142: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winAdd the matching-credential accept case.
This only proves rejection. A regression that closes every same-build socket once
endpointCredentialis configured — or that ignores the credential and rejects unconditionally — still passes. Pair it with a test that passes'secret-credential'to bothstartDaemonandrunConnectHandshakeand assertsacceptedresolves.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b3e48674-edd0-44ca-a751-8cbdcede95c3
📒 Files selected for processing (190)
config/reliability-gates.jsoncdocs/plans/2026-07-27-ssh-relay-pty-backpressure.mdsrc/main/agent-hooks/wsl-hook-relay-sentinel.test.tssrc/main/agent-hooks/wsl-hook-relay-sentinel.tssrc/main/ipc/pty-pending-data-drain-contract.tssrc/main/ipc/pty-pending-projection-admissions.test.tssrc/main/ipc/pty-pending-projection-admissions.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/ipc/ssh-pty-closed-generation-ranges.tssrc/main/ipc/ssh-pty-legacy-projection-publication.tssrc/main/ipc/ssh-pty-legacy-projection-record.tssrc/main/ipc/ssh-pty-legacy-projection.test.tssrc/main/ipc/ssh-pty-legacy-projection.tssrc/main/ipc/ssh-pty-model-admission-contract.tssrc/main/ipc/ssh-pty-model-admission-entry.tssrc/main/ipc/ssh-pty-model-admission-limits.tssrc/main/ipc/ssh-pty-model-admission-migration.tssrc/main/ipc/ssh-pty-model-admission-pressure.tssrc/main/ipc/ssh-pty-model-admission-snapshot.tssrc/main/ipc/ssh-pty-model-admission.test.tssrc/main/ipc/ssh-pty-model-admission.tssrc/main/ipc/ssh-pty-output-exit-deadline.test.tssrc/main/ipc/ssh-pty-output-exit-deadline.tssrc/main/ipc/ssh-pty-output-exit.tssrc/main/ipc/ssh-pty-output-generation-guard.test.tssrc/main/ipc/ssh-pty-output-generation-guard.tssrc/main/ipc/ssh-pty-output-intake-contract.tssrc/main/ipc/ssh-pty-output-intake-registry.tssrc/main/ipc/ssh-pty-output-intake-test-harness.tssrc/main/ipc/ssh-pty-output-intake-validation.tssrc/main/ipc/ssh-pty-output-intake.test.tssrc/main/ipc/ssh-pty-output-intake.tssrc/main/ipc/ssh-pty-output-model-migration.test.tssrc/main/ipc/ssh-pty-output-model-migration.tssrc/main/ipc/ssh-pty-output-source-obligations.tssrc/main/ipc/ssh-pty-projection-terminality.tssrc/main/ipc/ssh-pty-remote-source-range-consumers.test.tssrc/main/ipc/ssh-pty-remote-source-range-consumers.tssrc/main/ipc/ssh-pty-remote-source-range-replacement.tssrc/main/ipc/ssh-pty-source-ack-coalescer.test.tssrc/main/ipc/ssh-pty-source-ack-coalescer.tssrc/main/ipc/ssh-pty-source-ack-publication.tssrc/main/ipc/ssh-pty-source-ack-session-contract.test.tssrc/main/ipc/ssh-pty-source-obligation-contract.tssrc/main/ipc/ssh-pty-source-obligation-coordinator.test.tssrc/main/ipc/ssh-pty-source-obligation-coordinator.tssrc/main/ipc/ssh-pty-source-obligation-ledger.test.tssrc/main/ipc/ssh-pty-source-obligation-ledger.tssrc/main/ipc/ssh-pty-source-obligation-state.tssrc/main/ipc/ssh-pty-source-obligation-transitions.tssrc/main/ipc/ssh.test.tssrc/main/ipc/ssh.tssrc/main/providers/pty-spawn-result.tssrc/main/providers/ssh-agent-session-create-operation.tssrc/main/providers/ssh-pty-notification-routing.test.tssrc/main/providers/ssh-pty-notification-routing.tssrc/main/providers/ssh-pty-provider-agent-session-create-operation.test.tssrc/main/providers/ssh-pty-provider-contract.tssrc/main/providers/ssh-pty-provider-exit-race.test.tssrc/main/providers/ssh-pty-provider-output-state.tssrc/main/providers/ssh-pty-provider-process-events.test.tssrc/main/providers/ssh-pty-provider-reattach-incarnation.test.tssrc/main/providers/ssh-pty-provider.test.tssrc/main/providers/ssh-pty-provider.tssrc/main/providers/ssh-pty-session-reattach.tssrc/main/providers/ssh-pty-source-delivery-ledger.test.tssrc/main/providers/ssh-pty-source-delivery-ledger.tssrc/main/providers/ssh-pty-source-frame.tssrc/main/providers/ssh-pty-spawn-env.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/remote-terminal-source-range-consumer.tssrc/main/runtime/rpc/methods/terminal.tssrc/main/runtime/rpc/terminal-multiplex.test.tssrc/main/runtime/rpc/terminal-output-frame-chunks-equivalence.test.tssrc/main/runtime/rpc/terminal-output-frame-chunks.tssrc/main/runtime/rpc/terminal-output-frame-source-ranges.test.tssrc/main/runtime/rpc/terminal-source-range-ledger.test.tssrc/main/runtime/rpc/terminal-source-range-ledger.tssrc/main/runtime/rpc/terminal-source-range-registry.tssrc/main/runtime/rpc/terminal-source-range-validation.tssrc/main/ssh/relay-frame-decoder.tssrc/main/ssh/relay-protocol-backpressure.test.tssrc/main/ssh/relay-protocol.tssrc/main/ssh/ssh-channel-multiplexer-backpressure.test.tssrc/main/ssh/ssh-channel-multiplexer-settlement.test.tssrc/main/ssh/ssh-channel-multiplexer.test.tssrc/main/ssh/ssh-channel-multiplexer.tssrc/main/ssh/ssh-multiplexer-transport-writer.test.tssrc/main/ssh/ssh-multiplexer-transport-writer.tssrc/main/ssh/ssh-multiplexer-writer-lane-scheduler.tssrc/main/ssh/ssh-pty-consumer-session.test.tssrc/main/ssh/ssh-pty-consumer-session.tssrc/main/ssh/ssh-pty-recovery-retention-budget.test.tssrc/main/ssh/ssh-pty-recovery-retention-budget.tssrc/main/ssh/ssh-pty-retired-source-deliveries.test.tssrc/main/ssh/ssh-pty-retired-source-deliveries.tssrc/main/ssh/ssh-pty-source-credit-rollout.test.tssrc/main/ssh/ssh-pty-source-credit-rollout.tssrc/main/ssh/ssh-relay-cross-version-isolation.test.tssrc/main/ssh/ssh-relay-deploy-helpers.test.tssrc/main/ssh/ssh-relay-deploy-helpers.tssrc/main/ssh/ssh-relay-deploy.test.tssrc/main/ssh/ssh-relay-deploy.tssrc/main/ssh/ssh-relay-endpoint-credential.test.tssrc/main/ssh/ssh-relay-endpoint-credential.tssrc/main/ssh/ssh-relay-gc-retry.test.tssrc/main/ssh/ssh-relay-native-deps-install-fixture.tssrc/main/ssh/ssh-relay-native-deps-install.test.tssrc/main/ssh/ssh-relay-session-agent-hooks.integration.test.tssrc/main/ssh/ssh-relay-session-data-delivery.test.tssrc/main/ssh/ssh-relay-session-incarnation.test.tssrc/main/ssh/ssh-relay-session-model-migration.test.tssrc/main/ssh/ssh-relay-session-reconnect-incarnation.test.tssrc/main/ssh/ssh-relay-session-recovery-races.test.tssrc/main/ssh/ssh-relay-session-terminal-error.test.tssrc/main/ssh/ssh-relay-session-test-fixtures.tssrc/main/ssh/ssh-relay-session.test.tssrc/main/ssh/ssh-relay-session.tssrc/main/ssh/ssh-relay-sftp-namespace-install.test.tssrc/main/ssh/ssh-remote-cli-launcher.test.tssrc/main/ssh/ssh-remote-cli-launcher.tssrc/relay/dispatcher-client-writer.test.tssrc/relay/dispatcher-client-writer.tssrc/relay/dispatcher-writer-admission.tssrc/relay/dispatcher-writer-lane-scheduler.tssrc/relay/dispatcher-writer-sink.tssrc/relay/dispatcher.test.tssrc/relay/dispatcher.tssrc/relay/fs-stream-pty-echo-backpressure.integration.test.tssrc/relay/git-response-pty-echo-backpressure.integration.test.tssrc/relay/git-response-stream-ownership.test.tssrc/relay/git-response-stream.tssrc/relay/legacy-relay-publication-ledger.test.tssrc/relay/legacy-relay-publication-ledger.tssrc/relay/protocol-backpressure.test.tssrc/relay/protocol.tssrc/relay/pty-handler-output-drain-differential.test.tssrc/relay/pty-handler-source-publication.test.tssrc/relay/pty-handler.test.tssrc/relay/pty-handler.tssrc/relay/pty-source-cancellation-index.tssrc/relay/pty-source-credit-ledger.test.tssrc/relay/pty-source-credit-ledger.tssrc/relay/pty-source-credit-limits.tssrc/relay/pty-source-credit-record.tssrc/relay/pty-source-credit-scheduler.test.tssrc/relay/pty-source-credit-scheduler.tssrc/relay/pty-source-credit-settlement.tssrc/relay/pty-source-delivery-ownership.tssrc/relay/pty-source-replay-index.test.tssrc/relay/pty-source-replay-index.tssrc/relay/relay-frame-decoder.tssrc/relay/relay-handshake-roundtrip.test.tssrc/relay/relay-handshake.tssrc/relay/relay-pty-source-activation.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.tssrc/relay/relay-pty-source-recovery-completion.test.tssrc/relay/relay-pty-source-recovery-completion.tssrc/relay/relay-pty-source-recovery-interleavings.test.tssrc/relay/relay-pty-source-restore-retry.test.tssrc/relay/relay-pty-source-send-scheduler.tssrc/relay/relay-watcher-event-emitter.test.tssrc/relay/relay-watcher-event-emitter.tssrc/relay/relay.tssrc/relay/ssh-pty-consumer-session-adapter.test.tssrc/relay/ssh-pty-consumer-session-adapter.tssrc/relay/ssh-pty-source-credit-adapter.test.tssrc/relay/ssh-pty-source-credit-adapter.tssrc/relay/wsl-agent-hook-relay.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.tssrc/renderer/src/runtime/remote-runtime-terminal-multiplexer.tssrc/renderer/src/runtime/runtime-terminal-stream.test.tssrc/shared/pty-consumer-session-contract.tssrc/shared/pty-consumer-session.test.tssrc/shared/pty-consumer-session.tssrc/shared/pty-retained-string-memory.tssrc/shared/pty-source-credit-contract.tssrc/shared/pty-source-credit-validation.tssrc/shared/pty-source-receiving-activation.tssrc/shared/pty-source-recovery-contract.tssrc/shared/relay-frame-buffer.tssrc/shared/relay-frame-decoder-contract.tssrc/shared/terminal-output-source-range.tstests/e2e/helpers/remote-terminal-source-range-contract-fixture.tstests/e2e/helpers/remote-terminal-source-range-contract-fixture.unit.test.tstests/e2e/ssh-docker-relay-perf.spec.ts
🚧 Files skipped from review as they are similar to previous changes (136)
- src/main/ipc/ssh-pty-output-intake-validation.ts
- src/main/ipc/ssh-pty-source-ack-publication.ts
- src/main/providers/ssh-pty-spawn-env.ts
- src/shared/pty-retained-string-memory.ts
- src/main/ipc/ssh-pty-model-admission-contract.ts
- tests/e2e/helpers/remote-terminal-source-range-contract-fixture.unit.test.ts
- src/main/providers/pty-spawn-result.ts
- src/relay/legacy-relay-publication-ledger.test.ts
- src/relay/relay-watcher-event-emitter.test.ts
- src/main/ipc/ssh-pty-source-obligation-coordinator.test.ts
- src/relay/pty-source-delivery-ownership.ts
- src/main/runtime/rpc/terminal-output-frame-source-ranges.test.ts
- src/shared/pty-source-receiving-activation.ts
- src/main/ssh/ssh-relay-gc-retry.test.ts
- src/relay/relay-pty-source-output.ts
- src/main/ssh/ssh-pty-source-credit-rollout.ts
- src/main/ipc/ssh-pty-model-admission-limits.ts
- src/main/ssh/ssh-pty-recovery-retention-budget.test.ts
- src/relay/pty-handler-output-drain-differential.test.ts
- src/relay/relay-pty-source-recovery-interleavings.test.ts
- src/relay/relay-pty-source-recovery-completion.ts
- src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
- src/shared/pty-source-credit-contract.ts
- src/main/ipc/ssh-pty-source-obligation-contract.ts
- src/main/ssh/ssh-remote-cli-launcher.test.ts
- src/relay/pty-source-credit-scheduler.ts
- src/main/ipc/pty-pending-data-drain-contract.ts
- src/main/ipc/ssh.ts
- src/shared/pty-source-credit-validation.ts
- src/relay/relay-watcher-event-emitter.ts
- src/shared/terminal-output-source-range.ts
- src/shared/pty-source-recovery-contract.ts
- src/main/runtime/rpc/terminal-source-range-registry.ts
- src/relay/git-response-stream.ts
- src/relay/pty-source-credit-limits.ts
- src/main/ipc/ssh-pty-source-ack-coalescer.test.ts
- src/main/ssh/ssh-pty-consumer-session.ts
- src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts
- src/main/ssh/ssh-pty-consumer-session.test.ts
- src/main/agent-hooks/wsl-hook-relay-sentinel.ts
- src/main/ipc/ssh-pty-model-admission-pressure.ts
- src/main/providers/ssh-pty-provider-contract.ts
- src/main/ipc/ssh-pty-output-intake-contract.ts
- src/main/ipc/ssh-pty-source-ack-session-contract.test.ts
- tests/e2e/ssh-docker-relay-perf.spec.ts
- src/main/ssh/ssh-relay-deploy-helpers.ts
- src/relay/dispatcher-writer-lane-scheduler.ts
- src/main/ipc/ssh-pty-output-generation-guard.ts
- src/relay/wsl-agent-hook-relay.ts
- src/relay/fs-stream-pty-echo-backpressure.integration.test.ts
- src/shared/pty-consumer-session-contract.ts
- src/main/runtime/rpc/terminal-output-frame-chunks-equivalence.test.ts
- src/main/ipc/ssh-pty-output-exit.ts
- src/main/ssh/ssh-relay-session-incarnation.test.ts
- src/main/ssh/ssh-relay-deploy-helpers.test.ts
- src/relay/relay-handshake.ts
- src/relay/pty-source-replay-index.test.ts
- src/main/ipc/ssh-pty-projection-terminality.ts
- tests/e2e/helpers/remote-terminal-source-range-contract-fixture.ts
- src/main/ssh/ssh-channel-multiplexer.test.ts
- src/main/ssh/ssh-channel-multiplexer-backpressure.test.ts
- src/main/ssh/relay-protocol-backpressure.test.ts
- src/main/providers/ssh-pty-provider-exit-race.test.ts
- src/main/ipc/ssh-pty-source-obligation-state.ts
- src/main/ipc/ssh-pty-model-admission-entry.ts
- src/relay/pty-source-credit-settlement.ts
- src/main/ipc/ssh-pty-legacy-projection-record.ts
- src/main/ssh/ssh-channel-multiplexer-settlement.test.ts
- src/main/ssh/ssh-pty-source-credit-rollout.test.ts
- src/main/ipc/ssh-pty-output-intake-registry.ts
- src/main/providers/ssh-pty-source-frame.ts
- src/shared/pty-consumer-session.test.ts
- src/renderer/src/runtime/runtime-terminal-stream.test.ts
- src/relay/legacy-relay-publication-ledger.ts
- src/relay/dispatcher-writer-sink.ts
- src/main/ipc/ssh-pty-source-obligation-coordinator.ts
- src/relay/git-response-pty-echo-backpressure.integration.test.ts
- src/main/runtime/remote-terminal-source-range-consumer.ts
- src/relay/relay-pty-source-exit-publication.ts
- src/main/ssh/ssh-relay-session-terminal-error.test.ts
- src/relay/ssh-pty-source-credit-adapter.test.ts
- src/main/ssh/ssh-remote-cli-launcher.ts
- src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts
- src/relay/pty-source-credit-ledger.ts
- src/relay/protocol.ts
- src/main/ssh/relay-protocol.ts
- src/relay/pty-source-replay-index.ts
- src/main/providers/ssh-pty-provider-output-state.ts
- src/main/ipc/ssh-pty-source-ack-coalescer.ts
- src/main/providers/ssh-pty-notification-routing.test.ts
- src/main/ssh/ssh-pty-recovery-retention-budget.ts
- src/relay/protocol-backpressure.test.ts
- src/relay/pty-source-cancellation-index.ts
- src/main/ipc/ssh-pty-legacy-projection.test.ts
- src/main/ssh/ssh-multiplexer-transport-writer.test.ts
- src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
- src/relay/relay-pty-source-recovery-completion.test.ts
- src/relay/relay-pty-source-send-scheduler.ts
- src/main/ssh/ssh-multiplexer-transport-writer.ts
- src/shared/pty-consumer-session.ts
- src/relay/dispatcher-client-writer.ts
- src/main/providers/ssh-agent-session-create-operation.ts
- src/main/ipc/ssh-pty-remote-source-range-replacement.ts
- src/main/ipc/ssh-pty-legacy-projection.ts
- src/main/runtime/rpc/terminal-output-frame-chunks.ts
- src/relay/pty-handler.test.ts
- src/main/ssh/ssh-relay-session.test.ts
- src/main/ssh/ssh-channel-multiplexer.ts
- src/relay/relay-pty-source-publication.test.ts
- src/relay/ssh-pty-consumer-session-adapter.ts
- src/main/ipc/ssh.test.ts
- src/main/ipc/ssh-pty-source-obligation-ledger.ts
- src/main/providers/ssh-pty-provider.ts
- src/relay/pty-source-credit-record.ts
- src/relay/ssh-pty-consumer-session-adapter.test.ts
- src/relay/dispatcher-client-writer.test.ts
- src/main/ipc/ssh-pty-output-intake.test.ts
- src/relay/dispatcher-writer-admission.ts
- src/main/ipc/ssh-pty-remote-source-range-consumers.ts
- src/main/ipc/pty.ts
- src/main/ssh/relay-frame-decoder.ts
- src/relay/relay-pty-source-publication.ts
- src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts
- src/relay/ssh-pty-source-credit-adapter.ts
- src/main/runtime/rpc/terminal-source-range-ledger.ts
- src/main/runtime/rpc/methods/terminal.ts
- src/relay/relay.ts
- docs/plans/2026-07-27-ssh-relay-pty-backpressure.md
- src/main/ssh/ssh-relay-sftp-namespace-install.test.ts
- src/relay/pty-source-credit-ledger.test.ts
- src/main/providers/ssh-pty-provider.test.ts
- src/relay/pty-handler.ts
- src/main/ssh/ssh-relay-session.ts
- src/main/runtime/orca-runtime.ts
- src/relay/pty-handler-source-publication.test.ts
- src/relay/dispatcher.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/renderer/src/i18n/locales/en.json (1)
7037-7039: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLocale keys break the
SshTargetFormhash-key convention.The new keys (
ptySourceCreditV1Label,ptySourceCreditV1Description,ptySourceCreditV1Toggle) are descriptive, while every other key in thisSshTargetFormnamespace is a 10-char SHA1-style hash. Consider regenerating these as hash keys and syncing viapnpm bootstrap:locale-catalog/pnpm sync:localization-catalogfor consistency with the established per-namespace convention.Based on learnings: "use hash-based locale keys with
translate('auto.components.<Dir>.<ComponentFile>.<10-char-hash>', 'Default English text')" and "prefer semantic locale keys when they match the established neighboring namespaces ... Hash-based keys may be generated for unnamed strings, but they are not a blanket requirement" — since the neighboringSshTargetFormnamespace is entirely hash-based, the new descriptive keys don't match its established convention.Source: Learnings
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f1eecd51-621c-4f62-a693-7f4bae246559
📒 Files selected for processing (21)
config/reliability-gates.jsoncdocs/plans/2026-07-27-ssh-relay-pty-backpressure.mdsrc/main/ipc/ssh.tssrc/main/persistence.test.tssrc/main/persistence.tssrc/main/ssh/ssh-pty-source-credit-rollout.test.tssrc/main/ssh/ssh-pty-source-credit-rollout.tssrc/main/ssh/ssh-relay-session-reconnect-incarnation.test.tssrc/main/ssh/ssh-relay-session.tssrc/renderer/src/components/settings/SshHostAdvancedFields.test.tsxsrc/renderer/src/components/settings/SshHostAdvancedFields.tsxsrc/renderer/src/components/settings/ssh-target-draft.test.tssrc/renderer/src/components/settings/ssh-target-draft.tssrc/renderer/src/components/settings/ssh-target-save-payload.test.tssrc/renderer/src/components/settings/ssh-target-save-payload.tssrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/i18n/locales/es.jsonsrc/renderer/src/i18n/locales/ja.jsonsrc/renderer/src/i18n/locales/ko.jsonsrc/renderer/src/i18n/locales/zh.jsonsrc/shared/ssh-types.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- docs/plans/2026-07-27-ssh-relay-pty-backpressure.md
- src/main/ssh/ssh-relay-session.ts
…ssure-2 # Conflicts: # config/reliability-gates.jsonc # src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts # src/main/ssh/ssh-relay-session.ts # src/relay/relay.ts
|
Final current-main checkpoint: production merge commit adba341 is validated by the exact four-case Docker SSH run; current PR head 728ed98 adds only provenance. The PR body now records the always-on same-build V1 decision, negotiated legacy behavior, exact hashes/results, and remaining topology gaps. All review threads are resolved, main is an ancestor, and fresh CI is running. @coderabbitai review Human architecture/terminal review remains requested from @nwparker. Do not merge until CI and normal maintainer review complete. |
|
✅ Action performedReview finished.
|
|
Final validation checkpoint: current head is |
…pacity (#11917) * fix(relay): chunk fs.changed notifications to fit the client frame capacity emitRelayWatcherEvents published an entire watcher batch as one fs.changed notification on the ordinary lane. A batch runs routinely tens of times over the per-frame producer capacity (12,288 bytes against a Node <=21 socket, 49,152 against Node >=22), and an over-capacity frame there is not queued or trimmed -- notify() fails admission and closes the client, tearing down every in-flight request on that connection. Regressed in 5f78074 (#11005). The emitter now sizes chunks against the tightest capacity across attached clients, measured in encoded bytes through the same envelope admission measures, and preserves event order. A single event too large for an empty envelope cannot be chunked, so the ordinary-lane close remains its backstop: a silent drop on this lane has no resync contract. * chore(relay): shorten watcher chunking comments
* docs: design SSH relay PTY backpressure * fix(ssh): bound relay frame decoding * fix(relay): bound PTY output publication * fix(ssh): bound PTY model admission * fix(ssh): settle closed model admissions * feat(ssh): negotiate bounded PTY consumer sessions * fix(ssh): fence exit on renderer settlement * feat(ssh): track PTY source credit end to end * fix(ssh): recover bounded PTY output across reconnect * feat(ssh): complete relay PTY output backpressure * fix(ssh): close final PTY source credit races * docs(ssh): record final backpressure validation * feat(ssh): complete relay PTY source-credit lifecycle * test(ssh): complete provider notification fixture * fix(ssh): preserve terminal source credit across rotation * fix(ssh): fail closed on recovery cancellation * fix(ssh): prioritize mux control writes after drain * fix(ssh): retire canceled relay restore deliveries * fix(ssh): order exit cancellation cleanup * fix(ssh): gate provisional source activation * test(ssh): register mux drain-priority coverage * fix(ssh): type stale owner recovery mismatches * fix(ssh): close projection replacement races * fix(relay): contain streaming edge failures * fix(ssh): secure relay endpoint credentials * docs(ssh): reconcile final backpressure lifecycle * fix(ssh): bound main IPC output lifecycle * fix(ssh): close recovery ownership gaps * docs(ssh): record exact artifact validation * fix(ssh): reject reclaimed snapshot replacements * fix(ssh): fence model admission across reconnect * fix(ssh): contain migration failure per PTY * docs(ssh): record final exact-head validation * test(ssh): align deploy fixtures with credential publication * feat(ssh): add per-target bounded output setting * fix(ssh): close source recovery review gaps * fix(ssh): latch source credit environment override * feat(ssh): make PTY source credit the default * docs(ssh): record always-on relay validation * docs(ssh): bind validation to current main * test(ssh): grant source credit in IPC fixture * test(ssh): grant source credit in fake relay --------- Co-authored-by: OrcaWin <[email protected]>
…pacity (stablyai#11917) * fix(relay): chunk fs.changed notifications to fit the client frame capacity emitRelayWatcherEvents published an entire watcher batch as one fs.changed notification on the ordinary lane. A batch runs routinely tens of times over the per-frame producer capacity (12,288 bytes against a Node <=21 socket, 49,152 against Node >=22), and an over-capacity frame there is not queued or trimmed -- notify() fails admission and closes the client, tearing down every in-flight request on that connection. Regressed in 63ec0b0 (stablyai#11005). The emitter now sizes chunks against the tightest capacity across attached clients, measured in encoded bytes through the same envelope admission measures, and preserves event order. A single event too large for an empty envelope cannot be chunked, so the ordinary-lane close remains its backstop: a silent drop on this lane has no resync contract. * chore(relay): shorten watcher chunking comments
Summary
Implements bounded SSH relay PTY output end to end, from the native PTY through relay publication, dispatcher/SSH transport, bounded frame decoding, main-process model and projection admission, renderer/remote consumer settlement, cumulative source ACK publication, exit, and reconnect.
The production invariant for every negotiated delivery token is:
0 <= sentEndSu - creditedEndSu <= windowSuEvery immutable source span and required consumer obligation ends exactly once as settled, transferred, or canceled. A
write(false)owns one frame exactly once; later ordinary traffic waits for drain while bounded control/liveness capacity remains available.What changed
PtyConsumerSessionstate machine with an SSH-specific authenticated transport adapter.This is intentionally a large cross-layer change: the bound is only real if the source, every transport queue, model admission, desktop/remote consumers, ACK publication, reconnect, exit, and cleanup share one lifecycle. The current PR is 43 commits and 189 files (
+34,172/-2,418), with most added lines in focused contracts and adversarial tests.Default and compatibility behavior
V1 source credit is the default and only same-build behavior:
SshRelaySessionoffers V1;pty.openClientmethod is absent uses the bounded legacy fallback;There is no target setting, experimental toggle, environment override, relay launch flag, or
.pty-source-credit-policy. No Orca restart is needed to select a mode because there is no selectable mode. Local and daemon protocols are not replaced by the SSH wire protocol.Compatibility is negotiated rather than inferred from version strings. Same-build SSH gets source credit; old peers retain legacy semantics without receiving unknown token fields. The legacy path still benefits from the bounded writer and decoder, but cannot provide the V1 source-window guarantee.
Architecture and lifecycle review
The architecture review located authority at the authenticated relay session, immutable source ledger, dispatcher writer, main SSH intake, model/projection owners, and mux ACK publication boundary. It selected shared
PtyConsumerSessionsemantics with transport adapters rather than a universal wire protocol.Adversarial review drove substantive fixes for the original major findings:
These contracts are reflected across invariants, pseudocode, lifecycle tables, implementation mapping, tests, rollout, and cleanup in the design document. Internal final architecture/lifecycle and transport reviews are clean. All GitHub review threads are resolved; human architecture/terminal review remains requested from
@nwparker.Validation
Current branch head is
8c35d4f89826e5a38ee5642434caf557ef71b89dwith treeb2e35b5fdab000cb5475345298baa64b67190fce. Currentorigin/main@0349cb6bdbdb19119585ecb6048d884c5ee8b97dis nine unrelated commits ahead of the last branch merge; synthetic merge tree802c27aa3c0a3c28e1c3c8176c5eb876e8d522b5is conflict-free.Post-main-merge validation:
pnpm run typecheckpnpm run check:reliability-gates: 53 gatespnpm exec oxfmt --check docs/plans/2026-07-27-ssh-relay-pty-backpressure.md config/reliability-gates.jsoncgit diff --checkpnpm exec electron-vite build --mode e2eExact Docker artifact provenance is bound to production merge commit
adba3410fe4427ceb7525f3fdce2ec58973263a7, treee43d87340666ca3a733bdb38007c24f95be3f219:3c304ffc0618520e42bede9a52f72d4b7bb68cbfe543974f89e82a3c477c44b3366cb7ccf2e4b388cc6f81a8f6055ab9fde57d2d91381767005c15908832e776Commit
728ed98ab7changes only validation provenance. Commits6ddd86ae4eand8c35d4f898update the SSH IPC and fake-relay test harnesses to grant the now-unconditional V1 capability; they change no production source. Fresh GitHub CI is green for the current pushed head: PR Checks run 30497200229 attempt 2 has 35/35 jobs green, and the accompanying golden macOS/Linux, Ubuntu/Windows smoke, Windows terminal restart, and packaged crash-survival workflows are green (41 passing checks total; 3 expected platform skips). The only first-attempt failure was an unrelated combined-diff scroll E2E flake; the exact test passed locally and the failed job passed on rerun.Evidence boundaries and remaining gaps
The Docker suite proves direct SSH against the deployed Linux relay: real SSH transport/process/filesystem/Git behavior, main desktop intake, writable/drain behavior, the exact source-window plateau, activity isolation, and reconnect.
It does not prove live headed/headless paired Orca runtime behavior, physical WSL, Windows ConPTY/named pipes, local daemon/provider behavior, folder workspaces, prior/mixed-version binaries, or Ubuntu 20.04 packaging. Those distinctions remain explicit in the design and reliability gate. Deterministic contracts cover their shared seams, but this PR does not claim unrun live topology evidence.
The primary tradeoff is protocol and lifecycle complexity across a broad surface. V1 bounds memory and makes ownership explicit, but legacy peers cannot gain the full source-window invariant, and wider live-topology soak history remains desirable. Because the behavior is always on for same-build SSH, operational rollback is a normal binary/code rollback rather than a user setting.
Security
pty.openClientrequest..git, socket order, and worktree identity grant no authority.Fresh CI is complete. Do not merge until normal maintainer review, including the requested architecture/terminal review from
@nwparker, is complete.