@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.
Files changed (63) hide show
  1. package/backend/chat/background-wait.test.ts +28 -0
  2. package/backend/chat/message-pages.test.ts +17 -0
  3. package/backend/chat/message-pages.ts +6 -2
  4. package/backend/chat/stream-manager.ts +73 -14
  5. package/backend/database/migrations/088_create_messages_fts_map.ts +52 -0
  6. package/backend/database/migrations/089_add_memory_layout_tiles.ts +58 -0
  7. package/backend/database/migrations/index.ts +14 -0
  8. package/backend/database/queries/graph-queries.ts +392 -135
  9. package/backend/database/queries/message-fts.test.ts +120 -0
  10. package/backend/database/queries/message-queries.ts +45 -9
  11. package/backend/database/queries/session-queries.ts +3 -2
  12. package/backend/database/queries/utils-queries.ts +3 -0
  13. package/backend/engine/adapters/claude/environment.ts +4 -0
  14. package/backend/engine/adapters/claude/input-gate.test.ts +59 -0
  15. package/backend/engine/adapters/claude/input-gate.ts +74 -0
  16. package/backend/engine/adapters/claude/message-converter.test.ts +16 -0
  17. package/backend/engine/adapters/claude/message-converter.ts +8 -0
  18. package/backend/engine/adapters/claude/stream.ts +15 -0
  19. package/backend/git/identity/scope-config.test.ts +7 -4
  20. package/backend/index.ts +35 -8
  21. package/backend/memory/README.md +7 -4
  22. package/backend/memory/layout.test.ts +377 -0
  23. package/backend/memory/layout.ts +1029 -265
  24. package/backend/memory/view.ts +257 -386
  25. package/backend/project/status-manager.ts +4 -2
  26. package/backend/ws/chat/stream.ts +19 -10
  27. package/backend/ws/memory/crud.ts +118 -81
  28. package/backend/ws/messages/crud.ts +3 -1
  29. package/bin/clopen.ts +3 -2
  30. package/dist/assets/{index-DD0-3EWg.js → index-By6KdSLT.js} +1 -1
  31. package/dist/assets/index-By6KdSLT.js.br +0 -0
  32. package/dist/assets/index-By6KdSLT.js.gz +0 -0
  33. package/dist/assets/{index-CrVWZH_D.js → index-DV4TiDn1.js} +1 -1
  34. package/dist/assets/index-DV4TiDn1.js.br +0 -0
  35. package/dist/assets/index-DV4TiDn1.js.gz +0 -0
  36. package/dist/assets/main-DIESTGTD.css +1 -0
  37. package/dist/assets/main-DIESTGTD.css.br +0 -0
  38. package/dist/assets/main-DIESTGTD.css.gz +0 -0
  39. package/dist/assets/{main-D2_TmcwQ.js → main-Da3JKoua.js} +612 -612
  40. package/dist/assets/main-Da3JKoua.js.br +0 -0
  41. package/dist/assets/main-Da3JKoua.js.gz +0 -0
  42. package/dist/index.html +2 -2
  43. package/dist/index.html.br +0 -0
  44. package/dist/index.html.gz +0 -0
  45. package/package.json +3 -3
  46. package/shared/types/memory.ts +96 -73
  47. package/shared/types/unified/index.ts +1 -0
  48. package/shared/types/unified/stream.ts +22 -1
  49. package/shared/utils/process-supervisor.test.ts +71 -1
  50. package/shared/utils/process-supervisor.ts +134 -29
  51. package/shared/utils/process-tree.ts +99 -0
  52. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +0 -1
  53. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
  54. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
  55. package/dist/assets/index-CrVWZH_D.js.br +0 -0
  56. package/dist/assets/index-CrVWZH_D.js.gz +0 -0
  57. package/dist/assets/index-DD0-3EWg.js.br +0 -0
  58. package/dist/assets/index-DD0-3EWg.js.gz +0 -0
  59. package/dist/assets/main-D2_TmcwQ.js.br +0 -0
  60. package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
  61. package/dist/assets/main-Yucigcmf.css +0 -1
  62. package/dist/assets/main-Yucigcmf.css.br +0 -0
  63. package/dist/assets/main-Yucigcmf.css.gz +0 -0
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The messages_fts index stays in step with messages through every write and
3
+ * delete path, and every delete finds its rows through messages_fts_map
4
+ * (by rowid) instead of scanning the index for a message id.
5
+ */
6
+
7
+ import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
8
+ import { initializeDatabase, closeDatabase, getDatabase } from '$backend/database';
9
+ import { messageQueries, projectQueries, sessionQueries } from '$backend/database/queries';
10
+ import type { UnifiedMessage } from '$shared/types/unified';
11
+
12
+ let projectId: string;
13
+
14
+ const engine = { type: 'claude-code', provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } };
15
+ const user = (text: string) => ({
16
+ type: 'user',
17
+ createdAt: '',
18
+ messageId: '',
19
+ sessionId: null,
20
+ parent: { messageId: null, sessionId: null, toolUseId: null },
21
+ engine,
22
+ content: [{ type: 'text', text }]
23
+ }) as unknown as UnifiedMessage;
24
+
25
+ function newSession(): string {
26
+ return sessionQueries.create({ project_id: projectId, engine: 'claude-code', started_at: new Date().toISOString() } as never).id;
27
+ }
28
+
29
+ function save(sessionId: string, text: string, timestamp?: string): string {
30
+ return messageQueries.create({ session_id: sessionId, message: user(text), timestamp }).id;
31
+ }
32
+
33
+ /** FTS rows and map rows of a session, plus whether they point at each other. */
34
+ function indexOf(sessionId: string) {
35
+ const db = getDatabase();
36
+ const fts = db.prepare('SELECT rowid, message_id FROM messages_fts WHERE session_id = ?').all(sessionId) as { rowid: number; message_id: string }[];
37
+ const map = db.prepare('SELECT message_id, fts_rowid FROM messages_fts_map WHERE session_id = ?').all(sessionId) as { message_id: string; fts_rowid: number }[];
38
+ const consistent = fts.length === map.length && map.every((m) => fts.some((f) => f.rowid === m.fts_rowid && f.message_id === m.message_id));
39
+ return { fts, map, consistent };
40
+ }
41
+
42
+ beforeAll(async () => {
43
+ await initializeDatabase();
44
+ projectId = projectQueries.create({ name: 'message-fts', path: `/tmp/message-fts-${crypto.randomUUID()}`, created_at: new Date().toISOString(), last_opened_at: new Date().toISOString() } as never).id;
45
+ });
46
+
47
+ afterAll(() => {
48
+ sessionQueries.deleteAllByProjectId(projectId);
49
+ projectQueries.deleteProject(projectId);
50
+ closeDatabase();
51
+ });
52
+
53
+ describe('messages_fts through messages_fts_map', () => {
54
+ it('indexes a saved message and maps it to its FTS row', () => {
55
+ const session = newSession();
56
+ const id = save(session, 'quokka sunrise');
57
+ const { fts, map, consistent } = indexOf(session);
58
+ expect(fts.map((r) => r.message_id)).toEqual([id]);
59
+ expect(map.map((r) => r.message_id)).toEqual([id]);
60
+ expect(consistent).toBe(true);
61
+ expect(sessionQueries.searchByMessageContent(projectId, 'quokka').map((r) => r.sessionId)).toContain(session);
62
+ });
63
+
64
+ it('leaves no FTS or map row for a message without searchable text', () => {
65
+ const session = newSession();
66
+ save(session, ' ');
67
+ expect(indexOf(session).fts).toHaveLength(0);
68
+ expect(indexOf(session).map).toHaveLength(0);
69
+ });
70
+
71
+ it('removes exactly the deleted message', () => {
72
+ const session = newSession();
73
+ const keep = save(session, 'keep this one');
74
+ const drop = save(session, 'drop this one');
75
+ messageQueries.delete(drop);
76
+ const { fts, consistent } = indexOf(session);
77
+ expect(fts.map((r) => r.message_id)).toEqual([keep]);
78
+ expect(consistent).toBe(true);
79
+ });
80
+
81
+ it('removes messages cut by deleteAfterTimestamp', () => {
82
+ const session = newSession();
83
+ const early = save(session, 'early message', '2026-01-01T00:00:00.000Z');
84
+ save(session, 'late message one', '2026-01-02T00:00:00.000Z');
85
+ save(session, 'late message two', '2026-01-03T00:00:00.000Z');
86
+ messageQueries.deleteAfterTimestamp(session, '2026-01-02T00:00:00.000Z');
87
+ const { fts, consistent } = indexOf(session);
88
+ expect(fts.map((r) => r.message_id)).toEqual([early]);
89
+ expect(consistent).toBe(true);
90
+ });
91
+
92
+ it('removes a whole session, through either delete path', () => {
93
+ const a = newSession();
94
+ const b = newSession();
95
+ save(a, 'session a text');
96
+ save(b, 'session b text');
97
+ messageQueries.deleteBySessionId(a);
98
+ sessionQueries.delete(b);
99
+ expect(indexOf(a).fts).toHaveLength(0);
100
+ expect(indexOf(a).map).toHaveLength(0);
101
+ expect(indexOf(b).fts).toHaveLength(0);
102
+ expect(indexOf(b).map).toHaveLength(0);
103
+ });
104
+
105
+ it('removes every session of a deleted project, and only those', async () => {
106
+ const otherProject = projectQueries.create({ name: 'message-fts-other', path: `/tmp/message-fts-other-${crypto.randomUUID()}`, created_at: new Date().toISOString(), last_opened_at: new Date().toISOString() } as never).id;
107
+ const other = sessionQueries.create({ project_id: otherProject, engine: 'claude-code', started_at: new Date().toISOString() } as never).id;
108
+ const mine = newSession();
109
+ save(other, 'other project text');
110
+ save(mine, 'my project text');
111
+
112
+ sessionQueries.deleteAllByProjectId(otherProject);
113
+ projectQueries.deleteProject(otherProject);
114
+
115
+ expect(indexOf(other).fts).toHaveLength(0);
116
+ expect(indexOf(other).map).toHaveLength(0);
117
+ expect(indexOf(mine).fts).toHaveLength(1);
118
+ expect(indexOf(mine).consistent).toBe(true);
119
+ });
120
+ });
@@ -26,10 +26,47 @@ function extractSearchableText(msg: UnifiedMessage): string {
26
26
  .join('\n');
27
27
  }
28
28
 
29
+ /**
30
+ * The messages_fts mirror is written and deleted only through these helpers.
31
+ *
32
+ * FTS5 cannot look a row up by `message_id` (an UNINDEXED column), so a delete
33
+ * by it walked the whole index on every message save — seconds on a large
34
+ * database, on the server's only thread. `messages_fts_map` records each
35
+ * message's FTS rowid, so every delete here is a direct lookup (migration 088).
36
+ */
37
+
38
+ /** Remove the FTS rows of the given messages. */
39
+ export function removeMessagesFts(ids: string[]): void {
40
+ if (ids.length === 0) return;
41
+ const db = getDatabase();
42
+ for (let start = 0; start < ids.length; start += 500) {
43
+ const chunk = ids.slice(start, start + 500);
44
+ const placeholders = chunk.map(() => '?').join(',');
45
+ db.prepare(`
46
+ DELETE FROM messages_fts
47
+ WHERE rowid IN (SELECT fts_rowid FROM messages_fts_map WHERE message_id IN (${placeholders}))
48
+ `).run(...chunk);
49
+ db.prepare(`DELETE FROM messages_fts_map WHERE message_id IN (${placeholders})`).run(...chunk);
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Remove the FTS rows of whole sessions, named by a subquery that returns
55
+ * session ids (e.g. `SELECT id FROM chat_sessions WHERE project_id = ?`).
56
+ */
57
+ export function removeSessionsFts(sessionIdsQuery: string, ...params: unknown[]): void {
58
+ const db = getDatabase();
59
+ db.prepare(`
60
+ DELETE FROM messages_fts
61
+ WHERE rowid IN (SELECT fts_rowid FROM messages_fts_map WHERE session_id IN (${sessionIdsQuery}))
62
+ `).run(...(params as never[]));
63
+ db.prepare(`DELETE FROM messages_fts_map WHERE session_id IN (${sessionIdsQuery})`).run(...(params as never[]));
64
+ }
65
+
29
66
  /** Keep the messages_fts mirror in sync with a message's current text content. */
30
67
  function syncMessageFts(id: string, sessionId: string, msg: UnifiedMessage): void {
31
68
  const db = getDatabase();
32
- db.prepare('DELETE FROM messages_fts WHERE message_id = ?').run(id);
69
+ removeMessagesFts([id]);
33
70
 
34
71
  const text = extractSearchableText(msg).trim();
35
72
  if (!text) return;
@@ -37,10 +74,12 @@ function syncMessageFts(id: string, sessionId: string, msg: UnifiedMessage): voi
37
74
  const session = db.prepare('SELECT project_id FROM chat_sessions WHERE id = ?').get(sessionId) as { project_id: string } | null;
38
75
  if (!session) return;
39
76
 
40
- db.prepare(`
77
+ const inserted = db.prepare(`
41
78
  INSERT INTO messages_fts (message_id, session_id, project_id, text)
42
79
  VALUES (?, ?, ?, ?)
43
- `).run(id, sessionId, session.project_id, text);
80
+ `).run(id, sessionId, session.project_id, text) as { lastInsertRowid: number | bigint };
81
+ db.prepare('INSERT OR REPLACE INTO messages_fts_map (message_id, session_id, fts_rowid) VALUES (?, ?, ?)')
82
+ .run(id, sessionId, Number(inserted.lastInsertRowid));
44
83
  }
45
84
 
46
85
  export const messageQueries = {
@@ -194,13 +233,13 @@ export const messageQueries = {
194
233
  delete(id: string): void {
195
234
  const db = getDatabase();
196
235
  db.prepare('DELETE FROM messages WHERE id = ?').run(id);
197
- db.prepare('DELETE FROM messages_fts WHERE message_id = ?').run(id);
236
+ removeMessagesFts([id]);
198
237
  },
199
238
 
200
239
  deleteBySessionId(sessionId: string): void {
201
240
  const db = getDatabase();
202
241
  db.prepare('DELETE FROM messages WHERE session_id = ?').run(sessionId);
203
- db.prepare('DELETE FROM messages_fts WHERE session_id = ?').run(sessionId);
242
+ removeSessionsFts('?', sessionId);
204
243
  },
205
244
 
206
245
  deleteAfterTimestamp(sessionId: string, timestamp: string): void {
@@ -214,10 +253,7 @@ export const messageQueries = {
214
253
  WHERE session_id = ? AND created_at >= ?
215
254
  `).run(sessionId, timestamp);
216
255
 
217
- if (ids.length > 0) {
218
- const placeholders = ids.map(() => '?').join(',');
219
- db.prepare(`DELETE FROM messages_fts WHERE message_id IN (${placeholders})`).run(...ids.map(r => r.id));
220
- }
256
+ removeMessagesFts(ids.map(r => r.id));
221
257
  },
222
258
 
223
259
  /**
@@ -3,6 +3,7 @@ import type { ChatSession, Branch, DatabaseMessage } from '$shared/types/databas
3
3
  import { loadMessage } from '$shared/utils/message-formatter';
4
4
  import { extractMessageText } from '../../snapshot/helpers';
5
5
  import { debug } from '$shared/utils/logger';
6
+ import { removeSessionsFts } from './message-queries';
6
7
 
7
8
  /** ChatSession plus an optional FTS snippet, set only for message-content matches. */
8
9
  export interface SessionSearchResult extends ChatSession {
@@ -398,7 +399,7 @@ export const sessionQueries = {
398
399
  db.prepare('DELETE FROM message_snapshots WHERE session_id = ?').run(id);
399
400
  db.prepare('DELETE FROM session_relationships WHERE parent_session_id = ? OR child_session_id = ?').run(id, id);
400
401
  db.prepare('DELETE FROM messages WHERE session_id = ?').run(id);
401
- db.prepare('DELETE FROM messages_fts WHERE session_id = ?').run(id);
402
+ removeSessionsFts('?', id);
402
403
  db.prepare('DELETE FROM unread_sessions WHERE session_id = ?').run(id);
403
404
  // Clear current_session_id references in workspace_projects
404
405
  db.prepare('UPDATE workspace_projects SET current_session_id = NULL WHERE current_session_id = ?').run(id);
@@ -426,7 +427,7 @@ export const sessionQueries = {
426
427
  OR child_session_id IN (SELECT id FROM chat_sessions WHERE project_id = ?)
427
428
  `).run(projectId, projectId);
428
429
  db.prepare('DELETE FROM messages WHERE session_id IN (SELECT id FROM chat_sessions WHERE project_id = ?)').run(projectId);
429
- db.prepare('DELETE FROM messages_fts WHERE project_id = ?').run(projectId);
430
+ removeSessionsFts('SELECT id FROM chat_sessions WHERE project_id = ?', projectId);
430
431
  db.prepare('DELETE FROM unread_sessions WHERE project_id = ?').run(projectId);
431
432
  // Clear current_session_id references in workspace_projects for this project
432
433
  db.prepare('UPDATE workspace_projects SET current_session_id = NULL WHERE project_id = ?').run(projectId);
@@ -2,6 +2,8 @@ import { getDatabase } from '../index';
2
2
  import type { DatabaseMessage } from '$shared/types/database/schema';
3
3
 
4
4
  import { debug } from '$shared/utils/logger';
5
+ import { removeSessionsFts } from './message-queries';
6
+
5
7
  export const dbUtils = {
6
8
  // Get dashboard statistics
7
9
  getStats(): {
@@ -51,6 +53,7 @@ export const dbUtils = {
51
53
 
52
54
  for (const session of oldSessions) {
53
55
  db.prepare('DELETE FROM messages WHERE session_id = ?').run(session.id);
56
+ removeSessionsFts('?', session.id);
54
57
  db.prepare('DELETE FROM chat_sessions WHERE id = ?').run(session.id);
55
58
  }
56
59
 
@@ -95,6 +95,10 @@ async function _doSetup(): Promise<void> {
95
95
 
96
96
  // Bypass permissions for Claude Code
97
97
  overrides['CLAUDE_CODE_PERMISSION_MODE'] = 'bypassPermissions';
98
+ // The CLI reports when it is idle, so the adapter can tell "this turn is
99
+ // done but background work will start another" from "nothing left to do"
100
+ // (see adapters/claude/input-gate.ts).
101
+ overrides['CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS'] = '1';
98
102
 
99
103
  // Isolate Claude config to ~/.clopen/claude/user/
100
104
  const claudeUserDir = getClaudeUserConfigDir();
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The orders below were recorded from the Claude Agent SDK 0.3.296 with
3
+ * CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS=1.
4
+ */
5
+
6
+ import { describe, it, expect } from 'bun:test';
7
+ import { ClaudeInputGate, type InputGateMessage } from './input-gate';
8
+
9
+ const state = (s: string): InputGateMessage => ({ type: 'system', subtype: 'session_state_changed', state: s });
10
+ const tasks = (n: number): InputGateMessage => ({ type: 'system', subtype: 'background_tasks_changed', tasks: Array.from({ length: n }, (_, i) => ({ task_id: `t${i}` })) });
11
+ const notification: InputGateMessage = { type: 'system', subtype: 'task_notification' };
12
+ const assistant: InputGateMessage = { type: 'assistant' };
13
+ const result: InputGateMessage = { type: 'result' };
14
+
15
+ function run(messages: InputGateMessage[]): number[] {
16
+ const closedAt: number[] = [];
17
+ let index = -1;
18
+ const gate = new ClaudeInputGate(() => closedAt.push(index));
19
+ for (index = 0; index < messages.length; index++) gate.observe(messages[index]);
20
+ return closedAt;
21
+ }
22
+
23
+ describe('ClaudeInputGate', () => {
24
+ it('stays open through the first result while a background task runs, and closes after the turn it starts', () => {
25
+ const order = [
26
+ state('running'), assistant, tasks(1), assistant, result,
27
+ state('idle'), // idle WHILE the background task still runs
28
+ notification, tasks(0), state('running'), assistant, result,
29
+ state('idle')
30
+ ];
31
+ expect(run(order)).toEqual([order.length - 1]);
32
+ });
33
+
34
+ it('closes at the first idle when a background task finished mid-turn', () => {
35
+ const order = [state('running'), assistant, tasks(1), notification, tasks(0), notification, assistant, result, state('idle')];
36
+ expect(run(order)).toEqual([order.length - 1]);
37
+ });
38
+
39
+ it('closes at the first idle of a turn without background work', () => {
40
+ const order = [state('running'), assistant, result, state('idle')];
41
+ expect(run(order)).toEqual([3]);
42
+ });
43
+
44
+ it('without session-state events, closes on a result with no background task', () => {
45
+ expect(run([assistant, result])).toEqual([1]);
46
+ const order = [assistant, tasks(1), result, notification, tasks(0), assistant, result];
47
+ expect(run(order)).toEqual([order.length - 1]);
48
+ });
49
+
50
+ it('closes once', () => {
51
+ let calls = 0;
52
+ const gate = new ClaudeInputGate(() => calls++);
53
+ gate.observe(result);
54
+ gate.shut();
55
+ gate.observe(state('idle'));
56
+ expect(calls).toBe(1);
57
+ expect(gate.isClosed).toBe(true);
58
+ });
59
+ });
@@ -0,0 +1,74 @@
1
+ /**
2
+ * When a Claude run's prompt input may close.
3
+ *
4
+ * The SDK closes the CLI's stdin once its prompt iterable ends and the first
5
+ * `result` arrives. But the CLI keeps going after that `result` while
6
+ * background work it started is still running: when a backgrounded command or
7
+ * agent finishes, it starts a new turn on its own. Every request that turn
8
+ * makes back to the host — in-process MCP tools (browser automation, memory),
9
+ * `canUseTool`, hooks — travels over stdin, so with stdin closed each one
10
+ * failed at once ("The tool call was interrupted before a result was
11
+ * received"). Recorded with SDK 0.3.296: the in-process tool's handler never
12
+ * ran in the notification turn.
13
+ *
14
+ * So Clopen holds the prompt iterable open and closes it only when the CLI has
15
+ * nothing left to do:
16
+ *
17
+ * - With session-state events (`CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS`), the
18
+ * CLI reports `idle` after every turn — including while background work is
19
+ * still running, which is exactly why `idle` alone was not enough. Close on
20
+ * `idle` when the background task list is empty.
21
+ * - Without them (an older CLI), close on a `result` when the background task
22
+ * list is empty.
23
+ *
24
+ * The background list is the authoritative `background_tasks_changed` list.
25
+ * `task_started` / `task_notification` are not used: foreground commands emit
26
+ * them too (`is_backgrounded: false`), and their notification comes inside the
27
+ * same turn.
28
+ */
29
+
30
+ export interface InputGateMessage {
31
+ type: string;
32
+ subtype?: string;
33
+ state?: string;
34
+ tasks?: unknown[];
35
+ }
36
+
37
+ export class ClaudeInputGate {
38
+ private backgroundTasks = 0;
39
+ private sawSessionState = false;
40
+ private closed = false;
41
+
42
+ constructor(private readonly close: () => void) {}
43
+
44
+ /** Feed every SDK message, in order. */
45
+ observe(message: InputGateMessage): void {
46
+ if (this.closed) return;
47
+
48
+ if (message.type === 'system' && message.subtype === 'background_tasks_changed') {
49
+ this.backgroundTasks = Array.isArray(message.tasks) ? message.tasks.length : 0;
50
+ return;
51
+ }
52
+
53
+ if (message.type === 'system' && message.subtype === 'session_state_changed') {
54
+ this.sawSessionState = true;
55
+ if (message.state === 'idle' && this.backgroundTasks === 0) this.shut();
56
+ return;
57
+ }
58
+
59
+ if (message.type === 'result' && !this.sawSessionState && this.backgroundTasks === 0) {
60
+ this.shut();
61
+ }
62
+ }
63
+
64
+ /** Close regardless — the run was cancelled or the stream ended. */
65
+ shut(): void {
66
+ if (this.closed) return;
67
+ this.closed = true;
68
+ this.close();
69
+ }
70
+
71
+ get isClosed(): boolean {
72
+ return this.closed;
73
+ }
74
+ }
@@ -81,3 +81,19 @@ describe('Claude sub-agent scoping', () => {
81
81
  expect(stop).toEqual([{ type: 'stream_event', event: 'stop', sessionId: 'session-1', reasoning: true }]);
82
82
  });
83
83
  });
84
+
85
+ describe('Claude background work', () => {
86
+ test('reports the complete background task list, empty once everything finished', () => {
87
+ const convert = createSdkMessageConverter();
88
+ const running = [...convert({
89
+ type: 'system', subtype: 'background_tasks_changed', session_id: 'session-1', uuid: 'bg-1',
90
+ tasks: [{ task_id: 'b1', run_id: 'r1', task_type: 'local_bash', description: 'sleep 6' }],
91
+ } as any)];
92
+ const done = [...convert({
93
+ type: 'system', subtype: 'background_tasks_changed', session_id: 'session-1', uuid: 'bg-2', tasks: [],
94
+ } as any)];
95
+
96
+ expect(running).toEqual([{ type: 'background_work', sessionId: 'session-1', tasks: [{ id: 'b1', description: 'sleep 6' }] }]);
97
+ expect(done).toEqual([{ type: 'background_work', sessionId: 'session-1', tasks: [] }]);
98
+ });
99
+ });
@@ -41,6 +41,7 @@ import type {
41
41
  SystemInitEvent,
42
42
  RateLimitEvent,
43
43
  NotificationEvent,
44
+ BackgroundWorkEvent,
44
45
  TokenUsage,
45
46
  StopReason,
46
47
  } from '$shared/types/unified';
@@ -586,6 +587,13 @@ function* dispatchUnscopedSdkMessage(msg: SDKMessage, state: StreamConverterStat
586
587
  yield convertModelRefusalFallback(msg as SDKModelRefusalFallbackMessage);
587
588
  } else if (subtype === 'model_refusal_no_fallback') {
588
589
  yield convertModelRefusalNoFallback(msg as SDKModelRefusalNoFallbackMessage);
590
+ } else if (subtype === 'background_tasks_changed') {
591
+ const changed = msg as unknown as { session_id: string; tasks?: Array<{ task_id: string; description?: string }> };
592
+ yield {
593
+ type: 'background_work',
594
+ sessionId: changed.session_id,
595
+ tasks: (changed.tasks ?? []).map((task) => ({ id: task.task_id, description: task.description }))
596
+ } satisfies BackgroundWorkEvent;
589
597
  } else if (subtype === 'task_started') {
590
598
  const task = msg as unknown as { session_id: string; uuid?: string; task_id: string; tool_use_id?: string; task_type?: string; workflow_name?: string; description?: string };
591
599
  if (task.task_type === 'local_workflow' && task.tool_use_id) {
@@ -27,6 +27,7 @@ import type {
27
27
  } from '@anthropic-ai/claude-agent-sdk';
28
28
  import type { EngineOutput } from '$shared/types/unified';
29
29
  import type { StructuredGenerationOptions } from '../../types';
30
+ import { ClaudeInputGate, type InputGateMessage } from './input-gate';
30
31
  import { createSdkMessageConverter, toSdkUserMessage } from './message-converter';
31
32
  import { WorkflowTranscriptTailer } from './workflow-transcript';
32
33
  import { resolveOsPath } from '$backend/utils/paths';
@@ -165,6 +166,7 @@ export class ClaudeCodeEngine implements AIEngine {
165
166
  this.runs.add(run);
166
167
 
167
168
  const resolvedProjectPath = resolveOsPath(projectPath);
169
+ let inputGate: ClaudeInputGate | null = null;
168
170
 
169
171
  try {
170
172
  // Active Profile for this stream (resolved in stream-manager). Scopes the
@@ -341,8 +343,18 @@ export class ClaudeCodeEngine implements AIEngine {
341
343
 
342
344
  // Convert UserMessage → SDKUserMessage for SDK
343
345
  const sdkPrompt = toSdkUserMessage(prompt);
346
+ // The prompt stays open until the CLI has nothing left to do — see
347
+ // ClaudeInputGate. Ending it after the one message let the SDK close
348
+ // stdin at the first result, and every tool call, permission check and
349
+ // hook of a turn started by finished background work then failed.
350
+ let releaseInput!: () => void;
351
+ const inputReleased = new Promise<void>((resolve) => { releaseInput = resolve; });
352
+ inputGate = new ClaudeInputGate(releaseInput);
353
+ const gate = inputGate;
354
+ streamController.signal.addEventListener('abort', () => gate.shut(), { once: true });
344
355
  const promptIterable = (async function* () {
345
356
  yield sdkPrompt;
357
+ await inputReleased;
346
358
  })();
347
359
 
348
360
  const { query } = await loadEngineSdk<typeof import('@anthropic-ai/claude-agent-sdk')>('claude-code', '@anthropic-ai/claude-agent-sdk');
@@ -363,6 +375,7 @@ export class ClaudeCodeEngine implements AIEngine {
363
375
  const sdkProducer = (async () => {
364
376
  try {
365
377
  for await (const sdkMessage of queryInstance) {
378
+ gate.observe(sdkMessage as InputGateMessage);
366
379
  observeAskUserQuestion(sdkMessage);
367
380
  // Register Workflow launches after queueing the corresponding parent
368
381
  // and tool result, preserving their ordering ahead of child records.
@@ -408,6 +421,8 @@ export class ClaudeCodeEngine implements AIEngine {
408
421
  } catch (error) {
409
422
  handleStreamError(error);
410
423
  } finally {
424
+ // However the stream ends, the held-open prompt must end with it.
425
+ inputGate?.shut();
411
426
  // Retire THIS run only — a concurrent stream of another chat session in
412
427
  // the same project is still using the instance.
413
428
  this.forgetRun(run);
@@ -42,12 +42,15 @@ async function writeGenerated(pairs: Array<[string, string]>): Promise<string> {
42
42
  }
43
43
 
44
44
  async function gitConfig(key: string, configPath: string, cwd: string): Promise<string> {
45
+ // GIT_CONFIG_COUNT/KEY_n/VALUE_n outrank every config file. A shell Clopen
46
+ // started carries the user's identity in them, which would answer instead
47
+ // of the file under test.
48
+ const env = Object.fromEntries(
49
+ Object.entries(process.env).filter(([name]) => !/^GIT_CONFIG_(COUNT|KEY_\d+|VALUE_\d+)$/.test(name))
50
+ );
45
51
  const proc = Bun.spawn(['git', 'config', '--get', key], {
46
52
  cwd,
47
- env: { ...process.env, GIT_CONFIG_GLOBAL: configPath, GIT_CONFIG_SYSTEM: '/dev/null' } as Record<
48
- string,
49
- string
50
- >,
53
+ env: { ...env, GIT_CONFIG_GLOBAL: configPath, GIT_CONFIG_SYSTEM: '/dev/null' } as Record<string, string>,
51
54
  stdout: 'pipe',
52
55
  stderr: 'pipe'
53
56
  });
package/backend/index.ts CHANGED
@@ -33,6 +33,10 @@ import { runGitHelper } from './git/identity/cli';
33
33
  }
34
34
 
35
35
  import { Elysia } from 'elysia';
36
+ import { watchSupervisor } from '$shared/utils/process-supervisor';
37
+ import { collectDescendants, signalAll } from '$shared/utils/process-tree';
38
+ import { ptyKitManager } from './terminal/ptykit';
39
+ import { tunnelKit } from './tunnel/tunnel-config';
36
40
  import { corsMiddleware } from './middleware/cors';
37
41
  import { errorHandlerMiddleware } from './middleware/error-handler';
38
42
  import { loggerMiddleware } from './middleware/logger';
@@ -367,6 +371,14 @@ async function startServer() {
367
371
  });
368
372
  }
369
373
 
374
+ // Supervised (bin/clopen.ts, scripts/dev.ts): if the supervisor disappears
375
+ // without stopping us, stop anyway rather than keep the port unowned. Read
376
+ // before startServer spawns anything that would inherit the variable.
377
+ watchSupervisor(() => {
378
+ debug.warn('server', 'Supervisor is gone — shutting down');
379
+ void gracefulShutdown();
380
+ });
381
+
370
382
  startServer().catch((error) => {
371
383
  console.error('❌ Failed to start server:', error);
372
384
  process.exit(1);
@@ -379,12 +391,15 @@ async function gracefulShutdown() {
379
391
  if (isShuttingDown) return;
380
392
  isShuttingDown = true;
381
393
 
382
- // Force exit after 5 seconds — prevents port from being held by slow cleanup
383
- // during bun --watch restarts, which causes ECONNREFUSED on the Vite WS proxy.
394
+ // The port is released first thing (app.stop below), so the rest takes the
395
+ // time it actually needs. This only bounds a step that hangs: whatever this
396
+ // process started is then killed with it — the preview's Chrome sits in a
397
+ // process group of its own and would otherwise outlive us.
384
398
  const forceExitTimer = setTimeout(() => {
385
- debug.warn('server', '⚠️ Shutdown timeout — forcing exit to release port');
399
+ debug.warn('server', '⚠️ Shutdown timeout — forcing exit');
400
+ signalAll(collectDescendants(process.pid), 'SIGKILL');
386
401
  process.exit(1);
387
- }, 5_000);
402
+ }, 12_000);
388
403
 
389
404
  console.log('\n🛑 Shutting down server...');
390
405
  try {
@@ -404,6 +419,12 @@ async function gracefulShutdown() {
404
419
  // transport so their remote sessions and bound ports are released now.
405
420
  await sshForwardManager.stopAll();
406
421
  sshClientPool.closeAll();
422
+ // Terminal tabs: each session's shell and everything started from it
423
+ // (a dev server, a background job) ends with the server.
424
+ ptyKitManager.dispose();
425
+ // Tunnels: cloudflared drains before it exits; wait for it so nothing is
426
+ // left serving this server's public URL.
427
+ await tunnelKit.stopAll();
407
428
  // Dispose rate limiter timer
408
429
  authRateLimiter.dispose();
409
430
  // Dispose expired session cleanup timer
@@ -445,11 +466,17 @@ async function gracefulShutdown() {
445
466
  process.on('SIGINT', gracefulShutdown);
446
467
  process.on('SIGTERM', gracefulShutdown);
447
468
 
448
- // Ignore SIGHUP — sent when the controlling terminal closes or an SSH session
449
- // disconnects. Without a handler Bun exits immediately; we want the server to
450
- // keep running (e.g. started in a background tab or remote shell).
469
+ // SIGHUP: the controlling terminal or SSH session closed. Started in a
470
+ // terminal, the server goes with it, like any program run there. Without one
471
+ // on stdout — supervised (the supervisor decides), `nohup`, a service — it
472
+ // keeps running. Without a handler Bun would exit abruptly instead.
473
+ const startedInTerminal = process.stdout.isTTY === true;
451
474
  process.on('SIGHUP', () => {
452
- debug.log('server', 'Received SIGHUP — ignoring (server stays running)');
475
+ if (startedInTerminal) {
476
+ void gracefulShutdown();
477
+ return;
478
+ }
479
+ debug.log('server', 'Received SIGHUP — no terminal attached, server stays running');
453
480
  });
454
481
 
455
482
  // Safety net: prevent server crash from unhandled promise rejections.
@@ -308,7 +308,8 @@ graph_node_entities subjects a memory is about (an ATTRIBUTE, not nodes)
308
308
  graph_node_paths files a memory is about (likewise)
309
309
  graph_vectors one int8 vector per node, 260 bytes at 256 dims
310
310
  graph_nodes_fts FTS5 mirror for BM25
311
- graph_layout persisted positions and communities (migration 067)
311
+ graph_layout persisted positions, communities and degree (067, 089)
312
+ graph_layout_edges derived edges the layout pass laid out on (089)
312
313
  memory_extraction_queue durable queue of turns awaiting summarisation
313
314
  ```
314
315
 
@@ -349,8 +350,9 @@ of sentences all shaped "X is a project that does Y", every pair is similar in
349
350
  shape rather than in subject, so 144 of one graph's 371 edges were pairings like
350
351
  *"Vantum monorepo phase 1.8"* ↔ *"ChatKit runs on Node.js 18+"*. The fault was
351
352
  never that they connected memories — it was that **cosine chose which**. Edges are
352
- now derived at read time from the subjects extraction already recorded, and never
353
- stored.
353
+ now derived from the subjects extraction already recorded. They are never stored
354
+ as relations; the layout pass keeps the set it laid out on in
355
+ `graph_layout_edges`, which is disposable like the rest of the arrangement.
354
356
 
355
357
  ---
356
358
 
@@ -364,7 +366,8 @@ bootstrap.ts startup; idempotent, also re-run after Clear All Data
364
366
 
365
367
  retrieval.ts BM25 + vector, RRF fusion, spreading activation
366
368
  context.ts builds the injected block; standing instructions
367
- view.ts graph serialization for the UI
369
+ layout.ts background arrangement: cold passes, warm arrival placement, the world
370
+ view.ts the graph view as map tiles, plus locate and node detail
368
371
 
369
372
  extract/
370
373
  scheduler.ts durable queue, retries, concurrency