Open History to see the last commit
1import { CheckpointRef, EnvironmentId, MessageId, TurnId } from "@t3tools/contracts";
2import { createRef, type ReactNode, type Ref } from "react";
3import { renderToStaticMarkup } from "react-dom/server";
4import { beforeAll, describe, expect, it, vi } from "vite-plus/test";
5import type { LegendListRef } from "@legendapp/list/react";
6
7vi.mock("@legendapp/list/react", async () => {
8 const legendListTestId = "legend-list";
9
10 const LegendList = (props: {
11 data: Array<{ id: string }>;
12 keyExtractor: (item: { id: string }) => string;
13 renderItem: (args: { item: { id: string } }) => ReactNode;
14 ListHeaderComponent?: ReactNode;
15 ListFooterComponent?: ReactNode;
16 anchoredEndSpace?: {
17 anchorIndex: number;
18 anchorMaxSize?: number;
19 anchorOffset?: number;
20 onReady?: (info: { anchorIndex: number }) => void;
21 onSizeChanged?: (size: number) => void;
22 };
23 contentInsetEndAdjustment?: number;
24 className?: string;
25 maintainScrollAtEnd?:
26 | boolean
27 | {
28 animated?: boolean;
29 on?: {
30 dataChange?: boolean;
31 itemLayout?: boolean;
32 layout?: boolean;
33 };
34 };
35 maintainVisibleContentPosition?:
36 | boolean
37 | {
38 data?: boolean;
39 size?: boolean;
40 shouldRestorePosition?: (item: { id: string }) => boolean;
41 };
42 ref?: Ref<LegendListRef>;
43 }) => {
44 if (props.anchoredEndSpace) {
45 props.anchoredEndSpace.onSizeChanged?.(240);
46 props.anchoredEndSpace.onReady?.({ anchorIndex: props.anchoredEndSpace.anchorIndex });
47 }
48 return (
49 <div
50 data-testid={legendListTestId}
51 data-anchor-index={props.anchoredEndSpace?.anchorIndex}
52 data-anchor-max-size={props.anchoredEndSpace?.anchorMaxSize}
53 data-anchor-offset={props.anchoredEndSpace?.anchorOffset}
54 data-anchor-on-ready={Boolean(props.anchoredEndSpace?.onReady)}
55 data-content-inset-end={props.contentInsetEndAdjustment}
56 data-class-name={props.className}
57 data-maintain-scroll-at-end={props.maintainScrollAtEnd ? "enabled" : undefined}
58 data-maintain-scroll-at-end-animated={
59 typeof props.maintainScrollAtEnd === "object"
60 ? props.maintainScrollAtEnd.animated
61 : undefined
62 }
63 data-maintain-scroll-at-end-data-change={
64 typeof props.maintainScrollAtEnd === "object"
65 ? props.maintainScrollAtEnd.on?.dataChange
66 : undefined
67 }
68 data-maintain-scroll-at-end-item-layout={
69 typeof props.maintainScrollAtEnd === "object"
70 ? props.maintainScrollAtEnd.on?.itemLayout
71 : undefined
72 }
73 data-maintain-scroll-at-end-layout={
74 typeof props.maintainScrollAtEnd === "object"
75 ? props.maintainScrollAtEnd.on?.layout
76 : undefined
77 }
78 data-maintain-visible-content-position={
79 typeof props.maintainVisibleContentPosition === "object"
80 ? "object"
81 : props.maintainVisibleContentPosition
82 }
83 data-maintain-visible-content-position-data={
84 typeof props.maintainVisibleContentPosition === "object"
85 ? props.maintainVisibleContentPosition.data
86 : undefined
87 }
88 data-maintain-visible-content-position-size={
89 typeof props.maintainVisibleContentPosition === "object"
90 ? props.maintainVisibleContentPosition.size
91 : undefined
92 }
93 >
94 {props.ListHeaderComponent}
95 {props.data.map((item) => (
96 <div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
97 ))}
98 {props.ListFooterComponent}
99 </div>
100 );
101 };
102
103 return { LegendList };
104});
105
106function MockFileDiff(props: {
107 fileDiff: { name?: string | null; prevName?: string | null };
108 renderCustomHeader?: (fileDiff: {
109 name?: string | null;
110 prevName?: string | null;
111 }) => React.ReactNode;
112}) {
113 return (
114 <div data-testid="file-diff">
115 {props.renderCustomHeader?.(props.fileDiff)}
116 {props.fileDiff.name ?? props.fileDiff.prevName ?? "diff"}
117 </div>
118 );
119}
120
121vi.mock("@pierre/diffs/react", () => {
122 return { FileDiff: MockFileDiff };
123});
124
125function matchMedia() {
126 return {
127 matches: false,
128 addEventListener: () => {},
129 removeEventListener: () => {},
130 };
131}
132
133let MessagesTimeline: typeof import("./MessagesTimeline").MessagesTimeline;
134
135beforeAll(async () => {
136 const classList = {
137 add: () => {},
138 remove: () => {},
139 toggle: () => {},
140 contains: () => false,
141 };
142
143 vi.stubGlobal("localStorage", {
144 getItem: () => null,
145 setItem: () => {},
146 removeItem: () => {},
147 clear: () => {},
148 });
149 vi.stubGlobal("window", {
150 matchMedia,
151 addEventListener: () => {},
152 removeEventListener: () => {},
153 requestAnimationFrame: (callback: FrameRequestCallback) => {
154 callback(0);
155 return 0;
156 },
157 cancelAnimationFrame: () => {},
158 desktopBridge: undefined,
159 });
160 vi.stubGlobal("document", {
161 documentElement: {
162 classList,
163 offsetHeight: 0,
164 },
165 });
166
167 ({ MessagesTimeline } = await import("./MessagesTimeline"));
168}, 30_000);
169
170const ACTIVE_THREAD_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
171const MESSAGE_CREATED_AT = "2026-03-17T19:12:28.000Z";
172
173function buildProps() {
174 return {
175 isWorking: false,
176 activeTurnInProgress: false,
177 activeTurnStartedAt: null,
178 listRef: createRef<LegendListRef | null>(),
179 latestTurn: null,
180 runningTurnId: null,
181 turnDiffSummaryByAssistantMessageId: new Map(),
182 routeThreadKey: "environment-local:thread-1",
183 onOpenTurnDiff: () => {},
184 revertTurnCountByUserMessageId: new Map(),
185 onRevertUserMessage: () => {},
186 isRevertingCheckpoint: false,
187 onImageExpand: () => {},
188 activeThreadEnvironmentId: ACTIVE_THREAD_ENVIRONMENT_ID,
189 markdownCwd: undefined,
190 resolvedTheme: "light" as const,
191 timestampFormat: "locale" as const,
192 workspaceRoot: undefined,
193 anchorMessageId: null,
194 onAnchorReady: () => {},
195 onAnchorSizeChanged: () => {},
196 contentInsetEndAdjustment: 0,
197 onIsAtEndChange: () => {},
198 onManualNavigation: () => {},
199 };
200}
201
202function buildLongUserMessageText(tail = "deep hidden detail only after expand") {
203 return Array.from({ length: 9 }, (_, index) =>
204 index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`,
205 ).join("\n");
206}
207
208function buildUserTimelineEntry(text: string) {
209 return {
210 id: "entry-1",
211 kind: "message" as const,
212 createdAt: MESSAGE_CREATED_AT,
213 message: {
214 id: MessageId.make("message-1"),
215 role: "user" as const,
216 text,
217 turnId: null,
218 createdAt: MESSAGE_CREATED_AT,
219 updatedAt: MESSAGE_CREATED_AT,
220 streaming: false,
221 },
222 };
223}
224
225describe("MessagesTimeline", () => {
226 it("uses the larger leading inset only when the top fade is enabled", () => {
227 const timelineEntries = [buildUserTimelineEntry("Hello")];
228
229 const compactMarkup = renderToStaticMarkup(
230 <MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} />,
231 );
232 const fadedMarkup = renderToStaticMarkup(
233 <MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} topFadeEnabled />,
234 );
235
236 expect(compactMarkup).toContain('class="h-3 sm:h-4"');
237 expect(compactMarkup).not.toContain("chat-timeline-scroll-fade");
238 expect(fadedMarkup).toContain('class="h-10 sm:h-12"');
239 expect(fadedMarkup).toContain("chat-timeline-scroll-fade");
240 });
241
242 it("keeps assistant changed-files headers sticky below the thread header", () => {
243 const assistantMessageId = MessageId.make("message-assistant-with-files");
244 const turnId = TurnId.make("turn-with-files");
245 const markup = renderToStaticMarkup(
246 <MessagesTimeline
247 {...buildProps()}
248 latestTurn={{
249 turnId,
250 state: "completed",
251 startedAt: MESSAGE_CREATED_AT,
252 completedAt: MESSAGE_CREATED_AT,
253 }}
254 timelineEntries={[
255 {
256 id: "entry-assistant-with-files",
257 kind: "message",
258 createdAt: MESSAGE_CREATED_AT,
259 message: {
260 id: assistantMessageId,
261 role: "assistant",
262 text: "Updated the fixture.",
263 turnId,
264 createdAt: MESSAGE_CREATED_AT,
265 updatedAt: MESSAGE_CREATED_AT,
266 streaming: false,
267 },
268 },
269 ]}
270 turnDiffSummaryByAssistantMessageId={
271 new Map([
272 [
273 assistantMessageId,
274 {
275 turnId,
276 checkpointTurnCount: 1,
277 checkpointRef: CheckpointRef.make("checkpoint-with-files"),
278 status: "ready",
279 files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }],
280 assistantMessageId,
281 completedAt: MESSAGE_CREATED_AT,
282 },
283 ],
284 ])
285 }
286 />,
287 );
288
289 expect(markup).toContain("sticky top-2 z-10");
290 expect(markup).not.toContain("self-start");
291 expect(markup).toContain("whitespace-nowrap");
292 expect(markup).toContain("!size-[22px]");
293 expect(markup).toContain("size-3");
294 expect(markup).toContain('aria-label="Collapse all folders"');
295 expect(markup).toContain('aria-label="Open diff"');
296 expect(markup).toContain("1 changed file");
297 });
298
299 it("uses LegendList isNearEnd when deciding whether the live edge is visible", async () => {
300 const {
301 resolveTimelineIsAtEnd,
302 resolveTimelineMinimapHasPersistentGutter,
303 resolveTimelineMinimapHeightStyle,
304 resolveTimelineMinimapHitStripWidth,
305 resolveTimelineMinimapIndexFromPointer,
306 resolveTimelineMinimapInteractiveWidth,
307 resolveTimelineMinimapTopPercent,
308 } = await import("./MessagesTimeline.logic");
309
310 expect(resolveTimelineIsAtEnd({ isNearEnd: true, isAtEnd: false })).toBe(true);
311 expect(resolveTimelineIsAtEnd({ isNearEnd: false, isAtEnd: true })).toBe(false);
312 expect(resolveTimelineIsAtEnd({ isAtEnd: true })).toBe(true);
313 expect(resolveTimelineIsAtEnd(undefined)).toBeUndefined();
314
315 expect(resolveTimelineMinimapHeightStyle(5)).toBe("min(32px, calc(100vh - 18rem))");
316 expect(resolveTimelineMinimapTopPercent(2, 5)).toBe(50);
317 expect(
318 resolveTimelineMinimapIndexFromPointer({
319 itemCount: 101,
320 railTop: 100,
321 railHeight: 500,
322 pointerY: 350,
323 }),
324 ).toBe(50);
325 expect(
326 resolveTimelineMinimapIndexFromPointer({
327 itemCount: 101,
328 railTop: 100,
329 railHeight: 500,
330 pointerY: 999,
331 }),
332 ).toBe(100);
333 expect(resolveTimelineMinimapHasPersistentGutter(832)).toBe(false);
334 expect(resolveTimelineMinimapHasPersistentGutter(863)).toBe(false);
335 expect(resolveTimelineMinimapHasPersistentGutter(864)).toBe(true);
336
337 // No usable gutter (zoomed in / narrow pane): the strip must go inert
338 // instead of overlaying the centered content column.
339 expect(resolveTimelineMinimapHitStripWidth(768)).toBe(0);
340 expect(resolveTimelineMinimapHitStripWidth(792)).toBe(0);
341 // Partial gutter: strip shrinks to what fits between the viewport edge
342 // and the content column.
343 expect(resolveTimelineMinimapHitStripWidth(820)).toBe(14);
344 // Full gutter: unchanged 40px-wide strip.
345 expect(resolveTimelineMinimapHitStripWidth(872)).toBe(40);
346 expect(resolveTimelineMinimapHitStripWidth(1400)).toBe(40);
347 expect(resolveTimelineMinimapHitStripWidth(0)).toBe(0);
348 expect(resolveTimelineMinimapHitStripWidth(Number.NaN)).toBe(0);
349
350 // The collapsed target stays narrow, but an open preview keeps its full
351 // 20rem width plus the 2rem offset from the minimap rail interactive.
352 expect(resolveTimelineMinimapInteractiveWidth(0, false)).toBe(0);
353 expect(resolveTimelineMinimapInteractiveWidth(14, false)).toBe(14);
354 expect(resolveTimelineMinimapInteractiveWidth(40, false)).toBe(40);
355 expect(resolveTimelineMinimapInteractiveWidth(0, true)).toBe("22rem");
356 expect(resolveTimelineMinimapInteractiveWidth(14, true)).toBe("22rem");
357 expect(resolveTimelineMinimapInteractiveWidth(40, true)).toBe("22rem");
358 });
359
360 it("anchors a sent attachment message using its measured height", () => {
361 const onAnchorReady = vi.fn();
362 const onAnchorSizeChanged = vi.fn();
363 const firstEntry = buildUserTimelineEntry("First prompt.");
364 const secondEntry = {
365 ...buildUserTimelineEntry("Newest prompt."),
366 id: "entry-2",
367 message: {
368 ...buildUserTimelineEntry("Newest prompt.").message,
369 id: MessageId.make("message-2"),
370 attachments: [
371 {
372 type: "image" as const,
373 id: "attachment-1",
374 name: "screenshot.png",
375 mimeType: "image/png",
376 sizeBytes: 1,
377 previewUrl: "data:image/png;base64,iVBORw0KGgo=",
378 },
379 ],
380 },
381 };
382 const markup = renderToStaticMarkup(
383 <MessagesTimeline
384 {...buildProps()}
385 anchorMessageId={secondEntry.message.id}
386 onAnchorReady={onAnchorReady}
387 onAnchorSizeChanged={onAnchorSizeChanged}
388 contentInsetEndAdjustment={144}
389 timelineEntries={[firstEntry, secondEntry]}
390 />,
391 );
392
393 expect(markup).toContain('data-anchor-index="1"');
394 expect(markup).toContain('data-anchor-offset="16"');
395 expect(markup).toContain('data-anchor-on-ready="true"');
396 expect(markup).not.toContain("data-anchor-max-size=");
397 expect(markup).toContain('data-content-inset-end="144"');
398 expect(markup).toContain("[overflow-anchor:none]");
399 expect(markup).not.toContain('data-maintain-scroll-at-end="enabled"');
400 expect(markup).toContain('data-maintain-visible-content-position="object"');
401 expect(markup).toContain('data-maintain-visible-content-position-data="true"');
402 expect(markup).toContain('data-maintain-visible-content-position-size="false"');
403 expect(onAnchorReady).toHaveBeenCalledOnce();
404 expect(onAnchorReady).toHaveBeenCalledWith(secondEntry.message.id, 1);
405 expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);
406 });
407
408 it("renders collapse controls for long user messages", () => {
409 const markup = renderToStaticMarkup(
410 <MessagesTimeline
411 {...buildProps()}
412 timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
413 />,
414 );
415
416 expect(markup).toContain("Show full message");
417 expect(markup).toContain('data-maintain-scroll-at-end="enabled"');
418 expect(markup).toContain('data-maintain-scroll-at-end-animated="false"');
419 expect(markup).toContain('data-maintain-scroll-at-end-data-change="true"');
420 expect(markup).toContain('data-maintain-scroll-at-end-item-layout="true"');
421 expect(markup).toContain('data-maintain-scroll-at-end-layout="true"');
422 expect(markup).toContain('data-user-message-collapsed="true"');
423 expect(markup).toContain('data-user-message-fade="true"');
424 expect(markup).toContain('data-user-message-footer="true"');
425 });
426
427 it("does not render collapse controls for short user messages", () => {
428 const markup = renderToStaticMarkup(
429 <MessagesTimeline
430 {...buildProps()}
431 timelineEntries={[buildUserTimelineEntry("Short prompt.")]}
432 />,
433 );
434
435 expect(markup).not.toContain("Show full message");
436 expect(markup).toContain('data-user-message-collapsible="false"');
437 expect(markup).toContain("rounded-2xl bg-accent p-3");
438 });
439
440 it("renders inline terminal labels with the composer chip UI", () => {
441 const markup = renderToStaticMarkup(
442 <MessagesTimeline
443 {...buildProps()}
444 timelineEntries={[
445 buildUserTimelineEntry(
446 [
447 buildLongUserMessageText("yoo what's @terminal-1:1-5 mean"),
448 "",
449 "<terminal_context>",
450 "- Terminal 1 lines 1-5:",
451 " 1 | julius@mac effect-http-ws-cli % bun i",
452 " 2 | bun install v1.3.9 (cf6cdbbb)",
453 "</terminal_context>",
454 ].join("\n"),
455 ),
456 ]}
457 />,
458 );
459
460 expect(markup).toContain("Terminal 1 lines 1-5");
461 expect(markup).toContain("lucide-terminal");
462 expect(markup).toContain("yoo what's</p>");
463 expect(markup).toContain('<span aria-hidden="true"> </span>');
464 expect(markup).toContain("Show full message");
465 }, 20_000);
466
467 it("renders chips for standalone element-pick context messages", () => {
468 const markup = renderToStaticMarkup(
469 <MessagesTimeline
470 {...buildProps()}
471 timelineEntries={[
472 buildUserTimelineEntry(
473 [
474 "<element_context>",
475 "- <SubmitButton> (Button.tsx:12):",
476 " url: https://example.com/dashboard",
477 " selector: button.submit",
478 " source: /repo/src/Button.tsx:12:5",
479 " html:",
480 ' <button class="submit">Save</button>',
481 "</element_context>",
482 ].join("\n"),
483 ),
484 ]}
485 />,
486 );
487
488 expect(markup).toContain("SubmitButton");
489 expect(markup).not.toContain("<element_context");
490 expect(markup).not.toContain("<element_context");
491 });
492
493 it("keeps the copy button for collapsed long user messages", () => {
494 const markup = renderToStaticMarkup(
495 <MessagesTimeline
496 {...buildProps()}
497 timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
498 />,
499 );
500
501 expect(markup).toContain('aria-label="Copy link"');
502 expect(markup).toContain('data-user-message-collapsed="true"');
503 expect(markup).toContain('data-user-message-footer="true"');
504 });
505
506 it("renders context compaction entries in the normal work log", () => {
507 const markup = renderToStaticMarkup(
508 <MessagesTimeline
509 {...buildProps()}
510 timelineEntries={[
511 {
512 id: "entry-1",
513 kind: "work",
514 createdAt: "2026-03-17T19:12:28.000Z",
515 entry: {
516 id: "work-1",
517 createdAt: "2026-03-17T19:12:28.000Z",
518 label: "Context compacted",
519 tone: "info",
520 },
521 },
522 ]}
523 />,
524 );
525
526 expect(markup).toContain("Context compacted");
527 expect(markup).toContain("Work Log");
528 });
529
530 it("formats changed file paths from the workspace root", () => {
531 const markup = renderToStaticMarkup(
532 <MessagesTimeline
533 {...buildProps()}
534 timelineEntries={[
535 {
536 id: "entry-1",
537 kind: "work",
538 createdAt: "2026-03-17T19:12:28.000Z",
539 entry: {
540 id: "work-1",
541 createdAt: "2026-03-17T19:12:28.000Z",
542 label: "Updated files",
543 tone: "tool",
544 changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
545 },
546 },
547 ]}
548 workspaceRoot="C:/Users/mike/dev-stuff/t3code"
549 />,
550 );
551
552 expect(markup).toContain("t3code/apps/web/src/session-logic.ts");
553 expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
554 });
555
556 it("renders review comment contexts as structured cards instead of raw tags", () => {
557 const markup = renderToStaticMarkup(
558 <MessagesTimeline
559 {...buildProps()}
560 timelineEntries={[
561 {
562 id: "entry-1",
563 kind: "message",
564 createdAt: "2026-03-17T19:12:28.000Z",
565 message: {
566 id: MessageId.make("message-2"),
567 role: "user",
568 text: [
569 '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
570 "Wadduo",
571 "```diff",
572 "@@ -0,0 +47,2 @@",
573 '+ it("keeps valid zero-usage snapshots", () => {',
574 "+ expect(snapshot).not.toBeNull();",
575 "```",
576 "</review_comment>",
577 ].join("\n"),
578 turnId: null,
579 createdAt: "2026-03-17T19:12:28.000Z",
580 updatedAt: "2026-03-17T19:12:28.000Z",
581 streaming: false,
582 },
583 },
584 ]}
585 />,
586 );
587
588 expect(markup).toContain("contextWindow.test.ts");
589 expect(markup).toContain("Wadduo");
590 expect(markup).toContain('data-testid="file-diff"');
591 expect(markup).not.toContain(">Review comment<");
592 expect(markup).not.toContain("<review_comment");
593 expect(markup).not.toContain("</review_comment>");
594 });
595
596 it("renders file review comments as source code instead of diffs", () => {
597 const markup = renderToStaticMarkup(
598 <MessagesTimeline
599 {...buildProps()}
600 timelineEntries={[
601 {
602 id: "entry-1",
603 kind: "message",
604 createdAt: "2026-03-17T19:12:28.000Z",
605 message: {
606 id: MessageId.make("message-source-comment"),
607 role: "user",
608 text: [
609 '<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
610 "Clarify this.",
611 "```md",
612 "# Plan",
613 "- Step one",
614 "```",
615 "</review_comment>",
616 ].join("\n"),
617 turnId: null,
618 createdAt: "2026-03-17T19:12:28.000Z",
619 updatedAt: "2026-03-17T19:12:28.000Z",
620 streaming: false,
621 },
622 },
623 ]}
624 />,
625 );
626
627 expect(markup).toContain("plan.md");
628 expect(markup).toContain("Clarify this.");
629 expect(markup).toContain("# Plan");
630 expect(markup).not.toContain('data-testid="file-diff"');
631 });
632
633 it("renders a failure marker for failed tool lifecycle entries", () => {
634 const markup = renderToStaticMarkup(
635 <MessagesTimeline
636 {...buildProps()}
637 timelineEntries={[
638 {
639 id: "entry-1",
640 kind: "work",
641 createdAt: "2026-03-17T19:12:28.000Z",
642 entry: {
643 id: "work-1",
644 createdAt: "2026-03-17T19:12:28.000Z",
645 label: "Glob",
646 tone: "tool",
647 toolLifecycleStatus: "failed",
648 detail: "No files found",
649 },
650 },
651 ]}
652 />,
653 );
654
655 expect(markup).toContain("lucide-x");
656 expect(markup).toContain('aria-label="Tool call failed"');
657 });
658});