Open History to see the last commit
1import { CheckpointRef, EnvironmentId, MessageId, TurnId } from "@t3tools/contracts";
2import { codexFeedbackMessage } from "@t3tools/client-runtime/state/threads";
3import { createRef, type ReactNode, type Ref } from "react";
4import { renderToStaticMarkup } from "react-dom/server";
5import { beforeAll, describe, expect, it, vi } from "vite-plus/test";
6import type { LegendListRef } from "@legendapp/list/react";
7
8vi.mock("@legendapp/list/react", async () => {
9 const legendListTestId = "legend-list";
10
11 const LegendList = (props: {
12 data: Array<{ id: string }>;
13 keyExtractor: (item: { id: string }) => string;
14 renderItem: (args: { item: { id: string } }) => ReactNode;
15 ListHeaderComponent?: ReactNode;
16 ListFooterComponent?: ReactNode;
17 anchoredEndSpace?: {
18 anchorIndex: number;
19 anchorMaxSize?: number;
20 anchorOffset?: number;
21 onReady?: (info: { anchorIndex: 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.onReady?.({ anchorIndex: props.anchoredEndSpace.anchorIndex });
46 }
47 return (
48 <div
49 data-testid={legendListTestId}
50 data-anchor-index={props.anchoredEndSpace?.anchorIndex}
51 data-anchor-max-size={props.anchoredEndSpace?.anchorMaxSize}
52 data-anchor-offset={props.anchoredEndSpace?.anchorOffset}
53 data-anchor-on-ready={Boolean(props.anchoredEndSpace?.onReady)}
54 data-content-inset-end={props.contentInsetEndAdjustment}
55 data-class-name={props.className}
56 data-maintain-scroll-at-end={props.maintainScrollAtEnd ? "enabled" : undefined}
57 data-maintain-scroll-at-end-animated={
58 typeof props.maintainScrollAtEnd === "object"
59 ? props.maintainScrollAtEnd.animated
60 : undefined
61 }
62 data-maintain-scroll-at-end-data-change={
63 typeof props.maintainScrollAtEnd === "object"
64 ? props.maintainScrollAtEnd.on?.dataChange
65 : undefined
66 }
67 data-maintain-scroll-at-end-item-layout={
68 typeof props.maintainScrollAtEnd === "object"
69 ? props.maintainScrollAtEnd.on?.itemLayout
70 : undefined
71 }
72 data-maintain-scroll-at-end-layout={
73 typeof props.maintainScrollAtEnd === "object"
74 ? props.maintainScrollAtEnd.on?.layout
75 : undefined
76 }
77 data-maintain-visible-content-position={
78 typeof props.maintainVisibleContentPosition === "object"
79 ? "object"
80 : props.maintainVisibleContentPosition
81 }
82 data-maintain-visible-content-position-data={
83 typeof props.maintainVisibleContentPosition === "object"
84 ? props.maintainVisibleContentPosition.data
85 : undefined
86 }
87 data-maintain-visible-content-position-size={
88 typeof props.maintainVisibleContentPosition === "object"
89 ? props.maintainVisibleContentPosition.size
90 : undefined
91 }
92 data-maintain-visible-content-position-restore={
93 typeof props.maintainVisibleContentPosition === "object"
94 ? Boolean(props.maintainVisibleContentPosition.shouldRestorePosition)
95 : undefined
96 }
97 >
98 {props.ListHeaderComponent}
99 {props.data.map((item) => (
100 <div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
101 ))}
102 {props.ListFooterComponent}
103 </div>
104 );
105 };
106
107 return { LegendList };
108});
109
110function MockFileDiff(props: {
111 fileDiff: { name?: string | null; prevName?: string | null };
112 renderCustomHeader?: (fileDiff: {
113 name?: string | null;
114 prevName?: string | null;
115 }) => React.ReactNode;
116}) {
117 return (
118 <div data-testid="file-diff">
119 {props.renderCustomHeader?.(props.fileDiff)}
120 {props.fileDiff.name ?? props.fileDiff.prevName ?? "diff"}
121 </div>
122 );
123}
124
125vi.mock("@pierre/diffs/react", () => {
126 return { FileDiff: MockFileDiff };
127});
128
129function matchMedia() {
130 return {
131 matches: false,
132 addEventListener: () => {},
133 removeEventListener: () => {},
134 };
135}
136
137let MessagesTimeline: typeof import("./MessagesTimeline").MessagesTimeline;
138
139beforeAll(async () => {
140 const classList = {
141 add: () => {},
142 remove: () => {},
143 toggle: () => {},
144 contains: () => false,
145 };
146
147 vi.stubGlobal("localStorage", {
148 getItem: () => null,
149 setItem: () => {},
150 removeItem: () => {},
151 clear: () => {},
152 });
153 vi.stubGlobal("window", {
154 matchMedia,
155 addEventListener: () => {},
156 removeEventListener: () => {},
157 requestAnimationFrame: (callback: FrameRequestCallback) => {
158 callback(0);
159 return 0;
160 },
161 cancelAnimationFrame: () => {},
162 desktopBridge: undefined,
163 });
164 vi.stubGlobal("document", {
165 documentElement: {
166 classList,
167 offsetHeight: 0,
168 },
169 });
170
171 ({ MessagesTimeline } = await import("./MessagesTimeline"));
172}, 30_000);
173
174const ACTIVE_THREAD_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
175const MESSAGE_CREATED_AT = "2026-03-17T19:12:28.000Z";
176
177function buildProps() {
178 return {
179 isWorking: 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 };
203}
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");
209}
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 };
226}
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 };
237}
238
239describe("MessagesTimeline", () => {
240 it("renders a feedback command and its pending response as normal thread messages", () => {
241 const submission = {
242 id: MessageId.make("feedback-command"),
243 command: "/feedback The agent stopped early.",
244 createdAt: MESSAGE_CREATED_AT,
245 status: "uploading" as const,
246 };
247 const messages = [
248 codexFeedbackMessage(submission),
249 codexFeedbackMessage(submission, "assistant"),
250 ];
251 const markup = renderToStaticMarkup(
252 <MessagesTimeline
253 {...buildProps()}
254 timelineEntries={messages.map((message) => ({
255 id: message.id,
256 kind: "message" as const,
257 createdAt: message.createdAt,
258 message,
259 }))}
260 />,
261 );
262
263 expect(markup).toContain("/feedback The agent stopped early.");
264 expect(markup).toContain("Sending feedback to OpenAI...");
265 });
266
267 it("renders the returned Codex thread ID in the feedback response", () => {
268 const submission = {
269 id: MessageId.make("feedback-command"),
270 command: "/feedback The agent stopped early.",
271 createdAt: MESSAGE_CREATED_AT,
272 status: "sent" as const,
273 feedbackId: "codex-thread-1",
274 };
275 const messages = [
276 codexFeedbackMessage(submission),
277 codexFeedbackMessage(submission, "assistant"),
278 ];
279 const markup = renderToStaticMarkup(
280 <MessagesTimeline
281 {...buildProps()}
282 timelineEntries={messages.map((message) => ({
283 id: message.id,
284 kind: "message" as const,
285 createdAt: message.createdAt,
286 message,
287 }))}
288 />,
289 );
290
291 expect(markup).toContain("Feedback sent to OpenAI.");
292 expect(markup).toContain("codex-thread-1");
293 });
294
295 it("renders the worked-for row at assistant response text size", () => {
296 const turnId = TurnId.make("turn-with-fold");
297 const assistantEntry = buildAssistantTimelineEntry("Done.");
298 const markup = renderToStaticMarkup(
299 <MessagesTimeline
300 {...buildProps()}
301 latestTurn={{
302 turnId,
303 state: "completed",
304 startedAt: "2026-03-17T19:12:20.000Z",
305 completedAt: "2026-03-17T19:12:28.000Z",
306 }}
307 timelineEntries={[
308 {
309 id: "work-entry-with-fold",
310 kind: "work",
311 createdAt: "2026-03-17T19:12:22.000Z",
312 entry: {
313 id: "work-with-fold",
314 createdAt: "2026-03-17T19:12:22.000Z",
315 turnId,
316 label: "Ran command",
317 tone: "tool",
318 toolLifecycleStatus: "completed",
319 },
320 },
321 {
322 ...assistantEntry,
323 message: { ...assistantEntry.message, turnId },
324 },
325 ]}
326 />,
327 );
328
329 expect(markup).toContain("Worked for 8.0s");
330 expect(markup).toContain("px-1 text-sm leading-relaxed text-muted-foreground");
331 });
332
333 it("uses the larger leading inset only when the top fade is enabled", () => {
334 const timelineEntries = [buildUserTimelineEntry("Hello")];
335
336 const compactMarkup = renderToStaticMarkup(
337 <MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} />,
338 );
339 const fadedMarkup = renderToStaticMarkup(
340 <MessagesTimeline {...buildProps()} timelineEntries={timelineEntries} topFadeEnabled />,
341 );
342
343 expect(compactMarkup).toContain('class="h-3 sm:h-4"');
344 expect(compactMarkup).not.toContain("topbar-scroll-fade");
345 expect(fadedMarkup).toContain('class="h-10 sm:h-12"');
346 expect(fadedMarkup).toContain("topbar-scroll-fade");
347 });
348
349 it("keeps assistant changed-files headers sticky below the thread header", () => {
350 const assistantMessageId = MessageId.make("message-assistant-with-files");
351 const turnId = TurnId.make("turn-with-files");
352 const markup = renderToStaticMarkup(
353 <MessagesTimeline
354 {...buildProps()}
355 latestTurn={{
356 turnId,
357 state: "completed",
358 startedAt: MESSAGE_CREATED_AT,
359 completedAt: MESSAGE_CREATED_AT,
360 }}
361 timelineEntries={[
362 {
363 id: "entry-assistant-with-files",
364 kind: "message",
365 createdAt: MESSAGE_CREATED_AT,
366 message: {
367 id: assistantMessageId,
368 role: "assistant",
369 text: "Updated the fixture.",
370 turnId,
371 createdAt: MESSAGE_CREATED_AT,
372 updatedAt: MESSAGE_CREATED_AT,
373 streaming: false,
374 },
375 },
376 ]}
377 turnDiffSummaryByAssistantMessageId={
378 new Map([
379 [
380 assistantMessageId,
381 {
382 turnId,
383 checkpointTurnCount: 1,
384 checkpointRef: CheckpointRef.make("checkpoint-with-files"),
385 status: "ready",
386 files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }],
387 assistantMessageId,
388 completedAt: MESSAGE_CREATED_AT,
389 },
390 ],
391 ])
392 }
393 />,
394 );
395
396 expect(markup).toContain("sticky top-2 z-10");
397 expect(markup).not.toContain("self-start");
398 expect(markup).toContain("whitespace-nowrap");
399 expect(markup).toContain("!size-[22px]");
400 expect(markup).toContain("size-3");
401 expect(markup).toContain('aria-label="Collapse all folders"');
402 expect(markup).toContain('aria-label="Open diff"');
403 expect(markup).toContain("1 changed file");
404 });
405
406 it("treats only the strict list end as the live edge", async () => {
407 const {
408 resolveTimelineIsAtEnd,
409 resolveTimelineMinimapHasPersistentGutter,
410 resolveTimelineMinimapHeightStyle,
411 resolveTimelineMinimapHitStripWidth,
412 resolveTimelineMinimapIndexFromPointer,
413 resolveTimelineMinimapInteractiveWidth,
414 resolveTimelineMinimapTopPercent,
415 } = await import("./MessagesTimeline.logic");
416
417 expect(resolveTimelineIsAtEnd({ isAtEnd: true })).toBe(true);
418 expect(resolveTimelineIsAtEnd(undefined)).toBeUndefined();
419 // Within the pixel band above the content bottom counts as the end...
420 expect(
421 resolveTimelineIsAtEnd({
422 isAtEnd: false,
423 contentLength: 2000,
424 scroll: 1170,
425 scrollLength: 800,
426 }),
427 ).toBe(true);
428 // ...but half a viewport up (LegendList's isNearEnd territory) does not.
429 expect(
430 resolveTimelineIsAtEnd({
431 isAtEnd: false,
432 contentLength: 2000,
433 scroll: 900,
434 scrollLength: 800,
435 }),
436 ).toBe(false);
437 // The composer inset is part of contentLength and must not count as
438 // distance-to-end.
439 expect(
440 resolveTimelineIsAtEnd(
441 { isAtEnd: false, contentLength: 2100, scroll: 1170, scrollLength: 800 },
442 100,
443 ),
444 ).toBe(true);
445 // Geometry missing (older state shape): fall back to the strict flag.
446 expect(resolveTimelineIsAtEnd({ isAtEnd: false })).toBe(false);
447
448 expect(resolveTimelineMinimapHeightStyle(5)).toBe("min(32px, calc(100vh - 18rem))");
449 expect(resolveTimelineMinimapTopPercent(2, 5)).toBe(50);
450 expect(
451 resolveTimelineMinimapIndexFromPointer({
452 itemCount: 101,
453 railTop: 100,
454 railHeight: 500,
455 pointerY: 350,
456 }),
457 ).toBe(50);
458 expect(
459 resolveTimelineMinimapIndexFromPointer({
460 itemCount: 101,
461 railTop: 100,
462 railHeight: 500,
463 pointerY: 999,
464 }),
465 ).toBe(100);
466 expect(resolveTimelineMinimapHasPersistentGutter(832)).toBe(false);
467 expect(resolveTimelineMinimapHasPersistentGutter(863)).toBe(false);
468 expect(resolveTimelineMinimapHasPersistentGutter(864)).toBe(true);
469
470 // No usable gutter (zoomed in / narrow pane): the strip must go inert
471 // instead of overlaying the centered content column.
472 expect(resolveTimelineMinimapHitStripWidth(768)).toBe(0);
473 expect(resolveTimelineMinimapHitStripWidth(792)).toBe(0);
474 // Partial gutter: strip shrinks to what fits between the viewport edge
475 // and the content column.
476 expect(resolveTimelineMinimapHitStripWidth(820)).toBe(14);
477 // Full gutter: unchanged 40px-wide strip.
478 expect(resolveTimelineMinimapHitStripWidth(872)).toBe(40);
479 expect(resolveTimelineMinimapHitStripWidth(1400)).toBe(40);
480 expect(resolveTimelineMinimapHitStripWidth(0)).toBe(0);
481 expect(resolveTimelineMinimapHitStripWidth(Number.NaN)).toBe(0);
482
483 // The collapsed target stays narrow, but an open preview keeps its full
484 // 20rem width plus the 2rem offset from the minimap rail interactive.
485 expect(resolveTimelineMinimapInteractiveWidth(0, false)).toBe(0);
486 expect(resolveTimelineMinimapInteractiveWidth(14, false)).toBe(14);
487 expect(resolveTimelineMinimapInteractiveWidth(40, false)).toBe(40);
488 expect(resolveTimelineMinimapInteractiveWidth(0, true)).toBe("22rem");
489 expect(resolveTimelineMinimapInteractiveWidth(14, true)).toBe("22rem");
490 expect(resolveTimelineMinimapInteractiveWidth(40, true)).toBe("22rem");
491 });
492
493 it("anchors the first user message using its measured height", () => {
494 const onAnchorReady = vi.fn();
495 const firstEntry = {
496 ...buildUserTimelineEntry("First prompt."),
497 message: {
498 ...buildUserTimelineEntry("First prompt.").message,
499 attachments: [
500 {
501 type: "image" as const,
502 id: "attachment-1",
503 name: "screenshot.png",
504 mimeType: "image/png",
505 sizeBytes: 1,
506 previewUrl: "data:image/png;base64,iVBORw0KGgo=",
507 },
508 ],
509 },
510 };
511 const markup = renderToStaticMarkup(
512 <MessagesTimeline
513 {...buildProps()}
514 anchorMessageId={firstEntry.message.id}
515 onAnchorReady={onAnchorReady}
516 contentInsetEndAdjustment={144}
517 timelineEntries={[firstEntry]}
518 />,
519 );
520
521 expect(markup).toContain('data-anchor-index="0"');
522 expect(markup).toContain('data-anchor-offset="16"');
523 expect(markup).toContain('data-anchor-on-ready="true"');
524 expect(markup).not.toContain("data-anchor-max-size=");
525 expect(markup).toContain('data-content-inset-end="144"');
526 expect(markup).toContain("[overflow-anchor:none]");
527 expect(markup).not.toContain('data-maintain-scroll-at-end="enabled"');
528 expect(markup).toContain('data-maintain-visible-content-position="object"');
529 expect(markup).toContain('data-maintain-visible-content-position-data="true"');
530 expect(markup).toContain('data-maintain-visible-content-position-size="true"');
531 expect(markup).toContain('data-maintain-visible-content-position-restore="true"');
532 expect(onAnchorReady).toHaveBeenCalledOnce();
533 expect(onAnchorReady).toHaveBeenCalledWith(firstEntry.message.id, 0);
534 });
535
536 it("does not reserve end space for a follow-up user message", () => {
537 const onAnchorReady = vi.fn();
538 const firstEntry = buildUserTimelineEntry("First prompt.");
539 const secondEntry = {
540 ...buildUserTimelineEntry("Newest prompt."),
541 id: "entry-2",
542 message: {
543 ...buildUserTimelineEntry("Newest prompt.").message,
544 id: MessageId.make("message-2"),
545 },
546 };
547 const markup = renderToStaticMarkup(
548 <MessagesTimeline
549 {...buildProps()}
550 anchorMessageId={secondEntry.message.id}
551 onAnchorReady={onAnchorReady}
552 timelineEntries={[firstEntry, secondEntry]}
553 />,
554 );
555
556 expect(markup).not.toContain("data-anchor-index=");
557 expect(markup).toContain('data-maintain-scroll-at-end="enabled"');
558 expect(onAnchorReady).not.toHaveBeenCalled();
559 });
560
561 it("keeps reserved end space when tool work starts while reading history", () => {
562 const turnId = TurnId.make("turn-with-active-tool");
563 const firstEntry = buildUserTimelineEntry("Run the command.");
564 const markup = renderToStaticMarkup(
565 <MessagesTimeline
566 {...buildProps()}
567 isWorking
568 activeTurnStartedAt={MESSAGE_CREATED_AT}
569 latestTurn={{
570 turnId,
571 state: "running",
572 startedAt: MESSAGE_CREATED_AT,
573 completedAt: null,
574 }}
575 runningTurnId={turnId}
576 anchorMessageId={firstEntry.message.id}
577 liveFollowEnabled={false}
578 timelineEntries={[
579 firstEntry,
580 {
581 id: "entry-active-tool",
582 kind: "work",
583 createdAt: MESSAGE_CREATED_AT,
584 entry: {
585 id: "work-active-tool",
586 createdAt: MESSAGE_CREATED_AT,
587 turnId,
588 toolCallId: "call-active-tool",
589 label: "Run command",
590 tone: "tool",
591 itemType: "command_execution",
592 command: "git status",
593 toolLifecycleStatus: "inProgress",
594 },
595 },
596 ]}
597 />,
598 );
599
600 expect(markup).toContain('data-anchor-index="0"');
601 expect(markup).not.toContain('data-maintain-scroll-at-end="enabled"');
602 });
603
604 it("hands end-following back to the list once the send anchor is released", () => {
605 const firstEntry = buildUserTimelineEntry("First prompt.");
606 const secondEntry = {
607 ...buildUserTimelineEntry("Newest prompt."),
608 id: "entry-2",
609 message: {
610 ...buildUserTimelineEntry("Newest prompt.").message,
611 id: MessageId.make("message-2"),
612 },
613 };
614 const timelineEntries = [firstEntry, secondEntry];
615
616 // While the send anchor holds the end space open, ChatView owns streaming
617 // scrolls and LegendList must not re-pin behind it.
618 expect(
619 renderToStaticMarkup(
620 <MessagesTimeline
621 {...buildProps()}
622 anchorMessageId={firstEntry.message.id}
623 timelineEntries={timelineEntries}
624 />,
625 ),
626 ).not.toContain('data-maintain-scroll-at-end="enabled"');
627
628 // Dropping the anchor is what actually gives end-following back, so
629 // returning to the live edge has to release it — re-enabling live follow
630 // alone leaves nothing pinned to the stream.
631 expect(
632 renderToStaticMarkup(
633 <MessagesTimeline
634 {...buildProps()}
635 anchorMessageId={null}
636 timelineEntries={timelineEntries}
637 />,
638 ),
639 ).toContain('data-maintain-scroll-at-end="enabled"');
640
641 // Reading history still wins over both.
642 expect(
643 renderToStaticMarkup(
644 <MessagesTimeline
645 {...buildProps()}
646 anchorMessageId={null}
647 liveFollowEnabled={false}
648 timelineEntries={timelineEntries}
649 />,
650 ),
651 ).not.toContain('data-maintain-scroll-at-end="enabled"');
652 });
653
654 it("renders collapse controls for long user messages", () => {
655 const markup = renderToStaticMarkup(
656 <MessagesTimeline
657 {...buildProps()}
658 timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
659 />,
660 );
661
662 expect(markup).toContain("Show full message");
663 expect(markup).toContain('data-maintain-scroll-at-end="enabled"');
664 expect(markup).toContain('data-maintain-scroll-at-end-animated="false"');
665 expect(markup).toContain('data-maintain-scroll-at-end-data-change="true"');
666 expect(markup).toContain('data-maintain-scroll-at-end-item-layout="true"');
667 expect(markup).toContain('data-maintain-scroll-at-end-layout="true"');
668 expect(markup).toContain('data-user-message-collapsed="true"');
669 expect(markup).toContain('data-user-message-fade="true"');
670 expect(markup).toContain('data-user-message-footer="true"');
671 });
672
673 it("does not render collapse controls for short user messages", () => {
674 const markup = renderToStaticMarkup(
675 <MessagesTimeline
676 {...buildProps()}
677 timelineEntries={[buildUserTimelineEntry("Short prompt.")]}
678 />,
679 );
680
681 expect(markup).not.toContain("Show full message");
682 expect(markup).toContain('data-user-message-collapsible="false"');
683 expect(markup).toContain("rounded-2xl bg-message p-3");
684 });
685
686 it("preserves arbitrary XML-like tags and comparisons in rendered user messages", async () => {
687 const { MessagesTimeline } = await import("./MessagesTimeline");
688 const markup = renderToStaticMarkup(
689 <MessagesTimeline
690 {...buildProps()}
691 timelineEntries={[
692 buildUserTimelineEntry(
693 [
694 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
695 'Before <nested data-value="a&b">inside</nested> after',
696 "</global-agent-instructions> in your context?",
697 "Comparison: 2 < 3 and 5 > 4.",
698 ].join("\n"),
699 ),
700 ]}
701 />,
702 );
703
704 expect(markup).toContain("<global-agent-instructions scope="workspace">");
705 expect(markup).toContain(
706 "Before <nested data-value="a&b">inside</nested> after",
707 );
708 expect(markup).toContain("</global-agent-instructions> in your context?");
709 expect(markup).toContain("Comparison: 2 < 3 and 5 > 4.");
710 });
711
712 it("preserves XML-like source inside user code spans and fences", async () => {
713 const { MessagesTimeline } = await import("./MessagesTimeline");
714 const markup = renderToStaticMarkup(
715 <MessagesTimeline
716 {...buildProps()}
717 timelineEntries={[
718 buildUserTimelineEntry(
719 [
720 'Inline `<tag attr="x">`',
721 "",
722 "```xml",
723 '<root><child enabled="true" /></root>',
724 "```",
725 ].join("\n"),
726 ),
727 ]}
728 />,
729 );
730
731 expect(markup).toContain('<code data-inline-code=""><tag attr="x"></code>');
732 expect(markup).toContain("<root><child enabled="true" /></root>");
733 });
734
735 it("does not render markdown title attributes in user messages", async () => {
736 const { MessagesTimeline } = await import("./MessagesTimeline");
737 const markup = renderToStaticMarkup(
738 <MessagesTimeline
739 {...buildProps()}
740 timelineEntries={[
741 buildUserTimelineEntry(
742 '[link](https://example.com "link tip") ',
743 ),
744 ]}
745 />,
746 );
747
748 expect(markup).toContain('href="https://example.com"');
749 expect(markup).toContain('src="https://example.com/image.png"');
750 expect(markup).not.toContain('title="link tip"');
751 expect(markup).not.toContain('title="image tip"');
752 });
753
754 it("renders unsafe user HTML as inert source text", async () => {
755 const { MessagesTimeline } = await import("./MessagesTimeline");
756 const markup = renderToStaticMarkup(
757 <MessagesTimeline
758 {...buildProps()}
759 timelineEntries={[
760 buildUserTimelineEntry(
761 '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">',
762 ),
763 ]}
764 />,
765 );
766
767 expect(markup).toContain("<script>globalThis.__t3Xss = 1</script>");
768 expect(markup).toContain(
769 "<img src="x" onerror="globalThis.__t3Xss = 2">",
770 );
771 expect(markup).not.toMatch(/<script(?:\s|>)/i);
772 expect(markup).not.toMatch(/<img(?:\s|>)/i);
773 });
774
775 it("continues to render sanitized raw HTML in assistant messages", async () => {
776 const { MessagesTimeline } = await import("./MessagesTimeline");
777 const markup = renderToStaticMarkup(
778 <MessagesTimeline
779 {...buildProps()}
780 timelineEntries={[
781 buildAssistantTimelineEntry("<details><summary>More</summary>Details</details>"),
782 ]}
783 />,
784 );
785
786 expect(markup).toContain('data-markdown-details=""');
787 expect(markup).toContain("More");
788 expect(markup).not.toContain("<details>");
789 });
790
791 it("sanitizes executable HTML while preserving supported assistant markup", async () => {
792 const { MessagesTimeline } = await import("./MessagesTimeline");
793 const markup = renderToStaticMarkup(
794 <MessagesTimeline
795 {...buildProps()}
796 timelineEntries={[
797 buildAssistantTimelineEntry(
798 [
799 '<details open onclick="globalThis.__t3Xss = 1">',
800 "<summary>Safe details</summary>",
801 "<script>globalThis.__t3Xss = 2</script>",
802 '<img src="x" onerror="globalThis.__t3Xss = 3">',
803 '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
804 "</details>",
805 ].join(""),
806 ),
807 ]}
808 />,
809 );
810
811 expect(markup).toContain('data-markdown-details=""');
812 expect(markup).toContain("Safe details");
813 expect(markup).not.toMatch(/<script(?:\s|>)/i);
814 expect(markup).not.toContain("onclick=");
815 expect(markup).not.toContain("onerror=");
816 expect(markup).not.toContain("javascript:");
817 expect(markup).not.toContain("globalThis.__t3Xss");
818 });
819
820 it("renders inline terminal labels with the composer chip UI", async () => {
821 const { MessagesTimeline } = await import("./MessagesTimeline");
822 const markup = renderToStaticMarkup(
823 <MessagesTimeline
824 {...buildProps()}
825 timelineEntries={[
826 buildUserTimelineEntry(
827 [
828 buildLongUserMessageText("yoo what's @terminal-1:1-5 mean"),
829 "",
830 "<terminal_context>",
831 "- Terminal 1 lines 1-5:",
832 " 1 | julius@mac effect-http-ws-cli % bun i",
833 " 2 | bun install v1.3.9 (cf6cdbbb)",
834 "</terminal_context>",
835 ].join("\n"),
836 ),
837 ]}
838 />,
839 );
840
841 expect(markup).toContain("Terminal 1 lines 1-5");
842 expect(markup).toContain("lucide-terminal");
843 expect(markup).toContain("yoo what's</p>");
844 expect(markup).toContain('<span aria-hidden="true"> </span>');
845 expect(markup).toContain("Show full message");
846 }, 20_000);
847
848 it("renders chips for standalone element-pick context messages", () => {
849 const markup = renderToStaticMarkup(
850 <MessagesTimeline
851 {...buildProps()}
852 timelineEntries={[
853 buildUserTimelineEntry(
854 [
855 "<element_context>",
856 "- <SubmitButton> (Button.tsx:12):",
857 " url: https://example.com/dashboard",
858 " selector: button.submit",
859 " source: /repo/src/Button.tsx:12:5",
860 " html:",
861 ' <button class="submit">Save</button>',
862 "</element_context>",
863 ].join("\n"),
864 ),
865 ]}
866 />,
867 );
868
869 expect(markup).toContain("SubmitButton");
870 expect(markup).not.toContain("<element_context");
871 expect(markup).not.toContain("<element_context");
872 });
873
874 it("keeps the copy button for collapsed long user messages", () => {
875 const markup = renderToStaticMarkup(
876 <MessagesTimeline
877 {...buildProps()}
878 timelineEntries={[buildUserTimelineEntry(buildLongUserMessageText())]}
879 />,
880 );
881
882 expect(markup).toContain('aria-label="Copy link"');
883 expect(markup).toContain('data-user-message-collapsed="true"');
884 expect(markup).toContain('data-user-message-footer="true"');
885 });
886
887 it("renders context compaction entries in the normal work log", () => {
888 const markup = renderToStaticMarkup(
889 <MessagesTimeline
890 {...buildProps()}
891 timelineEntries={[
892 {
893 id: "entry-1",
894 kind: "work",
895 createdAt: "2026-03-17T19:12:28.000Z",
896 entry: {
897 id: "work-1",
898 createdAt: "2026-03-17T19:12:28.000Z",
899 label: "Context compacted",
900 tone: "info",
901 },
902 },
903 ]}
904 />,
905 );
906
907 expect(markup).toContain("Context compacted");
908 expect(markup).toContain("Work Log");
909 });
910
911 it("summarizes changed files in one line", () => {
912 const markup = renderToStaticMarkup(
913 <MessagesTimeline
914 {...buildProps()}
915 timelineEntries={[
916 {
917 id: "entry-1",
918 kind: "work",
919 createdAt: "2026-03-17T19:12:28.000Z",
920 entry: {
921 id: "work-1",
922 createdAt: "2026-03-17T19:12:28.000Z",
923 label: "Updated files",
924 tone: "tool",
925 changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
926 },
927 },
928 ]}
929 workspaceRoot="C:/Users/mike/dev-stuff/t3code"
930 />,
931 );
932
933 expect(markup).toContain("Changed 1 file");
934 expect(markup).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
935 });
936
937 it("keeps mixed-success tool groups neutral", () => {
938 const markup = renderToStaticMarkup(
939 <MessagesTimeline
940 {...buildProps()}
941 timelineEntries={[
942 {
943 id: "entry-failed",
944 kind: "work",
945 createdAt: "2026-03-17T19:12:28.000Z",
946 entry: {
947 id: "work-failed",
948 createdAt: "2026-03-17T19:12:28.000Z",
949 label: "Run search",
950 tone: "tool",
951 itemType: "command_execution",
952 toolLifecycleStatus: "failed",
953 },
954 },
955 {
956 id: "entry-completed",
957 kind: "work",
958 createdAt: "2026-03-17T19:12:29.000Z",
959 entry: {
960 id: "work-completed",
961 createdAt: "2026-03-17T19:12:29.000Z",
962 label: "Run tests",
963 tone: "tool",
964 itemType: "command_execution",
965 toolLifecycleStatus: "completed",
966 },
967 },
968 ]}
969 />,
970 );
971
972 expect(markup).toContain("Ran 2 commands");
973 expect(markup).not.toContain('aria-label="Tool call failed"');
974 });
975
976 it("keeps the collapsed summary icon neutral when the group ends in a failure", () => {
977 const markup = renderToStaticMarkup(
978 <MessagesTimeline
979 {...buildProps()}
980 timelineEntries={[
981 {
982 id: "entry-completed",
983 kind: "work",
984 createdAt: "2026-03-17T19:12:28.000Z",
985 entry: {
986 id: "work-completed",
987 createdAt: "2026-03-17T19:12:28.000Z",
988 label: "Run tests",
989 tone: "tool",
990 itemType: "command_execution",
991 toolLifecycleStatus: "completed",
992 },
993 },
994 {
995 id: "entry-failed",
996 kind: "work",
997 createdAt: "2026-03-17T19:12:29.000Z",
998 entry: {
999 id: "work-failed",
1000 createdAt: "2026-03-17T19:12:29.000Z",
1001 label: "Run lint",
1002 tone: "tool",
1003 itemType: "command_execution",
1004 toolLifecycleStatus: "failed",
1005 },
1006 },
1007 ]}
1008 />,
1009 );
1010
1011 expect(markup).toContain("Ran 2 commands");
1012 expect(markup).toContain("lucide-terminal");
1013 expect(markup).not.toContain("lucide-x");
1014 expect(markup).not.toContain("text-destructive");
1015 // The failure stays discoverable for screen readers.
1016 expect(markup).toContain("tool call failed");
1017 });
1018
1019 it("keeps mixed work logs neutral after a later tool call succeeds", () => {
1020 const markup = renderToStaticMarkup(
1021 <MessagesTimeline
1022 {...buildProps()}
1023 timelineEntries={[
1024 {
1025 id: "entry-failed",
1026 kind: "work",
1027 createdAt: "2026-03-17T19:12:28.000Z",
1028 entry: {
1029 id: "work-failed",
1030 createdAt: "2026-03-17T19:12:28.000Z",
1031 label: "Run search",
1032 tone: "tool",
1033 itemType: "command_execution",
1034 toolLifecycleStatus: "failed",
1035 },
1036 },
1037 {
1038 id: "entry-info",
1039 kind: "work",
1040 createdAt: "2026-03-17T19:12:29.000Z",
1041 entry: {
1042 id: "work-info",
1043 createdAt: "2026-03-17T19:12:29.000Z",
1044 label: "Status updated",
1045 tone: "info",
1046 },
1047 },
1048 {
1049 id: "entry-completed",
1050 kind: "work",
1051 createdAt: "2026-03-17T19:12:30.000Z",
1052 entry: {
1053 id: "work-completed",
1054 createdAt: "2026-03-17T19:12:30.000Z",
1055 label: "Run tests",
1056 tone: "tool",
1057 itemType: "command_execution",
1058 toolLifecycleStatus: "completed",
1059 },
1060 },
1061 ]}
1062 />,
1063 );
1064
1065 expect(markup).toContain("+2 previous log entries");
1066 expect(markup).not.toContain('aria-label="Hidden work includes a failure"');
1067 });
1068
1069 it("shows the animated one-line label for a live tool group", () => {
1070 const turnId = TurnId.make("turn-live");
1071 const markup = renderToStaticMarkup(
1072 <MessagesTimeline
1073 {...buildProps()}
1074 isWorking
1075 activeTurnStartedAt={MESSAGE_CREATED_AT}
1076 latestTurn={{
1077 turnId,
1078 state: "running",
1079 startedAt: MESSAGE_CREATED_AT,
1080 completedAt: null,
1081 }}
1082 runningTurnId={turnId}
1083 timelineEntries={[
1084 {
1085 id: "entry-live",
1086 kind: "work",
1087 createdAt: MESSAGE_CREATED_AT,
1088 entry: {
1089 id: "work-live",
1090 createdAt: MESSAGE_CREATED_AT,
1091 turnId,
1092 toolCallId: "call-live",
1093 label: "Run tests",
1094 tone: "tool",
1095 itemType: "command_execution",
1096 command: "pnpm test",
1097 toolLifecycleStatus: "inProgress",
1098 },
1099 },
1100 ]}
1101 />,
1102 );
1103
1104 expect(markup).toContain("Working for");
1105 expect(markup).toContain("Running pnpm");
1106 expect(markup).toContain("live-activity-focus");
1107 });
1108
1109 it("scopes a live row failure to the tool named by the row", () => {
1110 const turnId = TurnId.make("turn-live");
1111 const markup = renderToStaticMarkup(
1112 <MessagesTimeline
1113 {...buildProps()}
1114 isWorking
1115 activeTurnStartedAt={MESSAGE_CREATED_AT}
1116 latestTurn={{
1117 turnId,
1118 state: "running",
1119 startedAt: MESSAGE_CREATED_AT,
1120 completedAt: null,
1121 }}
1122 runningTurnId={turnId}
1123 timelineEntries={[
1124 {
1125 id: "entry-failed",
1126 kind: "work",
1127 createdAt: MESSAGE_CREATED_AT,
1128 entry: {
1129 id: "work-failed",
1130 createdAt: MESSAGE_CREATED_AT,
1131 turnId,
1132 toolCallId: "call-failed",
1133 label: "Run lint",
1134 tone: "tool",
1135 itemType: "command_execution",
1136 command: "pnpm lint",
1137 toolLifecycleStatus: "failed",
1138 },
1139 },
1140 {
1141 id: "entry-running",
1142 kind: "work",
1143 createdAt: MESSAGE_CREATED_AT,
1144 entry: {
1145 id: "work-running",
1146 createdAt: MESSAGE_CREATED_AT,
1147 turnId,
1148 toolCallId: "call-running",
1149 label: "Run tests",
1150 tone: "tool",
1151 itemType: "command_execution",
1152 command: "pnpm test",
1153 toolLifecycleStatus: "inProgress",
1154 },
1155 },
1156 ]}
1157 />,
1158 );
1159
1160 expect(markup).toContain("Running pnpm");
1161 expect(markup).not.toContain("tool call failed");
1162 });
1163
1164 it("keeps terminal command copy live while the parent turn is active", () => {
1165 const turnId = TurnId.make("turn-live");
1166 const markup = renderToStaticMarkup(
1167 <MessagesTimeline
1168 {...buildProps()}
1169 isWorking
1170 activeTurnStartedAt={MESSAGE_CREATED_AT}
1171 latestTurn={{
1172 turnId,
1173 state: "running",
1174 startedAt: MESSAGE_CREATED_AT,
1175 completedAt: null,
1176 }}
1177 runningTurnId={turnId}
1178 timelineEntries={[
1179 {
1180 id: "entry-failed",
1181 kind: "work",
1182 createdAt: MESSAGE_CREATED_AT,
1183 entry: {
1184 id: "work-failed",
1185 createdAt: MESSAGE_CREATED_AT,
1186 turnId,
1187 toolCallId: "call-failed",
1188 label: "Run lint",
1189 tone: "tool",
1190 itemType: "command_execution",
1191 command: "pnpm lint",
1192 toolLifecycleStatus: "failed",
1193 },
1194 },
1195 ]}
1196 />,
1197 );
1198
1199 expect(markup).toContain("Running pnpm");
1200 expect(markup).toContain("tool call failed");
1201 });
1202
1203 it("aligns the iconless Thinking row with the working timer", () => {
1204 const markup = renderToStaticMarkup(
1205 <MessagesTimeline
1206 {...buildProps()}
1207 isWorking
1208 activeTurnStartedAt={MESSAGE_CREATED_AT}
1209 timelineEntries={[]}
1210 />,
1211 );
1212
1213 expect(markup).toContain("Working for");
1214 expect(markup).toContain("Thinking");
1215 expect(markup).toContain("gap-1.5 py-0.5 px-1");
1216 });
1217
1218 it("renders review comment contexts as structured cards instead of raw tags", () => {
1219 const markup = renderToStaticMarkup(
1220 <MessagesTimeline
1221 {...buildProps()}
1222 timelineEntries={[
1223 {
1224 id: "entry-1",
1225 kind: "message",
1226 createdAt: "2026-03-17T19:12:28.000Z",
1227 message: {
1228 id: MessageId.make("message-2"),
1229 role: "user",
1230 text: [
1231 '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
1232 "Wadduo",
1233 "```diff",
1234 "@@ -0,0 +47,2 @@",
1235 '+ it("keeps valid zero-usage snapshots", () => {',
1236 "+ expect(snapshot).not.toBeNull();",
1237 "```",
1238 "</review_comment>",
1239 ].join("\n"),
1240 turnId: null,
1241 createdAt: "2026-03-17T19:12:28.000Z",
1242 updatedAt: "2026-03-17T19:12:28.000Z",
1243 streaming: false,
1244 },
1245 },
1246 ]}
1247 />,
1248 );
1249
1250 expect(markup).toContain("contextWindow.test.ts");
1251 expect(markup).toContain("Wadduo");
1252 expect(markup).toContain('data-testid="file-diff"');
1253 expect(markup).not.toContain(">Review comment<");
1254 expect(markup).not.toContain("<review_comment");
1255 expect(markup).not.toContain("</review_comment>");
1256 });
1257
1258 it("renders file review comments as source code instead of diffs", () => {
1259 const markup = renderToStaticMarkup(
1260 <MessagesTimeline
1261 {...buildProps()}
1262 timelineEntries={[
1263 {
1264 id: "entry-1",
1265 kind: "message",
1266 createdAt: "2026-03-17T19:12:28.000Z",
1267 message: {
1268 id: MessageId.make("message-source-comment"),
1269 role: "user",
1270 text: [
1271 '<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
1272 "Clarify this.",
1273 "```md",
1274 "# Plan",
1275 "- Step one",
1276 "```",
1277 "</review_comment>",
1278 ].join("\n"),
1279 turnId: null,
1280 createdAt: "2026-03-17T19:12:28.000Z",
1281 updatedAt: "2026-03-17T19:12:28.000Z",
1282 streaming: false,
1283 },
1284 },
1285 ]}
1286 />,
1287 );
1288
1289 expect(markup).toContain("plan.md");
1290 expect(markup).toContain("Clarify this.");
1291 expect(markup).toContain("# Plan");
1292 expect(markup).not.toContain('data-testid="file-diff"');
1293 });
1294
1295 it("renders a muted failure marker for failed tool lifecycle entries", () => {
1296 const markup = renderToStaticMarkup(
1297 <MessagesTimeline
1298 {...buildProps()}
1299 timelineEntries={[
1300 {
1301 id: "entry-info",
1302 kind: "work",
1303 createdAt: "2026-03-17T19:12:27.000Z",
1304 entry: {
1305 id: "work-info",
1306 createdAt: "2026-03-17T19:12:27.000Z",
1307 label: "Status updated",
1308 tone: "info",
1309 },
1310 },
1311 {
1312 id: "entry-1",
1313 kind: "work",
1314 createdAt: "2026-03-17T19:12:28.000Z",
1315 entry: {
1316 id: "work-1",
1317 createdAt: "2026-03-17T19:12:28.000Z",
1318 label: "Glob",
1319 tone: "tool",
1320 toolLifecycleStatus: "failed",
1321 detail: "No files found",
1322 },
1323 },
1324 ]}
1325 />,
1326 );
1327
1328 expect(markup).toContain("lucide-x");
1329 expect(markup).toContain('aria-label="Tool call failed"');
1330 // Ordinary tool failures render muted, not red.
1331 expect(markup).not.toContain("text-destructive");
1332 });
1333
1334 it("keeps the red treatment for severe orchestration failures", () => {
1335 const markup = renderToStaticMarkup(
1336 <MessagesTimeline
1337 {...buildProps()}
1338 timelineEntries={[
1339 {
1340 id: "entry-info",
1341 kind: "work",
1342 createdAt: "2026-03-17T19:12:27.000Z",
1343 entry: {
1344 id: "work-info",
1345 createdAt: "2026-03-17T19:12:27.000Z",
1346 label: "Status updated",
1347 tone: "info",
1348 },
1349 },
1350 {
1351 id: "entry-turn-failed",
1352 kind: "work",
1353 createdAt: "2026-03-17T19:12:28.000Z",
1354 entry: {
1355 id: "work-turn-failed",
1356 createdAt: "2026-03-17T19:12:28.000Z",
1357 label: "Provider turn start failed",
1358 tone: "error",
1359 sourceActivityKind: "provider.turn.start.failed",
1360 },
1361 },
1362 ]}
1363 />,
1364 );
1365
1366 expect(markup).toContain("lucide-x");
1367 expect(markup).toContain("text-destructive");
1368 });
1369});