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

MessagesTimeline.browser.test.tsx

1,304 lines44.5 KB

1import { RegistryProvider } from "@effect/atom-react";
2import {
3 ApprovalRequestId,
4 CheckpointRef,
5 EnvironmentId,
6 MessageId,
7 RunId,
8 ThreadId,
9} from "@t3tools/contracts";
10import type { LegendListRef } from "@legendapp/list/react";
11import { act, createRef, Profiler, useState, type ComponentProps, type ReactElement } from "react";
12import { createRoot, type Root } from "react-dom/client";
13import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
14import { userEvent } from "vite-plus/test/browser";
15​
16import "~/index.css";
17​
18import { serverEnvironment } from "../../state/server";
19import { PullRequestLinkPreview } from "../pullRequest/PullRequestLinkPreview";
20import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "../ui/tooltip";
21import { MessagesTimeline } from "./MessagesTimeline";
22import { readTimelinePosition } from "./timelineScrollAnchoring";
23import { useComposerFocusState } from "./useComposerFocusState";
24​
25const pullRequestQuery = vi.hoisted(() => ({ error: "Pull request not found" }));
26vi.mock(import("~/state/query"), async (original) => ({
27 ...(await original()),
28 useEnvironmentQuery: (() => ({
29 data: null,
30 dataUpdatedAt: 0,
31 error: pullRequestQuery.error,
32 failure: null,
33 isPending: false,
34 isSuccess: false,
35 refresh: () => {},
36 })) as never,
37}));
38​
39const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
40const CREATED_AT = "2026-03-17T19:12:28.000Z";
41​
42type TimelineProps = ComponentProps<typeof MessagesTimeline>;
43type Entry = TimelineProps["timelineEntries"][number];
44​
45// The timeline remembers scroll position and open disclosures per thread key,
46// so every render gets a fresh thread.
47let threadCount = 0;
48​
49function baseProps(): Omit<TimelineProps, "timelineEntries"> {
50 threadCount += 1;
51 return {
52 isWorking: false,
53 activeTurnInProgress: false,
54 listRef: createRef<LegendListRef | null>(),
55 latestRun: null,
56 turnDiffSummaries: [],
57 runs: [],
58 routeThreadKey: `environment-local:thread-${threadCount}`,
59 onOpenTurnDiff: () => {},
60 onOpenThread: () => {},
61 onForkFromRun: async () => {},
62 onRollbackCheckpoint: () => {},
63 supportsConversationRollback: false,
64 onRevertToTurnCount: () => {},
65 isRevertingCheckpoint: false,
66 onImageExpand: () => {},
67 activeThreadEnvironmentId: ENVIRONMENT_ID,
68 markdownCwd: undefined,
69 resolvedTheme: "light",
70 timestampFormat: "locale",
71 workspaceRoot: undefined,
72 anchorMessageId: null,
73 onAnchorReady: () => {},
74 onAnchorSizeChanged: () => {},
75 contentInsetEndAdjustment: 0,
76 liveFollowEnabled: true,
77 onIsAtEndChange: () => {},
78 onManualNavigation: () => {},
79 };
81​
82function message(
83 text: string,
84 overrides: Partial<Extract<Entry, { kind: "message" }>["message"]> = {},
85 id = "message-1",
86): Entry {
87 return {
88 id: `entry-${id}`,
89 kind: "message",
90 createdAt: CREATED_AT,
91 message: {
92 id: MessageId.make(id),
93 role: "user",
94 text,
95 runId: null,
96 createdAt: CREATED_AT,
97 updatedAt: CREATED_AT,
98 streaming: false,
99 ...overrides,
100 },
101 };
103​
104function work(id: string, entry: Record<string, unknown>): Entry {
105 return {
106 id,
107 kind: "work",
108 createdAt: CREATED_AT,
109 entry: { id, createdAt: CREATED_AT, ...entry },
110 } as Entry;
112​
113function v2Item(type: string, fields: Record<string, unknown>) {
114 const id = (fields.id as string | undefined) ?? type;
115 return {
116 position: 0,
117 visibility: "local",
118 sourceThreadId: "thread-1",
119 sourceItemId: id,
120 item: {
121 id,
122 threadId: "thread-1",
123 runId: "run-1",
124 nodeId: null,
125 providerThreadId: null,
126 providerTurnId: null,
127 nativeItemRef: null,
128 parentItemId: null,
129 ordinal: 0,
130 status: "completed",
131 title: null,
132 startedAt: null,
133 completedAt: null,
134 updatedAt: {},
135 type,
136 ...fields,
137 },
138 } as never;
140​
141function longText(tail = "deep hidden detail only after expand") {
142 return Array.from({ length: 9 }, (_, index) =>
143 index === 8 ? tail : `Line ${index + 1}: ${"verbose prompt content ".repeat(8).trim()}`,
144 ).join("\n");
146​
147const roots: Root[] = [];
148let container: HTMLDivElement;
149​
150beforeEach(() => {
151 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
152});
153​
154afterEach(async () => {
155 for (const root of roots.splice(0)) await act(async () => root.unmount());
156 document.body.replaceChildren();
157 vi.unstubAllGlobals();
158});
159​
160async function renderElement(element: ReactElement) {
161 container = document.body.appendChild(document.createElement("div"));
162 container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
163 const root = createRoot(container);
164 roots.push(root);
165 await act(async () => root.render(element));
166 return container;
168​
169function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelineProps> = {}) {
170 return renderElement(
171 <MessagesTimeline {...baseProps()} timelineEntries={entries as Entry[]} {...props} />,
172 );
174​
175function text() {
176 return container.textContent ?? "";
178​
179function buttons(name: string | RegExp) {
180 return [...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => {
181 const label = button.getAttribute("aria-label") ?? button.textContent ?? "";
182 return typeof name === "string" ? label === name : name.test(label);
183 });
185​
186function button(name: string | RegExp) {
187 const [match] = buttons(name);
188 if (!match) throw new Error(`Missing button: ${String(name)}`);
189 return match;
191​
192async function click(element: HTMLElement) {
193 await act(async () => element.click());
195​
196describe("MessagesTimeline work rows", () => {
197 it("shows dynamic tool input without cached output when the row is expanded", async () => {
198 await renderTimeline([
199 work("tool-with-cached-output", {
200 label: "Example tool",
201 toolTitle: "Example tool",
202 tone: "tool",
203 itemType: "dynamic_tool",
204 toolLifecycleStatus: "completed",
205 toolData: {
206 input: { query: "KEEP_TOOL_INPUT" },
207 output: { text: "RAW_CACHED_TOOL_OUTPUT" },
208 },
209 }),
210 ]);
211 await click(button("Example tool"));
212 expect(text()).toContain("KEEP_TOOL_INPUT");
213 expect(text()).not.toContain("RAW_CACHED_TOOL_OUTPUT");
214 await click(button("Example tool"));
215 await vi.waitFor(() => expect(text()).not.toContain("KEEP_TOOL_INPUT"));
216 });
217​
218 it("expands and collapses a tool call through its header", async () => {
219 await renderTimeline([
220 work("work-standalone", {
221 toolCallId: "call-standalone",
222 label: "Run lint",
223 tone: "tool",
224 itemType: "command_execution",
225 command: "pnpm lint",
226 toolLifecycleStatus: "completed",
227 }),
228 ]);
229 const header = () => container.querySelector<HTMLElement>("[aria-expanded]")!;
230 expect(header().getAttribute("aria-expanded")).toBe("false");
231 await click(header());
232 expect(header().getAttribute("aria-expanded")).toBe("true");
233 await click(header());
234 expect(header().getAttribute("aria-expanded")).toBe("false");
235 });
236​
237 it("leads an unanswered question row with the question text", async () => {
238 await renderTimeline([
239 work("question-work", {
240 label: "User input requested",
241 tone: "tool",
242 questionAnswer: {
243 requestId: ApprovalRequestId.make("question-request"),
244 answers: {},
245 questionTextById: { scope: "Which repository?" },
246 attachmentsByQuestionId: {},
247 },
248 }),
249 ]);
250 const toggle = button("Which repository?");
251 expect(toggle.getAttribute("aria-expanded")).toBe("false");
252 const before = text().match(/Which repository\?/g)?.length ?? 0;
253 expect(before).toBeGreaterThan(0);
254 await click(toggle);
255 expect(text().match(/Which repository\?/g)?.length).toBe(before + 1);
256 });
257​
258 it("collapses settled tool runs behind a generated summary and names a failure", async () => {
259 await renderTimeline([
260 work("work-1", {
261 label: "Ran command",
262 command: "vp lint",
263 tone: "tool",
264 itemType: "command_execution",
265 toolLifecycleStatus: "completed",
266 }),
267 work("work-2", {
268 label: "Run lint",
269 command: "vp test run",
270 tone: "tool",
271 itemType: "command_execution",
272 toolLifecycleStatus: "failed",
273 }),
274 ]);
275 const summary = button(/^Ran 2 commands/);
276 expect(summary.getAttribute("aria-label")).toContain("tool call failed");
277 expect(text()).not.toContain("vp lint");
278 await click(summary);
279 await vi.waitFor(() => expect(text()).toContain("vp lint"));
280 });
281​
282 it("keeps mixed work logs neutral after a later tool call succeeds", async () => {
283 await renderTimeline([
284 work("work-failed", {
285 label: "Run search",
286 tone: "tool",
287 itemType: "command_execution",
288 toolLifecycleStatus: "failed",
289 }),
290 work("work-info", { label: "Status updated", tone: "info" }),
291 work("work-completed", {
292 label: "Run tests",
293 tone: "tool",
294 itemType: "command_execution",
295 toolLifecycleStatus: "completed",
296 }),
297 ]);
298 expect(button("Ran 2 commands and received 1 update")).toBeDefined();
299 });
300​
301 it("marks a failed tool inside an expanded work log", async () => {
302 await renderTimeline([
303 work("work-info", { label: "Status updated", tone: "info" }),
304 work("work-1", {
305 label: "Glob",
306 tone: "tool",
307 toolLifecycleStatus: "failed",
308 detail: "No files found",
309 }),
310 ]);
311 await click(button(/^Received 1 update/));
312 await vi.waitFor(() =>
313 expect(container.querySelector('[aria-label="Tool call failed"]')).not.toBeNull(),
314 );
315 });
316​
317 it("renders context compaction entries in the normal work log", async () => {
318 await renderTimeline([work("work-1", { label: "Context compacted", tone: "info" })]);
319 expect(text()).toContain("Context compacted");
320 });
321​
322 it("formats changed file paths from the workspace root", async () => {
323 await renderTimeline(
324 [
325 work("context-info", { label: "Session started", tone: "info" }),
326 work("work-1", {
327 label: "Updated files",
328 tone: "tool",
329 itemType: "file_change",
330 toolLifecycleStatus: "completed",
331 changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
332 }),
333 ],
334 { workspaceRoot: "C:/Users/mike/dev-stuff/t3code" },
335 );
336 await click(button(/^Received 1 update/));
337 await vi.waitFor(() => expect(text()).toContain("t3code/apps/web/src/session-logic.ts"));
338 expect(text()).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
339 });
340​
341 it("renders T3 MCP dynamic tools with their pretty name", async () => {
342 const item = {
343 id: "tool-t3-thread-read",
344 type: "dynamic_tool",
345 toolName: "mcp__t3-code__t3_thread_read",
346 input: { threadId: "thread-child" },
347 output: { messages: [] },
348 };
349 await renderTimeline([
350 work("context-info", { label: "Session started", tone: "info" }),
351 work(item.id, {
352 runId: null,
353 label: item.toolName,
354 tone: "tool",
355 itemType: item.type,
356 toolTitle: item.toolName,
357 toolLifecycleStatus: "completed",
358 toolData: { input: item.input, output: item.output },
359 structuredPayload: v2Item("dynamic_tool", item),
360 projectedItem: v2Item("dynamic_tool", item),
361 }),
362 ]);
363 await click(button(/^Received 1 update/));
364 await vi.waitFor(() => expect(text()).toContain("Read a T3 thread"));
365 expect(text()).not.toContain("mcp__t3-code__t3_thread_read");
366 });
367​
368 it("keeps a provider retry collapsed in the work log", async () => {
369 const retryItem = {
370 id: "provider-error",
371 status: "running",
372 title: "Provider retry",
373 failure: {
374 class: "transport_error",
375 message: "The response stream disconnected.",
376 code: "responseStreamDisconnected",
377 retryable: true,
378 },
379 retry: { attempt: 2, maxAttempts: 5, retryDelayMs: null },
380 };
381 await renderTimeline(
382 [
383 work("provider-error", {
384 runId: "run-1",
385 label: "Retrying provider (2/5)",
386 detail: retryItem.failure.message,
387 tone: "info",
388 itemType: "error",
389 toolLifecycleStatus: "inProgress",
390 projectedItem: v2Item("error", retryItem),
391 }),
392 ],
393 {
394 isWorking: true,
395 activeTurnInProgress: true,
396 latestRun: {
397 runId: RunId.make("run-1"),
398 status: "running",
399 startedAt: CREATED_AT,
400 completedAt: null,
401 },
402 },
403 );
404 expect(text()).toContain("Retrying provider (2/5)");
405 expect(text()).not.toContain("Structured details");
406 });
407​
408 it.each([
409 [
410 "**Viewing image first** with *care*, ~~old~~ `code` and [context](https://example.com)",
411 "Viewing image first with care, old code and context",
412 1,
413 ],
414 ["first paragraph\n\nsecond paragraph", "first paragraph second paragraph", 0],
415 ["- first\n- second", "first second", 0],
416 ["first \nsecond", "first second", 0],
417 ["![image description](image.png)", "image description", 0],
418 ["![](image.png)", "Thought", 0],
419 ["---", "Thought", 0],
420 ] as const)(
421 "shows plain text for a V2 reasoning preview: %s",
422 async (markdown, expected, strongCount) => {
423 await renderTimeline([
424 work("reasoning-preview", {
425 label: markdown,
426 detail: markdown,
427 tone: "thinking",
428 itemType: "reasoning",
429 toolLifecycleStatus: "completed",
430 }),
431 ]);
432 const row = () => container.querySelector<HTMLElement>("[role=button][aria-expanded]")!;
433 const preview = () => row().textContent!.replace(/\s+/g, " ");
434 expect(preview()).toContain(expected);
435 expect(container.querySelectorAll("strong")).toHaveLength(0);
436 await click(row());
437 expect(container.querySelectorAll("strong")).toHaveLength(strongCount);
438 await click(row());
439 expect(preview()).toContain(expected);
440 await vi.waitFor(() => expect(container.querySelectorAll("strong")).toHaveLength(0));
441 },
442 );
443});
444​
445describe("MessagesTimeline messages", () => {
446 it("preserves XML-like tags and comparisons in user messages as text", async () => {
447 const source = [
448 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
449 'Before <nested data-value="a&b">inside</nested> after',
450 "</global-agent-instructions> in your context?",
451 "Comparison: 2 < 3 and 5 > 4.",
452 ];
453 await renderTimeline([message(source.join("\n"))]);
454 for (const line of source) expect(text()).toContain(line);
455 expect(container.querySelector("global-agent-instructions, nested")).toBeNull();
456 });
457​
458 it("preserves XML-like source inside user code spans and fences", async () => {
459 await renderTimeline([
460 message(
461 [
462 'Inline `<tag attr="x">`',
463 "",
464 "```xml",
465 '<root><child enabled="true" /></root>',
466 "```",
467 ].join("\n"),
468 ),
469 ]);
470 expect(container.querySelector("code[data-inline-code]")?.textContent).toBe('<tag attr="x">');
471 expect(text()).toContain('<root><child enabled="true" /></root>');
472 });
473​
474 it("does not show markdown titles in user messages", async () => {
475 await renderTimeline([
476 message(
477 '[link](https://example.com "link tip") ![image](https://example.com/image.png "image tip")',
478 ),
479 ]);
480 expect(container.querySelector('a[href="https://example.com"]')).not.toBeNull();
481 expect(container.querySelector('img[src="https://example.com/image.png"]')).not.toBeNull();
482 expect(container.querySelector('[title="link tip"], [title="image tip"]')).toBeNull();
483 });
484​
485 it("renders unsafe user HTML as inert source text", async () => {
486 const source =
487 '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">';
488 await renderTimeline([message(source)]);
489 expect(text()).toContain(source);
490 expect(container.querySelector("script, img")).toBeNull();
491 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
492 });
493​
494 it("renders sanitized raw HTML in assistant messages", async () => {
495 await renderTimeline([
496 message(
497 [
498 '<details onclick="globalThis.__t3Xss = 1">',
499 "<summary>Safe details</summary>",
500 "<script>globalThis.__t3Xss = 2</script>",
501 '<img src="x" onerror="globalThis.__t3Xss = 3">',
502 '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
503 "</details>",
504 ].join(""),
505 { role: "assistant" },
506 ),
507 ]);
508 expect(container.querySelector("[data-markdown-details]")?.textContent).toContain(
509 "Safe details",
510 );
511 expect(text()).not.toContain("<details");
512 expect(container.querySelector("script, [onclick], [onerror]")).toBeNull();
513 expect(container.innerHTML).not.toContain("javascript:");
514 await click(button("Safe details"));
515 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
516 });
517​
518 it("collapses long user messages behind a toggle and keeps their copy button", async () => {
519 await renderTimeline([message(longText())]);
520 const toggle = button("Show full message");
521 expect(toggle.getAttribute("aria-expanded")).toBe("false");
522 expect(buttons("Copy message")).toHaveLength(1);
523 await click(toggle);
524 expect(button("Show less").getAttribute("aria-expanded")).toBe("true");
525 });
526​
527 it("does not offer a collapse toggle for short user messages", async () => {
528 await renderTimeline([message("Short prompt.")]);
529 expect(buttons(/Show full message|Show less/)).toHaveLength(0);
530 });
531​
532 it("identifies user-role messages sent by another agent", async () => {
533 await renderTimeline([
534 message("Review this area", { createdBy: "agent", creationSource: "provider" }),
535 ]);
536 expect(text()).toContain("Sent by another agent");
537 await act(async () => roots.pop()!.unmount());
538 await renderTimeline([message("Review this area")]);
539 expect(text()).not.toContain("Sent by another agent");
540 });
541​
542 it("shows steer intent ahead of committed user messages", async () => {
543 await renderTimeline([message("Adjust the current turn", { inputIntent: "steer" })]);
544 expect(text().indexOf("Steer")).toBeGreaterThanOrEqual(0);
545 expect(text().indexOf("Steer")).toBeLessThan(text().indexOf("Adjust the current turn"));
546 });
547​
548 it("renders inline terminal labels as chips", async () => {
549 await renderTimeline([
550 message(
551 [
552 longText("yoo what's @terminal-1:1-5 mean"),
553 "",
554 "<terminal_context>",
555 "- Terminal 1 lines 1-5:",
556 " 1 | julius@mac effect-http-ws-cli % bun i",
557 " 2 | bun install v1.3.9 (cf6cdbbb)",
558 "</terminal_context>",
559 ].join("\n"),
560 ),
561 ]);
562 expect(text()).toContain("Terminal 1 lines 1-5");
563 expect(text()).toContain("yoo what's");
564 expect(text()).not.toContain("terminal_context");
565 expect(buttons("Show full message")).toHaveLength(1);
566 });
567​
568 it("renders chips for standalone element-pick context messages", async () => {
569 await renderTimeline([
570 message(
571 [
572 "<element_context>",
573 "- <SubmitButton> (Button.tsx:12):",
574 " url: https://example.com/dashboard",
575 " selector: button.submit",
576 " source: /repo/src/Button.tsx:12:5",
577 " html:",
578 ' <button class="submit">Save</button>',
579 "</element_context>",
580 ].join("\n"),
581 ),
582 ]);
583 expect(text()).toContain("SubmitButton");
584 expect(text()).not.toContain("element_context");
585 });
586​
587 it("renders review comment contexts as structured cards instead of raw tags", async () => {
588 await renderTimeline([
589 message(
590 [
591 '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
592 "Wadduo",
593 "```diff",
594 "@@ -0,0 +47,2 @@",
595 '+ it("keeps valid zero-usage snapshots", () => {',
596 "+ expect(snapshot).not.toBeNull();",
597 "```",
598 "</review_comment>",
599 ].join("\n"),
600 ),
601 ]);
602 expect(text()).toContain("contextWindow.test.ts L47 to L58");
603 expect(text()).not.toContain("review_comment");
604 });
605​
606 it("renders file review comments as source code", async () => {
607 await renderTimeline([
608 message(
609 [
610 '<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
611 "Clarify this.",
612 "```md",
613 "# Plan",
614 "- Step one",
615 "```",
616 "</review_comment>",
617 ].join("\n"),
618 ),
619 ]);
620 expect(text()).toContain("plan.md L1 to L2");
621 expect(text()).not.toContain("review_comment");
622 });
623​
624 it("collapses superseded attempt output behind a disclosure", async () => {
625 const runId = RunId.make("run-steered");
626 const attempt = (id: string, ordinal: number, status: string) =>
627 ({
628 id,
629 runId,
630 attemptOrdinal: ordinal,
631 rootNodeId: `node-${id}`,
632 status,
633 completedAt: null,
634 }) as never;
635 await renderTimeline(
636 [
637 {
638 ...message(
639 "Partial response from the old attempt",
640 { role: "assistant", runId },
641 "superseded-response",
642 ),
643 attempt: attempt("attempt-1", 1, "superseded"),
644 } as Entry,
645 {
646 ...message(
647 "Current response remains visible",
648 { role: "assistant", runId, streaming: true },
649 "active-response",
650 ),
651 attempt: attempt("attempt-2", 2, "running"),
652 } as Entry,
653 ],
654 {
655 latestRun: { runId, status: "running", startedAt: CREATED_AT, completedAt: null },
656 },
657 );
658 expect(text()).toContain("Current response remains visible");
659 expect(text()).not.toContain("Partial response from the old attempt");
660 const disclosure = button(/Superseded attempt/);
661 expect(disclosure.textContent).toContain("Cut off by a steer");
662 await click(disclosure);
663 expect(text()).toContain("Partial response from the old attempt");
664 });
665​
666 it("forks from a completed assistant response", async () => {
667 const onForkFromRun = vi.fn(async () => {});
668 await renderTimeline(
669 [
670 {
671 ...message("Done", { role: "assistant", runId: RunId.make("run-1") }, "assistant-1"),
672 projectedItem: v2Item("assistant_message", {
673 id: "assistant-item-1",
674 messageId: "assistant-1",
675 text: "Done",
676 streaming: false,
677 }),
678 } as Entry,
679 ],
680 { onForkFromRun },
681 );
682 await click(button("Fork from this response"));
683 expect(onForkFromRun).toHaveBeenCalledWith({ sourceThreadId: "thread-1", runId: "run-1" });
684 });
685​
686 it("opens the changed files of an assistant response", async () => {
687 const assistantMessageId = MessageId.make("assistant-with-files");
688 const runId = RunId.make("run-with-files");
689 const onOpenTurnDiff = vi.fn();
690 await renderTimeline(
691 [message("Updated the fixture.", { role: "assistant", runId }, assistantMessageId)],
692 {
693 onOpenTurnDiff,
694 latestRun: { runId, status: "completed", startedAt: CREATED_AT, completedAt: CREATED_AT },
695 turnDiffSummaries: [
696 {
697 runId,
698 checkpointTurnCount: 1,
699 checkpointRef: CheckpointRef.make("checkpoint-with-files"),
700 status: "ready",
701 files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }],
702 assistantMessageId,
703 completedAt: CREATED_AT,
704 },
705 ],
706 },
707 );
708 expect(text()).toContain("1 changed file");
709 await click(button("Open diff"));
710 expect(onOpenTurnDiff).toHaveBeenCalledWith(runId, "README.md");
711 });
712});
713​
714describe("MessagesTimeline attachments", () => {
715 const withAttachment = (attachment: Record<string, unknown>) =>
716 message("Read the report.", {
717 attachments: [
718 {
719 type: "file",
720 name: "report.pdf",
721 mimeType: "application/pdf",
722 sizeBytes: 42,
723 ...attachment,
724 },
725 ] as never,
726 });
727​
728 it("offers preview and download actions for PDF attachments", async () => {
729 await renderTimeline([
730 withAttachment({
731 id: "attachment-report-pdf",
732 previewUrl: "https://environment.test/api/assets/report.pdf",
733 }),
734 ]);
735 expect(buttons("Preview report.pdf")).toHaveLength(1);
736 expect(buttons("Download report.pdf")).toHaveLength(1);
737 expect(container.querySelector('img[alt="report.pdf"]')).toBeNull();
738 });
739​
740 it("does not create a download URL before the download is requested", async () => {
741 await renderTimeline([withAttachment({ id: "attachment-report-pdf" })]);
742 expect(buttons("Download report.pdf")).toHaveLength(1);
743 expect(container.querySelector("a[href]")).toBeNull();
744 });
745​
746 it("does not download an optimistic file before the server supplies its attachment ID", async () => {
747 await renderTimeline([withAttachment({ id: "composer-local-report", downloadable: false })]);
748 expect(text()).toContain("report.pdf");
749 expect(buttons("Download report.pdf")).toHaveLength(0);
750 });
751​
752 it("renders unknown attachment types as inert rows instead of crashing", async () => {
753 await renderTimeline([
754 withAttachment({
755 type: "recording",
756 id: "attachment-voice-memo",
757 name: "voice-memo.ogg",
758 mimeType: "audio/ogg",
759 }),
760 ]);
761 expect(text()).toContain("voice-memo.ogg");
762 expect(buttons("Download voice-memo.ogg")).toHaveLength(0);
763 expect(container.querySelector("a[href], img")).toBeNull();
764 });
765​
766 it("shows SnapShot window details only after the preview resolves", async () => {
767 const snapShot = (previewUrl?: string) =>
768 message("First prompt.", {
769 attachments: [
770 {
771 type: "image",
772 id: "attachment-1",
773 name: "screenshot.png",
774 mimeType: "image/png",
775 sizeBytes: 1,
776 ...(previewUrl ? { previewUrl } : {}),
777 source: {
778 kind: "snap-shot",
779 capturedAt: CREATED_AT,
780 appName: "Terminal",
781 windowTitle: "t3code — Tests",
782 appIconDataUrl: "data:image/png;base64,aWNvbg==",
783 },
784 },
785 ] as never,
786 });
787 await renderTimeline([snapShot()]);
788 expect(text()).toContain("screenshot.png");
789 expect(text()).not.toContain("t3code — Tests");
790 await act(async () => roots.pop()!.unmount());
791 await renderTimeline([snapShot("data:image/png;base64,iVBORw0KGgo=")]);
792 expect(text()).toContain("Terminal");
793 expect(text()).toContain("t3code — Tests");
794 });
795});
796​
797describe("MessagesTimeline history and thread links", () => {
798 it("loads earlier turns from a control ahead of the bounded timeline", async () => {
799 const onLoadEarlier = vi.fn();
800 await renderTimeline([message("Recent activity")], {
801 historyControls: {
802 hasMoreHistory: true,
803 loading: false,
804 error: "Earlier activity could not be loaded.",
805 onLoadEarlier,
806 },
807 });
808 expect(text()).toContain("Earlier activity could not be loaded.");
809 expect(text().indexOf("Load earlier turns")).toBeLessThan(text().indexOf("Recent activity"));
810 await click(button("Load earlier turns"));
811 expect(onLoadEarlier).toHaveBeenCalledOnce();
812 });
813​
814 it("keeps an empty bounded timeline busy while earlier history loads", async () => {
815 await renderTimeline([], {
816 historyControls: {
817 hasMoreHistory: true,
818 loading: true,
819 error: null,
820 onLoadEarlier: () => {},
821 },
822 });
823 expect(text()).toContain("Loading earlier turns…");
824 expect(button("Load earlier turns")).toHaveProperty("disabled", true);
825 expect(text()).not.toContain("Send a message to start the conversation.");
826 });
827​
828 it("opens the parent thread from the top of an empty subagent timeline", async () => {
829 const onOpenThread = vi.fn();
830 await renderTimeline([], {
831 onOpenThread,
832 parentThreadLink: { threadId: ThreadId.make("thread-parent"), title: "Architecture audit" },
833 });
834 expect(text()).toContain("Subagent of");
835 expect(text()).toContain("Architecture audit");
836 expect(text()).not.toContain("Send a message to start the conversation");
837 await click(button("Open parent thread"));
838 expect(onOpenThread).toHaveBeenCalledWith("thread-parent");
839 });
840​
841 it("does not render the transient V2 interruption request", async () => {
842 await renderTimeline([
843 {
844 id: "interrupt-request",
845 kind: "event",
846 createdAt: CREATED_AT,
847 projectedItem: v2Item("run_interrupt_request", {
848 id: "interrupt-request",
849 message: "Waiting for the provider to stop.",
850 }),
851 } as Entry,
852 ]);
853 expect(text()).not.toContain("Interrupt requested");
854 expect(text()).not.toContain("Waiting for the provider to stop.");
855 });
856​
857 it("opens created threads from a lean row", async () => {
858 const onOpenThread = vi.fn();
859 await renderTimeline(
860 [
861 {
862 id: "thread-created",
863 kind: "event",
864 createdAt: CREATED_AT,
865 projectedItem: v2Item("thread_created", {
866 id: "thread-created",
867 nodeId: "node-1",
868 ordinal: 1,
869 title: "Claude research thread",
870 targetThreadId: "thread-2",
871 targetRunId: "run-2",
872 targetProviderInstanceId: "claude-default",
873 targetModel: "claude-sonnet-4-6",
874 }),
875 } as Entry,
876 ],
877 { onOpenThread },
878 );
879 expect(text()).toContain("Claude research thread");
880 expect(text()).not.toContain("Work Log");
881 await click(button("Open Claude research thread"));
882 expect(onOpenThread).toHaveBeenCalledWith("thread-2");
883 });
884​
885 it("renders context handoffs as from → to model endpoints instead of the summary", async () => {
886 const provider = (instanceId: string, driver: string, slug: string, name: string) => ({
887 instanceId,
888 driver,
889 enabled: true,
890 installed: true,
891 version: null,
892 status: "ready",
893 auth: {},
894 checkedAt: CREATED_AT,
895 models: [{ slug, name, isCustom: false, capabilities: null }],
896 slashCommands: [],
897 skills: [],
898 });
899 const providers = [
900 provider("codex_personal", "codex", "gpt-5.6-sol", "GPT 5.6 Sol"),
901 provider("claudeAgent", "claudeAgent", "claude-fable-5", "Claude Fable 5"),
902 ] as never;
903 const handoff = (fields: Record<string, unknown>) =>
904 ({
905 id: "handoff-1",
906 kind: "event",
907 createdAt: CREATED_AT,
908 projectedItem: v2Item("handoff", {
909 id: "handoff-1",
910 runId: "run-2",
911 title: "Provider handoff",
912 contextHandoffId: "handoff-1",
913 fromProviderThreadIds: ["provider-thread-1"],
914 toProviderThreadId: "provider-thread-2",
915 strategy: "full_thread_summary",
916 summary: "Full conversation context for provider handoff.",
917 fromProviderInstanceIds: ["codex_personal"],
918 toProviderInstanceId: "claudeAgent",
919 ...fields,
920 }),
921 }) as Entry;
922 const show = async (entry: Entry, props: Partial<TimelineProps> = {}) => {
923 for (const root of roots.splice(0)) await act(async () => root.unmount());
924 await renderElement(
925 <RegistryProvider
926 initialValues={[[serverEnvironment.providersValueAtom(ENVIRONMENT_ID), providers]]}
927 >
928 <MessagesTimeline {...baseProps()} timelineEntries={[entry]} {...props} />
929 </RegistryProvider>,
930 );
931 };
932​
933 await show(
934 handoff({
935 fromModelSelections: [{ instanceId: "codex_personal", model: "gpt-5.6-sol" }],
936 toModel: "claude-fable-5",
937 }),
938 );
939 expect(text()).toContain("Context handoff");
940 expect(text()).toContain("GPT 5.6 Sol");
941 expect(text()).toContain("Claude Fable 5");
942 expect(text()).not.toContain("Full conversation context");
943​
944 await show(handoff({}), {
945 runs: [
946 {
947 id: "run-1",
948 ordinal: 1,
949 providerInstanceId: "codex_personal",
950 modelSelection: { instanceId: "codex_personal", model: "gpt-5.6-sol" },
951 },
952 {
953 id: "run-2",
954 ordinal: 2,
955 providerInstanceId: "claudeAgent",
956 modelSelection: { instanceId: "claudeAgent", model: "claude-fable-5" },
957 },
958 ] as never,
959 });
960 expect(text()).toContain("GPT 5.6 Sol");
961 expect(text()).toContain("Claude Fable 5");
962​
963 await show(handoff({}));
964 expect(text()).toContain("Codex Personal");
965 expect(text()).not.toContain("Full conversation context");
966 });
967});
968​
969describe("MessagesTimeline subagents", () => {
970 it.each(
971 (
972 [
973 {
974 status: "running",
975 progress: "Reading src/index.ts",
976 result: null,
977 preview: "Reading src/index.ts",
978 },
979 {
980 status: "completed",
981 progress: "Reading src/index.ts",
982 result: "Tests should be isolated.",
983 preview: "Tests should be isolated.",
984 },
985 {
986 status: "running",
987 progress: "Reading src/index.ts",
988 result: "Partial streamed answer",
989 preview: "Reading src/index.ts",
990 },
991 {
992 status: "running",
993 progress: undefined,
994 result: "Streaming answer so far",
995 preview: "Streaming answer so far",
996 },
997 {
998 status: "cancelled",
999 progress: "Reading src/index.ts",
1000 result: "Partial output before cancel",
1001 preview: "Partial output before cancel",
1002 },
1004 status: "completed",
1005 progress: "Audited 12 packages",
1006 result: " \n\t ",
1007 preview: "Audited 12 packages",
1008 },
1009 ] as const
1010 ).flatMap((scenario) => [1, 2].map((count) => ({ ...scenario, count }))),
1011 )(
1012 "shows $count $status subagents with '$preview', grouping only multiple agents",
1013 async ({ status, progress, result, preview, count }) => {
1014 const onOpenThread = vi.fn();
1015 await renderTimeline(
1016 Array.from(
1017 { length: count },
1018 (_, index) =>
1019 ({
1020 id: `subagent-progress-${index}`,
1021 kind: "event",
1022 createdAt: CREATED_AT,
1023 projectedItem: v2Item("subagent", {
1024 id: `subagent-progress-${index}`,
1025 nodeId: `node-subagent-${index}`,
1026 providerThreadId: "provider-thread-1",
1027 providerTurnId: "provider-turn-1",
1028 ordinal: 1,
1029 status,
1030 title: "Package audit",
1031 subagentId: `node-subagent-${index}`,
1032 origin: "provider_native",
1033 driver: "claudeAgent",
1034 providerInstanceId: "claudeAgent",
1035 childThreadId: "thread-subagent-1",
1036 prompt: "Inspect the package",
1037 progress,
1038 result,
1039 }),
1040 }) as Entry,
1041 ),
1042 { onOpenThread },
1043 );
1044 const children = () => buttons("Open Package audit");
1045 // A settled run folds its work behind a "Worked for" summary.
1046 const fold = buttons(/^Worked for/)[0];
1047 if (fold) await click(fold);
1048 if (count > 1) {
1049 expect(children()).toHaveLength(0);
1050 await click(button(`${count} subagents`));
1051 } else {
1052 expect(buttons(`${count} subagents`)).toHaveLength(0);
1054 expect(children()).toHaveLength(count);
1055 expect(text()).toContain(preview);
1056 expect(text()).not.toContain("Inspect the package");
1057 if (result?.trim() && result !== preview) expect(text()).not.toContain(result);
1058 if (progress && progress !== preview) expect(text()).not.toContain(progress);
1059 await click(children()[0]!);
1060 expect(onOpenThread).toHaveBeenCalledWith("thread-subagent-1");
1061 if (count > 1) {
1062 await click(button(`${count} subagents`));
1063 await vi.waitFor(() => expect(children()).toHaveLength(0));
1065 },
1066 );
1067});
1068​
1069describe("timeline tooltip scroll dismissal", () => {
1070 const openPopup = () =>
1071 document.querySelector('[data-slot="tooltip-popup"][data-open]')?.textContent ?? null;
1072​
1073 async function renderTooltip(pullRequest: boolean, outside: boolean) {
1074 const tooltip = pullRequest ? (
1075 <PullRequestLinkPreview
1076 link={<button>message link</button>}
1077 originalUrl="https://example.com"
1078 target={{
1079 environmentId: ENVIRONMENT_ID,
1080 input: { projectId: "project-1" as never, repository: "pingdotgg/t3code", number: 1 },
1081 }}
1082 />
1083 ) : (
1084 <Tooltip>
1085 <TooltipTrigger delay={50}>message link</TooltipTrigger>
1086 <TooltipPopup>https://example.com</TooltipPopup>
1087 </Tooltip>
1088 );
1089 await renderElement(
1090 <>
1091 <TooltipScrollDismissArea>
1092 <div data-testid="scrollable" className="h-[100px] overflow-auto">
1093 {outside ? null : tooltip}
1094 <div className="h-[1000px]" />
1095 </div>
1096 </TooltipScrollDismissArea>
1097 {outside ? tooltip : null}
1098 </>,
1099 );
1100 return {
1101 trigger: container.querySelector<HTMLButtonElement>("button")!,
1102 scrollable: container.querySelector<HTMLElement>('[data-testid="scrollable"]')!,
1103 };
1105​
1106 async function scroll(scrollable: HTMLElement) {
1107 await act(async () => {
1108 scrollable.scrollTop += 50;
1109 scrollable.dispatchEvent(new Event("scroll"));
1110 });
1112​
1113 it.each([false, true])(
1114 "closes a hovered tooltip on scroll but keeps a focused one (pull request=%s)",
1115 async (pullRequest) => {
1116 const { trigger, scrollable } = await renderTooltip(pullRequest, false);
1117 await userEvent.hover(trigger);
1118 await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1119 await scroll(scrollable);
1120 await vi.waitFor(() => expect(openPopup()).toBeNull());
1121​
1122 await userEvent.unhover(trigger);
1123 await userEvent.keyboard("{Tab}");
1124 expect(document.activeElement).toBe(trigger);
1125 await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1126 await scroll(scrollable);
1127 expect(openPopup()).toBe("https://example.com");
1128 expect(document.activeElement).toBe(trigger);
1129 },
1130 );
1131​
1132 it("leaves tooltips outside the timeline open when it scrolls", async () => {
1133 const { trigger, scrollable } = await renderTooltip(false, true);
1134 await userEvent.hover(trigger);
1135 await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1136 await scroll(scrollable);
1137 expect(openPopup()).toBe("https://example.com");
1138 });
1139​
1140 it("keeps a hovered tooltip open on a wheel that does not scroll", async () => {
1141 const { trigger, scrollable } = await renderTooltip(false, false);
1142 await userEvent.hover(trigger);
1143 await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1144 await act(async () => {
1145 scrollable.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: 100 }));
1146 });
1147 expect(openPopup()).toBe("https://example.com");
1148 });
1149});
1150​
1151describe("MessagesTimeline scroll position", () => {
1152 const tall = (index: number) =>
1153 message(
1154 `Message ${index}\n\n${"Long paragraph. ".repeat(80)}`,
1155 { role: "assistant" },
1156 `message-${index}`,
1157 );
1158 const tallEntries = Array.from({ length: 12 }, (_, index) => tall(index));
1159​
1160 async function waitForList(props: ReturnType<typeof baseProps>) {
1161 await vi.waitFor(() => {
1162 const viewport = props.listRef.current?.getScrollableNode();
1163 expect(viewport?.scrollHeight ?? 0).toBeGreaterThan(viewport?.clientHeight ?? 0);
1164 });
1165 return props.listRef.current!.getScrollableNode()!;
1167​
1168 it("settles when earlier short replies load above long ones", async () => {
1169 const props = baseProps();
1170 const short = Array.from({ length: 80 }, (_, index) =>
1171 message(`Short reply ${index}`, { role: "assistant" }, `short-${index}`),
1172 );
1173 const long = Array.from({ length: 4 }, (_, index) =>
1174 message(
1175 `${"Long handbook paragraph. ".repeat(40)}\n\n`.repeat(60),
1176 { role: "assistant" },
1177 `long-${index}`,
1178 ),
1179 );
1180 let nestedCommits = 0;
1181 let maxNestedCommits = 0;
1182 const onRender = (_id: string, phase: string) => {
1183 nestedCommits = phase === "nested-update" ? nestedCommits + 1 : 0;
1184 maxNestedCommits = Math.max(maxNestedCommits, nestedCommits);
1185 };
1186 const timeline = (entries: Entry[]) => (
1187 <Profiler id="timeline" onRender={onRender}>
1188 <MessagesTimeline {...props} timelineEntries={entries} />
1189 </Profiler>
1190 );
1191 await renderElement(timeline(long));
1192 const viewport = await waitForList(props);
1193 await act(async () => {
1194 viewport.scrollTop = 0;
1195 viewport.dispatchEvent(new Event("scroll"));
1196 });
1197​
1198 maxNestedCommits = 0;
1199 await act(async () => roots.at(-1)!.render(timeline([...short, ...long])));
1200 await vi.waitFor(async () => {
1201 await act(async () => {
1202 viewport.scrollTop = 0;
1203 viewport.dispatchEvent(new Event("scroll"));
1204 });
1205 expect(text()).toContain("Short reply 0");
1206 });
1207 expect(maxNestedCommits).toBeLessThan(8);
1208 });
1209​
1210 it("remembers a manual reading position when the chat closes", async () => {
1211 const props = baseProps();
1212 function Chat() {
1213 const [liveFollowEnabled, setLiveFollowEnabled] = useState(true);
1214 // The chat view stops following the live edge when the reader scrolls.
1215 return (
1216 <div className="contents" onWheelCapture={() => setLiveFollowEnabled(false)}>
1217 <MessagesTimeline
1218 {...props}
1219 timelineEntries={tallEntries}
1220 liveFollowEnabled={liveFollowEnabled}
1221 />
1222 </div>
1223 );
1225 await renderElement(<Chat />);
1226 const viewport = await waitForList(props);
1227 await vi.waitFor(() => expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(true));
1228​
1229 await userEvent.wheel(viewport, { delta: { y: -600 } });
1230 await vi.waitFor(() => expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(false));
1231 const offset = viewport.scrollTop;
1232 await act(async () => roots.pop()!.unmount());
1233 expect(readTimelinePosition(props.routeThreadKey)).toMatchObject({
1234 atEnd: false,
1235 scrollOffset: offset,
1236 });
1237 });
1238​
1239 it("restores the composer after closing tool output only at the end", async () => {
1240 const props = baseProps();
1241 function Thread() {
1242 const composer = useComposerFocusState();
1243 return (
1244 <>
1245 <button onClick={() => composer.setIsComposerScrollCollapsed(true)}>Collapse</button>
1246 <output>{composer.isComposerScrollCollapsed ? "collapsed" : "resting"}</output>
1247 <MessagesTimeline
1248 {...props}
1249 onToolOutputCollapsedAtEnd={composer.restoreAfterTimelineReachedEnd}
1250 timelineEntries={[
1251 ...tallEntries,
1252 work("tool", {
1253 label: "Run command",
1254 tone: "tool",
1255 toolLifecycleStatus: "completed",
1256 detail: "Command output",
1257 }),
1258 ]}
1259 />
1260 </>
1261 );
1263 await renderElement(<Thread />);
1264 const composerState = () => container.querySelector("output")!.textContent;
1265 const viewport = await waitForList(props);
1266 await click(button("Collapse"));
1267 const toggle = () => button("Command output");
1268 await click(toggle());
1269 await click(toggle());
1270 await vi.waitFor(() => expect(composerState()).toBe("resting"));
1271​
1272 await click(button("Collapse"));
1273 await userEvent.wheel(viewport, { delta: { y: -2000 } });
1274 await click(toggle());
1275 await click(toggle());
1276 await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
1277 expect(composerState()).toBe("collapsed");
1278 });
1279});
1280​
1281describe("MessagesTimeline send anchor", () => {
1282 it("reports the anchored sent message once it is laid out", async () => {
1283 const onAnchorReady = vi.fn();
1284 const sent = message("Newest prompt.", {}, "message-2");
1285 await renderTimeline([message("Earlier reply.", { role: "assistant" }), sent], {
1286 anchorMessageId: MessageId.make("message-2"),
1287 onAnchorReady,
1288 contentInsetEndAdjustment: 144,
1289 });
1290 await vi.waitFor(() =>
1291 expect(onAnchorReady).toHaveBeenCalledWith(MessageId.make("message-2"), 1),
1292 );
1293 });
1294​
1295 it("does not anchor a follow-up user message that is not the newest turn", async () => {
1296 const onAnchorReady = vi.fn();
1297 await renderTimeline([message("First prompt."), message("Newest prompt.", {}, "message-2")], {
1298 anchorMessageId: MessageId.make("message-2"),
1299 onAnchorReady,
1300 });
1301 await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
1302 expect(onAnchorReady).not.toHaveBeenCalled();
1303 });
1304});