@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
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/dist/index.html CHANGED
@@ -63,8 +63,8 @@
63
63
  }
64
64
  })();
65
65
  </script>
66
- <script type="module" crossorigin src="/assets/main-nBOb9YOA.js"></script>
67
- <link rel="stylesheet" crossorigin href="/assets/main-BUiUL3eZ.css">
66
+ <script type="module" crossorigin src="/assets/main-Da3JKoua.js"></script>
67
+ <link rel="stylesheet" crossorigin href="/assets/main-DIESTGTD.css">
68
68
  </head>
69
69
  <body
70
70
  class="min-h-dvh bg-white text-slate-900 dark:bg-slate-950 dark:text-slate-100 transition-colors duration-200"
Binary file
Binary file
package/dist/sw.js.br ADDED
Binary file
package/dist/sw.js.gz ADDED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myrialabs/clopen",
3
- "version": "0.4.48",
3
+ "version": "0.4.50",
4
4
  "description": "All-in-one web workspace for AI coding agents — Claude Code, OpenCode, Codex, Copilot, Qwen Code, Pi, Cline, and Cursor — with chat, terminal, git, browser preview, database client, checkpoints, and real-time collaboration",
5
5
  "author": "Myria Labs",
6
6
  "license": "MIT",
@@ -104,7 +104,6 @@
104
104
  "@types/qrcode": "^1.5.6",
105
105
  "@types/random-useragent": "^0.3.3",
106
106
  "@types/ssh2": "^1.15.5",
107
- "concurrently": "^9.2.1",
108
107
  "eslint": "^9.31.0",
109
108
  "eslint-plugin-svelte": "^3.10.1",
110
109
  "globals": "^16.3.0",
@@ -124,8 +123,8 @@
124
123
  "@modelcontextprotocol/sdk": "1.31.0",
125
124
  "@monaco-editor/loader": "1.7.0",
126
125
  "@myrialabs/chatkit": "0.0.3",
127
- "@myrialabs/ptykit": "0.0.7",
128
- "@myrialabs/tunnelkit": "0.0.15",
126
+ "@myrialabs/ptykit": "0.1.1",
127
+ "@myrialabs/tunnelkit": "0.1.0",
129
128
  "@myrialabs/zipkit": "0.0.11",
130
129
  "@sinclair/typebox": "0.34.48",
131
130
  "@xyflow/svelte": "1.6.2",
@@ -351,40 +351,19 @@ export interface RetrievalResult {
351
351
  // Visualization
352
352
  // ─────────────────────────────────────────────────────────────────────────────
353
353
 
354
- /** A node as sent to the graph view: display fields plus its community. */
355
- export interface GraphViewNode {
356
- id: string;
357
- subkind: GraphNodeSubkind;
358
- scope: GraphScope;
359
- label: string;
360
- projectId: string | null;
361
- /** Degree, used to size the node. */
362
- degree: number;
363
- weight: number;
364
- pinned: boolean;
365
- /** Louvain community index — the "lobe" a node belongs to. */
366
- community: number;
367
- createdAt: string;
368
- /**
369
- * Where the persisted layout put this node, when it has been laid out.
370
- *
371
- * Absent means "no position yet" — a memory written since the last layout
372
- * pass — and the client seeds those from their neighbours rather than
373
- * re-solving the whole graph. See `backend/memory/layout.ts`.
374
- */
375
- x?: number;
376
- y?: number;
377
- }
378
-
379
- export interface GraphViewEdge {
380
- id: number;
381
- source: string;
382
- target: string;
383
- rel: GraphRelation;
384
- weight: number;
354
+ /**
355
+ * The square the graph view is cut into tiles from, in layout coordinates.
356
+ *
357
+ * Fixed between layout passes that change the map, so a tile's address means
358
+ * the same rectangle for as long as the client's `epoch` matches the server's.
359
+ */
360
+ export interface GraphWorld {
361
+ minX: number;
362
+ minY: number;
363
+ size: number;
385
364
  }
386
365
 
387
- /** A rectangle in layout space — what a zoomed-in view is scoped to. */
366
+ /** A rectangle in layout space. */
388
367
  export interface GraphRegion {
389
368
  minX: number;
390
369
  maxX: number;
@@ -393,65 +372,109 @@ export interface GraphRegion {
393
372
  }
394
373
 
395
374
  /**
396
- * Several memories that fell in one cell of the layout grid, drawn as one mark.
375
+ * Everything the view needs before it can ask for a single tile.
397
376
  *
398
- * This is what keeps the view's cost bounded without taking anything out of the
399
- * picture, and the distinction from the alternative matters. Grouping by
400
- * COMMUNITY replaces the picture — you see lobes instead of memories, and
401
- * reaching a memory means opening one. Grouping by POSITION keeps the picture:
402
- * marks merge only where their dots would have overlapped anyway, so the
403
- * silhouette, the lobes and the colours are the ones the full graph would have
404
- * drawn. Below the render budget nothing merges at all and every memory is its
405
- * own mark, exactly as before.
377
+ * The counts are the FILTER's, not the screen's: how many memories match, how
378
+ * many of those have a place on the map, and where they are — which is what
379
+ * "Fit" frames.
380
+ */
381
+ export interface GraphViewMeta {
382
+ /** Changes whenever the world does; a tile from another epoch is from another map. */
383
+ epoch: number;
384
+ /** Changes whenever a layout pass writes; tiles from an older stamp may be missing memories. */
385
+ stamp: number;
386
+ /** Null until the first layout pass has placed anything. */
387
+ world: GraphWorld | null;
388
+ /** Median distance between a memory and its nearest neighbour, in layout units. */
389
+ spacing: number;
390
+ /** Memories matching the filter. */
391
+ total: number;
392
+ /** Of those, how many have no position yet — they appear once a pass places them. */
393
+ unplaced: number;
394
+ /** Where the placed matches are; null when none are. */
395
+ extent: GraphRegion | null;
396
+ /** The degree that counts as "fully connected" when sizing nodes; see `degreeScale`. */
397
+ degreeScale: number;
398
+ }
399
+
400
+ /** A memory as a tile carries it: enough to draw and hover, nothing to inspect. */
401
+ export interface GraphTileNode {
402
+ id: string;
403
+ label: string;
404
+ /** Louvain community index — the "lobe" a node belongs to, and its colour. */
405
+ community: number;
406
+ /** Connections in the whole graph, stored and derived. Sizes the node. */
407
+ degree: number;
408
+ x: number;
409
+ y: number;
410
+ }
411
+
412
+ /**
413
+ * Several memories sharing one cell of a crowded tile, drawn as one mark.
406
414
  *
407
- * A bin is not a memory — it has no body, no scope and nothing to inspect —
408
- * which is why it travels in its own array rather than as a node wearing a fake
409
- * subkind.
415
+ * Only a tile with more memories than its budget is folded like this, and only
416
+ * where a cell holds more than one; zooming in asks for smaller tiles, which
417
+ * fit, so a cluster always resolves into its memories by zooming alone.
410
418
  */
411
- export interface GraphViewBin {
412
- /** `bin:<cellX>:<cellY>` — namespaced so it cannot collide with a node id. */
419
+ export interface GraphTileCluster {
420
+ /** `cluster:<z>:<cellX>:<cellY>` — namespaced so it cannot collide with a node id. */
413
421
  id: string;
414
- /** How many memories it stands for; drives its size. */
415
422
  members: number;
416
423
  /** The most reinforced member's summary, for the hover pill. */
417
424
  label: string;
418
425
  /** Community of that same member, so the mark keeps its lobe's colour. */
419
426
  community: number;
420
- /** Centroid of its members — not the cell's centre, which would grid the map. */
427
+ /** Centroid of the members. */
421
428
  x: number;
422
429
  y: number;
423
- /** The cell itself, so opening the mark asks for exactly this rectangle. */
424
- region: GraphRegion;
430
+ /** The cell, in global cell coordinates at this tile's zoom. */
431
+ cellX: number;
432
+ cellY: number;
425
433
  }
426
434
 
427
- /** A connection between two bins, weighted by the edges that cross between them. */
428
- export interface GraphViewBinEdge {
435
+ /**
436
+ * An edge from one of a tile's memories, with where its far end sits.
437
+ *
438
+ * The far end may be in a tile the client has not loaded, or folded into a
439
+ * cluster there — its position is what lets the client attach the edge to
440
+ * whichever mark currently stands for it.
441
+ */
442
+ export interface GraphTileEdge {
429
443
  source: string;
430
444
  target: string;
431
445
  weight: number;
446
+ targetX: number;
447
+ targetY: number;
432
448
  }
433
449
 
434
- export interface GraphView {
435
- /**
436
- * `flat` when every matching memory is drawn individually — the ordinary case,
437
- * and the only one below the render budget. `binned` when some marks stand for
438
- * more than one memory.
439
- *
440
- * Both populate `nodes`: a cell holding a single memory returns that memory,
441
- * not a bin of one. So the two are not alternatives to each other — a binned
442
- * view is a full-fidelity view everywhere it can afford to be.
443
- */
444
- level: 'flat' | 'binned';
445
- nodes: GraphViewNode[];
446
- edges: GraphViewEdge[];
447
- bins: GraphViewBin[];
448
- binEdges: GraphViewBinEdge[];
449
- /** The rectangle this view was scoped to, when the caller zoomed into one. */
450
- region: GraphRegion | null;
451
- /** Total nodes matching the filter before any display cap was applied. */
452
- totalNodes: number;
453
- /** True when `totalNodes` exceeded the cap and the view was trimmed. */
454
- truncated: boolean;
450
+ /** An edge out of a crowded tile, rolled up to the cell it lands in. */
451
+ export interface GraphTileCellEdge {
452
+ /** The mark in this tile it leaves from — a cluster id or a memory id. */
453
+ source: string;
454
+ targetCellX: number;
455
+ targetCellY: number;
456
+ weight: number;
457
+ }
458
+
459
+ /** One square of the map at one zoom level. */
460
+ export interface GraphTile {
461
+ z: number;
462
+ x: number;
463
+ y: number;
464
+ /** Cells per tile side when this tile was folded; 0 when it was not. */
465
+ cells: number;
466
+ nodes: GraphTileNode[];
467
+ clusters: GraphTileCluster[];
468
+ edges: GraphTileEdge[];
469
+ cellEdges: GraphTileCellEdge[];
470
+ }
471
+
472
+ export interface GraphTilesResponse {
473
+ /** The server's epoch. When it is not the one asked about, `stale` is set. */
474
+ epoch: number;
475
+ /** The map changed since the client last read the meta; nothing was served. */
476
+ stale: boolean;
477
+ tiles: GraphTile[];
455
478
  }
456
479
 
457
480
  /**
@@ -146,6 +146,7 @@ export type {
146
146
  RateLimitEvent,
147
147
  RateLimitType,
148
148
  NotificationEvent,
149
+ BackgroundWorkEvent,
149
150
  EngineOutput,
150
151
  StreamEventType,
151
152
  StreamStatus,
@@ -156,6 +156,26 @@ export interface NotificationEvent {
156
156
  message: string;
157
157
  }
158
158
 
159
+ /**
160
+ * The background work an engine is still running for this stream — commands or
161
+ * agents it started without waiting for them — as the COMPLETE current list
162
+ * (empty once everything finished).
163
+ *
164
+ * Some engines start a turn on their own when such work finishes, after the
165
+ * turn that started it already ended (Claude Code; Open Code with background
166
+ * sub-agents enabled). Others hold their completion signal until it is done
167
+ * (Qwen Code holds `result`, Copilot holds `session.idle`), and Codex, Cursor,
168
+ * Pi and Cline have no such work; those never emit this. An adapter that does
169
+ * must keep its stream — and its channel back to Clopen for tools and
170
+ * permissions — open until the list is empty and the engine is idle. The
171
+ * stream manager shows the gap between turns as "waiting for background work".
172
+ */
173
+ export interface BackgroundWorkEvent {
174
+ type: 'background_work';
175
+ sessionId: string;
176
+ tasks: Array<{ id: string; description?: string }>;
177
+ }
178
+
159
179
  // ============================================================
160
180
  // Engine Output
161
181
  // ============================================================
@@ -173,7 +193,8 @@ export type EngineOutput =
173
193
  | ResultEvent
174
194
  | SystemInitEvent
175
195
  | RateLimitEvent
176
- | NotificationEvent;
196
+ | NotificationEvent
197
+ | BackgroundWorkEvent;
177
198
 
178
199
  // ============================================================
179
200
  // Stream Transport (WebSocket layer)
@@ -196,10 +217,20 @@ export interface StreamNotification {
196
217
  message: string;
197
218
  }
198
219
 
220
+ /**
221
+ * One streamed piece of an assistant (or reasoning) block.
222
+ *
223
+ * `update` carries only `deltaText`, placed at `offset` within the block; the
224
+ * full text is sent once, on `end`. `block` changes on every `start`.
225
+ */
199
226
  export interface PartialMessageData {
200
227
  processId: string;
201
228
  eventType: 'start' | 'update' | 'end';
202
- partialText: string;
229
+ block: number;
230
+ /** Length of the block's text before `deltaText` (on `start` and `update`). */
231
+ offset?: number;
232
+ /** The block's full text — on `end` only. */
233
+ partialText?: string;
203
234
  deltaText: string;
204
235
  reasoning: boolean;
205
236
  timestamp: string;
@@ -10,7 +10,16 @@
10
10
 
11
11
  import { describe, test, expect } from 'bun:test';
12
12
 
13
- import { countLineChanges, calculateFileChangeStats, isBinaryBuffer } from './diff-calculator';
13
+ import {
14
+ countLineChanges,
15
+ countLineChangesAsync,
16
+ countLineChangesTask,
17
+ countCommon,
18
+ diffSequences,
19
+ isBinaryBuffer,
20
+ runSliced,
21
+ runToEnd
22
+ } from './diff-calculator';
14
23
 
15
24
  describe('countLineChanges', () => {
16
25
  test('counts a created file by its real lines, trailing newline and all', () => {
@@ -45,45 +54,173 @@ describe('isBinaryBuffer', () => {
45
54
  });
46
55
  });
47
56
 
48
- describe('calculateFileChangeStats', () => {
49
- test('adds up across added, modified and deleted files', () => {
50
- const before = {
51
- 'keep.ts': Buffer.from('a\nb\n'),
52
- 'gone.ts': Buffer.from('x\ny\n')
53
- };
54
- const after = {
55
- 'keep.ts': Buffer.from('a\nB\n'),
56
- 'new.ts': Buffer.from('n\n')
57
- };
58
-
59
- expect(calculateFileChangeStats(before, after)).toEqual({
60
- filesChanged: 3,
61
- insertions: 2,
62
- deletions: 3
63
- });
64
- });
65
-
66
- test('counts a binary file as changed but contributes none of its bytes as lines', () => {
67
- // A PNG split on newline bytes yields a line count with no meaning: two
68
- // screenshots once added +159 to a checkpoint whose source changes were +17.
69
- const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0x0a, 0x0a, 0x0a, 0x0a]);
70
- const before = { 'src/a.ts': Buffer.from('a\n') };
71
- const after = { 'src/a.ts': Buffer.from('b\n'), 'shot.png': png };
72
-
73
- expect(calculateFileChangeStats(before, after)).toEqual({
74
- filesChanged: 2,
75
- insertions: 1,
76
- deletions: 1
77
- });
78
- });
79
-
80
- test('counts a deleted binary the same way', () => {
81
- const png = Buffer.from([0x89, 0x50, 0x00, 0x0a, 0x0a]);
82
-
83
- expect(calculateFileChangeStats({ 'shot.png': png }, {})).toEqual({
84
- filesChanged: 1,
85
- insertions: 0,
86
- deletions: 0
87
- });
57
+ /** The textbook O(old×new) LCS table — the reference the fast count must equal. */
58
+ function referenceCounts(oldContent: string, newContent: string): { additions: number; deletions: number } {
59
+ const split = (text: string) => {
60
+ if (!text) return [];
61
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
62
+ if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();
63
+ return lines;
64
+ };
65
+ const a = split(oldContent);
66
+ const b = split(newContent);
67
+ const dp = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));
68
+ for (let i = 1; i <= a.length; i++) {
69
+ for (let j = 1; j <= b.length; j++) {
70
+ dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);
71
+ }
72
+ }
73
+ const common = dp[a.length][b.length];
74
+ return { additions: b.length - common, deletions: a.length - common };
75
+ }
76
+
77
+ /** Deterministic PRNG so a failure reproduces. */
78
+ function seeded(seed: number): () => number {
79
+ let state = seed;
80
+ return () => {
81
+ state = (state * 1103515245 + 12345) & 0x7fffffff;
82
+ return state / 0x7fffffff;
83
+ };
84
+ }
85
+
86
+ /** Replay an edit script: it must consume all of `a` and produce exactly `b`. */
87
+ function applyScript(a: string[], b: string[]): string[] {
88
+ const out: string[] = [];
89
+ let consumed = 0;
90
+ for (const op of diffSequences(a, b)) {
91
+ if (op.type === 'keep') {
92
+ expect(a[op.oldIndex]).toBe(b[op.newIndex]);
93
+ out.push(b[op.newIndex]);
94
+ consumed++;
95
+ } else if (op.type === 'insert') {
96
+ out.push(b[op.newIndex]);
97
+ } else {
98
+ consumed++;
99
+ }
100
+ }
101
+ expect(consumed).toBe(a.length);
102
+ return out;
103
+ }
104
+
105
+ describe('diffSequences', () => {
106
+ test('produces a script that turns one side into the other, minimally', () => {
107
+ const random = seeded(7);
108
+ for (let round = 0; round < 2000; round++) {
109
+ const alphabetSize = 1 + Math.floor(random() * 6);
110
+ const make = (length: number) =>
111
+ Array.from({ length }, () => String(Math.floor(random() * alphabetSize)));
112
+ const a = make(Math.floor(random() * 30));
113
+ const b = random() < 0.5 ? make(Math.floor(random() * 30)) : a.filter(() => random() > 0.3);
114
+
115
+ expect(applyScript(a, b)).toEqual(b);
116
+ const kept = diffSequences(a, b).filter((op) => op.type === 'keep').length;
117
+ const reference = referenceCounts(a.join('\n'), b.join('\n'));
118
+ expect(kept).toBe(b.length - reference.additions);
119
+ expect(countCommon(a, b)).toBe(kept);
120
+ }
121
+ });
122
+
123
+ test('puts deletions before insertions inside a changed region', () => {
124
+ expect(diffSequences(['a', 'x', 'c'], ['a', 'y', 'c']).map((op) => op.type)).toEqual([
125
+ 'keep',
126
+ 'delete',
127
+ 'insert',
128
+ 'keep'
129
+ ]);
130
+ });
131
+ });
132
+
133
+ describe('countLineChanges exactness', () => {
134
+ test('matches the full LCS table on random edits, including repeated lines', () => {
135
+ const random = seeded(42);
136
+ // A small alphabet forces repeats, which is where a shortcut would go wrong.
137
+ const alphabet = ['}', '', 'a', 'b', 'c', 'return x;', '{', 'd'];
138
+ const pick = () => alphabet[Math.floor(random() * alphabet.length)];
139
+
140
+ for (let round = 0; round < 400; round++) {
141
+ const oldLines = Array.from({ length: Math.floor(random() * 40) }, pick);
142
+ const newLines = oldLines.filter(() => random() > 0.2);
143
+ for (let i = 0; i < Math.floor(random() * 10); i++) {
144
+ newLines.splice(Math.floor(random() * (newLines.length + 1)), 0, pick());
145
+ }
146
+ const oldText = oldLines.join('\n');
147
+ const newText = newLines.join('\n');
148
+ expect(countLineChanges(oldText, newText)).toEqual(referenceCounts(oldText, newText));
149
+ }
150
+ });
151
+
152
+ test('counts a full rewrite as every line out and every line in', () => {
153
+ expect(countLineChanges('a\nb\nc\n', 'x\ny\n')).toEqual({ additions: 2, deletions: 3 });
154
+ });
155
+ });
156
+
157
+ describe('countLineChanges on large files', () => {
158
+ test('counts a small edit to a huge file without an old×new table', () => {
159
+ // The shape that froze the server: a ~47k-line generated catalog that grew
160
+ // by a few hundred lines. The old table needed ~2.3 billion cells here.
161
+ const base = Array.from({ length: 47_000 }, (_, i) => ` "key_${i}" : { "value" : "${i}" },`);
162
+ const grown = [...base];
163
+ for (let i = 0; i < 300; i++) grown.splice(i * 150, 0, ` "new_${i}" : { "value" : "n" },`);
164
+
165
+ const started = performance.now();
166
+ const counts = countLineChanges(base.join('\n'), grown.join('\n'));
167
+ const elapsed = performance.now() - started;
168
+
169
+ expect(counts).toEqual({ additions: 300, deletions: 0 });
170
+ expect(elapsed).toBeLessThan(2000);
171
+ });
172
+
173
+ test('counts a rewritten region of a large file exactly', () => {
174
+ const head = Array.from({ length: 20_000 }, (_, i) => `line ${i}`);
175
+ const oldText = [...head, ...Array.from({ length: 2_000 }, (_, i) => `old ${i}`)].join('\n');
176
+ const newText = [...head, ...Array.from({ length: 1_500 }, (_, i) => `new ${i}`)].join('\n');
177
+
178
+ expect(countLineChanges(oldText, newText)).toEqual({ additions: 1_500, deletions: 2_000 });
179
+ });
180
+ });
181
+
182
+ describe('runSliced', () => {
183
+ /** A reversed run of repeated lines: the slow shape for any exact diff. */
184
+ const reversedRepeats = (size: number) => {
185
+ const lines = Array.from({ length: size }, (_, i) => `line ${i % 40}`);
186
+ return [lines.join('\n'), [...lines].reverse().join('\n')] as const;
187
+ };
188
+
189
+ test('answers exactly what the synchronous driver answers', async () => {
190
+ const [before, after] = reversedRepeats(3_000);
191
+ expect(await runSliced(countLineChangesTask(before, after))).toEqual(
192
+ runToEnd(countLineChangesTask(before, after))
193
+ );
194
+ });
195
+
196
+ test('keeps the event loop turning while a slow diff runs', async () => {
197
+ // This is the property the server relies on: a pathological pair takes
198
+ // long, but timers (and sockets) are still served every few milliseconds.
199
+ const [before, after] = reversedRepeats(12_000);
200
+ let last = performance.now();
201
+ let longestGap = 0;
202
+ let ticks = 0;
203
+ const timer = setInterval(() => {
204
+ const now = performance.now();
205
+ longestGap = Math.max(longestGap, now - last);
206
+ last = now;
207
+ ticks++;
208
+ }, 1);
209
+
210
+ const started = performance.now();
211
+ await countLineChangesAsync(before, after);
212
+ const elapsed = performance.now() - started;
213
+ clearInterval(timer);
214
+
215
+ expect(elapsed).toBeGreaterThan(100);
216
+ expect(ticks).toBeGreaterThan(5);
217
+ expect(longestGap).toBeLessThan(100);
218
+ });
219
+
220
+ test('stops when its signal is aborted', async () => {
221
+ const [before, after] = reversedRepeats(12_000);
222
+ const controller = new AbortController();
223
+ setTimeout(() => controller.abort(new Error('no longer wanted')), 20);
224
+ await expect(countLineChangesAsync(before, after, controller.signal)).rejects.toThrow('no longer wanted');
88
225
  });
89
226
  });