Repository navigation
fix(terminal): measure output stalls by ACK progress, not time since queueing - #960
Merged
Merged
Conversation
…queueing A late joiner of a busy pane was sent a 256 KiB replay, the same size as the high-water mark, so its window blocked at once, and the 2 s stall deadline started when the frame was queued. A phone on a weak link cannot carry and parse that frame in 2 s, so it was closed with 4008 while still receiving, and it paused the pty the other tabs share meanwhile. - OutputWindow.check decides flow/pause/stop; every ACK that advances restarts the stall clock, duplicates do not. - A joiner gets a budget sized to its replay (2 s plus the frame at 32 KiB/s, at most 15 s) until its first ACK, and never pauses the shared pty in it. - The replay tail is 128 KiB, half the high-water mark. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 22 minutes. View limit details
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 |
… relay stalls by progress - OutputWindow.check stops a client that has held the shared pty paused for OUTPUT_PAUSE_MAX_MS (10 s) in a row, however it acknowledges, so a byte-at-a-time ACK or a very slow phone cannot cap its peers at its rate. - OutputWindow.join takes the replay text and sizes the budget from its JSON-serialized length (wireBytes): an ESC costs six bytes on the wire. - A joiner whose budget ran out while it was not blocked becomes an ordinary client and gets the usual 2 s deadline once it is blocked. - MachineRelay closes with 4008 only after 2 s of queued bytes with no progress (bytes leaving a queue, or a browser pty-ack that moved), via RelayStall; it still never acknowledges anything itself. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The relay's stall rule is already being changed by open PR #952, which adds server/machine-relay.test.ts too; keep this PR to the local OutputWindow. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 13, 2026
…ead of a replay, size the stall deadline by the frame in flight - A pane with no more than the low watermark of its own outstanding is no longer paused or stopped because the shared socket queue is high from another pane on the same connection (split panes, split view). - join() adds what the socket already has queued ahead of the replay to the budget, so a reconnect that re-attaches several panes back to back gives each replay time for the frames before it. - The stall deadline grows by the time the oldest unacknowledged frame needs to cross a 32 KiB/s link as serialized; the 10 s pause cap and the hard budgets are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A pty-backed contract case: a joiner that does not ACK its replay for longer than the stall deadline is not closed and does not pause the operator's output. It fails when the join() call in the attach handler is removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
devswha
added a commit
that referenced
this pull request
Oct 13, 2026
#952) ## Problem Viewing a pane on another PC (`/ws?machine_id=…`, through `MachineRelay`) from a phone on a slow or changing cellular link, a burst of output during a ~2 s stall ended the stream with "Terminal output stopped because this device could not keep up.", while the same pane on this PC would have survived. ## Cause `server/machine-relay.ts` started its stall clock on **any** non-zero `getBufferedAmount()` and closed with 4008 after 2 s unless a 100 ms sample saw exactly 0. A slow phone link keeps a few KB queued in userspace even while output moves. The local bridge (`reconcileOutput` in `server/index.ts`) counts a client's socket as blocked only while 256 KiB or more is buffered. ## Fix - New `RelayStallClock` in `machine-relay.ts` with this PC's rule: the clock runs only while `OUTPUT_HIGH_BYTES` (256 KiB) or more is queued, clears on the first sample below it, and fires after `OUTPUT_STALL_MS`. The end-to-end ACK window is still enforced by the remote bridge (ACK frames pass through the relay unchanged), so the relay only needs a memory backstop. - A relay stall still closes with the explicit 4008, like this PC's stall: an overload is never auto-replayed. - Buffering past the 1 MiB hard budget still closes with 4008 at once; an upstream 4008 passes through unchanged and other upstream ends map to 1012 (`upstreamCloseCode`, same behaviour as before). ## Tests - New `server/machine-relay.test.ts` (bun:test): a few KB and just under 256 KiB queued for 3 s do not close (fails on main, where any byte counts); 256 KiB queued for 2 s closes with 4008; one sample below 256 KiB clears the clock; hard overflow is 4008; upstream close-code mapping. - `bun run typecheck`: pass. `HERDR_TEST_MODE=unit bun test ./server/machine-relay.test.ts`: 5 pass. `bun run test:unit`: 3074 pass, 0 fail, 8 skip. - No browser script run (server-only change). ## Notes - From a mobile-terminal stability audit (finding connection-3). Related to #781 (4008 family), not a duplicate. No open PR touches `server/machine-relay.ts`. - An earlier revision of this PR closed a relay stall with 1012 so the phone would reconnect. Review showed that loops (the client resets its backoff on every open, so a recurring stall reconnected every 250 ms) and appends the bounded replay tail to the live terminal, which the 4008 path exists to avoid. That part was dropped; safe automatic recovery needs an offset-based resume and is left out. - Left out: the relay's threshold is on JSON-framed bytes while the remote's ACK window counts payload bytes, so the relay can still stop a little before the remote would. Same code and same user-visible result either way. 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Merge-session review Fixed: - The new tests only exercised `RelayStallClock`/`upstreamCloseCode`; no test built a `MachineRelay`, so restoring the old any-byte timer body (for example in a conflict with #960) would have stayed green. The timer body is now `MachineRelay.tick(now)`, and two tests drive a real relay (throwaway upstream WebSocket server, stub phone socket): 8 KiB queued for 3 s does not close; `OUTPUT_HIGH_BYTES` queued for `OUTPUT_STALL_MS` closes with 4008. Mutation-checked: reinstating the any-byte rule fails the first, skipping the stall sample fails the second. (4d89851) Deferred: none. No user-visible change, so the changelog fragment is unchanged. Checks: `bun run check fast` passes (typecheck, build, unit tests). --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
devswha
added a commit
that referenced
this pull request
Oct 13, 2026
…ped output (#968) ## Problem A phone put away while its pane stays attached comes back to "Terminal output stopped because this device could not keep up." and a dead terminal for the whole PC. The pane stays attached in two cases: a message queued from this tab (`queueWaits`), or a mirrored pane (`fixedGridRef`). Its frozen page sends no `pty-ack`, so the server's 2 s stall check closes it with 4008. Unlocking the phone does not recover it. The only ways out are the banner's Reconnect link, which reloads the whole app, or picking another pane. This is stability-audit findings connection-2, history-2 and moshi-2. ## Cause - On a 4008 close, `HerdrSocket` sets its stopped flag and schedules no reconnect. `wake()` refuses while the output is stopped (intended: no automatic reconnect loop). - Only `attach()` clears that flag. `PaneTerminal.back()` calls `resume()`, which attaches, only for a released pane. A pane that kept its attach only gets `refit()`, which sends a resize into a closed socket. - A frozen page often reads the server's close only after it resumes, after `visibilitychange` and `back()` have already run. Also, the 2 s stall clock can still run out while the page catches up on the ACKs it held back. So checking visibility when the close arrives is not enough. ## Fix - `src/lib/ws.ts`: - New getters `outputStopped` and `stoppedWhileHidden`. The private field is renamed to `stopped`. - A 4008 counts as the hidden page's in three cases: it came while the page was hidden; it came while the page had been hidden and not yet shown; or it came within `SHOWN_GRACE_MS` (5 s) of the page being shown again. - A page that connects while hidden counts as put away until it is first shown. - The `attach()` that clears the stop also clears the mark and uses up the grace period. A second stall on the new connection while the page is in use is therefore final. - `wake()` still refuses a stopped output, as `src/AGENTS.md` requires. - `src/components/PaneTerminal.tsx`: - New `reattach()`. It clears `stalledRef`, the notice and `ended`, runs the `resume()` path (stream-order `\x1bc` reset, unwatch if watching, `socket.attach`), and restores `disableStdin`. The attach reconnects, and the connection's open replays every attach remembered for that PC. - It runs once when the page is back in use. It is called from `back()` when the close was read while the page was hidden. It is called from the `output_stalled` handler, in a microtask, when the close is read after the page was shown. - A 4008 while the page stays in use keeps today's behaviour: notice, no automatic reconnect. - The banner's Reconnect `<a href="?machine=&pane=">` (a full page reload) is now a `<button>` that runs the same in-place `reattach()`. The label is unchanged, so no i18n entries were added. - Docs: `docs/terminal-flow-control.md` step 5 and the QA paragraph, and the 4008 rule in `src/AGENTS.md`. - Changelog fragment `changelog.d/recover-hidden-output-stall.md`. ## Tests - `src/lib/ws.test.ts`: four new cases. Each one fails without the fix, checked by stashing `ws.ts`. - A 4008 while hidden is marked. Showing the page reconnects nothing by itself. An attach after showing clears `outputStopped`, reconnects, and replays both remembered attaches. - A 4008 read 1 s after the page is shown again is marked. After the re-attach, a second 4008 while in use is final (`stoppedWhileHidden` false). - A 4008 long after the page came back is final. A later `wake()` and a hide/show do not reconnect, even 60 s later. - A page that connected while hidden counts as put away until it is first shown. - `scripts/output-browser-qa.ts`, real herdr, xterm and Chromium, run with `bun run check run`: **passed**. - The existing visible-stall flow now clicks the Reconnect **button** and still asserts no automatic reconnect loop. - A new scenario fakes `visibilityState`/`hasFocus`, puts the page away with ACKs held and the pane still attached (desktop, release-when-away off), and waits for the 4008. It then shows the page and asserts that the pane attaches again with no click, the notice goes away, and exactly one reconnect happened. - With the two recovery branches disabled, the new scenario times out at "shown page attaches again by itself". - It covers only the order where the close is read while the page is hidden. The other order is covered by the unit tests. This script is not part of CI's lanes. - `bun run typecheck`: passed. `bun run test:unit`: 3091 pass, 0 fail, 8 skip; this ran before the small follow-up commit, after which `ws.test.ts` and typecheck were run again and passed. `check full`/`concurrent` were not run. ## Notes - Stacked on #967: it builds on #967's `ConnectionState`/`endedEarly` and the wake/probe code in `ws.ts`. Retarget to main after #967 merges. - #951 adds its own `?machine=&pane=` Reconnect link in a composer notice. It is a different element, so there is no conflict, but that link still reloads the page. A follow-up could send it through the same re-attach. - #960 (stall clock driven by ACK progress, server side) and issue #781 (stop hidden clients from reaching 4008 at all) are the prevention half. This PR is client recovery only and does not touch the server. The queued message that the server's `stopSlowClient` closes is still #686/#874. - The banner also shows for `attach_conflict`, so the button re-attaches in place for that code too. The server no longer sends it; only a test mentions it. - The re-attach redraws the pane in view from a reset screen. Other panes of the same PC come back through the replayed attach and their snapshot, as they do after a pane pick today. ## Review follow-up (cc86059, 0303ac0) These fix the probe and held-draft code this branch carries from #967 (#967 itself was not updated). Fix: 1. (high) Hiding the page during a probe released waiting sends on an unverified socket. `endProbe()` now records whether the probe was answered; `probeSettled()` lets a waiting submit, pending action or secret go only after a pong. A probe cancelled by hiding (or ended by the connection) settles them as `disconnected`, and the secret is cleared on that path. The secret still lives in the closure while it waits for the pong; that is inherent to waiting, and it is never sent unanswered. 2. (high) Ctrl+Enter under modifyOtherKeys (`ESC[27;5;13~`) passed the held-draft guard and committed the partial line. New pure `heldInputAction()` in `src/lib/draft.ts` decides by meaning: Enter itself (captured before the remap), any encoded Enter (`CSI 27;m;13~`, `CSI 13;m u`), any line break and chords are blocked with the existing "Not sent: send or discard the held input first." note. The input line (`sendTerminalLine`) and the composer (`submitComposerMessage`, new `held_input` code in `submitNote`) also refuse while a draft is held. 3. (medium) The pong returned before handlers ran, so a view that stored `inputReady=false` during the probe stayed disabled. The probe's pong now goes on to handlers after the state is updated, and PaneTerminal's 1 s poll also re-reads `canInput()` (covers the probe start, which has no frame). 4. (medium) Remembered ping support could drop an older bridge after a reconnect. A snapshot that leaves out `ping` now ends a probe in flight as answered (trusted as before) without counting a drop. A separate deadline for a snapshot that never comes was left out: on such a socket the probe's own two pings still decide. 5. (medium) Backspace now edits the held draft (`eraseFromDraft`, whole code points). A paste the draft cannot keep whole (line breaks) is refused with the same note instead of being lost silently. Line breaks are not held: Send types the draft with `sendInput`, so a held newline would run lines. 6. (low, not changed) Typing during a probe goes to the held draft. Buffering keys and flushing them on the pong would queue input typed into an unverified socket, against the never-queue rule in `src/AGENTS.md`; holding only after the first ping times out would send on a possibly dead socket for the first deadline, which defeats the probe. Left as a known UX trade-off for the maintainer to decide. Tests: - `src/lib/ws.test.ts`: three new cases (hidden page refuses waiting submit/pending action/secret, then a fresh probe's pong sends a new submit; the pong reaches handlers with `canInput()` true; a snapshot without `ping` ends a remembered probe and the connection is kept past 30 s). All three fail with `ws.ts` stashed. - `src/lib/draft.test.ts`: `heldInputAction` table (encoded Ctrl+Enter, CR/LF/Alt+Enter, Backspace, single- and multi-line pastes, pass-through controls) and `eraseFromDraft`. - `scripts/terminal-input-regression.ts`: with a held draft, the pane sends `ESC[>4;2m`, Ctrl+Enter shows the note and sends nothing, Backspace edits the draft. - `bun run typecheck` passed; `bun run test:unit` 3099 pass, 0 fail, 8 skip; `bun run build` then `bun run check run bun scripts/ui-regression.ts` passed (all PASS, exit 0). `check full`/`concurrent` not run. ## Merge-session review (d0b66cc..HEAD) Fixed: 1. (low) A probe the hidden page cancelled while a submit, pending action or secret still waited for the snapshot let the frame go out unverified (`probeSettled()` only counted a probe whose timer was still running). Requests now read a probe generation (`probeMark()`) before the snapshot wait; a probe in flight then, or started during the wait, counts even if it already ended, and only its pong lets the request go. Test: `src/lib/ws.test.ts` "refuses a submit, a pending action and a secret whose probe the hidden page cancelled while they waited for the snapshot" (fails without the fix). 2. (low) `held_input` was missing from `submitNotTyped()`, so Send now on a local held queue row refused for a held terminal draft turned the row "uncertain" (Copy only). Added, with a case in `src/lib/compose.test.ts`. 3. (medium, merge coordination with #956) `heldInputAction()` now blocks line breaks, encoded Enter and pasted tabs before it asks `applyToDraft()`, so its answer no longer changes when #956 makes `applyToDraft()` fold breaks into a space. `eraseFromDraft()` now follows #956's Backspace rule: it leaves a truncated draft alone and returns `EMPTY_DRAFT` when erased to nothing. Checked with a throwaway no-commit merge of #956 into this head: `src/lib/draft.test.ts` passes (30/30). Policy kept: Enter beside a held draft is refused with "Not sent: send or discard the held input first." (this PR), not folded into a space with the left-out notice (#956). #956's left-out path still applies to the chunk that starts a draft. For the restack onto main once #956 is merged: - `scripts/terminal-input-regression.ts` conflicts textually. Take this PR's post-ready block. In #956's not-ready step, the Enter pressed with "a" held is now refused: expect the "Not sent" note and draft text "a" (no left-out notice), and adjust the reload/Send expectations from "a " to "a" accordingly. - Keep one Backspace path: replace `setDraft(eraseFromDraft)` in PaneTerminal with `setDraft((prev) => applyToDraft(prev, input))` (#956's ERASE) and drop `eraseFromDraft` and its tests. Keeping `eraseFromDraft` instead fails typecheck after #956 (`InputDraft` gains a required `leftOut`, so its test fixtures need `leftOut: false`); the throwaway merge ran `bun test` only. Deferred: - Item 6 of the review follow-up above (typing during a probe goes to the held draft) is still a maintainer decision. Checks: `bun run check fast` passed (typecheck, build, unit 3101 pass / 0 fail / 8 skip). `CI=1 bun run check run --build bun scripts/ui-regression.ts` passed (terminal input, held input and Safari replay steps included). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
A phone on a weak mobile link (about 1 Mbit/s) opens, or comes back to, a busy pane that a desktop tab already shows. It gets "Terminal output stopped because this device could not keep up." (4008) within about 2 s, while it is still receiving. Every pane of that PC drops on the phone, and the desktop tab's output freezes for up to 2 s, because the server pauses the shared pty for the phone meanwhile. This is stability-audit finding moshi-3.
Cause
MAX_REPLAY_BYTES= 256 KiB, the same asOUTPUT_HIGH_BYTES. Once the attachment has streamed more than that, the replay frame alone blocks the joiner's window.reconcileOutputstarts the 2 s stall clock at the first blocked check, which is when the frame is queued. The client can only ACK after the whole frame has crossed the link and xterm has parsed it, and with JSON escaping the frame is 290 KB or more on the wire. A slow link cannot do that in 2 s.paused, so the pty everyone shares stops.Fix
This change is flow control only, on this PC's bridge.
OutputWindow.check(buffered, now)returnsflow,pauseorstopfor an ACK client.reconcileOutputuses it. Clients without ACKs keep the old transport-only path.acknowledgedrestarts the stall clock. A duplicate or out-of-order ACK does not restart it. A blocked client whose ACKs have not moved for 2 s still gets 4008.OUTPUT_PAUSE_MAX_MS(10 s) in a row, however it acknowledges. A client that ACKs a byte at a time, or a phone slower than about 19 KiB/s, can no longer cap every peer at its own rate. Draining from the high to the low watermark (192 KiB) takes 6 s at 32 KiB/s, so an honest slow phone fits.OutputWindow.join(replay)is called right before the replay frame is sent. Until the joiner's first ACK, it gets a budget sized to that frame as serialized (wireBytes, JSON escaping included, where an ESC costs six bytes) instead of the 2 s deadline: 2 s plus the frame at 32 KiB/s, at most 15 s. Within that budget the joiner never pauses the shared pty. Only its own window grows, andOUTPUT_HARD_BYTESstill bounds it. Flow credit and offsets still count payload bytes.MAX_REPLAY_BYTESis now 128 KiB, half the high-water mark, so a join no longer blocks the joiner's window on its own. The changelog says so.server/AGENTS.mdanddocs/terminal-flow-control.mdare updated to describe the new rules.Tests
server/output-window.test.tscases, which fail without the fix:stop(4008).pausethe pty, its budget is capped at 15 s, and a full transport queue still stops it.bun run typecheck: passed.HERDR_TEST_MODE=unit bun test ./server/output-window.test.ts: 14 pass.bun run test:unit: 3077 pass, 0 fail, 8 skip.bun run check run bun test ./server/output.contract.test.ts(real herdr): 7 pass.bun run buildthenbun run check run bun scripts/output-browser-qa.ts: passed, with the overload notice, reconnect action and manual recovery all working.bun run check fast/fullnot run.Notes
fix(relay)) changesserver/machine-relay.ts: remote-PC connections still close after 2 s of any queued bytes on main. That PR owns the relay's stall rule, so this PR leaves the relay alone (a progress-based relay clock was tried here and dropped to avoid duplicating it). fix(relay): stop a relayed pane only past 256 KiB queued, like this PC #952's rule (clock only while 256 KiB or more is queued) still does not count drain progress. A relayed ESC-dense replay frame of 256 KiB or more that drains slowly can therefore still trip it. That belongs to fix(relay): stop a relayed pane only past 256 KiB queued, like this PC #952 or a follow-up.fix/late-joiner-screen) is complementary and does not duplicate this PR. fix(terminal): draw a late joiner of a busy pane from herdr's own screen #939 changes what a late joiner is drawn from (herdr'spane.readscreen instead of the tail). This PR changes only how the flow window treats the joiner. The two touch adjacent lines in theattachhandler and inoutput-window.ts/its test, so whichever merges second has a small conflict. When resolving it, fix(terminal): draw a late joiner of a busy pane from herdr's own screen #939'sjoinFromScreenshould callclient.data.output.get(paneId)?.join(frame)(the replay text, not a byte count) right before itssendOutput(client, paneId, screen + held.join("")). fix(terminal): draw a late joiner of a busy pane from herdr's own screen #939's fallback (() => tail) is then also bounded to 128 KiB.wireBytesstringifies the replay once more beforesenddoes. This happens once per join, at most 128 KiB.presence:false, the server-side grace window for an app-switcher peek (moshi-6). That is a follow-up. Also left out: WebSocketperMessageDeflate.Merge-session review
Fixed (commits 61de841, 355e037):
OutputWindow.checknow counts the shared WebSocket send queue against a window only while that window has more thanOUTPUT_LOW_BYTESof its own outstanding. A quiet, fully ACKed split pane on the same socket as a busy joiner is no longer paused (freezing its pty for desktop peers) and then closed with 4008.OUTPUT_HARD_BYTESon the queue still stops every pane, and the pane that owns the backlog still pauses or stops. Regression test: idle window at 300 KiB buffered staysflowpast 2 s and 10 s.join(replay, ahead, now); the attach handler passesclient.getBufferedAmount(), so a reconnect that re-attaches several panes back to back gives each replay time for the frames ahead of it (still capped at 15 s). Regression test fails against the old budget.write(bytes, wire)records each frame's serialized size; the stall deadline is nowOUTPUT_STALL_MSplus the oldest unACKed frame's crossing time at 32 KiB/s (capped so the total stays within 15 s). Regression test: 128 KiB ESC-dense replay plus two 64 KiB colored frames, replay ACK at 4 s, no stop at ~6.1 s, and a silent client is still stopped once that crossing time is up.server/AGENTS.mdand the changelog fragment were updated together. Revert just this part of 61de841 if that trade is not wanted.wireBytesnow runs once per ACK frame insendOutput(not only once per join), one extraJSON.stringifyof the payload.server/output.contract.test.tscase: an operator floods a pane, a second ACK client attaches and does not ACK its replay for 3 s; it stays open and the operator keeps receiving (> 64 KiB in the 2 s window), then it ACKs and carries on. Commenting out thejoin()line makes it fail (operator got 12 KiB). Timing margin for a future flake: the joiner ACKs at ~3 s, and at the flood's ~180 KB/s ceiling (pythontime.sleep(.01)) the 1 MiB hard budget would stop it at ~5 s.// fixed wait: ...(they prove nothing stalls for a set time);scripts/fixed-sleeps.jsonwas not raised.Mutation checks: reverting each of the three
output-window.tsfixes fails its new unit test; removing thejoin()call fails the contract case.For #939's conflict resolution:
joinnow takes(frame, ahead), sojoinFromScreenshould callclient.data.output.get(paneId)?.join(frame, client.getBufferedAmount()).Checks:
bun run check fastpassed (unit 3080 pass, 0 fail);bun run check run bun test ./server/output.contract.test.ts8 pass.Deferred: none from this review. The relay finding stays with #952 as noted above.
🤖 Generated with Claude Code