@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,99 @@
1
+ /**
2
+ * The processes below a pid, and waiting for them to be gone.
3
+ *
4
+ * A supervised child (the server, the dev frontend) starts processes of its
5
+ * own — engine CLIs, the preview's Chrome, cloudflared — and some of those sit
6
+ * in other process groups, so a signal to the child's group does not reach
7
+ * them. Collected BEFORE anything is signalled: once their parent exits they
8
+ * are re-parented and can no longer be found by parent id.
9
+ *
10
+ * POSIX only (`ps`); on Windows the lists are empty and callers fall back to
11
+ * the single pid.
12
+ */
13
+
14
+ const IS_WINDOWS = process.platform === 'win32';
15
+
16
+ /** Every descendant of `rootPid` (not `rootPid` itself). */
17
+ export function collectDescendants(rootPid: number): number[] {
18
+ if (IS_WINDOWS || !Number.isInteger(rootPid) || rootPid <= 0) return [];
19
+ let output: string;
20
+ try {
21
+ output = new TextDecoder().decode(Bun.spawnSync(['ps', '-A', '-o', 'pid=,ppid='], { stdout: 'pipe', stderr: 'ignore' }).stdout);
22
+ } catch {
23
+ return [];
24
+ }
25
+ const children = new Map<number, number[]>();
26
+ for (const line of output.split('\n')) {
27
+ const [pid, ppid] = line.trim().split(/\s+/).map(Number);
28
+ if (!pid || ppid === undefined || Number.isNaN(ppid)) continue;
29
+ const list = children.get(ppid);
30
+ if (list) list.push(pid);
31
+ else children.set(ppid, [pid]);
32
+ }
33
+ const found = new Set<number>();
34
+ const queue = [rootPid];
35
+ while (queue.length > 0) {
36
+ const pid = queue.pop()!;
37
+ for (const child of children.get(pid) ?? []) {
38
+ if (found.has(child) || child === rootPid || child === process.pid) continue;
39
+ found.add(child);
40
+ queue.push(child);
41
+ }
42
+ }
43
+ return [...found];
44
+ }
45
+
46
+ /** Whether `pid` still exists (one we may not signal counts as existing). */
47
+ export function isAlive(pid: number): boolean {
48
+ try {
49
+ process.kill(pid, 0);
50
+ return true;
51
+ } catch (err) {
52
+ return (err as NodeJS.ErrnoException).code === 'EPERM';
53
+ }
54
+ }
55
+
56
+ /** Send `signal` to every pid still there. */
57
+ export function signalAll(pids: number[], signal: NodeJS.Signals): void {
58
+ for (const pid of pids) {
59
+ try {
60
+ process.kill(pid, signal);
61
+ } catch {
62
+ // Already gone.
63
+ }
64
+ }
65
+ }
66
+
67
+ /** Resolves once none of `pids` exists, or after `timeoutMs`; returns the survivors. */
68
+ export async function waitForExit(pids: number[], timeoutMs: number, pollMs = 50): Promise<number[]> {
69
+ const deadline = Date.now() + timeoutMs;
70
+ let alive = pids.filter(isAlive);
71
+ while (alive.length > 0 && Date.now() < deadline) {
72
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
73
+ alive = alive.filter(isAlive);
74
+ }
75
+ return alive;
76
+ }
77
+
78
+ /**
79
+ * Whether this process's parent forwards terminal signals to it: a script
80
+ * runner (`bun run`, `bun x`) in the same process group. A Ctrl+C reaches the
81
+ * whole foreground group — runner and child — and the runner then forwards its
82
+ * copy, so the child receives the FIRST Ctrl+C twice (measured: 1 ms apart;
83
+ * later presses arrive once). A plain shell does not forward.
84
+ */
85
+ export function parentForwardsSignals(): boolean {
86
+ if (IS_WINDOWS) return false;
87
+ try {
88
+ const read = (pid: number, field: string) =>
89
+ new TextDecoder().decode(Bun.spawnSync(['ps', '-o', `${field}=`, '-p', String(pid)], { stdout: 'pipe', stderr: 'ignore' }).stdout).trim();
90
+ const ownGroup = read(process.pid, 'pgid');
91
+ const parentGroup = read(process.ppid, 'pgid');
92
+ if (!ownGroup || ownGroup !== parentGroup) return false;
93
+ const command = read(process.ppid, 'command');
94
+ const program = command.split(/\s+/)[0]?.split('/').pop() ?? '';
95
+ return program === 'bun' || program === 'bunx' || program === 'bun.exe';
96
+ } catch {
97
+ return false;
98
+ }
99
+ }
@@ -0,0 +1,33 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+
3
+ import { decodeChunk, encodeChunk, sliceText } from './ws-chunk';
4
+
5
+ describe('ws chunk format', () => {
6
+ test('round-trips header and slice, including separators-like text in the slice', () => {
7
+ const frame = encodeChunk('7', 'messages:list-1-abc', 2, 5, '{"a":"x:y-z"}');
8
+ expect(decodeChunk(frame)).toEqual({
9
+ streamId: '7',
10
+ requestId: 'messages:list-1-abc',
11
+ index: 2,
12
+ count: 5,
13
+ slice: '{"a":"x:y-z"}'
14
+ });
15
+ });
16
+
17
+ test('rejects frames that are not chunks or are out of range', () => {
18
+ expect(decodeChunk('{"action":"x"}')).toBeNull();
19
+ expect(decodeChunk(encodeChunk('1', 'r', 5, 5, 'x'))).toBeNull();
20
+ expect(decodeChunk('\u0001broken')).toBeNull();
21
+ });
22
+
23
+ test('never splits a surrogate pair and reassembles to the original', () => {
24
+ const text = 'ab😀'.repeat(1000);
25
+ const slices = sliceText(text, 7);
26
+ for (const slice of slices) {
27
+ const last = slice.charCodeAt(slice.length - 1);
28
+ expect(last >= 0xd800 && last <= 0xdbff).toBe(false);
29
+ expect(slice.length).toBeLessThanOrEqual(7);
30
+ }
31
+ expect(slices.join('')).toBe(text);
32
+ });
33
+ });
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Wire format of a chunked request-response reply — shared by the server that
3
+ * cuts it (backend/utils/ws-wire.ts) and the client that reassembles it
4
+ * (shared/utils/ws-client.ts), so the two cannot drift.
5
+ *
6
+ * `\u0001<streamId>\u0002<requestId>\u0002<index>\u0002<count>\u0002<text slice>`
7
+ *
8
+ * `streamId` is unique per reply. A read that was re-sent can be answered
9
+ * twice under one requestId, and the two replies must not be stitched into
10
+ * each other; the second one to complete is ignored like any duplicate reply.
11
+ *
12
+ * JSON frames always start with `{`, so a leading control character cannot be
13
+ * mistaken for one, and the slice is raw text — not re-escaped inside another
14
+ * JSON string, which would grow every quote and backslash.
15
+ */
16
+
17
+ export const CHUNK_MARKER = '\u0001';
18
+ export const CHUNK_MARKER_CODE = 1;
19
+ export const CHUNK_SEPARATOR = '\u0002';
20
+
21
+ export interface Chunk {
22
+ streamId: string;
23
+ requestId: string;
24
+ index: number;
25
+ count: number;
26
+ slice: string;
27
+ }
28
+
29
+ export function encodeChunk(streamId: string, requestId: string, index: number, count: number, slice: string): string {
30
+ return [CHUNK_MARKER + streamId, requestId, index, count, slice].join(CHUNK_SEPARATOR);
31
+ }
32
+
33
+ export function decodeChunk(frame: string): Chunk | null {
34
+ if (frame.charCodeAt(0) !== CHUNK_MARKER_CODE) return null;
35
+ const cuts: number[] = [];
36
+ let from = 0;
37
+ for (let i = 0; i < 4; i++) {
38
+ const at = frame.indexOf(CHUNK_SEPARATOR, from);
39
+ if (at < 0) return null;
40
+ cuts.push(at);
41
+ from = at + 1;
42
+ }
43
+ const index = Number(frame.slice(cuts[1] + 1, cuts[2]));
44
+ const count = Number(frame.slice(cuts[2] + 1, cuts[3]));
45
+ if (!Number.isInteger(index) || !Number.isInteger(count) || index < 0 || index >= count) return null;
46
+ return {
47
+ streamId: frame.slice(1, cuts[0]),
48
+ requestId: frame.slice(cuts[0] + 1, cuts[1]),
49
+ index,
50
+ count,
51
+ slice: frame.slice(cuts[3] + 1)
52
+ };
53
+ }
54
+
55
+ /**
56
+ * Cut text into pieces of at most `size` UTF-16 units without splitting a
57
+ * surrogate pair — half of one would be replaced on the wire and corrupt the
58
+ * reassembled JSON.
59
+ */
60
+ export function sliceText(text: string, size: number): string[] {
61
+ const slices: string[] = [];
62
+ let start = 0;
63
+ while (start < text.length) {
64
+ let end = Math.min(start + size, text.length);
65
+ if (end < text.length) {
66
+ const code = text.charCodeAt(end - 1);
67
+ if (code >= 0xd800 && code <= 0xdbff) end--;
68
+ }
69
+ slices.push(text.slice(start, end));
70
+ start = end;
71
+ }
72
+ return slices;
73
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * End to end: a large request-response reply leaves the server in chunks
3
+ * (backend/utils/ws-wire.ts) and the real client reassembles it into exactly
4
+ * the reply it would have received whole.
5
+ */
6
+
7
+ import { afterEach, expect, test } from 'bun:test';
8
+
9
+ import { WSClient } from './ws-client';
10
+ import { CHUNK_BYTES, sendReply } from '$backend/utils/ws-wire';
11
+
12
+ const servers: Array<{ stop: (force?: boolean) => void }> = [];
13
+ afterEach(() => {
14
+ for (const server of servers.splice(0)) server.stop(true);
15
+ });
16
+
17
+ test('a chunked reply resolves ws.http() with the whole value', async () => {
18
+ const big = { rows: Array.from({ length: 12000 }, (_, i) => ({ id: i, text: `row ${i} — ✓ 😀 "quoted"` })) };
19
+ const server = Bun.serve({
20
+ port: 0,
21
+ fetch(req, srv) {
22
+ return srv.upgrade(req) ? undefined : new Response('no', { status: 400 });
23
+ },
24
+ websocket: {
25
+ async message(ws, raw) {
26
+ const { action, payload } = JSON.parse(String(raw));
27
+ if (action !== 'messages:list') return;
28
+ const reply = JSON.stringify({
29
+ action: 'messages:list:response',
30
+ payload: { success: true, data: big, requestId: payload.requestId }
31
+ });
32
+ expect(reply.length).toBeGreaterThan(CHUNK_BYTES);
33
+ await sendReply(ws, 'messages:list:response', payload.requestId, reply);
34
+ }
35
+ }
36
+ });
37
+ servers.push(server);
38
+
39
+ const client = new WSClient<{ client: any; server: any }>(`ws://localhost:${server.port}`, { autoReconnect: false });
40
+ await client.waitUntilConnected(5000);
41
+
42
+ const data = await client.http('messages:list' as never, {} as never, 10_000);
43
+ expect(data).toEqual(big);
44
+ client.disconnect();
45
+ });
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import { debug } from './logger';
13
+ import { CHUNK_MARKER_CODE, decodeChunk } from './ws-chunk';
13
14
 
14
15
  // ============================================================================
15
16
  // Singleton Encoders (Performance Optimization)
@@ -275,6 +276,8 @@ export class WSClient<TAPI extends { client: any; server: any }> {
275
276
 
276
277
  /** In-flight HTTP requests, keyed by requestId, for resend-on-reconnect. */
277
278
  private pendingHttpRequests = new Map<string, PendingHttpRequest>();
279
+ /** Large replies being reassembled, by reply stream. Dropped with the socket. */
280
+ private chunkAssemblies = new Map<string, { parts: string[]; received: number }>();
278
281
  /** Prevents a heal-reconnect stampede when many requests time out at once. */
279
282
  private healingReconnect = false;
280
283
 
@@ -461,6 +464,9 @@ export class WSClient<TAPI extends { client: any; server: any }> {
461
464
  debug.log('websocket', 'Disconnected');
462
465
  this.isConnected = false;
463
466
  this.ws = null;
467
+ // Pieces of a reply cannot be completed on another socket; the request
468
+ // itself is re-sent on reconnect and its reply starts over.
469
+ this.chunkAssemblies.clear();
464
470
 
465
471
  // Auto-reconnect
466
472
  if (this.shouldReconnect && this.options.autoReconnect) {
@@ -482,6 +488,11 @@ export class WSClient<TAPI extends { client: any; server: any }> {
482
488
  * Handle text/JSON message from server
483
489
  */
484
490
  private handleTextMessage(data: string): void {
491
+ if (data.charCodeAt(0) === CHUNK_MARKER_CODE) {
492
+ this.handleChunk(data);
493
+ return;
494
+ }
495
+
485
496
  // Check if data looks like binary (not valid JSON start)
486
497
  if (data && data.length > 0 && data[0] !== '{' && data[0] !== '[') {
487
498
  debug.warn('websocket', `Received non-JSON text data (length: ${data.length}), first char code: ${data.charCodeAt(0)}`);
@@ -499,6 +510,38 @@ export class WSClient<TAPI extends { client: any; server: any }> {
499
510
  this.dispatchToListeners(action, payload);
500
511
  }
501
512
 
513
+ /**
514
+ * One piece of a large request-response reply (format: shared/utils/ws-chunk.ts).
515
+ *
516
+ * Each piece is proof the reply is still arriving, so it re-arms that
517
+ * request's timeout — without this a slow link timed a big reply out halfway
518
+ * and re-requested it, downloading it again. The last piece completes the
519
+ * frame, which is then handled exactly like one sent whole.
520
+ */
521
+ private handleChunk(data: string): void {
522
+ const chunk = decodeChunk(data);
523
+ if (!chunk) {
524
+ debug.warn('websocket', 'Dropping malformed chunk frame');
525
+ return;
526
+ }
527
+ const { streamId, requestId, index, count } = chunk;
528
+
529
+ let assembly = this.chunkAssemblies.get(streamId);
530
+ if (!assembly) {
531
+ assembly = { parts: new Array<string>(count), received: 0 };
532
+ this.chunkAssemblies.set(streamId, assembly);
533
+ }
534
+ if (assembly.parts[index] === undefined) {
535
+ assembly.parts[index] = chunk.slice;
536
+ assembly.received++;
537
+ }
538
+ this.pendingHttpRequests.get(requestId)?.arm();
539
+
540
+ if (assembly.received < count) return;
541
+ this.chunkAssemblies.delete(streamId);
542
+ this.handleTextMessage(assembly.parts.join(''));
543
+ }
544
+
502
545
  /**
503
546
  * Handle binary message from server
504
547
  */
@@ -14,6 +14,7 @@ import type { Elysia } from 'elysia';
14
14
  import { t, type TSchema, type Static } from 'elysia';
15
15
  import { Value } from '@sinclair/typebox/value';
16
16
  import { debug } from './logger';
17
+ import { sendBinary, sendReply, sendText } from '$backend/utils/ws-wire';
17
18
 
18
19
  // ============================================================================
19
20
  // Singleton Encoders (Performance Optimization)
@@ -606,13 +607,13 @@ export class WSRouter<
606
607
  if (isBinaryAction(responseAction, validatedResponse)) {
607
608
  // For binary responses, wrap in success envelope with requestId
608
609
  const wrappedResponse = { success: true, data: validatedResponse, requestId };
609
- const binaryMessage = encodeBinaryMessage(responseAction, wrappedResponse);
610
- conn.send(Buffer.from(binaryMessage));
610
+ sendBinary(conn, responseAction, encodeBinaryMessage(responseAction, wrappedResponse));
611
611
  debug.log('websocket', 'HTTP success (binary):', action);
612
612
  } else {
613
- // For JSON responses, wrap in success envelope with requestId
613
+ // For JSON responses, wrap in success envelope with requestId. Large
614
+ // replies leave in chunks (see sendReply).
614
615
  const wrappedResponse = { success: true, data: validatedResponse, requestId };
615
- conn.send(JSON.stringify({ action: responseAction, payload: wrappedResponse }));
616
+ await sendReply(conn, responseAction, requestId, JSON.stringify({ action: responseAction, payload: wrappedResponse }));
616
617
  debug.log('websocket', 'HTTP success (JSON):', action);
617
618
  }
618
619
  } catch (err) {
@@ -620,7 +621,11 @@ export class WSRouter<
620
621
  const errorMessage = err instanceof Error ? err.message : String(err);
621
622
 
622
623
  const errorResponse = { success: false, error: errorMessage, requestId };
623
- conn.send(JSON.stringify({ action: responseAction, payload: errorResponse }));
624
+ try {
625
+ sendText(conn, responseAction, JSON.stringify({ action: responseAction, payload: errorResponse }));
626
+ } catch {
627
+ // Connection may be closed
628
+ }
624
629
  debug.error('websocket', `HTTP error [${action}]:`, errorMessage);
625
630
  }
626
631
  }
@@ -668,12 +673,12 @@ export class WSRouter<
668
673
  // so ws.http() on the client receives it instead of timing out
669
674
  if (this.httpRoutes.has(action)) {
670
675
  const requestId = payload?.requestId;
671
- conn.send(JSON.stringify({
676
+ sendText(conn, `${action}:response`, JSON.stringify({
672
677
  action: `${action}:response`,
673
678
  payload: { success: false, error: authResult.error, requestId }
674
679
  }));
675
680
  } else {
676
- conn.send(JSON.stringify({
681
+ sendText(conn, 'auth:error', JSON.stringify({
677
682
  action: 'auth:error',
678
683
  payload: { error: authResult.error, blockedAction: action }
679
684
  }));
@@ -709,7 +714,7 @@ export class WSRouter<
709
714
  // have no requestId and still just drop.
710
715
  if (isRequest) {
711
716
  try {
712
- conn.send(JSON.stringify({
717
+ sendText(conn, `${action}:response`, JSON.stringify({
713
718
  action: `${action}:response`,
714
719
  payload: {
715
720
  success: false,
@@ -759,13 +764,11 @@ export class WSRouter<
759
764
  */
760
765
  asPlugin(path: string = '/ws') {
761
766
  return (app: Elysia) => {
767
+ // Socket limits (payload size, idle timeout, compression) are NOT set
768
+ // here: Elysia ignores them on a `.ws()` route and only passes the
769
+ // app-level `websocket` config to Bun.serve — see WS_SERVER_OPTIONS
770
+ // in backend/utils/ws-wire.ts.
762
771
  return app.ws(path, {
763
- // Allow large binary frames (file uploads, zip extracts).
764
- // Bun/uWS default is 16MB which trips EPIPE on the dev proxy
765
- // long before the configurable per-file limit kicks in.
766
- maxPayloadLength: 1024 * 1024 * 1024, // 1 GiB
767
- // Disable inactivity disconnects during long binary transfers.
768
- idleTimeout: 960, // seconds (max allowed by uWS)
769
772
  message: (conn, message) => {
770
773
  this.handleMessage(conn, message);
771
774
  },
@@ -1,170 +0,0 @@
1
- /**
2
- * Migration 086 takes a multi-user install to a single owner. It runs the real
3
- * migration chain up to 085 against an in-memory SQLite, seeds the shapes a
4
- * team install actually had, then checks what 086 keeps and what it removes —
5
- * above all that no credential of a removed account survives.
6
- */
7
-
8
- import { describe, expect, test } from 'bun:test';
9
- import { Database } from 'bun:sqlite';
10
- import { mkdtempSync, mkdirSync, existsSync, rmSync } from 'fs';
11
- import { join } from 'path';
12
- import { tmpdir } from 'os';
13
- import type { DatabaseConnection } from '$shared/types/database/connection';
14
- import migrations from './index';
15
- import { up, down } from './086_single_owner';
16
-
17
- const NOW = '2026-01-01T00:00:00.000Z';
18
-
19
- function migratedTo085(): Database {
20
- const db = new Database(':memory:');
21
- db.exec('PRAGMA foreign_keys = ON');
22
- for (const migration of [...migrations].sort((a, b) => a.id.localeCompare(b.id))) {
23
- if (migration.id >= '086') break;
24
- migration.up(db as unknown as DatabaseConnection);
25
- }
26
- return db;
27
- }
28
-
29
- function addUser(db: Database, id: string, role: 'admin' | 'member', createdAt: string): void {
30
- db.prepare(`INSERT INTO users (id, name, color, avatar, role, personal_access_token_hash, created_at, updated_at) VALUES (?, ?, '#000', 'X', ?, ?, ?, ?)`)
31
- .run(id, id, role, `pat-${id}`, createdAt, createdAt);
32
- db.prepare(`INSERT INTO auth_sessions (id, user_id, token_hash, expires_at, created_at, last_active_at) VALUES (?, ?, ?, '2099-01-01', ?, ?)`)
33
- .run(`s-${id}`, id, `hash-${id}`, NOW, NOW);
34
- }
35
-
36
- function addProject(db: Database, id: string, path: string, kind: 'project' | 'home' = 'project', owner: string | null = null): void {
37
- db.prepare(`INSERT INTO projects (id, name, path, created_at, last_opened_at, kind, owner_user_id) VALUES (?, ?, ?, ?, ?, ?, ?)`)
38
- .run(id, id, path, NOW, NOW, kind, owner);
39
- }
40
-
41
- function seed(home: string): Database {
42
- const db = migratedTo085();
43
- // The oldest admin is the owner; a second admin and a member are removed.
44
- addUser(db, 'owner', 'admin', '2025-01-01');
45
- addUser(db, 'admin2', 'admin', '2025-02-01');
46
- addUser(db, 'member', 'member', '2024-01-01');
47
-
48
- addProject(db, 'shared', '/repo/shared');
49
- addProject(db, 'removed', '/repo/removed');
50
- addProject(db, 'home-owner', join(home, 'owner'), 'home', 'owner');
51
- addProject(db, 'home-member', join(home, 'member'), 'home', 'member');
52
- mkdirSync(join(home, 'member'), { recursive: true });
53
-
54
- for (const [user, project, state] of [['owner', 'shared', 'owner-layout'], ['owner', 'home-owner', null], ['member', 'shared', 'member-layout'], ['member', 'home-member', null]] as const) {
55
- db.prepare(`INSERT INTO user_projects (user_id, project_id, joined_at, workspace_state) VALUES (?, ?, ?, ?)`).run(user, project, NOW, state);
56
- }
57
-
58
- // A chat the member had in the shared project is project history; one in their Home is theirs.
59
- db.prepare(`INSERT INTO chat_sessions (id, project_id, started_at) VALUES ('chat-shared', 'shared', ?)`).run(NOW);
60
- db.prepare(`INSERT INTO chat_sessions (id, project_id, started_at) VALUES ('chat-home', 'home-member', ?)`).run(NOW);
61
- db.prepare(`INSERT INTO user_unread_sessions (user_id, session_id, project_id, marked_at) VALUES ('owner', 'chat-shared', 'shared', ?), ('member', 'chat-shared', 'shared', ?)`).run(NOW, NOW);
62
-
63
- db.prepare(`INSERT INTO invite_tokens (id, token_hash, role, created_by, created_at) VALUES ('inv', 'inv-hash', 'member', 'owner', ?)`).run(NOW);
64
- db.prepare(`INSERT INTO device_codes (id, code_hash, user_id, expires_at, created_at) VALUES ('dev', 'dev-hash', 'member', '2099-01-01', ?)`).run(NOW);
65
-
66
- for (const [id, owner] of [['db-owner', 'owner'], ['db-member', 'member'], ['db-legacy', null]] as const) {
67
- db.prepare(`INSERT INTO db_client_connections (id, name, driver, created_at, updated_at, owner_user_id) VALUES (?, ?, 'postgres', ?, ?, ?)`).run(id, id, NOW, NOW, owner);
68
- }
69
- for (const [id, owner] of [['ssh-owner', 'owner'], ['ssh-member', 'member']] as const) {
70
- db.prepare(`INSERT INTO ssh_connections (id, name, host, port, username, auth_method, created_at, updated_at, owner_user_id) VALUES (?, ?, 'h', 22, 'u', 'agent', ?, ?, ?)`).run(id, id, NOW, NOW, owner);
71
- }
72
- for (const [id, owner, isDefault] of [['gi-owner', 'owner', 1], ['gi-member', 'member', 1]] as const) {
73
- db.prepare(`INSERT INTO git_identities (id, owner_user_id, label, name, email, is_default, created_at, updated_at) VALUES (?, ?, 'Work', 'N', 'e@x.y', ?, ?, ?)`).run(id, owner, isDefault, NOW, NOW);
74
- }
75
- db.prepare(`INSERT INTO git_identity_bindings (project_id, user_id, identity_id, created_at, updated_at) VALUES ('shared', 'owner', 'gi-owner', ?, ?), ('shared', 'member', 'gi-member', ?, ?)`).run(NOW, NOW, NOW, NOW);
76
-
77
- db.prepare(`INSERT INTO integration_accounts (id, provider, label, auth_method, created_at, updated_at) VALUES ('bot', 'telegram', 'Bot', 'token', ?, ?)`).run(NOW, NOW);
78
- db.prepare(`INSERT INTO channel_links (id, account_id, user_id, conversation_id, platform_user_id, status, created_at) VALUES ('link-owner', 'bot', 'owner', 'c1', 'p1', 'approved', ?), ('link-member', 'bot', 'member', 'c2', 'p2', 'pending', ?)`).run(NOW, NOW);
79
- return db;
80
- }
81
-
82
- function ids(db: Database, sql: string): string[] {
83
- return (db.prepare(sql).all() as { id: string }[]).map((row) => row.id);
84
- }
85
-
86
- function columns(db: Database, table: string): string[] {
87
- return (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).map((c) => c.name);
88
- }
89
-
90
- describe('migration 086', () => {
91
- // Homes live under `<data dir>/home/<userId>`; the migration only removes a
92
- // directory of exactly that shape.
93
- const dataDir = mkdtempSync(join(tmpdir(), 'clopen-086-'));
94
- const home = join(dataDir, 'home');
95
-
96
- test('keeps the oldest admin as the only account, and nothing a removed account could sign in with', () => {
97
- const db = seed(home);
98
- up(db as unknown as DatabaseConnection);
99
-
100
- expect(ids(db, 'SELECT id FROM users')).toEqual(['owner']);
101
- expect(ids(db, 'SELECT user_id AS id FROM auth_sessions')).toEqual(['owner']);
102
- expect(ids(db, 'SELECT id FROM device_codes')).toEqual([]);
103
- expect(ids(db, 'SELECT id FROM channel_links')).toEqual(['link-owner']);
104
- expect(columns(db, 'users')).not.toContain('role');
105
- expect(db.prepare(`SELECT name FROM sqlite_master WHERE name = 'invite_tokens'`).get()).toBeNull();
106
- db.close();
107
- });
108
-
109
- test('removes what was the others alone, keeps shared project history', () => {
110
- const db = seed(home);
111
- up(db as unknown as DatabaseConnection);
112
-
113
- expect(ids(db, 'SELECT id FROM projects ORDER BY id')).toEqual(['home-owner', 'removed', 'shared']);
114
- expect(ids(db, 'SELECT id FROM chat_sessions')).toEqual(['chat-shared']);
115
- expect(existsSync(join(home, 'member'))).toBe(false);
116
- expect(ids(db, 'SELECT id FROM db_client_connections ORDER BY id')).toEqual(['db-legacy', 'db-owner']);
117
- expect(ids(db, 'SELECT id FROM ssh_connections')).toEqual(['ssh-owner']);
118
- expect(ids(db, 'SELECT id FROM git_identities')).toEqual(['gi-owner']);
119
- expect(ids(db, 'SELECT identity_id AS id FROM git_identity_bindings')).toEqual(['gi-owner']);
120
- db.close();
121
- });
122
-
123
- test("carries the owner's workspace list and state over, without a user key", () => {
124
- const db = seed(home);
125
- up(db as unknown as DatabaseConnection);
126
-
127
- const rows = db.prepare('SELECT project_id, workspace_state FROM workspace_projects ORDER BY project_id').all();
128
- expect(rows).toEqual([
129
- { project_id: 'home-owner', workspace_state: null },
130
- { project_id: 'shared', workspace_state: 'owner-layout' }
131
- ]);
132
- // `removed` was never in the owner's list, so it stays removed.
133
- expect(db.prepare(`SELECT session_id FROM unread_sessions`).all()).toEqual([{ session_id: 'chat-shared' }]);
134
- for (const [table, column] of [['projects', 'owner_user_id'], ['db_client_connections', 'owner_user_id'], ['ssh_connections', 'owner_user_id'], ['git_identities', 'owner_user_id'], ['git_identity_bindings', 'user_id'], ['chat_sessions', 'sender_id'], ['channel_links', 'status']] as const) {
135
- expect(columns(db, table)).not.toContain(column);
136
- }
137
- db.close();
138
- });
139
-
140
- test('rolls back to the multi-user schema, the owner as its admin', () => {
141
- const db = seed(home);
142
- up(db as unknown as DatabaseConnection);
143
- down(db as unknown as DatabaseConnection);
144
-
145
- expect(db.prepare('SELECT id, role FROM users').all()).toEqual([{ id: 'owner', role: 'admin' }]);
146
- expect(db.prepare('SELECT user_id, project_id FROM user_projects ORDER BY project_id').all()).toEqual([
147
- { user_id: 'owner', project_id: 'home-owner' },
148
- { user_id: 'owner', project_id: 'shared' }
149
- ]);
150
- expect(db.prepare('SELECT owner_user_id FROM git_identities').all()).toEqual([{ owner_user_id: 'owner' }]);
151
- expect(columns(db, 'chat_sessions')).toContain('sender_id');
152
- db.close();
153
- });
154
-
155
- test('allows one Home and one default identity for the install', () => {
156
- const db = seed(home);
157
- up(db as unknown as DatabaseConnection);
158
-
159
- expect(() => addProjectAfter(db, 'home-2')).toThrow();
160
- expect(() =>
161
- db.prepare(`INSERT INTO git_identities (id, label, name, email, is_default, created_at, updated_at) VALUES ('gi-2', 'Other', 'N', 'e@x.y', 1, ?, ?)`).run(NOW, NOW)
162
- ).toThrow();
163
- db.close();
164
- rmSync(dataDir, { recursive: true, force: true });
165
- });
166
- });
167
-
168
- function addProjectAfter(db: Database, id: string): void {
169
- db.prepare(`INSERT INTO projects (id, name, path, created_at, last_opened_at, kind) VALUES (?, ?, ?, ?, ?, 'home')`).run(id, id, `/${id}`, NOW, NOW);
170
- }