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

MessagesTimeline.test.tsx

831 lines28.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 };
22 contentInsetEndAdjustment?: number;
23 className?: string;
24 maintainScrollAtEnd?:
25 | boolean
26 | {
27 animated?: boolean;
28 on?: {
29 dataChange?: boolean;
30 itemLayout?: boolean;
31 layout?: boolean;
32 };
33 };
34 maintainVisibleContentPosition?:
35 | boolean
36 | {
37 data?: boolean;
38 size?: boolean;
39 shouldRestorePosition?: (item: { id: string }) => boolean;
40 };
41 ref?: Ref<LegendListRef>;
42 }) => {
43 if (props.anchoredEndSpace) {
44 props.anchoredEndSpace.onReady?.({ anchorIndex: props.anchoredEndSpace.anchorIndex });
45 }
46 return (
47 <div
48 data-testid={legendListTestId}
49 data-anchor-index={props.anchoredEndSpace?.anchorIndex}
50 data-anchor-max-size={props.anchoredEndSpace?.anchorMaxSize}
51 data-anchor-offset={props.anchoredEndSpace?.anchorOffset}
52 data-anchor-on-ready={Boolean(props.anchoredEndSpace?.onReady)}
53 data-content-inset-end={props.contentInsetEndAdjustment}
54 data-class-name={props.className}
55 data-maintain-scroll-at-end={props.maintainScrollAtEnd ? "enabled" : undefined}
56 data-maintain-scroll-at-end-animated={
57 typeof props.maintainScrollAtEnd === "object"
58 ? props.maintainScrollAtEnd.animated
59 : undefined
60 }
61 data-maintain-scroll-at-end-data-change={
62 typeof props.maintainScrollAtEnd === "object"
63 ? props.maintainScrollAtEnd.on?.dataChange
64 : undefined
65 }
66 data-maintain-scroll-at-end-item-layout={
67 typeof props.maintainScrollAtEnd === "object"
68 ? props.maintainScrollAtEnd.on?.itemLayout
69 : undefined
70 }
71 data-maintain-scroll-at-end-layout={
72 typeof props.maintainScrollAtEnd === "object"
73 ? props.maintainScrollAtEnd.on?.layout
74 : undefined
75 }
76 data-maintain-visible-content-position={
77 typeof props.maintainVisibleContentPosition === "object"
78 ? "object"
79 : props.maintainVisibleContentPosition
80 }
81 data-maintain-visible-content-position-data={
82 typeof props.maintainVisibleContentPosition === "object"
83 ? props.maintainVisibleContentPosition.data
84 : undefined
85 }
86 data-maintain-visible-content-position-size={
87 typeof props.maintainVisibleContentPosition === "object"
88 ? props.maintainVisibleContentPosition.size
89 : undefined
90 }
91 data-maintain-visible-content-position-restore={
92 typeof props.maintainVisibleContentPosition === "object"
93 ? Boolean(props.maintainVisibleContentPosition.shouldRestorePosition)
94 : undefined
95 }
96 >
97 {props.ListHeaderComponent}
98 {props.data.map((item) => (
99 <div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
100 ))}
101 {props.ListFooterComponent}
102 </div>
103 );
104 };
105​
106 return { LegendList };
107});
108​
109function MockFileDiff(props: {
110 fileDiff: { name?: string | null; prevName?: string | null };
111 renderCustomHeader?: (fileDiff: {
112 name?: string | null;
113 prevName?: string | null;
114 }) => React.ReactNode;
115}) {
116 return (
117 <div data-testid="file-diff">
118 {props.renderCustomHeader?.(props.fileDiff)}
119 {props.fileDiff.name ?? props.fileDiff.prevName ?? "diff"}
120 </div>
121 );
123​
124vi.mock("@pierre/diffs/react", () => {
125 return { FileDiff: MockFileDiff };
126});
127​
128function matchMedia() {
129 return {
130 matches: false,
131 addEventListener: () => {},
132 removeEventListener: () => {},
133 };
135​
136let MessagesTimeline: typeof import("./MessagesTimeline").MessagesTimeline;
137​
138beforeAll(async () => {
139 const classList = {
140 add: () => {},
141 remove: () => {},
142 toggle: () => {},
143 contains: () => false,
144 };
145​
146 vi.stubGlobal("localStorage", {
147 getItem: () => null,
148 setItem: () => {},
149 removeItem: () => {},
150 clear: () => {},
151 });
152 vi.stubGlobal("window", {
153 matchMedia,
154 addEventListener: () => {},
155 removeEventListener: () => {},
156 requestAnimationFrame: (callback: FrameRequestCallback) => {
157 callback(0);
158 return 0;
159 },
160 cancelAnimationFrame: () => {},
161 desktopBridge: undefined,
162 });
163 vi.stubGlobal("document", {
164 documentElement: {
165 classList,
166 offsetHeight: 0,
167 },
168 });
169​
170 ({ MessagesTimeline } = await import("./MessagesTimeline"));
171}, 30_000);
172​
173const ACTIVE_THREAD_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
174const MESSAGE_CREATED_AT = "2026-03-17T19:12:28.000Z";
175​
176function buildProps() {
177 return {
178 isWorking: false,
179 activeTurnInProgress: false,
180 activeTurnStartedAt: null,
181 listRef: createRef<LegendListRef | null>(),
182 latestTurn: null,
183 runningTurnId: null,
184 turnDiffSummaryByAssistantMessageId: new Map(),
185 routeThreadKey: "environment-local:thread-1",
186 onOpenTurnDiff: () => {},
187 revertTurnCountByUserMessageId: new Map(),
188 onRevertUserMessage: () => {},
189 isRevertingCheckpoint: false,
190 onImageExpand: () => {},
191 activeThreadEnvironmentId: ACTIVE_THREAD_ENVIRONMENT_ID,
192 markdownCwd: undefined,
193 resolvedTheme: "light" as const,
194 timestampFormat: "locale" as const,
195 workspaceRoot: undefined,
196 anchorMessageId: null,
197 onAnchorReady: () => {},
198 contentInsetEndAdjustment: 0,
199 liveFollowEnabled: true,
200 onIsAtEndChange: () => {},
201 onManualNavigation: () => {},
202 };
204​
205function buildLongUserMessageText(tail = "deep hidden detail only after expand") {
206 return Array.from({ length: 9 }, (_, index) =>
207 index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`,
208 ).join("\n");
210​
211function buildUserTimelineEntry(text: string) {
212 return {
213 id: "entry-1",
214 kind: "message" as const,
215 createdAt: MESSAGE_CREATED_AT,
216 message: {
217 id: MessageId.make("message-1"),
218 role: "user" as const,
219 text,
220 turnId: null,
221 createdAt: MESSAGE_CREATED_AT,
222 updatedAt: MESSAGE_CREATED_AT,
223 streaming: false,
224 },
225 };
227​
228function buildAssistantTimelineEntry(text: string) {
229 const entry = buildUserTimelineEntry(text);
230 return {
231 ...entry,
232 message: {
233 ...entry.message,
234 role: "assistant" as const,
235 },
236 };
238​
239describe("MessagesTimeline", () => {
240 it("uses the larger leading inset only when the top fade is enabled", () => {
241 const timelineEntries = [buildUserTimelineEntry("Hello")];
242​
243 const compactMarkup = renderToStaticMarkup(
244 <MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} />,
245 );
246 const fadedMarkup = renderToStaticMarkup(
247 <MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} topFadeEnabled />,
248 );
249​
250 expect(compactMarkup).toContain('class="h-3 sm:h-4"');
251 expect(compactMarkup).not.toContain("topbar-scroll-fade");
252 expect(fadedMarkup).toContain('class="h-10 sm:h-12"');
253 expect(fadedMarkup).toContain("topbar-scroll-fade");
254 });
255​
256 it("keeps assistant changed-files headers sticky below the thread header", () => {
257 const assistantMessageId = MessageId.make("message-assistant-with-files");
258 const turnId = TurnId.make("turn-with-files");
259 const markup = renderToStaticMarkup(
260 <MessagesTimeline
261 {...buildProps()}
262 latestTurn={{
263 turnId,
264 state: "completed",
265 startedAt: MESSAGE_CREATED_AT,
266 completedAt: MESSAGE_CREATED_AT,
267 }}
268 timelineEntries={[
269 {
270 id: "entry-assistant-with-files",
271 kind: "message",
272 createdAt: MESSAGE_CREATED_AT,
273 message: {
274 id: assistantMessageId,
275 role: "assistant",
276 text: "Updated the fixture.",
277 turnId,
278 createdAt: MESSAGE_CREATED_AT,
279 updatedAt: MESSAGE_CREATED_AT,
280 streaming: false,
281 },
282 },
283 ]}
284 turnDiffSummaryByAssistantMessageId={
285 new Map([
286 [
287 assistantMessageId,
288 {
289 turnId,
290 checkpointTurnCount: 1,
291 checkpointRef: CheckpointRef.make("checkpoint-with-files"),
292 status: "ready",
293 files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }],
294 assistantMessageId,
295 completedAt: MESSAGE_CREATED_AT,
296 },
297 ],
298 ])
299 }
300 />,
301 );
302​
303 expect(markup).toContain("sticky top-2 z-10");
304 expect(markup).not.toContain("self-start");
305 expect(markup).toContain("whitespace-nowrap");
306 expect(markup).toContain("!size-[22px]");
307 expect(markup).toContain("size-3");
308 expect(markup).toContain('aria-label="Collapse all folders"');
309 expect(markup).toContain('aria-label="Open diff"');
310 expect(markup).toContain("1 changed file");
311 });
312​
313 it("treats only the strict list end as the live edge", async () => {
314 const {
315 resolveTimelineIsAtEnd,
316 resolveTimelineMinimapHasPersistentGutter,
317 resolveTimelineMinimapHeightStyle,
318 resolveTimelineMinimapHitStripWidth,
319 resolveTimelineMinimapIndexFromPointer,
320 resolveTimelineMinimapInteractiveWidth,
321 resolveTimelineMinimapTopPercent,
322 } = await import("./MessagesTimeline.logic");
323​
324 expect(resolveTimelineIsAtEnd({ isAtEnd: true })).toBe(true);
325 expect(resolveTimelineIsAtEnd(undefined)).toBeUndefined();
326 // Within the pixel band above the content bottom counts as the end...
327 expect(
328 resolveTimelineIsAtEnd({
329 isAtEnd: false,
330 contentLength: 2000,
331 scroll: 1170,
332 scrollLength: 800,
333 }),
334 ).toBe(true);
335 // ...but half a viewport up (LegendList's isNearEnd territory) does not.
336 expect(
337 resolveTimelineIsAtEnd({
338 isAtEnd: false,
339 contentLength: 2000,
340 scroll: 900,
341 scrollLength: 800,
342 }),
343 ).toBe(false);
344 // The composer inset is part of contentLength and must not count as
345 // distance-to-end.
346 expect(
347 resolveTimelineIsAtEnd(
348 { isAtEnd: false, contentLength: 2100, scroll: 1170, scrollLength: 800 },
349 100,
350 ),
351 ).toBe(true);
352 // Geometry missing (older state shape): fall back to the strict flag.
353 expect(resolveTimelineIsAtEnd({ isAtEnd: false })).toBe(false);
354​
355 expect(resolveTimelineMinimapHeightStyle(5)).toBe("min(32px, calc(100vh - 18rem))");
356 expect(resolveTimelineMinimapTopPercent(2, 5)).toBe(50);
357 expect(
358 resolveTimelineMinimapIndexFromPointer({
359 itemCount: 101,
360 railTop: 100,
361 railHeight: 500,
362 pointerY: 350,
363 }),
364 ).toBe(50);
365 expect(
366 resolveTimelineMinimapIndexFromPointer({
367 itemCount: 101,
368 railTop: 100,
369 railHeight: 500,
370 pointerY: 999,
371 }),
372 ).toBe(100);
373 expect(resolveTimelineMinimapHasPersistentGutter(832)).toBe(false);
374 expect(resolveTimelineMinimapHasPersistentGutter(863)).toBe(false);
375 expect(resolveTimelineMinimapHasPersistentGutter(864)).toBe(true);
376​
377 // No usable gutter (zoomed in / narrow pane): the strip must go inert
378 // instead of overlaying the centered content column.
379 expect(resolveTimelineMinimapHitStripWidth(768)).toBe(0);
380 expect(resolveTimelineMinimapHitStripWidth(792)).toBe(0);
381 // Partial gutter: strip shrinks to what fits between the viewport edge
382 // and the content column.
383 expect(resolveTimelineMinimapHitStripWidth(820)).toBe(14);
384 // Full gutter: unchanged 40px-wide strip.
385 expect(resolveTimelineMinimapHitStripWidth(872)).toBe(40);
386 expect(resolveTimelineMinimapHitStripWidth(1400)).toBe(40);
387 expect(resolveTimelineMinimapHitStripWidth(0)).toBe(0);
388 expect(resolveTimelineMinimapHitStripWidth(Number.NaN)).toBe(0);
389​
390 // The collapsed target stays narrow, but an open preview keeps its full
391 // 20rem width plus the 2rem offset from the minimap rail interactive.
392 expect(resolveTimelineMinimapInteractiveWidth(0, false)).toBe(0);
393 expect(resolveTimelineMinimapInteractiveWidth(14, false)).toBe(14);
394 expect(resolveTimelineMinimapInteractiveWidth(40, false)).toBe(40);
395 expect(resolveTimelineMinimapInteractiveWidth(0, true)).toBe("22rem");
396 expect(resolveTimelineMinimapInteractiveWidth(14, true)).toBe("22rem");
397 expect(resolveTimelineMinimapInteractiveWidth(40, true)).toBe("22rem");
398 });
399​
400 it("anchors a sent attachment message using its measured height", () => {
401 const onAnchorReady = vi.fn();
402 const firstEntry = buildUserTimelineEntry("First prompt.");
403 const secondEntry = {
404 ...buildUserTimelineEntry("Newest prompt."),
405 id: "entry-2",
406 message: {
407 ...buildUserTimelineEntry("Newest prompt.").message,
408 id: MessageId.make("message-2"),
409 attachments: [
410 {
411 type: "image" as const,
412 id: "attachment-1",
413 name: "screenshot.png",
414 mimeType: "image/png",
415 sizeBytes: 1,
416 previewUrl: "data:image/png;base64,iVBORw0KGgo=",
417 },
418 ],
419 },
420 };
421 const markup = renderToStaticMarkup(
422 <MessagesTimeline
423 {...buildProps()}
424 anchorMessageId={secondEntry.message.id}
425 onAnchorReady={onAnchorReady}
426 contentInsetEndAdjustment={144}
427 timelineEntries={[firstEntry, secondEntry]}
428 />,
429 );
430​
431 expect(markup).toContain('data-anchor-index="1"');
432 expect(markup).toContain('data-anchor-offset="16"');
433 expect(markup).toContain('data-anchor-on-ready="true"');
434 expect(markup).not.toContain("data-anchor-max-size=");
435 expect(markup).toContain('data-content-inset-end="144"');
436 expect(markup).toContain("[overflow-anchor:none]");
437 expect(markup).not.toContain('data-maintain-scroll-at-end="enabled"');
438 expect(markup).toContain('data-maintain-visible-content-position="object"');
439 expect(markup).toContain('data-maintain-visible-content-position-data="true"');
440 expect(markup).toContain('data-maintain-visible-content-position-size="true"');
441 expect(markup).toContain('data-maintain-visible-content-position-restore="true"');
442 expect(onAnchorReady).toHaveBeenCalledOnce();
443 expect(onAnchorReady).toHaveBeenCalledWith(secondEntry.message.id, 1);
444 });
445​
446 it("renders collapse controls for long user messages", () => {
447 const markup = renderToStaticMarkup(
448 <MessagesTimeline
449 {...buildProps()}
450 timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
451 />,
452 );
453​
454 expect(markup).toContain("Show full message");
455 expect(markup).toContain('data-maintain-scroll-at-end="enabled"');
456 expect(markup).toContain('data-maintain-scroll-at-end-animated="false"');
457 expect(markup).toContain('data-maintain-scroll-at-end-data-change="true"');
458 expect(markup).toContain('data-maintain-scroll-at-end-item-layout="true"');
459 expect(markup).toContain('data-maintain-scroll-at-end-layout="true"');
460 expect(markup).toContain('data-user-message-collapsed="true"');
461 expect(markup).toContain('data-user-message-fade="true"');
462 expect(markup).toContain('data-user-message-footer="true"');
463 });
464​
465 it("does not render collapse controls for short user messages", () => {
466 const markup = renderToStaticMarkup(
467 <MessagesTimeline
468 {...buildProps()}
469 timelineEntries={[buildUserTimelineEntry("Short prompt.")]}
470 />,
471 );
472​
473 expect(markup).not.toContain("Show full message");
474 expect(markup).toContain('data-user-message-collapsible="false"');
475 expect(markup).toContain("rounded-2xl bg-message p-3");
476 });
477​
478 it("preserves arbitrary XML-like tags and comparisons in rendered user messages", async () => {
479 const { MessagesTimeline } = await import("./MessagesTimeline");
480 const markup = renderToStaticMarkup(
481 <MessagesTimeline
482 {...buildProps()}
483 timelineEntries={[
484 buildUserTimelineEntry(
485 [
486 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
487 'Before <nested data-value="a&b">inside</nested> after',
488 "</global-agent-instructions> in your context?",
489 "Comparison: 2 < 3 and 5 > 4.",
490 ].join("\n"),
491 ),
492 ]}
493 />,
494 );
495​
496 expect(markup).toContain("&lt;global-agent-instructions scope=&quot;workspace&quot;&gt;");
497 expect(markup).toContain(
498 "Before &lt;nested data-value=&quot;a&amp;b&quot;&gt;inside&lt;/nested&gt; after",
499 );
500 expect(markup).toContain("&lt;/global-agent-instructions&gt; in your context?");
501 expect(markup).toContain("Comparison: 2 &lt; 3 and 5 &gt; 4.");
502 });
503​
504 it("preserves XML-like source inside user code spans and fences", async () => {
505 const { MessagesTimeline } = await import("./MessagesTimeline");
506 const markup = renderToStaticMarkup(
507 <MessagesTimeline
508 {...buildProps()}
509 timelineEntries={[
510 buildUserTimelineEntry(
511 [
512 'Inline `<tag attr="x">`',
513 "",
514 "```xml",
515 '<root><child enabled="true" /></root>',
516 "```",
517 ].join("\n"),
518 ),
519 ]}
520 />,
521 );
522​
523 expect(markup).toContain('<code data-inline-code="">&lt;tag attr=&quot;x&quot;&gt;</code>');
524 expect(markup).toContain("&lt;root&gt;&lt;child enabled=&quot;true&quot; /&gt;&lt;/root&gt;");
525 });
526​
527 it("does not render markdown title attributes in user messages", async () => {
528 const { MessagesTimeline } = await import("./MessagesTimeline");
529 const markup = renderToStaticMarkup(
530 <MessagesTimeline
531 {...buildProps()}
532 timelineEntries={[
533 buildUserTimelineEntry(
534 '[link](https://example.com "link tip") ![image](https://example.com/image.png "image tip")',
535 ),
536 ]}
537 />,
538 );
539​
540 expect(markup).toContain('href="https://example.com"');
541 expect(markup).toContain('src="https://example.com/image.png"');
542 expect(markup).not.toContain('title="link tip"');
543 expect(markup).not.toContain('title="image tip"');
544 });
545​
546 it("renders unsafe user HTML as inert source text", async () => {
547 const { MessagesTimeline } = await import("./MessagesTimeline");
548 const markup = renderToStaticMarkup(
549 <MessagesTimeline
550 {...buildProps()}
551 timelineEntries={[
552 buildUserTimelineEntry(
553 '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">',
554 ),
555 ]}
556 />,
557 );
558​
559 expect(markup).toContain("&lt;script&gt;globalThis.__t3Xss = 1&lt;/script&gt;");
560 expect(markup).toContain(
561 "&lt;img src=&quot;x&quot; onerror=&quot;globalThis.__t3Xss = 2&quot;&gt;",
562 );
563 expect(markup).not.toMatch(/<script(?:\s|>)/i);
564 expect(markup).not.toMatch(/<img(?:\s|>)/i);
565 });
566​
567 it("continues to render sanitized raw HTML in assistant messages", async () => {
568 const { MessagesTimeline } = await import("./MessagesTimeline");
569 const markup = renderToStaticMarkup(
570 <MessagesTimeline
571 {...buildProps()}
572 timelineEntries={[
573 buildAssistantTimelineEntry("<details><summary>More</summary>Details</details>"),
574 ]}
575 />,
576 );
577​
578 expect(markup).toContain('data-markdown-details=""');
579 expect(markup).toContain("More");
580 expect(markup).not.toContain("&lt;details&gt;");
581 });
582​
583 it("sanitizes executable HTML while preserving supported assistant markup", async () => {
584 const { MessagesTimeline } = await import("./MessagesTimeline");
585 const markup = renderToStaticMarkup(
586 <MessagesTimeline
587 {...buildProps()}
588 timelineEntries={[
589 buildAssistantTimelineEntry(
590 [
591 '<details open onclick="globalThis.__t3Xss = 1">',
592 "<summary>Safe details</summary>",
593 "<script>globalThis.__t3Xss = 2</script>",
594 '<img src="x" onerror="globalThis.__t3Xss = 3">',
595 '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
596 "</details>",
597 ].join(""),
598 ),
599 ]}
600 />,
601 );
602​
603 expect(markup).toContain('data-markdown-details=""');
604 expect(markup).toContain("Safe details");
605 expect(markup).not.toMatch(/<script(?:\s|>)/i);
606 expect(markup).not.toContain("onclick=");
607 expect(markup).not.toContain("onerror=");
608 expect(markup).not.toContain("javascript:");
609 expect(markup).not.toContain("globalThis.__t3Xss");
610 });
611​
612 it("renders inline terminal labels with the composer chip UI", async () => {
613 const { MessagesTimeline } = await import("./MessagesTimeline");
614 const markup = renderToStaticMarkup(
615 <MessagesTimeline
616 {...buildProps()}
617 timelineEntries={[
618 buildUserTimelineEntry(
619 [
620 buildLongUserMessageText("yoo what's @terminal-1:1-5 mean"),
621 "",
622 "<terminal_context>",
623 "- Terminal 1 lines 1-5:",
624 " 1 | julius@mac effect-http-ws-cli % bun i",
625 " 2 | bun install v1.3.9 (cf6cdbbb)",
626 "</terminal_context>",
627 ].join("\n"),
628 ),
629 ]}
630 />,
631 );
632​
633 expect(markup).toContain("Terminal 1 lines 1-5");
634 expect(markup).toContain("lucide-terminal");
635 expect(markup).toContain("yoo what&#x27;s</p>");
636 expect(markup).toContain('<span aria-hidden="true"> </span>');
637 expect(markup).toContain("Show full message");
638 }, 20_000);
639​
640 it("renders chips for standalone element-pick context messages", () => {
641 const markup = renderToStaticMarkup(
642 <MessagesTimeline
643 {...buildProps()}
644 timelineEntries={[
645 buildUserTimelineEntry(
646 [
647 "<element_context>",
648 "- <SubmitButton> (Button.tsx:12):",
649 " url: https://example.com/dashboard",
650 " selector: button.submit",
651 " source: /repo/src/Button.tsx:12:5",
652 " html:",
653 ' <button class="submit">Save</button>',
654 "</element_context>",
655 ].join("\n"),
656 ),
657 ]}
658 />,
659 );
660​
661 expect(markup).toContain("SubmitButton");
662 expect(markup).not.toContain("&lt;element_context");
663 expect(markup).not.toContain("<element_context");
664 });
665​
666 it("keeps the copy button for collapsed long user messages", () => {
667 const markup = renderToStaticMarkup(
668 <MessagesTimeline
669 {...buildProps()}
670 timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
671 />,
672 );
673​
674 expect(markup).toContain('aria-label="Copy link"');
675 expect(markup).toContain('data-user-message-collapsed="true"');
676 expect(markup).toContain('data-user-message-footer="true"');
677 });
678​
679 it("renders context compaction entries in the normal work log", () => {
680 const markup = renderToStaticMarkup(
681 <MessagesTimeline
682 {...buildProps()}
683 timelineEntries={[
684 {
685 id: "entry-1",
686 kind: "work",
687 createdAt: "2026-03-17T19:12:28.000Z",
688 entry: {
689 id: "work-1",
690 createdAt: "2026-03-17T19:12:28.000Z",
691 label: "Context compacted",
692 tone: "info",
693 },
694 },
695 ]}
696 />,
697 );
698​
699 expect(markup).toContain("Context compacted");
700 expect(markup).toContain("Work Log");
701 });
702​
703 it("formats changed file paths from the workspace root", () => {
704 const markup = renderToStaticMarkup(
705 <MessagesTimeline
706 {...buildProps()}
707 timelineEntries={[
708 {
709 id: "entry-1",
710 kind: "work",
711 createdAt: "2026-03-17T19:12:28.000Z",
712 entry: {
713 id: "work-1",
714 createdAt: "2026-03-17T19:12:28.000Z",
715 label: "Updated files",
716 tone: "tool",
717 changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
718 },
719 },
720 ]}
721 workspaceRoot="C:/Users/mike/dev-stuff/t3code"
722 />,
723 );
724​
725 expect(markup).toContain("t3code/apps/web/src/session-logic.ts");
726 expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
727 });
728​
729 it("renders review comment contexts as structured cards instead of raw tags", () => {
730 const markup = renderToStaticMarkup(
731 <MessagesTimeline
732 {...buildProps()}
733 timelineEntries={[
734 {
735 id: "entry-1",
736 kind: "message",
737 createdAt: "2026-03-17T19:12:28.000Z",
738 message: {
739 id: MessageId.make("message-2"),
740 role: "user",
741 text: [
742 '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
743 "Wadduo",
744 "```diff",
745 "@@ -0,0 +47,2 @@",
746 '+ it("keeps valid zero-usage snapshots", () => {',
747 "+ expect(snapshot).not.toBeNull();",
748 "```",
749 "</review_comment>",
750 ].join("\n"),
751 turnId: null,
752 createdAt: "2026-03-17T19:12:28.000Z",
753 updatedAt: "2026-03-17T19:12:28.000Z",
754 streaming: false,
755 },
756 },
757 ]}
758 />,
759 );
760​
761 expect(markup).toContain("contextWindow.test.ts");
762 expect(markup).toContain("Wadduo");
763 expect(markup).toContain('data-testid="file-diff"');
764 expect(markup).not.toContain(">Review comment<");
765 expect(markup).not.toContain("&lt;review_comment");
766 expect(markup).not.toContain("&lt;/review_comment&gt;");
767 });
768​
769 it("renders file review comments as source code instead of diffs", () => {
770 const markup = renderToStaticMarkup(
771 <MessagesTimeline
772 {...buildProps()}
773 timelineEntries={[
774 {
775 id: "entry-1",
776 kind: "message",
777 createdAt: "2026-03-17T19:12:28.000Z",
778 message: {
779 id: MessageId.make("message-source-comment"),
780 role: "user",
781 text: [
782 '<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
783 "Clarify this.",
784 "```md",
785 "# Plan",
786 "- Step one",
787 "```",
788 "</review_comment>",
789 ].join("\n"),
790 turnId: null,
791 createdAt: "2026-03-17T19:12:28.000Z",
792 updatedAt: "2026-03-17T19:12:28.000Z",
793 streaming: false,
794 },
795 },
796 ]}
797 />,
798 );
799​
800 expect(markup).toContain("plan.md");
801 expect(markup).toContain("Clarify this.");
802 expect(markup).toContain("# Plan");
803 expect(markup).not.toContain('data-testid="file-diff"');
804 });
805​
806 it("renders a failure marker for failed tool lifecycle entries", () => {
807 const markup = renderToStaticMarkup(
808 <MessagesTimeline
809 {...buildProps()}
810 timelineEntries={[
811 {
812 id: "entry-1",
813 kind: "work",
814 createdAt: "2026-03-17T19:12:28.000Z",
815 entry: {
816 id: "work-1",
817 createdAt: "2026-03-17T19:12:28.000Z",
818 label: "Glob",
819 tone: "tool",
820 toolLifecycleStatus: "failed",
821 detail: "No files found",
822 },
823 },
824 ]}
825 />,
826 );
827​
828 expect(markup).toContain("lucide-x");
829 expect(markup).toContain('aria-label="Tool call failed"');
830 });
831});