Repository navigation
Compress daemon and terminal WebSockets for peers on another machine - #7881
Merged
Merged
Conversation
/internal/ws and /ws/terminals/:id always declined permessage-deflate, so terminal output (base64 inside JSON) and daemon RPC traffic crossed LAN, Tailscale and other direct routes at full size. They now negotiate the same level-1, 1 KB-threshold compression as the browser /ws when the peer is not on this machine: a non-loopback address, or a request forwarded by a proxy (X-Forwarded-For / Forwarded). Same-machine peers stay uncompressed. - The server compresses daemon frames and terminal output when negotiated. - Daemons offer level-1 compression and send host.read_file_chunk replies uncompressed: deflating file bytes cut fast-link downloads from ~120 to ~31 MB/s. - No protocol bump: compression is negotiated per connection, older daemons already offer it, and older servers decline it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ssion-thr_6xtgkb7avh
…mpression Daemons shipped before this change offer permessage-deflate with ws defaults, so against this server they compress every frame at level 6, file chunks included. Measured on an unconstrained link, 30 MB downloads through such a daemon ran at ~31-40 MB/s instead of ~120 MB/s. The bump makes enrolled daemons update to the level-1, file-chunks-uncompressed sender. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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
/internal/ws(host daemons) and/ws/terminals/:idalways declinedpermessage-deflate(declineWebSocketCompression). #6209 compressed only the browser/ws. So terminal output (base64 inside JSON, 1.4× the decoded bytes) and daemon RPC traffic crossed LAN, Tailscale and other direct routes at full size. On a 3.6 MB/s link a text-heavy terminal topped out at ~2.4 MB/s and buried replies behind it. Measured in the #6748 transport report: level-1 deflate brings terminal text to ~33% of its wire bytes.What changed
apps/server/src/ws/compression.ts,server.ts):X-Forwarded-For/Forwardedheader (declineSameMachineWebSocketCompression). Requests forwarded by a local proxy such as Tailscale Serve count as remote.DaemonChanneland the terminal send path now passcompress: true. hono's ws adapter otherwise sends uncompressed even when compression was negotiated.apps/host-daemon/src/websocket-constructor.ts,server-connection*.ts):host.read_file_chunkreplies go out uncompressed through a newsendUncompressed. partysocket'ssenddrops ws options, so this writes to the underlying ws directly.permessage-deflate(thewsdefault) and handle it. But withwsdefaults they compress every frame at level 6, file chunks included: against this server, 30 MB downloads through a pre-PR daemon on an unconstrained link ran at ~31 MB/s (random) / ~40 MB/s (text) instead of ~120 MB/s. The bump makes enrolled daemons update to the level-1 sender that leaves file chunks uncompressed.docs/configuration.md.perMessageDeflate: false. Event POST bodies (HTTP) are also unchanged.How you verified
Numbers. I used the #6748 harness on one M4 Mac, with an origin/main
basestack and this branch. Each isolatedstart:worktreeserver was bound to0.0.0.0. Each client daemon reached its server through the shaping proxy at the machine's LAN address (non-loopback, so compression applies). Runs were interleaved base/branch with the order alternating per round.find apps/server/src -name '*.ts' | head -400 | xargs catin a loop.Wire bytes on the daemon leg for the same text flood (proxy tally): 1.42 bytes per decoded terminal byte on main vs 0.44 here (3.2× fewer).
Cost.
Tests:
websocket-compression.test.ts: a forwarded or remote peer gets compressed daemon and terminal sockets. A 400-entry daemon message crosses in < 1/4 of its bytes; this fails without thecompress: truesend flag. Loopback peers still decline. The same-machine rule is covered for IPv4, IPv6, IPv4-mapped and forwarded cases.server-connection-support.test.ts: against a real compressingwsserver, a normal send compresses (< 1/4) andsendUncompresseddoes not.server-connection.test.ts:host.read_file_chunkreplies take the uncompressed path; other replies do not.Commands:
pnpm exec turbo run typecheck lint --filter='...[origin/main]': 11/11.pnpm exec turbo run test --filter=@bb/server --filter=@bb/host-daemon: server 4344 passed, host-daemon 885 passed. These ran before the uncompressed-chunk change; I reran the affected daemon files after it (server-connection*.test.ts,websocket-constructor.test.ts,app.test.ts).Live check. I used an isolated instance with a second daemon on the LAN address behind the 45 ms / 3.6 MB/s shaper, and the app loaded from the LAN address in a browser:
bb6748-42,19999,20000forecho bb6748-$((6*7)) && seq 1 20000 | tail -2.Interaction with #7874. The two PRs merge with conflicts in the daemon send path; they are independent but touch the same lines. Whichever lands second should keep #7874's binary chunk frames out of compression. In the local merge I measured, the rule "compress text frames only" in the ws
sendoverride replacessendUncompressed.Refs #6748
🤖 Generated with Claude Code