@myrialabs/clopen 0.4.48 → 0.4.49

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 (91) hide show
  1. package/backend/chat/message-pages.test.ts +163 -0
  2. package/backend/chat/message-pages.ts +233 -0
  3. package/backend/chat/stream-manager.ts +29 -5
  4. package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/database/queries/blob-line-stats-queries.ts +48 -0
  7. package/backend/database/queries/index.ts +2 -0
  8. package/backend/db-client/env/diff.ts +9 -33
  9. package/backend/db-client/env/env.test.ts +8 -8
  10. package/backend/db-client/env/service.ts +1 -1
  11. package/backend/files/file-watcher.ts +19 -0
  12. package/backend/git/contributors.test.ts +35 -0
  13. package/backend/git/contributors.ts +46 -0
  14. package/backend/http/static-assets.test.ts +78 -0
  15. package/backend/http/static-assets.ts +104 -0
  16. package/backend/index.ts +11 -9
  17. package/backend/preview/browser/browser-preview-service.ts +24 -6
  18. package/backend/snapshot/blob-store.ts +9 -1
  19. package/backend/snapshot/helpers.ts +3 -10
  20. package/backend/snapshot/line-stats.test.ts +80 -0
  21. package/backend/snapshot/line-stats.ts +64 -0
  22. package/backend/snapshot/snapshot-service.ts +14 -27
  23. package/backend/snapshot/turn-changes.test.ts +10 -5
  24. package/backend/snapshot/turn-changes.ts +78 -40
  25. package/backend/terminal/ptykit.ts +6 -1
  26. package/backend/utils/ws-wire.test.ts +87 -0
  27. package/backend/utils/ws-wire.ts +189 -0
  28. package/backend/utils/ws.ts +40 -38
  29. package/backend/ws/chat/stream.ts +41 -10
  30. package/backend/ws/files/read.ts +30 -0
  31. package/backend/ws/git/log.ts +52 -0
  32. package/backend/ws/messages/crud.ts +49 -0
  33. package/backend/ws/preview/index.ts +2 -0
  34. package/backend/ws/preview/watchers.ts +84 -0
  35. package/backend/ws/sessions/crud.ts +8 -12
  36. package/backend/ws/snapshot/changes.ts +5 -6
  37. package/backend/ws/terminal/tunnel.ts +2 -2
  38. package/bin/clopen.ts +36 -30
  39. package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
  40. package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
  41. package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
  42. package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
  43. package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
  44. package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
  45. package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
  46. package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
  47. package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
  48. package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
  49. package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
  50. package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
  51. package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
  52. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
  53. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
  54. package/dist/assets/{index-CONlwAXZ.js → index-CrVWZH_D.js} +1 -1
  55. package/dist/assets/index-CrVWZH_D.js.br +0 -0
  56. package/dist/assets/index-CrVWZH_D.js.gz +0 -0
  57. package/dist/assets/{index-DJzwt-hq.js → index-DD0-3EWg.js} +1 -1
  58. package/dist/assets/index-DD0-3EWg.js.br +0 -0
  59. package/dist/assets/index-DD0-3EWg.js.gz +0 -0
  60. package/dist/assets/{main-nBOb9YOA.js → main-D2_TmcwQ.js} +604 -604
  61. package/dist/assets/main-D2_TmcwQ.js.br +0 -0
  62. package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
  63. package/dist/assets/main-Yucigcmf.css +1 -0
  64. package/dist/assets/main-Yucigcmf.css.br +0 -0
  65. package/dist/assets/main-Yucigcmf.css.gz +0 -0
  66. package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
  67. package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
  68. package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
  69. package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
  70. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
  71. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
  72. package/dist/fonts/dm-sans.css.br +0 -0
  73. package/dist/fonts/dm-sans.css.gz +0 -0
  74. package/dist/index.html +2 -2
  75. package/dist/index.html.br +0 -0
  76. package/dist/index.html.gz +0 -0
  77. package/dist/sw.js.br +0 -0
  78. package/dist/sw.js.gz +0 -0
  79. package/package.json +2 -3
  80. package/shared/types/unified/stream.ts +11 -1
  81. package/shared/utils/diff-calculator.test.ts +178 -41
  82. package/shared/utils/diff-calculator.ts +383 -100
  83. package/shared/utils/process-supervisor.test.ts +172 -0
  84. package/shared/utils/process-supervisor.ts +251 -0
  85. package/shared/utils/ws-chunk.test.ts +33 -0
  86. package/shared/utils/ws-chunk.ts +73 -0
  87. package/shared/utils/ws-client-chunks.test.ts +45 -0
  88. package/shared/utils/ws-client.ts +43 -0
  89. package/shared/utils/ws-server.ts +17 -14
  90. package/backend/database/migrations/086_single_owner.test.ts +0 -170
  91. package/dist/assets/main-BUiUL3eZ.css +0 -1
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The production `LineStatsSource`: every pair of blobs is counted once.
3
+ *
4
+ * Blobs are content-addressed, so the +/- count of (oldHash, newHash) is a
5
+ * fact that never changes. It used to be recomputed on every chat open, every
6
+ * reconnect and every pending-changes poll — twice per request, once for the
7
+ * turn list and once for the net total — and a single large file made each of
8
+ * those block the server. Now the first caller computes it and every later
9
+ * one, on any surface, reads the same row (migration 087).
10
+ *
11
+ * The count itself is `countPairFromBlobs`; this module only remembers it.
12
+ */
13
+
14
+ import { blobLineStatsQueries } from '../database/queries/blob-line-stats-queries';
15
+ import { blobStore } from './blob-store';
16
+ import { countPairFromBlobs } from './turn-changes';
17
+ import type { LineStatsSource, PairLineStats } from './turn-changes';
18
+ import { debug } from '$shared/utils/logger';
19
+
20
+ /** Pairs being counted right now, so concurrent callers share one computation. */
21
+ const inFlight = new Map<string, Promise<PairLineStats>>();
22
+
23
+ const readBlob = (hash: string) => blobStore.readBlob(hash);
24
+
25
+ /** Whether both sides of a pair can still be read — the diff view needs them. */
26
+ async function contentAvailable(oldHash: string, newHash: string): Promise<boolean> {
27
+ const [hasOld, hasNew] = await Promise.all([
28
+ oldHash ? blobStore.hasBlob(oldHash) : true,
29
+ newHash ? blobStore.hasBlob(newHash) : true
30
+ ]);
31
+ return hasOld && hasNew;
32
+ }
33
+
34
+ async function computeAndRemember(oldHash: string, newHash: string): Promise<PairLineStats> {
35
+ const stats = await countPairFromBlobs(oldHash, newHash, readBlob);
36
+ // A missing blob yields a non-answer, not a count — never store it.
37
+ if (stats.contentAvailable) {
38
+ try {
39
+ blobLineStatsQueries.save(oldHash, newHash, stats);
40
+ } catch (error) {
41
+ debug.warn('snapshot', 'Failed to cache line stats:', error);
42
+ }
43
+ }
44
+ return stats;
45
+ }
46
+
47
+ export const blobLineStats: LineStatsSource = async (oldHash, newHash) => {
48
+ try {
49
+ const cached = blobLineStatsQueries.get(oldHash, newHash);
50
+ if (cached) {
51
+ return { ...cached, contentAvailable: await contentAvailable(oldHash, newHash) };
52
+ }
53
+ } catch (error) {
54
+ debug.warn('snapshot', 'Failed to read cached line stats:', error);
55
+ }
56
+
57
+ const key = `${oldHash}:${newHash}`;
58
+ const pending = inFlight.get(key);
59
+ if (pending) return pending;
60
+
61
+ const computation = computeAndRemember(oldHash, newHash).finally(() => inFlight.delete(key));
62
+ inFlight.set(key, computation);
63
+ return computation;
64
+ };
@@ -23,7 +23,8 @@ import { attributeGitChanges, readRepoHeads, type RepoHeads } from './git-attrib
23
23
  import { TurnActivity, type ObservedOutput } from './turn-activity';
24
24
  import { fileWatcher } from '../files/file-watcher';
25
25
  import type { MessageSnapshot, SessionScopedChanges } from '$shared/types/database/schema';
26
- import { calculateFileChangeStats } from '$shared/utils/diff-calculator';
26
+ import { buildTurnFiles, summariseTurnFiles } from './turn-changes';
27
+ import { blobLineStats } from './line-stats';
27
28
  import { makeScopeKey } from '$shared/utils/workspace-scope';
28
29
  import { debug } from '$shared/utils/logger';
29
30
 
@@ -180,14 +181,13 @@ export class SnapshotService {
180
181
  private async scanTree(
181
182
  root: string,
182
183
  previous: TreeMap
183
- ): Promise<{ tree: TreeMap; contents: Map<string, Buffer> }> {
184
+ ): Promise<{ tree: TreeMap }> {
184
185
  const scan = await scanSnapshotFiles(root, { pruneGenerated: true });
185
186
  if (scan.incomplete.includes('')) {
186
187
  throw new Error(`Could not list the files of ${root}`);
187
188
  }
188
189
 
189
190
  const tree: TreeMap = {};
190
- const contents = new Map<string, Buffer>();
191
191
 
192
192
  if (scan.incomplete.length > 0) {
193
193
  for (const [filepath, hash] of Object.entries(previous)) {
@@ -207,16 +207,13 @@ export class SnapshotService {
207
207
 
208
208
  const result = await blobStore.hashFile(filepath);
209
209
  tree[relativePath] = result.hash;
210
- if (result.content !== null && result.hash !== previous[relativePath]) {
211
- contents.set(relativePath, result.content);
212
- }
213
210
  } catch (error) {
214
211
  if (isMissingFile(error)) return;
215
212
  if (previous[relativePath]) tree[relativePath] = previous[relativePath];
216
213
  }
217
214
  });
218
215
 
219
- return { tree, contents };
216
+ return { tree };
220
217
  }
221
218
 
222
219
  // ========================================================================
@@ -556,7 +553,7 @@ export class SnapshotService {
556
553
  // closed. A gitignore-aware scan + hash diff against the baseline is
557
554
  // always correct, and blobStore.hashFile's mtime+size cache keeps it
558
555
  // cheap — only files that actually changed are re-read.
559
- const { tree: currentTree, contents: readContents } = await this.scanTree(projectPath, previousTree);
556
+ const { tree: currentTree } = await this.scanTree(projectPath, previousTree);
560
557
  const sessionChanges = diffTrees(previousTree, currentTree);
561
558
 
562
559
  // A disk diff sees every writer. Take out what is not this turn's.
@@ -589,7 +586,7 @@ export class SnapshotService {
589
586
  }
590
587
 
591
588
  // Calculate line-level file change stats
592
- const fileStats = await this.calculateChangeStats(sessionChanges, readContents);
589
+ const fileStats = await this.calculateChangeStats(sessionChanges);
593
590
 
594
591
  const metadata: SnapshotMetadata = {
595
592
  totalFiles: Object.keys(currentTree).length,
@@ -1069,27 +1066,17 @@ export class SnapshotService {
1069
1066
  }
1070
1067
 
1071
1068
  /**
1072
- * Calculate line-level change stats for changed files.
1069
+ * Line-level change stats for a turn's changed files.
1070
+ *
1071
+ * Counted through the same `buildTurnFiles` + `blobLineStats` every other
1072
+ * surface reads, so the numbers stored on the row are the ones the Changes
1073
+ * tab shows — and counting here, at capture, is what puts each pair in the
1074
+ * cache before anyone opens the chat.
1073
1075
  */
1074
1076
  private async calculateChangeStats(
1075
- sessionChanges: SessionScopedChanges,
1076
- readContents: Map<string, Buffer>
1077
+ sessionChanges: SessionScopedChanges
1077
1078
  ): Promise<{ filesChanged: number; insertions: number; deletions: number }> {
1078
- const previousSnapshot: Record<string, Buffer> = {};
1079
- const currentSnapshot: Record<string, Buffer> = {};
1080
-
1081
- for (const [filepath, change] of Object.entries(sessionChanges)) {
1082
- try {
1083
- if (change.oldHash) {
1084
- previousSnapshot[filepath] = await blobStore.readBlob(change.oldHash);
1085
- }
1086
- if (change.newHash) {
1087
- currentSnapshot[filepath] = readContents.get(filepath) ?? await blobStore.readBlob(change.newHash);
1088
- }
1089
- } catch { /* skip */ }
1090
- }
1091
-
1092
- return calculateFileChangeStats(previousSnapshot, currentSnapshot);
1079
+ return summariseTurnFiles(await buildTurnFiles(sessionChanges, blobLineStats));
1093
1080
  }
1094
1081
 
1095
1082
  /**
@@ -18,16 +18,21 @@ import {
18
18
  summariseTurnFiles,
19
19
  excerptPrompt,
20
20
  netChangeRuns,
21
- summariseNetChanges
21
+ summariseNetChanges,
22
+ statsFromBlobs
22
23
  } from './turn-changes';
24
+ import type { LineStatsSource } from './turn-changes';
23
25
 
24
- /** Blob reader over an in-memory store, so the tests own their failure modes. */
25
- function readerFor(blobs: Record<string, string | Buffer>) {
26
- return async (hash: string): Promise<Buffer> => {
26
+ /**
27
+ * Line stats over an in-memory blob store, so the tests own their failure
28
+ * modes. Uncached on purpose: the hashes here are labels, not content hashes.
29
+ */
30
+ function readerFor(blobs: Record<string, string | Buffer>): LineStatsSource {
31
+ return statsFromBlobs(async (hash: string): Promise<Buffer> => {
27
32
  const value = blobs[hash];
28
33
  if (value === undefined) throw new Error(`missing blob ${hash}`);
29
34
  return Buffer.isBuffer(value) ? value : Buffer.from(value, 'utf8');
30
- };
35
+ });
31
36
  }
32
37
 
33
38
  describe('statusOf', () => {
@@ -18,7 +18,7 @@
18
18
 
19
19
  import type { SessionScopedChanges } from '$shared/types/database/schema';
20
20
  import { naturalCompare } from '$shared/utils/compare';
21
- import { countLineChanges, isBinaryBuffer } from '$shared/utils/diff-calculator';
21
+ import { countLineChangesAsync, isBinaryBuffer } from '$shared/utils/diff-calculator';
22
22
 
23
23
  export { isBinaryBuffer };
24
24
 
@@ -46,54 +46,92 @@ export function statusOf(oldHash: string, newHash: string): TurnFileStatus {
46
46
  return 'modified';
47
47
  }
48
48
 
49
+ /** What one (old, new) pair of blobs amounts to as a +/- badge. */
50
+ export interface PairLineStats {
51
+ insertions: number;
52
+ deletions: number;
53
+ isBinary: boolean;
54
+ /** False when a blob this pair needs is no longer readable. */
55
+ contentAvailable: boolean;
56
+ }
57
+
58
+ /**
59
+ * Where a pair's numbers come from. Production passes `blobLineStats`
60
+ * (backend/snapshot/line-stats.ts), which counts each pair once and remembers
61
+ * it; tests pass `statsFromBlobs` over an in-memory store.
62
+ */
63
+ export type LineStatsSource = (oldHash: string, newHash: string) => Promise<PairLineStats>;
64
+
65
+ /**
66
+ * Count one pair straight from its blobs. This is the single definition of
67
+ * "how many lines did this change" — the cache only stores what it returns.
68
+ */
69
+ export async function countPairFromBlobs(
70
+ oldHash: string,
71
+ newHash: string,
72
+ readBlob: (hash: string) => Promise<Buffer>
73
+ ): Promise<PairLineStats> {
74
+ let oldBuf: Buffer | null = null;
75
+ let newBuf: Buffer | null = null;
76
+ let contentAvailable = true;
77
+
78
+ if (oldHash) {
79
+ try {
80
+ oldBuf = await readBlob(oldHash);
81
+ } catch {
82
+ contentAvailable = false;
83
+ }
84
+ }
85
+ if (newHash) {
86
+ try {
87
+ newBuf = await readBlob(newHash);
88
+ } catch {
89
+ contentAvailable = false;
90
+ }
91
+ }
92
+
93
+ const isBinary =
94
+ (oldBuf !== null && isBinaryBuffer(oldBuf)) || (newBuf !== null && isBinaryBuffer(newBuf));
95
+
96
+ let insertions = 0;
97
+ let deletions = 0;
98
+ if (contentAvailable && !isBinary) {
99
+ // Cooperative: a pathological pair takes long, but never holds the
100
+ // server's thread for more than a few milliseconds at a time.
101
+ const counts = await countLineChangesAsync(
102
+ oldBuf ? oldBuf.toString('utf8') : '',
103
+ newBuf ? newBuf.toString('utf8') : ''
104
+ );
105
+ insertions = counts.additions;
106
+ deletions = counts.deletions;
107
+ }
108
+
109
+ return { insertions, deletions, isBinary, contentAvailable };
110
+ }
111
+
112
+ /** An uncached source over any blob reader. */
113
+ export function statsFromBlobs(readBlob: (hash: string) => Promise<Buffer>): LineStatsSource {
114
+ return (oldHash, newHash) => countPairFromBlobs(oldHash, newHash, readBlob);
115
+ }
116
+
49
117
  /**
50
118
  * Turn one checkpoint's `session_changes` into a displayable file list.
51
119
  *
52
- * `readBlob` is injected so this stays a pure function over its inputs — the
53
- * only I/O is the reader the caller hands in.
120
+ * `statsFor` is injected so this stays a pure function over its inputs — the
121
+ * only I/O is the source the caller hands in.
54
122
  */
55
123
  export async function buildTurnFiles(
56
124
  changes: SessionScopedChanges,
57
- readBlob: (hash: string) => Promise<Buffer>
125
+ statsFor: LineStatsSource
58
126
  ): Promise<TurnFileChange[]> {
59
127
  const files: TurnFileChange[] = [];
60
128
 
61
129
  for (const [path, change] of Object.entries(changes)) {
62
130
  const status = statusOf(change.oldHash, change.newHash);
63
-
64
- let oldBuf: Buffer | null = null;
65
- let newBuf: Buffer | null = null;
66
- let contentAvailable = true;
67
-
68
- if (change.oldHash) {
69
- try {
70
- oldBuf = await readBlob(change.oldHash);
71
- } catch {
72
- contentAvailable = false;
73
- }
74
- }
75
- if (change.newHash) {
76
- try {
77
- newBuf = await readBlob(change.newHash);
78
- } catch {
79
- contentAvailable = false;
80
- }
81
- }
82
-
83
- const isBinary =
84
- (oldBuf !== null && isBinaryBuffer(oldBuf)) || (newBuf !== null && isBinaryBuffer(newBuf));
85
-
86
- let insertions = 0;
87
- let deletions = 0;
88
- if (contentAvailable && !isBinary) {
89
- const counts = countLineChanges(
90
- oldBuf ? oldBuf.toString('utf8') : '',
91
- newBuf ? newBuf.toString('utf8') : ''
92
- );
93
- insertions = counts.additions;
94
- deletions = counts.deletions;
95
- }
96
-
131
+ const { insertions, deletions, isBinary, contentAvailable } = await statsFor(
132
+ change.oldHash,
133
+ change.newHash
134
+ );
97
135
  files.push({ path, status, insertions, deletions, isBinary, contentAvailable });
98
136
  }
99
137
 
@@ -177,7 +215,7 @@ export function netChangeRuns(turns: SessionScopedChanges[]): Map<string, Change
177
215
  /** The chat-level numbers: net files changed, and net lines in and out. */
178
216
  export async function summariseNetChanges(
179
217
  turns: SessionScopedChanges[],
180
- readBlob: (hash: string) => Promise<Buffer>
218
+ statsFor: LineStatsSource
181
219
  ): Promise<{ filesChanged: number; insertions: number; deletions: number }> {
182
220
  let insertions = 0;
183
221
  let deletions = 0;
@@ -189,7 +227,7 @@ export async function summariseNetChanges(
189
227
  list.forEach((run, index) => {
190
228
  changes[`${index}\0${path}`] = run;
191
229
  });
192
- const summary = summariseTurnFiles(await buildTurnFiles(changes, readBlob));
230
+ const summary = summariseTurnFiles(await buildTurnFiles(changes, statsFor));
193
231
  insertions += summary.insertions;
194
232
  deletions += summary.deletions;
195
233
  }
@@ -35,13 +35,18 @@ export const ptyKitManager = new PtyKitManager({
35
35
  // refresh/reconnect can still replay their final screen (matches old 5-min window).
36
36
  idleTtl: null,
37
37
  retainExitedMs: 5 * 60_000,
38
+ // A flood (a build, a dev server's log) is held to one frame per window;
39
+ // the first chunk after a pause still goes out at once, so typing is not.
40
+ outputCoalesceMs: 16,
38
41
  env: { sanitize: true, inject: TERMINAL_ENV }
39
42
  });
40
43
 
41
44
  /**
42
45
  * Embedded WebSocket server over the manager. No HTTP/Bun mounting — Clopen's
43
46
  * tunnel feeds it frames and supplies per-connection `send`. `authorize` enforces
44
- * project access; the room is the project so every device sees the same output.
47
+ * project access. The room is the workspace scope, which carries awareness (tabs
48
+ * opened or closed on any device); a session's output goes only to the devices
49
+ * that have that tab mounted (PtyKit 0.1.0).
45
50
  */
46
51
  export const ptyKitServer = createPtyKitServer(ptyKitManager, {
47
52
  room: (ctx) => ctx.namespace,
@@ -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
+ }