Open History to see the last commit
1import { AudioPreview } from "../files/AudioPreview";
2import { onTestFinished } from "vite-plus/test";
3import { stubGlobal } from "../../../test/render";
4import {
5 EnvironmentId,
6 MessageId,
7 RunAttemptId,
8 RunId,
9 ScheduledTaskId,
10 ThreadId,
11} from "@t3tools/contracts";
12import type { LegendListRef } from "@legendapp/list/react";
13import { createRef, Profiler, StrictMode, type ComponentProps, type ReactElement } from "react";
14import { describe, expect, it, vi } from "vite-plus/test";
15
16import "~/index.css";
17
18import { act, fakeTimers, render } from "../../../test/render";
19import { MessagesTimeline } from "./MessagesTimeline";
20import { makeStreamingTimelineFixture } from "../../test-fixtures";
21import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic";
22import { remarkThoughtPreview } from "./TimelineWorkEntryRow.logic";
23import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
24import { collectThreadFindRanges } from "./threadFindHighlights";
25import { toastManager } from "../ui/toast";
26import type { CitedHistory } from "./citationProcedure";
27import type { TimelineNavigation } from "./timelineViewport";
28import { rememberTimelinePosition } from "./timelineScrollAnchoring";
29
30const environmentQuery = vi.hoisted(() => ({
31 error: "Pull request not found",
32 data: null as unknown,
33}));
34vi.mock(import("~/state/query"), async (original) => ({
35 ...(await original()),
36 useEnvironmentQuery: (() => ({
37 data: environmentQuery.data,
38 dataUpdatedAt: 0,
39 error: environmentQuery.error,
40 failure: null,
41 isPending: false,
42 isSuccess: false,
43 refresh: () => {},
44 })) as never,
45}));
46
47const audioAsset = vi.hoisted(() => ({ url: "" }));
48vi.mock(import("~/assets/assetUrls"), async (original) => {
49 const actual = await original();
50 return {
51 ...actual,
52 useAssetUrlState: ((...args: Parameters<typeof actual.useAssetUrlState>) =>
53 audioAsset.url
54 ? { _tag: "Success", url: audioAsset.url }
55 : actual.useAssetUrlState(...args)) as typeof actual.useAssetUrlState,
56 };
57});
58
59const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
60const CREATED_AT = "2026-03-17T19:12:28.000Z";
61
62type TimelineProps = ComponentProps<typeof MessagesTimeline>;
63type Entry = TimelineProps["timelineEntries"][number];
64
65// The timeline remembers scroll position and open disclosures per thread key,
66// so every render gets a fresh thread.
67function baseProps(): Omit<TimelineProps, "timelineEntries"> {
68 return {
69 isWorking: false,
70 activeTurnInProgress: false,
71 listRef: createRef<LegendListRef | null>(),
72 latestRun: null,
73 turnDiffSummaries: [],
74 runs: [],
75 routeThreadKey: `environment-local:thread-${Math.random().toString(36).slice(2)}`,
76 onOpenTurnDiff: () => {},
77 onOpenThread: () => {},
78 onForkFromRun: async () => {},
79 onRollbackCheckpoint: () => {},
80 supportsConversationRollback: false,
81 onRevertToTurnCount: () => {},
82 isRevertingCheckpoint: false,
83 onImageExpand: () => {},
84 activeThreadEnvironmentId: ENVIRONMENT_ID,
85 markdownCwd: undefined,
86 resolvedTheme: "light",
87 timestampFormat: "locale",
88 workspaceRoot: undefined,
89 anchorMessageId: null,
90 onAnchorReady: () => {},
91 onAnchorSizeChanged: () => {},
92 contentInsetEndAdjustment: 0,
93 emptyPlaceholderInset: 0,
94 liveFollowEnabled: true,
95 onIsAtEndChange: () => {},
96 };
97}
98
99function message(
100 text: string,
101 overrides: Partial<Extract<Entry, { kind: "message" }>["message"]> = {},
102 id = "message-1",
103): Entry {
104 return {
105 id: `entry-${id}`,
106 kind: "message",
107 createdAt: CREATED_AT,
108 message: {
109 id: MessageId.make(id),
110 role: "user",
111 text,
112 runId: null,
113 createdAt: CREATED_AT,
114 updatedAt: CREATED_AT,
115 streaming: false,
116 ...overrides,
117 },
118 };
119}
120
121async function renderElement(element: ReactElement, options: { router?: false } = {}) {
122 const container = document.createElement("div");
123 container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
124 const screen = await render(element, { container, ...options });
125 const buttons = (name: string | RegExp) =>
126 [...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => {
127 const label = button.getAttribute("aria-label") ?? button.textContent ?? "";
128 return typeof name === "string" ? label === name : name.test(label);
129 });
130 return Object.assign(screen, {
131 text: () => container.textContent ?? "",
132 buttons,
133 button: (name: string | RegExp) => {
134 const [match] = buttons(name);
135 if (!match) throw new Error(`Missing button: ${String(name)}`);
136 return match;
137 },
138 });
139}
140
141function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelineProps> = {}) {
142 return renderElement(
143 <MessagesTimeline {...baseProps()} timelineEntries={entries as Entry[]} {...props} />,
144 );
145}
146
147async function click(element: HTMLElement) {
148 await act(async () => element.click());
149}
150
151function setup({ scheduledTasks = [] as ReadonlyArray<{ id: string; title: string }> } = {}) {
152 environmentQuery.data = { tasks: scheduledTasks };
153}
154
155const TASK_ID = ScheduledTaskId.make("task-1");
156const AUTOMATION_PROMPT = "Triage the inbox\n\nLabel every new issue and close duplicates.";
157
158describe("MessagesTimeline messages", () => {
159 it("settles when equally long messages have very different rendered heights", async () => {
160 const props = baseProps();
161 const tall = message("a\n\n".repeat(6000), { role: "assistant" }, "tall");
162 const earlier = Array.from({ length: 80 }, (_, index) =>
163 message(
164 `<details><summary>Reply ${index}</summary>${"compact ".repeat(2250)}</details>`,
165 { role: "assistant" },
166 `earlier-${index}`,
167 ),
168 );
169 let nestedCommits = 0;
170 let maxNestedCommits = 0;
171 const onRender = (_id: string, phase: string) => {
172 nestedCommits = phase === "nested-update" ? nestedCommits + 1 : 0;
173 maxNestedCommits = Math.max(maxNestedCommits, nestedCommits);
174 };
175 const timeline = (entries: Entry[]) => (
176 <Profiler id="timeline" onRender={onRender}>
177 <MessagesTimeline {...props} timelineEntries={entries} />
178 </Profiler>
179 );
180 await using screen = await renderElement(timeline([tall]));
181 await vi.waitFor(() =>
182 expect(props.listRef.current?.getState().sizeAtIndex(0)).toBeGreaterThan(100_000),
183 );
184 const viewport = props.listRef.current!.getScrollableNode()!;
185 await act(() => {
186 viewport.scrollTop = 0;
187 viewport.dispatchEvent(new Event("scroll"));
188 });
189 await screen.rerender(timeline([...earlier, tall]));
190 await act(() => {
191 void props.listRef.current!.scrollToIndex({ index: 0, animated: false });
192 });
193 await vi.waitFor(async () => {
194 await act(() => {
195 viewport.scrollTop = 0;
196 viewport.dispatchEvent(new Event("scroll"));
197 });
198 expect(screen.text().includes("Reply 0")).toBe(true);
199 expect(props.listRef.current!.getState().sizeAtIndex(0)).toBeGreaterThan(0);
200 });
201 expect(maxNestedCommits).toBeLessThan(20);
202 });
203
204 it("keeps the first and last message headings reachable from either end", async () => {
205 setup();
206 const props = baseProps();
207 // Folded messages at both ends: their headings must not live inside the fold.
208 const entries = Array.from({ length: 120 }, (_, index) =>
209 index === 0
210 ? message("First turn", { scheduledTaskId: TASK_ID }, "turn-0")
211 : index === 119
212 ? message(
213 "Last turn",
214 { createdBy: "agent", senderThreadId: ThreadId.make("thread-sender") },
215 "turn-119",
216 )
217 : message(
218 `Turn ${index}:\n\n${"x ".repeat(200)}`,
219 { role: index % 2 === 0 ? "user" : "assistant" },
220 `turn-${index}`,
221 ),
222 );
223 await using screen = await renderElement(
224 <MessagesTimeline {...props} timelineEntries={entries} />,
225 );
226 const headings = () => [...screen.container.querySelectorAll("h3")];
227 const headingFor = (text: string) =>
228 headings().find((heading) => heading.parentElement?.textContent?.includes(text));
229 const viewport = props.listRef.current!.getScrollableNode()!;
230 // A screen reader scrolls the heading it moves to into view.
231 const expectHeadingInView = async (text: string, neighbour: string) => {
232 await act(() => headingFor(text)!.scrollIntoView({ block: "start" }));
233 await vi.waitFor(() => expect(screen.text()).toContain(neighbour));
234 const row = headingFor(text)!.parentElement!.getBoundingClientRect();
235 const view = viewport.getBoundingClientRect();
236 expect(row.top).toBeLessThan(view.bottom);
237 expect(row.bottom).toBeGreaterThan(view.top);
238 };
239
240 await vi.waitFor(() => expect(screen.text()).toContain("Turn 118:"));
241 expect(screen.text()).not.toContain("Turn 60:");
242 // Wrapping follows DOM order, so the ends must also sit first and last.
243 await vi.waitFor(() => {
244 expect(headings()[0]).toBe(headingFor("First turn"));
245 expect(headings().at(-1)).toBe(headingFor("Last turn"));
246 });
247
248 await expectHeadingInView("First turn", "Turn 1:");
249 expect(headingFor("Last turn")).toBeDefined();
250 await expectHeadingInView("Last turn", "Turn 118:");
251 });
252
253 it("keeps rows in item order after a reload or thread switch, before any timer runs", async () => {
254 setup();
255 // NVDA's browse mode keeps the first DOM order it reads, so a timer that sorts rows later is too late.
256 using _timers = fakeTimers();
257 const thread = (name: string) =>
258 Array.from({ length: 120 }, (_, index) =>
259 message(
260 `${name} turn ${index}:\n\n${"x ".repeat(200)}`,
261 { role: index % 2 === 0 ? "user" : "assistant" },
262 `${name}-${index}`,
263 ),
264 );
265 const props = baseProps();
266 await using screen = await renderElement(
267 <MessagesTimeline {...props} timelineEntries={thread("A")} />,
268 );
269 const turnsInDomOrder = () =>
270 [...screen.container.querySelectorAll("h3")].map((heading) =>
271 Number(/turn (\d+):/.exec(heading.parentElement?.textContent ?? "")?.[1]),
272 );
273 const expectItemOrder = () => {
274 const turns = turnsInDomOrder();
275 expect(turns).toEqual(turns.toSorted((a, b) => a - b));
276 };
277
278 expect(screen.text()).toContain("A turn 118:");
279 expect(turnsInDomOrder()).toContain(0);
280 expectItemOrder();
281
282 await screen.rerender(
283 <MessagesTimeline
284 {...props}
285 routeThreadKey={`${props.routeThreadKey}-other`}
286 timelineEntries={thread("B")}
287 />,
288 );
289 expect(screen.text()).toContain("B turn 118:");
290 expect(screen.text()).not.toContain("A turn");
291 expectItemOrder();
292 });
293
294 it("puts rows back in item order soon after a continuous scroll stops", async () => {
295 setup();
296 const props = baseProps();
297 await using screen = await renderElement(
298 <MessagesTimeline
299 {...props}
300 timelineEntries={Array.from({ length: 120 }, (_, index) =>
301 message(
302 `Turn ${index}:\n\n${"x ".repeat(200)}`,
303 { role: index % 2 === 0 ? "user" : "assistant" },
304 `turn-${index}`,
305 ),
306 )}
307 />,
308 );
309 await vi.waitFor(() => expect(screen.text()).toContain("Turn 118:"));
310 using _timers = fakeTimers();
311 const turnsInDomOrder = () =>
312 [...screen.container.querySelectorAll("h3")].map((heading) =>
313 Number(/Turn (\d+):/.exec(heading.parentElement?.textContent ?? "")?.[1]),
314 );
315 const viewport = props.listRef.current!.getScrollableNode()!;
316
317 const scroll = async (by: number) => {
318 for (let step = 0; step < 40; step++) {
319 await act(() => {
320 viewport.scrollTop += by;
321 viewport.dispatchEvent(new Event("scroll"));
322 vi.advanceTimersByTime(16);
323 });
324 }
325 // Wrapping right after a scroll must still reach the first and last message.
326 expect(turnsInDomOrder()[0]).toBe(0);
327 expect(turnsInDomOrder().at(-1)).toBe(119);
328 };
329
330 await act(() => {
331 viewport.scrollTop = 0;
332 viewport.dispatchEvent(new Event("scroll"));
333 vi.advanceTimersByTime(300);
334 });
335 await scroll(300);
336 expect(turnsInDomOrder().filter((turn) => turn > 0 && turn < 100).length).toBeGreaterThan(0);
337 await scroll(-300);
338
339 await act(() => vi.advanceTimersByTime(300));
340 const turns = turnsInDomOrder();
341 expect(turns).toEqual(turns.toSorted((a, b) => a - b));
342 });
343
344 it("preserves XML-like tags and comparisons in user messages as text", async () => {
345 const source = [
346 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
347 'Before <nested data-value="a&b">inside</nested> after',
348 "</global-agent-instructions> in your context?",
349 "Comparison: 2 < 3 and 5 > 4.",
350 ];
351 await using screen = await renderTimeline([message(source.join("\n"))]);
352 for (const line of source) expect(screen.text()).toContain(line);
353 expect(screen.container.querySelector("global-agent-instructions, nested")).toBeNull();
354 });
355
356 it("renders unsafe user HTML as inert source text", async () => {
357 const source =
358 '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">';
359 await using screen = await renderTimeline([message(source)]);
360 expect(screen.text()).toContain(source);
361 expect(screen.container.querySelector("script, img")).toBeNull();
362 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
363 });
364
365 it("renders sanitized raw HTML in assistant messages", async () => {
366 await using screen = await renderTimeline([
367 message(
368 [
369 '<details onclick="globalThis.__t3Xss = 1">',
370 "<summary>Safe details</summary>",
371 "<script>globalThis.__t3Xss = 2</script>",
372 '<img src="x" onerror="globalThis.__t3Xss = 3">',
373 '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
374 "</details>",
375 ].join(""),
376 { role: "assistant" },
377 ),
378 ]);
379 expect(screen.container.querySelector("[data-markdown-details]")?.textContent).toContain(
380 "Safe details",
381 );
382 expect(screen.text()).not.toContain("<details");
383 expect(screen.container.querySelector("script, [onclick], [onerror]")).toBeNull();
384 expect(screen.container.innerHTML).not.toContain("javascript:");
385 await click(screen.button("Safe details"));
386 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
387 });
388});
389
390const CITATION_REQUEST = {
391 key: "activation-1",
392 citation: {
393 version: 1,
394 environmentId: ENVIRONMENT_ID,
395 threadId: ThreadId.make("thread-cited"),
396 messageId: MessageId.make("cited"),
397 text: "the cited answer",
398 start: 0,
399 end: 16,
400 prefix: "",
401 suffix: "",
402 },
403} satisfies NonNullable<TimelineProps["citationRequest"]>;
404
405describe("MessagesTimeline citations", () => {
406 it("lands a citation present at mount under StrictMode", async () => {
407 await using _screen = await renderElement(
408 <StrictMode>
409 <MessagesTimeline
410 {...baseProps()}
411 timelineEntries={[
412 message("A question", {}, "question"),
413 message("the cited answer", { role: "assistant" }, "cited"),
414 ]}
415 citationRequest={CITATION_REQUEST}
416 citationHistory={{ _tag: "found" }}
417 />
418 </StrictMode>,
419 // The test router mounts route content without StrictMode's effect replay.
420 { router: false },
421 );
422 // StrictMode replays effect cleanups on mount; the activation must survive them.
423 await vi.waitFor(() =>
424 expect(document.querySelector("[data-citation-highlighted]")?.textContent).toContain(
425 "the cited answer",
426 ),
427 );
428 });
429
430 it("opens the superseded attempt that folds the cited response", async () => {
431 const runId = RunId.make("run-steered");
432 const attempt = (id: string, ordinal: number, status: "superseded" | "running") => ({
433 id: RunAttemptId.make(id),
434 runId,
435 attemptOrdinal: ordinal,
436 rootNodeId: `node-${id}` as never,
437 status,
438 completedAt: null,
439 });
440 const superseded = attempt("attempt-1", 1, "superseded");
441 const active = attempt("attempt-2", 2, "running");
442 const inAttempt = (entry: Entry, entryAttempt: typeof superseded): Entry => ({
443 ...entry,
444 attempt: entryAttempt,
445 });
446 await using _screen = await renderTimeline(
447 [
448 inAttempt(message("Build it", { runId }, "question"), superseded),
449 inAttempt(message("the cited answer", { role: "assistant", runId }, "cited"), superseded),
450 inAttempt(message("Change direction", { runId }, "steer"), active),
451 inAttempt(message("Current response", { role: "assistant", runId }, "current"), active),
452 ],
453 {
454 latestRun: { runId, status: "running", startedAt: CREATED_AT, completedAt: null },
455 citationRequest: CITATION_REQUEST,
456 citationHistory: { _tag: "found" },
457 },
458 );
459 await vi.waitFor(() =>
460 expect(document.querySelector("[data-citation-highlighted]")?.textContent).toContain(
461 "the cited answer",
462 ),
463 );
464 });
465
466 it("waits for cited history to load before giving up on a response outside the window", async () => {
467 using toast = vi.spyOn(toastManager, "add");
468 const props = baseProps();
469 const citationRequest = CITATION_REQUEST;
470 const recent = message("A recent question", {}, "recent");
471 const timeline = (entries: Entry[], citationHistory: CitedHistory) => (
472 <MessagesTimeline
473 {...props}
474 timelineEntries={entries}
475 citationRequest={citationRequest}
476 citationHistory={citationHistory}
477 />
478 );
479 await using screen = await renderElement(timeline([recent], { _tag: "loading" }));
480 await expect.element(screen.getByText("A recent question")).toBeVisible();
481
482 await screen.rerender(
483 timeline([message("the cited answer", { role: "assistant" }, "cited"), recent], {
484 _tag: "found",
485 }),
486 );
487 await expect.element(screen.getByText("the cited answer")).toBeVisible();
488 expect(toast).not.toHaveBeenCalled();
489 });
490});
491
492describe("MessagesTimeline automation prompts", () => {
493 it("folds an automation prompt into a bubble titled by its task", async () => {
494 setup({ scheduledTasks: [{ id: TASK_ID, title: "Nightly triage" }] });
495 await using screen = await renderTimeline([
496 message(AUTOMATION_PROMPT, { scheduledTaskId: TASK_ID }),
497 ]);
498 const row = screen.button(/^Automation/);
499 expect(row.textContent).toContain("Nightly triage");
500 expect(row.getAttribute("aria-expanded")).toBe("false");
501 expect(screen.text()).not.toContain("close duplicates");
502
503 await click(row);
504 expect(screen.text()).toContain("Label every new issue and close duplicates.");
505 const link = [...screen.container.querySelectorAll("a")].find(
506 (anchor) => anchor.textContent === "Open automation",
507 );
508 expect(link?.getAttribute("href")).toContain(`taskId=${TASK_ID}`);
509 expect(screen.buttons(/copy/i)).not.toHaveLength(0);
510 });
511
512 it("falls back to the prompt's first line without a task title", async () => {
513 setup();
514 await using screen = await renderTimeline([
515 message(AUTOMATION_PROMPT, { scheduledTaskId: TASK_ID }),
516 ]);
517 expect(screen.button(/^Automation/).textContent).toContain("Triage the inbox");
518 });
519
520 it("leaves ordinary user messages as full bubbles", async () => {
521 setup();
522 await using screen = await renderTimeline([message(AUTOMATION_PROMPT)]);
523 expect(screen.buttons(/^Automation/)).toHaveLength(0);
524 expect(screen.text()).toContain("Label every new issue and close duplicates.");
525 });
526
527 it("reveals a find match beyond the folded automation prompt's initial viewport", async () => {
528 setup();
529 const prompt = `${"Inspect the next item.\n\n".repeat(16)}Close duplicates.`;
530 await using screen = await renderTimeline([message(prompt, { scheduledTaskId: TASK_ID })], {
531 findExpanded: true,
532 findQuery: "duplicates",
533 activeFindMatch: { entryId: "entry-message-1", runId: null, occurrence: 0 },
534 });
535 await vi.waitFor(() =>
536 expect(screen.button(/^Automation/).getAttribute("aria-expanded")).toBe("true"),
537 );
538 const { range } = collectThreadFindRanges(screen.container, "duplicates")[0]!;
539 const details = screen.container.querySelector("[data-thread-find-text]")!;
540 expect(range.getBoundingClientRect().top - details.getBoundingClientRect().top).toBeGreaterThan(
541 384,
542 );
543 expect(range.getBoundingClientRect().bottom).toBeLessThanOrEqual(
544 details.getBoundingClientRect().bottom,
545 );
546 });
547
548 it("shows edit-from-here once an automation prompt is expanded", async () => {
549 setup();
550 const runId = RunId.make("run-1");
551 await using screen = await renderTimeline(
552 [
553 message(
554 AUTOMATION_PROMPT,
555 { scheduledTaskId: TASK_ID, runId, inputIntent: "turn_start" },
556 "user-1",
557 ),
558 message("Done", { role: "assistant", runId }, "assistant-1"),
559 ],
560 {
561 supportsConversationRollback: true,
562 threadStartCheckpointReady: true,
563 turnDiffSummaries: [
564 {
565 runId,
566 checkpointTurnCount: 1,
567 checkpointRef: "checkpoint-1" as never,
568 status: "ready",
569 files: [],
570 assistantMessageId: MessageId.make("assistant-1"),
571 completedAt: CREATED_AT,
572 },
573 ],
574 },
575 );
576 expect(screen.buttons("Edit from here")).toHaveLength(0);
577 await click(screen.button(/^Automation/));
578 expect(screen.buttons("Edit from here")).toHaveLength(1);
579 });
580});
581
582const SENDER_THREAD_ID = ThreadId.make("thread-sender");
583const AGENT_MESSAGE = "Review finished\n\nThe migration drops the index before backfilling it.";
584
585describe("MessagesTimeline agent messages", () => {
586 it("folds a message from another agent into a one-line preview", async () => {
587 setup();
588 const onOpenThread = vi.fn();
589 await using screen = await renderTimeline(
590 [message(AGENT_MESSAGE, { createdBy: "agent", senderThreadId: SENDER_THREAD_ID })],
591 { onOpenThread },
592 );
593 const row = screen.button(/^Agent/);
594 expect(row.textContent).toContain("Review finished");
595 expect(row.getAttribute("aria-expanded")).toBe("false");
596 expect(screen.text()).not.toContain("drops the index");
597 expect(screen.buttons("Open thread")).toHaveLength(0);
598
599 await click(row);
600 expect(screen.text()).toContain("The migration drops the index before backfilling it.");
601 await click(screen.button("Open thread"));
602 expect(onOpenThread).toHaveBeenCalledWith(SENDER_THREAD_ID);
603
604 await click(screen.button(/^Agent/));
605 expect(screen.text()).not.toContain("drops the index");
606 });
607
608 it("leaves messages sent by T3 Code as full bubbles", async () => {
609 setup();
610 await using screen = await renderTimeline([
611 message(AGENT_MESSAGE, { createdBy: "agent", creationSource: "server" }),
612 ]);
613 expect(screen.buttons(/^Agent/)).toHaveLength(0);
614 expect(screen.text()).toContain("drops the index");
615 });
616
617 it("reveals a find match inside a folded agent message", async () => {
618 setup();
619 const text = `${"Checked the next file.\n\n".repeat(16)}The migration drops the index.`;
620 await using screen = await renderTimeline(
621 [message(text, { createdBy: "agent", senderThreadId: SENDER_THREAD_ID })],
622 {
623 findExpanded: true,
624 findQuery: "drops the index",
625 activeFindMatch: { entryId: "entry-message-1", runId: null, occurrence: 0 },
626 },
627 );
628 await vi.waitFor(() =>
629 expect(screen.button(/^Agent/).getAttribute("aria-expanded")).toBe("true"),
630 );
631 const { range } = collectThreadFindRanges(screen.container, "drops the index")[0]!;
632 const body = screen.container.querySelector("[data-user-message-body]")!;
633 expect(range.getBoundingClientRect().height).toBeGreaterThan(0);
634 expect(range.getBoundingClientRect().bottom).toBeLessThanOrEqual(
635 body.getBoundingClientRect().bottom,
636 );
637 });
638});
639
640describe("MessagesTimeline attachments", () => {
641 it.each(["loadedmetadata", "loadeddata", "canplay"])(
642 "plays audio with unknown duration after %s and updates the total later",
643 async (readyEvent) => {
644 const onOpen = vi.fn();
645 const preview = (failed = false) => (
646 <AudioPreview
647 compact
648 src="data:audio/webm;base64,"
649 name="recording.webm"
650 failed={failed}
651 onOpen={onOpen}
652 />
653 );
654 await using screen = await renderElement(preview());
655 const audio = screen.container.querySelector("audio")!;
656 const duration = vi.spyOn(audio, "duration", "get").mockReturnValue(Infinity);
657 const play = vi.spyOn(audio, "play").mockResolvedValue();
658 expect(screen.button("Loading recording.webm")).toHaveProperty("disabled", true);
659 await act(() => audio.dispatchEvent(new Event(readyEvent)));
660 expect(screen.button("Play recording.webm")).toHaveProperty("disabled", false);
661 expect(screen.text()).toContain("0:00");
662 expect(screen.text()).not.toContain("/");
663 await click(screen.button("Play recording.webm"));
664 expect(play).toHaveBeenCalledOnce();
665 await act(() => {
666 vi.spyOn(audio, "currentTime", "get").mockReturnValue(3);
667 audio.dispatchEvent(new Event("play"));
668 audio.dispatchEvent(new Event("timeupdate"));
669 });
670 expect(screen.button("Pause recording.webm")).toHaveProperty("disabled", false);
671 expect(screen.text()).toContain("0:03");
672 const progress = screen.container.querySelector<HTMLElement>("span[aria-hidden]")!;
673 expect(progress.style.width).toBe("0%");
674 await act(() => {
675 duration.mockReturnValue(10);
676 audio.dispatchEvent(new Event("durationchange"));
677 });
678 expect(screen.text()).toContain("0:03 / 0:10");
679 expect(progress.style.width).toBe("30%");
680 await act(() => {
681 duration.mockReturnValue(NaN);
682 audio.dispatchEvent(new Event("durationchange"));
683 });
684 expect(screen.text()).not.toContain("/");
685 expect(progress.style.width).toBe("0%");
686 expect(screen.button("Pause recording.webm")).toHaveProperty("disabled", false);
687 await screen.rerender(preview(true));
688 expect(screen.text()).toContain("Unavailable");
689 await click(screen.button("Audio unavailable. Open recording.webm"));
690 expect(onOpen).toHaveBeenCalledOnce();
691 },
692 );
693
694 it.each(["pause", "error"])("unpins audio after %s", async (event) => {
695 const NativeObserver = IntersectionObserver;
696 using _observer = stubGlobal(
697 "IntersectionObserver",
698 class extends NativeObserver {
699 constructor(
700 private readonly notify: IntersectionObserverCallback,
701 options?: IntersectionObserverInit,
702 ) {
703 super(notify, options);
704 }
705 override observe(target: Element) {
706 this.notify([{ target, isIntersecting: true } as IntersectionObserverEntry], this);
707 }
708 },
709 );
710 const src =
711 "data:audio/wav;base64,UklGRiUAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQEAAACA";
712 audioAsset.url = src;
713 onTestFinished(() => {
714 audioAsset.url = "";
715 });
716 const props = baseProps();
717 await using screen = await renderTimeline(
718 [
719 // The first message row is always mounted, so the recordings go in the second.
720 message("Start of the thread.", { role: "user" }, "opening"),
721 message(
722 "Two recordings.",
723 {
724 attachments: ["one", "two"].map((name) => ({
725 type: "file",
726 id: `attachment-${name}`,
727 name: `${name}.wav`,
728 mimeType: "audio/wav",
729 sizeBytes: 45,
730 previewUrl: src,
731 })),
732 },
733 "audio",
734 ),
735 ...Array.from({ length: 40 }, (_, index) =>
736 message("Conversation history. ".repeat(40), { role: "user" }, `history-${index}`),
737 ),
738 ],
739 props,
740 );
741 screen.container.style.height = "600px";
742 screen.container.scrollIntoView({ block: "start" });
743 await vi.waitFor(
744 async () => {
745 await act(() => {
746 void props.listRef.current?.scrollToIndex({ index: 1, animated: false });
747 });
748 expect(screen.container.querySelectorAll("audio")).toHaveLength(2);
749 },
750 { timeout: 5000 },
751 );
752 const [one, two] = [...screen.container.querySelectorAll("audio")];
753 await act(async () => {
754 vi.spyOn(one!, "paused", "get").mockReturnValue(false);
755 vi.spyOn(two!, "paused", "get").mockReturnValue(false);
756 one!.dispatchEvent(new Event("play"));
757 two!.dispatchEvent(new Event("play"));
758 });
759 await vi.waitFor(async () => {
760 await act(() => {
761 void props.listRef.current!.scrollToEnd({ animated: false });
762 });
763 const scroll = props.listRef.current!.getScrollableNode()!;
764 expect(scroll.scrollTop).toBeGreaterThan(5000);
765 });
766 expect(one!.isConnected).toBe(true);
767 expect(two!.isConnected).toBe(true);
768 await act(async () => {
769 vi.spyOn(one!, "paused", "get").mockReturnValue(true);
770 one!.dispatchEvent(new Event("pause"));
771 });
772 expect(two!.isConnected).toBe(true);
773 await act(async () => {
774 if (event === "pause") vi.spyOn(two!, "paused", "get").mockReturnValue(true);
775 two!.dispatchEvent(new Event(event));
776 });
777 await act(() => {
778 void props.listRef.current!.scrollToIndex({ index: 20, animated: false });
779 });
780 await vi.waitFor(() => expect(one!.isConnected).toBe(false));
781 });
782});
783
784describe("MessagesTimeline thread find", () => {
785 // Opening find is navigation; on a list already showing the thread the open
786 // action navigates, so the list itself releases follow only when it starts
787 // showing a thread whose find is already open.
788 function renderObserved() {
789 const navigations: TimelineNavigation[] = [];
790 const base = baseProps();
791 const element = (next: Partial<TimelineProps>) => (
792 <MessagesTimeline
793 {...base}
794 timelineEntries={[message("Where is the sidebar fix?")]}
795 onViewportAttach={(viewport) =>
796 viewport.subscribe((navigation) => navigations.push(navigation))
797 }
798 {...next}
799 />
800 );
801 return { navigations, element };
802 }
803 const released = { source: "command", releasesFollow: true };
804
805 it("releases follow once when it starts showing a thread whose find is open", async () => {
806 setup();
807 const { navigations, element } = renderObserved();
808 await using screen = await renderElement(element({}));
809 expect(navigations).toEqual([]);
810
811 const other = "environment-local:thread-find-open";
812 await screen.rerender(element({ routeThreadKey: other, findOpen: true }));
813 expect(navigations).toEqual([released]);
814 await screen.rerender(element({ routeThreadKey: other, findOpen: false }));
815 await screen.rerender(element({ routeThreadKey: other, findOpen: true }));
816 expect(navigations).toEqual([released]);
817 });
818
819 it("releases follow once when it mounts on a thread whose find is open", async () => {
820 setup();
821 const { navigations, element } = renderObserved();
822 await using screen = await renderElement(element({ findOpen: true }));
823 await screen.rerender(element({ findOpen: true }));
824 expect(navigations).toEqual([released]);
825 });
826
827 it("still restores the position of a thread it switches to whose find is open", async () => {
828 setup();
829 const base = baseProps();
830 const other = "environment-local:thread-find-open-positioned";
831 const replies = Array.from({ length: 40 }, (_, index) =>
832 message(`Reply ${index}\n\n${"line\n\n".repeat(8)}`, { role: "assistant" }, `r-${index}`),
833 );
834 rememberTimelinePosition(
835 other,
836 { rowId: "entry-r-20", offsetWithinRow: 0, scrollOffset: 0, atEnd: false },
837 false,
838 );
839 await using screen = await renderElement(
840 <MessagesTimeline {...base} timelineEntries={[message("Short thread")]} />,
841 );
842 await screen.rerender(
843 <MessagesTimeline
844 {...base}
845 routeThreadKey={other}
846 timelineEntries={replies}
847 liveFollowEnabled={false}
848 findOpen
849 />,
850 );
851 const viewport = base.listRef.current!.getScrollableNode()!;
852 await vi.waitFor(() => {
853 const row = screen.container.querySelector('[data-timeline-row-id="entry-r-20"]');
854 expect(row).not.toBeNull();
855 expect(
856 Math.abs(row!.getBoundingClientRect().top - viewport.getBoundingClientRect().top),
857 ).toBeLessThanOrEqual(2);
858 });
859 });
860 it("reveals find's match, not the remembered row, on a thread it switches to", async () => {
861 setup();
862 const base = baseProps();
863 const other = "environment-local:thread-find-open-match";
864 const replies = Array.from({ length: 40 }, (_, index) =>
865 message(
866 `${index === 5 ? "Needle here" : `Reply ${index}`}\n\n${"line\n\n".repeat(8)}`,
867 { role: "assistant" },
868 `r-${index}`,
869 ),
870 );
871 rememberTimelinePosition(
872 other,
873 { rowId: "entry-r-20", offsetWithinRow: 0, scrollOffset: 0, atEnd: false },
874 false,
875 );
876 await using screen = await renderElement(
877 <MessagesTimeline {...base} timelineEntries={[message("Short thread")]} />,
878 );
879 await screen.rerender(
880 <MessagesTimeline
881 {...base}
882 routeThreadKey={other}
883 timelineEntries={replies}
884 liveFollowEnabled={false}
885 findOpen
886 findExpanded
887 findQuery="Needle"
888 activeFindMatch={{ entryId: "entry-r-5", runId: null, occurrence: 0 }}
889 />,
890 );
891 const viewport = base.listRef.current!.getScrollableNode()!;
892 await vi.waitFor(() => {
893 const row = screen.container.querySelector('[data-timeline-row-id="entry-r-5"]');
894 expect(row).not.toBeNull();
895 const bounds = viewport.getBoundingClientRect();
896 const top = row!.getBoundingClientRect().top;
897 expect(top).toBeGreaterThanOrEqual(bounds.top);
898 expect(top).toBeLessThan(bounds.bottom);
899 });
900 });
901});
902
903describe("compact reasoning math", () => {
904 it("keeps formulas while flattening compact reasoning previews", () => {
905 const tree = parseMarkdownWithMath("## Reasoning\n\nUse **norm** $|x|$ and \\[x^2\\]");
906 remarkThoughtPreview("Reasoning")(tree);
907 expect(tree.children.map((node) => node.type)).toEqual([
908 "text",
909 "inlineMath",
910 "text",
911 "inlineMath",
912 ]);
913 expect(tree.children.map((node) => ("value" in node ? node.value : null))).toEqual([
914 "Reasoning Use norm ",
915 "|x|",
916 " and ",
917 "x^2",
918 ]);
919 });
920});
921
922it("renders automatic compaction as one live divider that finishes with its reason and token delta", async () => {
923 setup();
924 const fixture = makeStreamingTimelineFixture();
925 const prompt = fixture.visibleTurnItems[3]!;
926 const assistant = fixture.visibleTurnItems[5]!;
927 if (prompt.item.type !== "user_message" || assistant.item.type !== "assistant_message") {
928 throw new Error("Expected streaming fixture messages");
929 }
930 const promptItem = prompt.item;
931 const compaction = {
932 ...assistant,
933 item: {
934 ...assistant.item,
935 type: "compaction" as const,
936 driver: null,
937 beforeTokenCount: 899_000,
938 },
939 };
940 const entries = (completed: boolean) =>
941 deriveTimelineEntriesFromVisibleTurnItems({
942 visibleTurnItems: [
943 {
944 ...prompt,
945 item: { ...promptItem, text: "/compact", idleCompaction: "beforeCacheExpires" },
946 },
947 {
948 ...compaction,
949 item: {
950 ...compaction.item,
951 status: completed ? "completed" : "running",
952 afterTokenCount: completed ? 19_000 : undefined,
953 },
954 },
955 ],
956 optimisticMessages: [],
957 });
958 const props = baseProps();
959 const ui = (completed: boolean) => (
960 <MessagesTimeline
961 {...props}
962 timelineEntries={entries(completed)}
963 isWorking={!completed}
964 isCompacting={!completed}
965 activeTurnInProgress={!completed}
966 activeTurnStartedAt={fixture.time(5)}
967 latestRun={{
968 runId: fixture.runId,
969 status: completed ? "completed" : "running",
970 startedAt: fixture.time(5),
971 completedAt: completed ? fixture.time(9) : null,
972 }}
973 />
974 );
975 const container = document.createElement("div");
976 container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
977 await using screen = await render(ui(false), { container });
978 await expect
979 .element(screen.getByRole("separator", { name: "Compacting before the cache expires…" }))
980 .toBeVisible();
981 expect(container.textContent).not.toContain("/compact");
982 expect(container.textContent).not.toContain("Thinking");
983 expect(container.textContent).not.toContain("Working");
984 expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1);
985 await screen.rerender(ui(true));
986 await expect
987 .element(
988 screen.getByRole("separator", {
989 name: "Context automatically compacted before cache expiry 899K → 19K tokens",
990 }),
991 )
992 .toBeVisible();
993 expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1);
994 expect(container.textContent).not.toContain("Compacting before");
995});