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

MessagesTimeline.test.tsx

1,067 lines34.9 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 activeTurnStartedAt: null,
180 listRef: createRef<LegendListRef | null>(),
181 latestTurn: null,
182 runningTurnId: null,
183 turnDiffSummaryByAssistantMessageId: new Map(),
184 routeThreadKey: "environment-local:thread-1",
185 onOpenTurnDiff: () => {},
186 revertTurnCountByUserMessageId: new Map(),
187 onRevertUserMessage: () => {},
188 isRevertingCheckpoint: false,
189 onImageExpand: () => {},
190 activeThreadEnvironmentId: ACTIVE_THREAD_ENVIRONMENT_ID,
191 markdownCwd: undefined,
192 resolvedTheme: "light" as const,
193 timestampFormat: "locale" as const,
194 workspaceRoot: undefined,
195 anchorMessageId: null,
196 onAnchorReady: () => {},
197 contentInsetEndAdjustment: 0,
198 liveFollowEnabled: true,
199 onIsAtEndChange: () => {},
200 onManualNavigation: () => {},
201 };
203​
204function buildLongUserMessageText(tail = "deep hidden detail only after expand") {
205 return Array.from({ length: 9 }, (_, index) =>
206 index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`,
207 ).join("\n");
209​
210function buildUserTimelineEntry(text: string) {
211 return {
212 id: "entry-1",
213 kind: "message" as const,
214 createdAt: MESSAGE_CREATED_AT,
215 message: {
216 id: MessageId.make("message-1"),
217 role: "user" as const,
218 text,
219 turnId: null,
220 createdAt: MESSAGE_CREATED_AT,
221 updatedAt: MESSAGE_CREATED_AT,
222 streaming: false,
223 },
224 };
226​
227function buildAssistantTimelineEntry(text: string) {
228 const entry = buildUserTimelineEntry(text);
229 return {
230 ...entry,
231 message: {
232 ...entry.message,
233 role: "assistant" as const,
234 },
235 };
237​
238describe("MessagesTimeline", () => {
239 it("renders the worked-for row at assistant response text size", () => {
240 const turnId = TurnId.make("turn-with-fold");
241 const assistantEntry = buildAssistantTimelineEntry("Done.");
242 const markup = renderToStaticMarkup(
243 <MessagesTimeline
244 {...buildProps()}
245 latestTurn={{
246 turnId,
247 state: "completed",
248 startedAt: "2026-03-17T19:12:20.000Z",
249 completedAt: "2026-03-17T19:12:28.000Z",
250 }}
251 timelineEntries={[
252 {
253 id: "work-entry-with-fold",
254 kind: "work",
255 createdAt: "2026-03-17T19:12:22.000Z",
256 entry: {
257 id: "work-with-fold",
258 createdAt: "2026-03-17T19:12:22.000Z",
259 turnId,
260 label: "Ran command",
261 tone: "tool",
262 toolLifecycleStatus: "completed",
263 },
264 },
265 {
266 ...assistantEntry,
267 message: { ...assistantEntry.message, turnId },
268 },
269 ]}
270 />,
271 );
272​
273 expect(markup).toContain("Worked for 8.0s");
274 expect(markup).toContain("px-1 text-sm leading-relaxed text-muted-foreground");
275 });
276​
277 it("uses the larger leading inset only when the top fade is enabled", () => {
278 const timelineEntries = [buildUserTimelineEntry("Hello")];
279​
280 const compactMarkup = renderToStaticMarkup(
281 <MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} />,
282 );
283 const fadedMarkup = renderToStaticMarkup(
284 <MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} topFadeEnabled />,
285 );
286​
287 expect(compactMarkup).toContain('class="h-3 sm:h-4"');
288 expect(compactMarkup).not.toContain("topbar-scroll-fade");
289 expect(fadedMarkup).toContain('class="h-10 sm:h-12"');
290 expect(fadedMarkup).toContain("topbar-scroll-fade");
291 });
292​
293 it("keeps assistant changed-files headers sticky below the thread header", () => {
294 const assistantMessageId = MessageId.make("message-assistant-with-files");
295 const turnId = TurnId.make("turn-with-files");
296 const markup = renderToStaticMarkup(
297 <MessagesTimeline
298 {...buildProps()}
299 latestTurn={{
300 turnId,
301 state: "completed",
302 startedAt: MESSAGE_CREATED_AT,
303 completedAt: MESSAGE_CREATED_AT,
304 }}
305 timelineEntries={[
306 {
307 id: "entry-assistant-with-files",
308 kind: "message",
309 createdAt: MESSAGE_CREATED_AT,
310 message: {
311 id: assistantMessageId,
312 role: "assistant",
313 text: "Updated the fixture.",
314 turnId,
315 createdAt: MESSAGE_CREATED_AT,
316 updatedAt: MESSAGE_CREATED_AT,
317 streaming: false,
318 },
319 },
320 ]}
321 turnDiffSummaryByAssistantMessageId={
322 new Map([
323 [
324 assistantMessageId,
325 {
326 turnId,
327 checkpointTurnCount: 1,
328 checkpointRef: CheckpointRef.make("checkpoint-with-files"),
329 status: "ready",
330 files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }],
331 assistantMessageId,
332 completedAt: MESSAGE_CREATED_AT,
333 },
334 ],
335 ])
336 }
337 />,
338 );
339​
340 expect(markup).toContain("sticky top-2 z-10");
341 expect(markup).not.toContain("self-start");
342 expect(markup).toContain("whitespace-nowrap");
343 expect(markup).toContain("!size-[22px]");
344 expect(markup).toContain("size-3");
345 expect(markup).toContain('aria-label="Collapse all folders"');
346 expect(markup).toContain('aria-label="Open diff"');
347 expect(markup).toContain("1 changed file");
348 });
349​
350 it("treats only the strict list end as the live edge", async () => {
351 const {
352 resolveTimelineIsAtEnd,
353 resolveTimelineMinimapHasPersistentGutter,
354 resolveTimelineMinimapHeightStyle,
355 resolveTimelineMinimapHitStripWidth,
356 resolveTimelineMinimapIndexFromPointer,
357 resolveTimelineMinimapInteractiveWidth,
358 resolveTimelineMinimapTopPercent,
359 } = await import("./MessagesTimeline.logic");
360​
361 expect(resolveTimelineIsAtEnd({ isAtEnd: true })).toBe(true);
362 expect(resolveTimelineIsAtEnd(undefined)).toBeUndefined();
363 // Within the pixel band above the content bottom counts as the end...
364 expect(
365 resolveTimelineIsAtEnd({
366 isAtEnd: false,
367 contentLength: 2000,
368 scroll: 1170,
369 scrollLength: 800,
370 }),
371 ).toBe(true);
372 // ...but half a viewport up (LegendList's isNearEnd territory) does not.
373 expect(
374 resolveTimelineIsAtEnd({
375 isAtEnd: false,
376 contentLength: 2000,
377 scroll: 900,
378 scrollLength: 800,
379 }),
380 ).toBe(false);
381 // The composer inset is part of contentLength and must not count as
382 // distance-to-end.
383 expect(
384 resolveTimelineIsAtEnd(
385 { isAtEnd: false, contentLength: 2100, scroll: 1170, scrollLength: 800 },
386 100,
387 ),
388 ).toBe(true);
389 // Geometry missing (older state shape): fall back to the strict flag.
390 expect(resolveTimelineIsAtEnd({ isAtEnd: false })).toBe(false);
391​
392 expect(resolveTimelineMinimapHeightStyle(5)).toBe("min(32px, calc(100vh - 18rem))");
393 expect(resolveTimelineMinimapTopPercent(2, 5)).toBe(50);
394 expect(
395 resolveTimelineMinimapIndexFromPointer({
396 itemCount: 101,
397 railTop: 100,
398 railHeight: 500,
399 pointerY: 350,
400 }),
401 ).toBe(50);
402 expect(
403 resolveTimelineMinimapIndexFromPointer({
404 itemCount: 101,
405 railTop: 100,
406 railHeight: 500,
407 pointerY: 999,
408 }),
409 ).toBe(100);
410 expect(resolveTimelineMinimapHasPersistentGutter(832)).toBe(false);
411 expect(resolveTimelineMinimapHasPersistentGutter(863)).toBe(false);
412 expect(resolveTimelineMinimapHasPersistentGutter(864)).toBe(true);
413​
414 // No usable gutter (zoomed in / narrow pane): the strip must go inert
415 // instead of overlaying the centered content column.
416 expect(resolveTimelineMinimapHitStripWidth(768)).toBe(0);
417 expect(resolveTimelineMinimapHitStripWidth(792)).toBe(0);
418 // Partial gutter: strip shrinks to what fits between the viewport edge
419 // and the content column.
420 expect(resolveTimelineMinimapHitStripWidth(820)).toBe(14);
421 // Full gutter: unchanged 40px-wide strip.
422 expect(resolveTimelineMinimapHitStripWidth(872)).toBe(40);
423 expect(resolveTimelineMinimapHitStripWidth(1400)).toBe(40);
424 expect(resolveTimelineMinimapHitStripWidth(0)).toBe(0);
425 expect(resolveTimelineMinimapHitStripWidth(Number.NaN)).toBe(0);
426​
427 // The collapsed target stays narrow, but an open preview keeps its full
428 // 20rem width plus the 2rem offset from the minimap rail interactive.
429 expect(resolveTimelineMinimapInteractiveWidth(0, false)).toBe(0);
430 expect(resolveTimelineMinimapInteractiveWidth(14, false)).toBe(14);
431 expect(resolveTimelineMinimapInteractiveWidth(40, false)).toBe(40);
432 expect(resolveTimelineMinimapInteractiveWidth(0, true)).toBe("22rem");
433 expect(resolveTimelineMinimapInteractiveWidth(14, true)).toBe("22rem");
434 expect(resolveTimelineMinimapInteractiveWidth(40, true)).toBe("22rem");
435 });
436​
437 it("anchors a sent attachment message using its measured height", () => {
438 const onAnchorReady = vi.fn();
439 const firstEntry = buildUserTimelineEntry("First prompt.");
440 const secondEntry = {
441 ...buildUserTimelineEntry("Newest prompt."),
442 id: "entry-2",
443 message: {
444 ...buildUserTimelineEntry("Newest prompt.").message,
445 id: MessageId.make("message-2"),
446 attachments: [
447 {
448 type: "image" as const,
449 id: "attachment-1",
450 name: "screenshot.png",
451 mimeType: "image/png",
452 sizeBytes: 1,
453 previewUrl: "data:image/png;base64,iVBORw0KGgo=",
454 },
455 ],
456 },
457 };
458 const markup = renderToStaticMarkup(
459 <MessagesTimeline
460 {...buildProps()}
461 anchorMessageId={secondEntry.message.id}
462 onAnchorReady={onAnchorReady}
463 contentInsetEndAdjustment={144}
464 timelineEntries={[firstEntry, secondEntry]}
465 />,
466 );
467​
468 expect(markup).toContain('data-anchor-index="1"');
469 expect(markup).toContain('data-anchor-offset="16"');
470 expect(markup).toContain('data-anchor-on-ready="true"');
471 expect(markup).not.toContain("data-anchor-max-size=");
472 expect(markup).toContain('data-content-inset-end="144"');
473 expect(markup).toContain("[overflow-anchor:none]");
474 expect(markup).not.toContain('data-maintain-scroll-at-end="enabled"');
475 expect(markup).toContain('data-maintain-visible-content-position="object"');
476 expect(markup).toContain('data-maintain-visible-content-position-data="true"');
477 expect(markup).toContain('data-maintain-visible-content-position-size="true"');
478 expect(markup).toContain('data-maintain-visible-content-position-restore="true"');
479 expect(onAnchorReady).toHaveBeenCalledOnce();
480 expect(onAnchorReady).toHaveBeenCalledWith(secondEntry.message.id, 1);
481 });
482​
483 it("hands end-following back to the list once the send anchor is released", () => {
484 const firstEntry = buildUserTimelineEntry("First prompt.");
485 const secondEntry = {
486 ...buildUserTimelineEntry("Newest prompt."),
487 id: "entry-2",
488 message: {
489 ...buildUserTimelineEntry("Newest prompt.").message,
490 id: MessageId.make("message-2"),
491 },
492 };
493 const timelineEntries = [firstEntry, secondEntry];
494​
495 // While the send anchor holds the end space open, ChatView owns streaming
496 // scrolls and LegendList must not re-pin behind it.
497 expect(
498 renderToStaticMarkup(
499 <MessagesTimeline
500 {...buildProps()}
501 anchorMessageId={secondEntry.message.id}
502 timelineEntries={timelineEntries}
503 />,
504 ),
505 ).not.toContain('data-maintain-scroll-at-end="enabled"');
506​
507 // Dropping the anchor is what actually gives end-following back, so
508 // returning to the live edge has to release it — re-enabling live follow
509 // alone leaves nothing pinned to the stream.
510 expect(
511 renderToStaticMarkup(
512 <MessagesTimeline
513 {...buildProps()}
514 anchorMessageId={null}
515 timelineEntries={timelineEntries}
516 />,
517 ),
518 ).toContain('data-maintain-scroll-at-end="enabled"');
519​
520 // Reading history still wins over both.
521 expect(
522 renderToStaticMarkup(
523 <MessagesTimeline
524 {...buildProps()}
525 anchorMessageId={null}
526 liveFollowEnabled={false}
527 timelineEntries={timelineEntries}
528 />,
529 ),
530 ).not.toContain('data-maintain-scroll-at-end="enabled"');
531 });
532​
533 it("renders collapse controls for long user messages", () => {
534 const markup = renderToStaticMarkup(
535 <MessagesTimeline
536 {...buildProps()}
537 timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
538 />,
539 );
540​
541 expect(markup).toContain("Show full message");
542 expect(markup).toContain('data-maintain-scroll-at-end="enabled"');
543 expect(markup).toContain('data-maintain-scroll-at-end-animated="false"');
544 expect(markup).toContain('data-maintain-scroll-at-end-data-change="true"');
545 expect(markup).toContain('data-maintain-scroll-at-end-item-layout="true"');
546 expect(markup).toContain('data-maintain-scroll-at-end-layout="true"');
547 expect(markup).toContain('data-user-message-collapsed="true"');
548 expect(markup).toContain('data-user-message-fade="true"');
549 expect(markup).toContain('data-user-message-footer="true"');
550 });
551​
552 it("does not render collapse controls for short user messages", () => {
553 const markup = renderToStaticMarkup(
554 <MessagesTimeline
555 {...buildProps()}
556 timelineEntries={[buildUserTimelineEntry("Short prompt.")]}
557 />,
558 );
559​
560 expect(markup).not.toContain("Show full message");
561 expect(markup).toContain('data-user-message-collapsible="false"');
562 expect(markup).toContain("rounded-2xl bg-message p-3");
563 });
564​
565 it("preserves arbitrary XML-like tags and comparisons in rendered user messages", async () => {
566 const { MessagesTimeline } = await import("./MessagesTimeline");
567 const markup = renderToStaticMarkup(
568 <MessagesTimeline
569 {...buildProps()}
570 timelineEntries={[
571 buildUserTimelineEntry(
572 [
573 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
574 'Before <nested data-value="a&b">inside</nested> after',
575 "</global-agent-instructions> in your context?",
576 "Comparison: 2 < 3 and 5 > 4.",
577 ].join("\n"),
578 ),
579 ]}
580 />,
581 );
582​
583 expect(markup).toContain("&lt;global-agent-instructions scope=&quot;workspace&quot;&gt;");
584 expect(markup).toContain(
585 "Before &lt;nested data-value=&quot;a&amp;b&quot;&gt;inside&lt;/nested&gt; after",
586 );
587 expect(markup).toContain("&lt;/global-agent-instructions&gt; in your context?");
588 expect(markup).toContain("Comparison: 2 &lt; 3 and 5 &gt; 4.");
589 });
590​
591 it("preserves XML-like source inside user code spans and fences", async () => {
592 const { MessagesTimeline } = await import("./MessagesTimeline");
593 const markup = renderToStaticMarkup(
594 <MessagesTimeline
595 {...buildProps()}
596 timelineEntries={[
597 buildUserTimelineEntry(
598 [
599 'Inline `<tag attr="x">`',
600 "",
601 "```xml",
602 '<root><child enabled="true" /></root>',
603 "```",
604 ].join("\n"),
605 ),
606 ]}
607 />,
608 );
609​
610 expect(markup).toContain('<code data-inline-code="">&lt;tag attr=&quot;x&quot;&gt;</code>');
611 expect(markup).toContain("&lt;root&gt;&lt;child enabled=&quot;true&quot; /&gt;&lt;/root&gt;");
612 });
613​
614 it("does not render markdown title attributes in user messages", async () => {
615 const { MessagesTimeline } = await import("./MessagesTimeline");
616 const markup = renderToStaticMarkup(
617 <MessagesTimeline
618 {...buildProps()}
619 timelineEntries={[
620 buildUserTimelineEntry(
621 '[link](https://example.com "link tip") ![image](https://example.com/image.png "image tip")',
622 ),
623 ]}
624 />,
625 );
626​
627 expect(markup).toContain('href="https://example.com"');
628 expect(markup).toContain('src="https://example.com/image.png"');
629 expect(markup).not.toContain('title="link tip"');
630 expect(markup).not.toContain('title="image tip"');
631 });
632​
633 it("renders unsafe user HTML as inert source text", async () => {
634 const { MessagesTimeline } = await import("./MessagesTimeline");
635 const markup = renderToStaticMarkup(
636 <MessagesTimeline
637 {...buildProps()}
638 timelineEntries={[
639 buildUserTimelineEntry(
640 '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">',
641 ),
642 ]}
643 />,
644 );
645​
646 expect(markup).toContain("&lt;script&gt;globalThis.__t3Xss = 1&lt;/script&gt;");
647 expect(markup).toContain(
648 "&lt;img src=&quot;x&quot; onerror=&quot;globalThis.__t3Xss = 2&quot;&gt;",
649 );
650 expect(markup).not.toMatch(/<script(?:\s|>)/i);
651 expect(markup).not.toMatch(/<img(?:\s|>)/i);
652 });
653​
654 it("continues to render sanitized raw HTML in assistant messages", async () => {
655 const { MessagesTimeline } = await import("./MessagesTimeline");
656 const markup = renderToStaticMarkup(
657 <MessagesTimeline
658 {...buildProps()}
659 timelineEntries={[
660 buildAssistantTimelineEntry("<details><summary>More</summary>Details</details>"),
661 ]}
662 />,
663 );
664​
665 expect(markup).toContain('data-markdown-details=""');
666 expect(markup).toContain("More");
667 expect(markup).not.toContain("&lt;details&gt;");
668 });
669​
670 it("sanitizes executable HTML while preserving supported assistant markup", async () => {
671 const { MessagesTimeline } = await import("./MessagesTimeline");
672 const markup = renderToStaticMarkup(
673 <MessagesTimeline
674 {...buildProps()}
675 timelineEntries={[
676 buildAssistantTimelineEntry(
677 [
678 '<details open onclick="globalThis.__t3Xss = 1">',
679 "<summary>Safe details</summary>",
680 "<script>globalThis.__t3Xss = 2</script>",
681 '<img src="x" onerror="globalThis.__t3Xss = 3">',
682 '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
683 "</details>",
684 ].join(""),
685 ),
686 ]}
687 />,
688 );
689​
690 expect(markup).toContain('data-markdown-details=""');
691 expect(markup).toContain("Safe details");
692 expect(markup).not.toMatch(/<script(?:\s|>)/i);
693 expect(markup).not.toContain("onclick=");
694 expect(markup).not.toContain("onerror=");
695 expect(markup).not.toContain("javascript:");
696 expect(markup).not.toContain("globalThis.__t3Xss");
697 });
698​
699 it("renders inline terminal labels with the composer chip UI", async () => {
700 const { MessagesTimeline } = await import("./MessagesTimeline");
701 const markup = renderToStaticMarkup(
702 <MessagesTimeline
703 {...buildProps()}
704 timelineEntries={[
705 buildUserTimelineEntry(
706 [
707 buildLongUserMessageText("yoo what's @terminal-1:1-5 mean"),
708 "",
709 "<terminal_context>",
710 "- Terminal 1 lines 1-5:",
711 " 1 | julius@mac effect-http-ws-cli % bun i",
712 " 2 | bun install v1.3.9 (cf6cdbbb)",
713 "</terminal_context>",
714 ].join("\n"),
715 ),
716 ]}
717 />,
718 );
719​
720 expect(markup).toContain("Terminal 1 lines 1-5");
721 expect(markup).toContain("lucide-terminal");
722 expect(markup).toContain("yoo what&#x27;s</p>");
723 expect(markup).toContain('<span aria-hidden="true"> </span>');
724 expect(markup).toContain("Show full message");
725 }, 20_000);
726​
727 it("renders chips for standalone element-pick context messages", () => {
728 const markup = renderToStaticMarkup(
729 <MessagesTimeline
730 {...buildProps()}
731 timelineEntries={[
732 buildUserTimelineEntry(
733 [
734 "<element_context>",
735 "- <SubmitButton> (Button.tsx:12):",
736 " url: https://example.com/dashboard",
737 " selector: button.submit",
738 " source: /repo/src/Button.tsx:12:5",
739 " html:",
740 ' <button class="submit">Save</button>',
741 "</element_context>",
742 ].join("\n"),
743 ),
744 ]}
745 />,
746 );
747​
748 expect(markup).toContain("SubmitButton");
749 expect(markup).not.toContain("&lt;element_context");
750 expect(markup).not.toContain("<element_context");
751 });
752​
753 it("keeps the copy button for collapsed long user messages", () => {
754 const markup = renderToStaticMarkup(
755 <MessagesTimeline
756 {...buildProps()}
757 timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
758 />,
759 );
760​
761 expect(markup).toContain('aria-label="Copy link"');
762 expect(markup).toContain('data-user-message-collapsed="true"');
763 expect(markup).toContain('data-user-message-footer="true"');
764 });
765​
766 it("renders context compaction entries in the normal work log", () => {
767 const markup = renderToStaticMarkup(
768 <MessagesTimeline
769 {...buildProps()}
770 timelineEntries={[
771 {
772 id: "entry-1",
773 kind: "work",
774 createdAt: "2026-03-17T19:12:28.000Z",
775 entry: {
776 id: "work-1",
777 createdAt: "2026-03-17T19:12:28.000Z",
778 label: "Context compacted",
779 tone: "info",
780 },
781 },
782 ]}
783 />,
784 );
785​
786 expect(markup).toContain("Context compacted");
787 expect(markup).toContain("Work Log");
788 });
789​
790 it("summarizes changed files in one line", () => {
791 const markup = renderToStaticMarkup(
792 <MessagesTimeline
793 {...buildProps()}
794 timelineEntries={[
795 {
796 id: "entry-1",
797 kind: "work",
798 createdAt: "2026-03-17T19:12:28.000Z",
799 entry: {
800 id: "work-1",
801 createdAt: "2026-03-17T19:12:28.000Z",
802 label: "Updated files",
803 tone: "tool",
804 changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
805 },
806 },
807 ]}
808 workspaceRoot="C:/Users/mike/dev-stuff/t3code"
809 />,
810 );
811​
812 expect(markup).toContain("Changed 1 file");
813 expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
814 });
815​
816 it("shows the animated one-line label for a live tool group", () => {
817 const turnId = TurnId.make("turn-live");
818 const markup = renderToStaticMarkup(
819 <MessagesTimeline
820 {...buildProps()}
821 isWorking
822 activeTurnStartedAt={MESSAGE_CREATED_AT}
823 latestTurn={{
824 turnId,
825 state: "running",
826 startedAt: MESSAGE_CREATED_AT,
827 completedAt: null,
828 }}
829 runningTurnId={turnId}
830 timelineEntries={[
831 {
832 id: "entry-live",
833 kind: "work",
834 createdAt: MESSAGE_CREATED_AT,
835 entry: {
836 id: "work-live",
837 createdAt: MESSAGE_CREATED_AT,
838 turnId,
839 toolCallId: "call-live",
840 label: "Run tests",
841 tone: "tool",
842 itemType: "command_execution",
843 command: "pnpm test",
844 toolLifecycleStatus: "inProgress",
845 },
846 },
847 ]}
848 />,
849 );
850​
851 expect(markup).toContain("Working for");
852 expect(markup).toContain("Running pnpm");
853 expect(markup).toContain("live-activity-focus");
854 });
855​
856 it("scopes a live row failure to the tool named by the row", () => {
857 const turnId = TurnId.make("turn-live");
858 const markup = renderToStaticMarkup(
859 <MessagesTimeline
860 {...buildProps()}
861 isWorking
862 activeTurnStartedAt={MESSAGE_CREATED_AT}
863 latestTurn={{
864 turnId,
865 state: "running",
866 startedAt: MESSAGE_CREATED_AT,
867 completedAt: null,
868 }}
869 runningTurnId={turnId}
870 timelineEntries={[
871 {
872 id: "entry-failed",
873 kind: "work",
874 createdAt: MESSAGE_CREATED_AT,
875 entry: {
876 id: "work-failed",
877 createdAt: MESSAGE_CREATED_AT,
878 turnId,
879 toolCallId: "call-failed",
880 label: "Run lint",
881 tone: "tool",
882 itemType: "command_execution",
883 command: "pnpm lint",
884 toolLifecycleStatus: "failed",
885 },
886 },
887 {
888 id: "entry-running",
889 kind: "work",
890 createdAt: MESSAGE_CREATED_AT,
891 entry: {
892 id: "work-running",
893 createdAt: MESSAGE_CREATED_AT,
894 turnId,
895 toolCallId: "call-running",
896 label: "Run tests",
897 tone: "tool",
898 itemType: "command_execution",
899 command: "pnpm test",
900 toolLifecycleStatus: "inProgress",
901 },
902 },
903 ]}
904 />,
905 );
906​
907 expect(markup).toContain("Running pnpm");
908 expect(markup).not.toContain("tool call failed");
909 });
910​
911 it("keeps terminal command copy live while the parent turn is active", () => {
912 const turnId = TurnId.make("turn-live");
913 const markup = renderToStaticMarkup(
914 <MessagesTimeline
915 {...buildProps()}
916 isWorking
917 activeTurnStartedAt={MESSAGE_CREATED_AT}
918 latestTurn={{
919 turnId,
920 state: "running",
921 startedAt: MESSAGE_CREATED_AT,
922 completedAt: null,
923 }}
924 runningTurnId={turnId}
925 timelineEntries={[
926 {
927 id: "entry-failed",
928 kind: "work",
929 createdAt: MESSAGE_CREATED_AT,
930 entry: {
931 id: "work-failed",
932 createdAt: MESSAGE_CREATED_AT,
933 turnId,
934 toolCallId: "call-failed",
935 label: "Run lint",
936 tone: "tool",
937 itemType: "command_execution",
938 command: "pnpm lint",
939 toolLifecycleStatus: "failed",
940 },
941 },
942 ]}
943 />,
944 );
945​
946 expect(markup).toContain("Running pnpm");
947 expect(markup).toContain("tool call failed");
948 });
949​
950 it("aligns the iconless Thinking row with the working timer", () => {
951 const markup = renderToStaticMarkup(
952 <MessagesTimeline
953 {...buildProps()}
954 isWorking
955 activeTurnStartedAt={MESSAGE_CREATED_AT}
956 timelineEntries={[]}
957 />,
958 );
959​
960 expect(markup).toContain("Working for");
961 expect(markup).toContain("Thinking");
962 expect(markup).toContain("gap-1.5 py-0.5 px-1");
963 });
964​
965 it("renders review comment contexts as structured cards instead of raw tags", () => {
966 const markup = renderToStaticMarkup(
967 <MessagesTimeline
968 {...buildProps()}
969 timelineEntries={[
970 {
971 id: "entry-1",
972 kind: "message",
973 createdAt: "2026-03-17T19:12:28.000Z",
974 message: {
975 id: MessageId.make("message-2"),
976 role: "user",
977 text: [
978 '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
979 "Wadduo",
980 "```diff",
981 "@@ -0,0 +47,2 @@",
982 '+ it("keeps valid zero-usage snapshots", () => {',
983 "+ expect(snapshot).not.toBeNull();",
984 "```",
985 "</review_comment>",
986 ].join("\n"),
987 turnId: null,
988 createdAt: "2026-03-17T19:12:28.000Z",
989 updatedAt: "2026-03-17T19:12:28.000Z",
990 streaming: false,
991 },
992 },
993 ]}
994 />,
995 );
996​
997 expect(markup).toContain("contextWindow.test.ts");
998 expect(markup).toContain("Wadduo");
999 expect(markup).toContain('data-testid="file-diff"');
1000 expect(markup).not.toContain(">Review comment<");
1001 expect(markup).not.toContain("&lt;review_comment");
1002 expect(markup).not.toContain("&lt;/review_comment&gt;");
1003 });
1004​
1005 it("renders file review comments as source code instead of diffs", () => {
1006 const markup = renderToStaticMarkup(
1007 <MessagesTimeline
1008 {...buildProps()}
1009 timelineEntries={[
1011 id: "entry-1",
1012 kind: "message",
1013 createdAt: "2026-03-17T19:12:28.000Z",
1014 message: {
1015 id: MessageId.make("message-source-comment"),
1016 role: "user",
1017 text: [
1018 '<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
1019 "Clarify this.",
1020 "```md",
1021 "# Plan",
1022 "- Step one",
1023 "```",
1024 "</review_comment>",
1025 ].join("\n"),
1026 turnId: null,
1027 createdAt: "2026-03-17T19:12:28.000Z",
1028 updatedAt: "2026-03-17T19:12:28.000Z",
1029 streaming: false,
1030 },
1031 },
1032 ]}
1033 />,
1034 );
1035​
1036 expect(markup).toContain("plan.md");
1037 expect(markup).toContain("Clarify this.");
1038 expect(markup).toContain("# Plan");
1039 expect(markup).not.toContain('data-testid="file-diff"');
1040 });
1041​
1042 it("renders a failure marker for failed tool lifecycle entries", () => {
1043 const markup = renderToStaticMarkup(
1044 <MessagesTimeline
1045 {...buildProps()}
1046 timelineEntries={[
1048 id: "entry-1",
1049 kind: "work",
1050 createdAt: "2026-03-17T19:12:28.000Z",
1051 entry: {
1052 id: "work-1",
1053 createdAt: "2026-03-17T19:12:28.000Z",
1054 label: "Glob",
1055 tone: "tool",
1056 toolLifecycleStatus: "failed",
1057 detail: "No files found",
1058 },
1059 },
1060 ]}
1061 />,
1062 );
1063​
1064 expect(markup).toContain("lucide-x");
1065 expect(markup).toContain('aria-label="Tool call failed"');
1066 });
1067});