@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.
Files changed (114) hide show
  1. package/backend/chat/background-wait.test.ts +28 -0
  2. package/backend/chat/message-pages.test.ts +180 -0
  3. package/backend/chat/message-pages.ts +237 -0
  4. package/backend/chat/stream-manager.ts +101 -18
  5. package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
  6. package/backend/database/migrations/088_create_messages_fts_map.ts +52 -0
  7. package/backend/database/migrations/089_add_memory_layout_tiles.ts +58 -0
  8. package/backend/database/migrations/index.ts +21 -0
  9. package/backend/database/queries/blob-line-stats-queries.ts +48 -0
  10. package/backend/database/queries/graph-queries.ts +392 -135
  11. package/backend/database/queries/index.ts +2 -0
  12. package/backend/database/queries/message-fts.test.ts +120 -0
  13. package/backend/database/queries/message-queries.ts +45 -9
  14. package/backend/database/queries/session-queries.ts +3 -2
  15. package/backend/database/queries/utils-queries.ts +3 -0
  16. package/backend/db-client/env/diff.ts +9 -33
  17. package/backend/db-client/env/env.test.ts +8 -8
  18. package/backend/db-client/env/service.ts +1 -1
  19. package/backend/engine/adapters/claude/environment.ts +4 -0
  20. package/backend/engine/adapters/claude/input-gate.test.ts +59 -0
  21. package/backend/engine/adapters/claude/input-gate.ts +74 -0
  22. package/backend/engine/adapters/claude/message-converter.test.ts +16 -0
  23. package/backend/engine/adapters/claude/message-converter.ts +8 -0
  24. package/backend/engine/adapters/claude/stream.ts +15 -0
  25. package/backend/files/file-watcher.ts +19 -0
  26. package/backend/git/contributors.test.ts +35 -0
  27. package/backend/git/contributors.ts +46 -0
  28. package/backend/git/identity/scope-config.test.ts +7 -4
  29. package/backend/http/static-assets.test.ts +78 -0
  30. package/backend/http/static-assets.ts +104 -0
  31. package/backend/index.ts +46 -17
  32. package/backend/memory/README.md +7 -4
  33. package/backend/memory/layout.test.ts +377 -0
  34. package/backend/memory/layout.ts +1029 -265
  35. package/backend/memory/view.ts +257 -386
  36. package/backend/preview/browser/browser-preview-service.ts +24 -6
  37. package/backend/project/status-manager.ts +4 -2
  38. package/backend/snapshot/blob-store.ts +9 -1
  39. package/backend/snapshot/helpers.ts +3 -10
  40. package/backend/snapshot/line-stats.test.ts +80 -0
  41. package/backend/snapshot/line-stats.ts +64 -0
  42. package/backend/snapshot/snapshot-service.ts +14 -27
  43. package/backend/snapshot/turn-changes.test.ts +10 -5
  44. package/backend/snapshot/turn-changes.ts +78 -40
  45. package/backend/terminal/ptykit.ts +6 -1
  46. package/backend/utils/ws-wire.test.ts +87 -0
  47. package/backend/utils/ws-wire.ts +189 -0
  48. package/backend/utils/ws.ts +40 -38
  49. package/backend/ws/chat/stream.ts +60 -20
  50. package/backend/ws/files/read.ts +30 -0
  51. package/backend/ws/git/log.ts +52 -0
  52. package/backend/ws/memory/crud.ts +118 -81
  53. package/backend/ws/messages/crud.ts +51 -0
  54. package/backend/ws/preview/index.ts +2 -0
  55. package/backend/ws/preview/watchers.ts +84 -0
  56. package/backend/ws/sessions/crud.ts +8 -12
  57. package/backend/ws/snapshot/changes.ts +5 -6
  58. package/backend/ws/terminal/tunnel.ts +2 -2
  59. package/bin/clopen.ts +37 -30
  60. package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
  61. package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
  62. package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
  63. package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
  64. package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
  65. package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
  66. package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
  67. package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
  68. package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
  69. package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
  70. package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
  71. package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
  72. package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
  73. package/dist/assets/{index-DJzwt-hq.js → index-By6KdSLT.js} +1 -1
  74. package/dist/assets/index-By6KdSLT.js.br +0 -0
  75. package/dist/assets/index-By6KdSLT.js.gz +0 -0
  76. package/dist/assets/{index-CONlwAXZ.js → index-DV4TiDn1.js} +1 -1
  77. package/dist/assets/index-DV4TiDn1.js.br +0 -0
  78. package/dist/assets/index-DV4TiDn1.js.gz +0 -0
  79. package/dist/assets/main-DIESTGTD.css +1 -0
  80. package/dist/assets/main-DIESTGTD.css.br +0 -0
  81. package/dist/assets/main-DIESTGTD.css.gz +0 -0
  82. package/dist/assets/{main-nBOb9YOA.js → main-Da3JKoua.js} +623 -623
  83. package/dist/assets/main-Da3JKoua.js.br +0 -0
  84. package/dist/assets/main-Da3JKoua.js.gz +0 -0
  85. package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
  86. package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
  87. package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
  88. package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
  89. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
  90. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
  91. package/dist/fonts/dm-sans.css.br +0 -0
  92. package/dist/fonts/dm-sans.css.gz +0 -0
  93. package/dist/index.html +2 -2
  94. package/dist/index.html.br +0 -0
  95. package/dist/index.html.gz +0 -0
  96. package/dist/sw.js.br +0 -0
  97. package/dist/sw.js.gz +0 -0
  98. package/package.json +3 -4
  99. package/shared/types/memory.ts +96 -73
  100. package/shared/types/unified/index.ts +1 -0
  101. package/shared/types/unified/stream.ts +33 -2
  102. package/shared/utils/diff-calculator.test.ts +178 -41
  103. package/shared/utils/diff-calculator.ts +383 -100
  104. package/shared/utils/process-supervisor.test.ts +242 -0
  105. package/shared/utils/process-supervisor.ts +356 -0
  106. package/shared/utils/process-tree.ts +99 -0
  107. package/shared/utils/ws-chunk.test.ts +33 -0
  108. package/shared/utils/ws-chunk.ts +73 -0
  109. package/shared/utils/ws-client-chunks.test.ts +45 -0
  110. package/shared/utils/ws-client.ts +43 -0
  111. package/shared/utils/ws-server.ts +17 -14
  112. package/backend/database/migrations/086_single_owner.test.ts +0 -170
  113. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +0 -1
  114. package/dist/assets/main-BUiUL3eZ.css +0 -1
@@ -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
+ });
@@ -0,0 +1,180 @@
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('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
+
140
+ it('answers an empty page for a session with no messages, or an unknown cursor', () => {
141
+ const session = newSession();
142
+ expect(getMessagePage(session)).toEqual({ messages: [], hasMore: false });
143
+ buildBranch(session, 1, 0);
144
+ expect(getMessagePage(session, { beforeId: 'not-a-message' })).toEqual({ messages: [], hasMore: false });
145
+ });
146
+ });
147
+
148
+ describe('getPromptIndex', () => {
149
+ it('lists every real prompt on the branch, oldest first, with no tool results', () => {
150
+ const session = newSession();
151
+ buildBranch(session, 4, 2);
152
+ expect(getPromptIndex(session).map((entry) => entry.text)).toEqual(['turn 0', 'turn 1', 'turn 2', 'turn 3']);
153
+ });
154
+ });
155
+
156
+ describe('getTaskHistory', () => {
157
+ it('returns the task calls and their results older than a message, and nothing else', () => {
158
+ const session = newSession();
159
+ let parent: string | undefined;
160
+ const push = (message: UnifiedMessage) => {
161
+ const row = messageQueries.create({ session_id: session, message, parent_message_id: parent });
162
+ parent = row.id;
163
+ sessionQueries.updateHead(session, row.id);
164
+ return row.id;
165
+ };
166
+ push(prompt('plan'));
167
+ push(toolCall('task-1', 'TaskCreate', { subject: 'Write tests' }));
168
+ push(toolResult('task-1', 'Task #1 created'));
169
+ push(toolCall('read-1', 'Read'));
170
+ push(toolResult('read-1', 'file body'));
171
+ const later = push(prompt('next'));
172
+ push(toolCall('task-2', 'TaskUpdate', { taskId: '1', status: 'completed' }));
173
+
174
+ const history = getTaskHistory(session, later);
175
+ expect(history.map((message) => message.type)).toEqual(['assistant', 'user']);
176
+ expect(JSON.stringify(history)).toContain('task-1');
177
+ expect(JSON.stringify(history)).not.toContain('read-1');
178
+ expect(JSON.stringify(history)).not.toContain('task-2'); // newer than the cursor
179
+ });
180
+ });
@@ -0,0 +1,237 @@
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
+ * 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.
93
+ */
94
+ export function getMessagePage(
95
+ sessionId: string,
96
+ options: { beforeId?: string; minCount?: number; untilId?: string } = {}
97
+ ): MessagePage {
98
+ const minCount = Math.max(1, options.minCount ?? DEFAULT_PAGE_SIZE);
99
+ const byId = getDatabase().prepare('SELECT * FROM messages WHERE id = ? AND session_id = ?');
100
+
101
+ let cursor: string | null;
102
+ if (options.beforeId) {
103
+ const anchor = byId.get(options.beforeId, sessionId) as DatabaseMessage | null;
104
+ if (!anchor) return { messages: [], hasMore: false };
105
+ cursor = anchor.parent_message_id ?? null;
106
+ } else {
107
+ cursor = headOf(sessionId);
108
+ }
109
+
110
+ const messages: UnifiedMessage[] = [];
111
+ const boundary = new BoundaryTracker();
112
+ let reachedUntil = !options.untilId;
113
+ while (cursor) {
114
+ const row = byId.get(cursor, sessionId) as DatabaseMessage | null;
115
+ if (!row) {
116
+ cursor = null;
117
+ break;
118
+ }
119
+ const message = JSON.parse(row.data) as UnifiedMessage;
120
+ messages.push(message);
121
+ cursor = row.parent_message_id ?? null;
122
+ if (row.id === options.untilId) reachedUntil = true;
123
+ const mayStartHere = boundary.add(message);
124
+ if (messages.length >= minCount && reachedUntil && mayStartHere) break;
125
+ }
126
+
127
+ return {
128
+ messages: messages.reverse().map(trimSubAgentForWire),
129
+ hasMore: cursor !== null && byId.get(cursor, sessionId) != null
130
+ };
131
+ }
132
+
133
+ /**
134
+ * The branch, newest first, as light rows: id and parent for every message,
135
+ * plus the body only where `wantBody` says so (decided in SQL, so the bodies
136
+ * of everything else — tool output, images — are never read into JS).
137
+ */
138
+ function branchRows(
139
+ sessionId: string,
140
+ wantBody: string,
141
+ fromId: string | null
142
+ ): Array<{ id: string; parent_message_id: string | null; data: string | null }> {
143
+ if (!fromId) return [];
144
+ const rows = getDatabase()
145
+ .prepare(`SELECT id, parent_message_id, CASE WHEN ${wantBody} THEN data END AS data FROM messages WHERE session_id = ?`)
146
+ .all(sessionId) as Array<{ id: string; parent_message_id: string | null; data: string | null }>;
147
+ const byId = new Map(rows.map((row) => [row.id, row]));
148
+
149
+ const branch: typeof rows = [];
150
+ const seen = new Set<string>();
151
+ let cursor: string | null = fromId;
152
+ while (cursor && !seen.has(cursor)) {
153
+ seen.add(cursor);
154
+ const row = byId.get(cursor);
155
+ if (!row) break;
156
+ branch.push(row);
157
+ cursor = row.parent_message_id;
158
+ }
159
+ return branch;
160
+ }
161
+
162
+ /** Every user prompt on the active branch, oldest first — the navigation rail. */
163
+ export function getPromptIndex(sessionId: string): PromptIndexEntry[] {
164
+ const rows = branchRows(sessionId, `json_extract(data, '$.type') = 'user'`, headOf(sessionId));
165
+ const prompts: PromptIndexEntry[] = [];
166
+ for (let i = rows.length - 1; i >= 0; i--) {
167
+ const row = rows[i];
168
+ if (!row.data) continue;
169
+ const asRow = row as unknown as DatabaseMessage;
170
+ if (!isCheckpointMessage(asRow)) continue;
171
+ const message = JSON.parse(row.data) as UnifiedMessage;
172
+ prompts.push({
173
+ messageId: row.id,
174
+ text: extractMessageText(message).slice(0, PROMPT_PREVIEW_LENGTH),
175
+ createdAt: (message as { createdAt?: string }).createdAt ?? ''
176
+ });
177
+ }
178
+ return prompts;
179
+ }
180
+
181
+ /**
182
+ * The task-tool calls (and their results) on the branch older than `beforeId`,
183
+ * oldest first. Together with the loaded messages this is exactly what the task
184
+ * widget used to replay from the full branch.
185
+ */
186
+ export function getTaskHistory(sessionId: string, beforeId: string): UnifiedMessage[] {
187
+ const parent = getDatabase()
188
+ .prepare('SELECT parent_message_id FROM messages WHERE id = ? AND session_id = ?')
189
+ .get(beforeId, sessionId) as { parent_message_id: string | null } | null;
190
+ if (!parent?.parent_message_id) return [];
191
+
192
+ // Pass 1: the branch, with bodies only for messages that call a task tool.
193
+ const mentionsTaskTool = TASK_TOOLS.map((name) => `instr(data, '"name":"${name}"') > 0`).join(' OR ');
194
+ const branch = branchRows(sessionId, mentionsTaskTool, parent.parent_message_id).reverse();
195
+
196
+ const taskCallIds = new Set<string>();
197
+ const calls = new Map<string, UnifiedMessage>();
198
+ for (const row of branch) {
199
+ if (!row.data) continue;
200
+ const message = JSON.parse(row.data) as UnifiedMessage;
201
+ if (message.type !== 'assistant') continue;
202
+ let hasTaskCall = false;
203
+ for (const block of message.content) {
204
+ if (block.type === 'tool_use' && (TASK_TOOLS as readonly string[]).includes(block.name)) {
205
+ taskCallIds.add(block.id);
206
+ hasTaskCall = true;
207
+ }
208
+ }
209
+ if (hasTaskCall) calls.set(row.id, message);
210
+ }
211
+ if (taskCallIds.size === 0) return [];
212
+
213
+ // Pass 2: only the messages that answer one of those calls — never the
214
+ // thousands of other tool results (file reads, screenshots) on the branch.
215
+ const ids = [...taskCallIds];
216
+ const answerRows = getDatabase()
217
+ .prepare(
218
+ `SELECT id, data FROM messages WHERE session_id = ? AND (${ids.map(() => 'instr(data, ?) > 0').join(' OR ')})`
219
+ )
220
+ .all(sessionId, ...ids.map((id) => `"toolUseId":"${id}"`)) as Array<{ id: string; data: string }>;
221
+ const answers = new Map<string, UnifiedMessage>();
222
+ for (const row of answerRows) {
223
+ const message = JSON.parse(row.data) as UnifiedMessage;
224
+ if (message.type !== 'user') continue;
225
+ const answersTask = message.content.some(
226
+ (block) => block.type === 'tool_result' && taskCallIds.has((block as { toolUseId: string }).toolUseId)
227
+ );
228
+ if (answersTask) answers.set(row.id, message);
229
+ }
230
+
231
+ const history: UnifiedMessage[] = [];
232
+ for (const row of branch) {
233
+ const message = calls.get(row.id) ?? answers.get(row.id);
234
+ if (message) history.push(message);
235
+ }
236
+ return history;
237
+ }
@@ -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,
@@ -78,6 +79,17 @@ export interface StreamState {
78
79
  currentMessage?: UnifiedMessage;
79
80
  currentPartialText?: string;
80
81
  currentReasoningText?: string;
82
+ /**
83
+ * Which streamed block `currentPartialText` / `currentReasoningText` belong
84
+ * to. Bumped on every `start`, so a catch-up snapshot of one block can never
85
+ * be mistaken for the text of the next.
86
+ */
87
+ partialBlock?: number;
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;
81
93
  error?: string;
82
94
  abortController?: AbortController;
83
95
  streamPromise?: Promise<void>;
@@ -279,6 +291,17 @@ export interface RateLimitSnapshot {
279
291
  receivedAt: string;
280
292
  }
281
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
+
282
305
  class StreamManager extends EventEmitter {
283
306
  private activeStreams = new Map<string, StreamState>();
284
307
  private sessionStreams = new Map<string, string>(); // composite key -> streamId
@@ -497,6 +520,31 @@ class StreamManager extends EventEmitter {
497
520
  /**
498
521
  * Emit a stream event to all subscribers
499
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
+
500
548
  private emitStreamEvent(streamState: StreamState, type: StreamEventType, data: any): void {
501
549
  // Increment sequence number for deduplication
502
550
  streamState.eventSeq++;
@@ -928,6 +976,8 @@ class StreamManager extends EventEmitter {
928
976
  // the same folder, for any tool (see snapshot/turn-activity.ts).
929
977
  if (chatSessionId) snapshotService.observeEngineOutput(chatSessionId, output);
930
978
 
979
+ this.trackTurnGap(streamState, output);
980
+
931
981
  // ── Route by type discriminant ──────────────────────────────
932
982
 
933
983
  // Extract session ID from first event that has one
@@ -977,6 +1027,10 @@ class StreamManager extends EventEmitter {
977
1027
  continue; // Don't save to DB
978
1028
  }
979
1029
 
1030
+ // ── Background work (tracked in trackTurnGap) ─────────────
1031
+ case 'background_work':
1032
+ continue;
1033
+
980
1034
  // ── Compact Boundary ───────────────────────────────────
981
1035
  case 'compact_boundary': {
982
1036
  const boundary = enrichMessageEngine(output, engineCtx) as CompactBoundaryMessage;
@@ -1106,17 +1160,28 @@ class StreamManager extends EventEmitter {
1106
1160
  case 'stream_event': {
1107
1161
  const streamEvt = output as UnifiedStreamEvent;
1108
1162
 
1163
+ // Partials carry the DELTA, not the text so far. Re-sending the
1164
+ // whole accumulated text on every token made a turn cost the sum
1165
+ // of all its prefixes — quadratic in its length, ~115× the text
1166
+ // itself on real chats. `offset` (the length before this delta)
1167
+ // and `block` let a client that joins mid-block or misses a frame
1168
+ // tell exactly what it has and resync instead of guessing; `end`
1169
+ // still carries the full text once, as the reconciliation point.
1109
1170
  if (streamEvt.event === 'start') {
1110
1171
  const lifecycle = streamEvt as StreamLifecycleEvent;
1172
+ let block: number;
1111
1173
  if (lifecycle.reasoning) {
1112
1174
  streamState.currentReasoningText = '';
1175
+ block = streamState.reasoningBlock = (streamState.reasoningBlock ?? 0) + 1;
1113
1176
  } else {
1114
1177
  streamState.currentPartialText = '';
1178
+ block = streamState.partialBlock = (streamState.partialBlock ?? 0) + 1;
1115
1179
  }
1116
1180
  this.emitStreamEvent(streamState, 'partial', {
1117
1181
  processId: streamState.processId,
1118
1182
  eventType: 'start',
1119
- partialText: '',
1183
+ block,
1184
+ offset: 0,
1120
1185
  deltaText: '',
1121
1186
  ...(lifecycle.reasoning && { reasoning: true }),
1122
1187
  timestamp: new Date().toISOString()
@@ -1124,42 +1189,55 @@ class StreamManager extends EventEmitter {
1124
1189
  } else if (streamEvt.event === 'delta') {
1125
1190
  const delta = streamEvt as TextDeltaEvent;
1126
1191
  if (delta.reasoning) {
1127
- streamState.currentReasoningText = (streamState.currentReasoningText || '') + delta.text;
1192
+ const before = streamState.currentReasoningText || '';
1193
+ streamState.currentReasoningText = before + delta.text;
1128
1194
  this.emitStreamEvent(streamState, 'partial', {
1129
1195
  processId: streamState.processId,
1130
1196
  eventType: 'update',
1131
- partialText: streamState.currentReasoningText,
1197
+ block: streamState.reasoningBlock ?? 0,
1198
+ offset: before.length,
1132
1199
  deltaText: delta.text,
1133
1200
  reasoning: true,
1134
1201
  timestamp: new Date().toISOString()
1135
1202
  });
1136
1203
  } else {
1137
- streamState.currentPartialText = (streamState.currentPartialText || '') + delta.text;
1204
+ const before = streamState.currentPartialText || '';
1205
+ streamState.currentPartialText = before + delta.text;
1138
1206
  this.emitStreamEvent(streamState, 'partial', {
1139
1207
  processId: streamState.processId,
1140
1208
  eventType: 'update',
1141
- partialText: streamState.currentPartialText,
1209
+ block: streamState.partialBlock ?? 0,
1210
+ offset: before.length,
1142
1211
  deltaText: delta.text,
1143
1212
  timestamp: new Date().toISOString()
1144
1213
  });
1145
1214
  }
1146
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.
1147
1221
  const lifecycle = streamEvt as StreamLifecycleEvent;
1148
- if (lifecycle.reasoning && streamState.currentReasoningText) {
1149
- this.emitStreamEvent(streamState, 'partial', {
1150
- processId: streamState.processId,
1151
- eventType: 'end',
1152
- partialText: streamState.currentReasoningText,
1153
- deltaText: '',
1154
- reasoning: true,
1155
- timestamp: new Date().toISOString()
1156
- });
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
+ }
1157
1234
  streamState.currentReasoningText = '';
1158
- } else {
1235
+ } else if (streamState.currentPartialText) {
1159
1236
  this.emitStreamEvent(streamState, 'partial', {
1160
1237
  processId: streamState.processId,
1161
1238
  eventType: 'end',
1162
- partialText: streamState.currentPartialText || '',
1239
+ block: streamState.partialBlock ?? 0,
1240
+ partialText: streamState.currentPartialText,
1163
1241
  deltaText: '',
1164
1242
  timestamp: new Date().toISOString()
1165
1243
  });
@@ -1216,6 +1294,13 @@ class StreamManager extends EventEmitter {
1216
1294
  const usage = assistantMsg.usage;
1217
1295
  const messageTimestamp = assistantMsg.createdAt;
1218
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
+
1219
1304
  let savedMsgId: string | undefined;
1220
1305
  let savedParentId: string | null = null;
1221
1306
  if (chatSessionId) {
@@ -1228,8 +1313,6 @@ class StreamManager extends EventEmitter {
1228
1313
  savedParentId = saved?.parent_message_id || null;
1229
1314
  }
1230
1315
 
1231
- if (!assistantMsg.parent.toolUseId) streamState.currentPartialText = undefined;
1232
-
1233
1316
  streamState.messages.push({
1234
1317
  processId: streamState.processId,
1235
1318
  message: assistantMsg as any,