Open History to see the last commit
1import { AudioPreview } from "../files/AudioPreview";
2import { onTestFinished } from "vite-plus/test";
3import { stubGlobal } from "../../../test/render";
4import {
5 EnvironmentId,
6 MessageId,
7 RunAttemptId,
8 RunId,
9 ScheduledTaskId,
10 ThreadId,
11} from "@t3tools/contracts";
12import type { LegendListRef } from "@legendapp/list/react";
13import { createRef, Profiler, StrictMode, type ComponentProps, type ReactElement } from "react";
14import { describe, expect, it, vi } from "vite-plus/test";
15
16import "~/index.css";
17
18import { act, render } from "../../../test/render";
19import { MessagesTimeline } from "./MessagesTimeline";
20import { makeStreamingTimelineFixture } from "../../test-fixtures";
21import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic";
22import { remarkThoughtPreview } from "./TimelineWorkEntryRow.logic";
23import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
24import { collectThreadFindRanges } from "./threadFindHighlights";
25import { toastManager } from "../ui/toast";
26import type { CitedHistory } from "./citationProcedure";
27
28const environmentQuery = vi.hoisted(() => ({
29 error: "Pull request not found",
30 data: null as unknown,
31}));
32vi.mock(import("~/state/query"), async (original) => ({
33 ...(await original()),
34 useEnvironmentQuery: (() => ({
35 data: environmentQuery.data,
36 dataUpdatedAt: 0,
37 error: environmentQuery.error,
38 failure: null,
39 isPending: false,
40 isSuccess: false,
41 refresh: () => {},
42 })) as never,
43}));
44
45const audioAsset = vi.hoisted(() => ({ url: "" }));
46vi.mock(import("~/assets/assetUrls"), async (original) => {
47 const actual = await original();
48 return {
49 ...actual,
50 useAssetUrlState: ((...args: Parameters<typeof actual.useAssetUrlState>) =>
51 audioAsset.url
52 ? { _tag: "Success", url: audioAsset.url }
53 : actual.useAssetUrlState(...args)) as typeof actual.useAssetUrlState,
54 };
55});
56
57const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
58const CREATED_AT = "2026-03-17T19:12:28.000Z";
59
60type TimelineProps = ComponentProps<typeof MessagesTimeline>;
61type Entry = TimelineProps["timelineEntries"][number];
62
63// The timeline remembers scroll position and open disclosures per thread key,
64// so every render gets a fresh thread.
65function baseProps(): Omit<TimelineProps, "timelineEntries"> {
66 return {
67 isWorking: false,
68 activeTurnInProgress: false,
69 listRef: createRef<LegendListRef | null>(),
70 latestRun: null,
71 turnDiffSummaries: [],
72 runs: [],
73 routeThreadKey: `environment-local:thread-${Math.random().toString(36).slice(2)}`,
74 onOpenTurnDiff: () => {},
75 onOpenThread: () => {},
76 onForkFromRun: async () => {},
77 onRollbackCheckpoint: () => {},
78 supportsConversationRollback: false,
79 onRevertToTurnCount: () => {},
80 isRevertingCheckpoint: false,
81 onImageExpand: () => {},
82 activeThreadEnvironmentId: ENVIRONMENT_ID,
83 markdownCwd: undefined,
84 resolvedTheme: "light",
85 timestampFormat: "locale",
86 workspaceRoot: undefined,
87 anchorMessageId: null,
88 onAnchorReady: () => {},
89 onAnchorSizeChanged: () => {},
90 contentInsetEndAdjustment: 0,
91 emptyPlaceholderInset: 0,
92 liveFollowEnabled: true,
93 onIsAtEndChange: () => {},
94 onManualNavigation: () => {},
95 };
96}
97
98function message(
99 text: string,
100 overrides: Partial<Extract<Entry, { kind: "message" }>["message"]> = {},
101 id = "message-1",
102): Entry {
103 return {
104 id: `entry-${id}`,
105 kind: "message",
106 createdAt: CREATED_AT,
107 message: {
108 id: MessageId.make(id),
109 role: "user",
110 text,
111 runId: null,
112 createdAt: CREATED_AT,
113 updatedAt: CREATED_AT,
114 streaming: false,
115 ...overrides,
116 },
117 };
118}
119
120async function renderElement(element: ReactElement, options: { router?: false } = {}) {
121 const container = document.createElement("div");
122 container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
123 const screen = await render(element, { container, ...options });
124 const buttons = (name: string | RegExp) =>
125 [...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => {
126 const label = button.getAttribute("aria-label") ?? button.textContent ?? "";
127 return typeof name === "string" ? label === name : name.test(label);
128 });
129 return Object.assign(screen, {
130 text: () => container.textContent ?? "",
131 buttons,
132 button: (name: string | RegExp) => {
133 const [match] = buttons(name);
134 if (!match) throw new Error(`Missing button: ${String(name)}`);
135 return match;
136 },
137 });
138}
139
140function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelineProps> = {}) {
141 return renderElement(
142 <MessagesTimeline {...baseProps()} timelineEntries={entries as Entry[]} {...props} />,
143 );
144}
145
146async function click(element: HTMLElement) {
147 await act(async () => element.click());
148}
149
150function setup({ scheduledTasks = [] as ReadonlyArray<{ id: string; title: string }> } = {}) {
151 environmentQuery.data = { tasks: scheduledTasks };
152}
153
154const TASK_ID = ScheduledTaskId.make("task-1");
155const AUTOMATION_PROMPT = "Triage the inbox\n\nLabel every new issue and close duplicates.";
156
157describe("MessagesTimeline messages", () => {
158 it("settles when equally long messages have very different rendered heights", async () => {
159 const props = baseProps();
160 const tall = message("a\n\n".repeat(6000), { role: "assistant" }, "tall");
161 const earlier = Array.from({ length: 80 }, (_, index) =>
162 message(
163 `<details><summary>Reply ${index}</summary>${"compact ".repeat(2250)}</details>`,
164 { role: "assistant" },
165 `earlier-${index}`,
166 ),
167 );
168 let nestedCommits = 0;
169 let maxNestedCommits = 0;
170 const onRender = (_id: string, phase: string) => {
171 nestedCommits = phase === "nested-update" ? nestedCommits + 1 : 0;
172 maxNestedCommits = Math.max(maxNestedCommits, nestedCommits);
173 };
174 const timeline = (entries: Entry[]) => (
175 <Profiler id="timeline" onRender={onRender}>
176 <MessagesTimeline {...props} timelineEntries={entries} />
177 </Profiler>
178 );
179 await using screen = await renderElement(timeline([tall]));
180 await vi.waitFor(() =>
181 expect(props.listRef.current?.getState().sizeAtIndex(0)).toBeGreaterThan(100_000),
182 );
183 const viewport = props.listRef.current!.getScrollableNode()!;
184 await act(() => {
185 viewport.scrollTop = 0;
186 viewport.dispatchEvent(new Event("scroll"));
187 });
188 await screen.rerender(timeline([...earlier, tall]));
189 await act(() => {
190 void props.listRef.current!.scrollToIndex({ index: 0, animated: false });
191 });
192 await vi.waitFor(async () => {
193 await act(() => {
194 viewport.scrollTop = 0;
195 viewport.dispatchEvent(new Event("scroll"));
196 });
197 expect(screen.text().includes("Reply 0")).toBe(true);
198 expect(props.listRef.current!.getState().sizeAtIndex(0)).toBeGreaterThan(0);
199 });
200 expect(maxNestedCommits).toBeLessThan(20);
201 });
202
203 it("preserves XML-like tags and comparisons in user messages as text", async () => {
204 const source = [
205 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
206 'Before <nested data-value="a&b">inside</nested> after',
207 "</global-agent-instructions> in your context?",
208 "Comparison: 2 < 3 and 5 > 4.",
209 ];
210 await using screen = await renderTimeline([message(source.join("\n"))]);
211 for (const line of source) expect(screen.text()).toContain(line);
212 expect(screen.container.querySelector("global-agent-instructions, nested")).toBeNull();
213 });
214
215 it("renders unsafe user HTML as inert source text", async () => {
216 const source =
217 '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">';
218 await using screen = await renderTimeline([message(source)]);
219 expect(screen.text()).toContain(source);
220 expect(screen.container.querySelector("script, img")).toBeNull();
221 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
222 });
223
224 it("renders sanitized raw HTML in assistant messages", async () => {
225 await using screen = await renderTimeline([
226 message(
227 [
228 '<details onclick="globalThis.__t3Xss = 1">',
229 "<summary>Safe details</summary>",
230 "<script>globalThis.__t3Xss = 2</script>",
231 '<img src="x" onerror="globalThis.__t3Xss = 3">',
232 '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
233 "</details>",
234 ].join(""),
235 { role: "assistant" },
236 ),
237 ]);
238 expect(screen.container.querySelector("[data-markdown-details]")?.textContent).toContain(
239 "Safe details",
240 );
241 expect(screen.text()).not.toContain("<details");
242 expect(screen.container.querySelector("script, [onclick], [onerror]")).toBeNull();
243 expect(screen.container.innerHTML).not.toContain("javascript:");
244 await click(screen.button("Safe details"));
245 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
246 });
247});
248
249const CITATION_REQUEST = {
250 key: "activation-1",
251 citation: {
252 version: 1,
253 environmentId: ENVIRONMENT_ID,
254 threadId: ThreadId.make("thread-cited"),
255 messageId: MessageId.make("cited"),
256 text: "the cited answer",
257 start: 0,
258 end: 16,
259 prefix: "",
260 suffix: "",
261 },
262} satisfies NonNullable<TimelineProps["citationRequest"]>;
263
264describe("MessagesTimeline citations", () => {
265 it("lands a citation present at mount under StrictMode", async () => {
266 await using _screen = await renderElement(
267 <StrictMode>
268 <MessagesTimeline
269 {...baseProps()}
270 timelineEntries={[
271 message("A question", {}, "question"),
272 message("the cited answer", { role: "assistant" }, "cited"),
273 ]}
274 citationRequest={CITATION_REQUEST}
275 citationHistory={{ _tag: "found" }}
276 />
277 </StrictMode>,
278 // The test router mounts route content without StrictMode's effect replay.
279 { router: false },
280 );
281 // StrictMode replays effect cleanups on mount; the activation must survive them.
282 await vi.waitFor(() =>
283 expect(document.querySelector("[data-citation-highlighted]")?.textContent).toContain(
284 "the cited answer",
285 ),
286 );
287 });
288
289 it("opens the superseded attempt that folds the cited response", async () => {
290 const runId = RunId.make("run-steered");
291 const attempt = (id: string, ordinal: number, status: "superseded" | "running") => ({
292 id: RunAttemptId.make(id),
293 runId,
294 attemptOrdinal: ordinal,
295 rootNodeId: `node-${id}` as never,
296 status,
297 completedAt: null,
298 });
299 const superseded = attempt("attempt-1", 1, "superseded");
300 const active = attempt("attempt-2", 2, "running");
301 const inAttempt = (entry: Entry, entryAttempt: typeof superseded): Entry => ({
302 ...entry,
303 attempt: entryAttempt,
304 });
305 await using _screen = await renderTimeline(
306 [
307 inAttempt(message("Build it", { runId }, "question"), superseded),
308 inAttempt(message("the cited answer", { role: "assistant", runId }, "cited"), superseded),
309 inAttempt(message("Change direction", { runId }, "steer"), active),
310 inAttempt(message("Current response", { role: "assistant", runId }, "current"), active),
311 ],
312 {
313 latestRun: { runId, status: "running", startedAt: CREATED_AT, completedAt: null },
314 citationRequest: CITATION_REQUEST,
315 citationHistory: { _tag: "found" },
316 },
317 );
318 await vi.waitFor(() =>
319 expect(document.querySelector("[data-citation-highlighted]")?.textContent).toContain(
320 "the cited answer",
321 ),
322 );
323 });
324
325 it("waits for cited history to load before giving up on a response outside the window", async () => {
326 using toast = vi.spyOn(toastManager, "add");
327 const props = baseProps();
328 const citationRequest = CITATION_REQUEST;
329 const recent = message("A recent question", {}, "recent");
330 const timeline = (entries: Entry[], citationHistory: CitedHistory) => (
331 <MessagesTimeline
332 {...props}
333 timelineEntries={entries}
334 citationRequest={citationRequest}
335 citationHistory={citationHistory}
336 />
337 );
338 await using screen = await renderElement(timeline([recent], { _tag: "loading" }));
339 await expect.element(screen.getByText("A recent question")).toBeVisible();
340
341 await screen.rerender(
342 timeline([message("the cited answer", { role: "assistant" }, "cited"), recent], {
343 _tag: "found",
344 }),
345 );
346 await expect.element(screen.getByText("the cited answer")).toBeVisible();
347 expect(toast).not.toHaveBeenCalled();
348 });
349});
350
351describe("MessagesTimeline automation prompts", () => {
352 it("folds an automation prompt into a bubble titled by its task", async () => {
353 setup({ scheduledTasks: [{ id: TASK_ID, title: "Nightly triage" }] });
354 await using screen = await renderTimeline([
355 message(AUTOMATION_PROMPT, { scheduledTaskId: TASK_ID }),
356 ]);
357 const row = screen.button(/^Automation/);
358 expect(row.textContent).toContain("Nightly triage");
359 expect(row.getAttribute("aria-expanded")).toBe("false");
360 expect(screen.text()).not.toContain("close duplicates");
361
362 await click(row);
363 expect(screen.text()).toContain("Label every new issue and close duplicates.");
364 const link = [...screen.container.querySelectorAll("a")].find(
365 (anchor) => anchor.textContent === "Open automation",
366 );
367 expect(link?.getAttribute("href")).toContain(`taskId=${TASK_ID}`);
368 expect(screen.buttons(/copy/i)).not.toHaveLength(0);
369 });
370
371 it("falls back to the prompt's first line without a task title", async () => {
372 setup();
373 await using screen = await renderTimeline([
374 message(AUTOMATION_PROMPT, { scheduledTaskId: TASK_ID }),
375 ]);
376 expect(screen.button(/^Automation/).textContent).toContain("Triage the inbox");
377 });
378
379 it("leaves ordinary user messages as full bubbles", async () => {
380 setup();
381 await using screen = await renderTimeline([message(AUTOMATION_PROMPT)]);
382 expect(screen.buttons(/^Automation/)).toHaveLength(0);
383 expect(screen.text()).toContain("Label every new issue and close duplicates.");
384 });
385
386 it("reveals a find match beyond the folded automation prompt's initial viewport", async () => {
387 setup();
388 const prompt = `${"Inspect the next item.\n\n".repeat(16)}Close duplicates.`;
389 await using screen = await renderTimeline([message(prompt, { scheduledTaskId: TASK_ID })], {
390 findExpanded: true,
391 findQuery: "duplicates",
392 activeFindMatch: { entryId: "entry-message-1", runId: null, occurrence: 0 },
393 });
394 await vi.waitFor(() =>
395 expect(screen.button(/^Automation/).getAttribute("aria-expanded")).toBe("true"),
396 );
397 const { range } = collectThreadFindRanges(screen.container, "duplicates")[0]!;
398 const details = screen.container.querySelector("[data-thread-find-text]")!;
399 expect(range.getBoundingClientRect().top - details.getBoundingClientRect().top).toBeGreaterThan(
400 384,
401 );
402 expect(range.getBoundingClientRect().bottom).toBeLessThanOrEqual(
403 details.getBoundingClientRect().bottom,
404 );
405 });
406
407 it("shows edit-from-here once an automation prompt is expanded", async () => {
408 setup();
409 const runId = RunId.make("run-1");
410 await using screen = await renderTimeline(
411 [
412 message(
413 AUTOMATION_PROMPT,
414 { scheduledTaskId: TASK_ID, runId, inputIntent: "turn_start" },
415 "user-1",
416 ),
417 message("Done", { role: "assistant", runId }, "assistant-1"),
418 ],
419 {
420 supportsConversationRollback: true,
421 threadStartCheckpointReady: true,
422 turnDiffSummaries: [
423 {
424 runId,
425 checkpointTurnCount: 1,
426 checkpointRef: "checkpoint-1" as never,
427 status: "ready",
428 files: [],
429 assistantMessageId: MessageId.make("assistant-1"),
430 completedAt: CREATED_AT,
431 },
432 ],
433 },
434 );
435 expect(screen.buttons("Edit from here")).toHaveLength(0);
436 await click(screen.button(/^Automation/));
437 expect(screen.buttons("Edit from here")).toHaveLength(1);
438 });
439});
440
441const SENDER_THREAD_ID = ThreadId.make("thread-sender");
442const AGENT_MESSAGE = "Review finished\n\nThe migration drops the index before backfilling it.";
443
444describe("MessagesTimeline agent messages", () => {
445 it("folds a message from another agent into a one-line preview", async () => {
446 setup();
447 const onOpenThread = vi.fn();
448 await using screen = await renderTimeline(
449 [message(AGENT_MESSAGE, { createdBy: "agent", senderThreadId: SENDER_THREAD_ID })],
450 { onOpenThread },
451 );
452 const row = screen.button(/^Agent/);
453 expect(row.textContent).toContain("Review finished");
454 expect(row.getAttribute("aria-expanded")).toBe("false");
455 expect(screen.text()).not.toContain("drops the index");
456 expect(screen.buttons("Open thread")).toHaveLength(0);
457
458 await click(row);
459 expect(screen.text()).toContain("The migration drops the index before backfilling it.");
460 await click(screen.button("Open thread"));
461 expect(onOpenThread).toHaveBeenCalledWith(SENDER_THREAD_ID);
462
463 await click(screen.button(/^Agent/));
464 expect(screen.text()).not.toContain("drops the index");
465 });
466
467 it("leaves messages sent by T3 Code as full bubbles", async () => {
468 setup();
469 await using screen = await renderTimeline([
470 message(AGENT_MESSAGE, { createdBy: "agent", creationSource: "server" }),
471 ]);
472 expect(screen.buttons(/^Agent/)).toHaveLength(0);
473 expect(screen.text()).toContain("drops the index");
474 });
475
476 it("reveals a find match inside a folded agent message", async () => {
477 setup();
478 const text = `${"Checked the next file.\n\n".repeat(16)}The migration drops the index.`;
479 await using screen = await renderTimeline(
480 [message(text, { createdBy: "agent", senderThreadId: SENDER_THREAD_ID })],
481 {
482 findExpanded: true,
483 findQuery: "drops the index",
484 activeFindMatch: { entryId: "entry-message-1", runId: null, occurrence: 0 },
485 },
486 );
487 await vi.waitFor(() =>
488 expect(screen.button(/^Agent/).getAttribute("aria-expanded")).toBe("true"),
489 );
490 const { range } = collectThreadFindRanges(screen.container, "drops the index")[0]!;
491 const body = screen.container.querySelector("[data-user-message-body]")!;
492 expect(range.getBoundingClientRect().height).toBeGreaterThan(0);
493 expect(range.getBoundingClientRect().bottom).toBeLessThanOrEqual(
494 body.getBoundingClientRect().bottom,
495 );
496 });
497});
498
499describe("MessagesTimeline attachments", () => {
500 it.each(["loadedmetadata", "loadeddata", "canplay"])(
501 "plays audio with unknown duration after %s and updates the total later",
502 async (readyEvent) => {
503 const onOpen = vi.fn();
504 const preview = (failed = false) => (
505 <AudioPreview
506 compact
507 src="data:audio/webm;base64,"
508 name="recording.webm"
509 failed={failed}
510 onOpen={onOpen}
511 />
512 );
513 await using screen = await renderElement(preview());
514 const audio = screen.container.querySelector("audio")!;
515 const duration = vi.spyOn(audio, "duration", "get").mockReturnValue(Infinity);
516 const play = vi.spyOn(audio, "play").mockResolvedValue();
517 expect(screen.button("Loading recording.webm")).toHaveProperty("disabled", true);
518 await act(() => audio.dispatchEvent(new Event(readyEvent)));
519 expect(screen.button("Play recording.webm")).toHaveProperty("disabled", false);
520 expect(screen.text()).toContain("0:00");
521 expect(screen.text()).not.toContain("/");
522 await click(screen.button("Play recording.webm"));
523 expect(play).toHaveBeenCalledOnce();
524 await act(() => {
525 vi.spyOn(audio, "currentTime", "get").mockReturnValue(3);
526 audio.dispatchEvent(new Event("play"));
527 audio.dispatchEvent(new Event("timeupdate"));
528 });
529 expect(screen.button("Pause recording.webm")).toHaveProperty("disabled", false);
530 expect(screen.text()).toContain("0:03");
531 const progress = screen.container.querySelector<HTMLElement>("span[aria-hidden]")!;
532 expect(progress.style.width).toBe("0%");
533 await act(() => {
534 duration.mockReturnValue(10);
535 audio.dispatchEvent(new Event("durationchange"));
536 });
537 expect(screen.text()).toContain("0:03 / 0:10");
538 expect(progress.style.width).toBe("30%");
539 await act(() => {
540 duration.mockReturnValue(NaN);
541 audio.dispatchEvent(new Event("durationchange"));
542 });
543 expect(screen.text()).not.toContain("/");
544 expect(progress.style.width).toBe("0%");
545 expect(screen.button("Pause recording.webm")).toHaveProperty("disabled", false);
546 await screen.rerender(preview(true));
547 expect(screen.text()).toContain("Unavailable");
548 await click(screen.button("Audio unavailable. Open recording.webm"));
549 expect(onOpen).toHaveBeenCalledOnce();
550 },
551 );
552
553 it.each(["pause", "error"])("unpins audio after %s", async (event) => {
554 const NativeObserver = IntersectionObserver;
555 using _observer = stubGlobal(
556 "IntersectionObserver",
557 class extends NativeObserver {
558 constructor(
559 private readonly notify: IntersectionObserverCallback,
560 options?: IntersectionObserverInit,
561 ) {
562 super(notify, options);
563 }
564 override observe(target: Element) {
565 this.notify([{ target, isIntersecting: true } as IntersectionObserverEntry], this);
566 }
567 },
568 );
569 const src =
570 "data:audio/wav;base64,UklGRiUAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQEAAACA";
571 audioAsset.url = src;
572 onTestFinished(() => {
573 audioAsset.url = "";
574 });
575 const props = baseProps();
576 await using screen = await renderTimeline(
577 [
578 message(
579 "Two recordings.",
580 {
581 attachments: ["one", "two"].map((name) => ({
582 type: "file",
583 id: `attachment-${name}`,
584 name: `${name}.wav`,
585 mimeType: "audio/wav",
586 sizeBytes: 45,
587 previewUrl: src,
588 })),
589 },
590 "audio",
591 ),
592 ...Array.from({ length: 40 }, (_, index) =>
593 message("Conversation history. ".repeat(40), { role: "user" }, `history-${index}`),
594 ),
595 ],
596 props,
597 );
598 screen.container.style.height = "600px";
599 screen.container.scrollIntoView({ block: "start" });
600 await vi.waitFor(
601 async () => {
602 await act(() => {
603 void props.listRef.current?.scrollToIndex({ index: 0, animated: false });
604 });
605 expect(screen.container.querySelectorAll("audio")).toHaveLength(2);
606 },
607 { timeout: 5000 },
608 );
609 const [one, two] = [...screen.container.querySelectorAll("audio")];
610 await act(async () => {
611 vi.spyOn(one!, "paused", "get").mockReturnValue(false);
612 vi.spyOn(two!, "paused", "get").mockReturnValue(false);
613 one!.dispatchEvent(new Event("play"));
614 two!.dispatchEvent(new Event("play"));
615 });
616 await vi.waitFor(async () => {
617 await act(() => {
618 void props.listRef.current!.scrollToEnd({ animated: false });
619 });
620 const scroll = props.listRef.current!.getScrollableNode()!;
621 expect(scroll.scrollTop).toBeGreaterThan(5000);
622 });
623 expect(one!.isConnected).toBe(true);
624 expect(two!.isConnected).toBe(true);
625 await act(async () => {
626 vi.spyOn(one!, "paused", "get").mockReturnValue(true);
627 one!.dispatchEvent(new Event("pause"));
628 });
629 expect(two!.isConnected).toBe(true);
630 await act(async () => {
631 if (event === "pause") vi.spyOn(two!, "paused", "get").mockReturnValue(true);
632 two!.dispatchEvent(new Event(event));
633 });
634 await act(() => {
635 void props.listRef.current!.scrollToIndex({ index: 20, animated: false });
636 });
637 await vi.waitFor(() => expect(one!.isConnected).toBe(false));
638 });
639});
640
641describe("compact reasoning math", () => {
642 it("keeps formulas while flattening compact reasoning previews", () => {
643 const tree = parseMarkdownWithMath("## Reasoning\n\nUse **norm** $|x|$ and \\[x^2\\]");
644 remarkThoughtPreview("Reasoning")(tree);
645 expect(tree.children.map((node) => node.type)).toEqual([
646 "text",
647 "inlineMath",
648 "text",
649 "inlineMath",
650 ]);
651 expect(tree.children.map((node) => ("value" in node ? node.value : null))).toEqual([
652 "Reasoning Use norm ",
653 "|x|",
654 " and ",
655 "x^2",
656 ]);
657 });
658});
659
660it("renders automatic compaction as one live divider that finishes with its reason and token delta", async () => {
661 setup();
662 const fixture = makeStreamingTimelineFixture();
663 const prompt = fixture.visibleTurnItems[3]!;
664 const assistant = fixture.visibleTurnItems[5]!;
665 if (prompt.item.type !== "user_message" || assistant.item.type !== "assistant_message") {
666 throw new Error("Expected streaming fixture messages");
667 }
668 const promptItem = prompt.item;
669 const compaction = {
670 ...assistant,
671 item: {
672 ...assistant.item,
673 type: "compaction" as const,
674 driver: null,
675 beforeTokenCount: 899_000,
676 },
677 };
678 const entries = (completed: boolean) =>
679 deriveTimelineEntriesFromVisibleTurnItems({
680 visibleTurnItems: [
681 {
682 ...prompt,
683 item: { ...promptItem, text: "/compact", idleCompaction: "beforeCacheExpires" },
684 },
685 {
686 ...compaction,
687 item: {
688 ...compaction.item,
689 status: completed ? "completed" : "running",
690 afterTokenCount: completed ? 19_000 : undefined,
691 },
692 },
693 ],
694 optimisticMessages: [],
695 });
696 const props = baseProps();
697 const ui = (completed: boolean) => (
698 <MessagesTimeline
699 {...props}
700 timelineEntries={entries(completed)}
701 isWorking={!completed}
702 isCompacting={!completed}
703 activeTurnInProgress={!completed}
704 activeTurnStartedAt={fixture.time(5)}
705 latestRun={{
706 runId: fixture.runId,
707 status: completed ? "completed" : "running",
708 startedAt: fixture.time(5),
709 completedAt: completed ? fixture.time(9) : null,
710 }}
711 />
712 );
713 const container = document.createElement("div");
714 container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
715 await using screen = await render(ui(false), { container });
716 await expect
717 .element(screen.getByRole("separator", { name: "Compacting before the cache expires…" }))
718 .toBeVisible();
719 expect(container.textContent).not.toContain("/compact");
720 expect(container.textContent).not.toContain("Thinking");
721 expect(container.textContent).not.toContain("Working");
722 expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1);
723 await screen.rerender(ui(true));
724 await expect
725 .element(
726 screen.getByRole("separator", {
727 name: "Context automatically compacted before cache expiry 899K → 19K tokens",
728 }),
729 )
730 .toBeVisible();
731 expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1);
732 expect(container.textContent).not.toContain("Compacting before");
733});