@myrialabs/clopen 0.4.48 → 0.4.49
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/message-pages.test.ts +163 -0
- package/backend/chat/message-pages.ts +233 -0
- package/backend/chat/stream-manager.ts +29 -5
- package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/blob-line-stats-queries.ts +48 -0
- package/backend/database/queries/index.ts +2 -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/files/file-watcher.ts +19 -0
- package/backend/git/contributors.test.ts +35 -0
- package/backend/git/contributors.ts +46 -0
- package/backend/http/static-assets.test.ts +78 -0
- package/backend/http/static-assets.ts +104 -0
- package/backend/index.ts +11 -9
- package/backend/preview/browser/browser-preview-service.ts +24 -6
- 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 +41 -10
- package/backend/ws/files/read.ts +30 -0
- package/backend/ws/git/log.ts +52 -0
- package/backend/ws/messages/crud.ts +49 -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 +36 -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/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
- package/dist/assets/{index-CONlwAXZ.js → index-CrVWZH_D.js} +1 -1
- package/dist/assets/index-CrVWZH_D.js.br +0 -0
- package/dist/assets/index-CrVWZH_D.js.gz +0 -0
- package/dist/assets/{index-DJzwt-hq.js → index-DD0-3EWg.js} +1 -1
- package/dist/assets/index-DD0-3EWg.js.br +0 -0
- package/dist/assets/index-DD0-3EWg.js.gz +0 -0
- package/dist/assets/{main-nBOb9YOA.js → main-D2_TmcwQ.js} +604 -604
- package/dist/assets/main-D2_TmcwQ.js.br +0 -0
- package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
- package/dist/assets/main-Yucigcmf.css +1 -0
- package/dist/assets/main-Yucigcmf.css.br +0 -0
- package/dist/assets/main-Yucigcmf.css.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 +2 -3
- package/shared/types/unified/stream.ts +11 -1
- package/shared/utils/diff-calculator.test.ts +178 -41
- package/shared/utils/diff-calculator.ts +383 -100
- package/shared/utils/process-supervisor.test.ts +172 -0
- package/shared/utils/process-supervisor.ts +251 -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/main-BUiUL3eZ.css +0 -1
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Paging a chat's active branch: pages start at a turn so no turn is split,
|
|
3
|
+
* consecutive pages cover the branch exactly once, and the prompt index and
|
|
4
|
+
* task history cover what is not loaded.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
|
|
8
|
+
import { initializeDatabase, closeDatabase } from '$backend/database';
|
|
9
|
+
import { messageQueries, projectQueries, sessionQueries } from '$backend/database/queries';
|
|
10
|
+
import type { UnifiedMessage } from '$shared/types/unified';
|
|
11
|
+
|
|
12
|
+
import { getMessagePage, getPromptIndex, getTaskHistory } from './message-pages';
|
|
13
|
+
|
|
14
|
+
let projectId: string;
|
|
15
|
+
const engine = { type: 'claude-code', provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } };
|
|
16
|
+
const base = { createdAt: '2026-11-17T00:00:00.000Z', sessionId: null, engine };
|
|
17
|
+
|
|
18
|
+
const prompt = (text: string) =>
|
|
19
|
+
({ ...base, type: 'user', parent: { messageId: null, sessionId: null, toolUseId: null }, content: [{ type: 'text', text }] }) as unknown as UnifiedMessage;
|
|
20
|
+
const toolCall = (id: string, name = 'Read', input: unknown = {}) =>
|
|
21
|
+
({ ...base, type: 'assistant', parent: { messageId: null, sessionId: null, toolUseId: null }, content: [{ type: 'tool_use', id, name, input }] }) as unknown as UnifiedMessage;
|
|
22
|
+
const toolResult = (toolUseId: string, content = 'ok') =>
|
|
23
|
+
({ ...base, type: 'user', parent: { messageId: null, sessionId: null, toolUseId: null }, content: [{ type: 'tool_result', toolUseId, content }] }) as unknown as UnifiedMessage;
|
|
24
|
+
const answer = (text: string) =>
|
|
25
|
+
({ ...base, type: 'assistant', parent: { messageId: null, sessionId: null, toolUseId: null }, content: [{ type: 'text', text }] }) as unknown as UnifiedMessage;
|
|
26
|
+
|
|
27
|
+
function newSession(): string {
|
|
28
|
+
return sessionQueries.create({ project_id: projectId, engine: 'claude-code', started_at: new Date().toISOString() } as never).id;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Build a branch of turns: each turn = prompt, N tool call/result pairs, answer. */
|
|
32
|
+
function buildBranch(sessionId: string, turns: number, toolsPerTurn: number): string[] {
|
|
33
|
+
const ids: string[] = [];
|
|
34
|
+
let parent: string | undefined;
|
|
35
|
+
const push = (message: UnifiedMessage) => {
|
|
36
|
+
const row = messageQueries.create({ session_id: sessionId, message, parent_message_id: parent });
|
|
37
|
+
parent = row.id;
|
|
38
|
+
ids.push(row.id);
|
|
39
|
+
sessionQueries.updateHead(sessionId, row.id);
|
|
40
|
+
};
|
|
41
|
+
for (let t = 0; t < turns; t++) {
|
|
42
|
+
push(prompt(`turn ${t}`));
|
|
43
|
+
for (let k = 0; k < toolsPerTurn; k++) {
|
|
44
|
+
push(toolCall(`call-${t}-${k}`));
|
|
45
|
+
push(toolResult(`call-${t}-${k}`));
|
|
46
|
+
}
|
|
47
|
+
push(answer(`done ${t}`));
|
|
48
|
+
}
|
|
49
|
+
return ids;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const textOf = (message: UnifiedMessage) =>
|
|
53
|
+
message.type === 'user' || message.type === 'assistant'
|
|
54
|
+
? (message.content.find((block) => block.type === 'text') as { text?: string } | undefined)?.text
|
|
55
|
+
: undefined;
|
|
56
|
+
|
|
57
|
+
beforeAll(async () => {
|
|
58
|
+
await initializeDatabase();
|
|
59
|
+
projectId = projectQueries.create({ name: 'message-pages', path: `/tmp/message-pages-${crypto.randomUUID()}`, created_at: new Date().toISOString(), last_opened_at: new Date().toISOString() } as never).id;
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
afterAll(() => {
|
|
63
|
+
sessionQueries.deleteAllByProjectId(projectId);
|
|
64
|
+
projectQueries.deleteProject(projectId);
|
|
65
|
+
closeDatabase();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
describe('getMessagePage', () => {
|
|
69
|
+
it('never splits a tool call from its result, even inside a long turn', () => {
|
|
70
|
+
const session = newSession();
|
|
71
|
+
buildBranch(session, 2, 60); // two turns of 122 messages each
|
|
72
|
+
|
|
73
|
+
const page = getMessagePage(session, { minCount: 10 });
|
|
74
|
+
expect(page.messages.length).toBeLessThan(20); // cut inside the turn, not at its start
|
|
75
|
+
expect(page.hasMore).toBe(true);
|
|
76
|
+
const calls = new Set<string>();
|
|
77
|
+
for (const message of page.messages) {
|
|
78
|
+
if (message.type !== 'user' && message.type !== 'assistant') continue;
|
|
79
|
+
for (const block of message.content) {
|
|
80
|
+
if (block.type === 'tool_use') calls.add(block.id);
|
|
81
|
+
if (block.type === 'tool_result') expect(calls.has((block as { toolUseId: string }).toolUseId)).toBe(true);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('does not begin a page with a synthetic message, nor split a sub-agent from its call', () => {
|
|
87
|
+
const session = newSession();
|
|
88
|
+
let parent: string | undefined;
|
|
89
|
+
const push = (message: UnifiedMessage) => {
|
|
90
|
+
const row = messageQueries.create({ session_id: session, message, parent_message_id: parent });
|
|
91
|
+
parent = row.id;
|
|
92
|
+
sessionQueries.updateHead(session, row.id);
|
|
93
|
+
};
|
|
94
|
+
push(prompt('start'));
|
|
95
|
+
push(toolCall('agent-1', 'Agent'));
|
|
96
|
+
push({ ...(prompt('sub-agent work') as object), parent: { messageId: null, sessionId: null, toolUseId: 'agent-1' } } as unknown as UnifiedMessage);
|
|
97
|
+
push({ ...(answer('sub-agent answer') as object), parent: { messageId: null, sessionId: null, toolUseId: 'agent-1' } } as unknown as UnifiedMessage);
|
|
98
|
+
push(toolResult('agent-1'));
|
|
99
|
+
push(toolCall('skill-1', 'Skill'));
|
|
100
|
+
push({ ...(prompt('expanded skill prompt') as object), synthetic: true } as unknown as UnifiedMessage);
|
|
101
|
+
|
|
102
|
+
const page = getMessagePage(session, { minCount: 1 });
|
|
103
|
+
expect((page.messages[0] as { synthetic?: boolean }).synthetic).not.toBe(true);
|
|
104
|
+
const texts = page.messages.map(textOf);
|
|
105
|
+
if (texts.includes('sub-agent work')) expect(page.messages.some((m) => JSON.stringify(m).includes('"id":"agent-1"'))).toBe(true);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('pages back through the whole branch exactly once, in order', () => {
|
|
109
|
+
const session = newSession();
|
|
110
|
+
const ids = buildBranch(session, 12, 2);
|
|
111
|
+
|
|
112
|
+
const collected: string[] = [];
|
|
113
|
+
let before: string | undefined;
|
|
114
|
+
for (let guard = 0; guard < 50; guard++) {
|
|
115
|
+
const page = getMessagePage(session, { beforeId: before, minCount: 7 });
|
|
116
|
+
collected.unshift(...page.messages.map((message) => (message as { messageId: string }).messageId));
|
|
117
|
+
if (!page.hasMore) break;
|
|
118
|
+
before = (page.messages[0] as { messageId: string }).messageId;
|
|
119
|
+
}
|
|
120
|
+
expect(collected).toEqual(ids);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('answers an empty page for a session with no messages, or an unknown cursor', () => {
|
|
124
|
+
const session = newSession();
|
|
125
|
+
expect(getMessagePage(session)).toEqual({ messages: [], hasMore: false });
|
|
126
|
+
buildBranch(session, 1, 0);
|
|
127
|
+
expect(getMessagePage(session, { beforeId: 'not-a-message' })).toEqual({ messages: [], hasMore: false });
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
describe('getPromptIndex', () => {
|
|
132
|
+
it('lists every real prompt on the branch, oldest first, with no tool results', () => {
|
|
133
|
+
const session = newSession();
|
|
134
|
+
buildBranch(session, 4, 2);
|
|
135
|
+
expect(getPromptIndex(session).map((entry) => entry.text)).toEqual(['turn 0', 'turn 1', 'turn 2', 'turn 3']);
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
describe('getTaskHistory', () => {
|
|
140
|
+
it('returns the task calls and their results older than a message, and nothing else', () => {
|
|
141
|
+
const session = newSession();
|
|
142
|
+
let parent: string | undefined;
|
|
143
|
+
const push = (message: UnifiedMessage) => {
|
|
144
|
+
const row = messageQueries.create({ session_id: session, message, parent_message_id: parent });
|
|
145
|
+
parent = row.id;
|
|
146
|
+
sessionQueries.updateHead(session, row.id);
|
|
147
|
+
return row.id;
|
|
148
|
+
};
|
|
149
|
+
push(prompt('plan'));
|
|
150
|
+
push(toolCall('task-1', 'TaskCreate', { subject: 'Write tests' }));
|
|
151
|
+
push(toolResult('task-1', 'Task #1 created'));
|
|
152
|
+
push(toolCall('read-1', 'Read'));
|
|
153
|
+
push(toolResult('read-1', 'file body'));
|
|
154
|
+
const later = push(prompt('next'));
|
|
155
|
+
push(toolCall('task-2', 'TaskUpdate', { taskId: '1', status: 'completed' }));
|
|
156
|
+
|
|
157
|
+
const history = getTaskHistory(session, later);
|
|
158
|
+
expect(history.map((message) => message.type)).toEqual(['assistant', 'user']);
|
|
159
|
+
expect(JSON.stringify(history)).toContain('task-1');
|
|
160
|
+
expect(JSON.stringify(history)).not.toContain('read-1');
|
|
161
|
+
expect(JSON.stringify(history)).not.toContain('task-2'); // newer than the cursor
|
|
162
|
+
});
|
|
163
|
+
});
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading a chat's active branch a page at a time.
|
|
3
|
+
*
|
|
4
|
+
* Opening a chat used to send its whole branch — every message since the first,
|
|
5
|
+
* images included — which on a long chat was tens of megabytes on every open.
|
|
6
|
+
* The chat now loads its most recent turns and fetches older ones as the user
|
|
7
|
+
* scrolls up (or jumps to a message that is not loaded yet).
|
|
8
|
+
*
|
|
9
|
+
* A page never starts where it would split something the chat renders as one:
|
|
10
|
+
* every tool result and every sub-agent message in it has its tool call in the
|
|
11
|
+
* same page, and it does not begin with a synthetic user message (a compaction
|
|
12
|
+
* summary or an expanded skill prompt, which belong to the message before
|
|
13
|
+
* them). That is checked on the page itself, so a boundary can fall inside a
|
|
14
|
+
* long agent turn — turns of several hundred messages are common, and cutting
|
|
15
|
+
* only at user prompts made the first page nearly the whole chat. A user
|
|
16
|
+
* prompt always qualifies.
|
|
17
|
+
*
|
|
18
|
+
* Two things the chat needs from the WHOLE branch are served separately and
|
|
19
|
+
* cheaply, without message bodies the user is not looking at:
|
|
20
|
+
* - the prompt index (the navigation rail's dots, one per user prompt);
|
|
21
|
+
* - the task tools older than the loaded page (the task progress widget
|
|
22
|
+
* replays TaskCreate / TaskUpdate / TodoWrite from the start).
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { getDatabase } from '../database';
|
|
26
|
+
import type { DatabaseMessage } from '$shared/types/database/schema';
|
|
27
|
+
import type { UnifiedMessage } from '$shared/types/unified';
|
|
28
|
+
import { trimSubAgentForWire } from '$shared/utils/subagent-wire-trim';
|
|
29
|
+
import { isCheckpointMessage, extractMessageText } from '../snapshot/helpers';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Walks a branch from newest to oldest and says where a page may begin: at a
|
|
33
|
+
* message no later message depends on from across the boundary.
|
|
34
|
+
*/
|
|
35
|
+
class BoundaryTracker {
|
|
36
|
+
private readonly defined = new Set<string>();
|
|
37
|
+
private readonly needed = new Set<string>();
|
|
38
|
+
|
|
39
|
+
/** Record `message` (older than everything seen so far); true if a page may start at it. */
|
|
40
|
+
add(message: UnifiedMessage): boolean {
|
|
41
|
+
if (message.type === 'user' || message.type === 'assistant') {
|
|
42
|
+
const parentToolUseId = message.parent?.toolUseId;
|
|
43
|
+
if (parentToolUseId && !this.defined.has(parentToolUseId)) this.needed.add(parentToolUseId);
|
|
44
|
+
for (const block of message.content) {
|
|
45
|
+
if (block.type === 'tool_result') {
|
|
46
|
+
const id = (block as { toolUseId?: string }).toolUseId;
|
|
47
|
+
if (id && !this.defined.has(id)) this.needed.add(id);
|
|
48
|
+
} else if (block.type === 'tool_use') {
|
|
49
|
+
this.defined.add(block.id);
|
|
50
|
+
this.needed.delete(block.id);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const synthetic = message.type === 'user' && (message as { synthetic?: boolean }).synthetic === true;
|
|
55
|
+
return this.needed.size === 0 && !synthetic;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Messages a page holds at least — then it is extended back to the start of a turn. */
|
|
60
|
+
export const DEFAULT_PAGE_SIZE = 80;
|
|
61
|
+
|
|
62
|
+
/** Longest prompt preview the navigation rail shows. */
|
|
63
|
+
const PROMPT_PREVIEW_LENGTH = 200;
|
|
64
|
+
|
|
65
|
+
/** Tools the task progress widget replays. */
|
|
66
|
+
const TASK_TOOLS = ['TaskCreate', 'TaskUpdate', 'TodoWrite'] as const;
|
|
67
|
+
|
|
68
|
+
export interface MessagePage {
|
|
69
|
+
/** Oldest first, as the chat renders them. */
|
|
70
|
+
messages: UnifiedMessage[];
|
|
71
|
+
/** Whether older messages exist on the branch before this page. */
|
|
72
|
+
hasMore: boolean;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface PromptIndexEntry {
|
|
76
|
+
messageId: string;
|
|
77
|
+
text: string;
|
|
78
|
+
createdAt: string;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function headOf(sessionId: string): string | null {
|
|
82
|
+
const row = getDatabase()
|
|
83
|
+
.prepare('SELECT head_message_id FROM chat_sessions WHERE id = ?')
|
|
84
|
+
.get(sessionId) as { head_message_id: string | null } | null;
|
|
85
|
+
return row?.head_message_id ?? null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* One page of the active branch, ending just before `beforeId` (or at the head
|
|
90
|
+
* when absent). Holds at least `minCount` messages and always begins at a turn.
|
|
91
|
+
*/
|
|
92
|
+
export function getMessagePage(
|
|
93
|
+
sessionId: string,
|
|
94
|
+
options: { beforeId?: string; minCount?: number } = {}
|
|
95
|
+
): MessagePage {
|
|
96
|
+
const minCount = Math.max(1, options.minCount ?? DEFAULT_PAGE_SIZE);
|
|
97
|
+
const byId = getDatabase().prepare('SELECT * FROM messages WHERE id = ? AND session_id = ?');
|
|
98
|
+
|
|
99
|
+
let cursor: string | null;
|
|
100
|
+
if (options.beforeId) {
|
|
101
|
+
const anchor = byId.get(options.beforeId, sessionId) as DatabaseMessage | null;
|
|
102
|
+
if (!anchor) return { messages: [], hasMore: false };
|
|
103
|
+
cursor = anchor.parent_message_id ?? null;
|
|
104
|
+
} else {
|
|
105
|
+
cursor = headOf(sessionId);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const messages: UnifiedMessage[] = [];
|
|
109
|
+
const boundary = new BoundaryTracker();
|
|
110
|
+
while (cursor) {
|
|
111
|
+
const row = byId.get(cursor, sessionId) as DatabaseMessage | null;
|
|
112
|
+
if (!row) {
|
|
113
|
+
cursor = null;
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
const message = JSON.parse(row.data) as UnifiedMessage;
|
|
117
|
+
messages.push(message);
|
|
118
|
+
cursor = row.parent_message_id ?? null;
|
|
119
|
+
const mayStartHere = boundary.add(message);
|
|
120
|
+
if (messages.length >= minCount && mayStartHere) break;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
messages: messages.reverse().map(trimSubAgentForWire),
|
|
125
|
+
hasMore: cursor !== null && byId.get(cursor, sessionId) != null
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The branch, newest first, as light rows: id and parent for every message,
|
|
131
|
+
* plus the body only where `wantBody` says so (decided in SQL, so the bodies
|
|
132
|
+
* of everything else — tool output, images — are never read into JS).
|
|
133
|
+
*/
|
|
134
|
+
function branchRows(
|
|
135
|
+
sessionId: string,
|
|
136
|
+
wantBody: string,
|
|
137
|
+
fromId: string | null
|
|
138
|
+
): Array<{ id: string; parent_message_id: string | null; data: string | null }> {
|
|
139
|
+
if (!fromId) return [];
|
|
140
|
+
const rows = getDatabase()
|
|
141
|
+
.prepare(`SELECT id, parent_message_id, CASE WHEN ${wantBody} THEN data END AS data FROM messages WHERE session_id = ?`)
|
|
142
|
+
.all(sessionId) as Array<{ id: string; parent_message_id: string | null; data: string | null }>;
|
|
143
|
+
const byId = new Map(rows.map((row) => [row.id, row]));
|
|
144
|
+
|
|
145
|
+
const branch: typeof rows = [];
|
|
146
|
+
const seen = new Set<string>();
|
|
147
|
+
let cursor: string | null = fromId;
|
|
148
|
+
while (cursor && !seen.has(cursor)) {
|
|
149
|
+
seen.add(cursor);
|
|
150
|
+
const row = byId.get(cursor);
|
|
151
|
+
if (!row) break;
|
|
152
|
+
branch.push(row);
|
|
153
|
+
cursor = row.parent_message_id;
|
|
154
|
+
}
|
|
155
|
+
return branch;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Every user prompt on the active branch, oldest first — the navigation rail. */
|
|
159
|
+
export function getPromptIndex(sessionId: string): PromptIndexEntry[] {
|
|
160
|
+
const rows = branchRows(sessionId, `json_extract(data, '$.type') = 'user'`, headOf(sessionId));
|
|
161
|
+
const prompts: PromptIndexEntry[] = [];
|
|
162
|
+
for (let i = rows.length - 1; i >= 0; i--) {
|
|
163
|
+
const row = rows[i];
|
|
164
|
+
if (!row.data) continue;
|
|
165
|
+
const asRow = row as unknown as DatabaseMessage;
|
|
166
|
+
if (!isCheckpointMessage(asRow)) continue;
|
|
167
|
+
const message = JSON.parse(row.data) as UnifiedMessage;
|
|
168
|
+
prompts.push({
|
|
169
|
+
messageId: row.id,
|
|
170
|
+
text: extractMessageText(message).slice(0, PROMPT_PREVIEW_LENGTH),
|
|
171
|
+
createdAt: (message as { createdAt?: string }).createdAt ?? ''
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
return prompts;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* The task-tool calls (and their results) on the branch older than `beforeId`,
|
|
179
|
+
* oldest first. Together with the loaded messages this is exactly what the task
|
|
180
|
+
* widget used to replay from the full branch.
|
|
181
|
+
*/
|
|
182
|
+
export function getTaskHistory(sessionId: string, beforeId: string): UnifiedMessage[] {
|
|
183
|
+
const parent = getDatabase()
|
|
184
|
+
.prepare('SELECT parent_message_id FROM messages WHERE id = ? AND session_id = ?')
|
|
185
|
+
.get(beforeId, sessionId) as { parent_message_id: string | null } | null;
|
|
186
|
+
if (!parent?.parent_message_id) return [];
|
|
187
|
+
|
|
188
|
+
// Pass 1: the branch, with bodies only for messages that call a task tool.
|
|
189
|
+
const mentionsTaskTool = TASK_TOOLS.map((name) => `instr(data, '"name":"${name}"') > 0`).join(' OR ');
|
|
190
|
+
const branch = branchRows(sessionId, mentionsTaskTool, parent.parent_message_id).reverse();
|
|
191
|
+
|
|
192
|
+
const taskCallIds = new Set<string>();
|
|
193
|
+
const calls = new Map<string, UnifiedMessage>();
|
|
194
|
+
for (const row of branch) {
|
|
195
|
+
if (!row.data) continue;
|
|
196
|
+
const message = JSON.parse(row.data) as UnifiedMessage;
|
|
197
|
+
if (message.type !== 'assistant') continue;
|
|
198
|
+
let hasTaskCall = false;
|
|
199
|
+
for (const block of message.content) {
|
|
200
|
+
if (block.type === 'tool_use' && (TASK_TOOLS as readonly string[]).includes(block.name)) {
|
|
201
|
+
taskCallIds.add(block.id);
|
|
202
|
+
hasTaskCall = true;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (hasTaskCall) calls.set(row.id, message);
|
|
206
|
+
}
|
|
207
|
+
if (taskCallIds.size === 0) return [];
|
|
208
|
+
|
|
209
|
+
// Pass 2: only the messages that answer one of those calls — never the
|
|
210
|
+
// thousands of other tool results (file reads, screenshots) on the branch.
|
|
211
|
+
const ids = [...taskCallIds];
|
|
212
|
+
const answerRows = getDatabase()
|
|
213
|
+
.prepare(
|
|
214
|
+
`SELECT id, data FROM messages WHERE session_id = ? AND (${ids.map(() => 'instr(data, ?) > 0').join(' OR ')})`
|
|
215
|
+
)
|
|
216
|
+
.all(sessionId, ...ids.map((id) => `"toolUseId":"${id}"`)) as Array<{ id: string; data: string }>;
|
|
217
|
+
const answers = new Map<string, UnifiedMessage>();
|
|
218
|
+
for (const row of answerRows) {
|
|
219
|
+
const message = JSON.parse(row.data) as UnifiedMessage;
|
|
220
|
+
if (message.type !== 'user') continue;
|
|
221
|
+
const answersTask = message.content.some(
|
|
222
|
+
(block) => block.type === 'tool_result' && taskCallIds.has((block as { toolUseId: string }).toolUseId)
|
|
223
|
+
);
|
|
224
|
+
if (answersTask) answers.set(row.id, message);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const history: UnifiedMessage[] = [];
|
|
228
|
+
for (const row of branch) {
|
|
229
|
+
const message = calls.get(row.id) ?? answers.get(row.id);
|
|
230
|
+
if (message) history.push(message);
|
|
231
|
+
}
|
|
232
|
+
return history;
|
|
233
|
+
}
|
|
@@ -78,6 +78,13 @@ export interface StreamState {
|
|
|
78
78
|
currentMessage?: UnifiedMessage;
|
|
79
79
|
currentPartialText?: string;
|
|
80
80
|
currentReasoningText?: string;
|
|
81
|
+
/**
|
|
82
|
+
* Which streamed block `currentPartialText` / `currentReasoningText` belong
|
|
83
|
+
* to. Bumped on every `start`, so a catch-up snapshot of one block can never
|
|
84
|
+
* be mistaken for the text of the next.
|
|
85
|
+
*/
|
|
86
|
+
partialBlock?: number;
|
|
87
|
+
reasoningBlock?: number;
|
|
81
88
|
error?: string;
|
|
82
89
|
abortController?: AbortController;
|
|
83
90
|
streamPromise?: Promise<void>;
|
|
@@ -1106,17 +1113,28 @@ class StreamManager extends EventEmitter {
|
|
|
1106
1113
|
case 'stream_event': {
|
|
1107
1114
|
const streamEvt = output as UnifiedStreamEvent;
|
|
1108
1115
|
|
|
1116
|
+
// Partials carry the DELTA, not the text so far. Re-sending the
|
|
1117
|
+
// whole accumulated text on every token made a turn cost the sum
|
|
1118
|
+
// of all its prefixes — quadratic in its length, ~115× the text
|
|
1119
|
+
// itself on real chats. `offset` (the length before this delta)
|
|
1120
|
+
// and `block` let a client that joins mid-block or misses a frame
|
|
1121
|
+
// tell exactly what it has and resync instead of guessing; `end`
|
|
1122
|
+
// still carries the full text once, as the reconciliation point.
|
|
1109
1123
|
if (streamEvt.event === 'start') {
|
|
1110
1124
|
const lifecycle = streamEvt as StreamLifecycleEvent;
|
|
1125
|
+
let block: number;
|
|
1111
1126
|
if (lifecycle.reasoning) {
|
|
1112
1127
|
streamState.currentReasoningText = '';
|
|
1128
|
+
block = streamState.reasoningBlock = (streamState.reasoningBlock ?? 0) + 1;
|
|
1113
1129
|
} else {
|
|
1114
1130
|
streamState.currentPartialText = '';
|
|
1131
|
+
block = streamState.partialBlock = (streamState.partialBlock ?? 0) + 1;
|
|
1115
1132
|
}
|
|
1116
1133
|
this.emitStreamEvent(streamState, 'partial', {
|
|
1117
1134
|
processId: streamState.processId,
|
|
1118
1135
|
eventType: 'start',
|
|
1119
|
-
|
|
1136
|
+
block,
|
|
1137
|
+
offset: 0,
|
|
1120
1138
|
deltaText: '',
|
|
1121
1139
|
...(lifecycle.reasoning && { reasoning: true }),
|
|
1122
1140
|
timestamp: new Date().toISOString()
|
|
@@ -1124,21 +1142,25 @@ class StreamManager extends EventEmitter {
|
|
|
1124
1142
|
} else if (streamEvt.event === 'delta') {
|
|
1125
1143
|
const delta = streamEvt as TextDeltaEvent;
|
|
1126
1144
|
if (delta.reasoning) {
|
|
1127
|
-
|
|
1145
|
+
const before = streamState.currentReasoningText || '';
|
|
1146
|
+
streamState.currentReasoningText = before + delta.text;
|
|
1128
1147
|
this.emitStreamEvent(streamState, 'partial', {
|
|
1129
1148
|
processId: streamState.processId,
|
|
1130
1149
|
eventType: 'update',
|
|
1131
|
-
|
|
1150
|
+
block: streamState.reasoningBlock ?? 0,
|
|
1151
|
+
offset: before.length,
|
|
1132
1152
|
deltaText: delta.text,
|
|
1133
1153
|
reasoning: true,
|
|
1134
1154
|
timestamp: new Date().toISOString()
|
|
1135
1155
|
});
|
|
1136
1156
|
} else {
|
|
1137
|
-
|
|
1157
|
+
const before = streamState.currentPartialText || '';
|
|
1158
|
+
streamState.currentPartialText = before + delta.text;
|
|
1138
1159
|
this.emitStreamEvent(streamState, 'partial', {
|
|
1139
1160
|
processId: streamState.processId,
|
|
1140
1161
|
eventType: 'update',
|
|
1141
|
-
|
|
1162
|
+
block: streamState.partialBlock ?? 0,
|
|
1163
|
+
offset: before.length,
|
|
1142
1164
|
deltaText: delta.text,
|
|
1143
1165
|
timestamp: new Date().toISOString()
|
|
1144
1166
|
});
|
|
@@ -1149,6 +1171,7 @@ class StreamManager extends EventEmitter {
|
|
|
1149
1171
|
this.emitStreamEvent(streamState, 'partial', {
|
|
1150
1172
|
processId: streamState.processId,
|
|
1151
1173
|
eventType: 'end',
|
|
1174
|
+
block: streamState.reasoningBlock ?? 0,
|
|
1152
1175
|
partialText: streamState.currentReasoningText,
|
|
1153
1176
|
deltaText: '',
|
|
1154
1177
|
reasoning: true,
|
|
@@ -1159,6 +1182,7 @@ class StreamManager extends EventEmitter {
|
|
|
1159
1182
|
this.emitStreamEvent(streamState, 'partial', {
|
|
1160
1183
|
processId: streamState.processId,
|
|
1161
1184
|
eventType: 'end',
|
|
1185
|
+
block: streamState.partialBlock ?? 0,
|
|
1162
1186
|
partialText: streamState.currentPartialText || '',
|
|
1163
1187
|
deltaText: '',
|
|
1164
1188
|
timestamp: new Date().toISOString()
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { DatabaseConnection } from '$shared/types/database/connection';
|
|
2
|
+
import { debug } from '$shared/utils/logger';
|
|
3
|
+
|
|
4
|
+
export const description = 'Create blob_line_stats to count each pair of file versions once';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The +/- line counts of one pair of snapshot blobs.
|
|
8
|
+
*
|
|
9
|
+
* Blobs are content-addressed (sha256), so the count for a given
|
|
10
|
+
* (old_hash, new_hash) can never change — it is computed the first time any
|
|
11
|
+
* surface asks and read from here ever after. Every chat open used to re-diff
|
|
12
|
+
* every changed file of every turn, twice; on a chat that touched a large
|
|
13
|
+
* generated file that recomputation alone could block the server for minutes.
|
|
14
|
+
*
|
|
15
|
+
* An empty hash is a side that does not exist (a created or deleted file).
|
|
16
|
+
* Rows are pruned together with the blobs they describe.
|
|
17
|
+
*/
|
|
18
|
+
export const up = (db: DatabaseConnection): void => {
|
|
19
|
+
debug.log('migration', '📋 Creating blob_line_stats table...');
|
|
20
|
+
db.exec(`
|
|
21
|
+
CREATE TABLE IF NOT EXISTS blob_line_stats (
|
|
22
|
+
old_hash TEXT NOT NULL,
|
|
23
|
+
new_hash TEXT NOT NULL,
|
|
24
|
+
insertions INTEGER NOT NULL,
|
|
25
|
+
deletions INTEGER NOT NULL,
|
|
26
|
+
is_binary INTEGER NOT NULL DEFAULT 0,
|
|
27
|
+
PRIMARY KEY (old_hash, new_hash)
|
|
28
|
+
) WITHOUT ROWID
|
|
29
|
+
`);
|
|
30
|
+
db.exec('CREATE INDEX IF NOT EXISTS idx_blob_line_stats_new_hash ON blob_line_stats (new_hash)');
|
|
31
|
+
debug.log('migration', '✅ blob_line_stats table created');
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export const down = (db: DatabaseConnection): void => {
|
|
35
|
+
db.exec('DROP INDEX IF EXISTS idx_blob_line_stats_new_hash');
|
|
36
|
+
db.exec('DROP TABLE IF EXISTS blob_line_stats');
|
|
37
|
+
};
|
|
@@ -85,6 +85,7 @@ import * as migration083 from './083_create_project_mcp_trust';
|
|
|
85
85
|
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
|
+
import * as migration087 from './087_create_blob_line_stats';
|
|
88
89
|
|
|
89
90
|
// Export all migrations in order
|
|
90
91
|
export const migrations = [
|
|
@@ -603,6 +604,12 @@ export const migrations = [
|
|
|
603
604
|
description: migration086.description,
|
|
604
605
|
up: migration086.up,
|
|
605
606
|
down: migration086.down
|
|
607
|
+
},
|
|
608
|
+
{
|
|
609
|
+
id: '087',
|
|
610
|
+
description: migration087.description,
|
|
611
|
+
up: migration087.up,
|
|
612
|
+
down: migration087.down
|
|
606
613
|
}
|
|
607
614
|
];
|
|
608
615
|
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cached +/- line counts per pair of snapshot blobs (see migration 087).
|
|
3
|
+
*
|
|
4
|
+
* Keyed by content hashes, so a row is true forever: the only writes are the
|
|
5
|
+
* first computation of a pair and the prune that follows its blobs out.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { getDatabase } from '../index';
|
|
9
|
+
|
|
10
|
+
export interface BlobLineStatsRow {
|
|
11
|
+
insertions: number;
|
|
12
|
+
deletions: number;
|
|
13
|
+
isBinary: boolean;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const blobLineStatsQueries = {
|
|
17
|
+
get(oldHash: string, newHash: string): BlobLineStatsRow | null {
|
|
18
|
+
const row = getDatabase()
|
|
19
|
+
.prepare('SELECT insertions, deletions, is_binary FROM blob_line_stats WHERE old_hash = ? AND new_hash = ?')
|
|
20
|
+
.get(oldHash, newHash) as { insertions: number; deletions: number; is_binary: number } | null;
|
|
21
|
+
return row ? { insertions: row.insertions, deletions: row.deletions, isBinary: row.is_binary === 1 } : null;
|
|
22
|
+
},
|
|
23
|
+
|
|
24
|
+
save(oldHash: string, newHash: string, stats: BlobLineStatsRow): void {
|
|
25
|
+
getDatabase()
|
|
26
|
+
.prepare(`
|
|
27
|
+
INSERT OR IGNORE INTO blob_line_stats (old_hash, new_hash, insertions, deletions, is_binary)
|
|
28
|
+
VALUES (?, ?, ?, ?, ?)
|
|
29
|
+
`)
|
|
30
|
+
.run(oldHash, newHash, stats.insertions, stats.deletions, stats.isBinary ? 1 : 0);
|
|
31
|
+
},
|
|
32
|
+
|
|
33
|
+
/** Drop every pair that names one of these blobs — they are gone from the store. */
|
|
34
|
+
deleteByHashes(hashes: string[]): void {
|
|
35
|
+
const db = getDatabase();
|
|
36
|
+
const byOld = db.prepare('DELETE FROM blob_line_stats WHERE old_hash = ?');
|
|
37
|
+
const byNew = db.prepare('DELETE FROM blob_line_stats WHERE new_hash = ?');
|
|
38
|
+
const prune = () => {
|
|
39
|
+
for (const hash of hashes) {
|
|
40
|
+
if (!hash) continue;
|
|
41
|
+
byOld.run(hash);
|
|
42
|
+
byNew.run(hash);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
if (db.transaction) db.transaction(prune)();
|
|
46
|
+
else prune();
|
|
47
|
+
}
|
|
48
|
+
};
|
|
@@ -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';
|
|
@@ -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
|