4
computeStableMessagesTimelineRows,
5
computeMessageDurationStart,
6
deriveMessagesTimelineRows,
7
+ deriveMessagesTimelineRowsWithState,
8
liveWorkEntryLabel,
9
normalizeCompactToolLabel,
10
resolveAssistantMessageCopyState,
14
type MessagesTimelineRow,
15
workEntryDisplayLabel,
16
} from "./MessagesTimeline.logic";
17
+import {
18
+ createMessageAttachmentPreviewProjector,
19
+ deriveTimelineEntries,
20
+ deriveTimelineEntriesWithState,
21
+ type WorkLogEntry,
22
+} from "../../session-logic";
23
+import { isImageAttachment, type ChatMessage, type TurnDiffSummary } from "../../types";
24
+
25
+describe("streaming row projection", () => {
26
+ function fixture(text = "") {
27
+ const turnId = TurnId.make("live-turn");
28
+ const historyTurnId = TurnId.make("history-turn");
29
+ const time = (second: number) => new Date(Date.UTC(2026, 8, 4, 0, 0, second)).toISOString();
30
+ const messages: ChatMessage[] = [
31
+ {
32
+ id: MessageId.make("history-user"),
33
+ role: "user",
34
+ text: "Inspect",
35
+ turnId: null,
36
+ createdAt: time(0),
37
+ updatedAt: time(0),
38
+ streaming: false,
39
+ },
40
+ {
41
+ id: MessageId.make("history-assistant"),
42
+ role: "assistant",
43
+ text: "Done",
44
+ turnId: historyTurnId,
45
+ createdAt: time(3),
46
+ updatedAt: time(4),
47
+ streaming: false,
48
+ },
49
+ {
50
+ id: MessageId.make("live-user"),
51
+ role: "user",
52
+ text: "Continue",
53
+ turnId: null,
54
+ createdAt: time(5),
55
+ updatedAt: time(5),
56
+ streaming: false,
57
+ },
58
+ {
59
+ id: MessageId.make("live-assistant"),
60
+ role: "assistant",
61
+ text,
62
+ turnId,
63
+ createdAt: time(7),
64
+ updatedAt: time(7),
65
+ streaming: true,
66
+ },
67
+ ];
68
+ const work: WorkLogEntry[] = [
69
+ {
70
+ id: "history-work",
71
+ turnId: historyTurnId,
72
+ createdAt: time(1),
73
+ label: "Ran command",
74
+ tone: "tool",
75
+ command: "vp test",
76
+ toolCallId: "history-tool",
77
+ toolLifecycleStatus: "failed",
78
+ sourceActivityKind: "tool.completed",
79
+ },
80
+ {
81
+ id: "live-work",
82
+ turnId,
83
+ createdAt: time(6),
84
+ label: "Read file",
85
+ tone: "tool",
86
+ changedFiles: ["/repo/src/index.ts"],
87
+ toolCallId: "live-tool",
88
+ toolLifecycleStatus: "completed",
89
+ sourceActivityKind: "tool.completed",
90
+ },
91
+ ];
92
+ const timeline = deriveTimelineEntriesWithState(messages, [], work);
93
+ const input = {
94
+ timelineEntries: timeline.entries,
95
+ latestTurn: { turnId, state: "running", startedAt: time(5), completedAt: null },
96
+ runningTurnId: turnId,
97
+ isWorking: true,
98
+ activeTurnStartedAt: time(5),
99
+ turnDiffSummaryByAssistantMessageId: new Map<MessageId, TurnDiffSummary>(),
100
+ revertTurnCountByUserMessageId: new Map<MessageId, number>(),
101
+ } satisfies Parameters<typeof deriveMessagesTimelineRows>[0];
102
+ return { messages, work, timeline, input, time, turnId, historyTurnId };
103
+ }
104
+
105
+ it.each([
106
+ ["", "Now visible"],
107
+ [" \n", "Now visible"],
108
+ ["Visible", ""],
109
+ ["", " \t\n"],
110
+ ["Visible", "★ Insight\nKeep these line breaks"],
111
+ ])("keeps row parity and history identity when text changes from %j to %j", (before, after) => {
112
+ const initial = fixture(before);
113
+ const previous = deriveMessagesTimelineRowsWithState(initial.input);
114
+ Object.freeze(previous.rows);
115
+ for (const row of previous.rows) Object.freeze(row);
116
+ const last = initial.messages.at(-1)!;
117
+ const messages = [
118
+ ...initial.messages.slice(0, -1),
119
+ { ...last, text: after, updatedAt: initial.time(8) },
120
+ ];
121
+ const timeline = deriveTimelineEntriesWithState(messages, [], initial.work, initial.timeline);
122
+ const input = { ...initial.input, timelineEntries: timeline.entries };
123
+ const next = deriveMessagesTimelineRowsWithState(input, previous);
124
+
125
+ expect(next.rows).toEqual(
126
+ deriveMessagesTimelineRows({
127
+ ...input,
128
+ timelineEntries: deriveTimelineEntries(messages, [], initial.work),
129
+ }),
130
+ );
131
+ for (const [index, row] of previous.rows.entries()) {
132
+ if ((row.kind === "message" || row.kind === "assistant-meta") && row.message === last) {
133
+ expect(next.rows[index]).toMatchObject({ message: { text: after } });
134
+ expect(row.message.text).toBe(before);
135
+ } else {
136
+ expect(next.rows[index]).toBe(row);
137
+ }
138
+ }
139
+ });
140
+
141
+ it("keeps earlier emitted rows unchanged across two projection branches", () => {
142
+ const initial = fixture();
143
+ const previous = deriveMessagesTimelineRowsWithState(initial.input);
144
+ const last = initial.messages.at(-1)!;
145
+ const branch = (text: string) => {
146
+ const messages = [...initial.messages.slice(0, -1), { ...last, text }];
147
+ const timeline = deriveTimelineEntriesWithState(messages, [], initial.work, initial.timeline);
148
+ const input = { ...initial.input, timelineEntries: timeline.entries };
149
+ const projection = deriveMessagesTimelineRowsWithState(input, previous);
150
+ expect(projection.rows).toEqual(deriveMessagesTimelineRows(input));
151
+ return projection;
152
+ };
153
+ const first = branch("First branch");
154
+ const savedFirst = structuredClone(first.rows);
155
+ branch("Second branch");
156
+ expect(first.rows).toEqual(savedFirst);
157
+ expect(previous.rows).toEqual(deriveMessagesTimelineRows(initial.input));
158
+ });
159
+
160
+ it.each(["file", "image", "handoff", "streaming-image"] as const)(
161
+ "preserves stream reuse through the real %s preview materializer",
162
+ (kind) => {
163
+ const initial = fixture("Partial");
164
+ const image = {
165
+ type: "image" as const,
166
+ id: "image",
167
+ name: "image.png",
168
+ mimeType: "image/png",
169
+ sizeBytes: 42,
170
+ };
171
+ const file = {
172
+ type: "file" as const,
173
+ id: "file",
174
+ name: "file.txt",
175
+ mimeType: "text/plain",
176
+ sizeBytes: 8,
177
+ };
178
+ const source = initial.messages.map((message, index) =>
179
+ index === 0 || (kind === "streaming-image" && index === initial.messages.length - 1)
180
+ ? { ...message, attachments: kind === "file" ? [file] : [image, file] }
181
+ : message,
182
+ );
183
+ const server = createMessageAttachmentPreviewProjector();
184
+ const handoff = createMessageAttachmentPreviewProjector();
185
+ const materialize = (messages: ReadonlyArray<ChatMessage>, url: string) => {
186
+ const urls = new Map(kind === "handoff" ? [] : [[image.id, url]]);
187
+ return messages.map((message) => {
188
+ const displayed = server(message, (attachment) => urls.get(attachment.id));
189
+ return kind === "handoff" && message.role === "user"
190
+ ? handoff(displayed, (attachment) =>
191
+ isImageAttachment(attachment) ? "blob:handoff" : undefined,
192
+ )
193
+ : displayed;
194
+ });
195
+ };
196
+ const firstMessages = materialize(source, "https://first.test/image");
197
+ const firstTimeline = deriveTimelineEntriesWithState(firstMessages, [], initial.work);
198
+ const input = { ...initial.input, timelineEntries: firstTimeline.entries };
199
+ const previous = deriveMessagesTimelineRowsWithState(input);
200
+ const saved = structuredClone(previous.rows);
201
+ const nextSource = [...source.slice(0, -1), { ...source.at(-1)!, text: "Next token" }];
202
+ const nextMessages = materialize(nextSource, "https://first.test/image");
203
+ const nextTimeline = deriveTimelineEntriesWithState(
204
+ nextMessages,
205
+ [],
206
+ initial.work,
207
+ firstTimeline,
208
+ );
209
+ const nextInput = { ...input, timelineEntries: nextTimeline.entries };
210
+ const next = deriveMessagesTimelineRowsWithState(nextInput, previous);
211
+
212
+ expect(nextMessages[0]).toBe(firstMessages[0]);
213
+ expect(next.rows).toEqual(deriveMessagesTimelineRows(nextInput));
214
+ for (const [index, row] of previous.rows.entries()) {
215
+ if (
216
+ (row.kind === "message" || row.kind === "assistant-meta") &&
217
+ row.message.id === source.at(-1)?.id
218
+ )
219
+ continue;
220
+ expect(next.rows[index]).toBe(row);
221
+ }
222
+ expect(previous.rows).toEqual(saved);
223
+
224
+ if (kind === "image" || kind === "streaming-image") {
225
+ const renewed = materialize(nextSource, "https://renewed.test/image");
226
+ const renewedTimeline = deriveTimelineEntriesWithState(
227
+ renewed,
228
+ [],
229
+ initial.work,
230
+ nextTimeline,
231
+ );
232
+ const renewedInput = { ...input, timelineEntries: renewedTimeline.entries };
233
+ const renewedRows = deriveMessagesTimelineRowsWithState(renewedInput, next);
234
+ expect(renewedRows.rows).toEqual(deriveMessagesTimelineRows(renewedInput));
235
+ expect(renewed[0]?.attachments?.[0]).toMatchObject({
236
+ previewUrl: "https://renewed.test/image",
237
+ });
238
+ expect(firstMessages[0]?.attachments?.[0]).toMatchObject({
239
+ previewUrl: "https://first.test/image",
240
+ });
241
+ }
242
+ },
243
+ );
244
+
245
+ it.each(["completion", "turn", "role", "ordering"] as const)(
246
+ "rebuilds row structure for a %s change with otherwise unchanged controls",
247
+ (change) => {
248
+ const initial = fixture("Partial");
249
+ const input = {
250
+ ...initial.input,
251
+ latestTurn: {
252
+ ...initial.input.latestTurn,
253
+ state: "completed" as const,
254
+ completedAt: initial.time(9),
255
+ },
256
+ runningTurnId: null,
257
+ isWorking: false,
258
+ };
259
+ const previous = deriveMessagesTimelineRowsWithState(input);
260
+ const last = initial.messages.at(-1)!;
261
+ const changed: ChatMessage =
262
+ change === "completion"
263
+ ? { ...last, streaming: false, updatedAt: initial.time(10) }
264
+ : change === "turn"
265
+ ? { ...last, turnId: initial.historyTurnId }
266
+ : change === "role"
267
+ ? { ...last, role: "user", turnId: null }
268
+ : { ...last, createdAt: initial.time(0) };
269
+ const messages = [...initial.messages.slice(0, -1), changed];
270
+ const timeline = deriveTimelineEntriesWithState(messages, [], initial.work, initial.timeline);
271
+ const nextInput = { ...input, timelineEntries: timeline.entries };
272
+ const next = deriveMessagesTimelineRowsWithState(nextInput, previous);
273
+ expect(next.rows).toEqual(
274
+ deriveMessagesTimelineRows({
275
+ ...nextInput,
276
+ timelineEntries: deriveTimelineEntries(messages, [], initial.work),
277
+ }),
278
+ );
279
+ expect(previous.rows).toEqual(deriveMessagesTimelineRows(input));
280
+ },
281
+ );
282
+
283
+ it("keeps full parity through completion, trailing failure, metadata, expansion, and paging", () => {
284
+ const initial = fixture("Partial");
285
+ let timeline = initial.timeline;
286
+ let input: Parameters<typeof deriveMessagesTimelineRows>[0] = initial.input;
287
+ let projection = deriveMessagesTimelineRowsWithState(input);
288
+ let messages = initial.messages;
289
+ let work = initial.work;
290
+ const check = (changes: Partial<typeof input> = {}) => {
291
+ const oldRows = structuredClone(projection.rows);
292
+ const previous = projection;
293
+ timeline = deriveTimelineEntriesWithState(messages, [], work, timeline);
294
+ input = { ...input, ...changes, timelineEntries: timeline.entries };
295
+ projection = deriveMessagesTimelineRowsWithState(input, previous);
296
+ expect(projection.rows).toEqual(
297
+ deriveMessagesTimelineRows({
298
+ ...input,
299
+ timelineEntries: deriveTimelineEntries(messages, [], work),
300
+ }),
301
+ );
302
+ expect(previous.rows).toEqual(oldRows);
303
+ };
304
+
305
+ messages = [
306
+ ...messages.slice(0, -1),
307
+ { ...messages.at(-1)!, streaming: false, text: "Complete", updatedAt: initial.time(9) },
308
+ ];
309
+ check({
310
+ latestTurn: { ...initial.input.latestTurn, state: "completed", completedAt: initial.time(9) },
311
+ runningTurnId: null,
312
+ isWorking: false,
313
+ });
314
+ work = [
315
+ ...work,
316
+ {
317
+ id: "late-failure",
318
+ turnId: initial.turnId,
319
+ createdAt: initial.time(10),
320
+ label: "Failed command",
321
+ command: "vp test",
322
+ tone: "error",
323
+ toolCallId: "failed-tool",
324
+ toolLifecycleStatus: "failed",
325
+ sourceActivityKind: "tool.completed",
326
+ },
327
+ ];
328
+ check();
329
+ messages = [
330
+ ...messages.slice(0, -1),
331
+ { ...messages.at(-1)!, text: "Updated final text", updatedAt: initial.time(11) },
332
+ ];
333
+ check();
334
+ check({
335
+ latestTurn: {
336
+ ...initial.input.latestTurn,
337
+ state: "interrupted",
338
+ completedAt: initial.time(12),
339
+ },
340
+ });
341
+ check({ expandedTurnIds: new Set([initial.historyTurnId, initial.turnId]) });
342
+ const group = projection.rows.find((row) => row.kind === "work-toggle");
343
+ check({ expandedWorkGroupIds: new Set(group ? [group.id] : []) });
344
+ messages = [
345
+ { ...messages[0]!, id: MessageId.make("older-user"), createdAt: "2026-09-03T23:59:00.000Z" },
346
+ ...messages,
347
+ ];
348
+ check();
349
+ messages = messages.map((message) =>
350
+ message.id === MessageId.make("live-assistant")
351
+ ? { ...message, role: "user", turnId: null, createdAt: initial.time(0) }
352
+ : message,
353
+ );
354
+ check({ revertTurnCountByUserMessageId: new Map([[MessageId.make("live-user"), 3]]) });
355
+ });
356
+});
357
358
describe("expanded tool group scrolling", () => {
359
const entries = [{ id: "first" }, { id: "second" }];