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