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