@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,242 @@
1
+ /**
2
+ * The supervisor that keeps the Clopen server (and the dev frontend/backend)
3
+ * running: a child killed from outside comes back, a requested stop does not,
4
+ * and the child lives in its own process group so a signal aimed at it cannot
5
+ * reach the supervisor.
6
+ */
7
+
8
+ import { afterAll, describe, expect, test } from 'bun:test';
9
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
10
+ import { tmpdir } from 'node:os';
11
+ import { join } from 'node:path';
12
+
13
+ import { elapsedSeconds, supervise } from './process-supervisor';
14
+
15
+ const posix = process.platform !== 'win32';
16
+ const dir = mkdtempSync(join(tmpdir(), 'clopen-supervisor-'));
17
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
18
+
19
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
20
+
21
+ /** A child that prints its pid and process group, then waits. */
22
+ const LONG_RUNNING = ['sh', '-c', 'echo "pid=$$ pgid=$(ps -o pgid= -p $$ | tr -d " ")"; sleep 30'];
23
+
24
+ function collect() {
25
+ const lines: string[] = [];
26
+ const decoder = new TextDecoder();
27
+ return { lines, sink: (chunk: Uint8Array) => lines.push(...decoder.decode(chunk).split('\n').filter(Boolean)) };
28
+ }
29
+
30
+ async function waitFor(check: () => boolean, timeoutMs = 5000) {
31
+ const deadline = Date.now() + timeoutMs;
32
+ while (!check()) {
33
+ if (Date.now() > deadline) throw new Error('timed out');
34
+ await sleep(20);
35
+ }
36
+ }
37
+
38
+ const pidsIn = (lines: string[]) =>
39
+ lines.map((line) => /pid=(\d+) pgid=(\d+)/.exec(line)).filter(Boolean).map((m) => ({ pid: Number(m![1]), pgid: Number(m![2]) }));
40
+
41
+ describe.if(posix)('supervise', () => {
42
+ test('runs the child in its own process group', async () => {
43
+ const out = collect();
44
+ const s = supervise({ name: 't', cmd: LONG_RUNNING, onStdout: out.sink, log: () => {} });
45
+ await waitFor(() => pidsIn(out.lines).length > 0);
46
+ const [{ pid, pgid }] = pidsIn(out.lines);
47
+ expect(pgid).toBe(pid);
48
+ expect(pgid).not.toBe(Number(Bun.spawnSync(['ps', '-o', 'pgid=', '-p', String(process.pid)]).stdout.toString().trim()));
49
+ await s.stop();
50
+ });
51
+
52
+ test('restarts a child killed from outside, and writes a report', async () => {
53
+ const out = collect();
54
+ const logs: string[] = [];
55
+ const reportFile = join(dir, 'report.log');
56
+ const s = supervise({
57
+ name: 'server',
58
+ cmd: LONG_RUNNING,
59
+ onStdout: out.sink,
60
+ log: (line) => logs.push(line),
61
+ reportFile,
62
+ restartDelayMs: 50
63
+ });
64
+ await waitFor(() => pidsIn(out.lines).length === 1);
65
+ const [first] = pidsIn(out.lines);
66
+
67
+ // A stray SIGTERM to the child's whole group — what took the server down.
68
+ process.kill(-first.pgid, 'SIGTERM');
69
+
70
+ await waitFor(() => pidsIn(out.lines).length === 2);
71
+ const [, second] = pidsIn(out.lines);
72
+ expect(second.pid).not.toBe(first.pid);
73
+ expect(logs.some((line) => line.includes('restarting'))).toBe(true);
74
+ expect(existsSync(reportFile)).toBe(true);
75
+ expect(readFileSync(reportFile, 'utf8')).toContain('exited without being asked to (signal SIGTERM)');
76
+ await s.stop();
77
+ });
78
+
79
+ test('a requested stop reaches the whole group and is not restarted', async () => {
80
+ const out = collect();
81
+ const s = supervise({
82
+ name: 't',
83
+ // The child starts a grandchild that reports its pid, then both wait.
84
+ cmd: ['sh', '-c', 'sleep 30 & echo "grandchild=$!"; wait'],
85
+ onStdout: out.sink,
86
+ log: () => {},
87
+ restartDelayMs: 50
88
+ });
89
+ await waitFor(() => out.lines.some((line) => line.startsWith('grandchild=')));
90
+ const grandchild = Number(out.lines.find((line) => line.startsWith('grandchild='))!.split('=')[1]);
91
+
92
+ const code = await s.stop('SIGTERM');
93
+ expect(typeof code).toBe('number');
94
+ await sleep(150);
95
+ expect(out.lines.filter((line) => line.startsWith('grandchild='))).toHaveLength(1); // not restarted
96
+ expect(() => process.kill(grandchild, 0)).toThrow(); // the grandchild went with it
97
+ });
98
+
99
+ /**
100
+ * A child whose grandchild lives in another process group (like the
101
+ * preview's Chrome): on SIGTERM the child asks the grandchild to stop and
102
+ * exits at once; the grandchild takes `drainMs` (or ignores it).
103
+ */
104
+ function childWithDetachedGrandchild(name: string, drainMs: number | 'ignore'): string[] {
105
+ const grandchild = join(dir, `${name}-grandchild.ts`);
106
+ writeFileSync(
107
+ grandchild,
108
+ drainMs === 'ignore'
109
+ ? `process.on('SIGTERM', () => {}); console.log('ready'); setInterval(() => {}, 1000);`
110
+ : `process.on('SIGTERM', () => setTimeout(() => process.exit(0), ${drainMs})); console.log('ready'); setInterval(() => {}, 1000);`
111
+ );
112
+ const child = join(dir, `${name}-child.ts`);
113
+ writeFileSync(
114
+ child,
115
+ `const g = Bun.spawn(['bun', ${JSON.stringify(grandchild)}], { detached: true, stdout: 'pipe' });
116
+ for await (const chunk of g.stdout) { if (new TextDecoder().decode(chunk).includes('ready')) break; }
117
+ console.log('grandchild=' + g.pid);
118
+ process.on('SIGTERM', () => { g.kill('SIGTERM'); process.exit(0); });
119
+ setInterval(() => {}, 1000);`
120
+ );
121
+ return ['bun', child];
122
+ }
123
+
124
+ test('a stop is over only once what the child started in other groups has exited', async () => {
125
+ const out = collect();
126
+ const s = supervise({ name: 't', cmd: childWithDetachedGrandchild('drain', 400), onStdout: out.sink, log: () => {} });
127
+ await waitFor(() => out.lines.some((line) => line.startsWith('grandchild=')), 10_000);
128
+ const grandchild = Number(out.lines.find((line) => line.startsWith('grandchild='))!.split('=')[1]);
129
+
130
+ const started = Date.now();
131
+ await s.stop('SIGTERM');
132
+ expect(Date.now() - started).toBeGreaterThanOrEqual(350);
133
+ expect(() => process.kill(grandchild, 0)).toThrow();
134
+ });
135
+
136
+ test('a process that hangs past the stop timeout is killed', async () => {
137
+ const out = collect();
138
+ const s = supervise({ name: 't', cmd: childWithDetachedGrandchild('hang', 'ignore'), onStdout: out.sink, log: () => {}, stopTimeoutMs: 600 });
139
+ await waitFor(() => out.lines.some((line) => line.startsWith('grandchild=')), 10_000);
140
+ const grandchild = Number(out.lines.find((line) => line.startsWith('grandchild='))!.split('=')[1]);
141
+
142
+ await s.stop('SIGTERM');
143
+ expect(() => process.kill(grandchild, 0)).toThrow();
144
+ });
145
+
146
+ test('a supervised child stops itself when its supervisor is gone', async () => {
147
+ const marker = join(dir, 'supervisor-gone');
148
+ const child = join(dir, 'watching-child.ts');
149
+ writeFileSync(
150
+ child,
151
+ `import { watchSupervisor } from ${JSON.stringify(join(import.meta.dir, 'process-supervisor.ts'))};
152
+ watchSupervisor(() => { require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'gone'); process.exit(0); }, 100);
153
+ console.log('watching'); setInterval(() => {}, 1000);`
154
+ );
155
+ const supervisor = join(dir, 'doomed-supervisor.ts');
156
+ writeFileSync(
157
+ supervisor,
158
+ `import { supervise } from ${JSON.stringify(join(import.meta.dir, 'process-supervisor.ts'))};
159
+ supervise({ name: 'c', cmd: ['bun', ${JSON.stringify(child)}], log: () => {} });`
160
+ );
161
+ const proc = Bun.spawn(['bun', supervisor], { stdout: 'pipe' });
162
+ for await (const chunk of proc.stdout) if (new TextDecoder().decode(chunk).includes('watching')) break;
163
+
164
+ proc.kill('SIGKILL'); // gone without stopping anything
165
+ await waitFor(() => existsSync(marker), 5000);
166
+ expect(readFileSync(marker, 'utf8')).toBe('gone');
167
+ });
168
+
169
+ test('gives up on a child that keeps dying', async () => {
170
+ const s = supervise({ name: 't', cmd: ['sh', '-c', 'exit 3'], log: () => {}, restartDelayMs: 10, maxRestarts: 2 });
171
+ expect(await s.done).toBe(3);
172
+ });
173
+ });
174
+
175
+ describe('elapsedSeconds', () => {
176
+ test('reads the ps elapsed-time formats', () => {
177
+ expect(elapsedSeconds('00:05')).toBe(5);
178
+ expect(elapsedSeconds('01:02:03')).toBe(3723);
179
+ expect(elapsedSeconds('2-00:00:01')).toBe(172_801);
180
+ expect(elapsedSeconds('garbage')).toBe(Number.POSITIVE_INFINITY);
181
+ });
182
+ });
183
+
184
+ /**
185
+ * The launcher as a whole, in its own process: SIGHUP leaves the server
186
+ * running, a stray SIGTERM to the server's group brings it back, and Ctrl+C
187
+ * to the launcher stops it with a graceful shutdown.
188
+ */
189
+ describe.if(posix)('a supervising launcher', () => {
190
+ test('survives SIGHUP, recovers from a stray SIGTERM, stops on SIGINT', async () => {
191
+ const server = join(dir, 'fake-server.ts');
192
+ const launcher = join(dir, 'launcher.ts');
193
+ await Bun.write(
194
+ server,
195
+ `console.log('up pid=' + process.pid);
196
+ process.on('SIGHUP', () => console.log('ignored SIGHUP'));
197
+ const shutdown = (sig) => { console.log('graceful ' + sig); process.exit(0); };
198
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
199
+ process.on('SIGINT', () => shutdown('SIGINT'));
200
+ setInterval(() => {}, 1000);
201
+ `
202
+ );
203
+ await Bun.write(
204
+ launcher,
205
+ `import { supervise, stopOnSignals } from ${JSON.stringify(join(import.meta.dir, 'process-supervisor.ts'))};
206
+ const s = supervise({ name: 'server', cmd: ['bun', ${JSON.stringify(server)}], restartDelayMs: 50, log: (l) => console.log(l.split('\\n')[0]) });
207
+ stopOnSignals([s]);
208
+ process.exit(await s.done);
209
+ `
210
+ );
211
+
212
+ const proc = Bun.spawn(['bun', launcher], { stdout: 'pipe', stderr: 'pipe' });
213
+ const out = collect();
214
+ void (async () => {
215
+ const reader = proc.stdout.getReader();
216
+ for (;;) {
217
+ const { done, value } = await reader.read();
218
+ if (done) break;
219
+ out.sink(value);
220
+ }
221
+ })();
222
+
223
+ const ups = () => out.lines.filter((line) => line.startsWith('up pid='));
224
+ await waitFor(() => ups().length === 1, 10_000);
225
+ const firstPid = Number(ups()[0].split('=')[1]);
226
+
227
+ process.kill(proc.pid, 'SIGHUP');
228
+ await sleep(300);
229
+ expect(proc.exitCode).toBeNull();
230
+ expect(() => process.kill(firstPid, 0)).not.toThrow(); // server still running
231
+
232
+ process.kill(-firstPid, 'SIGTERM'); // stray signal to the server's group
233
+ await waitFor(() => ups().length === 2, 10_000);
234
+ expect(proc.exitCode).toBeNull();
235
+
236
+ process.kill(proc.pid, 'SIGINT');
237
+ const code = await proc.exited;
238
+ expect(code).toBe(0);
239
+ expect(out.lines.some((line) => line === 'graceful SIGINT')).toBe(true);
240
+ expect(ups()).toHaveLength(2); // not restarted after the requested stop
241
+ }, 30_000);
242
+ });
@@ -0,0 +1,356 @@
1
+ /**
2
+ * Keep a long-running child process (the Clopen server, the dev frontend) up.
3
+ *
4
+ * Shared by the production launcher (bin/clopen.ts) and the dev runner
5
+ * (scripts/dev.ts) so both stop and recover the same way:
6
+ *
7
+ * - **Its own process group** (POSIX). A signal aimed at one process group —
8
+ * by an agent's tooling, a terminal, anything — no longer reaches the
9
+ * others. Windows has no process groups to speak of and `detached` there
10
+ * means a new console, so it is left as is.
11
+ * - **Restarted when it exits without being asked to.** Exit codes cannot tell
12
+ * the difference: a server that received a stray SIGTERM shuts down cleanly
13
+ * and exits 0. What can is whether this supervisor asked it to stop. A child
14
+ * that keeps dying (5 times in 60 s) is given up on instead of looping.
15
+ * - **Stopped on request, completely.** SIGINT/SIGTERM to the supervisor are
16
+ * forwarded to the child's whole group — what a terminal did before the
17
+ * child had a group of its own. The stop is over only when the child AND
18
+ * every process it started (collected first: some sit in other groups, like
19
+ * the preview's Chrome) have exited, so the shell prompt comes back with the
20
+ * ports free. Only a process that hangs past `stopTimeoutMs` is SIGKILLed.
21
+ * A second Ctrl+C forces; the copy of the first one that `bun run` forwards
22
+ * is not a second press (see `stopOnSignals`).
23
+ * - **Tied to its terminal, unless run in the background.** SIGHUP (the
24
+ * terminal or SSH session closed) stops everything when the supervisor was
25
+ * started from a terminal. Run without one — `nohup`, a service, a container
26
+ * — it is ignored and the server keeps running. Writes to a terminal that is
27
+ * gone are dropped instead of crashing.
28
+ * - **Diagnosed.** Each unrequested exit is logged with its code or signal and
29
+ * the processes started shortly before it (pid, ppid, pgid, command), to the
30
+ * console and to `reportFile`, so the next occurrence leaves a trail. The OS
31
+ * never says who sent a signal; what was running when it arrived is the
32
+ * best available evidence.
33
+ */
34
+
35
+ import { appendFileSync, mkdirSync } from 'node:fs';
36
+ import { dirname } from 'node:path';
37
+ import { collectDescendants, parentForwardsSignals, signalAll, waitForExit } from './process-tree';
38
+
39
+ type Subprocess = ReturnType<typeof Bun.spawn>;
40
+
41
+ export interface SupervisedProcessOptions {
42
+ /** Short label for log lines, e.g. `server`. */
43
+ name: string;
44
+ cmd: string[];
45
+ cwd?: string;
46
+ env?: Record<string, string | undefined>;
47
+ /** Where each chunk of the child's output goes. Defaults to inheriting. */
48
+ onStdout?: (chunk: Uint8Array) => void;
49
+ onStderr?: (chunk: Uint8Array) => void;
50
+ /** Lines the supervisor itself prints (restarts, diagnostics). */
51
+ log?: (line: string) => void;
52
+ /** Append-only file for unrequested-exit diagnostics. */
53
+ reportFile?: string;
54
+ /** Defaults: 5 restarts per 60 s, 15 s to stop, 1 s first restart delay. */
55
+ maxRestarts?: number;
56
+ restartWindowMs?: number;
57
+ stopTimeoutMs?: number;
58
+ restartDelayMs?: number;
59
+ }
60
+
61
+ export interface Supervisor {
62
+ /** Resolves with the child's final exit code once it is stopped or given up on. */
63
+ readonly done: Promise<number>;
64
+ /** Ask the child to stop (forwarding `signal` to its group). Idempotent. */
65
+ stop(signal?: NodeJS.Signals): Promise<number>;
66
+ /** Stop now: SIGKILL the child's group. */
67
+ kill(): Promise<number>;
68
+ }
69
+
70
+ const IS_WINDOWS = process.platform === 'win32';
71
+
72
+ /** Tells a supervised child which process supervises it. */
73
+ export const SUPERVISOR_PID_ENV = 'CLOPEN_SUPERVISOR_PID';
74
+
75
+ /**
76
+ * In a supervised child: run `onGone` once the supervisor that started it is
77
+ * gone (its parent pid changes), so the child does not outlive an ungraceful
78
+ * end of its supervisor. The variable is removed from the environment at once:
79
+ * everything the child starts inherits it — terminal shells included — and a
80
+ * dev server started from one would otherwise watch the wrong supervisor.
81
+ */
82
+ export function watchSupervisor(onGone: () => void, pollMs = 1000): void {
83
+ const supervisorPid = Number(process.env[SUPERVISOR_PID_ENV]);
84
+ delete process.env[SUPERVISOR_PID_ENV];
85
+ if (!(supervisorPid > 0) || process.ppid !== supervisorPid) return;
86
+ const timer = setInterval(() => {
87
+ if (process.ppid === supervisorPid) return;
88
+ clearInterval(timer);
89
+ onGone();
90
+ }, pollMs);
91
+ timer.unref?.();
92
+ }
93
+
94
+ /** Run `options.cmd` under supervision until it is stopped. */
95
+ export function supervise(options: SupervisedProcessOptions): Supervisor {
96
+ const log = options.log ?? ((line: string) => console.error(line));
97
+ const maxRestarts = options.maxRestarts ?? 5;
98
+ const restartWindowMs = options.restartWindowMs ?? 60_000;
99
+ const stopTimeoutMs = options.stopTimeoutMs ?? 15_000;
100
+ const baseDelayMs = options.restartDelayMs ?? 1000;
101
+
102
+ let child: Subprocess | null = null;
103
+ let stopping = false;
104
+ const restarts: number[] = [];
105
+ let resolveDone!: (code: number) => void;
106
+ const done = new Promise<number>((resolve) => (resolveDone = resolve));
107
+
108
+ const spawnChild = () => {
109
+ child = Bun.spawn(options.cmd, {
110
+ cwd: options.cwd,
111
+ // The child stops itself if this supervisor disappears without stopping
112
+ // it (see watchSupervisor) — killed outright, a terminal runner's own
113
+ // SIGKILL — instead of running on, unowned, holding its port.
114
+ env: { ...(options.env ?? process.env), [SUPERVISOR_PID_ENV]: String(process.pid) } as Record<string, string>,
115
+ stdin: 'ignore',
116
+ stdout: options.onStdout ? 'pipe' : 'inherit',
117
+ stderr: options.onStderr ? 'pipe' : 'inherit',
118
+ // Own process group on POSIX — see the module comment.
119
+ ...(IS_WINDOWS ? {} : { detached: true })
120
+ } as Parameters<typeof Bun.spawn>[1]) as Subprocess;
121
+
122
+ const current = child;
123
+ if (options.onStdout) void pump(current.stdout as ReadableStream<Uint8Array>, options.onStdout);
124
+ if (options.onStderr) void pump(current.stderr as ReadableStream<Uint8Array>, options.onStderr);
125
+
126
+ void current.exited.then(async (code) => {
127
+ if (child !== current) return;
128
+ const signal = current.signalCode ?? null;
129
+ if (stopping) {
130
+ // The child is out; what it started may still be shutting down.
131
+ const survivors = await waitForExit(stopTree, Math.max(0, stopDeadline - Date.now()));
132
+ if (survivors.length > 0) {
133
+ signalAll(survivors, 'SIGKILL');
134
+ await waitForExit(survivors, 2000);
135
+ }
136
+ resolveDone(code ?? (signal ? 1 : 0));
137
+ return;
138
+ }
139
+
140
+ const now = Date.now();
141
+ while (restarts.length > 0 && now - restarts[0] > restartWindowMs) restarts.shift();
142
+ const description = signal ? `signal ${signal}` : `code ${code}`;
143
+ const report = await diagnose(options.name, description, current.pid);
144
+ log(report);
145
+ if (options.reportFile) writeReport(options.reportFile, report);
146
+
147
+ if (restarts.length >= maxRestarts) {
148
+ log(`[${options.name}] exited ${restarts.length + 1} times within ${restartWindowMs / 1000}s — not restarting.`);
149
+ resolveDone(code ?? 1);
150
+ return;
151
+ }
152
+ restarts.push(now);
153
+ const delay = Math.min(baseDelayMs * 2 ** (restarts.length - 1), 10_000);
154
+ log(`[${options.name}] stopped unexpectedly (${description}); restarting in ${delay / 1000}s…`);
155
+ setTimeout(() => {
156
+ if (!stopping) spawnChild();
157
+ }, delay);
158
+ });
159
+ };
160
+
161
+ const signalGroup = (signal: NodeJS.Signals) => {
162
+ const pid = child?.pid;
163
+ if (!pid || child?.exitCode !== null) return;
164
+ try {
165
+ // The whole group — the child and whatever it started — like a terminal would.
166
+ if (IS_WINDOWS) process.kill(pid, signal);
167
+ else process.kill(-pid, signal);
168
+ } catch {
169
+ try {
170
+ process.kill(pid, signal);
171
+ } catch {
172
+ // Already gone.
173
+ }
174
+ }
175
+ };
176
+
177
+ /** The child's descendants when the stop began, and when the stop gives up waiting. */
178
+ let stopTree: number[] = [];
179
+ let stopDeadline = 0;
180
+
181
+ /** Begin stopping: remember everything the child started, before signalling it. */
182
+ const beginStop = (): boolean => {
183
+ if (stopping) return false;
184
+ stopping = true;
185
+ stopDeadline = Date.now() + stopTimeoutMs;
186
+ if (!child || child.exitCode !== null || child.signalCode !== null) {
187
+ resolveDone(child?.exitCode ?? 0);
188
+ return false;
189
+ }
190
+ stopTree = collectDescendants(child.pid);
191
+ return true;
192
+ };
193
+
194
+ const forceKill = () => {
195
+ signalGroup('SIGKILL');
196
+ signalAll(stopTree, 'SIGKILL');
197
+ };
198
+
199
+ const stop = (signal: NodeJS.Signals = 'SIGTERM'): Promise<number> => {
200
+ if (!beginStop()) return done;
201
+ // On Windows the child shares the console, so Ctrl+C already reached it;
202
+ // forwarding would terminate it outright instead of letting it shut down.
203
+ if (!(IS_WINDOWS && signal === 'SIGINT')) signalGroup(signal);
204
+ const timer = setTimeout(forceKill, stopTimeoutMs);
205
+ timer.unref?.();
206
+ void done.then(() => clearTimeout(timer));
207
+ return done;
208
+ };
209
+
210
+ const kill = (): Promise<number> => {
211
+ beginStop();
212
+ forceKill();
213
+ return done;
214
+ };
215
+
216
+ spawnChild();
217
+ return { done, stop, kill };
218
+ }
219
+
220
+ /**
221
+ * Forward termination signals to a set of supervisors and exit once they are
222
+ * all down, with the first non-zero code. Returns a function that stops them
223
+ * the same way (for callers that end on their own terms).
224
+ */
225
+ /** Set once a signal asked the supervisors to stop; that handler then owns the exit. */
226
+ let signalStopRequested = false;
227
+
228
+ /** Whether a signal (Ctrl+C, SIGTERM, a closed terminal) is stopping everything. */
229
+ export function stopRequestedBySignal(): boolean {
230
+ return signalStopRequested;
231
+ }
232
+
233
+ export function stopOnSignals(supervisors: Supervisor[]): (signal?: NodeJS.Signals) => Promise<number> {
234
+ const stopAll = async (signal: NodeJS.Signals = 'SIGTERM') => {
235
+ const codes = await Promise.all(supervisors.map((s) => s.stop(signal)));
236
+ return codes.find((code) => code !== 0) ?? 0;
237
+ };
238
+ // Ctrl+C reaches the whole foreground group. Under `bun run` that is the
239
+ // runner AND this process, and the runner forwards its copy — so the first
240
+ // press arrives twice, 1 ms apart (later presses once). That copy is not a
241
+ // second press: treating it as one used to SIGKILL every child on a single
242
+ // Ctrl+C, and `bun run`, on its own second SIGINT, then killed this process
243
+ // and returned the prompt with the children orphaned and their ports held.
244
+ // Set at the end, once every handler is in place (see there).
245
+ let runnerCopyPending = false;
246
+ let presses = 0;
247
+ const log = (line: string) => {
248
+ try {
249
+ process.stderr.write(`${line}\n`);
250
+ } catch {
251
+ // The terminal is gone.
252
+ }
253
+ };
254
+ const begin = (signal: NodeJS.Signals) => {
255
+ signalStopRequested = true;
256
+ log('\nStopping… (press Ctrl+C again to force)');
257
+ // A stop that was asked for and completed is a clean exit, whatever
258
+ // code the children ended with on the way (130 after SIGINT made `bun
259
+ // run` report the stop as an error). Forced, it reports the interrupt.
260
+ void stopAll(signal).then(() => process.exit(presses > 1 ? 130 : 0));
261
+ };
262
+ for (const signal of ['SIGINT', 'SIGTERM'] as const) {
263
+ process.on(signal, () => {
264
+ if (signal === 'SIGINT' && presses === 1 && runnerCopyPending) {
265
+ runnerCopyPending = false;
266
+ return;
267
+ }
268
+ presses++;
269
+ if (presses === 1) {
270
+ begin(signal);
271
+ return;
272
+ }
273
+ // A second press means "stop waiting": everything goes now, and the
274
+ // exit still waits until it is gone.
275
+ log('Forcing stop…');
276
+ for (const supervisor of supervisors) void supervisor.kill();
277
+ });
278
+ }
279
+ // The terminal closed. Started from one, everything goes with it — leaving
280
+ // a server running behind a closed tab is what users did not expect. Run in
281
+ // the background (`nohup`, a service: no terminal on stdout), it keeps going.
282
+ const startedInTerminal = process.stdout.isTTY === true;
283
+ process.on('SIGHUP', () => {
284
+ if (!startedInTerminal || presses > 0) return;
285
+ presses++;
286
+ begin('SIGTERM');
287
+ });
288
+ for (const stream of [process.stdout, process.stderr]) {
289
+ stream.on('error', () => {
290
+ // EIO/EPIPE once the terminal is gone — nothing left to write to.
291
+ });
292
+ }
293
+ // Only now, with every handler installed: this runs `ps`, and until a
294
+ // handler exists a signal takes its default action — SIGHUP or SIGINT
295
+ // killed this process outright and left the child running unsupervised.
296
+ // A signal that arrives meanwhile is queued, and its handler runs after
297
+ // this returns, so it still sees the right value.
298
+ runnerCopyPending = parentForwardsSignals();
299
+ return stopAll;
300
+ }
301
+
302
+ async function pump(stream: ReadableStream<Uint8Array>, sink: (chunk: Uint8Array) => void): Promise<void> {
303
+ const reader = stream.getReader();
304
+ try {
305
+ for (;;) {
306
+ const { done, value } = await reader.read();
307
+ if (done) return;
308
+ if (value) sink(value);
309
+ }
310
+ } catch {
311
+ // The stream closes with the process.
312
+ } finally {
313
+ reader.releaseLock();
314
+ }
315
+ }
316
+
317
+ /** What was running when a child died — processes started in the last 10 minutes. */
318
+ async function diagnose(name: string, description: string, pid: number): Promise<string> {
319
+ const lines = [`[${name}] pid ${pid} exited without being asked to (${description}) at ${new Date().toISOString()}.`];
320
+ if (IS_WINDOWS) return lines.join('\n');
321
+ try {
322
+ const ps = Bun.spawn(['ps', '-A', '-o', 'pid=,ppid=,pgid=,etime=,command='], { stdout: 'pipe', stderr: 'ignore' });
323
+ const output = await new Response(ps.stdout).text();
324
+ const recent = output
325
+ .split('\n')
326
+ .map((line) => line.trim())
327
+ .filter(Boolean)
328
+ .filter((line) => {
329
+ const etime = line.split(/\s+/)[3] ?? '';
330
+ return elapsedSeconds(etime) <= 600;
331
+ })
332
+ .map((line) => (line.length > 220 ? `${line.slice(0, 220)}…` : line));
333
+ lines.push('Processes started in the last 10 minutes (pid ppid pgid elapsed command):', ...recent.map((line) => ` ${line}`));
334
+ } catch {
335
+ lines.push('(process list unavailable)');
336
+ }
337
+ return lines.join('\n');
338
+ }
339
+
340
+ /** `ps` elapsed time ([[dd-]hh:]mm:ss) in seconds. */
341
+ export function elapsedSeconds(etime: string): number {
342
+ const [daysPart, clock] = etime.includes('-') ? etime.split('-') : ['0', etime];
343
+ const parts = clock.split(':').map(Number);
344
+ if (parts.some((part) => !Number.isFinite(part))) return Number.POSITIVE_INFINITY;
345
+ const [h, m, s] = parts.length === 3 ? parts : [0, parts[0] ?? 0, parts[1] ?? 0];
346
+ return Number(daysPart) * 86_400 + h * 3600 + m * 60 + s;
347
+ }
348
+
349
+ function writeReport(file: string, report: string): void {
350
+ try {
351
+ mkdirSync(dirname(file), { recursive: true });
352
+ appendFileSync(file, `${report}\n\n`);
353
+ } catch {
354
+ // A report that cannot be written must not take the supervisor down.
355
+ }
356
+ }