Open History to see the last commit
1import "../../index.css";
2
3import { MessageId, type TurnId } from "@t3tools/contracts";
4import { page } from "vitest/browser";
5import { useCallback, useState, type ComponentProps } from "react";
6import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
7import { render } from "vitest-browser-react";
8
9import { deriveTimelineEntries, type WorkLogEntry } from "../../session-logic";
10import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
11import { MessagesTimeline } from "./MessagesTimeline";
12import {
13 deriveMessagesTimelineRows,
14 estimateMessagesTimelineRowHeight,
15} from "./MessagesTimeline.logic";
16
17const DEFAULT_VIEWPORT = {
18 width: 960,
19 height: 1_100,
20};
21const MARKDOWN_CWD = "/repo/project";
22const ACTIVE_THREAD_ENVIRONMENT_ID = "environment-local" as never;
23
24interface RowMeasurement {
25 actualHeightPx: number;
26 estimatedHeightPx: number;
27 timelineWidthPx: number;
28 virtualizerSizePx: number;
29 renderedInVirtualizedRegion: boolean;
30}
31
32interface VirtualizationScenario {
33 name: string;
34 targetRowId: string;
35 props: Omit<
36 ComponentProps<typeof MessagesTimeline>,
37 "scrollContainer" | "activeThreadEnvironmentId"
38 >;
39 maxEstimateDeltaPx: number;
40}
41
42interface VirtualizerSnapshot {
43 totalSize: number;
44 measurements: ReadonlyArray<{
45 id: string;
46 kind: string;
47 index: number;
48 size: number;
49 start: number;
50 end: number;
51 }>;
52}
53
54function MessagesTimelineBrowserHarness(
55 props: Omit<
56 ComponentProps<typeof MessagesTimeline>,
57 "scrollContainer" | "activeThreadEnvironmentId"
58 >,
59) {
60 const [scrollContainer, setScrollContainer] = useState<HTMLDivElement | null>(null);
61 const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>(
62 () => props.expandedWorkGroups,
63 );
64 const handleToggleWorkGroup = useCallback(
65 (groupId: string) => {
66 setExpandedWorkGroups((current) => ({
67 ...current,
68 [groupId]: !(current[groupId] ?? false),
69 }));
70 props.onToggleWorkGroup(groupId);
71 },
72 [props],
73 );
74
75 return (
76 <div
77 ref={setScrollContainer}
78 data-testid="messages-timeline-scroll-container"
79 className="h-full overflow-y-auto overscroll-y-contain"
80 >
81 <MessagesTimeline
82 {...props}
83 activeThreadEnvironmentId={ACTIVE_THREAD_ENVIRONMENT_ID}
84 scrollContainer={scrollContainer}
85 expandedWorkGroups={expandedWorkGroups}
86 onToggleWorkGroup={handleToggleWorkGroup}
87 />
88 </div>
89 );
90}
91
92function isoAt(offsetSeconds: number): string {
93 return new Date(Date.UTC(2026, 2, 17, 19, 12, 28) + offsetSeconds * 1_000).toISOString();
94}
95
96function createMessage(input: {
97 id: string;
98 role: ChatMessage["role"];
99 text: string;
100 offsetSeconds: number;
101 attachments?: ChatMessage["attachments"];
102}): ChatMessage {
103 return {
104 id: MessageId.makeUnsafe(input.id),
105 role: input.role,
106 text: input.text,
107 ...(input.attachments ? { attachments: input.attachments } : {}),
108 createdAt: isoAt(input.offsetSeconds),
109 ...(input.role === "assistant" ? { completedAt: isoAt(input.offsetSeconds + 1) } : {}),
110 streaming: false,
111 };
112}
113
114function createToolWorkEntry(input: {
115 id: string;
116 offsetSeconds: number;
117 label?: string;
118 detail?: string;
119}): WorkLogEntry {
120 return {
121 id: input.id,
122 createdAt: isoAt(input.offsetSeconds),
123 label: input.label ?? "exec_command completed",
124 ...(input.detail ? { detail: input.detail } : {}),
125 tone: "tool",
126 toolTitle: "exec_command",
127 };
128}
129
130function createPlan(input: {
131 id: string;
132 offsetSeconds: number;
133 planMarkdown: string;
134}): ProposedPlan {
135 return {
136 id: input.id as ProposedPlan["id"],
137 turnId: null,
138 planMarkdown: input.planMarkdown,
139 implementedAt: null,
140 implementationThreadId: null,
141 createdAt: isoAt(input.offsetSeconds),
142 updatedAt: isoAt(input.offsetSeconds + 1),
143 };
144}
145
146function createBaseTimelineProps(input: {
147 messages?: ChatMessage[];
148 proposedPlans?: ProposedPlan[];
149 workEntries?: WorkLogEntry[];
150 expandedWorkGroups?: Record<string, boolean>;
151 completionDividerBeforeEntryId?: string | null;
152 turnDiffSummaryByAssistantMessageId?: Map<MessageId, TurnDiffSummary>;
153 onVirtualizerSnapshot?: ComponentProps<typeof MessagesTimeline>["onVirtualizerSnapshot"];
154}): Omit<ComponentProps<typeof MessagesTimeline>, "scrollContainer" | "activeThreadEnvironmentId"> {
155 return {
156 hasMessages: true,
157 isWorking: false,
158 activeTurnInProgress: false,
159 activeTurnStartedAt: null,
160 timelineEntries: deriveTimelineEntries(
161 input.messages ?? [],
162 input.proposedPlans ?? [],
163 input.workEntries ?? [],
164 ),
165 completionDividerBeforeEntryId: input.completionDividerBeforeEntryId ?? null,
166 completionSummary: null,
167 turnDiffSummaryByAssistantMessageId: input.turnDiffSummaryByAssistantMessageId ?? new Map(),
168 nowIso: isoAt(10_000),
169 expandedWorkGroups: input.expandedWorkGroups ?? {},
170 onToggleWorkGroup: () => {},
171 onOpenTurnDiff: () => {},
172 revertTurnCountByUserMessageId: new Map(),
173 onRevertUserMessage: () => {},
174 isRevertingCheckpoint: false,
175 onImageExpand: () => {},
176 markdownCwd: MARKDOWN_CWD,
177 resolvedTheme: "light",
178 timestampFormat: "locale",
179 workspaceRoot: MARKDOWN_CWD,
180 ...(input.onVirtualizerSnapshot ? { onVirtualizerSnapshot: input.onVirtualizerSnapshot } : {}),
181 };
182}
183
184function createFillerMessages(input: {
185 prefix: string;
186 startOffsetSeconds: number;
187 pairCount: number;
188}): ChatMessage[] {
189 const messages: ChatMessage[] = [];
190 for (let index = 0; index < input.pairCount; index += 1) {
191 const baseOffset = input.startOffsetSeconds + index * 4;
192 messages.push(
193 createMessage({
194 id: `${input.prefix}-user-${index}`,
195 role: "user",
196 text: `filler user message ${index}`,
197 offsetSeconds: baseOffset,
198 }),
199 );
200 messages.push(
201 createMessage({
202 id: `${input.prefix}-assistant-${index}`,
203 role: "assistant",
204 text: `filler assistant message ${index}`,
205 offsetSeconds: baseOffset + 1,
206 }),
207 );
208 }
209 return messages;
210}
211
212function createChangedFilesSummary(
213 targetMessageId: MessageId,
214 files: TurnDiffSummary["files"],
215): Map<MessageId, TurnDiffSummary> {
216 return new Map([
217 [
218 targetMessageId,
219 {
220 turnId: "turn-changed-files" as TurnId,
221 completedAt: isoAt(10),
222 assistantMessageId: targetMessageId,
223 files,
224 },
225 ],
226 ]);
227}
228
229function createChangedFilesScenario(input: {
230 name: string;
231 rowId: string;
232 files: TurnDiffSummary["files"];
233 maxEstimateDeltaPx?: number;
234}): VirtualizationScenario {
235 const beforeMessages = createFillerMessages({
236 prefix: `${input.rowId}-before`,
237 startOffsetSeconds: 0,
238 pairCount: 2,
239 });
240 const afterMessages = createFillerMessages({
241 prefix: `${input.rowId}-after`,
242 startOffsetSeconds: 40,
243 pairCount: 8,
244 });
245 const changedFilesMessage = createMessage({
246 id: input.rowId,
247 role: "assistant",
248 text: "Validation passed on the merged tree.",
249 offsetSeconds: 12,
250 });
251
252 return {
253 name: input.name,
254 targetRowId: changedFilesMessage.id,
255 props: createBaseTimelineProps({
256 messages: [...beforeMessages, changedFilesMessage, ...afterMessages],
257 turnDiffSummaryByAssistantMessageId: createChangedFilesSummary(
258 changedFilesMessage.id,
259 input.files,
260 ),
261 }),
262 maxEstimateDeltaPx: input.maxEstimateDeltaPx ?? 72,
263 };
264}
265
266function createAssistantMessageScenario(input: {
267 name: string;
268 rowId: string;
269 text: string;
270 maxEstimateDeltaPx?: number;
271}): VirtualizationScenario {
272 const beforeMessages = createFillerMessages({
273 prefix: `${input.rowId}-before`,
274 startOffsetSeconds: 0,
275 pairCount: 2,
276 });
277 const afterMessages = createFillerMessages({
278 prefix: `${input.rowId}-after`,
279 startOffsetSeconds: 40,
280 pairCount: 8,
281 });
282 const assistantMessage = createMessage({
283 id: input.rowId,
284 role: "assistant",
285 text: input.text,
286 offsetSeconds: 12,
287 });
288
289 return {
290 name: input.name,
291 targetRowId: assistantMessage.id,
292 props: createBaseTimelineProps({
293 messages: [...beforeMessages, assistantMessage, ...afterMessages],
294 }),
295 maxEstimateDeltaPx: input.maxEstimateDeltaPx ?? 16,
296 };
297}
298
299function buildStaticScenarios(): VirtualizationScenario[] {
300 const beforeMessages = createFillerMessages({
301 prefix: "before",
302 startOffsetSeconds: 0,
303 pairCount: 2,
304 });
305 const afterMessages = createFillerMessages({
306 prefix: "after",
307 startOffsetSeconds: 40,
308 pairCount: 8,
309 });
310
311 const longUserMessage = createMessage({
312 id: "target-user-long",
313 role: "user",
314 text: "x".repeat(3_200),
315 offsetSeconds: 12,
316 });
317 const workEntries = Array.from({ length: 4 }, (_, index) =>
318 createToolWorkEntry({
319 id: `target-work-${index}`,
320 offsetSeconds: 12 + index,
321 detail: `tool output line ${index + 1}`,
322 }),
323 );
324 const moderatePlan = createPlan({
325 id: "target-plan",
326 offsetSeconds: 12,
327 planMarkdown: [
328 "# Stabilize virtualization",
329 "",
330 "- Gather baseline measurements",
331 "- Add browser harness coverage",
332 "- Compare estimated and rendered heights",
333 "- Fix the broken rows without broad refactors",
334 "- Re-run lint and typecheck",
335 ].join("\n"),
336 });
337 return [
338 {
339 name: "long user message",
340 targetRowId: longUserMessage.id,
341 props: createBaseTimelineProps({
342 messages: [...beforeMessages, longUserMessage, ...afterMessages],
343 }),
344 maxEstimateDeltaPx: 56,
345 },
346 {
347 name: "grouped work log row",
348 targetRowId: workEntries[0]!.id,
349 props: createBaseTimelineProps({
350 messages: [...beforeMessages, ...afterMessages],
351 workEntries,
352 }),
353 maxEstimateDeltaPx: 56,
354 },
355 {
356 name: "expanded grouped work log row with show more enabled",
357 targetRowId: "target-work-expanded-0",
358 props: createBaseTimelineProps({
359 messages: [...beforeMessages, ...afterMessages],
360 workEntries: Array.from({ length: 10 }, (_, index) =>
361 createToolWorkEntry({
362 id: `target-work-expanded-${index}`,
363 offsetSeconds: 12 + index,
364 detail: `tool output line ${index + 1}`,
365 }),
366 ),
367 expandedWorkGroups: {
368 "target-work-expanded-0": true,
369 },
370 }),
371 maxEstimateDeltaPx: 72,
372 },
373 {
374 name: "proposed plan row",
375 targetRowId: moderatePlan.id,
376 props: createBaseTimelineProps({
377 messages: [...beforeMessages, ...afterMessages],
378 proposedPlans: [moderatePlan],
379 }),
380 maxEstimateDeltaPx: 96,
381 },
382 createAssistantMessageScenario({
383 name: "assistant single-paragraph row with plain prose",
384 rowId: "target-assistant-plain-prose",
385 text: [
386 "The host is still expanding to content somewhere in the grid layout.",
387 "I'm stripping it back further to a plain block container so the test width",
388 "is actually the timeline width.",
389 ].join(" "),
390 }),
391 createAssistantMessageScenario({
392 name: "assistant single-paragraph row with inline code",
393 rowId: "target-assistant-inline-code",
394 text: [
395 "Typecheck found one exact-optional-property issue in the browser harness:",
396 "I was always passing `onVirtualizerSnapshot`, including `undefined`.",
397 "I'm tightening that object construction and rerunning the checks.",
398 ].join(" "),
399 maxEstimateDeltaPx: 28,
400 }),
401 createChangedFilesScenario({
402 name: "assistant changed-files row with a compacted single-chain directory",
403 rowId: "target-assistant-changed-files-single-chain",
404 files: [
405 { path: "apps/web/src/components/chat/ChangedFilesTree.tsx", additions: 37, deletions: 45 },
406 {
407 path: "apps/web/src/components/chat/ChangedFilesTree.test.tsx",
408 additions: 0,
409 deletions: 26,
410 },
411 ],
412 }),
413 createChangedFilesScenario({
414 name: "assistant changed-files row with a branch after compaction",
415 rowId: "target-assistant-changed-files-branch-point",
416 files: [
417 { path: "apps/server/src/git/Layers/GitCore.ts", additions: 44, deletions: 38 },
418 { path: "apps/server/src/git/Layers/GitCore.test.ts", additions: 18, deletions: 9 },
419 {
420 path: "apps/server/src/provider/Layers/CodexAdapter.ts",
421 additions: 27,
422 deletions: 8,
423 },
424 {
425 path: "apps/server/src/provider/Layers/CodexAdapter.test.ts",
426 additions: 36,
427 deletions: 0,
428 },
429 ],
430 }),
431 createChangedFilesScenario({
432 name: "assistant changed-files row with mixed root and nested entries",
433 rowId: "target-assistant-changed-files-mixed-root",
434 files: [
435 { path: "README.md", additions: 5, deletions: 1 },
436 { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
437 { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
438 ],
439 }),
440 ];
441}
442
443async function nextFrame(): Promise<void> {
444 await new Promise<void>((resolve) => {
445 window.requestAnimationFrame(() => resolve());
446 });
447}
448
449async function waitForLayout(): Promise<void> {
450 await nextFrame();
451 await nextFrame();
452 await nextFrame();
453}
454
455async function setViewport(viewport: { width: number; height: number }): Promise<void> {
456 await page.viewport(viewport.width, viewport.height);
457 await waitForLayout();
458}
459
460async function waitForProductionStyles(): Promise<void> {
461 await vi.waitFor(
462 () => {
463 expect(
464 getComputedStyle(document.documentElement).getPropertyValue("--background").trim(),
465 ).not.toBe("");
466 expect(getComputedStyle(document.body).marginTop).toBe("0px");
467 },
468 { timeout: 4_000, interval: 16 },
469 );
470}
471
472async function waitForElement<T extends Element>(
473 query: () => T | null,
474 errorMessage: string,
475): Promise<T> {
476 let element: T | null = null;
477 await vi.waitFor(
478 () => {
479 element = query();
480 expect(element, errorMessage).toBeTruthy();
481 },
482 { timeout: 8_000, interval: 16 },
483 );
484 if (!element) {
485 throw new Error(errorMessage);
486 }
487 return element;
488}
489
490async function measureTimelineRow(input: {
491 host: HTMLElement;
492 props: Omit<
493 ComponentProps<typeof MessagesTimeline>,
494 "scrollContainer" | "activeThreadEnvironmentId"
495 >;
496 targetRowId: string;
497}): Promise<RowMeasurement> {
498 const scrollContainer = await waitForElement(
499 () =>
500 input.host.querySelector<HTMLDivElement>(
501 '[data-testid="messages-timeline-scroll-container"]',
502 ),
503 "Unable to find MessagesTimeline scroll container.",
504 );
505
506 const rowSelector = `[data-timeline-row-id="${input.targetRowId}"]`;
507 const virtualRowSelector = `[data-virtual-row-id="${input.targetRowId}"]`;
508
509 let timelineWidthPx = 0;
510 let actualHeightPx = 0;
511 let virtualizerSizePx = 0;
512 let renderedInVirtualizedRegion = false;
513
514 await vi.waitFor(
515 async () => {
516 scrollContainer.scrollTop = 0;
517 scrollContainer.dispatchEvent(new Event("scroll"));
518 await waitForLayout();
519
520 const rowElement = input.host.querySelector<HTMLElement>(rowSelector);
521 const virtualRowElement = input.host.querySelector<HTMLElement>(virtualRowSelector);
522 const timelineRoot = input.host.querySelector<HTMLElement>('[data-timeline-root="true"]');
523
524 expect(rowElement, "Unable to locate target timeline row.").toBeTruthy();
525 expect(virtualRowElement, "Unable to locate target virtualized wrapper.").toBeTruthy();
526 expect(timelineRoot, "Unable to locate MessagesTimeline root.").toBeTruthy();
527
528 timelineWidthPx = timelineRoot!.getBoundingClientRect().width;
529 actualHeightPx = rowElement!.getBoundingClientRect().height;
530 virtualizerSizePx = Number.parseFloat(virtualRowElement!.dataset.virtualRowSize ?? "0");
531 renderedInVirtualizedRegion = virtualRowElement!.hasAttribute("data-index");
532
533 expect(timelineWidthPx).toBeGreaterThan(0);
534 expect(actualHeightPx).toBeGreaterThan(0);
535 expect(virtualizerSizePx).toBeGreaterThan(0);
536 expect(renderedInVirtualizedRegion).toBe(true);
537 },
538 { timeout: 8_000, interval: 16 },
539 );
540
541 const rows = deriveMessagesTimelineRows({
542 timelineEntries: input.props.timelineEntries,
543 completionDividerBeforeEntryId: input.props.completionDividerBeforeEntryId,
544 isWorking: input.props.isWorking,
545 activeTurnStartedAt: input.props.activeTurnStartedAt,
546 });
547 const targetRow = rows.find((row) => row.id === input.targetRowId);
548 expect(targetRow, `Unable to derive target row ${input.targetRowId}.`).toBeTruthy();
549
550 return {
551 actualHeightPx,
552 estimatedHeightPx: estimateMessagesTimelineRowHeight(targetRow!, {
553 expandedWorkGroups: input.props.expandedWorkGroups,
554 timelineWidthPx,
555 turnDiffSummaryByAssistantMessageId: input.props.turnDiffSummaryByAssistantMessageId,
556 }),
557 timelineWidthPx,
558 virtualizerSizePx,
559 renderedInVirtualizedRegion,
560 };
561}
562
563async function mountMessagesTimeline(input: {
564 props: Omit<
565 ComponentProps<typeof MessagesTimeline>,
566 "scrollContainer" | "activeThreadEnvironmentId"
567 >;
568 viewport?: { width: number; height: number };
569}) {
570 const viewport = input.viewport ?? DEFAULT_VIEWPORT;
571 await setViewport(viewport);
572 await waitForProductionStyles();
573
574 const host = document.createElement("div");
575 host.style.width = `${viewport.width}px`;
576 host.style.minWidth = `${viewport.width}px`;
577 host.style.maxWidth = `${viewport.width}px`;
578 host.style.height = `${viewport.height}px`;
579 host.style.minHeight = `${viewport.height}px`;
580 host.style.maxHeight = `${viewport.height}px`;
581 host.style.display = "block";
582 host.style.overflow = "hidden";
583 document.body.append(host);
584
585 const screen = await render(<MessagesTimelineBrowserHarness {...input.props} />, {
586 container: host,
587 });
588 await waitForLayout();
589
590 return {
591 host,
592 rerender: async (
593 nextProps: Omit<
594 ComponentProps<typeof MessagesTimeline>,
595 "scrollContainer" | "activeThreadEnvironmentId"
596 >,
597 ) => {
598 await screen.rerender(<MessagesTimelineBrowserHarness {...nextProps} />);
599 await waitForLayout();
600 },
601 setContainerSize: async (nextViewport: { width: number; height: number }) => {
602 await setViewport(nextViewport);
603 host.style.width = `${nextViewport.width}px`;
604 host.style.minWidth = `${nextViewport.width}px`;
605 host.style.maxWidth = `${nextViewport.width}px`;
606 host.style.height = `${nextViewport.height}px`;
607 host.style.minHeight = `${nextViewport.height}px`;
608 host.style.maxHeight = `${nextViewport.height}px`;
609 await waitForLayout();
610 },
611 cleanup: async () => {
612 await screen.unmount();
613 host.remove();
614 },
615 };
616}
617
618async function measureRenderedRowActualHeight(input: {
619 host: HTMLElement;
620 targetRowId: string;
621}): Promise<number> {
622 const rowElement = await waitForElement(
623 () => input.host.querySelector<HTMLElement>(`[data-timeline-row-id="${input.targetRowId}"]`),
624 `Unable to locate rendered row ${input.targetRowId}.`,
625 );
626 return rowElement.getBoundingClientRect().height;
627}
628
629describe("MessagesTimeline virtualization harness", () => {
630 beforeEach(async () => {
631 document.body.innerHTML = "";
632 await setViewport(DEFAULT_VIEWPORT);
633 });
634
635 afterEach(() => {
636 document.body.innerHTML = "";
637 });
638
639 it.each(buildStaticScenarios())("keeps the $name estimate within tolerance", async (scenario) => {
640 const mounted = await mountMessagesTimeline({ props: scenario.props });
641
642 try {
643 const measurement = await measureTimelineRow({
644 host: mounted.host,
645 props: scenario.props,
646 targetRowId: scenario.targetRowId,
647 });
648
649 expect(
650 Math.abs(measurement.actualHeightPx - measurement.estimatedHeightPx),
651 `estimate delta for ${scenario.name}`,
652 ).toBeLessThanOrEqual(scenario.maxEstimateDeltaPx);
653 } finally {
654 await mounted.cleanup();
655 }
656 });
657
658 it("keeps the changed-files row virtualizer size in sync after collapsing directories", async () => {
659 const beforeMessages = createFillerMessages({
660 prefix: "before-collapse",
661 startOffsetSeconds: 0,
662 pairCount: 2,
663 });
664 const afterMessages = createFillerMessages({
665 prefix: "after-collapse",
666 startOffsetSeconds: 40,
667 pairCount: 8,
668 });
669 const targetMessage = createMessage({
670 id: "target-assistant-collapse",
671 role: "assistant",
672 text: "Validation passed on the merged tree.",
673 offsetSeconds: 12,
674 });
675 const props = createBaseTimelineProps({
676 messages: [...beforeMessages, targetMessage, ...afterMessages],
677 turnDiffSummaryByAssistantMessageId: createChangedFilesSummary(targetMessage.id, [
678 { path: ".plans/effect-atom.md", additions: 89, deletions: 0 },
679 {
680 path: "apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts",
681 additions: 4,
682 deletions: 3,
683 },
684 {
685 path: "apps/server/src/checkpointing/Layers/CheckpointStore.ts",
686 additions: 131,
687 deletions: 128,
688 },
689 {
690 path: "apps/server/src/checkpointing/Layers/CheckpointStore.test.ts",
691 additions: 1,
692 deletions: 1,
693 },
694 { path: "apps/server/src/checkpointing/Errors.ts", additions: 1, deletions: 1 },
695 {
696 path: "apps/server/src/git/Layers/ClaudeTextGeneration.ts",
697 additions: 106,
698 deletions: 112,
699 },
700 { path: "apps/server/src/git/Layers/GitCore.ts", additions: 44, deletions: 38 },
701 { path: "apps/server/src/git/Layers/GitCore.test.ts", additions: 18, deletions: 9 },
702 {
703 path: "apps/web/src/components/chat/MessagesTimeline.tsx",
704 additions: 52,
705 deletions: 7,
706 },
707 {
708 path: "apps/web/src/components/chat/ChangedFilesTree.tsx",
709 additions: 32,
710 deletions: 4,
711 },
712 { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
713 { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
714 ]),
715 });
716 const mounted = await mountMessagesTimeline({
717 props,
718 viewport: { width: 320, height: 700 },
719 });
720
721 try {
722 const beforeCollapse = await measureTimelineRow({
723 host: mounted.host,
724 props,
725 targetRowId: targetMessage.id,
726 });
727 const targetRowElement = mounted.host.querySelector<HTMLElement>(
728 `[data-timeline-row-id="${targetMessage.id}"]`,
729 );
730 expect(targetRowElement, "Unable to locate target changed-files row.").toBeTruthy();
731
732 const collapseAllButton =
733 Array.from(targetRowElement!.querySelectorAll<HTMLButtonElement>("button")).find(
734 (button) => button.textContent?.trim() === "Collapse all",
735 ) ?? null;
736 expect(collapseAllButton, 'Unable to find "Collapse all" button.').toBeTruthy();
737
738 collapseAllButton!.click();
739
740 await vi.waitFor(
741 async () => {
742 const afterCollapse = await measureTimelineRow({
743 host: mounted.host,
744 props,
745 targetRowId: targetMessage.id,
746 });
747 expect(afterCollapse.actualHeightPx).toBeLessThan(beforeCollapse.actualHeightPx - 24);
748 },
749 { timeout: 8_000, interval: 16 },
750 );
751
752 const afterCollapse = await measureTimelineRow({
753 host: mounted.host,
754 props,
755 targetRowId: targetMessage.id,
756 });
757 expect(
758 Math.abs(afterCollapse.actualHeightPx - afterCollapse.virtualizerSizePx),
759 ).toBeLessThanOrEqual(8);
760 } finally {
761 await mounted.cleanup();
762 }
763 });
764
765 it("keeps the work-log row virtualizer size in sync after show more expands the group", async () => {
766 const beforeMessages = createFillerMessages({
767 prefix: "before-worklog-expand",
768 startOffsetSeconds: 0,
769 pairCount: 2,
770 });
771 const afterMessages = createFillerMessages({
772 prefix: "after-worklog-expand",
773 startOffsetSeconds: 40,
774 pairCount: 8,
775 });
776 const workEntries = Array.from({ length: 10 }, (_, index) =>
777 createToolWorkEntry({
778 id: `target-work-toggle-${index}`,
779 offsetSeconds: 12 + index,
780 detail: `tool output line ${index + 1}`,
781 }),
782 );
783 const props = createBaseTimelineProps({
784 messages: [...beforeMessages, ...afterMessages],
785 workEntries,
786 });
787 const mounted = await mountMessagesTimeline({ props });
788
789 try {
790 const beforeExpand = await measureTimelineRow({
791 host: mounted.host,
792 props,
793 targetRowId: workEntries[0]!.id,
794 });
795 const targetRowElement = mounted.host.querySelector<HTMLElement>(
796 `[data-timeline-row-id="${workEntries[0]!.id}"]`,
797 );
798 expect(targetRowElement, "Unable to locate target work-log row.").toBeTruthy();
799
800 const showMoreButton =
801 Array.from(targetRowElement!.querySelectorAll<HTMLButtonElement>("button")).find((button) =>
802 button.textContent?.includes("Show 4 more"),
803 ) ?? null;
804 expect(showMoreButton, 'Unable to find "Show more" button.').toBeTruthy();
805
806 showMoreButton!.click();
807
808 await vi.waitFor(
809 async () => {
810 const afterExpand = await measureTimelineRow({
811 host: mounted.host,
812 props,
813 targetRowId: workEntries[0]!.id,
814 });
815 expect(afterExpand.actualHeightPx).toBeGreaterThan(beforeExpand.actualHeightPx + 72);
816 },
817 { timeout: 8_000, interval: 16 },
818 );
819
820 const afterExpand = await measureTimelineRow({
821 host: mounted.host,
822 props,
823 targetRowId: workEntries[0]!.id,
824 });
825 expect(
826 Math.abs(afterExpand.actualHeightPx - afterExpand.virtualizerSizePx),
827 ).toBeLessThanOrEqual(8);
828 } finally {
829 await mounted.cleanup();
830 }
831 });
832
833 it("preserves measured tail row heights when rows transition into virtualization", async () => {
834 const beforeMessages = createFillerMessages({
835 prefix: "tail-transition-before",
836 startOffsetSeconds: 0,
837 pairCount: 1,
838 });
839 const afterMessages = createFillerMessages({
840 prefix: "tail-transition-after",
841 startOffsetSeconds: 40,
842 pairCount: 3,
843 });
844 const targetMessage = createMessage({
845 id: "target-tail-transition",
846 role: "assistant",
847 text: "Validation passed on the merged tree.",
848 offsetSeconds: 12,
849 });
850 let latestSnapshot: VirtualizerSnapshot | null = null;
851 const initialProps = createBaseTimelineProps({
852 messages: [...beforeMessages, targetMessage, ...afterMessages],
853 turnDiffSummaryByAssistantMessageId: createChangedFilesSummary(targetMessage.id, [
854 { path: ".plans/effect-atom.md", additions: 89, deletions: 0 },
855 {
856 path: "apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts",
857 additions: 4,
858 deletions: 3,
859 },
860 {
861 path: "apps/server/src/checkpointing/Layers/CheckpointStore.ts",
862 additions: 131,
863 deletions: 128,
864 },
865 {
866 path: "apps/server/src/checkpointing/Layers/CheckpointStore.test.ts",
867 additions: 1,
868 deletions: 1,
869 },
870 { path: "apps/server/src/checkpointing/Errors.ts", additions: 1, deletions: 1 },
871 {
872 path: "apps/server/src/git/Layers/ClaudeTextGeneration.ts",
873 additions: 106,
874 deletions: 112,
875 },
876 { path: "apps/server/src/git/Layers/GitCore.ts", additions: 44, deletions: 38 },
877 { path: "apps/server/src/git/Layers/GitCore.test.ts", additions: 18, deletions: 9 },
878 {
879 path: "apps/web/src/components/chat/MessagesTimeline.tsx",
880 additions: 52,
881 deletions: 7,
882 },
883 {
884 path: "apps/web/src/components/chat/ChangedFilesTree.tsx",
885 additions: 32,
886 deletions: 4,
887 },
888 { path: "packages/contracts/src/orchestration.ts", additions: 13, deletions: 3 },
889 { path: "packages/shared/src/git.ts", additions: 8, deletions: 2 },
890 ]),
891 onVirtualizerSnapshot: (snapshot) => {
892 latestSnapshot = {
893 totalSize: snapshot.totalSize,
894 measurements: snapshot.measurements,
895 };
896 },
897 });
898
899 const mounted = await mountMessagesTimeline({ props: initialProps });
900
901 try {
902 const initiallyRenderedHeight = await measureRenderedRowActualHeight({
903 host: mounted.host,
904 targetRowId: targetMessage.id,
905 });
906
907 const appendedProps = createBaseTimelineProps({
908 messages: [
909 ...beforeMessages,
910 targetMessage,
911 ...afterMessages,
912 ...createFillerMessages({
913 prefix: "tail-transition-extra",
914 startOffsetSeconds: 120,
915 pairCount: 8,
916 }),
917 ],
918 turnDiffSummaryByAssistantMessageId: initialProps.turnDiffSummaryByAssistantMessageId,
919 onVirtualizerSnapshot: initialProps.onVirtualizerSnapshot,
920 });
921 await mounted.rerender(appendedProps);
922
923 const scrollContainer = await waitForElement(
924 () =>
925 mounted.host.querySelector<HTMLDivElement>(
926 '[data-testid="messages-timeline-scroll-container"]',
927 ),
928 "Unable to find MessagesTimeline scroll container.",
929 );
930 scrollContainer.scrollTop = scrollContainer.scrollHeight;
931 scrollContainer.dispatchEvent(new Event("scroll"));
932 await waitForLayout();
933
934 await vi.waitFor(
935 () => {
936 const measurement = latestSnapshot?.measurements.find(
937 (entry) => entry.id === targetMessage.id,
938 );
939 expect(
940 measurement,
941 "Expected target row to transition into virtualizer cache.",
942 ).toBeTruthy();
943 expect(Math.abs((measurement?.size ?? 0) - initiallyRenderedHeight)).toBeLessThanOrEqual(
944 8,
945 );
946 },
947 { timeout: 8_000, interval: 16 },
948 );
949 } finally {
950 await mounted.cleanup();
951 }
952 });
953
954 it("preserves measured tail image row heights when rows transition into virtualization", async () => {
955 const beforeMessages = createFillerMessages({
956 prefix: "tail-image-before",
957 startOffsetSeconds: 0,
958 pairCount: 1,
959 });
960 const afterMessages = createFillerMessages({
961 prefix: "tail-image-after",
962 startOffsetSeconds: 40,
963 pairCount: 3,
964 });
965 const targetMessage = createMessage({
966 id: "target-tail-image-transition",
967 role: "user",
968 text: "Here is a narrow screenshot.",
969 offsetSeconds: 12,
970 attachments: [
971 {
972 type: "image",
973 id: "target-tail-image",
974 name: "narrow.svg",
975 mimeType: "image/svg+xml",
976 sizeBytes: 512,
977 previewUrl:
978 "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='72'%3E%3Crect width='240' height='72' fill='%23dbeafe'/%3E%3C/svg%3E",
979 },
980 ],
981 });
982 let latestSnapshot: VirtualizerSnapshot | null = null;
983 const initialProps = createBaseTimelineProps({
984 messages: [...beforeMessages, targetMessage, ...afterMessages],
985 onVirtualizerSnapshot: (snapshot) => {
986 latestSnapshot = {
987 totalSize: snapshot.totalSize,
988 measurements: snapshot.measurements,
989 };
990 },
991 });
992 const mounted = await mountMessagesTimeline({ props: initialProps });
993
994 try {
995 await vi.waitFor(
996 () => {
997 const image = mounted.host.querySelector<HTMLImageElement>(
998 `[data-timeline-row-id="${targetMessage.id}"] img`,
999 );
1000 expect(image?.naturalHeight ?? 0).toBeGreaterThan(0);
1001 },
1002 { timeout: 8_000, interval: 16 },
1003 );
1004
1005 const initiallyRenderedHeight = await measureRenderedRowActualHeight({
1006 host: mounted.host,
1007 targetRowId: targetMessage.id,
1008 });
1009 const appendedProps = createBaseTimelineProps({
1010 messages: [
1011 ...beforeMessages,
1012 targetMessage,
1013 ...afterMessages,
1014 ...createFillerMessages({
1015 prefix: "tail-image-extra",
1016 startOffsetSeconds: 120,
1017 pairCount: 8,
1018 }),
1019 ],
1020 onVirtualizerSnapshot: initialProps.onVirtualizerSnapshot,
1021 });
1022 await mounted.rerender(appendedProps);
1023
1024 const scrollContainer = await waitForElement(
1025 () =>
1026 mounted.host.querySelector<HTMLDivElement>(
1027 '[data-testid="messages-timeline-scroll-container"]',
1028 ),
1029 "Unable to find MessagesTimeline scroll container.",
1030 );
1031 scrollContainer.scrollTop = scrollContainer.scrollHeight;
1032 scrollContainer.dispatchEvent(new Event("scroll"));
1033 await waitForLayout();
1034
1035 await vi.waitFor(
1036 () => {
1037 const measurement = latestSnapshot?.measurements.find(
1038 (entry) => entry.id === targetMessage.id,
1039 );
1040 expect(
1041 measurement,
1042 "Expected target image row to transition into virtualizer cache.",
1043 ).toBeTruthy();
1044 expect(Math.abs((measurement?.size ?? 0) - initiallyRenderedHeight)).toBeLessThanOrEqual(
1045 8,
1046 );
1047 },
1048 { timeout: 8_000, interval: 16 },
1049 );
1050 } finally {
1051 await mounted.cleanup();
1052 }
1053 });
1054});