cc-viewer 1.9.26 → 1.9.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.html CHANGED
@@ -21,7 +21,7 @@
21
21
  // 整体显示大小已弃用 CSS zoom:Electron 改用 webFrame.setZoomFactor(首屏抢占见
22
22
  // electron/tab-content-preload.js),纯浏览器交由用户用浏览器自带快捷键缩放,故此处不再设 zoom。
23
23
  </script>
24
- <script type="module" crossorigin src="./assets/index-Dn7twftJ.js"></script>
24
+ <script type="module" crossorigin src="./assets/index-CINNXEHT.js"></script>
25
25
  <link rel="modulepreload" crossorigin href="./assets/vendor-antd-VJVAjRBJ.js">
26
26
  <link rel="modulepreload" crossorigin href="./assets/vendor-codemirror-D2yaEhu3.js">
27
27
  <link rel="modulepreload" crossorigin href="./assets/vendor-mdxeditor-DKI8QSRd.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-viewer",
3
- "version": "1.9.26",
3
+ "version": "1.9.28",
4
4
  "description": "Claude Code logging, visualization, and management toolkit — launch a web viewer alongside Claude Code with full request/response tracing, proxy, and mobile support",
5
5
  "license": "MIT",
6
6
  "main": "server.js",
@@ -36,7 +36,10 @@
36
36
 
37
37
  import { reportSwallowed } from './error-report.js';
38
38
 
39
- /** Per-connection cap on buffered bytes (mirrors the mux QUEUE_MAX_BYTES). */
39
+ /** Per-connection cap on buffered bytes. Counted in real UTF-8 bytes (Buffer.byteLength),
40
+ * matching the mux QUEUE_MAX_BYTES units so a full proxy can never overflow the socket
41
+ * queue it replays into. For CJK content (JSON does not escape it) this bounds the proxy
42
+ * to roughly 1/3 the *character* count an ASCII session gets — the honest memory measure. */
40
43
  export const ATTACH_BUFFER_MAX_BYTES = 32 * 1024 * 1024;
41
44
 
42
45
  const CONV_FRAME_PREFIX = 'event: v3_conv\ndata: ';
@@ -63,7 +66,7 @@ export function createAttachBufferClient({ project, instance, maxBytes, onOverfl
63
66
  overflowed: false,
64
67
  write(text) {
65
68
  if (client.destroyed || client.overflowed) return true;
66
- const len = typeof text === 'string' ? text.length : (text ? text.length : 0);
69
+ const len = text ? Buffer.byteLength(text, 'utf8') : 0;
67
70
  if (client.bytes + len > limit) {
68
71
  // Overflow: degrade to today's pre-fix behavior (drop the window's
69
72
  // increments) rather than risk an unbounded queue. Never replay a
@@ -135,30 +138,66 @@ function _isCoveredConvFrame(frameText, convCoverage) {
135
138
  * any v3_conv frame the cold bundle already covered. Safe to call with a null
136
139
  * or overflowed client (no-op). Stops at the first dead sink or write error.
137
140
  *
138
- * @param {{write: (s:string)=>any, alive?: ()=>boolean}} sink
141
+ * Credit-based (async): the cold-load window now spans real time (the mux cold load is
142
+ * backpressured), so the replay may be multi-MB and must NOT dump synchronously into a
143
+ * possibly-congested socket. Each frame goes through the same contract as the cold load
144
+ * (write; if pressured, await drain; abort on a dead sink). `client.bytes` is decremented
145
+ * as frames are replayed so the cap tracks the LIVE backlog, not cumulative arrivals.
146
+ *
147
+ * Atomicity: the proxy is NOT cleared here. The caller passes an `onDrained` callback that
148
+ * — synchronously inside the final pass (no yield between the last write and it) — splices
149
+ * the proxy out of deps.clients, pushes the real registrable, and clears the proxy. That
150
+ * single synchronous step is what keeps the anti-flicker invariant: no broadcast can
151
+ * interleave between the final replay and the swap (a frame arriving mid-await is appended
152
+ * to the still-registered proxy and replayed on the next pass).
153
+ *
154
+ * @param {{write: (s:string)=>any, alive?: ()=>boolean,
155
+ * needsDrain?: ()=>boolean, awaitDrain?: ()=>Promise}} sink
139
156
  * @param {object|null} client - the attach buffer client.
140
157
  * @param {Map<string,{seqs:Set<number>, baseSeq:number}>|null} convCoverage
141
- * @returns {{replayed: number, skipped: number}}
158
+ * @param {()=>void} onDrained - called synchronously when the queue is fully replayed (the
159
+ * caller MUST do the proxy→registrable swap here).
160
+ * @param {()=>void} [onAbort] - called synchronously when the replay aborts early on a dead
161
+ * sink or a write error; the caller MUST remove the proxy from the broadcast list here
162
+ * (the registrable is NOT registered on abort). Both callbacks are the ONLY cleanup points
163
+ * for the proxy — the caller cannot rely on dispose() to splice it after this returns.
164
+ * @returns {Promise<{replayed: number, skipped: number}>}
142
165
  */
143
- export function flushAttachBuffer(sink, client, convCoverage) {
166
+ export async function flushAttachBuffer(sink, client, convCoverage, onDrained, onAbort) {
144
167
  const result = { replayed: 0, skipped: 0 };
145
168
  if (!client || client.overflowed || client.destroyed) {
146
169
  if (client) client._clear();
170
+ if (onDrained) onDrained();
147
171
  return result;
148
172
  }
149
173
  const frames = client.frames;
174
+ const abort = () => { client._clear(); if (onAbort) onAbort(); return result; };
175
+ // The for-loop re-reads frames.length every iteration, so frames appended to the
176
+ // still-registered proxy during an await below are replayed in order (the anti-loss
177
+ // invariant). Replayed entries are nulled in place so the array does not retain the whole
178
+ // replayed volume for the duration of a long backpressured flush (memory bound), and
179
+ // client.bytes is decremented so the cap tracks the live backlog, not cumulative arrivals.
150
180
  for (let i = 0; i < frames.length; i++) {
151
- if (typeof sink.alive === 'function' && !sink.alive()) break;
181
+ if (typeof sink.alive === 'function' && !sink.alive()) return abort();
152
182
  const frame = frames[i];
153
- if (_isCoveredConvFrame(frame, convCoverage)) { result.skipped++; continue; }
154
- try {
155
- sink.write(frame);
156
- result.replayed++;
157
- } catch (err) {
183
+ frames[i] = null; // release the reference immediately
184
+ if (_isCoveredConvFrame(frame, convCoverage)) { result.skipped++; client.bytes -= Buffer.byteLength(frame, 'utf8'); continue; }
185
+ let ok;
186
+ try { ok = sink.write(frame); } catch (err) {
158
187
  reportSwallowed('sse.attach-buffer.flush', err);
159
- break;
188
+ return abort();
189
+ }
190
+ result.replayed++;
191
+ client.bytes -= Buffer.byteLength(frame, 'utf8'); // free the cap as the backlog drains
192
+ if ((!ok || (typeof sink.needsDrain === 'function' && sink.needsDrain())) &&
193
+ typeof sink.awaitDrain === 'function') {
194
+ await sink.awaitDrain();
160
195
  }
161
196
  }
162
- client._clear();
197
+ // Swap synchronously at the end of the final pass (no yield after the last write): the
198
+ // caller splices proxy→registrable and clears the proxy here, so nothing can land in a
199
+ // cleared-but-still-registered proxy.
200
+ if (onDrained) onDrained();
201
+ else client._clear();
163
202
  return result;
164
203
  }
@@ -133,10 +133,12 @@ export function needsDrain(res) {
133
133
  /**
134
134
  * Wait until the response's write target can accept more data (or the
135
135
  * connection dies, or timeoutMs elapses). On the plain path this is exactly
136
- * awaitDrainOrClose(res). On the compressed path the pressured stream is the
137
- * ENCODER (its 'drain' fires when compression consumes the input backlog) —
138
- * waiting on res 'drain' there can stall the full timeout, because compressed
139
- * output is 20-80x smaller and may never backpressure the socket at all.
136
+ * awaitDrainOrClose(res). On the compressed path the pressured stream may be the
137
+ * ENCODER (its 'drain' fires when compression consumes the input backlog) OR the
138
+ * socket (res 'drain'): when the caller wrote successfully (encoder accepted the
139
+ * input) but the socket is backpressured (res.writableNeedDrain), only res 'drain'
140
+ * signals recovery — the encoder never emits 'drain' because it never returned
141
+ * false. Wait on BOTH so a socket-level stall doesn't sit out the full timeout.
140
142
  */
141
143
  export function awaitWireDrain(res, timeoutMs) {
142
144
  const encoder = res._wireEnc;
@@ -147,6 +149,7 @@ export function awaitWireDrain(res, timeoutMs) {
147
149
  clearTimeout(t);
148
150
  encoder.off('drain', done);
149
151
  encoder.off('close', done);
152
+ res.off('drain', done);
150
153
  res.off('close', done);
151
154
  res.off('error', done);
152
155
  resolve();
@@ -154,6 +157,7 @@ export function awaitWireDrain(res, timeoutMs) {
154
157
  t = setTimeout(done, timeoutMs);
155
158
  encoder.once('drain', done);
156
159
  encoder.once('close', done); // encoder is destroyed on res close
160
+ res.once('drain', done); // socket-level recovery (encoder accepted the write)
157
161
  res.once('close', done);
158
162
  res.once('error', done);
159
163
  });
@@ -36,6 +36,25 @@
36
36
  * changes. The shim is a real EventEmitter because `awaitWireDrain`/`_safeSseWrite`
37
37
  * use on/once/off('drain'|'close'|'error') on it.
38
38
  *
39
+ * Backpressure (2026-11 rework): the mux does NOT use lib/ws-backpressure.js's
40
+ * gate (that gate's contract is "skip the send + resync on resume", which the mux
41
+ * inverts into "queue + replay" — see st.send). Instead a self-contained per-socket
42
+ * pump (a single setInterval) is the ONLY queue driver. Invariants:
43
+ * - a frame is queued only via enterBehind() (queue non-empty ⇒ _behind + pump armed);
44
+ * - 'drain' fires once the socket has headroom again (the pump dequeued bytes AND
45
+ * bufferedAmount <= HIGH_WATER, or the queue fully drains to <= LOW_WATER) — never
46
+ * while peak-congested, or woken producers would reflood the queue past the cap;
47
+ * - health is measured by the pump DEQUEUING bytes (a frame left the app queue), NOT
48
+ * by the bufferedAmount level: a full socket buffer is refilled to ~HIGH every tick,
49
+ * so its level never drops even for a fast-draining client. A queue with no byte
50
+ * movement for WS_MUX_STALL_MS is closed 1011 (an absolute 2× ceiling covers a
51
+ * pathological run of event-loop stalls), even while control pings keep flowing.
52
+ * Bulk producers (the /events cold loads, the attach-buffer replay) are credit-based:
53
+ * they `await sink.awaitDrain()` instead of dumping a whole multi-MB burst in one tick.
54
+ * The cap is per-socket and the credit is per-producer, so N concurrent bulk streams on
55
+ * one socket can still aggregate past it — a large single frame is the residual exposure
56
+ * (tracked as follow-up: rowsPayload/conv-line chunking).
57
+ *
39
58
  * Pure logic: no `ws` module dependency (the WebSocketServer class is injected) and no
40
59
  * routes/ dependency (serveStream is injected by server.js), so this stays L1 and
41
60
  * unit-testable with fakes — same house style as lib/ws-backpressure.js.
@@ -43,23 +62,30 @@
43
62
  import { randomBytes } from 'node:crypto';
44
63
  import { EventEmitter } from 'node:events';
45
64
  import { reportSwallowed as defaultReport } from '../lib/error-report.js';
46
- import { createBackpressureGate } from './ws-backpressure.js';
47
65
 
48
66
  const STREAM_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
49
67
  const HEARTBEAT_SEND_MS = 25_000; // app-level ping cadence (chisel: proxies kill idle conns)
50
68
  const HEARTBEAT_REAP_MS = 60_000; // no inbound frame for this long → terminate the socket
51
69
  const MAX_STREAMS_PER_SOCKET = 8;
52
- // Per-socket queue is a pure MEMORY SAFETY NET (the primary slow-consumer eviction is the
53
- // per-stream 30s backpressure rule inherited from _safeSseWrite). Sized above any legitimate
54
- // cold-load burst so it only trips on a genuinely wedged socket, never on a fast-producer
55
- // burst. Postmortem (2026-10-15): cc-viewer's own ~11MB v3 cold load exceeded the old 8MB
56
- // cap — the CAP RAISE is the load-bearing fix; the perMessageDeflate disable below is
57
- // prophylactic (it removes bufferedAmount inflation so the gate stops false-tripping, but
58
- // even with deflate on the 32MB cap absorbs the burst: measured peak 10.6MB).
59
- // 32MB covers ~40k-row sessions while still bounding a truly dead client's damage.
70
+ // Per-socket queue is a pure MEMORY SAFETY NET. With the credit-based producers the
71
+ // queue only ever holds the admitted quantum (O(one frame) once a producer waits), so
72
+ // 32MB is a generous bound that only trips on a pathological single frame or a bug —
73
+ // never on a legitimate cold load, however large. Counted in real UTF-8 bytes
74
+ // (Buffer.byteLength), so CJK sessions consume the cap ~3x faster in *characters*
75
+ // than ASCII — the byte bound is the honest memory measure. Postmortem lineage
76
+ // (2026-10-15): the cap was raised 8MB→32MB when cc-viewer's own ~11MB v3 cold load
77
+ // overflowed; perMessageDeflate stays disabled (it inflates bufferedAmount with
78
+ // zlib-pending bytes and would re-break the pump's progress detection).
60
79
  export const QUEUE_MAX_BYTES = 32 * 1024 * 1024;
61
- const HIGH_WATER = 1024 * 1024; // mirrors terminal's hysteresis band
62
- const LOW_WATER = 256 * 1024;
80
+ const HIGH_WATER = 1024 * 1024; // enter behind / stop flushing above this
81
+ const LOW_WATER = 256 * 1024; // exit behind only below this (hysteresis band)
82
+
83
+ /** Pump cadence: how often a behind socket tries to flush its queue. */
84
+ export const WS_MUX_PUMP_MS = 100;
85
+ /** Max bytes dequeued per pump tick (after the guaranteed first frame). */
86
+ export const WS_MUX_FLUSH_BUDGET_BYTES = 4 * 1024 * 1024;
87
+ /** Kill a socket whose queue makes no byte-progress (bufferedAmount never drops) for this long. */
88
+ export const WS_MUX_STALL_MS = 30_000;
63
89
 
64
90
  /** Per-stream application error codes (WS close-code range, graphql-ws 44xx semantics). */
65
91
  export const MUX_CODES = {
@@ -242,8 +268,6 @@ export function createStreamMuxServer({
242
268
  epoch = randomBytes(6).toString('hex'),
243
269
  setInterval: setI = setInterval,
244
270
  clearInterval: clearI = clearInterval,
245
- setTimeout: setT = setTimeout,
246
- clearTimeout: clearT = clearTimeout,
247
271
  now = Date.now,
248
272
  } = {}) {
249
273
  // perMessageDeflate DISABLED (2026-10-15, queue-overflow postmortem): with deflate on,
@@ -275,76 +299,149 @@ export function createStreamMuxServer({
275
299
  streams: new Map(), // streamId -> { sink, handle, disposed }
276
300
  lastInboundAt: now(),
277
301
  closed: false,
278
- queue: [], // FIFO of encoded frames held while behind
302
+ queue: [], // FIFO of { text, bytes } held while behind
279
303
  queuedBytes: 0,
280
304
  _behind: false,
281
- gate: null,
305
+ pumpTimer: null,
306
+ lastProgressAt: 0, // stall-guard clock: reset on byte progress OR a tick-gap stall
307
+ lastByteProgressAt: 0, // ABSOLUTE clock: reset ONLY when bufferedAmount truly dropped —
308
+ // the stall-guard reset never touches it, so a pathological
309
+ // run of >500ms event-loop stalls cannot postpone the kill forever
310
+ lastBuffered: 0, // bufferedAmount sampled at the previous pump tick
311
+ lastTickAt: 0, // last pumpTick wall time (event-loop-stall guard)
282
312
  pingTimer: null,
283
- flushTimer: null,
284
313
  report: reportSwallowed,
285
314
  send: null, behind: null, closeStream: null,
286
315
  };
287
316
  sockets.add(st);
288
317
 
289
- // Drain the queue as a BOUNDED trickle, not a single-tick flood: after each frame, re-check
290
- // bufferedAmount and stop the moment it climbs back over highWater (a slow consumer's socket
291
- // buffer would otherwise spike to many times the high-water mark in one resume tick). The
292
- // trickle self-reschedules (the gate's poll stops once it fires onResume, so we can't rely on
293
- // it to drive the next trickle); teardown clears the timer.
294
- const flushQueue = () => {
295
- if (st.flushTimer) { clearT(st.flushTimer); st.flushTimer = null; }
318
+ // ── Backpressure pump (the ONLY queue driver) ────────────────────────────
319
+ // One self-scheduling setInterval per socket. A frame is queued only via
320
+ // enterBehind() (so queue non-empty ⇒ _behind ∧ pump armed — the invariant the
321
+ // old gate+flushQueue pair violated, leaving a wedged queue with no driver).
322
+ const fireAllDrain = () => {
323
+ // A throwing 'drain' listener must not escape into the pump's timer callback (an
324
+ // uncaught throw there would kill the process). Drain listeners are optional.
325
+ for (const rec of st.streams.values()) {
326
+ try { rec.sink.emit('drain'); } catch (err) { reportSwallowed('ws.mux.drain', err); }
327
+ }
328
+ };
329
+ const armPump = () => {
330
+ if (st.pumpTimer || st.closed) return;
331
+ st.pumpTimer = setI(pumpTick, WS_MUX_PUMP_MS);
332
+ st.pumpTimer.unref?.();
333
+ };
334
+ const disarmPump = () => {
335
+ if (st.pumpTimer) { clearI(st.pumpTimer); st.pumpTimer = null; }
336
+ };
337
+ const enterBehind = (buffered) => {
338
+ if (st._behind) return; // ONLY on the false→true edge: re-arming on every
339
+ st._behind = true; // enqueue would keep resetting the progress clock and
340
+ st.lastProgressAt = now(); // let live traffic starve the stall watchdog forever.
341
+ st.lastByteProgressAt = now();
342
+ st.lastBuffered = buffered;
343
+ st.lastTickAt = now();
344
+ armPump();
345
+ };
346
+ const exitBehind = () => {
347
+ // Clear the producer-facing flag so a new write may direct-send, but do NOT disarm:
348
+ // the pump keeps watching bufferedAmount until the socket is fully drained (the
349
+ // queue-empty-but-still-buffered wedge below HIGH needs the stall watchdog too).
350
+ // Only wake waiters once there is real headroom (<= HIGH_WATER): firing drain at peak
351
+ // congestion (queue just emptied but buffered > HIGH) would let every woken producer
352
+ // re-enqueue a frame at the worst moment — the F2 reflood this redesign exists to prevent.
353
+ st._behind = false;
354
+ if ((st.ws.bufferedAmount || 0) <= HIGH_WATER) fireAllDrain();
355
+ };
356
+ function pumpTick() {
357
+ if (st.closed || st.ws.readyState !== 1) return disarmPump();
358
+ // Event-loop-stall guard: a gap > 5 ticks is OUR scheduling stall (a big synchronous
359
+ // cold-load stringify), not the client dying — reset the progress clock rather than
360
+ // count it against a healthy-but-paused consumer.
361
+ if (now() - st.lastTickAt > 5 * WS_MUX_PUMP_MS) { st.lastProgressAt = now(); }
362
+ st.lastTickAt = now();
363
+ let sentBytes = 0;
296
364
  while (st.queue.length && !st.closed && st.ws.readyState === 1) {
297
- if ((st.ws.bufferedAmount || 0) > HIGH_WATER) {
298
- st._behind = true;
299
- st.flushTimer = setT(flushQueue, 100);
300
- st.flushTimer.unref?.();
301
- return;
302
- }
303
- const text = st.queue[0];
304
- try { st.ws.send(text); } catch (err) {
365
+ if ((st.ws.bufferedAmount || 0) > HIGH_WATER) break;
366
+ if (sentBytes > 0 && sentBytes >= WS_MUX_FLUSH_BUDGET_BYTES) break; // ≥1 frame, then bounded
367
+ const e = st.queue[0];
368
+ try { st.ws.send(e.text); } catch (err) {
305
369
  reportSwallowed('ws.mux.send', err);
306
370
  closeSocket(st, 1011, 'send-failed');
307
371
  return;
308
372
  }
309
373
  st.queue.shift();
310
- st.queuedBytes -= text.length;
374
+ st.queuedBytes -= e.bytes;
375
+ sentBytes += e.bytes;
311
376
  }
312
- };
313
- const fireAllDrain = () => {
314
- for (const rec of st.streams.values()) rec.sink.emit('drain');
315
- };
316
- st.gate = createBackpressureGate({
317
- getBufferedAmount: () => st.ws.bufferedAmount || 0,
318
- onResume: () => { st._behind = false; flushQueue(); fireAllDrain(); },
319
- onBehind: () => { st._behind = true; },
320
- onTimeout: () => {
321
- reportSwallowed('ws.mux.backpressure', new Error('timeout'));
377
+ if (st.closed) return;
378
+ const b = st.ws.bufferedAmount || 0;
379
+ if (st.queue.length === 0 && b <= LOW_WATER) {
380
+ // Fully drained: clear behind (if set), wake waiters, and DISARM — nothing left
381
+ // to watch. This is the only state where the pump stands down. Drain fires
382
+ // unconditionally here: maximal headroom, and a waiter that entered mid-band must
383
+ // not be stranded (the heartbeat timer shares lastBuffered — see ping — so a
384
+ // conditional drain could be lost). A drain with no listeners is a no-op.
385
+ st._behind = false;
386
+ disarmPump();
387
+ fireAllDrain();
388
+ st.lastBuffered = 0;
389
+ return;
390
+ }
391
+ // Queue empty but the socket still holds > LOW_WATER: producers may resume (clear the
392
+ // flag so a new write direct-sends), yet the pump stays armed to watch the wedge.
393
+ if (st._behind && st.queue.length === 0) exitBehind();
394
+ // Progress == the pump actually DEQUEUED bytes this tick (a frame left the app queue
395
+ // into the socket). This — NOT a bufferedAmount level drop — is the sound signal: when
396
+ // the queue stays non-empty the flush refills the socket buffer to ~HIGH every tick, so
397
+ // a level sample taken AFTER our own sends is pinned and never "declines" even for a
398
+ // client draining megabytes per second (it would be false-killed). A wedged client, by
399
+ // contrast, lets the socket buffer sit > HIGH so the flush breaks with sentBytes===0.
400
+ // (Also credit the residual band: queue empty, buffer draining from > LOW to <= LOW.)
401
+ if (sentBytes > 0 || (st.queue.length === 0 && b < st.lastBuffered)) {
402
+ st.lastProgressAt = now();
403
+ st.lastByteProgressAt = now(); // the ONLY clock that marks real byte movement
404
+ // Emit 'drain' once there is real headroom (<= HIGH_WATER), so a woken producer
405
+ // refills into a draining socket instead of reflooding a congested one.
406
+ if (b <= HIGH_WATER) fireAllDrain();
407
+ }
408
+ st.lastBuffered = b;
409
+ // Kill on measured no-progress. Two clocks: the stall-guard clock (lastProgressAt) is
410
+ // reset by event-loop stalls so a slow-but-paused consumer isn't false-killed; the
411
+ // absolute clock (lastByteProgressAt) is NEVER reset by a stall, so a pathological run
412
+ // of stalls (or a frozen client whose buffer never drains) is still killed — by the
413
+ // absolute ceiling 2×STALL_MS even if the guard keeps deferring the primary window.
414
+ const stalledPrimary = now() - st.lastProgressAt >= WS_MUX_STALL_MS;
415
+ const stalledAbsolute = now() - st.lastByteProgressAt >= 2 * WS_MUX_STALL_MS;
416
+ if (stalledPrimary || stalledAbsolute) {
417
+ reportSwallowed('ws.mux.backpressure', new Error('stalled'), { queuedBytes: st.queuedBytes, buffered: b, absolute: stalledAbsolute && !stalledPrimary });
322
418
  closeSocket(st, 1011, 'backpressure-timeout');
323
- },
324
- highWater: HIGH_WATER,
325
- lowWater: LOW_WATER,
326
- timeoutMs: 30000,
327
- });
419
+ }
420
+ }
421
+
328
422
  st.behind = () => st._behind || st.queuedBytes > 0;
329
423
 
330
424
  // Send-or-enqueue. NEVER drops: while behind, frames accumulate in the bounded queue
331
- // (order preserved). A wedged client dies by the 30s gate timeout / queue cap, then the
332
- // client reconnects and resumes via its since/cc cursor. The gate's offer() return is
333
- // ONLY a signal (its native contract is "skip this send" — the terminal path compensates
334
- // with data-resync; mux must NOT skip, so we ignore the return for the send decision).
425
+ // (order preserved). A genuinely wedged client is killed by the stall watchdog (its
426
+ // bufferedAmount stops dropping) or the queue cap, then the client reconnects and
427
+ // resumes via its since/cc cursor. Every enqueue goes through ONE path that both
428
+ // cap-checks and enterBehind()s — an enqueued frame always has the pump armed.
335
429
  st.send = (msg) => {
336
430
  if (st.closed || st.ws.readyState !== 1) return false;
337
431
  const text = encodeFrame(msg);
338
- st.gate.offer(); // signal only; result deliberately unused
339
- if (st._behind) {
340
- if (st.queuedBytes + text.length > QUEUE_MAX_BYTES) {
432
+ const enqueue = () => {
433
+ const bytes = Buffer.byteLength(text, 'utf8'); // real UTF-8 bytes ws.send will write
434
+ if (st.queuedBytes + bytes > QUEUE_MAX_BYTES) {
341
435
  closeSocket(st, 1011, 'queue-overflow');
342
436
  return false;
343
437
  }
344
- st.queue.push(text);
345
- st.queuedBytes += text.length;
438
+ st.queue.push({ text, bytes });
439
+ st.queuedBytes += bytes;
440
+ enterBehind(st.ws.bufferedAmount || 0);
346
441
  return false;
347
- }
442
+ };
443
+ if (st._behind || st.queue.length > 0) return enqueue(); // never direct-send while queued
444
+ if ((st.ws.bufferedAmount || 0) > HIGH_WATER) return enqueue();
348
445
  try { st.ws.send(text); } catch (err) {
349
446
  reportSwallowed('ws.mux.send', err);
350
447
  closeSocket(st, 1011, 'send-failed');
@@ -353,6 +450,21 @@ export function createStreamMuxServer({
353
450
  return true;
354
451
  };
355
452
 
453
+ // Control-plane bypass: ping/pong/open-ack carry no per-stream seq (the client's
454
+ // dedup cursor only applies to 'frame'), so they may overtake queued bulk data to
455
+ // keep liveness alive during a congested cold load. They do NOT count as queue
456
+ // progress (the stall watchdog only watches bufferedAmount), so they can never mask
457
+ // a wedged data queue. Data 'frame'/'close'/'error' still go through st.send (FIFO).
458
+ st.sendControl = (msg) => {
459
+ if (st.closed || st.ws.readyState !== 1) return false;
460
+ try { st.ws.send(encodeFrame(msg)); } catch (err) {
461
+ reportSwallowed('ws.mux.send', err);
462
+ closeSocket(st, 1011, 'send-failed');
463
+ return false;
464
+ }
465
+ return true;
466
+ };
467
+
356
468
  st.closeStream = (streamId, reason) => {
357
469
  const rec = st.streams.get(streamId);
358
470
  if (!rec || rec.disposed) return;
@@ -373,13 +485,24 @@ export function createStreamMuxServer({
373
485
  }
374
486
  };
375
487
 
488
+ // Ping-timer liveness sample: kept SEPARATE from the pump's lastBuffered baseline so a
489
+ // 25s heartbeat can never clobber the pump's final-drain 'drain' emission (lost wakeup).
490
+ let lastPingBuffered = 0;
376
491
  st.pingTimer = setI(() => {
377
492
  if (st.closed) return;
378
- if (now() - st.lastInboundAt > HEARTBEAT_REAP_MS) {
493
+ // Reap only on TRUE silence: inbound silence AND no outbound byte-progress. A slow
494
+ // client (a ping that bypasses the data queue still sits behind up to HIGH_WATER of
495
+ // socket buffer, so its pong can be >60s out on a very slow link) is kept alive as
496
+ // long as the socket keeps draining; only a socket that is neither heard from nor
497
+ // draining is reaped.
498
+ const b = st.ws.bufferedAmount || 0;
499
+ if (b < lastPingBuffered) st.lastProgressAt = now();
500
+ lastPingBuffered = b;
501
+ if (now() - st.lastInboundAt > HEARTBEAT_REAP_MS && now() - st.lastProgressAt > HEARTBEAT_REAP_MS) {
379
502
  closeSocket(st, 1001, 'heartbeat-reap');
380
503
  return;
381
504
  }
382
- st.send({ type: 'ping', ts: now() });
505
+ st.sendControl({ type: 'ping', ts: now() });
383
506
  }, HEARTBEAT_SEND_MS);
384
507
  st.pingTimer.unref?.();
385
508
 
@@ -395,7 +518,7 @@ export function createStreamMuxServer({
395
518
  return;
396
519
  }
397
520
  if (msg.type === 'pong') return;
398
- if (msg.type === 'ping') { st.send({ type: 'pong', ts: now() }); return; }
521
+ if (msg.type === 'ping') { st.sendControl({ type: 'pong', ts: now() }); return; }
399
522
  if (msg.type === 'close') {
400
523
  st.closeStream(msg.streamId, 'client-close'); // unknown id: ignore (graphql-ws)
401
524
  return;
@@ -421,8 +544,10 @@ export function createStreamMuxServer({
421
544
  const rec = { sink, handle: null, disposed: false };
422
545
  st.streams.set(v.streamId, rec);
423
546
  sink.on('close', () => st.closeStream(v.streamId, 'sink-close'));
424
- // ack precedes every frame of this stream (history frames included).
425
- st.send({ type: 'open-ack', streamId: v.streamId, epoch, seq: 0 });
547
+ // ack precedes every frame of this stream (history frames included). Sent via
548
+ // sendControl so it bypasses any queued bulk data — a cold-load backlog must not
549
+ // push the ack past the client's 2.5s/4s ack deadline and force an SSE fallback.
550
+ st.sendControl({ type: 'open-ack', streamId: v.streamId, epoch, seq: 0 });
426
551
  let handleP;
427
552
  try {
428
553
  handleP = serveStream(sink, v.qs);
@@ -463,9 +588,13 @@ export function createStreamMuxServer({
463
588
  if (st.closed) return;
464
589
  st.closed = true;
465
590
  for (const streamId of [...st.streams.keys()]) st.closeStream(streamId, _reason);
466
- try { st.gate.dispose(); } catch { /* best-effort */ }
467
591
  if (st.pingTimer) { clearI(st.pingTimer); st.pingTimer = null; }
468
- if (st.flushTimer) { clearT(st.flushTimer); st.flushTimer = null; }
592
+ if (st.pumpTimer) { clearI(st.pumpTimer); st.pumpTimer = null; }
593
+ // Reset the backpressure state so a dead sink's needsDrain() goes false and a
594
+ // writeBp loop aborts on alive() instead of waiting out the 30s awaitDrain timeout.
595
+ st._behind = false;
596
+ st.queue.length = 0;
597
+ st.queuedBytes = 0;
469
598
  sockets.delete(st);
470
599
  }
471
600
 
@@ -261,6 +261,19 @@ export async function serveEventStream(sink, params, deps) {
261
261
  // previous tail-registration leaked the timer and pushed a dead res in that window.
262
262
  sink.onClose?.(dispose);
263
263
 
264
+ // Credit-based bulk write: a cold-load / replay producer must NOT dump a whole
265
+ // multi-MB burst in one tick (the mux queue cap would 1011 the socket). Write one
266
+ // frame, then — if the sink signaled pressure (write returned false, or the socket
267
+ // is behind) — await drain before the next. Aborts on a dead sink. Mirrors the
268
+ // legacy per-entry loop's contract below; resolves to awaitWireDrain on SSE.
269
+ const writeBp = async (text) => {
270
+ if (!sink.alive()) return false;
271
+ let ok;
272
+ try { ok = sink.write(text); } catch (err) { reportSwallowed('events.cold-write', err); return false; }
273
+ if (!ok || sink.needsDrain()) await sink.awaitDrain();
274
+ return sink.alive();
275
+ };
276
+
264
277
  const { sidParam, projectParam, instanceParam, sinceParam, ccParam, limitRaw, limitGiven, shardBeforeParam } = {
265
278
  sidParam: params.sid,
266
279
  projectParam: params.project,
@@ -533,11 +546,8 @@ export async function serveEventStream(sink, params, deps) {
533
546
  for (const raw of shardRes.entries) {
534
547
  if (!sink.alive()) break;
535
548
  const out = enrichRawIfNeeded(raw);
536
- try {
537
- sink.write('event: load_chunk\ndata: [');
538
- sink.write(out.includes('\n') ? out.replace(/\n/g, '') : out);
539
- sink.write(']\n\n');
540
- } catch { break; }
549
+ const body = out.includes('\n') ? out.replace(/\n/g, '') : out;
550
+ if (!(await writeBp(`event: load_chunk\ndata: [${body}]\n\n`))) break;
541
551
  }
542
552
  } catch (err) {
543
553
  reportSwallowed('events.shard-load', err, { sid: sidParam, shardBefore: shardBeforeParam });
@@ -660,16 +670,20 @@ export async function serveEventStream(sink, params, deps) {
660
670
  loadStartData.oldestTs = meta.oldestTimestamp || '';
661
671
  }
662
672
  if (_coldShardCursor) loadStartData.shard = _coldShardCursor;
663
- sink.write(`event: load_start\ndata: ${JSON.stringify(loadStartData)}\n\n`);
664
- sink.write(`event: v2_requests\ndata: ${rowsPayload}\n\n`);
665
- for (const payload of native.convPayloads) sink.write(`event: v3_conv\ndata: ${payload}\n\n`);
666
- for (const payload of native.respPayloads) sink.write(`event: v3_resp\ndata: ${payload}\n\n`);
673
+ if (!(await writeBp(`event: load_start\ndata: ${JSON.stringify(loadStartData)}\n\n`))) { /* sink gone mid-load */ }
674
+ else if (!(await writeBp(`event: v2_requests\ndata: ${rowsPayload}\n\n`))) { /* sink gone mid-load */ }
675
+ else {
676
+ let aborted = false;
677
+ for (const payload of native.convPayloads) { if (!(await writeBp(`event: v3_conv\ndata: ${payload}\n\n`))) { aborted = true; break; } }
678
+ for (const payload of (!aborted ? native.respPayloads : [])) { if (!(await writeBp(`event: v3_resp\ndata: ${payload}\n\n`))) break; }
679
+ }
667
680
  // kv-cache / context_window sources: rebuild the newest completed
668
681
  // mainAgent rows. Depth 3 mirrors the legacy scan-ring fallback (review
669
682
  // P2-e): the newest main may lack usage/cached-content or be a
670
683
  // synthesis-gated orphan — earlier candidates then provide the values.
671
684
  const mains = meta.rows.filter((r) => r.mainAgent && !r.inProgress).slice(-3);
672
685
  for (const m of mains) {
686
+ if (!sink.alive()) break;
673
687
  const detail = await readV2SingleEntry(src, { seq: m.seq, sessionId: m.sessionId });
674
688
  if (detail && detail.entry) mainAgentRawRing.push(detail.entry);
675
689
  }
@@ -760,16 +774,29 @@ export async function serveEventStream(sink, params, deps) {
760
774
  //
761
775
  // Attach buffer flush + swap: replay every live delta queued during the cold
762
776
  // load (in emission order, conv-covered frames skipped), then swap the proxy
763
- // for the real registrable. This whole block is synchronous — no broadcast can
764
- // interleave between the replay and the swap, so nothing is double-sent or
765
- // lost. After this point the connection receives live frames directly.
777
+ // for the real registrable. The replay is awaited (credit-based: it paces into
778
+ // a congested socket instead of dumping a multi-MB burst), and the proxy stays
779
+ // registered throughout so frames landing mid-replay are appended + replayed in
780
+ // order. The proxy→registrable swap happens synchronously inside onDrained (no
781
+ // yield after the final replay write) — no broadcast can interleave between the
782
+ // last replay and the swap, so nothing is double-sent or lost. `closed` is
783
+ // RE-CHECKED after the await: a client that disconnects mid-flush must NOT have
784
+ // its (now-destroyed) registrable pushed into the broadcast list.
766
785
  if (!closed) {
767
- flushAttachBuffer(sink, attachBufferClient, coldConvCoverage);
768
- if (attachBufferClient) {
769
- const bi = deps.clients.indexOf(attachBufferClient);
770
- if (bi !== -1) deps.clients.splice(bi, 1);
771
- }
772
- deps.clients.push(registrable);
786
+ const removeProxy = () => {
787
+ if (attachBufferClient) {
788
+ const bi = deps.clients.indexOf(attachBufferClient);
789
+ if (bi !== -1) deps.clients.splice(bi, 1);
790
+ attachBufferClient._clear();
791
+ }
792
+ };
793
+ await flushAttachBuffer(sink, attachBufferClient, coldConvCoverage,
794
+ () => { // onDrained: swap proxy → registrable atomically
795
+ if (closed) { removeProxy(); return; } // client died mid-flush: drop, do not register
796
+ removeProxy();
797
+ deps.clients.push(registrable);
798
+ },
799
+ removeProxy); // onAbort (dead sink / write error): never leak the proxy
773
800
  }
774
801
  attachBufferClient = null;
775
802