-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessageList.test.tsx
More file actions
491 lines (431 loc) · 17 KB
/
Copy pathMessageList.test.tsx
File metadata and controls
491 lines (431 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import { act, fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useAppStore } from "@/renderer/state/appStore";
import {
ChatPaneActionsContext,
useChatPaneActions,
type ChatPaneActions,
} from "../chatPaneActionsContext";
import { MessageList } from "./MessageList";
type MockVirtualRow = {
key: string;
index: number;
start: number;
};
type MockVirtualizer = {
getVirtualItems: () => MockVirtualRow[];
getTotalSize: () => number;
measure: () => void;
measureElement: (element: HTMLDivElement | null) => void;
resizeItem: (index: number, size: number) => void;
options: { measureElement: (element: Element, entry: undefined, instance: unknown) => number };
scrollToIndex: (index: number, options?: { align?: "start" | "center" | "end" | "auto" }) => void;
shouldAdjustScrollPositionOnItemSizeChange?: (
item: { start: number; size: number },
delta: number,
instance: { isScrolling: boolean; scrollDirection: "forward" | "backward" | null },
) => boolean;
};
type MockVirtualizerOptions = {
count: number;
getScrollElement: () => Element | null;
useFlushSync?: boolean;
useAnimationFrameWithResizeObserver?: boolean;
};
const {
useVirtualizerMock,
measureMock,
measureElementMock,
resizeItemMock,
optionsMeasureElementMock,
scrollToIndexMock,
getVirtualItemsMock,
getTotalSizeMock,
} = vi.hoisted(() => ({
useVirtualizerMock: vi.fn<(options: MockVirtualizerOptions) => MockVirtualizer>(),
measureMock: vi.fn<() => void>(),
measureElementMock: vi.fn<(element: HTMLDivElement | null) => void>(),
resizeItemMock: vi.fn<(index: number, size: number) => void>(),
optionsMeasureElementMock:
vi.fn<(element: Element, entry: undefined, instance: unknown) => number>(),
scrollToIndexMock:
vi.fn<(index: number, options?: { align?: "start" | "center" | "end" | "auto" }) => void>(),
getVirtualItemsMock: vi.fn<() => MockVirtualRow[]>(),
getTotalSizeMock: vi.fn<() => number>(),
}));
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: useVirtualizerMock,
}));
vi.mock("./items/ChatItemRow", () => ({
ChatItemRow: (props: { entry: { id: string } }) => {
const actions = useChatPaneActions();
return (
<button type="button" onClick={() => actions?.onContentHeightChange()}>
{props.entry.id}
</button>
);
},
}));
describe("MessageList", () => {
beforeEach(() => {
vi.clearAllMocks();
useAppStore.setState((state) => ({
...state,
runtimeItemIdsByThread: {},
runtimeItemsByIdByThread: {},
runtimeItemChildrenByParentByThread: {},
runtimeCompletedTurnsByThread: {},
}));
getVirtualItemsMock.mockReturnValue([
{ key: "row-2", index: 1, start: 96 },
{ key: "row-3", index: 2, start: 192 },
]);
getTotalSizeMock.mockReturnValue(384);
optionsMeasureElementMock.mockReturnValue(96);
useVirtualizerMock.mockReturnValue({
getVirtualItems: getVirtualItemsMock,
getTotalSize: getTotalSizeMock,
measure: measureMock,
measureElement: measureElementMock,
resizeItem: resizeItemMock,
options: { measureElement: optionsMeasureElementMock },
scrollToIndex: scrollToIndexMock,
});
});
it("renders only the visible virtual rows", () => {
const scrollElement = document.createElement("div");
const actions = {
openProjectRelativePath: vi.fn<(path: string, lineNumber?: number) => void>(),
revealProjectFolderInTree: vi.fn<(path: string) => void>(),
showProjectEntryInExplorer: vi.fn<(path: string) => void>(),
onContentHeightChange: vi.fn<() => void>(),
projectLocation: { kind: "windows" as const, path: "C:\\repo" },
projectRootNames: new Set<string>(),
};
const threadId = "thread-1";
useAppStore.getState().applyRuntimeEvent(threadId, {
type: "item.started",
threadId,
itemId: "item-4",
itemType: "assistant_message",
});
render(
<ChatPaneActionsContext.Provider value={actions}>
<MessageList
threadId={threadId}
entries={makeEntries(["item-1", "item-2", "item-3", "item-4"])}
scrollElement={scrollElement}
/>
</ChatPaneActionsContext.Provider>,
);
expect(useVirtualizerMock).toHaveBeenCalledOnce();
const virtualizerOptions = useVirtualizerMock.mock.calls[0]![0];
expect(virtualizerOptions.count).toBe(4);
expect(virtualizerOptions.getScrollElement()).toBe(scrollElement);
expect(virtualizerOptions.useFlushSync).toBe(true);
expect(virtualizerOptions.useAnimationFrameWithResizeObserver).toBe(true);
expect(screen.queryByText("item-1")).not.toBeInTheDocument();
expect(screen.getByText("item-2")).toBeInTheDocument();
expect(screen.getByText("item-3")).toBeInTheDocument();
expect(screen.queryByText("item-4")).not.toBeInTheDocument();
expect(document.querySelectorAll("[data-chat-virtual-row='true']")).toHaveLength(2);
const virtualSizeBox = document.querySelector("[data-chat-virtual-size-box='true']");
expect(virtualSizeBox).toHaveClass("overflow-hidden");
expect(virtualSizeBox).toHaveAttribute("data-bottom-fade-visible", "true");
expect(virtualSizeBox).toHaveStyle({
height: "384px",
maskImage:
"linear-gradient(to bottom, black calc(100% - 14px), rgb(0 0 0 / var(--lc-chat-bottom-mask-end-alpha, 0)))",
});
expect(document.querySelector("[data-chat-virtual-block='true']")).toHaveStyle({
transform: "translateY(96px)",
});
expect(document.querySelector("[data-item-id='item-2']")).not.toHaveAttribute("style");
});
it("never lets TanStack adjust scroll itself and compensates rows fully above the viewport on the next commit", () => {
const { scrollElement, shouldAdjust, commit } = renderCompensationList();
expect(shouldAdjust({ start: 0, size: 80 }, 40, idleVirtualizer)).toBe(false);
commit();
expect(scrollElement.scrollTop).toBe(200);
});
it("does not compensate rows that overlap or sit below the viewport", () => {
const { scrollElement, shouldAdjust, commit } = renderCompensationList();
expect(shouldAdjust({ start: 96, size: 100 }, 40, idleVirtualizer)).toBe(false);
commit();
expect(scrollElement.scrollTop).toBe(160);
});
it("compensates rows above the viewport during active upward scroll", () => {
const { scrollElement, shouldAdjust, commit } = renderCompensationList();
scrollElement.scrollTop = 120;
expect(
shouldAdjust({ start: 0, size: 80 }, -40, {
isScrolling: true,
scrollDirection: "backward",
}),
).toBe(false);
commit();
expect(scrollElement.scrollTop).toBe(80);
});
it("compensates streaming row height changes when bottom-sticky", () => {
const actions = {
openProjectRelativePath: vi.fn<(path: string, lineNumber?: number) => void>(),
revealProjectFolderInTree: vi.fn<(path: string) => void>(),
showProjectEntryInExplorer: vi.fn<(path: string) => void>(),
onContentHeightChange: vi.fn<() => void>(),
isStickToBottom: vi.fn<() => boolean>().mockReturnValue(true),
projectLocation: { kind: "windows" as const, path: "C:\\repo" },
projectRootNames: new Set<string>(),
};
const { scrollElement, shouldAdjust, commit } = renderCompensationList(actions);
expect(shouldAdjust({ start: 96, size: 100 }, 24, idleVirtualizer)).toBe(false);
commit();
expect(scrollElement.scrollTop).toBe(184);
});
it("measures newly mounted rows synchronously so the size correction lands in the mount commit", () => {
const scrollElement = document.createElement("div");
optionsMeasureElementMock.mockReturnValue(132);
render(
<MessageList
threadId="thread-1"
entries={makeEntries(["item-1", "item-2", "item-3", "item-4"])}
scrollElement={scrollElement}
/>,
);
expect(resizeItemMock).toHaveBeenCalledWith(1, 132);
expect(resizeItemMock).toHaveBeenCalledWith(2, 132);
});
it("registers TanStack scrollToIndex as the bottom scroll handler", () => {
const registerVirtualScrollToBottom = vi.fn<(handler: (() => void) | null) => void>();
const actions = {
openProjectRelativePath: vi.fn<(path: string, lineNumber?: number) => void>(),
revealProjectFolderInTree: vi.fn<(path: string) => void>(),
showProjectEntryInExplorer: vi.fn<(path: string) => void>(),
onContentHeightChange: vi.fn<() => void>(),
registerVirtualScrollToBottom,
projectLocation: { kind: "windows" as const, path: "C:\\repo" },
projectRootNames: new Set<string>(),
};
const { unmount } = render(
<ChatPaneActionsContext.Provider value={actions}>
<MessageList
threadId="thread-1"
entries={makeEntries(["item-1", "item-2", "item-3", "item-4"])}
scrollElement={document.createElement("div")}
/>
</ChatPaneActionsContext.Provider>,
);
const handler = registerVirtualScrollToBottom.mock.calls.find(
(call): call is [() => void] => typeof call[0] === "function",
)?.[0];
expect(handler).toEqual(expect.any(Function));
handler?.();
expect(scrollToIndexMock).toHaveBeenCalledWith(3, { align: "end" });
unmount();
expect(registerVirtualScrollToBottom).toHaveBeenLastCalledWith(null);
});
it("coalesces live row remeasurement to one animation frame while text streams", async () => {
vi.useFakeTimers();
const scrollElement = document.createElement("div");
const threadId = "thread-1";
useAppStore.getState().applyRuntimeEvent(threadId, {
type: "item.started",
threadId,
itemId: "assistant-1",
itemType: "assistant_message",
});
try {
render(
<MessageList
threadId={threadId}
entries={makeEntries(["item-1", "item-2", "assistant-1"])}
scrollElement={scrollElement}
/>,
);
measureElementMock.mockClear();
act(() => {
useAppStore.getState().applyRuntimeEvent(threadId, {
type: "content.delta",
threadId,
itemId: "assistant-1",
stream: "assistant_text",
delta: "new streamed line",
});
useAppStore.getState().applyRuntimeEvent(threadId, {
type: "content.delta",
threadId,
itemId: "assistant-1",
stream: "assistant_text",
delta: " more text",
});
});
expect(measureElementMock).not.toHaveBeenCalled();
await act(async () => {
await vi.advanceTimersByTimeAsync(16);
});
expect(measureElementMock).toHaveBeenCalledTimes(1);
expect(measureElementMock.mock.calls[0]?.[0]).toBe(
document.querySelector("[data-item-id='assistant-1']"),
);
} finally {
vi.useRealTimers();
}
});
it("hides the bottom overflow fade when the last timeline item is not an assistant message", () => {
const threadId = "thread-1";
useAppStore.getState().applyRuntimeEvent(threadId, {
type: "item.started",
threadId,
itemId: "user-1",
itemType: "user_message",
});
render(
<MessageList
threadId={threadId}
entries={makeEntries(["assistant-1", "user-1"])}
scrollElement={document.createElement("div")}
/>,
);
const virtualSizeBox = document.querySelector("[data-chat-virtual-size-box='true']");
expect(virtualSizeBox).toHaveAttribute("data-bottom-fade-visible", "false");
expect(
(virtualSizeBox as HTMLElement).style.getPropertyValue("--lc-chat-bottom-mask-end-alpha"),
).toBe("1");
});
it("shows the bottom overflow fade only when the last timeline item is an assistant message", () => {
const threadId = "thread-1";
useAppStore.getState().applyRuntimeEvent(threadId, {
type: "item.started",
threadId,
itemId: "assistant-1",
itemType: "assistant_message",
});
render(
<MessageList
threadId={threadId}
entries={makeEntries(["user-1", "assistant-1"])}
scrollElement={document.createElement("div")}
/>,
);
const virtualSizeBox = document.querySelector("[data-chat-virtual-size-box='true']");
expect(virtualSizeBox).toHaveAttribute("data-bottom-fade-visible", "true");
expect(
(virtualSizeBox as HTMLElement).style.getPropertyValue("--lc-chat-bottom-mask-end-alpha"),
).toBe("0");
});
it("hides the bottom overflow fade when the last timeline item is reasoning", () => {
const threadId = "thread-1";
useAppStore.getState().applyRuntimeEvent(threadId, {
type: "item.started",
threadId,
itemId: "reasoning-1",
itemType: "reasoning",
});
render(
<MessageList
threadId={threadId}
entries={makeEntries(["assistant-1", "reasoning-1"])}
scrollElement={document.createElement("div")}
/>,
);
const virtualSizeBox = document.querySelector("[data-chat-virtual-size-box='true']");
expect(virtualSizeBox).toHaveAttribute("data-bottom-fade-visible", "false");
expect(
(virtualSizeBox as HTMLElement).style.getPropertyValue("--lc-chat-bottom-mask-end-alpha"),
).toBe("1");
});
it("reports virtual total size changes to parent actions", () => {
const onContentHeightChange = vi.fn<() => void>();
const actions = {
openProjectRelativePath: vi.fn<(path: string, lineNumber?: number) => void>(),
revealProjectFolderInTree: vi.fn<(path: string) => void>(),
showProjectEntryInExplorer: vi.fn<(path: string) => void>(),
onContentHeightChange,
projectLocation: { kind: "windows" as const, path: "C:\\repo" },
projectRootNames: new Set<string>(),
};
const scrollElement = document.createElement("div");
const { rerender } = render(
<ChatPaneActionsContext.Provider value={actions}>
<MessageList
threadId="thread-1"
entries={makeEntries(["item-1", "item-2", "item-3", "item-4"])}
scrollElement={scrollElement}
/>
</ChatPaneActionsContext.Provider>,
);
expect(onContentHeightChange).toHaveBeenCalledOnce();
getTotalSizeMock.mockReturnValue(288);
rerender(
<ChatPaneActionsContext.Provider value={actions}>
<MessageList
threadId="thread-1"
entries={makeEntries(["item-1", "item-2", "item-3", "item-4"])}
scrollElement={scrollElement}
/>
</ChatPaneActionsContext.Provider>,
);
expect(onContentHeightChange).toHaveBeenCalledTimes(2);
});
it("delegates height change to parent actions without calling virtualizer.measure()", () => {
const onContentHeightChange = vi.fn<() => void>();
const actions = {
openProjectRelativePath: vi.fn<(path: string, lineNumber?: number) => void>(),
revealProjectFolderInTree: vi.fn<(path: string) => void>(),
showProjectEntryInExplorer: vi.fn<(path: string) => void>(),
onContentHeightChange,
projectLocation: { kind: "windows" as const, path: "C:\\repo" },
projectRootNames: new Set<string>(),
};
render(
<ChatPaneActionsContext.Provider value={actions}>
<MessageList
threadId="thread-1"
entries={makeEntries(["item-1", "item-2", "item-3", "item-4"])}
scrollElement={document.createElement("div")}
/>
</ChatPaneActionsContext.Provider>,
);
onContentHeightChange.mockClear();
measureElementMock.mockClear();
fireEvent.click(screen.getByText("item-2"));
// The row-action path remeasures mounted rows with measureElement.
// Calling virtualizer.measure() (no args) resets the entire size cache
// which causes translateY gaps — so it must NOT be called here.
expect(measureElementMock).toHaveBeenCalled();
expect(measureMock).not.toHaveBeenCalled();
expect(onContentHeightChange).toHaveBeenCalledOnce();
});
});
function makeEntries(itemIds: readonly string[]) {
return itemIds.map((id) => ({ kind: "item" as const, id }));
}
const idleVirtualizer = { isScrolling: false, scrollDirection: null } as const;
/**
* Renders a MessageList wired for the scroll-compensation tests and returns
* the intercepted size-change predicate plus a `commit` that re-renders so the
* pending compensation layout effect applies.
*/
function renderCompensationList(actions?: ChatPaneActions) {
const scrollElement = document.createElement("div");
scrollElement.scrollTop = 160;
const entries = makeEntries(["item-1", "item-2", "item-3", "item-4"]);
// A fresh element per render: re-passing the identical element would let
// React bail out and skip the commit the compensation effect runs in.
const makeUi = () => {
const list = (
<MessageList threadId="thread-1" entries={entries} scrollElement={scrollElement} />
);
return actions ? (
<ChatPaneActionsContext.Provider value={actions}>{list}</ChatPaneActionsContext.Provider>
) : (
list
);
};
const { rerender } = render(makeUi());
const virtualizer = useVirtualizerMock.mock.results[0]!.value;
return {
scrollElement,
shouldAdjust: virtualizer.shouldAdjustScrollPositionOnItemSizeChange!,
commit: () => rerender(makeUi()),
};
}