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

MessagesTimeline.test.tsx

1,277 lines41.2 KB

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 );
124​
125vi.mock("@pierre/diffs/react", () => {
126 return { FileDiff: MockFileDiff };
127});
128​
129function matchMedia() {
130 return {
131 matches: false,
132 addEventListener: () => {},
133 removeEventListener: () => {},
134 };
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 };
204​
205function buildLongUserMessageText(tail = "deep hidden detail only after expand") {
206 return Array.from({ length: 9 }, (_, index) =>
207 index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`,
208 ).join("\n");
210​
211function buildUserTimelineEntry(text: string) {
212 return {
213 id: "entry-1",
214 kind: "message" as const,
215 createdAt: MESSAGE_CREATED_AT,
216 message: {
217 id: MessageId.make("message-1"),
218 role: "user" as const,
219 text,
220 turnId: null,
221 createdAt: MESSAGE_CREATED_AT,
222 updatedAt: MESSAGE_CREATED_AT,
223 streaming: false,
224 },
225 };
227​
228function buildAssistantTimelineEntry(text: string) {
229 const entry = buildUserTimelineEntry(text);
230 return {
231 ...entry,
232 message: {
233 ...entry.message,
234 role: "assistant" as const,
235 },
236 };
238​
239describe("MessagesTimeline", () => {
240 it("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("&lt;global-agent-instructions scope=&quot;workspace&quot;&gt;");
705 expect(markup).toContain(
706 "Before &lt;nested data-value=&quot;a&amp;b&quot;&gt;inside&lt;/nested&gt; after",
707 );
708 expect(markup).toContain("&lt;/global-agent-instructions&gt; in your context?");
709 expect(markup).toContain("Comparison: 2 &lt; 3 and 5 &gt; 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="">&lt;tag attr=&quot;x&quot;&gt;</code>');
732 expect(markup).toContain("&lt;root&gt;&lt;child enabled=&quot;true&quot; /&gt;&lt;/root&gt;");
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") ![image](https://example.com/image.png "image 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("&lt;script&gt;globalThis.__t3Xss = 1&lt;/script&gt;");
768 expect(markup).toContain(
769 "&lt;img src=&quot;x&quot; onerror=&quot;globalThis.__t3Xss = 2&quot;&gt;",
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("&lt;details&gt;");
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&#x27;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("&lt;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 mixed work logs neutral after a later tool call succeeds", () => {
977 const markup = renderToStaticMarkup(
978 <MessagesTimeline
979 {...buildProps()}
980 timelineEntries={[
981 {
982 id: "entry-failed",
983 kind: "work",
984 createdAt: "2026-03-17T19:12:28.000Z",
985 entry: {
986 id: "work-failed",
987 createdAt: "2026-03-17T19:12:28.000Z",
988 label: "Run search",
989 tone: "tool",
990 itemType: "command_execution",
991 toolLifecycleStatus: "failed",
992 },
993 },
994 {
995 id: "entry-info",
996 kind: "work",
997 createdAt: "2026-03-17T19:12:29.000Z",
998 entry: {
999 id: "work-info",
1000 createdAt: "2026-03-17T19:12:29.000Z",
1001 label: "Status updated",
1002 tone: "info",
1003 },
1004 },
1006 id: "entry-completed",
1007 kind: "work",
1008 createdAt: "2026-03-17T19:12:30.000Z",
1009 entry: {
1010 id: "work-completed",
1011 createdAt: "2026-03-17T19:12:30.000Z",
1012 label: "Run tests",
1013 tone: "tool",
1014 itemType: "command_execution",
1015 toolLifecycleStatus: "completed",
1016 },
1017 },
1018 ]}
1019 />,
1020 );
1021​
1022 expect(markup).toContain("+2 previous log entries");
1023 expect(markup).not.toContain('aria-label="Hidden work includes a failure"');
1024 });
1025​
1026 it("shows the animated one-line label for a live tool group", () => {
1027 const turnId = TurnId.make("turn-live");
1028 const markup = renderToStaticMarkup(
1029 <MessagesTimeline
1030 {...buildProps()}
1031 isWorking
1032 activeTurnStartedAt={MESSAGE_CREATED_AT}
1033 latestTurn={{
1034 turnId,
1035 state: "running",
1036 startedAt: MESSAGE_CREATED_AT,
1037 completedAt: null,
1038 }}
1039 runningTurnId={turnId}
1040 timelineEntries={[
1042 id: "entry-live",
1043 kind: "work",
1044 createdAt: MESSAGE_CREATED_AT,
1045 entry: {
1046 id: "work-live",
1047 createdAt: MESSAGE_CREATED_AT,
1048 turnId,
1049 toolCallId: "call-live",
1050 label: "Run tests",
1051 tone: "tool",
1052 itemType: "command_execution",
1053 command: "pnpm test",
1054 toolLifecycleStatus: "inProgress",
1055 },
1056 },
1057 ]}
1058 />,
1059 );
1060​
1061 expect(markup).toContain("Working for");
1062 expect(markup).toContain("Running pnpm");
1063 expect(markup).toContain("live-activity-focus");
1064 });
1065​
1066 it("scopes a live row failure to the tool named by the row", () => {
1067 const turnId = TurnId.make("turn-live");
1068 const markup = renderToStaticMarkup(
1069 <MessagesTimeline
1070 {...buildProps()}
1071 isWorking
1072 activeTurnStartedAt={MESSAGE_CREATED_AT}
1073 latestTurn={{
1074 turnId,
1075 state: "running",
1076 startedAt: MESSAGE_CREATED_AT,
1077 completedAt: null,
1078 }}
1079 runningTurnId={turnId}
1080 timelineEntries={[
1082 id: "entry-failed",
1083 kind: "work",
1084 createdAt: MESSAGE_CREATED_AT,
1085 entry: {
1086 id: "work-failed",
1087 createdAt: MESSAGE_CREATED_AT,
1088 turnId,
1089 toolCallId: "call-failed",
1090 label: "Run lint",
1091 tone: "tool",
1092 itemType: "command_execution",
1093 command: "pnpm lint",
1094 toolLifecycleStatus: "failed",
1095 },
1096 },
1098 id: "entry-running",
1099 kind: "work",
1100 createdAt: MESSAGE_CREATED_AT,
1101 entry: {
1102 id: "work-running",
1103 createdAt: MESSAGE_CREATED_AT,
1104 turnId,
1105 toolCallId: "call-running",
1106 label: "Run tests",
1107 tone: "tool",
1108 itemType: "command_execution",
1109 command: "pnpm test",
1110 toolLifecycleStatus: "inProgress",
1111 },
1112 },
1113 ]}
1114 />,
1115 );
1116​
1117 expect(markup).toContain("Running pnpm");
1118 expect(markup).not.toContain("tool call failed");
1119 });
1120​
1121 it("keeps terminal command copy live while the parent turn is active", () => {
1122 const turnId = TurnId.make("turn-live");
1123 const markup = renderToStaticMarkup(
1124 <MessagesTimeline
1125 {...buildProps()}
1126 isWorking
1127 activeTurnStartedAt={MESSAGE_CREATED_AT}
1128 latestTurn={{
1129 turnId,
1130 state: "running",
1131 startedAt: MESSAGE_CREATED_AT,
1132 completedAt: null,
1133 }}
1134 runningTurnId={turnId}
1135 timelineEntries={[
1137 id: "entry-failed",
1138 kind: "work",
1139 createdAt: MESSAGE_CREATED_AT,
1140 entry: {
1141 id: "work-failed",
1142 createdAt: MESSAGE_CREATED_AT,
1143 turnId,
1144 toolCallId: "call-failed",
1145 label: "Run lint",
1146 tone: "tool",
1147 itemType: "command_execution",
1148 command: "pnpm lint",
1149 toolLifecycleStatus: "failed",
1150 },
1151 },
1152 ]}
1153 />,
1154 );
1155​
1156 expect(markup).toContain("Running pnpm");
1157 expect(markup).toContain("tool call failed");
1158 });
1159​
1160 it("aligns the iconless Thinking row with the working timer", () => {
1161 const markup = renderToStaticMarkup(
1162 <MessagesTimeline
1163 {...buildProps()}
1164 isWorking
1165 activeTurnStartedAt={MESSAGE_CREATED_AT}
1166 timelineEntries={[]}
1167 />,
1168 );
1169​
1170 expect(markup).toContain("Working for");
1171 expect(markup).toContain("Thinking");
1172 expect(markup).toContain("gap-1.5 py-0.5 px-1");
1173 });
1174​
1175 it("renders review comment contexts as structured cards instead of raw tags", () => {
1176 const markup = renderToStaticMarkup(
1177 <MessagesTimeline
1178 {...buildProps()}
1179 timelineEntries={[
1181 id: "entry-1",
1182 kind: "message",
1183 createdAt: "2026-03-17T19:12:28.000Z",
1184 message: {
1185 id: MessageId.make("message-2"),
1186 role: "user",
1187 text: [
1188 '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
1189 "Wadduo",
1190 "```diff",
1191 "@@ -0,0 +47,2 @@",
1192 '+ it("keeps valid zero-usage snapshots", () => {',
1193 "+ expect(snapshot).not.toBeNull();",
1194 "```",
1195 "</review_comment>",
1196 ].join("\n"),
1197 turnId: null,
1198 createdAt: "2026-03-17T19:12:28.000Z",
1199 updatedAt: "2026-03-17T19:12:28.000Z",
1200 streaming: false,
1201 },
1202 },
1203 ]}
1204 />,
1205 );
1206​
1207 expect(markup).toContain("contextWindow.test.ts");
1208 expect(markup).toContain("Wadduo");
1209 expect(markup).toContain('data-testid="file-diff"');
1210 expect(markup).not.toContain(">Review comment<");
1211 expect(markup).not.toContain("&lt;review_comment");
1212 expect(markup).not.toContain("&lt;/review_comment&gt;");
1213 });
1214​
1215 it("renders file review comments as source code instead of diffs", () => {
1216 const markup = renderToStaticMarkup(
1217 <MessagesTimeline
1218 {...buildProps()}
1219 timelineEntries={[
1221 id: "entry-1",
1222 kind: "message",
1223 createdAt: "2026-03-17T19:12:28.000Z",
1224 message: {
1225 id: MessageId.make("message-source-comment"),
1226 role: "user",
1227 text: [
1228 '<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
1229 "Clarify this.",
1230 "```md",
1231 "# Plan",
1232 "- Step one",
1233 "```",
1234 "</review_comment>",
1235 ].join("\n"),
1236 turnId: null,
1237 createdAt: "2026-03-17T19:12:28.000Z",
1238 updatedAt: "2026-03-17T19:12:28.000Z",
1239 streaming: false,
1240 },
1241 },
1242 ]}
1243 />,
1244 );
1245​
1246 expect(markup).toContain("plan.md");
1247 expect(markup).toContain("Clarify this.");
1248 expect(markup).toContain("# Plan");
1249 expect(markup).not.toContain('data-testid="file-diff"');
1250 });
1251​
1252 it("renders a failure marker for failed tool lifecycle entries", () => {
1253 const markup = renderToStaticMarkup(
1254 <MessagesTimeline
1255 {...buildProps()}
1256 timelineEntries={[
1258 id: "entry-1",
1259 kind: "work",
1260 createdAt: "2026-03-17T19:12:28.000Z",
1261 entry: {
1262 id: "work-1",
1263 createdAt: "2026-03-17T19:12:28.000Z",
1264 label: "Glob",
1265 tone: "tool",
1266 toolLifecycleStatus: "failed",
1267 detail: "No files found",
1268 },
1269 },
1270 ]}
1271 />,
1272 );
1273​
1274 expect(markup).toContain("lucide-x");
1275 expect(markup).toContain('aria-label="Tool call failed"');
1276 });
1277});