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