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

MessagesTimeline.browser.test.tsx

1,482 lines51.0 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.each([
198 ["Enter", "{Enter}"],
199 ["Space", " "],
200 ])("opens a nested diff with %s without collapsing the tool row", async (_name, key) => {
201 const onOpenTurnDiff = vi.fn();
202 await renderTimeline(
203 [
204 work("file-change-1", {
205 label: "Updated src/index.ts",
206 tone: "tool",
207 itemType: "file_change",
208 toolLifecycleStatus: "completed",
209 projectedItem: v2Item("file_change", { id: "file-change-1", fileName: "src/index.ts" }),
210 }),
211 ],
212 { onOpenTurnDiff },
213 );
214 const row = container.querySelector<HTMLElement>('[data-v2-item-type="file_change"]')!;
215 const press = async (target: HTMLElement) => {
216 await act(async () => {
217 target.focus();
218 await userEvent.keyboard(key);
219 });
220 };
221 expect(row.getAttribute("aria-expanded")).toBe("false");
222 await press(row);
223 expect(row.getAttribute("aria-expanded")).toBe("true");
224 const openDiff = button("Open diff");
225 await press(openDiff);
226 expect(onOpenTurnDiff).toHaveBeenCalledWith("run-1", "src/index.ts");
227 expect(onOpenTurnDiff).toHaveBeenCalledTimes(1);
228 expect(row.getAttribute("aria-expanded")).toBe("true");
229 await press(row);
230 expect(row.getAttribute("aria-expanded")).toBe("false");
231 });
232​
233 it("shows dynamic tool input without cached output when the row is expanded", async () => {
234 await renderTimeline([
235 work("tool-with-cached-output", {
236 label: "Example tool",
237 toolTitle: "Example tool",
238 tone: "tool",
239 itemType: "dynamic_tool",
240 toolLifecycleStatus: "completed",
241 toolData: {
242 input: { query: "KEEP_TOOL_INPUT" },
243 output: { text: "RAW_CACHED_TOOL_OUTPUT" },
244 },
245 }),
246 ]);
247 await click(button("Example tool"));
248 expect(text()).toContain("KEEP_TOOL_INPUT");
249 expect(text()).not.toContain("RAW_CACHED_TOOL_OUTPUT");
250 await click(button("Example tool"));
251 await vi.waitFor(() => expect(text()).not.toContain("KEEP_TOOL_INPUT"));
252 });
253​
254 it("expands and collapses a tool call through its header", async () => {
255 await renderTimeline([
256 work("work-standalone", {
257 toolCallId: "call-standalone",
258 label: "Run lint",
259 tone: "tool",
260 itemType: "command_execution",
261 command: "pnpm lint",
262 toolLifecycleStatus: "completed",
263 }),
264 ]);
265 const header = () => container.querySelector<HTMLElement>("[aria-expanded]")!;
266 expect(header().getAttribute("aria-expanded")).toBe("false");
267 await click(header());
268 expect(header().getAttribute("aria-expanded")).toBe("true");
269 await click(header());
270 expect(header().getAttribute("aria-expanded")).toBe("false");
271 });
272​
273 it("leads an unanswered question row with the question text", async () => {
274 await renderTimeline([
275 work("question-work", {
276 label: "User input requested",
277 tone: "tool",
278 questionAnswer: {
279 requestId: ApprovalRequestId.make("question-request"),
280 answers: {},
281 questionTextById: { scope: "Which repository?" },
282 attachmentsByQuestionId: {},
283 },
284 }),
285 ]);
286 const toggle = button("Which repository?");
287 expect(toggle.getAttribute("aria-expanded")).toBe("false");
288 const before = text().match(/Which repository\?/g)?.length ?? 0;
289 expect(before).toBeGreaterThan(0);
290 await click(toggle);
291 expect(text().match(/Which repository\?/g)?.length).toBe(before + 1);
292 });
293​
294 it("collapses settled tool runs behind a generated summary and names a failure", async () => {
295 await renderTimeline([
296 work("work-1", {
297 label: "Ran command",
298 command: "vp lint",
299 tone: "tool",
300 itemType: "command_execution",
301 toolLifecycleStatus: "completed",
302 }),
303 work("work-2", {
304 label: "Run lint",
305 command: "vp test run",
306 tone: "tool",
307 itemType: "command_execution",
308 toolLifecycleStatus: "failed",
309 }),
310 ]);
311 const summary = button(/^Ran 2 commands/);
312 expect(summary.getAttribute("aria-label")).toContain("tool call failed");
313 expect(text()).not.toContain("vp lint");
314 await click(summary);
315 await vi.waitFor(() => expect(text()).toContain("vp lint"));
316 });
317​
318 it("keeps mixed work logs neutral after a later tool call succeeds", async () => {
319 await renderTimeline([
320 work("work-failed", {
321 label: "Run search",
322 tone: "tool",
323 itemType: "command_execution",
324 toolLifecycleStatus: "failed",
325 }),
326 work("work-info", { label: "Status updated", tone: "info" }),
327 work("work-completed", {
328 label: "Run tests",
329 tone: "tool",
330 itemType: "command_execution",
331 toolLifecycleStatus: "completed",
332 }),
333 ]);
334 expect(button("Ran 2 commands and received 1 update")).toBeDefined();
335 });
336​
337 it("marks a failed tool inside an expanded work log", async () => {
338 await renderTimeline([
339 work("work-info", { label: "Status updated", tone: "info" }),
340 work("work-1", {
341 label: "Glob",
342 tone: "tool",
343 toolLifecycleStatus: "failed",
344 detail: "No files found",
345 }),
346 ]);
347 await click(button(/^Received 1 update/));
348 await vi.waitFor(() =>
349 expect(container.querySelector('[aria-label="Tool call failed"]')).not.toBeNull(),
350 );
351 });
352​
353 it("renders context compaction entries in the normal work log", async () => {
354 await renderTimeline([work("work-1", { label: "Context compacted", tone: "info" })]);
355 expect(text()).toContain("Context compacted");
356 });
357​
358 it("formats changed file paths from the workspace root", async () => {
359 await renderTimeline(
360 [
361 work("context-info", { label: "Session started", tone: "info" }),
362 work("work-1", {
363 label: "Updated files",
364 tone: "tool",
365 itemType: "file_change",
366 toolLifecycleStatus: "completed",
367 changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"],
368 }),
369 ],
370 { workspaceRoot: "C:/Users/mike/dev-stuff/t3code" },
371 );
372 await click(button(/^Received 1 update/));
373 await vi.waitFor(() => expect(text()).toContain("t3code/apps/web/src/session-logic.ts"));
374 expect(text()).not.toContain("C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts");
375 });
376​
377 it("renders T3 MCP dynamic tools with their pretty name", async () => {
378 const item = {
379 id: "tool-t3-thread-read",
380 type: "dynamic_tool",
381 toolName: "mcp__t3-code__t3_thread_read",
382 input: { threadId: "thread-child" },
383 output: { messages: [] },
384 };
385 await renderTimeline([
386 work("context-info", { label: "Session started", tone: "info" }),
387 work(item.id, {
388 runId: null,
389 label: item.toolName,
390 tone: "tool",
391 itemType: item.type,
392 toolTitle: item.toolName,
393 toolLifecycleStatus: "completed",
394 toolData: { input: item.input, output: item.output },
395 structuredPayload: v2Item("dynamic_tool", item),
396 projectedItem: v2Item("dynamic_tool", item),
397 }),
398 ]);
399 await click(button(/^Received 1 update/));
400 await vi.waitFor(() => expect(text()).toContain("Read a T3 thread"));
401 expect(text()).not.toContain("mcp__t3-code__t3_thread_read");
402 });
403​
404 it("keeps a provider retry collapsed in the work log", async () => {
405 const retryItem = {
406 id: "provider-error",
407 status: "running",
408 title: "Provider retry",
409 failure: {
410 class: "transport_error",
411 message: "The response stream disconnected.",
412 code: "responseStreamDisconnected",
413 retryable: true,
414 },
415 retry: { attempt: 2, maxAttempts: 5, retryDelayMs: null },
416 };
417 await renderTimeline(
418 [
419 work("provider-error", {
420 runId: "run-1",
421 label: "Retrying provider (2/5)",
422 detail: retryItem.failure.message,
423 tone: "info",
424 itemType: "error",
425 toolLifecycleStatus: "inProgress",
426 projectedItem: v2Item("error", retryItem),
427 }),
428 ],
429 {
430 isWorking: true,
431 activeTurnInProgress: true,
432 latestRun: {
433 runId: RunId.make("run-1"),
434 status: "running",
435 startedAt: CREATED_AT,
436 completedAt: null,
437 },
438 },
439 );
440 expect(text()).toContain("Retrying provider (2/5)");
441 expect(text()).not.toContain("Structured details");
442 });
443​
444 it.each([
445 [
446 "**Viewing image first** with *care*, ~~old~~ `code` and [context](https://example.com)",
447 "Viewing image first with care, old code and context",
448 1,
449 ],
450 ["first paragraph\n\nsecond paragraph", "first paragraph second paragraph", 0],
451 ["- first\n- second", "first second", 0],
452 ["first \nsecond", "first second", 0],
453 ["![image description](image.png)", "image description", 0],
454 ["![](image.png)", "Thought", 0],
455 ["---", "Thought", 0],
456 ] as const)(
457 "shows plain text for a V2 reasoning preview: %s",
458 async (markdown, expected, strongCount) => {
459 await renderTimeline([
460 work("reasoning-preview", {
461 label: markdown,
462 detail: markdown,
463 tone: "thinking",
464 itemType: "reasoning",
465 toolLifecycleStatus: "completed",
466 }),
467 ]);
468 const row = () => container.querySelector<HTMLElement>("[role=button][aria-expanded]")!;
469 const preview = () => row().textContent!.replace(/\s+/g, " ");
470 expect(preview()).toContain(expected);
471 expect(container.querySelectorAll("strong")).toHaveLength(0);
472 await click(row());
473 expect(container.querySelectorAll("strong")).toHaveLength(strongCount);
474 await click(row());
475 expect(preview()).toContain(expected);
476 await vi.waitFor(() => expect(container.querySelectorAll("strong")).toHaveLength(0));
477 },
478 );
479});
480​
481describe("MessagesTimeline messages", () => {
482 it("preserves XML-like tags and comparisons in user messages as text", async () => {
483 const source = [
484 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
485 'Before <nested data-value="a&b">inside</nested> after',
486 "</global-agent-instructions> in your context?",
487 "Comparison: 2 < 3 and 5 > 4.",
488 ];
489 await renderTimeline([message(source.join("\n"))]);
490 for (const line of source) expect(text()).toContain(line);
491 expect(container.querySelector("global-agent-instructions, nested")).toBeNull();
492 });
493​
494 it("preserves XML-like source inside user code spans and fences", async () => {
495 await renderTimeline([
496 message(
497 [
498 'Inline `<tag attr="x">`',
499 "",
500 "```xml",
501 '<root><child enabled="true" /></root>',
502 "```",
503 ].join("\n"),
504 ),
505 ]);
506 expect(container.querySelector("code[data-inline-code]")?.textContent).toBe('<tag attr="x">');
507 expect(text()).toContain('<root><child enabled="true" /></root>');
508 });
509​
510 it("does not show markdown titles in user messages", async () => {
511 await renderTimeline([
512 message(
513 '[link](https://example.com "link tip") ![image](https://example.com/image.png "image tip")',
514 ),
515 ]);
516 expect(container.querySelector('a[href="https://example.com"]')).not.toBeNull();
517 expect(container.querySelector('img[src="https://example.com/image.png"]')).not.toBeNull();
518 expect(container.querySelector('[title="link tip"], [title="image tip"]')).toBeNull();
519 });
520​
521 it("renders unsafe user HTML as inert source text", async () => {
522 const source =
523 '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">';
524 await renderTimeline([message(source)]);
525 expect(text()).toContain(source);
526 expect(container.querySelector("script, img")).toBeNull();
527 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
528 });
529​
530 it("renders sanitized raw HTML in assistant messages", async () => {
531 await renderTimeline([
532 message(
533 [
534 '<details onclick="globalThis.__t3Xss = 1">',
535 "<summary>Safe details</summary>",
536 "<script>globalThis.__t3Xss = 2</script>",
537 '<img src="x" onerror="globalThis.__t3Xss = 3">',
538 '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
539 "</details>",
540 ].join(""),
541 { role: "assistant" },
542 ),
543 ]);
544 expect(container.querySelector("[data-markdown-details]")?.textContent).toContain(
545 "Safe details",
546 );
547 expect(text()).not.toContain("<details");
548 expect(container.querySelector("script, [onclick], [onerror]")).toBeNull();
549 expect(container.innerHTML).not.toContain("javascript:");
550 await click(button("Safe details"));
551 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
552 });
553​
554 it("collapses long user messages behind a toggle and keeps their copy button", async () => {
555 await renderTimeline([message(longText())]);
556 const toggle = button("Show full message");
557 expect(toggle.getAttribute("aria-expanded")).toBe("false");
558 expect(buttons("Copy message")).toHaveLength(1);
559 await click(toggle);
560 expect(button("Show less").getAttribute("aria-expanded")).toBe("true");
561 });
562​
563 it("does not offer a collapse toggle for short user messages", async () => {
564 await renderTimeline([message("Short prompt.")]);
565 expect(buttons(/Show full message|Show less/)).toHaveLength(0);
566 });
567​
568 it("identifies user-role messages sent by another agent", async () => {
569 await renderTimeline([
570 message("Review this area", { createdBy: "agent", creationSource: "provider" }),
571 ]);
572 expect(text()).toContain("Sent by another agent");
573 await act(async () => roots.pop()!.unmount());
574 await renderTimeline([message("Review this area")]);
575 expect(text()).not.toContain("Sent by another agent");
576 });
577​
578 it("shows steer intent ahead of committed user messages", async () => {
579 await renderTimeline([message("Adjust the current turn", { inputIntent: "steer" })]);
580 expect(text().indexOf("Steer")).toBeGreaterThanOrEqual(0);
581 expect(text().indexOf("Steer")).toBeLessThan(text().indexOf("Adjust the current turn"));
582 });
583​
584 it("renders inline terminal labels as chips", async () => {
585 await renderTimeline([
586 message(
587 [
588 longText("yoo what's @terminal-1:1-5 mean"),
589 "",
590 "<terminal_context>",
591 "- Terminal 1 lines 1-5:",
592 " 1 | julius@mac effect-http-ws-cli % bun i",
593 " 2 | bun install v1.3.9 (cf6cdbbb)",
594 "</terminal_context>",
595 ].join("\n"),
596 ),
597 ]);
598 expect(text()).toContain("Terminal 1 lines 1-5");
599 expect(text()).toContain("yoo what's");
600 expect(text()).not.toContain("terminal_context");
601 expect(buttons("Show full message")).toHaveLength(1);
602 });
603​
604 it("renders chips for standalone element-pick context messages", async () => {
605 await renderTimeline([
606 message(
607 [
608 "<element_context>",
609 "- <SubmitButton> (Button.tsx:12):",
610 " url: https://example.com/dashboard",
611 " selector: button.submit",
612 " source: /repo/src/Button.tsx:12:5",
613 " html:",
614 ' <button class="submit">Save</button>',
615 "</element_context>",
616 ].join("\n"),
617 ),
618 ]);
619 expect(text()).toContain("SubmitButton");
620 expect(text()).not.toContain("element_context");
621 });
622​
623 it("renders review comment contexts as structured cards instead of raw tags", async () => {
624 await renderTimeline([
625 message(
626 [
627 '<review_comment sectionId="turn:2" sectionTitle="Turn 2" filePath="apps/web/src/lib/contextWindow.test.ts" startIndex="3" endIndex="14" rangeLabel="+47 to +58">',
628 "Wadduo",
629 "```diff",
630 "@@ -0,0 +47,2 @@",
631 '+ it("keeps valid zero-usage snapshots", () => {',
632 "+ expect(snapshot).not.toBeNull();",
633 "```",
634 "</review_comment>",
635 ].join("\n"),
636 ),
637 ]);
638 expect(text()).toContain("contextWindow.test.ts L47 to L58");
639 expect(text()).not.toContain("review_comment");
640 });
641​
642 it("renders file review comments as source code", async () => {
643 await renderTimeline([
644 message(
645 [
646 '<review_comment sectionId="file:docs/plan.md" sectionTitle="File comment" filePath="docs/plan.md" startIndex="0" endIndex="1" rangeLabel="L1 to L2">',
647 "Clarify this.",
648 "```md",
649 "# Plan",
650 "- Step one",
651 "```",
652 "</review_comment>",
653 ].join("\n"),
654 ),
655 ]);
656 expect(text()).toContain("plan.md L1 to L2");
657 expect(text()).not.toContain("review_comment");
658 });
659​
660 it("collapses superseded attempt output behind a disclosure", async () => {
661 const runId = RunId.make("run-steered");
662 const attempt = (id: string, ordinal: number, status: string) =>
663 ({
664 id,
665 runId,
666 attemptOrdinal: ordinal,
667 rootNodeId: `node-${id}`,
668 status,
669 completedAt: null,
670 }) as never;
671 await renderTimeline(
672 [
673 {
674 ...message(
675 "Partial response from the old attempt",
676 { role: "assistant", runId },
677 "superseded-response",
678 ),
679 attempt: attempt("attempt-1", 1, "superseded"),
680 } as Entry,
681 {
682 ...message(
683 "Current response remains visible",
684 { role: "assistant", runId, streaming: true },
685 "active-response",
686 ),
687 attempt: attempt("attempt-2", 2, "running"),
688 } as Entry,
689 ],
690 {
691 latestRun: { runId, status: "running", startedAt: CREATED_AT, completedAt: null },
692 },
693 );
694 expect(text()).toContain("Current response remains visible");
695 expect(text()).not.toContain("Partial response from the old attempt");
696 const disclosure = button(/Superseded attempt/);
697 expect(disclosure.textContent).toContain("Cut off by a steer");
698 await click(disclosure);
699 expect(text()).toContain("Partial response from the old attempt");
700 });
701​
702 it("forks from a completed assistant response", async () => {
703 const onForkFromRun = vi.fn(async () => {});
704 await renderTimeline(
705 [
706 {
707 ...message("Done", { role: "assistant", runId: RunId.make("run-1") }, "assistant-1"),
708 projectedItem: v2Item("assistant_message", {
709 id: "assistant-item-1",
710 messageId: "assistant-1",
711 text: "Done",
712 streaming: false,
713 }),
714 } as Entry,
715 ],
716 { onForkFromRun },
717 );
718 await click(button("Fork from this response"));
719 expect(onForkFromRun).toHaveBeenCalledWith({ sourceThreadId: "thread-1", runId: "run-1" });
720 });
721​
722 it("opens the changed files of an assistant response", async () => {
723 const assistantMessageId = MessageId.make("assistant-with-files");
724 const runId = RunId.make("run-with-files");
725 const onOpenTurnDiff = vi.fn();
726 await renderTimeline(
727 [message("Updated the fixture.", { role: "assistant", runId }, assistantMessageId)],
728 {
729 onOpenTurnDiff,
730 latestRun: { runId, status: "completed", startedAt: CREATED_AT, completedAt: CREATED_AT },
731 turnDiffSummaries: [
732 {
733 runId,
734 checkpointTurnCount: 1,
735 checkpointRef: CheckpointRef.make("checkpoint-with-files"),
736 status: "ready",
737 files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }],
738 assistantMessageId,
739 completedAt: CREATED_AT,
740 },
741 ],
742 },
743 );
744 expect(text()).toContain("1 changed file");
745 await click(button("Open diff"));
746 expect(onOpenTurnDiff).toHaveBeenCalledWith(runId, "README.md");
747 });
748});
749​
750describe("MessagesTimeline attachments", () => {
751 const withAttachment = (attachment: Record<string, unknown>) =>
752 message("Read the report.", {
753 attachments: [
754 {
755 type: "file",
756 name: "report.pdf",
757 mimeType: "application/pdf",
758 sizeBytes: 42,
759 ...attachment,
760 },
761 ] as never,
762 });
763​
764 it("offers preview and download actions for PDF attachments", async () => {
765 await renderTimeline([
766 withAttachment({
767 id: "attachment-report-pdf",
768 previewUrl: "https://environment.test/api/assets/report.pdf",
769 }),
770 ]);
771 expect(buttons("Preview report.pdf")).toHaveLength(1);
772 expect(buttons("Download report.pdf")).toHaveLength(1);
773 expect(container.querySelector('img[alt="report.pdf"]')).toBeNull();
774 });
775​
776 it("does not create a download URL before the download is requested", async () => {
777 await renderTimeline([withAttachment({ id: "attachment-report-pdf" })]);
778 expect(buttons("Download report.pdf")).toHaveLength(1);
779 expect(container.querySelector("a[href]")).toBeNull();
780 });
781​
782 it("does not download an optimistic file before the server supplies its attachment ID", async () => {
783 await renderTimeline([withAttachment({ id: "composer-local-report", downloadable: false })]);
784 expect(text()).toContain("report.pdf");
785 expect(buttons("Download report.pdf")).toHaveLength(0);
786 });
787​
788 it("renders unknown attachment types as inert rows instead of crashing", async () => {
789 await renderTimeline([
790 withAttachment({
791 type: "recording",
792 id: "attachment-voice-memo",
793 name: "voice-memo.ogg",
794 mimeType: "audio/ogg",
795 }),
796 ]);
797 expect(text()).toContain("voice-memo.ogg");
798 expect(buttons("Download voice-memo.ogg")).toHaveLength(0);
799 expect(container.querySelector("a[href], img")).toBeNull();
800 });
801​
802 it("shows SnapShot window details only after the preview resolves", async () => {
803 const snapShot = (previewUrl?: string) =>
804 message("First prompt.", {
805 attachments: [
806 {
807 type: "image",
808 id: "attachment-1",
809 name: "screenshot.png",
810 mimeType: "image/png",
811 sizeBytes: 1,
812 ...(previewUrl ? { previewUrl } : {}),
813 source: {
814 kind: "snap-shot",
815 capturedAt: CREATED_AT,
816 appName: "Terminal",
817 windowTitle: "t3code — Tests",
818 appIconDataUrl: "data:image/png;base64,aWNvbg==",
819 },
820 },
821 ] as never,
822 });
823 await renderTimeline([snapShot()]);
824 expect(text()).toContain("screenshot.png");
825 expect(text()).not.toContain("t3code — Tests");
826 await act(async () => roots.pop()!.unmount());
827 await renderTimeline([snapShot("data:image/png;base64,iVBORw0KGgo=")]);
828 expect(text()).toContain("Terminal");
829 expect(text()).toContain("t3code — Tests");
830 });
831});
832​
833describe("MessagesTimeline history and thread links", () => {
834 it.each([
835 ["imported runless", null],
836 ["standard", RunId.make("citation-run")],
837 ] as const)("reveals a cited response inside a folded %s turn", async (_label, runId) => {
838 const quote = "The imported response contains this cited detail.";
839 const props = {
840 ...baseProps(),
841 timelineEntries: [
842 message("Investigate the issue.", { runId }, "citation-prompt"),
843 message(quote, { role: "assistant", runId }, "citation-source"),
844 message("Investigation complete.", { role: "assistant", runId }, "citation-answer"),
845 ],
846 };
847 await renderElement(<MessagesTimeline {...props} />);
848 const source = () =>
849 container.querySelector<HTMLElement>('[data-assistant-citation-source="citation-source"]');
850 await vi.waitFor(() => expect(text()).toContain("Investigation complete."));
851 expect(buttons(/^Worked/)).toHaveLength(1);
852 expect(source()).toBeNull();
853​
854 await act(async () =>
855 roots.at(-1)!.render(
856 <MessagesTimeline
857 {...props}
858 citationRequest={{
859 key: "open-citation",
860 citation: {
861 version: 1,
862 environmentId: ENVIRONMENT_ID,
863 threadId: ThreadId.make(`thread-${threadCount}`),
864 messageId: MessageId.make("citation-source"),
865 text: quote,
866 start: 0,
867 end: quote.length,
868 prefix: "",
869 suffix: "",
870 },
871 }}
872 />,
873 ),
874 );
875​
876 await vi.waitFor(() => {
877 expect(source()?.textContent ?? "").toContain(quote);
878 const highlight = CSS.highlights.get("t3-assistant-citation");
879 expect(highlight).toBeDefined();
880 const range = [...highlight!][0] as Range;
881 expect(range.toString()).toBe(quote);
882 const viewport = container.querySelector<HTMLElement>("[data-assistant-citation-viewport]")!;
883 const bounds = range.getBoundingClientRect();
884 expect(bounds.height).toBeGreaterThan(0);
885 expect(bounds.top).toBeGreaterThanOrEqual(viewport.getBoundingClientRect().top);
886 expect(bounds.bottom).toBeLessThanOrEqual(viewport.getBoundingClientRect().bottom);
887 });
888 });
889​
890 it("loads earlier turns from a control ahead of the bounded timeline", async () => {
891 const onLoadEarlier = vi.fn();
892 await renderTimeline([message("Recent activity")], {
893 historyControls: {
894 hasMoreHistory: true,
895 loading: false,
896 error: "Earlier activity could not be loaded.",
897 onLoadEarlier,
898 },
899 });
900 expect(text()).toContain("Earlier activity could not be loaded.");
901 expect(text().indexOf("Load earlier turns")).toBeLessThan(text().indexOf("Recent activity"));
902 await click(button("Load earlier turns"));
903 expect(onLoadEarlier).toHaveBeenCalledOnce();
904 });
905​
906 it("keeps an empty bounded timeline busy while earlier history loads", async () => {
907 await renderTimeline([], {
908 historyControls: {
909 hasMoreHistory: true,
910 loading: true,
911 error: null,
912 onLoadEarlier: () => {},
913 },
914 });
915 expect(text()).toContain("Loading earlier turns…");
916 expect(button("Load earlier turns")).toHaveProperty("disabled", true);
917 expect(text()).not.toContain("Send a message to start the conversation.");
918 });
919​
920 it("opens the parent thread from the top of an empty subagent timeline", async () => {
921 const onOpenThread = vi.fn();
922 await renderTimeline([], {
923 onOpenThread,
924 parentThreadLink: { threadId: ThreadId.make("thread-parent"), title: "Architecture audit" },
925 });
926 expect(text()).toContain("Subagent of");
927 expect(text()).toContain("Architecture audit");
928 expect(text()).not.toContain("Send a message to start the conversation");
929 await click(button("Open parent thread"));
930 expect(onOpenThread).toHaveBeenCalledWith("thread-parent");
931 });
932​
933 it("opens a thread at its newest message after an empty pane and restores it on return", async () => {
934 const props = baseProps();
935 const entries = Array.from({ length: 12 }, (_, index) =>
936 message(
937 Array.from({ length: 60 }, (_, line) => `Paragraph ${index}.${line}`).join("\n\n"),
938 { role: "assistant" },
939 `message-${index}`,
940 ),
941 );
942 await renderTimeline([], {
943 ...props,
944 routeThreadKey: `${props.routeThreadKey}-loading`,
945 hideEmptyPlaceholder: true,
946 });
947​
948 // Each row is much taller than LegendList's estimate.
949 await act(async () =>
950 roots.at(-1)!.render(<MessagesTimeline {...props} timelineEntries={entries} />),
951 );
952 const viewport = props.listRef.current!.getScrollableNode();
953 await vi.waitFor(() => {
954 expect(viewport.scrollHeight).toBeGreaterThan(viewport.clientHeight);
955 expect(text()).toContain("Paragraph 11.59");
956 expect(
957 viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop,
958 ).toBeLessThanOrEqual(1);
959 });
960​
961 const otherThreadKey = `${props.routeThreadKey}-other`;
962 await act(async () =>
963 roots
964 .at(-1)!
965 .render(
966 <MessagesTimeline
967 {...props}
968 routeThreadKey={otherThreadKey}
969 timelineEntries={entries}
970 liveFollowEnabled={false}
971 />,
972 ),
973 );
974 await vi.waitFor(() =>
975 expect(
976 viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop,
977 ).toBeLessThanOrEqual(1),
978 );
979 // Move beyond LegendList's one-viewport follow threshold so it cannot mask restoration.
980 await userEvent.wheel(viewport, { delta: { y: -2000 } });
981 await vi.waitFor(() => {
982 expect(readTimelinePosition(otherThreadKey)?.atEnd).toBe(false);
983 expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeGreaterThan(
984 viewport.clientHeight,
985 );
986 });
987​
988 await act(async () =>
989 roots.at(-1)!.render(<MessagesTimeline {...props} timelineEntries={entries} />),
990 );
991 await vi.waitFor(() => {
992 expect(text()).toContain("Paragraph 11.59");
993 expect(
994 viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop,
995 ).toBeLessThanOrEqual(1);
996 });
997 });
998​
999 it("does not render the transient V2 interruption request", async () => {
1000 await renderTimeline([
1002 id: "interrupt-request",
1003 kind: "event",
1004 createdAt: CREATED_AT,
1005 projectedItem: v2Item("run_interrupt_request", {
1006 id: "interrupt-request",
1007 message: "Waiting for the provider to stop.",
1008 }),
1009 } as Entry,
1010 ]);
1011 expect(text()).not.toContain("Interrupt requested");
1012 expect(text()).not.toContain("Waiting for the provider to stop.");
1013 });
1014​
1015 it("opens created threads from a lean row", async () => {
1016 const onOpenThread = vi.fn();
1017 await renderTimeline(
1020 id: "thread-created",
1021 kind: "event",
1022 createdAt: CREATED_AT,
1023 projectedItem: v2Item("thread_created", {
1024 id: "thread-created",
1025 nodeId: "node-1",
1026 ordinal: 1,
1027 title: "Claude research thread",
1028 targetThreadId: "thread-2",
1029 targetRunId: "run-2",
1030 targetProviderInstanceId: "claude-default",
1031 targetModel: "claude-sonnet-4-6",
1032 }),
1033 } as Entry,
1034 ],
1035 { onOpenThread },
1036 );
1037 expect(text()).toContain("Claude research thread");
1038 expect(text()).not.toContain("Work Log");
1039 await click(button("Open Claude research thread"));
1040 expect(onOpenThread).toHaveBeenCalledWith("thread-2");
1041 });
1042​
1043 it("renders context handoffs as from → to model endpoints instead of the summary", async () => {
1044 const provider = (instanceId: string, driver: string, slug: string, name: string) => ({
1045 instanceId,
1046 driver,
1047 enabled: true,
1048 installed: true,
1049 version: null,
1050 status: "ready",
1051 auth: {},
1052 checkedAt: CREATED_AT,
1053 models: [{ slug, name, isCustom: false, capabilities: null }],
1054 slashCommands: [],
1055 skills: [],
1056 });
1057 const providers = [
1058 provider("codex_personal", "codex", "gpt-5.6-sol", "GPT 5.6 Sol"),
1059 provider("claudeAgent", "claudeAgent", "claude-fable-5", "Claude Fable 5"),
1060 ] as never;
1061 const handoff = (fields: Record<string, unknown>) =>
1062 ({
1063 id: "handoff-1",
1064 kind: "event",
1065 createdAt: CREATED_AT,
1066 projectedItem: v2Item("handoff", {
1067 id: "handoff-1",
1068 runId: "run-2",
1069 title: "Provider handoff",
1070 contextHandoffId: "handoff-1",
1071 fromProviderThreadIds: ["provider-thread-1"],
1072 toProviderThreadId: "provider-thread-2",
1073 strategy: "full_thread_summary",
1074 summary: "Full conversation context for provider handoff.",
1075 fromProviderInstanceIds: ["codex_personal"],
1076 toProviderInstanceId: "claudeAgent",
1077 ...fields,
1078 }),
1079 }) as Entry;
1080 const show = async (entry: Entry, props: Partial<TimelineProps> = {}) => {
1081 for (const root of roots.splice(0)) await act(async () => root.unmount());
1082 await renderElement(
1083 <RegistryProvider
1084 initialValues={[[serverEnvironment.providersValueAtom(ENVIRONMENT_ID), providers]]}
1086 <MessagesTimeline {...baseProps()} timelineEntries={[entry]} {...props} />
1087 </RegistryProvider>,
1088 );
1089 };
1090​
1091 await show(
1092 handoff({
1093 fromModelSelections: [{ instanceId: "codex_personal", model: "gpt-5.6-sol" }],
1094 toModel: "claude-fable-5",
1095 }),
1096 );
1097 expect(text()).toContain("Context handoff");
1098 expect(text()).toContain("GPT 5.6 Sol");
1099 expect(text()).toContain("Claude Fable 5");
1100 expect(text()).not.toContain("Full conversation context");
1101​
1102 await show(handoff({}), {
1103 runs: [
1105 id: "run-1",
1106 ordinal: 1,
1107 providerInstanceId: "codex_personal",
1108 modelSelection: { instanceId: "codex_personal", model: "gpt-5.6-sol" },
1109 },
1111 id: "run-2",
1112 ordinal: 2,
1113 providerInstanceId: "claudeAgent",
1114 modelSelection: { instanceId: "claudeAgent", model: "claude-fable-5" },
1115 },
1116 ] as never,
1117 });
1118 expect(text()).toContain("GPT 5.6 Sol");
1119 expect(text()).toContain("Claude Fable 5");
1120​
1121 await show(handoff({}));
1122 expect(text()).toContain("Codex Personal");
1123 expect(text()).not.toContain("Full conversation context");
1124 });
1125});
1126​
1127describe("MessagesTimeline subagents", () => {
1128 it.each(
1132 status: "running",
1133 progress: "Reading src/index.ts",
1134 result: null,
1135 preview: "Reading src/index.ts",
1136 },
1138 status: "completed",
1139 progress: "Reading src/index.ts",
1140 result: "Tests should be isolated.",
1141 preview: "Tests should be isolated.",
1142 },
1144 status: "running",
1145 progress: "Reading src/index.ts",
1146 result: "Partial streamed answer",
1147 preview: "Reading src/index.ts",
1148 },
1150 status: "running",
1151 progress: undefined,
1152 result: "Streaming answer so far",
1153 preview: "Streaming answer so far",
1154 },
1156 status: "cancelled",
1157 progress: "Reading src/index.ts",
1158 result: "Partial output before cancel",
1159 preview: "Partial output before cancel",
1160 },
1162 status: "completed",
1163 progress: "Audited 12 packages",
1164 result: " \n\t ",
1165 preview: "Audited 12 packages",
1166 },
1167 ] as const
1168 ).flatMap((scenario) => [1, 2].map((count) => ({ ...scenario, count }))),
1169 )(
1170 "shows $count $status subagents with '$preview', grouping only multiple agents",
1171 async ({ status, progress, result, preview, count }) => {
1172 const onOpenThread = vi.fn();
1173 await renderTimeline(
1174 Array.from(
1175 { length: count },
1176 (_, index) =>
1177 ({
1178 id: `subagent-progress-${index}`,
1179 kind: "event",
1180 createdAt: CREATED_AT,
1181 projectedItem: v2Item("subagent", {
1182 id: `subagent-progress-${index}`,
1183 nodeId: `node-subagent-${index}`,
1184 providerThreadId: "provider-thread-1",
1185 providerTurnId: "provider-turn-1",
1186 ordinal: 1,
1187 status,
1188 title: "Package audit",
1189 subagentId: `node-subagent-${index}`,
1190 origin: "provider_native",
1191 driver: "claudeAgent",
1192 providerInstanceId: "claudeAgent",
1193 childThreadId: "thread-subagent-1",
1194 prompt: "Inspect the package",
1195 progress,
1196 result,
1197 }),
1198 }) as Entry,
1199 ),
1200 { onOpenThread },
1201 );
1202 const children = () => buttons("Open Package audit");
1203 // A settled run folds its work behind a "Worked for" summary.
1204 const fold = buttons(/^Worked for/)[0];
1205 if (fold) await click(fold);
1206 if (count > 1) {
1207 expect(children()).toHaveLength(0);
1208 await click(button(`${count} subagents`));
1209 } else {
1210 expect(buttons(`${count} subagents`)).toHaveLength(0);
1212 expect(children()).toHaveLength(count);
1213 expect(text()).toContain(preview);
1214 expect(text()).not.toContain("Inspect the package");
1215 if (result?.trim() && result !== preview) expect(text()).not.toContain(result);
1216 if (progress && progress !== preview) expect(text()).not.toContain(progress);
1217 await click(children()[0]!);
1218 expect(onOpenThread).toHaveBeenCalledWith("thread-subagent-1");
1219 if (count > 1) {
1220 await click(button(`${count} subagents`));
1221 await vi.waitFor(() => expect(children()).toHaveLength(0));
1223 },
1224 );
1225});
1226​
1227describe("timeline tooltip scroll dismissal", () => {
1228 const openPopup = () =>
1229 document.querySelector('[data-slot="tooltip-popup"][data-open]')?.textContent ?? null;
1230​
1231 async function renderTooltip(pullRequest: boolean, outside: boolean) {
1232 const tooltip = pullRequest ? (
1233 <PullRequestLinkPreview
1234 link={<button>message link</button>}
1235 originalUrl="https://example.com"
1236 target={{
1237 environmentId: ENVIRONMENT_ID,
1238 input: { projectId: "project-1" as never, repository: "pingdotgg/t3code", number: 1 },
1239 }}
1240 />
1241 ) : (
1242 <Tooltip>
1243 <TooltipTrigger delay={50}>message link</TooltipTrigger>
1244 <TooltipPopup>https://example.com</TooltipPopup>
1245 </Tooltip>
1246 );
1247 await renderElement(
1248 <>
1249 <TooltipScrollDismissArea>
1250 <div data-testid="scrollable" className="h-[100px] overflow-auto">
1251 {outside ? null : tooltip}
1252 <div className="h-[1000px]" />
1253 </div>
1254 </TooltipScrollDismissArea>
1255 {outside ? tooltip : null}
1256 </>,
1257 );
1258 return {
1259 trigger: container.querySelector<HTMLButtonElement>("button")!,
1260 scrollable: container.querySelector<HTMLElement>('[data-testid="scrollable"]')!,
1261 };
1263​
1264 async function scroll(scrollable: HTMLElement) {
1265 await act(async () => {
1266 scrollable.scrollTop += 50;
1267 scrollable.dispatchEvent(new Event("scroll"));
1268 });
1270​
1271 it.each([false, true])(
1272 "closes a hovered tooltip on scroll but keeps a focused one (pull request=%s)",
1273 async (pullRequest) => {
1274 const { trigger, scrollable } = await renderTooltip(pullRequest, false);
1275 await userEvent.hover(trigger);
1276 await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1277 await scroll(scrollable);
1278 await vi.waitFor(() => expect(openPopup()).toBeNull());
1279​
1280 await userEvent.unhover(trigger);
1281 await userEvent.keyboard("{Tab}");
1282 expect(document.activeElement).toBe(trigger);
1283 await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1284 await scroll(scrollable);
1285 expect(openPopup()).toBe("https://example.com");
1286 expect(document.activeElement).toBe(trigger);
1287 },
1288 );
1289​
1290 it("leaves tooltips outside the timeline open when it scrolls", async () => {
1291 const { trigger, scrollable } = await renderTooltip(false, true);
1292 await userEvent.hover(trigger);
1293 await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1294 await scroll(scrollable);
1295 expect(openPopup()).toBe("https://example.com");
1296 });
1297​
1298 it("keeps a hovered tooltip open on a wheel that does not scroll", async () => {
1299 const { trigger, scrollable } = await renderTooltip(false, false);
1300 await userEvent.hover(trigger);
1301 await vi.waitFor(() => expect(openPopup()).toBe("https://example.com"));
1302 await act(async () => {
1303 scrollable.dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: 100 }));
1304 });
1305 expect(openPopup()).toBe("https://example.com");
1306 });
1307});
1308​
1309describe("MessagesTimeline scroll position", () => {
1310 const tall = (index: number) =>
1311 message(
1312 `Message ${index}\n\n${"Long paragraph. ".repeat(80)}`,
1313 { role: "assistant" },
1314 `message-${index}`,
1315 );
1316 const tallEntries = Array.from({ length: 12 }, (_, index) => tall(index));
1317​
1318 async function waitForList(props: ReturnType<typeof baseProps>) {
1319 await vi.waitFor(() => {
1320 const viewport = props.listRef.current?.getScrollableNode();
1321 expect(viewport?.scrollHeight ?? 0).toBeGreaterThan(viewport?.clientHeight ?? 0);
1322 });
1323 return props.listRef.current!.getScrollableNode()!;
1325​
1326 it("settles when earlier short replies load above long ones", async () => {
1327 const props = baseProps();
1328 const short = Array.from({ length: 80 }, (_, index) =>
1329 message(`Short reply ${index}`, { role: "assistant" }, `short-${index}`),
1330 );
1331 const long = Array.from({ length: 4 }, (_, index) =>
1332 message(
1333 `${"Long handbook paragraph. ".repeat(40)}\n\n`.repeat(60),
1334 { role: "assistant" },
1335 `long-${index}`,
1336 ),
1337 );
1338 let nestedCommits = 0;
1339 let maxNestedCommits = 0;
1340 const onRender = (_id: string, phase: string) => {
1341 nestedCommits = phase === "nested-update" ? nestedCommits + 1 : 0;
1342 maxNestedCommits = Math.max(maxNestedCommits, nestedCommits);
1343 };
1344 const timeline = (entries: Entry[]) => (
1345 <Profiler id="timeline" onRender={onRender}>
1346 <MessagesTimeline {...props} timelineEntries={entries} />
1347 </Profiler>
1348 );
1349 await renderElement(timeline(long));
1350 const viewport = await waitForList(props);
1351 await act(async () => {
1352 viewport.scrollTop = 0;
1353 viewport.dispatchEvent(new Event("scroll"));
1354 });
1355​
1356 maxNestedCommits = 0;
1357 await act(async () => roots.at(-1)!.render(timeline([...short, ...long])));
1358 await vi.waitFor(async () => {
1359 await act(async () => {
1360 viewport.scrollTop = 0;
1361 viewport.dispatchEvent(new Event("scroll"));
1362 });
1363 expect(text()).toContain("Short reply 0");
1364 });
1365 expect(maxNestedCommits).toBeLessThan(8);
1366 });
1367​
1368 it("restores a manual reading position after reopening and switching threads", async () => {
1369 const props = baseProps();
1370 function Chat() {
1371 const [liveFollowEnabled, setLiveFollowEnabled] = useState(true);
1372 // The chat view stops following the live edge when the reader scrolls.
1373 return (
1374 <div className="contents" onWheelCapture={() => setLiveFollowEnabled(false)}>
1375 <MessagesTimeline
1376 {...props}
1377 timelineEntries={tallEntries}
1378 liveFollowEnabled={liveFollowEnabled}
1379 />
1380 </div>
1381 );
1383 await renderElement(<Chat />);
1384 const viewport = await waitForList(props);
1385 await vi.waitFor(() => expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(true));
1386​
1387 await userEvent.wheel(viewport, { delta: { y: -600 } });
1388 await vi.waitFor(() => expect(readTimelinePosition(props.routeThreadKey)?.atEnd).toBe(false));
1389 const offset = viewport.scrollTop;
1390 await act(async () => roots.pop()!.unmount());
1391 expect(readTimelinePosition(props.routeThreadKey)).toMatchObject({
1392 atEnd: false,
1393 scrollOffset: offset,
1394 });
1395​
1396 const timeline = (routeThreadKey: string) => (
1397 <MessagesTimeline {...props} routeThreadKey={routeThreadKey} timelineEntries={tallEntries} />
1398 );
1399 await renderElement(timeline(props.routeThreadKey));
1400 const reopenedViewport = await waitForList(props);
1401 await vi.waitFor(() =>
1402 expect(Math.abs(reopenedViewport.scrollTop - offset)).toBeLessThanOrEqual(1),
1403 );
1404​
1405 await act(async () => roots.at(-1)!.render(timeline(`${props.routeThreadKey}-other`)));
1406 await vi.waitFor(() =>
1407 expect(
1408 reopenedViewport.scrollHeight - reopenedViewport.clientHeight - reopenedViewport.scrollTop,
1409 ).toBeLessThanOrEqual(1),
1410 );
1411 await act(async () => roots.at(-1)!.render(timeline(props.routeThreadKey)));
1412 await vi.waitFor(() =>
1413 expect(Math.abs(reopenedViewport.scrollTop - offset)).toBeLessThanOrEqual(1),
1414 );
1415 });
1416​
1417 it("restores the composer after closing tool output only at the end", async () => {
1418 const props = baseProps();
1419 function Thread() {
1420 const composer = useComposerFocusState();
1421 return (
1422 <>
1423 <button onClick={() => composer.setIsComposerScrollCollapsed(true)}>Collapse</button>
1424 <output>{composer.isComposerScrollCollapsed ? "collapsed" : "resting"}</output>
1425 <MessagesTimeline
1426 {...props}
1427 onToolOutputCollapsedAtEnd={composer.restoreAfterTimelineReachedEnd}
1428 timelineEntries={[
1429 ...tallEntries,
1430 work("tool", {
1431 label: "Run command",
1432 tone: "tool",
1433 toolLifecycleStatus: "completed",
1434 detail: "Command output",
1435 }),
1436 ]}
1437 />
1438 </>
1439 );
1441 await renderElement(<Thread />);
1442 const composerState = () => container.querySelector("output")!.textContent;
1443 const viewport = await waitForList(props);
1444 await click(button("Collapse"));
1445 const toggle = () => button("Command output");
1446 await click(toggle());
1447 await click(toggle());
1448 await vi.waitFor(() => expect(composerState()).toBe("resting"));
1449​
1450 await click(button("Collapse"));
1451 await userEvent.wheel(viewport, { delta: { y: -2000 } });
1452 await click(toggle());
1453 await click(toggle());
1454 await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
1455 expect(composerState()).toBe("collapsed");
1456 });
1457});
1458​
1459describe("MessagesTimeline send anchor", () => {
1460 it("reports the anchored sent message once it is laid out", async () => {
1461 const onAnchorReady = vi.fn();
1462 const sent = message("Newest prompt.", {}, "message-2");
1463 await renderTimeline([message("Earlier reply.", { role: "assistant" }), sent], {
1464 anchorMessageId: MessageId.make("message-2"),
1465 onAnchorReady,
1466 contentInsetEndAdjustment: 144,
1467 });
1468 await vi.waitFor(() =>
1469 expect(onAnchorReady).toHaveBeenCalledWith(MessageId.make("message-2"), 1),
1470 );
1471 });
1472​
1473 it("does not anchor a follow-up user message that is not the newest turn", async () => {
1474 const onAnchorReady = vi.fn();
1475 await renderTimeline([message("First prompt."), message("Newest prompt.", {}, "message-2")], {
1476 anchorMessageId: MessageId.make("message-2"),
1477 onAnchorReady,
1478 });
1479 await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
1480 expect(onAnchorReady).not.toHaveBeenCalled();
1481 });
1482});