Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MessagesTimeline.test.tsx

643 lines22.0 KB

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