@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,28 @@
1
+ /**
2
+ * A stream shows "waiting for background work" only between turns: after an
3
+ * engine turn's result, while background work it started is still running.
4
+ */
5
+
6
+ import { describe, it, expect } from 'bun:test';
7
+ import { waitingOnBackground } from './stream-manager';
8
+
9
+ const task = (id: string) => ({ id });
10
+
11
+ describe('waitingOnBackground', () => {
12
+ it('counts the tasks of an active stream between turns', () => {
13
+ expect(waitingOnBackground({ status: 'active', betweenTurns: true, backgroundTasks: [task('a'), task('b')] })).toBe(2);
14
+ });
15
+
16
+ it('is 0 while the engine is producing output, even with work running', () => {
17
+ expect(waitingOnBackground({ status: 'active', betweenTurns: false, backgroundTasks: [task('a')] })).toBe(0);
18
+ });
19
+
20
+ it('is 0 between turns once nothing runs in the background', () => {
21
+ expect(waitingOnBackground({ status: 'active', betweenTurns: true, backgroundTasks: [] })).toBe(0);
22
+ expect(waitingOnBackground({ status: 'active', betweenTurns: true })).toBe(0);
23
+ });
24
+
25
+ it('is 0 for a stream that is no longer active', () => {
26
+ expect(waitingOnBackground({ status: 'completed', betweenTurns: true, backgroundTasks: [task('a')] })).toBe(0);
27
+ });
28
+ });
@@ -120,6 +120,23 @@ describe('getMessagePage', () => {
120
120
  expect(collected).toEqual(ids);
121
121
  });
122
122
 
123
+ it('reaches back to a requested message in one page, contiguous with the loaded ones', () => {
124
+ const session = newSession();
125
+ const ids = buildBranch(session, 12, 2); // 6 messages per turn
126
+
127
+ const latest = getMessagePage(session, { minCount: 7 });
128
+ const before = (latest.messages[0] as { messageId: string }).messageId;
129
+ const target = ids[7]; // inside turn 1, far older than one page
130
+ const page = getMessagePage(session, { beforeId: before, minCount: 7, untilId: target });
131
+ const pageIds = page.messages.map((message) => (message as { messageId: string }).messageId);
132
+
133
+ expect(pageIds).toContain(target);
134
+ const start = ids.indexOf(pageIds[0]);
135
+ expect(start).toBeLessThanOrEqual(7);
136
+ expect([...pageIds, ...latest.messages.map((m) => (m as { messageId: string }).messageId)]).toEqual(ids.slice(start));
137
+ expect(page.hasMore).toBe(true);
138
+ });
139
+
123
140
  it('answers an empty page for a session with no messages, or an unknown cursor', () => {
124
141
  const session = newSession();
125
142
  expect(getMessagePage(session)).toEqual({ messages: [], hasMore: false });
@@ -88,10 +88,12 @@ function headOf(sessionId: string): string | null {
88
88
  /**
89
89
  * One page of the active branch, ending just before `beforeId` (or at the head
90
90
  * when absent). Holds at least `minCount` messages and always begins at a turn.
91
+ * With `untilId` it also reaches back to that message, so a jump to an old
92
+ * prompt is one request instead of a page-by-page walk.
91
93
  */
92
94
  export function getMessagePage(
93
95
  sessionId: string,
94
- options: { beforeId?: string; minCount?: number } = {}
96
+ options: { beforeId?: string; minCount?: number; untilId?: string } = {}
95
97
  ): MessagePage {
96
98
  const minCount = Math.max(1, options.minCount ?? DEFAULT_PAGE_SIZE);
97
99
  const byId = getDatabase().prepare('SELECT * FROM messages WHERE id = ? AND session_id = ?');
@@ -107,6 +109,7 @@ export function getMessagePage(
107
109
 
108
110
  const messages: UnifiedMessage[] = [];
109
111
  const boundary = new BoundaryTracker();
112
+ let reachedUntil = !options.untilId;
110
113
  while (cursor) {
111
114
  const row = byId.get(cursor, sessionId) as DatabaseMessage | null;
112
115
  if (!row) {
@@ -116,8 +119,9 @@ export function getMessagePage(
116
119
  const message = JSON.parse(row.data) as UnifiedMessage;
117
120
  messages.push(message);
118
121
  cursor = row.parent_message_id ?? null;
122
+ if (row.id === options.untilId) reachedUntil = true;
119
123
  const mayStartHere = boundary.add(message);
120
- if (messages.length >= minCount && mayStartHere) break;
124
+ if (messages.length >= minCount && reachedUntil && mayStartHere) break;
121
125
  }
122
126
 
123
127
  return {
@@ -27,6 +27,7 @@ import type {
27
27
  RateLimitEvent,
28
28
  RateLimitType,
29
29
  NotificationEvent,
30
+ BackgroundWorkEvent,
30
31
  TokenUsage,
31
32
  StopReason,
32
33
  UserContentBlock,
@@ -85,6 +86,10 @@ export interface StreamState {
85
86
  */
86
87
  partialBlock?: number;
87
88
  reasoningBlock?: number;
89
+ /** Background work the engine is still running (see BackgroundWorkEvent). */
90
+ backgroundTasks?: Array<{ id: string; description?: string }>;
91
+ /** Between an engine turn's `result` and the stream's next output. */
92
+ betweenTurns?: boolean;
88
93
  error?: string;
89
94
  abortController?: AbortController;
90
95
  streamPromise?: Promise<void>;
@@ -286,6 +291,17 @@ export interface RateLimitSnapshot {
286
291
  receivedAt: string;
287
292
  }
288
293
 
294
+ /**
295
+ * How many background tasks an active stream is waiting on between turns — 0
296
+ * while the engine is producing output. The turn that started the work has
297
+ * ended; the engine will start another when the work finishes. Shown as
298
+ * "waiting for background work" instead of "generating".
299
+ */
300
+ export function waitingOnBackground(stream: Pick<StreamState, 'status' | 'betweenTurns' | 'backgroundTasks'>): number {
301
+ if (stream.status !== 'active' || !stream.betweenTurns) return 0;
302
+ return stream.backgroundTasks?.length ?? 0;
303
+ }
304
+
289
305
  class StreamManager extends EventEmitter {
290
306
  private activeStreams = new Map<string, StreamState>();
291
307
  private sessionStreams = new Map<string, string>(); // composite key -> streamId
@@ -504,6 +520,31 @@ class StreamManager extends EventEmitter {
504
520
  /**
505
521
  * Emit a stream event to all subscribers
506
522
  */
523
+ /**
524
+ * Follow whether the stream sits between turns waiting on background work,
525
+ * and announce every change (presence shows it on every device). A turn's
526
+ * `result` opens the gap; any output of the next turn closes it.
527
+ */
528
+ private trackTurnGap(streamState: StreamState, output: EngineOutput): void {
529
+ const before = waitingOnBackground(streamState);
530
+ if (output.type === 'background_work') {
531
+ streamState.backgroundTasks = (output as BackgroundWorkEvent).tasks;
532
+ } else if (output.type === 'result') {
533
+ streamState.betweenTurns = true;
534
+ } else if (output.type !== 'rate_limit' && output.type !== 'notification' && output.type !== 'system_init') {
535
+ streamState.betweenTurns = false;
536
+ }
537
+ const after = waitingOnBackground(streamState);
538
+ if (after !== before) {
539
+ this.emit('stream:background', {
540
+ streamId: streamState.streamId,
541
+ chatSessionId: streamState.chatSessionId,
542
+ projectId: streamState.projectId,
543
+ waiting: after
544
+ });
545
+ }
546
+ }
547
+
507
548
  private emitStreamEvent(streamState: StreamState, type: StreamEventType, data: any): void {
508
549
  // Increment sequence number for deduplication
509
550
  streamState.eventSeq++;
@@ -935,6 +976,8 @@ class StreamManager extends EventEmitter {
935
976
  // the same folder, for any tool (see snapshot/turn-activity.ts).
936
977
  if (chatSessionId) snapshotService.observeEngineOutput(chatSessionId, output);
937
978
 
979
+ this.trackTurnGap(streamState, output);
980
+
938
981
  // ── Route by type discriminant ──────────────────────────────
939
982
 
940
983
  // Extract session ID from first event that has one
@@ -984,6 +1027,10 @@ class StreamManager extends EventEmitter {
984
1027
  continue; // Don't save to DB
985
1028
  }
986
1029
 
1030
+ // ── Background work (tracked in trackTurnGap) ─────────────
1031
+ case 'background_work':
1032
+ continue;
1033
+
987
1034
  // ── Compact Boundary ───────────────────────────────────
988
1035
  case 'compact_boundary': {
989
1036
  const boundary = enrichMessageEngine(output, engineCtx) as CompactBoundaryMessage;
@@ -1166,24 +1213,31 @@ class StreamManager extends EventEmitter {
1166
1213
  });
1167
1214
  }
1168
1215
  } else if (streamEvt.event === 'stop') {
1216
+ // `end` re-sends a block's full text once, as the reconciliation
1217
+ // point. Only for a block still being streamed: once its saved
1218
+ // message has gone out (which clears the text below), the block is
1219
+ // settled and an `end` for it could only bring a stale copy back.
1220
+ // A reasoning stop never ends the text block.
1169
1221
  const lifecycle = streamEvt as StreamLifecycleEvent;
1170
- if (lifecycle.reasoning && streamState.currentReasoningText) {
1171
- this.emitStreamEvent(streamState, 'partial', {
1172
- processId: streamState.processId,
1173
- eventType: 'end',
1174
- block: streamState.reasoningBlock ?? 0,
1175
- partialText: streamState.currentReasoningText,
1176
- deltaText: '',
1177
- reasoning: true,
1178
- timestamp: new Date().toISOString()
1179
- });
1222
+ if (lifecycle.reasoning) {
1223
+ if (streamState.currentReasoningText) {
1224
+ this.emitStreamEvent(streamState, 'partial', {
1225
+ processId: streamState.processId,
1226
+ eventType: 'end',
1227
+ block: streamState.reasoningBlock ?? 0,
1228
+ partialText: streamState.currentReasoningText,
1229
+ deltaText: '',
1230
+ reasoning: true,
1231
+ timestamp: new Date().toISOString()
1232
+ });
1233
+ }
1180
1234
  streamState.currentReasoningText = '';
1181
- } else {
1235
+ } else if (streamState.currentPartialText) {
1182
1236
  this.emitStreamEvent(streamState, 'partial', {
1183
1237
  processId: streamState.processId,
1184
1238
  eventType: 'end',
1185
1239
  block: streamState.partialBlock ?? 0,
1186
- partialText: streamState.currentPartialText || '',
1240
+ partialText: streamState.currentPartialText,
1187
1241
  deltaText: '',
1188
1242
  timestamp: new Date().toISOString()
1189
1243
  });
@@ -1240,6 +1294,13 @@ class StreamManager extends EventEmitter {
1240
1294
  const usage = assistantMsg.usage;
1241
1295
  const messageTimestamp = assistantMsg.createdAt;
1242
1296
 
1297
+ // The text this message settles stops being "live" before it is
1298
+ // saved, so a catch-up snapshot can never carry text whose saved
1299
+ // message a reloaded transcript already shows. Only a root message
1300
+ // settles the root's live text — a sub-agent's (parent-tagged) one
1301
+ // finishing must not wipe the main turn's partial.
1302
+ if (!assistantMsg.parent.toolUseId) streamState.currentPartialText = undefined;
1303
+
1243
1304
  let savedMsgId: string | undefined;
1244
1305
  let savedParentId: string | null = null;
1245
1306
  if (chatSessionId) {
@@ -1252,8 +1313,6 @@ class StreamManager extends EventEmitter {
1252
1313
  savedParentId = saved?.parent_message_id || null;
1253
1314
  }
1254
1315
 
1255
- if (!assistantMsg.parent.toolUseId) streamState.currentPartialText = undefined;
1256
-
1257
1316
  streamState.messages.push({
1258
1317
  processId: streamState.processId,
1259
1318
  message: assistantMsg as any,
@@ -0,0 +1,52 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Map each message to its messages_fts row so saves stop scanning the whole index';
5
+
6
+ /**
7
+ * Which `messages_fts` row holds a message's text.
8
+ *
9
+ * `messages_fts.message_id` is an UNINDEXED FTS5 column: FTS5 cannot look a
10
+ * row up by it, so `DELETE FROM messages_fts WHERE message_id = ?` walked the
11
+ * entire index. Every message save ran that delete first, on the server's only
12
+ * thread — measured on a 4 GB database (165k indexed messages) at up to 1.8 s
13
+ * per save, 3–5 saves per turn, which stalled every panel, terminal and preview
14
+ * request while any chat was streaming. Deleting by `rowid` is a direct lookup.
15
+ *
16
+ * A separate narrow table rather than a column on `messages`: adding a column
17
+ * to `messages` and filling it rewrites every row, which on the same database
18
+ * took 31 s at startup; filling this table takes under 2 s. `session_id` is
19
+ * kept here so a whole session's or project's rows can be found without
20
+ * depending on the order `messages` rows are deleted in.
21
+ */
22
+ export const up = (db: DatabaseConnection): void => {
23
+ debug.log('migration', '📋 Creating messages_fts_map...');
24
+ db.exec(`
25
+ CREATE TABLE IF NOT EXISTS messages_fts_map (
26
+ message_id TEXT PRIMARY KEY,
27
+ session_id TEXT NOT NULL,
28
+ fts_rowid INTEGER NOT NULL
29
+ ) WITHOUT ROWID
30
+ `);
31
+ db.exec('CREATE INDEX IF NOT EXISTS idx_messages_fts_map_session ON messages_fts_map (session_id)');
32
+
33
+ // One pass over the index. If a message somehow has more than one row, the
34
+ // newest (highest rowid) wins and the others are dropped below.
35
+ db.exec(`
36
+ INSERT OR REPLACE INTO messages_fts_map (message_id, session_id, fts_rowid)
37
+ SELECT message_id, session_id, rowid FROM messages_fts ORDER BY rowid
38
+ `);
39
+
40
+ // Rows the map does not point at (duplicates), and rows whose message no
41
+ // longer exists, were never reachable by a delete before; drop them now.
42
+ db.exec('DELETE FROM messages_fts_map WHERE message_id NOT IN (SELECT id FROM messages)');
43
+ db.exec('DELETE FROM messages_fts WHERE rowid NOT IN (SELECT fts_rowid FROM messages_fts_map)');
44
+
45
+ const { count } = db.prepare('SELECT COUNT(*) AS count FROM messages_fts_map').get() as { count: number };
46
+ debug.log('migration', `✅ messages_fts_map created for ${count} messages`);
47
+ };
48
+
49
+ export const down = (db: DatabaseConnection): void => {
50
+ db.exec('DROP INDEX IF EXISTS idx_messages_fts_map_session');
51
+ db.exec('DROP TABLE IF EXISTS messages_fts_map');
52
+ };
@@ -0,0 +1,58 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description =
5
+ 'Persist memory-graph node degree and derived edges so the view can be served as tiles';
6
+
7
+ /**
8
+ * What a tiled Memory view needs from the arrangement and could not get.
9
+ *
10
+ * The view no longer asks for "the graph"; it asks for the rectangles of it that
11
+ * are on screen, at the resolution the camera is at. Two things a tile has to
12
+ * carry were only ever computed for a whole fetch:
13
+ *
14
+ * - DEGREE sizes a node. It was counted over whatever was drawn, which for a
15
+ * tile is a meaningless slice — the same memory would change size as the
16
+ * tiles around it loaded. The layout pass already builds the full graph, so
17
+ * it writes each node's degree alongside its position.
18
+ *
19
+ * - DERIVED EDGES (two memories naming the same subject or file) are most of
20
+ * the structure the episodic half has. They were derived at read time from
21
+ * the set being drawn, which is unbounded for the whole store and wrong for a
22
+ * tile: an edge whose other end sits in the next tile was never derived at
23
+ * all. The layout pass derives them over every live node anyway — it lays out
24
+ * on them — so it now keeps them. Stored edges stay in `graph_edges` and are
25
+ * read from there, so a connection a model records shows up without waiting
26
+ * for a pass.
27
+ *
28
+ * Both are derived and disposable like the rest of `graph_layout`: deleting them
29
+ * costs one background pass and no memory.
30
+ */
31
+ export const up = (db: DatabaseConnection): void => {
32
+ debug.log('migration', 'Adding memory layout degree and derived edges...');
33
+
34
+ const columns = db.prepare(`PRAGMA table_info(graph_layout)`).all() as { name: string }[];
35
+ if (!columns.some(column => column.name === 'degree')) {
36
+ db.exec(`ALTER TABLE graph_layout ADD COLUMN degree INTEGER NOT NULL DEFAULT 0`);
37
+ }
38
+
39
+ // Stored once per pair, smaller id first, so "edges touching this node" is the
40
+ // union of a lookup on each column — the same shape `graph_edges` is read in.
41
+ db.exec(`
42
+ CREATE TABLE IF NOT EXISTS graph_layout_edges (
43
+ src_id TEXT NOT NULL REFERENCES graph_nodes(id) ON DELETE CASCADE,
44
+ dst_id TEXT NOT NULL REFERENCES graph_nodes(id) ON DELETE CASCADE,
45
+ weight REAL NOT NULL DEFAULT 1,
46
+ PRIMARY KEY (src_id, dst_id)
47
+ ) WITHOUT ROWID
48
+ `);
49
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_layout_edges_dst ON graph_layout_edges (dst_id)`);
50
+
51
+ debug.log('migration', 'Memory layout tiles ready');
52
+ };
53
+
54
+ export const down = (db: DatabaseConnection): void => {
55
+ db.exec(`DROP INDEX IF EXISTS idx_graph_layout_edges_dst`);
56
+ db.exec(`DROP TABLE IF EXISTS graph_layout_edges`);
57
+ db.exec(`ALTER TABLE graph_layout DROP COLUMN degree`);
58
+ };
@@ -86,6 +86,8 @@ import * as migration084 from './084_create_channel_links';
86
86
  import * as migration085 from './085_add_home_projects';
87
87
  import * as migration086 from './086_single_owner';
88
88
  import * as migration087 from './087_create_blob_line_stats';
89
+ import * as migration088 from './088_create_messages_fts_map';
90
+ import * as migration089 from './089_add_memory_layout_tiles';
89
91
 
90
92
  // Export all migrations in order
91
93
  export const migrations = [
@@ -610,6 +612,18 @@ export const migrations = [
610
612
  description: migration087.description,
611
613
  up: migration087.up,
612
614
  down: migration087.down
615
+ },
616
+ {
617
+ id: '088',
618
+ description: migration088.description,
619
+ up: migration088.up,
620
+ down: migration088.down
621
+ },
622
+ {
623
+ id: '089',
624
+ description: migration089.description,
625
+ up: migration089.up,
626
+ down: migration089.down
613
627
  }
614
628
  ];
615
629