@myrialabs/clopen 0.4.48 → 0.4.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/backend/chat/background-wait.test.ts +28 -0
  2. package/backend/chat/message-pages.test.ts +180 -0
  3. package/backend/chat/message-pages.ts +237 -0
  4. package/backend/chat/stream-manager.ts +101 -18
  5. package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
  6. package/backend/database/migrations/088_create_messages_fts_map.ts +52 -0
  7. package/backend/database/migrations/089_add_memory_layout_tiles.ts +58 -0
  8. package/backend/database/migrations/index.ts +21 -0
  9. package/backend/database/queries/blob-line-stats-queries.ts +48 -0
  10. package/backend/database/queries/graph-queries.ts +392 -135
  11. package/backend/database/queries/index.ts +2 -0
  12. package/backend/database/queries/message-fts.test.ts +120 -0
  13. package/backend/database/queries/message-queries.ts +45 -9
  14. package/backend/database/queries/session-queries.ts +3 -2
  15. package/backend/database/queries/utils-queries.ts +3 -0
  16. package/backend/db-client/env/diff.ts +9 -33
  17. package/backend/db-client/env/env.test.ts +8 -8
  18. package/backend/db-client/env/service.ts +1 -1
  19. package/backend/engine/adapters/claude/environment.ts +4 -0
  20. package/backend/engine/adapters/claude/input-gate.test.ts +59 -0
  21. package/backend/engine/adapters/claude/input-gate.ts +74 -0
  22. package/backend/engine/adapters/claude/message-converter.test.ts +16 -0
  23. package/backend/engine/adapters/claude/message-converter.ts +8 -0
  24. package/backend/engine/adapters/claude/stream.ts +15 -0
  25. package/backend/files/file-watcher.ts +19 -0
  26. package/backend/git/contributors.test.ts +35 -0
  27. package/backend/git/contributors.ts +46 -0
  28. package/backend/git/identity/scope-config.test.ts +7 -4
  29. package/backend/http/static-assets.test.ts +78 -0
  30. package/backend/http/static-assets.ts +104 -0
  31. package/backend/index.ts +46 -17
  32. package/backend/memory/README.md +7 -4
  33. package/backend/memory/layout.test.ts +377 -0
  34. package/backend/memory/layout.ts +1029 -265
  35. package/backend/memory/view.ts +257 -386
  36. package/backend/preview/browser/browser-preview-service.ts +24 -6
  37. package/backend/project/status-manager.ts +4 -2
  38. package/backend/snapshot/blob-store.ts +9 -1
  39. package/backend/snapshot/helpers.ts +3 -10
  40. package/backend/snapshot/line-stats.test.ts +80 -0
  41. package/backend/snapshot/line-stats.ts +64 -0
  42. package/backend/snapshot/snapshot-service.ts +14 -27
  43. package/backend/snapshot/turn-changes.test.ts +10 -5
  44. package/backend/snapshot/turn-changes.ts +78 -40
  45. package/backend/terminal/ptykit.ts +6 -1
  46. package/backend/utils/ws-wire.test.ts +87 -0
  47. package/backend/utils/ws-wire.ts +189 -0
  48. package/backend/utils/ws.ts +40 -38
  49. package/backend/ws/chat/stream.ts +60 -20
  50. package/backend/ws/files/read.ts +30 -0
  51. package/backend/ws/git/log.ts +52 -0
  52. package/backend/ws/memory/crud.ts +118 -81
  53. package/backend/ws/messages/crud.ts +51 -0
  54. package/backend/ws/preview/index.ts +2 -0
  55. package/backend/ws/preview/watchers.ts +84 -0
  56. package/backend/ws/sessions/crud.ts +8 -12
  57. package/backend/ws/snapshot/changes.ts +5 -6
  58. package/backend/ws/terminal/tunnel.ts +2 -2
  59. package/bin/clopen.ts +37 -30
  60. package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
  61. package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
  62. package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
  63. package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
  64. package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
  65. package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
  66. package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
  67. package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
  68. package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
  69. package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
  70. package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
  71. package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
  72. package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
  73. package/dist/assets/{index-DJzwt-hq.js → index-By6KdSLT.js} +1 -1
  74. package/dist/assets/index-By6KdSLT.js.br +0 -0
  75. package/dist/assets/index-By6KdSLT.js.gz +0 -0
  76. package/dist/assets/{index-CONlwAXZ.js → index-DV4TiDn1.js} +1 -1
  77. package/dist/assets/index-DV4TiDn1.js.br +0 -0
  78. package/dist/assets/index-DV4TiDn1.js.gz +0 -0
  79. package/dist/assets/main-DIESTGTD.css +1 -0
  80. package/dist/assets/main-DIESTGTD.css.br +0 -0
  81. package/dist/assets/main-DIESTGTD.css.gz +0 -0
  82. package/dist/assets/{main-nBOb9YOA.js → main-Da3JKoua.js} +623 -623
  83. package/dist/assets/main-Da3JKoua.js.br +0 -0
  84. package/dist/assets/main-Da3JKoua.js.gz +0 -0
  85. package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
  86. package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
  87. package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
  88. package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
  89. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
  90. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
  91. package/dist/fonts/dm-sans.css.br +0 -0
  92. package/dist/fonts/dm-sans.css.gz +0 -0
  93. package/dist/index.html +2 -2
  94. package/dist/index.html.br +0 -0
  95. package/dist/index.html.gz +0 -0
  96. package/dist/sw.js.br +0 -0
  97. package/dist/sw.js.gz +0 -0
  98. package/package.json +3 -4
  99. package/shared/types/memory.ts +96 -73
  100. package/shared/types/unified/index.ts +1 -0
  101. package/shared/types/unified/stream.ts +33 -2
  102. package/shared/utils/diff-calculator.test.ts +178 -41
  103. package/shared/utils/diff-calculator.ts +383 -100
  104. package/shared/utils/process-supervisor.test.ts +242 -0
  105. package/shared/utils/process-supervisor.ts +356 -0
  106. package/shared/utils/process-tree.ts +99 -0
  107. package/shared/utils/ws-chunk.test.ts +33 -0
  108. package/shared/utils/ws-chunk.ts +73 -0
  109. package/shared/utils/ws-client-chunks.test.ts +45 -0
  110. package/shared/utils/ws-client.ts +43 -0
  111. package/shared/utils/ws-server.ts +17 -14
  112. package/backend/database/migrations/086_single_owner.test.ts +0 -170
  113. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +0 -1
  114. package/dist/assets/main-BUiUL3eZ.css +0 -1
@@ -0,0 +1,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
+ }
@@ -42,12 +42,15 @@ async function writeGenerated(pairs: Array<[string, string]>): Promise<string> {
42
42
  }
43
43
 
44
44
  async function gitConfig(key: string, configPath: string, cwd: string): Promise<string> {
45
+ // GIT_CONFIG_COUNT/KEY_n/VALUE_n outrank every config file. A shell Clopen
46
+ // started carries the user's identity in them, which would answer instead
47
+ // of the file under test.
48
+ const env = Object.fromEntries(
49
+ Object.entries(process.env).filter(([name]) => !/^GIT_CONFIG_(COUNT|KEY_\d+|VALUE_\d+)$/.test(name))
50
+ );
45
51
  const proc = Bun.spawn(['git', 'config', '--get', key], {
46
52
  cwd,
47
- env: { ...process.env, GIT_CONFIG_GLOBAL: configPath, GIT_CONFIG_SYSTEM: '/dev/null' } as Record<
48
- string,
49
- string
50
- >,
53
+ env: { ...env, GIT_CONFIG_GLOBAL: configPath, GIT_CONFIG_SYSTEM: '/dev/null' } as Record<string, string>,
51
54
  stdout: 'pipe',
52
55
  stderr: 'pipe'
53
56
  });
@@ -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
@@ -33,6 +33,10 @@ import { runGitHelper } from './git/identity/cli';
33
33
  }
34
34
 
35
35
  import { Elysia } from 'elysia';
36
+ import { watchSupervisor } from '$shared/utils/process-supervisor';
37
+ import { collectDescendants, signalAll } from '$shared/utils/process-tree';
38
+ import { ptyKitManager } from './terminal/ptykit';
39
+ import { tunnelKit } from './tunnel/tunnel-config';
36
40
  import { corsMiddleware } from './middleware/cors';
37
41
  import { errorHandlerMiddleware } from './middleware/error-handler';
38
42
  import { loggerMiddleware } from './middleware/logger';
@@ -98,6 +102,8 @@ import { ws as wsServer } from './utils/ws';
98
102
  import { messageRateLimiter } from './ws/message-rate-limiter';
99
103
  import { flushEpisodicIngest, stopExtractionRunner } from './memory/extract';
100
104
  import { stopMemoryMaintenance } from './memory/maintenance';
105
+ import { WS_SERVER_OPTIONS } from './utils/ws-wire';
106
+ import { serveIndexHtml, serveStaticFile } from './http/static-assets';
101
107
 
102
108
  /** How often (ms) the auth gate re-confirms a connection's session against the DB. */
103
109
  const SESSION_REVALIDATE_MS = 15_000;
@@ -161,7 +167,10 @@ const PORT = SERVER_ENV.PORT;
161
167
  const HOST = SERVER_ENV.HOST;
162
168
 
163
169
  // Create Elysia app
164
- const app = new Elysia()
170
+ // Socket options must be given at the app level: Elysia only passes the
171
+ // server-wide `websocket` config to Bun.serve and silently ignores the same
172
+ // keys on a `.ws()` route (see WS_SERVER_OPTIONS).
173
+ const app = new Elysia({ websocket: WS_SERVER_OPTIONS })
165
174
  // Apply middleware
166
175
  .use(corsMiddleware)
167
176
  .use(securityMiddleware)
@@ -260,27 +269,24 @@ if (!isDevelopment) {
260
269
  // an actual file before serving avoids this issue.
261
270
  const distDir = resolve(process.cwd(), 'dist');
262
271
  const indexHtml = await Bun.file(resolve(distDir, 'index.html')).text();
272
+ const indexEtag = `W/"${Bun.hash(indexHtml).toString(36)}"`;
263
273
 
264
- app.all('/*', ({ path }) => {
274
+ // Caching and compression are decided in backend/http/static-assets.ts.
275
+ app.all('/*', ({ path, request }) => {
265
276
  // Serve static files from dist/
266
277
  if (path !== '/' && !path.includes('..')) {
267
278
  const filePath = resolve(distDir, path.slice(1));
268
279
  if (filePath.startsWith(distDir)) {
269
280
  try {
270
281
  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
- });
282
+ return serveStaticFile(request, path, filePath);
275
283
  }
276
284
  } catch {}
277
285
  }
278
286
  }
279
287
 
280
288
  // SPA fallback: serve cached index.html
281
- return new Response(indexHtml, {
282
- headers: { 'Content-Type': 'text/html; charset=utf-8' }
283
- });
289
+ return serveIndexHtml(request, indexHtml, indexEtag);
284
290
  });
285
291
  }
286
292
 
@@ -365,6 +371,14 @@ async function startServer() {
365
371
  });
366
372
  }
367
373
 
374
+ // Supervised (bin/clopen.ts, scripts/dev.ts): if the supervisor disappears
375
+ // without stopping us, stop anyway rather than keep the port unowned. Read
376
+ // before startServer spawns anything that would inherit the variable.
377
+ watchSupervisor(() => {
378
+ debug.warn('server', 'Supervisor is gone — shutting down');
379
+ void gracefulShutdown();
380
+ });
381
+
368
382
  startServer().catch((error) => {
369
383
  console.error('❌ Failed to start server:', error);
370
384
  process.exit(1);
@@ -377,12 +391,15 @@ async function gracefulShutdown() {
377
391
  if (isShuttingDown) return;
378
392
  isShuttingDown = true;
379
393
 
380
- // Force exit after 5 seconds — prevents port from being held by slow cleanup
381
- // during bun --watch restarts, which causes ECONNREFUSED on the Vite WS proxy.
394
+ // The port is released first thing (app.stop below), so the rest takes the
395
+ // time it actually needs. This only bounds a step that hangs: whatever this
396
+ // process started is then killed with it — the preview's Chrome sits in a
397
+ // process group of its own and would otherwise outlive us.
382
398
  const forceExitTimer = setTimeout(() => {
383
- debug.warn('server', '⚠️ Shutdown timeout — forcing exit to release port');
399
+ debug.warn('server', '⚠️ Shutdown timeout — forcing exit');
400
+ signalAll(collectDescendants(process.pid), 'SIGKILL');
384
401
  process.exit(1);
385
- }, 5_000);
402
+ }, 12_000);
386
403
 
387
404
  console.log('\n🛑 Shutting down server...');
388
405
  try {
@@ -402,6 +419,12 @@ async function gracefulShutdown() {
402
419
  // transport so their remote sessions and bound ports are released now.
403
420
  await sshForwardManager.stopAll();
404
421
  sshClientPool.closeAll();
422
+ // Terminal tabs: each session's shell and everything started from it
423
+ // (a dev server, a background job) ends with the server.
424
+ ptyKitManager.dispose();
425
+ // Tunnels: cloudflared drains before it exits; wait for it so nothing is
426
+ // left serving this server's public URL.
427
+ await tunnelKit.stopAll();
405
428
  // Dispose rate limiter timer
406
429
  authRateLimiter.dispose();
407
430
  // Dispose expired session cleanup timer
@@ -443,11 +466,17 @@ async function gracefulShutdown() {
443
466
  process.on('SIGINT', gracefulShutdown);
444
467
  process.on('SIGTERM', gracefulShutdown);
445
468
 
446
- // Ignore SIGHUP — sent when the controlling terminal closes or an SSH session
447
- // disconnects. Without a handler Bun exits immediately; we want the server to
448
- // keep running (e.g. started in a background tab or remote shell).
469
+ // SIGHUP: the controlling terminal or SSH session closed. Started in a
470
+ // terminal, the server goes with it, like any program run there. Without one
471
+ // on stdout — supervised (the supervisor decides), `nohup`, a service — it
472
+ // keeps running. Without a handler Bun would exit abruptly instead.
473
+ const startedInTerminal = process.stdout.isTTY === true;
449
474
  process.on('SIGHUP', () => {
450
- debug.log('server', 'Received SIGHUP — ignoring (server stays running)');
475
+ if (startedInTerminal) {
476
+ void gracefulShutdown();
477
+ return;
478
+ }
479
+ debug.log('server', 'Received SIGHUP — no terminal attached, server stays running');
451
480
  });
452
481
 
453
482
  // Safety net: prevent server crash from unhandled promise rejections.
@@ -308,7 +308,8 @@ graph_node_entities subjects a memory is about (an ATTRIBUTE, not nodes)
308
308
  graph_node_paths files a memory is about (likewise)
309
309
  graph_vectors one int8 vector per node, 260 bytes at 256 dims
310
310
  graph_nodes_fts FTS5 mirror for BM25
311
- graph_layout persisted positions and communities (migration 067)
311
+ graph_layout persisted positions, communities and degree (067, 089)
312
+ graph_layout_edges derived edges the layout pass laid out on (089)
312
313
  memory_extraction_queue durable queue of turns awaiting summarisation
313
314
  ```
314
315
 
@@ -349,8 +350,9 @@ of sentences all shaped "X is a project that does Y", every pair is similar in
349
350
  shape rather than in subject, so 144 of one graph's 371 edges were pairings like
350
351
  *"Vantum monorepo phase 1.8"* ↔ *"ChatKit runs on Node.js 18+"*. The fault was
351
352
  never that they connected memories — it was that **cosine chose which**. Edges are
352
- now derived at read time from the subjects extraction already recorded, and never
353
- stored.
353
+ now derived from the subjects extraction already recorded. They are never stored
354
+ as relations; the layout pass keeps the set it laid out on in
355
+ `graph_layout_edges`, which is disposable like the rest of the arrangement.
354
356
 
355
357
  ---
356
358
 
@@ -364,7 +366,8 @@ bootstrap.ts startup; idempotent, also re-run after Clear All Data
364
366
 
365
367
  retrieval.ts BM25 + vector, RRF fusion, spreading activation
366
368
  context.ts builds the injected block; standing instructions
367
- view.ts graph serialization for the UI
369
+ layout.ts background arrangement: cold passes, warm arrival placement, the world
370
+ view.ts the graph view as map tiles, plus locate and node detail
368
371
 
369
372
  extract/
370
373
  scheduler.ts durable queue, retries, concurrency