@myrialabs/clopen 0.4.49 → 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.
- package/backend/chat/background-wait.test.ts +28 -0
- package/backend/chat/message-pages.test.ts +17 -0
- package/backend/chat/message-pages.ts +6 -2
- package/backend/chat/stream-manager.ts +73 -14
- package/backend/database/migrations/088_create_messages_fts_map.ts +52 -0
- package/backend/database/migrations/089_add_memory_layout_tiles.ts +58 -0
- package/backend/database/migrations/index.ts +14 -0
- package/backend/database/queries/graph-queries.ts +392 -135
- package/backend/database/queries/message-fts.test.ts +120 -0
- package/backend/database/queries/message-queries.ts +45 -9
- package/backend/database/queries/session-queries.ts +3 -2
- package/backend/database/queries/utils-queries.ts +3 -0
- package/backend/engine/adapters/claude/environment.ts +4 -0
- package/backend/engine/adapters/claude/input-gate.test.ts +59 -0
- package/backend/engine/adapters/claude/input-gate.ts +74 -0
- package/backend/engine/adapters/claude/message-converter.test.ts +16 -0
- package/backend/engine/adapters/claude/message-converter.ts +8 -0
- package/backend/engine/adapters/claude/stream.ts +15 -0
- package/backend/git/identity/scope-config.test.ts +7 -4
- package/backend/index.ts +35 -8
- package/backend/memory/README.md +7 -4
- package/backend/memory/layout.test.ts +377 -0
- package/backend/memory/layout.ts +1029 -265
- package/backend/memory/view.ts +257 -386
- package/backend/project/status-manager.ts +4 -2
- package/backend/ws/chat/stream.ts +19 -10
- package/backend/ws/memory/crud.ts +118 -81
- package/backend/ws/messages/crud.ts +3 -1
- package/bin/clopen.ts +3 -2
- package/dist/assets/{index-DD0-3EWg.js → index-By6KdSLT.js} +1 -1
- package/dist/assets/index-By6KdSLT.js.br +0 -0
- package/dist/assets/index-By6KdSLT.js.gz +0 -0
- package/dist/assets/{index-CrVWZH_D.js → index-DV4TiDn1.js} +1 -1
- package/dist/assets/index-DV4TiDn1.js.br +0 -0
- package/dist/assets/index-DV4TiDn1.js.gz +0 -0
- package/dist/assets/main-DIESTGTD.css +1 -0
- package/dist/assets/main-DIESTGTD.css.br +0 -0
- package/dist/assets/main-DIESTGTD.css.gz +0 -0
- package/dist/assets/{main-D2_TmcwQ.js → main-Da3JKoua.js} +612 -612
- package/dist/assets/main-Da3JKoua.js.br +0 -0
- package/dist/assets/main-Da3JKoua.js.gz +0 -0
- package/dist/index.html +2 -2
- package/dist/index.html.br +0 -0
- package/dist/index.html.gz +0 -0
- package/package.json +3 -3
- package/shared/types/memory.ts +96 -73
- package/shared/types/unified/index.ts +1 -0
- package/shared/types/unified/stream.ts +22 -1
- package/shared/utils/process-supervisor.test.ts +71 -1
- package/shared/utils/process-supervisor.ts +134 -29
- package/shared/utils/process-tree.ts +99 -0
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +0 -1
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
- package/dist/assets/index-CrVWZH_D.js.br +0 -0
- package/dist/assets/index-CrVWZH_D.js.gz +0 -0
- package/dist/assets/index-DD0-3EWg.js.br +0 -0
- package/dist/assets/index-DD0-3EWg.js.gz +0 -0
- package/dist/assets/main-D2_TmcwQ.js.br +0 -0
- package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
- package/dist/assets/main-Yucigcmf.css +0 -1
- package/dist/assets/main-Yucigcmf.css.br +0 -0
- package/dist/assets/main-Yucigcmf.css.gz +0 -0
|
Binary file
|
|
Binary file
|
package/dist/index.html
CHANGED
|
@@ -63,8 +63,8 @@
|
|
|
63
63
|
}
|
|
64
64
|
})();
|
|
65
65
|
</script>
|
|
66
|
-
<script type="module" crossorigin src="/assets/main-
|
|
67
|
-
<link rel="stylesheet" crossorigin href="/assets/main-
|
|
66
|
+
<script type="module" crossorigin src="/assets/main-Da3JKoua.js"></script>
|
|
67
|
+
<link rel="stylesheet" crossorigin href="/assets/main-DIESTGTD.css">
|
|
68
68
|
</head>
|
|
69
69
|
<body
|
|
70
70
|
class="min-h-dvh bg-white text-slate-900 dark:bg-slate-950 dark:text-slate-100 transition-colors duration-200"
|
package/dist/index.html.br
CHANGED
|
Binary file
|
package/dist/index.html.gz
CHANGED
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@myrialabs/clopen",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.50",
|
|
4
4
|
"description": "All-in-one web workspace for AI coding agents — Claude Code, OpenCode, Codex, Copilot, Qwen Code, Pi, Cline, and Cursor — with chat, terminal, git, browser preview, database client, checkpoints, and real-time collaboration",
|
|
5
5
|
"author": "Myria Labs",
|
|
6
6
|
"license": "MIT",
|
|
@@ -123,8 +123,8 @@
|
|
|
123
123
|
"@modelcontextprotocol/sdk": "1.31.0",
|
|
124
124
|
"@monaco-editor/loader": "1.7.0",
|
|
125
125
|
"@myrialabs/chatkit": "0.0.3",
|
|
126
|
-
"@myrialabs/ptykit": "0.1.
|
|
127
|
-
"@myrialabs/tunnelkit": "0.0
|
|
126
|
+
"@myrialabs/ptykit": "0.1.1",
|
|
127
|
+
"@myrialabs/tunnelkit": "0.1.0",
|
|
128
128
|
"@myrialabs/zipkit": "0.0.11",
|
|
129
129
|
"@sinclair/typebox": "0.34.48",
|
|
130
130
|
"@xyflow/svelte": "1.6.2",
|
package/shared/types/memory.ts
CHANGED
|
@@ -351,40 +351,19 @@ export interface RetrievalResult {
|
|
|
351
351
|
// Visualization
|
|
352
352
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
353
353
|
|
|
354
|
-
/**
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
pinned: boolean;
|
|
365
|
-
/** Louvain community index — the "lobe" a node belongs to. */
|
|
366
|
-
community: number;
|
|
367
|
-
createdAt: string;
|
|
368
|
-
/**
|
|
369
|
-
* Where the persisted layout put this node, when it has been laid out.
|
|
370
|
-
*
|
|
371
|
-
* Absent means "no position yet" — a memory written since the last layout
|
|
372
|
-
* pass — and the client seeds those from their neighbours rather than
|
|
373
|
-
* re-solving the whole graph. See `backend/memory/layout.ts`.
|
|
374
|
-
*/
|
|
375
|
-
x?: number;
|
|
376
|
-
y?: number;
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
export interface GraphViewEdge {
|
|
380
|
-
id: number;
|
|
381
|
-
source: string;
|
|
382
|
-
target: string;
|
|
383
|
-
rel: GraphRelation;
|
|
384
|
-
weight: number;
|
|
354
|
+
/**
|
|
355
|
+
* The square the graph view is cut into tiles from, in layout coordinates.
|
|
356
|
+
*
|
|
357
|
+
* Fixed between layout passes that change the map, so a tile's address means
|
|
358
|
+
* the same rectangle for as long as the client's `epoch` matches the server's.
|
|
359
|
+
*/
|
|
360
|
+
export interface GraphWorld {
|
|
361
|
+
minX: number;
|
|
362
|
+
minY: number;
|
|
363
|
+
size: number;
|
|
385
364
|
}
|
|
386
365
|
|
|
387
|
-
/** A rectangle in layout space
|
|
366
|
+
/** A rectangle in layout space. */
|
|
388
367
|
export interface GraphRegion {
|
|
389
368
|
minX: number;
|
|
390
369
|
maxX: number;
|
|
@@ -393,65 +372,109 @@ export interface GraphRegion {
|
|
|
393
372
|
}
|
|
394
373
|
|
|
395
374
|
/**
|
|
396
|
-
*
|
|
375
|
+
* Everything the view needs before it can ask for a single tile.
|
|
397
376
|
*
|
|
398
|
-
*
|
|
399
|
-
*
|
|
400
|
-
*
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
377
|
+
* The counts are the FILTER's, not the screen's: how many memories match, how
|
|
378
|
+
* many of those have a place on the map, and where they are — which is what
|
|
379
|
+
* "Fit" frames.
|
|
380
|
+
*/
|
|
381
|
+
export interface GraphViewMeta {
|
|
382
|
+
/** Changes whenever the world does; a tile from another epoch is from another map. */
|
|
383
|
+
epoch: number;
|
|
384
|
+
/** Changes whenever a layout pass writes; tiles from an older stamp may be missing memories. */
|
|
385
|
+
stamp: number;
|
|
386
|
+
/** Null until the first layout pass has placed anything. */
|
|
387
|
+
world: GraphWorld | null;
|
|
388
|
+
/** Median distance between a memory and its nearest neighbour, in layout units. */
|
|
389
|
+
spacing: number;
|
|
390
|
+
/** Memories matching the filter. */
|
|
391
|
+
total: number;
|
|
392
|
+
/** Of those, how many have no position yet — they appear once a pass places them. */
|
|
393
|
+
unplaced: number;
|
|
394
|
+
/** Where the placed matches are; null when none are. */
|
|
395
|
+
extent: GraphRegion | null;
|
|
396
|
+
/** The degree that counts as "fully connected" when sizing nodes; see `degreeScale`. */
|
|
397
|
+
degreeScale: number;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** A memory as a tile carries it: enough to draw and hover, nothing to inspect. */
|
|
401
|
+
export interface GraphTileNode {
|
|
402
|
+
id: string;
|
|
403
|
+
label: string;
|
|
404
|
+
/** Louvain community index — the "lobe" a node belongs to, and its colour. */
|
|
405
|
+
community: number;
|
|
406
|
+
/** Connections in the whole graph, stored and derived. Sizes the node. */
|
|
407
|
+
degree: number;
|
|
408
|
+
x: number;
|
|
409
|
+
y: number;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Several memories sharing one cell of a crowded tile, drawn as one mark.
|
|
406
414
|
*
|
|
407
|
-
*
|
|
408
|
-
*
|
|
409
|
-
*
|
|
415
|
+
* Only a tile with more memories than its budget is folded like this, and only
|
|
416
|
+
* where a cell holds more than one; zooming in asks for smaller tiles, which
|
|
417
|
+
* fit, so a cluster always resolves into its memories by zooming alone.
|
|
410
418
|
*/
|
|
411
|
-
export interface
|
|
412
|
-
/** `
|
|
419
|
+
export interface GraphTileCluster {
|
|
420
|
+
/** `cluster:<z>:<cellX>:<cellY>` — namespaced so it cannot collide with a node id. */
|
|
413
421
|
id: string;
|
|
414
|
-
/** How many memories it stands for; drives its size. */
|
|
415
422
|
members: number;
|
|
416
423
|
/** The most reinforced member's summary, for the hover pill. */
|
|
417
424
|
label: string;
|
|
418
425
|
/** Community of that same member, so the mark keeps its lobe's colour. */
|
|
419
426
|
community: number;
|
|
420
|
-
/** Centroid of
|
|
427
|
+
/** Centroid of the members. */
|
|
421
428
|
x: number;
|
|
422
429
|
y: number;
|
|
423
|
-
/** The cell
|
|
424
|
-
|
|
430
|
+
/** The cell, in global cell coordinates at this tile's zoom. */
|
|
431
|
+
cellX: number;
|
|
432
|
+
cellY: number;
|
|
425
433
|
}
|
|
426
434
|
|
|
427
|
-
/**
|
|
428
|
-
|
|
435
|
+
/**
|
|
436
|
+
* An edge from one of a tile's memories, with where its far end sits.
|
|
437
|
+
*
|
|
438
|
+
* The far end may be in a tile the client has not loaded, or folded into a
|
|
439
|
+
* cluster there — its position is what lets the client attach the edge to
|
|
440
|
+
* whichever mark currently stands for it.
|
|
441
|
+
*/
|
|
442
|
+
export interface GraphTileEdge {
|
|
429
443
|
source: string;
|
|
430
444
|
target: string;
|
|
431
445
|
weight: number;
|
|
446
|
+
targetX: number;
|
|
447
|
+
targetY: number;
|
|
432
448
|
}
|
|
433
449
|
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
450
|
+
/** An edge out of a crowded tile, rolled up to the cell it lands in. */
|
|
451
|
+
export interface GraphTileCellEdge {
|
|
452
|
+
/** The mark in this tile it leaves from — a cluster id or a memory id. */
|
|
453
|
+
source: string;
|
|
454
|
+
targetCellX: number;
|
|
455
|
+
targetCellY: number;
|
|
456
|
+
weight: number;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** One square of the map at one zoom level. */
|
|
460
|
+
export interface GraphTile {
|
|
461
|
+
z: number;
|
|
462
|
+
x: number;
|
|
463
|
+
y: number;
|
|
464
|
+
/** Cells per tile side when this tile was folded; 0 when it was not. */
|
|
465
|
+
cells: number;
|
|
466
|
+
nodes: GraphTileNode[];
|
|
467
|
+
clusters: GraphTileCluster[];
|
|
468
|
+
edges: GraphTileEdge[];
|
|
469
|
+
cellEdges: GraphTileCellEdge[];
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
export interface GraphTilesResponse {
|
|
473
|
+
/** The server's epoch. When it is not the one asked about, `stale` is set. */
|
|
474
|
+
epoch: number;
|
|
475
|
+
/** The map changed since the client last read the meta; nothing was served. */
|
|
476
|
+
stale: boolean;
|
|
477
|
+
tiles: GraphTile[];
|
|
455
478
|
}
|
|
456
479
|
|
|
457
480
|
/**
|
|
@@ -156,6 +156,26 @@ export interface NotificationEvent {
|
|
|
156
156
|
message: string;
|
|
157
157
|
}
|
|
158
158
|
|
|
159
|
+
/**
|
|
160
|
+
* The background work an engine is still running for this stream — commands or
|
|
161
|
+
* agents it started without waiting for them — as the COMPLETE current list
|
|
162
|
+
* (empty once everything finished).
|
|
163
|
+
*
|
|
164
|
+
* Some engines start a turn on their own when such work finishes, after the
|
|
165
|
+
* turn that started it already ended (Claude Code; Open Code with background
|
|
166
|
+
* sub-agents enabled). Others hold their completion signal until it is done
|
|
167
|
+
* (Qwen Code holds `result`, Copilot holds `session.idle`), and Codex, Cursor,
|
|
168
|
+
* Pi and Cline have no such work; those never emit this. An adapter that does
|
|
169
|
+
* must keep its stream — and its channel back to Clopen for tools and
|
|
170
|
+
* permissions — open until the list is empty and the engine is idle. The
|
|
171
|
+
* stream manager shows the gap between turns as "waiting for background work".
|
|
172
|
+
*/
|
|
173
|
+
export interface BackgroundWorkEvent {
|
|
174
|
+
type: 'background_work';
|
|
175
|
+
sessionId: string;
|
|
176
|
+
tasks: Array<{ id: string; description?: string }>;
|
|
177
|
+
}
|
|
178
|
+
|
|
159
179
|
// ============================================================
|
|
160
180
|
// Engine Output
|
|
161
181
|
// ============================================================
|
|
@@ -173,7 +193,8 @@ export type EngineOutput =
|
|
|
173
193
|
| ResultEvent
|
|
174
194
|
| SystemInitEvent
|
|
175
195
|
| RateLimitEvent
|
|
176
|
-
| NotificationEvent
|
|
196
|
+
| NotificationEvent
|
|
197
|
+
| BackgroundWorkEvent;
|
|
177
198
|
|
|
178
199
|
// ============================================================
|
|
179
200
|
// Stream Transport (WebSocket layer)
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { afterAll, describe, expect, test } from 'bun:test';
|
|
9
|
-
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
9
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
10
10
|
import { tmpdir } from 'node:os';
|
|
11
11
|
import { join } from 'node:path';
|
|
12
12
|
|
|
@@ -96,6 +96,76 @@ describe.if(posix)('supervise', () => {
|
|
|
96
96
|
expect(() => process.kill(grandchild, 0)).toThrow(); // the grandchild went with it
|
|
97
97
|
});
|
|
98
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
|
+
|
|
99
169
|
test('gives up on a child that keeps dying', async () => {
|
|
100
170
|
const s = supervise({ name: 't', cmd: ['sh', '-c', 'exit 3'], log: () => {}, restartDelayMs: 10, maxRestarts: 2 });
|
|
101
171
|
expect(await s.done).toBe(3);
|
|
@@ -12,13 +12,19 @@
|
|
|
12
12
|
* the difference: a server that received a stray SIGTERM shuts down cleanly
|
|
13
13
|
* and exits 0. What can is whether this supervisor asked it to stop. A child
|
|
14
14
|
* that keeps dying (5 times in 60 s) is given up on instead of looping.
|
|
15
|
-
* - **Stopped on request.** SIGINT/SIGTERM to the supervisor are
|
|
16
|
-
* the child's whole group — what a terminal did before the
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
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.
|
|
22
28
|
* - **Diagnosed.** Each unrequested exit is logged with its code or signal and
|
|
23
29
|
* the processes started shortly before it (pid, ppid, pgid, command), to the
|
|
24
30
|
* console and to `reportFile`, so the next occurrence leaves a trail. The OS
|
|
@@ -28,6 +34,7 @@
|
|
|
28
34
|
|
|
29
35
|
import { appendFileSync, mkdirSync } from 'node:fs';
|
|
30
36
|
import { dirname } from 'node:path';
|
|
37
|
+
import { collectDescendants, parentForwardsSignals, signalAll, waitForExit } from './process-tree';
|
|
31
38
|
|
|
32
39
|
type Subprocess = ReturnType<typeof Bun.spawn>;
|
|
33
40
|
|
|
@@ -62,6 +69,28 @@ export interface Supervisor {
|
|
|
62
69
|
|
|
63
70
|
const IS_WINDOWS = process.platform === 'win32';
|
|
64
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
|
+
|
|
65
94
|
/** Run `options.cmd` under supervision until it is stopped. */
|
|
66
95
|
export function supervise(options: SupervisedProcessOptions): Supervisor {
|
|
67
96
|
const log = options.log ?? ((line: string) => console.error(line));
|
|
@@ -79,7 +108,10 @@ export function supervise(options: SupervisedProcessOptions): Supervisor {
|
|
|
79
108
|
const spawnChild = () => {
|
|
80
109
|
child = Bun.spawn(options.cmd, {
|
|
81
110
|
cwd: options.cwd,
|
|
82
|
-
|
|
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>,
|
|
83
115
|
stdin: 'ignore',
|
|
84
116
|
stdout: options.onStdout ? 'pipe' : 'inherit',
|
|
85
117
|
stderr: options.onStderr ? 'pipe' : 'inherit',
|
|
@@ -95,7 +127,13 @@ export function supervise(options: SupervisedProcessOptions): Supervisor {
|
|
|
95
127
|
if (child !== current) return;
|
|
96
128
|
const signal = current.signalCode ?? null;
|
|
97
129
|
if (stopping) {
|
|
98
|
-
|
|
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));
|
|
99
137
|
return;
|
|
100
138
|
}
|
|
101
139
|
|
|
@@ -136,25 +174,42 @@ export function supervise(options: SupervisedProcessOptions): Supervisor {
|
|
|
136
174
|
}
|
|
137
175
|
};
|
|
138
176
|
|
|
139
|
-
|
|
140
|
-
|
|
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;
|
|
141
184
|
stopping = true;
|
|
142
|
-
|
|
185
|
+
stopDeadline = Date.now() + stopTimeoutMs;
|
|
186
|
+
if (!child || child.exitCode !== null || child.signalCode !== null) {
|
|
143
187
|
resolveDone(child?.exitCode ?? 0);
|
|
144
|
-
|
|
145
|
-
// On Windows the child shares the console, so Ctrl+C already reached it;
|
|
146
|
-
// forwarding would terminate it outright instead of letting it shut down.
|
|
147
|
-
if (!(IS_WINDOWS && signal === 'SIGINT')) signalGroup(signal);
|
|
148
|
-
const timer = setTimeout(() => signalGroup('SIGKILL'), stopTimeoutMs);
|
|
149
|
-
timer.unref?.();
|
|
150
|
-
void done.then(() => clearTimeout(timer));
|
|
188
|
+
return false;
|
|
151
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));
|
|
152
207
|
return done;
|
|
153
208
|
};
|
|
154
209
|
|
|
155
210
|
const kill = (): Promise<number> => {
|
|
156
|
-
|
|
157
|
-
|
|
211
|
+
beginStop();
|
|
212
|
+
forceKill();
|
|
158
213
|
return done;
|
|
159
214
|
};
|
|
160
215
|
|
|
@@ -167,30 +222,80 @@ export function supervise(options: SupervisedProcessOptions): Supervisor {
|
|
|
167
222
|
* all down, with the first non-zero code. Returns a function that stops them
|
|
168
223
|
* the same way (for callers that end on their own terms).
|
|
169
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
|
+
|
|
170
233
|
export function stopOnSignals(supervisors: Supervisor[]): (signal?: NodeJS.Signals) => Promise<number> {
|
|
171
234
|
const stopAll = async (signal: NodeJS.Signals = 'SIGTERM') => {
|
|
172
235
|
const codes = await Promise.all(supervisors.map((s) => s.stop(signal)));
|
|
173
236
|
return codes.find((code) => code !== 0) ?? 0;
|
|
174
237
|
};
|
|
175
|
-
|
|
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
|
+
};
|
|
176
262
|
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
|
177
263
|
process.on(signal, () => {
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
264
|
+
if (signal === 'SIGINT' && presses === 1 && runnerCopyPending) {
|
|
265
|
+
runnerCopyPending = false;
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
presses++;
|
|
269
|
+
if (presses === 1) {
|
|
270
|
+
begin(signal);
|
|
182
271
|
return;
|
|
183
272
|
}
|
|
184
|
-
|
|
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();
|
|
185
277
|
});
|
|
186
278
|
}
|
|
187
|
-
// The terminal closed
|
|
188
|
-
|
|
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
|
+
});
|
|
189
288
|
for (const stream of [process.stdout, process.stderr]) {
|
|
190
289
|
stream.on('error', () => {
|
|
191
290
|
// EIO/EPIPE once the terminal is gone — nothing left to write to.
|
|
192
291
|
});
|
|
193
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();
|
|
194
299
|
return stopAll;
|
|
195
300
|
}
|
|
196
301
|
|