@myrialabs/clopen 0.4.48 → 0.4.50

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.
Files changed (114) hide show
  1. package/backend/chat/background-wait.test.ts +28 -0
  2. package/backend/chat/message-pages.test.ts +180 -0
  3. package/backend/chat/message-pages.ts +237 -0
  4. package/backend/chat/stream-manager.ts +101 -18
  5. package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
  6. package/backend/database/migrations/088_create_messages_fts_map.ts +52 -0
  7. package/backend/database/migrations/089_add_memory_layout_tiles.ts +58 -0
  8. package/backend/database/migrations/index.ts +21 -0
  9. package/backend/database/queries/blob-line-stats-queries.ts +48 -0
  10. package/backend/database/queries/graph-queries.ts +392 -135
  11. package/backend/database/queries/index.ts +2 -0
  12. package/backend/database/queries/message-fts.test.ts +120 -0
  13. package/backend/database/queries/message-queries.ts +45 -9
  14. package/backend/database/queries/session-queries.ts +3 -2
  15. package/backend/database/queries/utils-queries.ts +3 -0
  16. package/backend/db-client/env/diff.ts +9 -33
  17. package/backend/db-client/env/env.test.ts +8 -8
  18. package/backend/db-client/env/service.ts +1 -1
  19. package/backend/engine/adapters/claude/environment.ts +4 -0
  20. package/backend/engine/adapters/claude/input-gate.test.ts +59 -0
  21. package/backend/engine/adapters/claude/input-gate.ts +74 -0
  22. package/backend/engine/adapters/claude/message-converter.test.ts +16 -0
  23. package/backend/engine/adapters/claude/message-converter.ts +8 -0
  24. package/backend/engine/adapters/claude/stream.ts +15 -0
  25. package/backend/files/file-watcher.ts +19 -0
  26. package/backend/git/contributors.test.ts +35 -0
  27. package/backend/git/contributors.ts +46 -0
  28. package/backend/git/identity/scope-config.test.ts +7 -4
  29. package/backend/http/static-assets.test.ts +78 -0
  30. package/backend/http/static-assets.ts +104 -0
  31. package/backend/index.ts +46 -17
  32. package/backend/memory/README.md +7 -4
  33. package/backend/memory/layout.test.ts +377 -0
  34. package/backend/memory/layout.ts +1029 -265
  35. package/backend/memory/view.ts +257 -386
  36. package/backend/preview/browser/browser-preview-service.ts +24 -6
  37. package/backend/project/status-manager.ts +4 -2
  38. package/backend/snapshot/blob-store.ts +9 -1
  39. package/backend/snapshot/helpers.ts +3 -10
  40. package/backend/snapshot/line-stats.test.ts +80 -0
  41. package/backend/snapshot/line-stats.ts +64 -0
  42. package/backend/snapshot/snapshot-service.ts +14 -27
  43. package/backend/snapshot/turn-changes.test.ts +10 -5
  44. package/backend/snapshot/turn-changes.ts +78 -40
  45. package/backend/terminal/ptykit.ts +6 -1
  46. package/backend/utils/ws-wire.test.ts +87 -0
  47. package/backend/utils/ws-wire.ts +189 -0
  48. package/backend/utils/ws.ts +40 -38
  49. package/backend/ws/chat/stream.ts +60 -20
  50. package/backend/ws/files/read.ts +30 -0
  51. package/backend/ws/git/log.ts +52 -0
  52. package/backend/ws/memory/crud.ts +118 -81
  53. package/backend/ws/messages/crud.ts +51 -0
  54. package/backend/ws/preview/index.ts +2 -0
  55. package/backend/ws/preview/watchers.ts +84 -0
  56. package/backend/ws/sessions/crud.ts +8 -12
  57. package/backend/ws/snapshot/changes.ts +5 -6
  58. package/backend/ws/terminal/tunnel.ts +2 -2
  59. package/bin/clopen.ts +37 -30
  60. package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
  61. package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
  62. package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
  63. package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
  64. package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
  65. package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
  66. package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
  67. package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
  68. package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
  69. package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
  70. package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
  71. package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
  72. package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
  73. package/dist/assets/{index-DJzwt-hq.js → index-By6KdSLT.js} +1 -1
  74. package/dist/assets/index-By6KdSLT.js.br +0 -0
  75. package/dist/assets/index-By6KdSLT.js.gz +0 -0
  76. package/dist/assets/{index-CONlwAXZ.js → index-DV4TiDn1.js} +1 -1
  77. package/dist/assets/index-DV4TiDn1.js.br +0 -0
  78. package/dist/assets/index-DV4TiDn1.js.gz +0 -0
  79. package/dist/assets/main-DIESTGTD.css +1 -0
  80. package/dist/assets/main-DIESTGTD.css.br +0 -0
  81. package/dist/assets/main-DIESTGTD.css.gz +0 -0
  82. package/dist/assets/{main-nBOb9YOA.js → main-Da3JKoua.js} +623 -623
  83. package/dist/assets/main-Da3JKoua.js.br +0 -0
  84. package/dist/assets/main-Da3JKoua.js.gz +0 -0
  85. package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
  86. package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
  87. package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
  88. package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
  89. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
  90. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
  91. package/dist/fonts/dm-sans.css.br +0 -0
  92. package/dist/fonts/dm-sans.css.gz +0 -0
  93. package/dist/index.html +2 -2
  94. package/dist/index.html.br +0 -0
  95. package/dist/index.html.gz +0 -0
  96. package/dist/sw.js.br +0 -0
  97. package/dist/sw.js.gz +0 -0
  98. package/package.json +3 -4
  99. package/shared/types/memory.ts +96 -73
  100. package/shared/types/unified/index.ts +1 -0
  101. package/shared/types/unified/stream.ts +33 -2
  102. package/shared/utils/diff-calculator.test.ts +178 -41
  103. package/shared/utils/diff-calculator.ts +383 -100
  104. package/shared/utils/process-supervisor.test.ts +242 -0
  105. package/shared/utils/process-supervisor.ts +356 -0
  106. package/shared/utils/process-tree.ts +99 -0
  107. package/shared/utils/ws-chunk.test.ts +33 -0
  108. package/shared/utils/ws-chunk.ts +73 -0
  109. package/shared/utils/ws-client-chunks.test.ts +45 -0
  110. package/shared/utils/ws-client.ts +43 -0
  111. package/shared/utils/ws-server.ts +17 -14
  112. package/backend/database/migrations/086_single_owner.test.ts +0 -170
  113. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +0 -1
  114. package/dist/assets/main-BUiUL3eZ.css +0 -1
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The send path every frame takes: what gets compressed, and how a large
3
+ * reply leaves in chunks without filling the socket's buffer.
4
+ */
5
+
6
+ import { describe, expect, test } from 'bun:test';
7
+
8
+ import { decodeChunk } from '$shared/utils/ws-chunk';
9
+ import { CHUNK_BYTES, COMPRESS_MIN_BYTES, sendBinary, sendReply, sendText } from './ws-wire';
10
+
11
+ class FakeSocket {
12
+ readyState = 1;
13
+ buffered = 0;
14
+ sent: Array<{ data: string | Buffer; compress?: boolean }> = [];
15
+ raw = { getBufferedAmount: () => this.buffered };
16
+ send(data: string | Buffer, compress?: boolean) {
17
+ this.sent.push({ data, compress });
18
+ }
19
+ }
20
+
21
+ describe('sendText / sendBinary', () => {
22
+ test('compresses text only when it is large enough to gain from it', () => {
23
+ const socket = new FakeSocket();
24
+ sendText(socket, 'small', 'x'.repeat(COMPRESS_MIN_BYTES - 1));
25
+ sendText(socket, 'large', 'x'.repeat(COMPRESS_MIN_BYTES));
26
+ expect(socket.sent.map((frame) => frame.compress)).toEqual([false, true]);
27
+ });
28
+
29
+ test('never compresses binary', () => {
30
+ const socket = new FakeSocket();
31
+ sendBinary(socket, 'file:download', new Uint8Array(100_000));
32
+ expect(socket.sent[0].compress).toBe(false);
33
+ expect(Buffer.isBuffer(socket.sent[0].data)).toBe(true);
34
+ });
35
+ });
36
+
37
+ describe('sendReply', () => {
38
+ test('sends a reply under the threshold as one ordinary frame', async () => {
39
+ const socket = new FakeSocket();
40
+ const text = JSON.stringify({ action: 'x:response', payload: { ok: true } });
41
+ await sendReply(socket, 'x:response', 'req-1', text);
42
+ expect(socket.sent).toEqual([{ data: text, compress: false }]);
43
+ });
44
+
45
+ test('chunks a large reply into pieces that reassemble to the exact text', async () => {
46
+ const socket = new FakeSocket();
47
+ const text = JSON.stringify({ action: 'messages:list:response', payload: { data: 'é😀'.repeat(CHUNK_BYTES) } });
48
+ await sendReply(socket, 'messages:list:response', 'req-2', text);
49
+
50
+ const chunks = socket.sent.map((frame) => decodeChunk(frame.data as string)!);
51
+ expect(chunks.length).toBeGreaterThan(1);
52
+ expect(new Set(chunks.map((chunk) => chunk.streamId)).size).toBe(1);
53
+ expect(chunks.every((chunk) => chunk.requestId === 'req-2' && chunk.count === chunks.length)).toBe(true);
54
+ expect(chunks.map((chunk) => chunk.slice).join('')).toBe(text);
55
+ });
56
+
57
+ test('two replies get distinct streams', async () => {
58
+ const socket = new FakeSocket();
59
+ const text = 'x'.repeat(CHUNK_BYTES * 2);
60
+ await sendReply(socket, 'a', 'req', text);
61
+ await sendReply(socket, 'a', 'req', text);
62
+ const streams = new Set(socket.sent.map((frame) => decodeChunk(frame.data as string)!.streamId));
63
+ expect(streams.size).toBe(2);
64
+ });
65
+
66
+ test('waits for the socket to drain between chunks', async () => {
67
+ const socket = new FakeSocket();
68
+ socket.buffered = 10 * 1024 * 1024;
69
+ const sending = sendReply(socket, 'a', 'req', 'x'.repeat(CHUNK_BYTES * 3));
70
+ await new Promise((resolve) => setTimeout(resolve, 40));
71
+ expect(socket.sent).toHaveLength(1); // first chunk only, then held
72
+
73
+ socket.buffered = 0;
74
+ await sending;
75
+ expect(socket.sent).toHaveLength(3);
76
+ });
77
+
78
+ test('stops when the socket closes mid-reply', async () => {
79
+ const socket = new FakeSocket();
80
+ socket.buffered = 10 * 1024 * 1024;
81
+ const sending = sendReply(socket, 'a', 'req', 'x'.repeat(CHUNK_BYTES * 3));
82
+ await new Promise((resolve) => setTimeout(resolve, 20));
83
+ socket.readyState = 3;
84
+ await sending;
85
+ expect(socket.sent).toHaveLength(1);
86
+ });
87
+ });
@@ -0,0 +1,189 @@
1
+ /**
2
+ * The last step before a frame leaves the server — the one place that decides
3
+ * how it travels.
4
+ *
5
+ * Every event (`backend/utils/ws.ts`) and every request-response reply
6
+ * (`shared/utils/ws-server.ts`) is sent through here, so three concerns live
7
+ * once instead of at every call site:
8
+ *
9
+ * 1. Compression. The socket negotiates permessage-deflate (see
10
+ * `WS_PER_MESSAGE_DEFLATE`), but Bun only compresses a frame when asked to.
11
+ * JSON shrinks 4–12× under deflate; a frame under ~1 KB grows instead, and
12
+ * binary frames (uploads, downloads, media) are already dense — so only text
13
+ * of at least `COMPRESS_MIN_BYTES` is compressed.
14
+ *
15
+ * 2. Large replies are chunked. A request-response reply above `CHUNK_BYTES`
16
+ * used to leave as one frame. The browser only reports a frame once all of it
17
+ * has arrived, so on a slow link a multi-megabyte reply looked like silence:
18
+ * the client's 30 s request timer fired mid-download and re-sent the read —
19
+ * queueing a second copy — or tore the socket down and started over. Chunks
20
+ * are proof of progress (each one re-arms the request's timer), they let
21
+ * events slip in between instead of waiting behind the whole reply, and
22
+ * sending waits for the socket to drain so a slow client never makes the
23
+ * server buffer an entire reply in memory. Events are never chunked: they
24
+ * must arrive in the order they were emitted.
25
+ *
26
+ * 3. A traffic meter (development, or `CLOPEN_WS_TRAFFIC=1`) that adds up bytes
27
+ * per action, so a bandwidth claim can be checked against real traffic
28
+ * instead of an estimate.
29
+ */
30
+
31
+ import type { WebSocketCompressor } from 'bun';
32
+ import { debug } from '$shared/utils/logger';
33
+ import { SERVER_ENV } from './env';
34
+ import { encodeChunk, sliceText } from '$shared/utils/ws-chunk';
35
+
36
+ /** Text frames shorter than this are sent uncompressed — deflate would grow them. */
37
+ export const COMPRESS_MIN_BYTES = 1024;
38
+
39
+ /** Request-response replies longer than this (in characters) are chunked. */
40
+ export const CHUNK_BYTES = 256 * 1024;
41
+
42
+ /** Stop sending chunks while the socket has more than this queued. */
43
+ const DRAIN_HIGH_WATER = 1024 * 1024;
44
+
45
+ /** How often to re-check a full socket. */
46
+ const DRAIN_POLL_MS = 10;
47
+
48
+ /**
49
+ * Compression the server offers. A per-socket compressor keeps context across
50
+ * messages, which is what makes the stream of small, similar JSON events
51
+ * (stream deltas, file changes, terminal output) compress well; 32 KB per
52
+ * connection is the price. Client → server frames are small and use the shared
53
+ * decompressor.
54
+ */
55
+ export const WS_PER_MESSAGE_DEFLATE: { compress: WebSocketCompressor; decompress: WebSocketCompressor } = {
56
+ compress: '32KB',
57
+ decompress: 'shared'
58
+ };
59
+
60
+ /**
61
+ * Server-wide socket options, handed to `new Elysia({ websocket })`.
62
+ *
63
+ * They must be set there. Elysia drops the same keys on a `.ws()` route, which
64
+ * is where they used to live — so for as long as that was the case Bun's
65
+ * defaults applied instead: a 16 MB frame limit that closed the socket on any
66
+ * larger upload (1006), and a 120 s idle timeout.
67
+ */
68
+ export const WS_SERVER_OPTIONS = {
69
+ // Allow large binary frames (file uploads, zip extracts); the per-file
70
+ // limits are enforced by the handlers, not by the transport.
71
+ maxPayloadLength: 1024 * 1024 * 1024, // 1 GiB
72
+ // Don't drop a connection that is busy with one long binary transfer.
73
+ idleTimeout: 960, // seconds (max allowed by uWS)
74
+ perMessageDeflate: WS_PER_MESSAGE_DEFLATE
75
+ };
76
+
77
+ /** Numbers each chunked reply, so two replies to one re-sent request stay apart. */
78
+ let replyStreams = 0;
79
+
80
+ /** The part of a socket this module needs: Elysia's wrapper or Bun's own. */
81
+ interface WireSocket {
82
+ readyState: number;
83
+ send(data: string | Buffer, compress?: boolean): unknown;
84
+ raw?: { getBufferedAmount?: () => number };
85
+ getBufferedAmount?: () => number;
86
+ }
87
+
88
+ /** Send one text frame, compressed when it is big enough to gain from it. */
89
+ export function sendText(conn: WireSocket, action: string, text: string): void {
90
+ conn.send(text, text.length >= COMPRESS_MIN_BYTES);
91
+ recordTraffic(action, text.length);
92
+ }
93
+
94
+ /** Send one binary frame. Never compressed: it is already dense. */
95
+ export function sendBinary(conn: WireSocket, action: string, data: ArrayBuffer | Uint8Array | Buffer): void {
96
+ const buffer = Buffer.isBuffer(data)
97
+ ? data
98
+ : data instanceof ArrayBuffer
99
+ ? Buffer.from(data)
100
+ : Buffer.from(data.buffer, data.byteOffset, data.byteLength);
101
+ conn.send(buffer, false);
102
+ recordTraffic(action, buffer.byteLength);
103
+ }
104
+
105
+ /**
106
+ * Send a serialized request-response reply, chunked when it is large.
107
+ * Resolves once the last chunk is handed to the socket (or the socket closed).
108
+ */
109
+ export async function sendReply(conn: WireSocket, action: string, requestId: string, text: string): Promise<void> {
110
+ if (text.length <= CHUNK_BYTES || !requestId) {
111
+ sendText(conn, action, text);
112
+ return;
113
+ }
114
+
115
+ const slices = sliceText(text, CHUNK_BYTES);
116
+ const streamId = String(++replyStreams);
117
+ for (let index = 0; index < slices.length; index++) {
118
+ if (index > 0) {
119
+ await waitForDrain(conn);
120
+ if (conn.readyState !== 1) return; // The client is gone; it will re-request.
121
+ }
122
+ const frame = encodeChunk(streamId, requestId, index, slices.length, slices[index]);
123
+ conn.send(frame, true);
124
+ recordTraffic(action, frame.length);
125
+ }
126
+ }
127
+
128
+ function bufferedAmount(conn: WireSocket): number {
129
+ try {
130
+ if (typeof conn.raw?.getBufferedAmount === 'function') return conn.raw.getBufferedAmount();
131
+ if (typeof conn.getBufferedAmount === 'function') return conn.getBufferedAmount();
132
+ } catch {
133
+ // A closed socket throws; the caller checks readyState next.
134
+ }
135
+ return 0;
136
+ }
137
+
138
+ async function waitForDrain(conn: WireSocket): Promise<void> {
139
+ while (conn.readyState === 1 && bufferedAmount(conn) > DRAIN_HIGH_WATER) {
140
+ await new Promise((resolve) => setTimeout(resolve, DRAIN_POLL_MS));
141
+ }
142
+ }
143
+
144
+ // ============================================================================
145
+ // Traffic meter
146
+ // ============================================================================
147
+
148
+ const TRAFFIC_ENABLED = SERVER_ENV.isDevelopment || process.env.CLOPEN_WS_TRAFFIC === '1';
149
+ const TRAFFIC_REPORT_MS = 30_000;
150
+
151
+ const traffic = new Map<string, { frames: number; bytes: number }>();
152
+ let reportTimer: ReturnType<typeof setInterval> | null = null;
153
+
154
+ function recordTraffic(action: string, bytes: number): void {
155
+ if (!TRAFFIC_ENABLED) return;
156
+ const entry = traffic.get(action);
157
+ if (entry) {
158
+ entry.frames++;
159
+ entry.bytes += bytes;
160
+ } else {
161
+ traffic.set(action, { frames: 1, bytes });
162
+ }
163
+ if (!reportTimer) {
164
+ reportTimer = setInterval(reportTraffic, TRAFFIC_REPORT_MS);
165
+ reportTimer.unref?.();
166
+ }
167
+ }
168
+
169
+ /** Bytes sent per action since the last report (before compression), largest first. */
170
+ export function takeTrafficReport(): Array<{ action: string; frames: number; bytes: number }> {
171
+ const rows = [...traffic.entries()]
172
+ .map(([action, entry]) => ({ action, ...entry }))
173
+ .sort((a, b) => b.bytes - a.bytes);
174
+ traffic.clear();
175
+ return rows;
176
+ }
177
+
178
+ function reportTraffic(): void {
179
+ const rows = takeTrafficReport();
180
+ if (rows.length === 0) return;
181
+ const total = rows.reduce((sum, row) => sum + row.bytes, 0);
182
+ const lines = rows
183
+ .slice(0, 15)
184
+ .map((row) => ` ${(row.bytes / 1024).toFixed(1).padStart(10)} KB ${String(row.frames).padStart(6)}× ${row.action}`);
185
+ debug.log(
186
+ 'websocket',
187
+ `WS traffic, last ${TRAFFIC_REPORT_MS / 1000}s: ${(total / 1024).toFixed(1)} KB before compression\n${lines.join('\n')}`
188
+ );
189
+ }
@@ -34,18 +34,13 @@ import type { WSConnection } from '$shared/utils/ws-server';
34
34
  import { encodeBinaryMessage, isBinaryAction } from '$shared/utils/ws-server';
35
35
  import { debug } from '$shared/utils/logger';
36
36
  import { clientIpFromConnection } from './client-ip';
37
+ import { sendBinary, sendText } from './ws-wire';
37
38
 
38
- /**
39
- * Performance configuration
40
- */
41
- const CONFIG = {
42
- /** Maximum send buffer before dropping frames (bytes) */
43
- MAX_BUFFER_SIZE: 1024 * 1024, // 1MB
44
- /** Enable backpressure handling */
45
- ENABLE_BACKPRESSURE: true,
46
- /** Log dropped frames */
47
- LOG_DROPPED_FRAMES: true
48
- };
39
+ /** The action of a serialized `{"action":"…",…}` event, for the traffic meter. */
40
+ function actionOf(message: string): string {
41
+ const match = /^\{"action":"([^"]+)"/.exec(message);
42
+ return match ? match[1] : 'unknown';
43
+ }
49
44
 
50
45
  /**
51
46
  * Metrics for monitoring
@@ -54,7 +49,6 @@ interface WSMetrics {
54
49
  totalConnections: number;
55
50
  activeProjects: number;
56
51
  activeUsers: number;
57
- droppedFrames: number;
58
52
  totalEmits: number;
59
53
  }
60
54
 
@@ -117,7 +111,6 @@ class WSServer {
117
111
  totalConnections: 0,
118
112
  activeProjects: 0,
119
113
  activeUsers: 0,
120
- droppedFrames: 0,
121
114
  totalEmits: 0
122
115
  };
123
116
 
@@ -731,33 +724,22 @@ class WSServer {
731
724
  }
732
725
 
733
726
  /**
734
- * Check if connection can receive data (backpressure check)
727
+ * Whether a connection can be written to at all.
728
+ *
729
+ * Deliberately not a backpressure gate. An earlier one dropped events while
730
+ * the socket's buffer held more than 1 MB — but it read `getBufferedAmount`
731
+ * off Elysia's wrapper, which does not have it, so it never fired. Making it
732
+ * fire would be worse than leaving it dead: events are a stream the client
733
+ * reassembles (stream deltas, file changes, terminal output), and a silently
734
+ * missing one is a wrong screen. What used to fill the buffer — one huge
735
+ * reply — is now chunked and drained instead (backend/utils/ws-wire.ts).
735
736
  */
736
737
  private canSend(conn: WSConnection): boolean {
737
- if (!CONFIG.ENABLE_BACKPRESSURE) return true;
738
-
739
- // Check WebSocket ready state
740
- if (conn.readyState !== 1) return false;
741
-
742
- // Check buffer size if available (Bun/uWebSockets)
743
- const rawWs = conn as any;
744
- if (typeof rawWs.getBufferedAmount === 'function') {
745
- const buffered = rawWs.getBufferedAmount();
746
- if (buffered > CONFIG.MAX_BUFFER_SIZE) {
747
- if (CONFIG.LOG_DROPPED_FRAMES) {
748
- this.metrics.droppedFrames++;
749
- const id = this.resolveId(conn) || 'unknown';
750
- debug.warn('websocket', `Backpressure: dropping frame for ${id} (buffer: ${buffered})`);
751
- }
752
- return false;
753
- }
754
- }
755
-
756
- return true;
738
+ return conn.readyState === 1;
757
739
  }
758
740
 
759
741
  /**
760
- * Send message to a single connection with backpressure handling
742
+ * Send a serialized event to a single connection.
761
743
  */
762
744
  private sendToConnection(conn: WSConnection, message: string | ArrayBuffer): boolean {
763
745
  if (!this.canSend(conn)) {
@@ -765,11 +747,10 @@ class WSServer {
765
747
  }
766
748
 
767
749
  try {
768
- // For binary data (ArrayBuffer), wrap in Buffer for Bun/Elysia compatibility
769
750
  if (message instanceof ArrayBuffer) {
770
- conn.send(Buffer.from(message));
751
+ sendBinary(conn, 'binary-event', message);
771
752
  } else {
772
- conn.send(message);
753
+ sendText(conn, actionOf(message), message);
773
754
  }
774
755
  return true;
775
756
  } catch (err) {
@@ -851,6 +832,27 @@ class WSServer {
851
832
  debug.log('websocket', `Emitted ${eventStr}${hasBinary ? ' (binary)' : ''} to ${sentCount}/${room.size} connections in project ${projectId}`);
852
833
  },
853
834
 
835
+ /**
836
+ * Emit to the connections of a project room that pass `include` — for a
837
+ * stream only some of the room is looking at (a panel's live detail).
838
+ */
839
+ projectWhere: <K extends keyof WSAPI['server']>(
840
+ projectId: string,
841
+ include: (connectionId: string) => boolean,
842
+ event: K,
843
+ payload: WSAPI['server'][K]
844
+ ): void => {
845
+ this.metrics.totalEmits++;
846
+ const room = this.projectRooms.get(projectId);
847
+ if (!room || room.size === 0) return;
848
+ let message: string | null = null;
849
+ for (const [connectionId, wsConn] of room) {
850
+ if (!include(connectionId)) continue;
851
+ message ??= JSON.stringify({ action: event, payload });
852
+ this.sendToConnection(wsConn, message);
853
+ }
854
+ },
855
+
854
856
  /**
855
857
  * Emit event to all connections of a specific user
856
858
  */
@@ -123,6 +123,14 @@ function handleWaitingInputChange(
123
123
  }
124
124
  }
125
125
 
126
+ // A stream started or stopped waiting on background work between turns: every
127
+ // device's indicator follows presence (see waitingOnBackground).
128
+ streamManager.on('stream:background', () => {
129
+ broadcastPresence().catch((err) => {
130
+ debug.warn('chat', 'Presence broadcast error on background-work change:', err);
131
+ });
132
+ });
133
+
126
134
  streamManager.on('stream:message', (payload: { event: StreamEvent; chatSessionId: string; projectId?: string }) => {
127
135
  try {
128
136
  handleWaitingInputChange(payload.event, payload.chatSessionId, payload.projectId);
@@ -207,20 +215,31 @@ const chatSessionModelState = new Map<string, { engine: string; provider: string
207
215
  // In-memory store for account state per chat session (keyed by chatSessionId)
208
216
  const chatSessionAccountState = new Map<string, { accountId: number | null; senderId: string }>();
209
217
 
218
+ /** Streams currently forwarded to their room — at most one bridge each. */
219
+ const roomBridges = new Map<string, () => void>();
220
+
210
221
  /**
211
222
  * Forward one stream's events to its chat session room until the stream ends.
212
223
  *
213
224
  * Every path that attaches a stream to the room goes through here — the
214
225
  * sender's own request, a client re-attaching after a refresh, and a queued
215
226
  * message the server starts on its own — so the event wire format exists once.
216
- * Returns the unsubscribe; a terminal event unsubscribes by itself.
227
+ *
228
+ * Idempotent per stream, and not tied to any connection. A bridge emits to the
229
+ * whole room, so one is all a room ever needs: every client that re-attached
230
+ * used to add its own, and each frame then reached every device once per
231
+ * bridge (the client dropped the copies by `seq`, the bandwidth was spent).
232
+ * Tying a bridge to its connection had the opposite failure: when the sender's
233
+ * tab closed, its bridge went with it and the other devices still in the room
234
+ * stopped receiving the turn. It lives until the stream's terminal event.
217
235
  */
218
236
  export function bridgeStreamToRoom(
219
237
  streamId: string,
220
238
  chatSessionId: string,
221
239
  projectId: string | undefined,
222
240
  options: { presenceOnConnection?: boolean } = {}
223
- ): () => void {
241
+ ): void {
242
+ if (roomBridges.has(streamId)) return;
224
243
  const { presenceOnConnection = true } = options;
225
244
 
226
245
  const handleStreamEvent = (event: StreamEvent) => {
@@ -262,7 +281,9 @@ export function bridgeStreamToRoom(
262
281
  chatSessionId,
263
282
  processId: event.processId,
264
283
  eventType: event.data.eventType as any,
265
- partialText: event.data.partialText || '',
284
+ block: event.data.block ?? 0,
285
+ ...(typeof event.data.offset === 'number' && { offset: event.data.offset }),
286
+ ...(typeof event.data.partialText === 'string' && { partialText: event.data.partialText }),
266
287
  deltaText: event.data.deltaText || '',
267
288
  ...(event.data.reasoning && { reasoning: true }),
268
289
  timestamp: event.data.timestamp,
@@ -335,8 +356,17 @@ export function bridgeStreamToRoom(
335
356
  }
336
357
  };
337
358
 
338
- const unsubscribe = streamManager.subscribeToStream(streamId, handleStreamEvent);
339
- return unsubscribe;
359
+ const stopForwarding = streamManager.subscribeToStream(streamId, handleStreamEvent);
360
+ const unsubscribe = () => {
361
+ stopForwarding();
362
+ roomBridges.delete(streamId);
363
+ };
364
+ roomBridges.set(streamId, unsubscribe);
365
+
366
+ // A stream that ended before it was bridged will never send the terminal
367
+ // event that removes the bridge.
368
+ const status = streamManager.getStream(streamId)?.status;
369
+ if (status && status !== 'active') unsubscribe();
340
370
  }
341
371
 
342
372
  /**
@@ -523,9 +553,8 @@ export const streamHandler = createRouter()
523
553
  });
524
554
  if (!streamId) return;
525
555
 
526
- // Tied to this connection: it closes with the connection, and the
527
- // client's reconnect builds a new one.
528
- ws.addCleanup(conn, bridgeStreamToRoom(streamId, data.chatSessionId, projectId));
556
+ // One bridge per stream, living until the stream ends — see bridgeStreamToRoom.
557
+ bridgeStreamToRoom(streamId, data.chatSessionId, projectId);
529
558
  })
530
559
 
531
560
  // Reconnect to an active stream (after browser refresh / project switch)
@@ -548,7 +577,7 @@ export const streamHandler = createRouter()
548
577
 
549
578
  debug.log('chat', 'Reconnecting to active stream:', streamState.streamId);
550
579
 
551
- ws.addCleanup(conn, bridgeStreamToRoom(streamState.streamId, chatSessionId, projectId, { presenceOnConnection: false }));
580
+ bridgeStreamToRoom(streamState.streamId, chatSessionId, projectId, { presenceOnConnection: false });
552
581
 
553
582
  // Send current state snapshot to chat session room so frontend can catch up
554
583
  ws.emit.chatSession(chatSessionId, 'chat:connection', {
@@ -615,9 +644,16 @@ export const streamHandler = createRouter()
615
644
  t.Literal('cancelled')
616
645
  ]),
617
646
  processId: t.String(),
618
- messages: t.Array(t.Any()),
647
+ /**
648
+ * The stream's event sequence when this snapshot was taken. A client
649
+ * that already applied a newer event treats the snapshot as stale.
650
+ */
651
+ seq: t.Optional(t.Number()),
619
652
  currentPartialText: t.Optional(t.String()),
620
653
  currentReasoningText: t.Optional(t.String()),
654
+ /** The blocks those two texts belong to (see `chat:partial`). */
655
+ partialBlock: t.Optional(t.Number()),
656
+ reasoningBlock: t.Optional(t.Number()),
621
657
  error: t.Optional(t.String()),
622
658
  startedAt: t.String(),
623
659
  completedAt: t.Optional(t.String())
@@ -640,7 +676,6 @@ export const streamHandler = createRouter()
640
676
  streamId: data.chatSessionId || '',
641
677
  status: 'completed' as const,
642
678
  processId: '',
643
- messages: [],
644
679
  currentPartialText: undefined,
645
680
  currentReasoningText: undefined,
646
681
  error: undefined,
@@ -653,16 +688,16 @@ export const streamHandler = createRouter()
653
688
  streamId: streamState.streamId,
654
689
  status: streamState.status,
655
690
  processId: streamState.processId,
656
- // Trim sub-agent noise from the catch-up buffer too (see trimSubAgentForWire).
657
- // Buffer entries wrap the UnifiedMessage under `.message`; leave the rest intact.
658
- messages: streamState.messages.map(entry => {
659
- const wrapped = entry as { message?: UnifiedMessage };
660
- return wrapped?.message
661
- ? { ...wrapped, message: trimSubAgentForWire(wrapped.message) }
662
- : entry;
663
- }),
691
+ // No message history here: the transcript is loaded through
692
+ // messages:list-page, and a long turn's history (screenshots
693
+ // included) made this reply megabytes — sent in chunks that newer
694
+ // live events overtook, so the snapshot landed after the messages
695
+ // it predated.
696
+ seq: streamState.eventSeq,
664
697
  currentPartialText: streamState.currentPartialText,
665
698
  currentReasoningText: streamState.currentReasoningText,
699
+ partialBlock: streamState.partialBlock,
700
+ reasoningBlock: streamState.reasoningBlock,
666
701
  error: streamState.error,
667
702
  startedAt: streamState.startedAt.toISOString(),
668
703
  completedAt: streamState.completedAt?.toISOString()
@@ -931,7 +966,12 @@ export const streamHandler = createRouter()
931
966
  t.Literal('update'),
932
967
  t.Literal('end')
933
968
  ]),
934
- partialText: t.String(),
969
+ /** Changes on every `start`; deltas only apply within their block. */
970
+ block: t.Number(),
971
+ /** Length of the block's text before `deltaText` (start/update). */
972
+ offset: t.Optional(t.Number()),
973
+ /** The block's full text — on `end` only. */
974
+ partialText: t.Optional(t.String()),
935
975
  deltaText: t.String(),
936
976
  reasoning: t.Optional(t.Boolean()),
937
977
  timestamp: t.String(),
@@ -179,6 +179,36 @@ export const readHandler = createRouter()
179
179
  return result;
180
180
  })
181
181
 
182
+ /**
183
+ * Size and modification time of several files at once, without their
184
+ * contents. The Files panel's safety-net check on focus uses it to re-read
185
+ * only the open tabs whose file actually changed, instead of downloading
186
+ * every open file again on every alt-tab. `modified` is in the same format
187
+ * `files:read-file` returns, so the two compare directly.
188
+ */
189
+ .http('files:read-stats', {
190
+ data: t.Object({
191
+ file_paths: t.Array(t.String())
192
+ }),
193
+ response: t.Array(t.Object({
194
+ /** The path as requested. */
195
+ path: t.String(),
196
+ exists: t.Boolean(),
197
+ size: t.Optional(t.Number()),
198
+ modified: t.Optional(t.String())
199
+ }))
200
+ }, async ({ data }) => {
201
+ return await Promise.all(data.file_paths.map(async (requested) => {
202
+ try {
203
+ const stats = await Bun.file(await resolveFilePath(requested)).stat();
204
+ if (!stats.isFile()) return { path: requested, exists: false };
205
+ return { path: requested, exists: true, size: stats.size, modified: stats.mtime.toISOString() };
206
+ } catch {
207
+ return { path: requested, exists: false };
208
+ }
209
+ }));
210
+ })
211
+
182
212
  // Read file content at a git ref (e.g. HEAD) for diff comparison
183
213
  .http('files:read-file-at', {
184
214
  data: t.Object({
@@ -8,6 +8,7 @@ import { createRouter } from '$shared/utils/ws-server';
8
8
  import { gitService } from '../../git/git-service';
9
9
  import { requireProjectWorkspace } from '../access';
10
10
  import { debug } from '$shared/utils/logger';
11
+ import { aggregateContributors, contributorKey, CONTRIBUTOR_WINDOW } from '../../git/contributors';
11
12
 
12
13
  /**
13
14
  * Resolve the working directory for a git operation. Defaults to the project
@@ -61,6 +62,57 @@ export const logHandler = createRouter()
61
62
  );
62
63
  })
63
64
 
65
+ /**
66
+ * Who authored the last `CONTRIBUTOR_WINDOW` commits, as counts. The panel used
67
+ * to download those commits in full on every git change to work this out.
68
+ */
69
+ .http('git:list-contributors', {
70
+ data: t.Object({
71
+ projectId: t.String(),
72
+ repoPath: t.Optional(t.String())
73
+ }),
74
+ response: t.Object({
75
+ contributors: t.Array(t.Object({
76
+ key: t.String(),
77
+ name: t.String(),
78
+ email: t.String(),
79
+ count: t.Number(),
80
+ lastDate: t.String()
81
+ })),
82
+ /** Commits sampled — the denominator of each contributor's share. */
83
+ total: t.Number()
84
+ })
85
+ }, async ({ data, conn }) => {
86
+ const { root } = requireProjectWorkspace(conn, data.projectId);
87
+ const cwd = resolveRepoCwd(root, data.repoPath);
88
+ const { commits } = await gitService.getLog(cwd, CONTRIBUTOR_WINDOW, 0);
89
+ return { contributors: aggregateContributors(commits), total: commits.length };
90
+ })
91
+
92
+ /** One contributor's commits within the same window — read when a row is expanded. */
93
+ .http('git:list-contributor-commits', {
94
+ data: t.Object({
95
+ projectId: t.String(),
96
+ key: t.String(),
97
+ repoPath: t.Optional(t.String())
98
+ }),
99
+ response: t.Array(t.Object({
100
+ hash: t.String(),
101
+ hashShort: t.String(),
102
+ author: t.String(),
103
+ authorEmail: t.String(),
104
+ date: t.String(),
105
+ message: t.String(),
106
+ parents: t.Array(t.String()),
107
+ refs: t.Optional(t.Array(t.String()))
108
+ }))
109
+ }, async ({ data, conn }) => {
110
+ const { root } = requireProjectWorkspace(conn, data.projectId);
111
+ const cwd = resolveRepoCwd(root, data.repoPath);
112
+ const { commits } = await gitService.getLog(cwd, CONTRIBUTOR_WINDOW, 0);
113
+ return commits.filter((commit) => contributorKey(commit) === data.key);
114
+ })
115
+
64
116
  /**
65
117
  * The repo's undo journal. Unlike `git log` this still lists commits that a
66
118
  * reset, a branch delete or a rebase orphaned, so it is the recovery path for