Repository navigation
Conversation
The daemon sent every terminal's output over the shared session socket, whether or not any client was attached, and paced it only for a visible, acknowledging browser. A terminal flooding output before any client attached filled the 32 MiB session send queue on a slow link, and the daemon dropped and reopened its session in a loop. The server now turns a terminal's live stream on with `terminal.stream` just before it attaches a client (or catches clients up after a daemon reconnect) and off when the last client leaves. Unstreamed output stays in the daemon's bounded scrollback ring and reaches clients through the attach replay. A streamed terminal is always paced by acknowledgements; with no visible acknowledging client the server acknowledges output as it arrives. `terminal.flow-control` is replaced by `terminal.stream`, so HOST_DAEMON_PROTOCOL_VERSION goes from 272 to 273. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
deleted the
bb/6748-bound-terminal-output-before-any-client-att-thr_82yawqbfrj
branch
November 20, 2026 17:52
ymichael
added a commit
that referenced
this pull request
Nov 20, 2026
…binary (#7874) ## Human comments ## What was wrong Everything a daemon sends to the server shares one session WebSocket, and the daemon wrote it in arrival order. A file download sent each 1 MiB chunk as one ~1.4 MB base64-in-JSON frame. A streamed terminal can have up to 1 MiB of unacknowledged output in flight (#7883), and the daemon handed it to the socket until 1 MiB sat in its buffer; more sat below that in kernel and network buffers. A small RPC reply, keystroke echo, heartbeat or event behind that data waited for it to drain. On current main, with #7881's compression and #7883's paced streaming, replies on a 45 ms / 3.6 MB/s relay link take ~414 ms during a download and ~250 ms during a terminal flood (55 ms idle). File transfer was also slow because it ran one 1 MiB RPC at a time and paid 1.34× in base64. Measured in the #6748 transport report. ## What changed - **Daemon send order** (`apps/host-daemon/src/session-send-queue.ts`, `server-connection.ts`). Terminal output and `host.read_file_chunk` replies are bulk. They queue per terminal or per chunk RPC, and the queues take turns. Everything else goes straight out: RPC replies, heartbeats, events, and stream messages under 4 KiB whose stream has nothing queued (keystroke echo). A terminal's exit, error and replay messages stay behind its own queued output. - **Bulk send window** (`apps/host-daemon/src/stream-send-window.ts`). Bulk is written only while the ws buffer holds ≤ 64 KiB and the bulk the server has not acknowledged fits a window. The window adapts between 64 KiB and 4 MiB, ±64 KiB per round trip, Vegas-style: - it grows while ack round trips of full-size (≥ 32 KiB) frames stay near the lowest seen in the last 10–20 s; - it shrinks while its own bulk keeps > ~144 KiB and > 10 ms queued. - The window, not `bufferedAmount`, bounds what sits in kernel and network buffers ahead of a reply. - The server's sequencer acknowledges every 32 KiB instead of 256 KiB. - Draining is driven by ws write callbacks instead of a 10 ms poll. - **Binary file chunks.** `host.read_file_chunk` returns raw bytes: - The sequencer frame becomes a binary WS message: a 4-byte header length, the usual JSON frame, then the bytes. It is retained and replayed like text frames. The contract codec (`encodeHostDaemonDaemonWsMessage` / `decodeHostDaemonDaemonWsMessage`) moves `result.content` into and out of the binary part. - Chunks are 64 KiB (`HOST_FILE_CHUNK_MAX_BYTES`). - `createFileStreamResponse` keeps up to 16 daemon reads in flight and still delivers in order. A failed chunk aborts the reads still in flight. - **Compression (#7881) rule.** The daemon's ws `send` compresses text frames only, so binary chunk frames are never deflated. This replaces #7881's `sendUncompressed` path and keeps its behaviour: file bytes cross uncompressed, everything else as before. - **Wire change:** `HOST_DAEMON_PROTOCOL_VERSION` 275 → 276. Changed: the chunk result type, the binary frames, and the ack cadence. - **Docs:** `docs/debugging-and-qa.md` (chunk transfer and send order). Not changed: the server → daemon direction still writes in order. Its bulk (attachments, plugin artifacts) goes over separate HTTP requests. ## How you verified **Numbers.** I used the #6748 measurement harness and its shaping proxy (FIFO bottleneck, 512 KB queue) on one M4 Mac, at host load ~2. - Two full stacks ran side by side: origin/main `81b1f612632` (includes #7881 and #7883) and this branch. Each ran an isolated `start:worktree` server bound to `0.0.0.0`, with its own client daemon reaching it through the shaper at the LAN address. The route is non-loopback, so #7881 compression is on in both stacks. - Runs were interleaved main/branch with the order alternating per round. - Cells are median/p95 in ms; "·" separates the two rounds; n is samples per round. - "Download" streams a 16 MiB (relay) or 64 MiB file in a loop. "Terminal flood" is `head -c 1M /dev/urandom | base64` in a loop. "Text flood" `cat`s 400 TypeScript files in a loop (compresses ~3×). Relay, 45 ms / 3.6 MB/s: | | origin/main | this PR | |---|---|---| | RPC during download | 414/422 · 414/424 (n=45, 45) | **97/102 · 96/101** (n=136, 137) | | echo during download | 413/423 · 413/423 | **94/100 · 94/100** | | RPC during terminal flood | 248/271 · 252/271 (n=69, 67) | **89/106 · 89/96** (n=142, 143) | | echo during terminal flood | 247/273 · 251/270 | **89/105 · 88/95** | | RPC during text flood | 107/119 · 107/120 (n=127, 129) | **59/68 · 61/87** (n=181, 176) | | file download MB/s | 2.13 · 2.13 | **3.29 · 3.29** | | first byte of a download | 519 · 529 ms | **133 · 130 ms** | | terminal flood MB/s | 3.43 · 3.43 | 3.45 · 3.43 | | text flood MB/s | 7.68 · 7.84 | 7.61 · 7.66 | | idle RPC / echo (n=100) | 55/59 · 56/59 / 53/55 · 53/55 | 56/59 · 55/58 / 53/56 · 53/55 | Far relay, 120 ms / 3.6 MB/s: | | origin/main | this PR | |---|---|---| | RPC during download | 490/503 · 493/506 (n=39, 39) | **171/181 · 170/183** (n=92, 93) | | RPC during terminal flood | 251/272 · 249/271 (n=70, 69) | **159/170 · 159/172** (n=97, 97) | | file download MB/s | 1.83 · 1.81 | **2.49 · 3.18** | | first byte | 664 · 671 ms | **286 · 290 ms** | | terminal flood MB/s | 3.39 · 3.36 | 3.39 · 3.39 | LAN emulation, 3 ms / 25 MB/s: | | origin/main | this PR | |---|---|---| | RPC during download | 25/30 · 25/32 (n=265, 264) | **15/19 · 16/21** (n=305, 302) | | RPC during terminal flood | 34/44 · 34/43 (n=239, 239) | **18/21 · 18/21** (n=294, 293) | | file download MB/s | 14.66 · 12.85 | **19.78 · 19.77** | | terminal flood MB/s | 22.20 · 22.06 | 22.02 · 22.00 | Unshaped LAN address (~loopback speed): | | origin/main | this PR | |---|---|---| | RPC during download | 6.0/10.0 · 5.6/9.3 (n=351, 354) | 4.9/7.8 · 4.9/8.0 (n=364, 364) | | RPC during terminal flood | 21/24 · 20/24 (n=286, 286) | **5.5/7.4 · 5.3/7.2** (n=359, 360) | | RPC during text flood | 14/20 · 11/17 (n=314, 327) | 11/14 · 11/14 (n=327, 330) | | file download MB/s | 124 · 121 | **290 · 276** | | terminal flood MB/s | 33.5 · 33.4 | 33.3 · 33.0 | **Known cost.** On the relay, text-heavy output that competes with interactive traffic moves a little slower: - 7.90/7.87 → 5.95/6.77 MB/s while the RPC and echo probes run alongside it. - On its own the text flood is at parity (7.68/7.84 vs 7.61/7.66). - The window counts uncompressed bytes, so with ~3× compression it treats ~48 KB of real queue as its 144 KiB limit and backs off early. - In exchange, replies during that flood take 59–61 ms instead of 107 ms. **Why an adaptive window.** Measured, not assumed: - Send order plus a 64 KiB high-water mark alone did not help terminal floods: the 1 MiB window moved into kernel buffers. - A fixed 256 KiB unacknowledged limit halved far-relay terminal throughput. - The adaptive window's queue band was tuned on current main with compression on: - 32/96 KiB kept far-relay replies at ~135 ms, but cost ~12% far-relay throughput (3.0 vs 3.4 MB/s). - 64/192 KiB reached parity but raised relay replies to ~106 ms. - 48/144 KiB (shipped) reaches parity on every profile, with relay replies at ~89 ms. **Tests:** - Send ordering under load: replies and echo go ahead of queued bulk; per-terminal order holds, including the exit; terminals take turns; bulk waits for and resumes on server acknowledgement. - File chunk replies go out as binary frames and other replies as text. - Against a real compressing `ws` server, text frames are compressed and binary frames are not. - `StreamSendWindow`: grows at base delay; settles near path capacity; backs off when delay jumps; ignores small-frame round trips. - Sequencer binary frames, and the codec rejecting bytes on other messages. - Daemon file stream: reads ahead in order; a failed chunk aborts the reads still in flight. **Commands:** - `pnpm exec turbo run typecheck lint --filter='...[origin/main]'`: 144/144. - `pnpm exec turbo run test --filter=@bb/host-daemon-contract --filter=@bb/host-daemon --filter=@bb/server`: contract 94, daemon 896, server 4368 passed. - After the final band change: `turbo run typecheck lint test --filter=@bb/host-daemon`: 8/8. **Live check.** On the earlier revision of this branch I ran an isolated instance with a second daemon behind the 45 ms shaper: an agent turn with an attachment, a file preview, and a terminal in the app. On this rebase: - Through the branch daemon on the 45 ms LAN-address route, a Claude Code turn with an uploaded attachment returned its token and ran a command in the client host's workspace. - 16 MiB and byte-range downloads through the branch daemon matched `shasum` of the source. - The proxy tally confirmed compression on both stacks (0.44 wire bytes per decoded terminal byte). Refs #6748 > AGENT GENERATED 🤖 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.
Human comments
What was wrong
The daemon sent every terminal's output over the shared session WebSocket, whether or not a client was attached. Output was paced only when a visible browser that acknowledges output was attached: the server turned
terminal.flow-controlon only for such a client. With no client attached, nothing pushed back on the PTY. The server dropped output nobody was watching (hasTerminalClientsis false), but it had already crossed the link. On a slow route a flooding terminal filled the daemon's 32 MiB send queue (TERMINAL_SOCKET_MAX_QUEUE_BYTESinserver-connection.ts). The daemon then abandoned its session withterminal-backpressure, reconnected, and overflowed again about 0.6 s later. The terminal kept flooding across reconnects, so this never ended. Every RPC, terminal and agent turn on that host failed. The same unpaced path applied to attached clients that were hidden, stalled, or did not send acks. Found by the #6748 transport work.What changed
The server subscribes to terminal output (
apps/server/src/services/terminals/terminal-output-flow-control.ts,terminal-session-lifecycle.ts).terminal.streamwithenabled: true. It also sends it before catching clients up after a daemon reconnect.enabled: falsewhen the last client detaches or its attach fails.The daemon keeps unsubscribed output local (
apps/host-daemon/src/terminals/terminal-manager.ts).releaseOutputStreams).A streamed terminal is always paced by acks.
Wire change:
terminal.flow-controlis replaced byterminal.stream(same fields, new meaning: when disabled, the daemon does not send output).HOST_DAEMON_PROTOCOL_VERSION272 → 273.Docs: "Terminal Output Streaming" in
docs/debugging-and-qa.md.Interaction with #7874. #7874 rewrites the daemon send path (per-stream queues, adaptive window), and it keeps a session-wide queue limit that drops the session. This PR does not touch
server-connection.ts. It changes what terminal output enters that path: nothing for terminals without a client, and at most a 1 MiB window per streamed terminal. The two compose. #7874 gets RPCs ahead of the bounded terminal windows; this PR keeps those windows bounded. Both bump the protocol to 273, so whichever lands second needs 274.How you verified
Live repro. Ran an isolated
start:worktreeserver and a second enrolled daemon behind the #6748 shaping proxy (45 ms RTT, 3.6 MB/s, 512 KiB queue). A script created 16 host-path terminals runningwhile :; do head -c 1048576 /dev/urandom | base64; donewithout attaching to them, probedpaths/existevery 250 ms, then attached one flooding terminal and ran keystroke echo on acatterminal.origin/main (9f4c156): the daemon overflowed before the second terminal opened. Terminal create returned
502 host_disconnected, every RPC returned 502, and the loop continued until the daemon was stopped. One terminal was enough. Daemon log:This branch: 0 overflows and 0 disconnects (one connect at daemon start).
terminal.outputcrossed the link until a client attached.Unpaced clients: 8 flooding terminals, 4 attached without acks and 4 hidden, for 25 s. 68 MB was delivered at link rate, with 0 RPC failures and 0 disconnects. RPC latency was median 782 ms here: RPCs wait behind 8 × 1 MiB of bounded terminal windows. That is the head-of-line blocking #7874 removes. On origin/main this path sends unpaced, the same way as the unattached flood.
Agent turn and UI, with the 16 unattached floods running on the shaped host:
seq 1 200000; echo BURST-DONErendered to the end.BURST-DONE.terminal run,create/send/wait/resize/output/closepassed on that host.Tests:
terminal-manager.test.ts, "keeps a flood bounded in scrollback without sending it until the server streams the terminal": 16 MiB of output without a stream sends noterminal.output, never pauses the PTY, and replays a ≤ 4 MiB tail ending at the latest output. Output afterterminal.streamis sent live. With the daemon's "no stream, no send" guard removed, this test and the release test fail.terminal-output-flow-control.test.ts: the stream is enabled only while a client is subscribed; pacing by the fastest visible client; receipt acks when no client paces; receipt acks for a stalled client until it catches up; re-binding to a reconnected daemon session while ignoring the old one.public-terminals.test.ts:terminal.streamprecedesterminal.attachfor browser attaches and reconnect catch-up; a non-acking browser gets receipt acks.pnpm exec turbo run typecheck lint lint:type-aware test --filter=@bb/host-daemon --filter=@bb/server --filter=@bb/host-daemon-contract: all green (host-daemon 887, server 4343, contract 92 tests).🤖 Generated with Claude Code