@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.
- package/backend/chat/background-wait.test.ts +28 -0
- package/backend/chat/message-pages.test.ts +180 -0
- package/backend/chat/message-pages.ts +237 -0
- package/backend/chat/stream-manager.ts +101 -18
- package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
- 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 +21 -0
- package/backend/database/queries/blob-line-stats-queries.ts +48 -0
- package/backend/database/queries/graph-queries.ts +392 -135
- package/backend/database/queries/index.ts +2 -0
- 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/db-client/env/diff.ts +9 -33
- package/backend/db-client/env/env.test.ts +8 -8
- package/backend/db-client/env/service.ts +1 -1
- 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/files/file-watcher.ts +19 -0
- package/backend/git/contributors.test.ts +35 -0
- package/backend/git/contributors.ts +46 -0
- package/backend/git/identity/scope-config.test.ts +7 -4
- package/backend/http/static-assets.test.ts +78 -0
- package/backend/http/static-assets.ts +104 -0
- package/backend/index.ts +46 -17
- 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/preview/browser/browser-preview-service.ts +24 -6
- package/backend/project/status-manager.ts +4 -2
- package/backend/snapshot/blob-store.ts +9 -1
- package/backend/snapshot/helpers.ts +3 -10
- package/backend/snapshot/line-stats.test.ts +80 -0
- package/backend/snapshot/line-stats.ts +64 -0
- package/backend/snapshot/snapshot-service.ts +14 -27
- package/backend/snapshot/turn-changes.test.ts +10 -5
- package/backend/snapshot/turn-changes.ts +78 -40
- package/backend/terminal/ptykit.ts +6 -1
- package/backend/utils/ws-wire.test.ts +87 -0
- package/backend/utils/ws-wire.ts +189 -0
- package/backend/utils/ws.ts +40 -38
- package/backend/ws/chat/stream.ts +60 -20
- package/backend/ws/files/read.ts +30 -0
- package/backend/ws/git/log.ts +52 -0
- package/backend/ws/memory/crud.ts +118 -81
- package/backend/ws/messages/crud.ts +51 -0
- package/backend/ws/preview/index.ts +2 -0
- package/backend/ws/preview/watchers.ts +84 -0
- package/backend/ws/sessions/crud.ts +8 -12
- package/backend/ws/snapshot/changes.ts +5 -6
- package/backend/ws/terminal/tunnel.ts +2 -2
- package/bin/clopen.ts +37 -30
- package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
- package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
- package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
- package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
- package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
- package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
- package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
- package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
- package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
- package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
- package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
- package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
- package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
- package/dist/assets/{index-DJzwt-hq.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-CONlwAXZ.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-nBOb9YOA.js → main-Da3JKoua.js} +623 -623
- package/dist/assets/main-Da3JKoua.js.br +0 -0
- package/dist/assets/main-Da3JKoua.js.gz +0 -0
- package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
- package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
- package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
- package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
- package/dist/fonts/dm-sans.css.br +0 -0
- package/dist/fonts/dm-sans.css.gz +0 -0
- package/dist/index.html +2 -2
- package/dist/index.html.br +0 -0
- package/dist/index.html.gz +0 -0
- package/dist/sw.js.br +0 -0
- package/dist/sw.js.gz +0 -0
- package/package.json +3 -4
- package/shared/types/memory.ts +96 -73
- package/shared/types/unified/index.ts +1 -0
- package/shared/types/unified/stream.ts +33 -2
- package/shared/utils/diff-calculator.test.ts +178 -41
- package/shared/utils/diff-calculator.ts +383 -100
- package/shared/utils/process-supervisor.test.ts +242 -0
- package/shared/utils/process-supervisor.ts +356 -0
- package/shared/utils/process-tree.ts +99 -0
- package/shared/utils/ws-chunk.test.ts +33 -0
- package/shared/utils/ws-chunk.ts +73 -0
- package/shared/utils/ws-client-chunks.test.ts +45 -0
- package/shared/utils/ws-client.ts +43 -0
- package/shared/utils/ws-server.ts +17 -14
- package/backend/database/migrations/086_single_owner.test.ts +0 -170
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +0 -1
- package/dist/assets/main-BUiUL3eZ.css +0 -1
|
@@ -5,6 +5,8 @@ export { messageQueries } from './message-queries';
|
|
|
5
5
|
export { settingsQueries } from './settings-queries';
|
|
6
6
|
export { dbUtils } from './utils-queries';
|
|
7
7
|
export { snapshotQueries } from './snapshot-queries';
|
|
8
|
+
export { blobLineStatsQueries } from './blob-line-stats-queries';
|
|
9
|
+
export type { BlobLineStatsRow } from './blob-line-stats-queries';
|
|
8
10
|
export { worktreeQueries } from './worktree-queries';
|
|
9
11
|
export { checkpointQueries } from './checkpoint-queries';
|
|
10
12
|
export { engineQueries } from './engine-queries';
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Exists because applying this feature EDITS SOMEONE'S CONFIGURATION FILE, and
|
|
5
5
|
* the only version of that which is defensible is one where they see the change
|
|
6
|
-
* first. `shared/utils/diff-calculator
|
|
7
|
-
*
|
|
6
|
+
* first. The edit script is the shared engine in `shared/utils/diff-calculator`,
|
|
7
|
+
* the same exact diff behind every other diff and +/- count in the app.
|
|
8
8
|
*
|
|
9
9
|
* Unchanged runs are collapsed to an ellipsis rather than dropped silently: a
|
|
10
10
|
* dotenv file can hold thirty unrelated variables, and a preview that showed
|
|
@@ -13,44 +13,20 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import type { DbEnvDiffLine } from '$shared/types/db-client';
|
|
16
|
+
import { diffSequencesAsync } from '$shared/utils/diff-calculator';
|
|
16
17
|
|
|
17
18
|
/** How many unchanged lines to keep on each side of a change. */
|
|
18
19
|
const CONTEXT = 2;
|
|
19
20
|
|
|
20
|
-
export function diffLines(before: string, after: string, context = CONTEXT): DbEnvDiffLine[] {
|
|
21
|
+
export async function diffLines(before: string, after: string, context = CONTEXT): Promise<DbEnvDiffLine[]> {
|
|
21
22
|
const a = before === '' ? [] : before.split('\n');
|
|
22
23
|
const b = after === '' ? [] : after.split('\n');
|
|
23
24
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
);
|
|
30
|
-
for (let i = a.length - 1; i >= 0; i -= 1) {
|
|
31
|
-
for (let j = b.length - 1; j >= 0; j -= 1) {
|
|
32
|
-
table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
const full: DbEnvDiffLine[] = [];
|
|
37
|
-
let i = 0;
|
|
38
|
-
let j = 0;
|
|
39
|
-
while (i < a.length && j < b.length) {
|
|
40
|
-
if (a[i] === b[j]) {
|
|
41
|
-
full.push({ kind: 'context', text: a[i] });
|
|
42
|
-
i += 1;
|
|
43
|
-
j += 1;
|
|
44
|
-
} else if (table[i + 1][j] >= table[i][j + 1]) {
|
|
45
|
-
full.push({ kind: 'removed', text: a[i] });
|
|
46
|
-
i += 1;
|
|
47
|
-
} else {
|
|
48
|
-
full.push({ kind: 'added', text: b[j] });
|
|
49
|
-
j += 1;
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
for (; i < a.length; i += 1) full.push({ kind: 'removed', text: a[i] });
|
|
53
|
-
for (; j < b.length; j += 1) full.push({ kind: 'added', text: b[j] });
|
|
25
|
+
const full: DbEnvDiffLine[] = (await diffSequencesAsync(a, b)).map((op): DbEnvDiffLine => {
|
|
26
|
+
if (op.type === 'keep') return { kind: 'context', text: a[op.oldIndex] };
|
|
27
|
+
if (op.type === 'delete') return { kind: 'removed', text: a[op.oldIndex] };
|
|
28
|
+
return { kind: 'added', text: b[op.newIndex] };
|
|
29
|
+
});
|
|
54
30
|
|
|
55
31
|
// A file's final newline shows up as a blank line gained or lost, which is
|
|
56
32
|
// not a change anyone means. Left in, it rendered as a lone `+` under every
|
|
@@ -545,30 +545,30 @@ describe('dbClientEnv.apply and remove', () => {
|
|
|
545
545
|
});
|
|
546
546
|
|
|
547
547
|
describe('diffLines', () => {
|
|
548
|
-
it('marks what went and what arrived', () => {
|
|
549
|
-
expect(diffLines('A=1\nB=2', 'A=1\nB=3')).toEqual([
|
|
548
|
+
it('marks what went and what arrived', async () => {
|
|
549
|
+
expect(await diffLines('A=1\nB=2', 'A=1\nB=3')).toEqual([
|
|
550
550
|
{ kind: 'context', text: 'A=1' },
|
|
551
551
|
{ kind: 'removed', text: 'B=2' },
|
|
552
552
|
{ kind: 'added', text: 'B=3' }
|
|
553
553
|
]);
|
|
554
554
|
});
|
|
555
555
|
|
|
556
|
-
it('collapses a long unchanged run instead of dropping it silently', () => {
|
|
556
|
+
it('collapses a long unchanged run instead of dropping it silently', async () => {
|
|
557
557
|
const before = Array.from({ length: 20 }, (_, i) => `K${i}=1`).join('\n');
|
|
558
558
|
const after = `${before}\nNEW=1`;
|
|
559
559
|
|
|
560
|
-
const diff = diffLines(before, after);
|
|
560
|
+
const diff = await diffLines(before, after);
|
|
561
561
|
expect(diff.filter((line) => line.text === '…')).toHaveLength(1);
|
|
562
562
|
expect(diff.at(-1)).toEqual({ kind: 'added', text: 'NEW=1' });
|
|
563
563
|
});
|
|
564
564
|
|
|
565
|
-
it('handles a file that did not exist, without a phantom blank line', () => {
|
|
566
|
-
expect(diffLines('', 'A=1\n')).toEqual([{ kind: 'added', text: 'A=1' }]);
|
|
565
|
+
it('handles a file that did not exist, without a phantom blank line', async () => {
|
|
566
|
+
expect(await diffLines('', 'A=1\n')).toEqual([{ kind: 'added', text: 'A=1' }]);
|
|
567
567
|
});
|
|
568
568
|
|
|
569
|
-
it('answers empty when nothing changed', () => {
|
|
569
|
+
it('answers empty when nothing changed', async () => {
|
|
570
570
|
// An ellipsis standing in for the whole file reads as "something is
|
|
571
571
|
// hidden here"; the honest rendering of no change is no diff.
|
|
572
|
-
expect(diffLines('A=1\nB=2\n', 'A=1\nB=2\n')).toEqual([]);
|
|
572
|
+
expect(await diffLines('A=1\nB=2\n', 'A=1\nB=2\n')).toEqual([]);
|
|
573
573
|
});
|
|
574
574
|
});
|
|
@@ -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);
|
|
@@ -116,6 +116,13 @@ const GIT_INTERNAL_IGNORED = new Set([
|
|
|
116
116
|
|
|
117
117
|
const GIT_DEBOUNCE_MS = 500;
|
|
118
118
|
|
|
119
|
+
/**
|
|
120
|
+
* Above this many changes in one flush, clients are told to resync instead of
|
|
121
|
+
* being sent the list. Every consumer of `files:changed` also handles
|
|
122
|
+
* `files:resync`, so the cut-off only changes the payload, not the outcome.
|
|
123
|
+
*/
|
|
124
|
+
const MAX_CHANGES_PER_EVENT = 1000;
|
|
125
|
+
|
|
119
126
|
/**
|
|
120
127
|
* Delay before re-resolving a project's git directories after an event arrived
|
|
121
128
|
* from one we do not know about yet. Debounced because the trigger is bursty:
|
|
@@ -776,6 +783,18 @@ class FileWatcherManager {
|
|
|
776
783
|
projectWatcher.pendingChanges.clear();
|
|
777
784
|
projectWatcher.debounceTimer = null;
|
|
778
785
|
|
|
786
|
+
// A burst this large (an install, a build writing its output, a checkout)
|
|
787
|
+
// is one resync, not a list of every path. Every client re-reads its view
|
|
788
|
+
// once either way; the list only added megabytes to each of them.
|
|
789
|
+
if (changes.length > MAX_CHANGES_PER_EVENT) {
|
|
790
|
+
ws.emit.project(scopeProjectId(projectId), 'files:resync', {
|
|
791
|
+
projectId,
|
|
792
|
+
timestamp: Date.now()
|
|
793
|
+
});
|
|
794
|
+
debug.log('file', `Collapsed ${changes.length} file changes into a resync for project ${projectId}`);
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
|
|
779
798
|
// Emit changes to users currently viewing the project
|
|
780
799
|
ws.emit.project(scopeProjectId(projectId), 'files:changed', {
|
|
781
800
|
projectId,
|