@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
@@ -545,30 +545,30 @@ describe('dbClientEnv.apply and remove', () => {
545
545
  });
546
546
 
547
547
  describe('diffLines', () => {
548
- it('marks what went and what arrived', () => {
549
- expect(diffLines('A=1\nB=2', 'A=1\nB=3')).toEqual([
548
+ it('marks what went and what arrived', async () => {
549
+ expect(await diffLines('A=1\nB=2', 'A=1\nB=3')).toEqual([
550
550
  { kind: 'context', text: 'A=1' },
551
551
  { kind: 'removed', text: 'B=2' },
552
552
  { kind: 'added', text: 'B=3' }
553
553
  ]);
554
554
  });
555
555
 
556
- it('collapses a long unchanged run instead of dropping it silently', () => {
556
+ it('collapses a long unchanged run instead of dropping it silently', async () => {
557
557
  const before = Array.from({ length: 20 }, (_, i) => `K${i}=1`).join('\n');
558
558
  const after = `${before}\nNEW=1`;
559
559
 
560
- const diff = diffLines(before, after);
560
+ const diff = await diffLines(before, after);
561
561
  expect(diff.filter((line) => line.text === '…')).toHaveLength(1);
562
562
  expect(diff.at(-1)).toEqual({ kind: 'added', text: 'NEW=1' });
563
563
  });
564
564
 
565
- it('handles a file that did not exist, without a phantom blank line', () => {
566
- expect(diffLines('', 'A=1\n')).toEqual([{ kind: 'added', text: 'A=1' }]);
565
+ it('handles a file that did not exist, without a phantom blank line', async () => {
566
+ expect(await diffLines('', 'A=1\n')).toEqual([{ kind: 'added', text: 'A=1' }]);
567
567
  });
568
568
 
569
- it('answers empty when nothing changed', () => {
569
+ it('answers empty when nothing changed', async () => {
570
570
  // An ellipsis standing in for the whole file reads as "something is
571
571
  // hidden here"; the honest rendering of no change is no diff.
572
- expect(diffLines('A=1\nB=2\n', 'A=1\nB=2\n')).toEqual([]);
572
+ expect(await diffLines('A=1\nB=2\n', 'A=1\nB=2\n')).toEqual([]);
573
573
  });
574
574
  });
@@ -399,7 +399,7 @@ export const dbClientEnv = {
399
399
  updated: plan.updated,
400
400
  appended: plan.appended,
401
401
  unchanged: plan.unchanged,
402
- diff: diffLines(plan.current, plan.next),
402
+ diff: await diffLines(plan.current, plan.next),
403
403
  warnings
404
404
  };
405
405
  },
@@ -116,6 +116,13 @@ const GIT_INTERNAL_IGNORED = new Set([
116
116
 
117
117
  const GIT_DEBOUNCE_MS = 500;
118
118
 
119
+ /**
120
+ * Above this many changes in one flush, clients are told to resync instead of
121
+ * being sent the list. Every consumer of `files:changed` also handles
122
+ * `files:resync`, so the cut-off only changes the payload, not the outcome.
123
+ */
124
+ const MAX_CHANGES_PER_EVENT = 1000;
125
+
119
126
  /**
120
127
  * Delay before re-resolving a project's git directories after an event arrived
121
128
  * from one we do not know about yet. Debounced because the trigger is bursty:
@@ -776,6 +783,18 @@ class FileWatcherManager {
776
783
  projectWatcher.pendingChanges.clear();
777
784
  projectWatcher.debounceTimer = null;
778
785
 
786
+ // A burst this large (an install, a build writing its output, a checkout)
787
+ // is one resync, not a list of every path. Every client re-reads its view
788
+ // once either way; the list only added megabytes to each of them.
789
+ if (changes.length > MAX_CHANGES_PER_EVENT) {
790
+ ws.emit.project(scopeProjectId(projectId), 'files:resync', {
791
+ projectId,
792
+ timestamp: Date.now()
793
+ });
794
+ debug.log('file', `Collapsed ${changes.length} file changes into a resync for project ${projectId}`);
795
+ return;
796
+ }
797
+
779
798
  // Emit changes to users currently viewing the project
780
799
  ws.emit.project(scopeProjectId(projectId), 'files:changed', {
781
800
  projectId,
@@ -0,0 +1,35 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+
3
+ import type { GitCommit } from '$shared/types/git';
4
+ import { aggregateContributors, contributorKey } from './contributors';
5
+
6
+ const commit = (author: string, authorEmail: string, date: string): GitCommit => ({
7
+ hash: `${author}-${date}`,
8
+ hashShort: 'abc',
9
+ author,
10
+ authorEmail,
11
+ date,
12
+ message: 'm',
13
+ parents: [],
14
+ refs: []
15
+ });
16
+
17
+ describe('aggregateContributors', () => {
18
+ test('groups one person across display names by email, most commits first', () => {
19
+ const result = aggregateContributors([
20
+ commit('Arga', 'Arga@Example.com', '2026-11-03T10:00:00+07:00'),
21
+ commit('Bot', 'bot@example.com', '2026-11-02T10:00:00+07:00'),
22
+ commit('Arga Fairuz ', 'arga@example.com', '2026-11-05T10:00:00+07:00'),
23
+ commit('Bot', 'bot@example.com', '2026-11-01T10:00:00+07:00'),
24
+ commit('Arga', 'arga@example.com', '2026-11-01T10:00:00+07:00')
25
+ ]);
26
+ expect(result).toEqual([
27
+ { key: 'arga@example.com', name: 'Arga', email: 'Arga@Example.com', count: 3, lastDate: '2026-11-05T10:00:00+07:00' },
28
+ { key: 'bot@example.com', name: 'Bot', email: 'bot@example.com', count: 2, lastDate: '2026-11-02T10:00:00+07:00' }
29
+ ]);
30
+ });
31
+
32
+ test('falls back to the author name when there is no email', () => {
33
+ expect(contributorKey({ author: ' Someone ', authorEmail: '' })).toBe('someone');
34
+ });
35
+ });
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Contributors of a repository: who authored the most recent commits, how many
3
+ * each, and when they were last active.
4
+ *
5
+ * Computed here rather than in the panel. The panel used to download the last
6
+ * 500 commits in full (~166 KB on this repository) on every git change just to
7
+ * count authors; now it receives the counts, and a contributor's own commits
8
+ * only when that contributor is expanded. Both read the same window through the
9
+ * same `getLog`, so the numbers are exactly what the panel computed before.
10
+ */
11
+
12
+ import type { GitCommit } from '$shared/types/git';
13
+
14
+ /** How many recent commits the Contributors view covers. */
15
+ export const CONTRIBUTOR_WINDOW = 500;
16
+
17
+ export interface ContributorSummary {
18
+ /** Grouping key: lowercased email when present, else author name. */
19
+ key: string;
20
+ name: string;
21
+ email: string;
22
+ count: number;
23
+ /** ISO date of this contributor's most recent commit. */
24
+ lastDate: string;
25
+ }
26
+
27
+ /** The grouping key for one commit — one person may commit under several names. */
28
+ export function contributorKey(commit: Pick<GitCommit, 'author' | 'authorEmail'>): string {
29
+ return (commit.authorEmail || commit.author).toLowerCase().trim();
30
+ }
31
+
32
+ /** Group commits by author, most commits first (ties keep first-seen order). */
33
+ export function aggregateContributors(commits: GitCommit[]): ContributorSummary[] {
34
+ const map = new Map<string, ContributorSummary>();
35
+ for (const commit of commits) {
36
+ const key = contributorKey(commit);
37
+ const existing = map.get(key);
38
+ if (existing) {
39
+ existing.count++;
40
+ if (commit.date > existing.lastDate) existing.lastDate = commit.date;
41
+ } else {
42
+ map.set(key, { key, name: commit.author.trim(), email: commit.authorEmail, count: 1, lastDate: commit.date });
43
+ }
44
+ }
45
+ return [...map.values()].sort((a, b) => b.count - a.count);
46
+ }
@@ -0,0 +1,78 @@
1
+ import { afterAll, describe, expect, test } from 'bun:test';
2
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { brotliCompressSync, brotliDecompressSync, gunzipSync, gzipSync } from 'node:zlib';
6
+
7
+ import { cacheControlFor, pickEncoding, serveIndexHtml, serveStaticFile } from './static-assets';
8
+
9
+ const dir = mkdtempSync(join(tmpdir(), 'clopen-static-'));
10
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
11
+
12
+ const source = 'console.log("hello");\n'.repeat(200);
13
+ const asset = join(dir, 'main-nBOb9YOA.js');
14
+ writeFileSync(asset, source);
15
+ writeFileSync(`${asset}.br`, brotliCompressSync(source));
16
+ writeFileSync(`${asset}.gz`, gzipSync(source));
17
+ const plain = join(dir, 'favicon.svg');
18
+ writeFileSync(plain, '<svg/>');
19
+
20
+ const request = (headers: Record<string, string> = {}) => new Request('http://localhost/x', { headers });
21
+
22
+ describe('cache policy', () => {
23
+ test('content-hashed build output is immutable; everything else revalidates', () => {
24
+ expect(cacheControlFor('/assets/main-nBOb9YOA.js')).toContain('immutable');
25
+ expect(cacheControlFor('/assets/xterm-B-qIQCd3.js')).toContain('immutable');
26
+ expect(cacheControlFor('/assets/zipkit-engine-CaR0t_Uy.wasm')).toContain('immutable');
27
+ expect(cacheControlFor('/sw.js')).toBe('no-cache');
28
+ expect(cacheControlFor('/index.html')).toBe('no-cache');
29
+ expect(cacheControlFor('/favicon.svg')).toBe('no-cache');
30
+ });
31
+ });
32
+
33
+ describe('encoding negotiation', () => {
34
+ const both = new Set(['br', 'gzip'] as const);
35
+ test('prefers brotli, falls back to gzip, honours q=0', () => {
36
+ expect(pickEncoding('gzip, deflate, br', both)).toBe('br');
37
+ expect(pickEncoding('gzip', both)).toBe('gzip');
38
+ expect(pickEncoding('br;q=0, gzip', both)).toBe('gzip');
39
+ expect(pickEncoding('identity', both)).toBeNull();
40
+ expect(pickEncoding(null, both)).toBeNull();
41
+ });
42
+ });
43
+
44
+ describe('serveStaticFile', () => {
45
+ test('sends the brotli copy with the original type, and decodes to the original', async () => {
46
+ const res = serveStaticFile(request({ 'accept-encoding': 'br, gzip' }), '/assets/main-nBOb9YOA.js', asset);
47
+ expect(res.headers.get('content-encoding')).toBe('br');
48
+ expect(res.headers.get('content-type')).toContain('javascript');
49
+ expect(res.headers.get('vary')).toBe('Accept-Encoding');
50
+ expect(res.headers.get('cache-control')).toContain('immutable');
51
+ expect(brotliDecompressSync(Buffer.from(await res.arrayBuffer())).toString()).toBe(source);
52
+ });
53
+
54
+ test('sends gzip to a client without brotli, and the raw file to one without either', async () => {
55
+ const gz = serveStaticFile(request({ 'accept-encoding': 'gzip' }), '/assets/main-nBOb9YOA.js', asset);
56
+ expect(gunzipSync(Buffer.from(await gz.arrayBuffer())).toString()).toBe(source);
57
+ const raw = serveStaticFile(request(), '/assets/main-nBOb9YOA.js', asset);
58
+ expect(raw.headers.get('content-encoding')).toBeNull();
59
+ expect(await raw.text()).toBe(source);
60
+ });
61
+
62
+ test('answers 304 when the browser already holds this version', () => {
63
+ const first = serveStaticFile(request(), '/favicon.svg', plain);
64
+ const etag = first.headers.get('etag')!;
65
+ const again = serveStaticFile(request({ 'if-none-match': etag }), '/favicon.svg', plain);
66
+ expect(again.status).toBe(304);
67
+ expect(again.headers.get('cache-control')).toBe('no-cache');
68
+ });
69
+ });
70
+
71
+ describe('serveIndexHtml', () => {
72
+ test('is always revalidated and answers 304 for the current version', () => {
73
+ const fresh = serveIndexHtml(request(), '<html></html>', 'W/"1"');
74
+ expect(fresh.headers.get('cache-control')).toBe('no-cache');
75
+ expect(serveIndexHtml(request({ 'if-none-match': 'W/"1"' }), '<html></html>', 'W/"1"').status).toBe(304);
76
+ expect(serveIndexHtml(request({ 'if-none-match': 'W/"0"' }), '<html></html>', 'W/"1"').status).toBe(200);
77
+ });
78
+ });
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Serving the built frontend (`dist/`) in production.
3
+ *
4
+ * It used to go out with no caching headers and no compression, so a browser
5
+ * had nothing to revalidate against and every page load — a refresh, a new tab,
6
+ * reopening the app on a phone — downloaded the whole bundle again: ~8 MB,
7
+ * ~1.6 MB of it after brotli.
8
+ *
9
+ * - Content-hashed build output (`/assets/name-<hash>.ext`) never changes under
10
+ * its name, so it is cached for a year as immutable.
11
+ * - Everything else (`index.html`, `sw.js`, the manifest, fonts, sounds) is
12
+ * revalidated on every use with an ETag, so an update is picked up at once
13
+ * and an unchanged file costs a 304. A new release's `index.html` names new
14
+ * hashed assets; the old ones simply stop being requested.
15
+ * - Brotli or gzip copies written at build time (scripts/vite-precompress.ts)
16
+ * are sent when the browser accepts them — no compression at request time.
17
+ */
18
+
19
+ import { statSync } from 'node:fs';
20
+
21
+ /** Build output named by its content hash, e.g. `main-nBOb9YOA.js`. */
22
+ const HASHED_ASSET = /^\/assets\/.+-[A-Za-z0-9_-]{8,}\.[a-z0-9]+$/;
23
+
24
+ const IMMUTABLE = 'public, max-age=31536000, immutable';
25
+ const REVALIDATE = 'no-cache';
26
+
27
+ type Encoding = 'br' | 'gzip';
28
+ const SUFFIX: Record<Encoding, string> = { br: '.br', gzip: '.gz' };
29
+
30
+ /** Which precompressed siblings exist — the build output does not change while running. */
31
+ const siblings = new Map<string, Set<Encoding>>();
32
+
33
+ function availableEncodings(filePath: string): Set<Encoding> {
34
+ let found = siblings.get(filePath);
35
+ if (!found) {
36
+ found = new Set();
37
+ for (const encoding of ['br', 'gzip'] as const) {
38
+ try {
39
+ if (statSync(filePath + SUFFIX[encoding]).isFile()) found.add(encoding);
40
+ } catch {
41
+ // No such copy.
42
+ }
43
+ }
44
+ siblings.set(filePath, found);
45
+ }
46
+ return found;
47
+ }
48
+
49
+ /** The best encoding both sides support: brotli, then gzip, else none. */
50
+ export function pickEncoding(acceptEncoding: string | null, available: Set<Encoding>): Encoding | null {
51
+ if (!acceptEncoding) return null;
52
+ const accepted = new Set(
53
+ acceptEncoding
54
+ .split(',')
55
+ .map((part) => part.trim())
56
+ .filter((part) => !/;\s*q=0(\.0+)?$/.test(part))
57
+ .map((part) => part.split(';')[0].trim().toLowerCase())
58
+ );
59
+ if (available.has('br') && accepted.has('br')) return 'br';
60
+ if (available.has('gzip') && (accepted.has('gzip') || accepted.has('*'))) return 'gzip';
61
+ return null;
62
+ }
63
+
64
+ /** Cache policy for a request path. */
65
+ export function cacheControlFor(urlPath: string): string {
66
+ return HASHED_ASSET.test(urlPath) ? IMMUTABLE : REVALIDATE;
67
+ }
68
+
69
+ /**
70
+ * A response for a file under `dist/`, or a 304 when the browser's copy is
71
+ * current. `filePath` must already be resolved and confined to `dist/`.
72
+ */
73
+ export function serveStaticFile(request: Request, urlPath: string, filePath: string): Response {
74
+ const stats = statSync(filePath);
75
+ const etag = `W/"${stats.size.toString(36)}-${Math.floor(stats.mtimeMs).toString(36)}"`;
76
+ const headers: Record<string, string> = {
77
+ 'Cache-Control': cacheControlFor(urlPath),
78
+ ETag: etag,
79
+ Vary: 'Accept-Encoding'
80
+ };
81
+
82
+ if (request.headers.get('if-none-match') === etag) {
83
+ return new Response(null, { status: 304, headers });
84
+ }
85
+
86
+ const original = Bun.file(filePath);
87
+ headers['Content-Type'] = original.type || 'application/octet-stream';
88
+
89
+ const encoding = pickEncoding(request.headers.get('accept-encoding'), availableEncodings(filePath));
90
+ if (encoding) {
91
+ headers['Content-Encoding'] = encoding;
92
+ return new Response(Bun.file(filePath + SUFFIX[encoding]), { headers });
93
+ }
94
+ return new Response(original, { headers });
95
+ }
96
+
97
+ /** The SPA shell (`index.html`), always revalidated so a release is picked up at once. */
98
+ export function serveIndexHtml(request: Request, html: string, etag: string): Response {
99
+ const headers = { 'Cache-Control': REVALIDATE, ETag: etag, 'Content-Type': 'text/html; charset=utf-8' };
100
+ if (request.headers.get('if-none-match') === etag) {
101
+ return new Response(null, { status: 304, headers });
102
+ }
103
+ return new Response(html, { headers });
104
+ }
package/backend/index.ts CHANGED
@@ -98,6 +98,8 @@ import { ws as wsServer } from './utils/ws';
98
98
  import { messageRateLimiter } from './ws/message-rate-limiter';
99
99
  import { flushEpisodicIngest, stopExtractionRunner } from './memory/extract';
100
100
  import { stopMemoryMaintenance } from './memory/maintenance';
101
+ import { WS_SERVER_OPTIONS } from './utils/ws-wire';
102
+ import { serveIndexHtml, serveStaticFile } from './http/static-assets';
101
103
 
102
104
  /** How often (ms) the auth gate re-confirms a connection's session against the DB. */
103
105
  const SESSION_REVALIDATE_MS = 15_000;
@@ -161,7 +163,10 @@ const PORT = SERVER_ENV.PORT;
161
163
  const HOST = SERVER_ENV.HOST;
162
164
 
163
165
  // Create Elysia app
164
- const app = new Elysia()
166
+ // Socket options must be given at the app level: Elysia only passes the
167
+ // server-wide `websocket` config to Bun.serve and silently ignores the same
168
+ // keys on a `.ws()` route (see WS_SERVER_OPTIONS).
169
+ const app = new Elysia({ websocket: WS_SERVER_OPTIONS })
165
170
  // Apply middleware
166
171
  .use(corsMiddleware)
167
172
  .use(securityMiddleware)
@@ -260,27 +265,24 @@ if (!isDevelopment) {
260
265
  // an actual file before serving avoids this issue.
261
266
  const distDir = resolve(process.cwd(), 'dist');
262
267
  const indexHtml = await Bun.file(resolve(distDir, 'index.html')).text();
268
+ const indexEtag = `W/"${Bun.hash(indexHtml).toString(36)}"`;
263
269
 
264
- app.all('/*', ({ path }) => {
270
+ // Caching and compression are decided in backend/http/static-assets.ts.
271
+ app.all('/*', ({ path, request }) => {
265
272
  // Serve static files from dist/
266
273
  if (path !== '/' && !path.includes('..')) {
267
274
  const filePath = resolve(distDir, path.slice(1));
268
275
  if (filePath.startsWith(distDir)) {
269
276
  try {
270
277
  if (statSync(filePath).isFile()) {
271
- const file = Bun.file(filePath);
272
- return new Response(file, {
273
- headers: { 'Content-Type': file.type || 'application/octet-stream' }
274
- });
278
+ return serveStaticFile(request, path, filePath);
275
279
  }
276
280
  } catch {}
277
281
  }
278
282
  }
279
283
 
280
284
  // SPA fallback: serve cached index.html
281
- return new Response(indexHtml, {
282
- headers: { 'Content-Type': 'text/html; charset=utf-8' }
283
- });
285
+ return serveIndexHtml(request, indexHtml, indexEtag);
284
286
  });
285
287
  }
286
288
 
@@ -16,6 +16,7 @@ import { ws } from '$backend/utils/ws';
16
16
  import { defaultRotation, type DeviceRequest } from '$shared/constants/preview.js';
17
17
  import { applyViewport, type EmulationPatch } from './viewport';
18
18
  import { debug } from '$shared/utils/logger';
19
+ import { emitToPreviewWatchers, forgetAgentCursor, rememberAgentCursor } from '../../ws/preview/watchers';
19
20
  import { sleep } from '$shared/utils/async';
20
21
  import { scopeProjectId } from '$shared/utils/workspace-scope';
21
22
  import type {
@@ -1786,12 +1787,15 @@ class BrowserPreviewServiceManager {
1786
1787
  });
1787
1788
 
1788
1789
  // Forward console events
1790
+ // Console lines are a panel's live detail, as frequent as the page is
1791
+ // chatty: only connections with a Preview open receive them. A panel that
1792
+ // opens later seeds itself from the console history.
1789
1793
  service.on('preview:browser-console-message', (data) => {
1790
- ws.emit.project(roomId, 'preview:browser-console-message', data);
1794
+ emitToPreviewWatchers(roomId, 'preview:browser-console-message', data);
1791
1795
  });
1792
1796
 
1793
1797
  service.on('preview:browser-console-clear', (data) => {
1794
- ws.emit.project(roomId, 'preview:browser-console-clear', data);
1798
+ emitToPreviewWatchers(roomId, 'preview:browser-console-clear', data);
1795
1799
  });
1796
1800
 
1797
1801
  // Forward dialog events
@@ -1910,6 +1914,7 @@ class BrowserPreviewServiceManager {
1910
1914
  // No longer pinned: an unwatched tab the agent has let go of is free
1911
1915
  // to fall asleep on the usual timer.
1912
1916
  this.services.get(data.projectId)?.noteTabActivity(data.browserTabId);
1917
+ forgetAgentCursor(data.projectId, data.browserTabId);
1913
1918
  ws.emit.project(data.projectId, 'preview:browser-mcp-control-end', {
1914
1919
  browserTabId: data.browserTabId,
1915
1920
  projectId: data.projectId,
@@ -1926,21 +1931,34 @@ class BrowserPreviewServiceManager {
1926
1931
  });
1927
1932
  });
1928
1933
 
1934
+ // The agent's cursor moves many times a second while it works and is only
1935
+ // drawn inside a Preview, so its steps go to connections with one open;
1936
+ // where it came to rest is remembered for a Preview that opens later.
1929
1937
  browserMcpControl.on('cursor-position', (data) => {
1930
1938
  if (!data.projectId) return;
1931
- ws.emit.project(data.projectId, 'preview:browser-mcp-cursor-position', {
1939
+ const cursor = {
1932
1940
  sessionId: data.tabId,
1933
1941
  x: data.x,
1934
1942
  y: data.y,
1935
1943
  pressed: data.pressed ?? false,
1936
1944
  timestamp: data.timestamp,
1937
1945
  source: 'mcp' as const
1938
- });
1946
+ };
1947
+ rememberAgentCursor(data.projectId, cursor);
1948
+ emitToPreviewWatchers(data.projectId, 'preview:browser-mcp-cursor-position', cursor);
1939
1949
  });
1940
1950
 
1941
1951
  browserMcpControl.on('cursor-glide', (data) => {
1942
1952
  if (!data.projectId) return;
1943
- ws.emit.project(data.projectId, 'preview:browser-mcp-cursor-glide', {
1953
+ rememberAgentCursor(data.projectId, {
1954
+ sessionId: data.tabId,
1955
+ x: data.to.x,
1956
+ y: data.to.y,
1957
+ pressed: data.pressed ?? false,
1958
+ timestamp: data.timestamp,
1959
+ source: 'mcp' as const
1960
+ });
1961
+ emitToPreviewWatchers(data.projectId, 'preview:browser-mcp-cursor-glide', {
1944
1962
  sessionId: data.tabId,
1945
1963
  from: data.from,
1946
1964
  control: data.control,
@@ -1955,7 +1973,7 @@ class BrowserPreviewServiceManager {
1955
1973
 
1956
1974
  browserMcpControl.on('cursor-click', (data) => {
1957
1975
  if (!data.projectId) return;
1958
- ws.emit.project(data.projectId, 'preview:browser-mcp-cursor-click', {
1976
+ emitToPreviewWatchers(data.projectId, 'preview:browser-mcp-cursor-click', {
1959
1977
  sessionId: data.tabId,
1960
1978
  x: data.x,
1961
1979
  y: data.y,
@@ -14,6 +14,7 @@ import fs from 'fs/promises';
14
14
  import { gzipSync, gunzipSync } from 'zlib';
15
15
  import { debug } from '$shared/utils/logger';
16
16
  import { getClopenDir } from '../utils/index.js';
17
+ import { blobLineStatsQueries } from '../database/queries/blob-line-stats-queries';
17
18
 
18
19
  const SNAPSHOTS_DIR = join(getClopenDir(), 'snapshots');
19
20
  const BLOBS_DIR = join(SNAPSHOTS_DIR, 'blobs');
@@ -156,7 +157,8 @@ class BlobStore {
156
157
 
157
158
  /**
158
159
  * Delete multiple blobs by hash.
159
- * Also invalidates fileHashCache entries whose hash matches a deleted blob.
160
+ * Also invalidates fileHashCache entries whose hash matches a deleted blob,
161
+ * and the cached line counts of every pair that names one.
160
162
  */
161
163
  async deleteBlobs(hashes: string[]): Promise<number> {
162
164
  const hashSet = new Set(hashes);
@@ -177,6 +179,12 @@ class BlobStore {
177
179
  }
178
180
  }
179
181
 
182
+ try {
183
+ blobLineStatsQueries.deleteByHashes(hashes);
184
+ } catch (error) {
185
+ debug.warn('snapshot', 'Failed to prune cached line stats:', error);
186
+ }
187
+
180
188
  return deleted;
181
189
  }
182
190
 
@@ -3,6 +3,7 @@ import { blobStore } from './blob-store';
3
3
  import { debug } from '$shared/utils/logger';
4
4
  import { loadMessage } from '$shared/utils/message-formatter';
5
5
  import { buildTurnFiles, summariseTurnFiles } from './turn-changes';
6
+ import { blobLineStats } from './line-stats';
6
7
  import type { DatabaseMessage, SessionScopedChanges } from '$shared/types/database/schema';
7
8
  import type { UnifiedMessage, UserMessage } from '$shared/types/unified';
8
9
 
@@ -348,16 +349,8 @@ export async function getCheckpointFileStats(
348
349
  const changes = JSON.parse(snapshot.session_changes as string) as SessionScopedChanges;
349
350
  if (Object.keys(changes).length === 0) return stored;
350
351
 
351
- let blobMissing = false;
352
- const files = await buildTurnFiles(changes, async (hash) => {
353
- try {
354
- return await blobStore.readBlob(hash);
355
- } catch (err) {
356
- blobMissing = true;
357
- throw err;
358
- }
359
- });
360
- return blobMissing ? stored : summariseTurnFiles(files);
352
+ const files = await buildTurnFiles(changes, blobLineStats);
353
+ return files.some((file) => !file.contentAvailable) ? stored : summariseTurnFiles(files);
361
354
  } catch {
362
355
  return stored;
363
356
  }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Counting each pair of blobs once.
3
+ *
4
+ * A chat open used to re-diff every changed file of every turn, and a single
5
+ * large file made that block the server for minutes. The pair's count is a
6
+ * fact about two content hashes, so it is computed on first use and read back
7
+ * from then on — and dropped when the blobs it describes are deleted.
8
+ */
9
+
10
+ import { describe, it, expect, beforeAll } from 'bun:test';
11
+ import { randomUUID } from 'node:crypto';
12
+
13
+ import { initializeDatabase } from '../database';
14
+ import { blobLineStatsQueries } from '../database/queries/blob-line-stats-queries';
15
+ import { blobStore } from './blob-store';
16
+ import { blobLineStats } from './line-stats';
17
+
18
+ /** Fresh content per test, so its hashes are not shared with any other run. */
19
+ async function storePair(oldText: string, newText: string) {
20
+ const salt = randomUUID();
21
+ const oldHash = await blobStore.storeBlob(Buffer.from(`${salt}\n${oldText}`, 'utf8'));
22
+ const newHash = await blobStore.storeBlob(Buffer.from(`${salt}\n${newText}`, 'utf8'));
23
+ return { oldHash, newHash };
24
+ }
25
+
26
+ beforeAll(async () => {
27
+ await initializeDatabase();
28
+ });
29
+
30
+ describe('blobLineStats', () => {
31
+ it('counts a pair on first use and remembers it', async () => {
32
+ const { oldHash, newHash } = await storePair('a\nb\nc\n', 'a\nB\nc\nd\n');
33
+
34
+ expect(blobLineStatsQueries.get(oldHash, newHash)).toBeNull();
35
+
36
+ const first = await blobLineStats(oldHash, newHash);
37
+ expect(first).toEqual({ insertions: 2, deletions: 1, isBinary: false, contentAvailable: true });
38
+ expect(blobLineStatsQueries.get(oldHash, newHash)).toEqual({ insertions: 2, deletions: 1, isBinary: false });
39
+
40
+ expect(await blobLineStats(oldHash, newHash)).toEqual(first);
41
+ });
42
+
43
+ it('counts a created file against an empty side', async () => {
44
+ const { newHash } = await storePair('', 'one\ntwo\n');
45
+
46
+ // The salt line makes it three.
47
+ expect(await blobLineStats('', newHash)).toEqual({
48
+ insertions: 3,
49
+ deletions: 0,
50
+ isBinary: false,
51
+ contentAvailable: true
52
+ });
53
+ });
54
+
55
+ it('shares one computation between concurrent callers', async () => {
56
+ const { oldHash, newHash } = await storePair('x\n', 'y\n');
57
+
58
+ const [a, b] = await Promise.all([blobLineStats(oldHash, newHash), blobLineStats(oldHash, newHash)]);
59
+ expect(a).toBe(b);
60
+ });
61
+
62
+ it('never stores a pair whose blob is missing', async () => {
63
+ const { newHash } = await storePair('', 'x\n');
64
+ const missing = 'f'.repeat(64);
65
+
66
+ const stats = await blobLineStats(missing, newHash);
67
+ expect(stats.contentAvailable).toBe(false);
68
+ expect(blobLineStatsQueries.get(missing, newHash)).toBeNull();
69
+ });
70
+
71
+ it('drops the remembered count when its blobs are deleted', async () => {
72
+ const { oldHash, newHash } = await storePair('a\n', 'b\n');
73
+ await blobLineStats(oldHash, newHash);
74
+
75
+ await blobStore.deleteBlobs([oldHash, newHash]);
76
+
77
+ expect(blobLineStatsQueries.get(oldHash, newHash)).toBeNull();
78
+ expect((await blobLineStats(oldHash, newHash)).contentAvailable).toBe(false);
79
+ });
80
+ });