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