Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MessagesTimeline.browser.test.tsx

465 lines17.1 KB

1import { EnvironmentId, MessageId, RunId, ScheduledTaskId, ThreadId } from "@t3tools/contracts";
2import type { LegendListRef } from "@legendapp/list/react";
3import { createRef, Profiler, type ComponentProps, type ReactElement } from "react";
4import { describe, expect, it, vi } from "vite-plus/test";
5​
6import "~/index.css";
7​
8import { act, render } from "../../../test/render";
9import { MessagesTimeline } from "./MessagesTimeline";
10import { makeStreamingTimelineFixture } from "../../test-fixtures";
11import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic";
12import { remarkThoughtPreview } from "./TimelineWorkEntryRow.logic";
13import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
14import { collectThreadFindRanges } from "./threadFindHighlights";
15​
16const environmentQuery = vi.hoisted(() => ({
17 error: "Pull request not found",
18 data: null as unknown,
19}));
20vi.mock(import("~/state/query"), async (original) => ({
21 ...(await original()),
22 useEnvironmentQuery: (() => ({
23 data: environmentQuery.data,
24 dataUpdatedAt: 0,
25 error: environmentQuery.error,
26 failure: null,
27 isPending: false,
28 isSuccess: false,
29 refresh: () => {},
30 })) as never,
31}));
32​
33const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
34const CREATED_AT = "2026-03-17T19:12:28.000Z";
35​
36type TimelineProps = ComponentProps<typeof MessagesTimeline>;
37type Entry = TimelineProps["timelineEntries"][number];
38​
39// The timeline remembers scroll position and open disclosures per thread key,
40// so every render gets a fresh thread.
41function baseProps(): Omit<TimelineProps, "timelineEntries"> {
42 return {
43 isWorking: false,
44 activeTurnInProgress: false,
45 listRef: createRef<LegendListRef | null>(),
46 latestRun: null,
47 turnDiffSummaries: [],
48 runs: [],
49 routeThreadKey: `environment-local:thread-${Math.random().toString(36).slice(2)}`,
50 onOpenTurnDiff: () => {},
51 onOpenThread: () => {},
52 onForkFromRun: async () => {},
53 onRollbackCheckpoint: () => {},
54 supportsConversationRollback: false,
55 onRevertToTurnCount: () => {},
56 isRevertingCheckpoint: false,
57 onImageExpand: () => {},
58 activeThreadEnvironmentId: ENVIRONMENT_ID,
59 markdownCwd: undefined,
60 resolvedTheme: "light",
61 timestampFormat: "locale",
62 workspaceRoot: undefined,
63 anchorMessageId: null,
64 onAnchorReady: () => {},
65 onAnchorSizeChanged: () => {},
66 contentInsetEndAdjustment: 0,
67 emptyPlaceholderInset: 0,
68 liveFollowEnabled: true,
69 onIsAtEndChange: () => {},
70 onManualNavigation: () => {},
71 };
73​
74function message(
75 text: string,
76 overrides: Partial<Extract<Entry, { kind: "message" }>["message"]> = {},
77 id = "message-1",
78): Entry {
79 return {
80 id: `entry-${id}`,
81 kind: "message",
82 createdAt: CREATED_AT,
83 message: {
84 id: MessageId.make(id),
85 role: "user",
86 text,
87 runId: null,
88 createdAt: CREATED_AT,
89 updatedAt: CREATED_AT,
90 streaming: false,
91 ...overrides,
92 },
93 };
95​
96async function renderElement(element: ReactElement) {
97 const container = document.createElement("div");
98 container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
99 const screen = await render(element, { container });
100 const buttons = (name: string | RegExp) =>
101 [...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => {
102 const label = button.getAttribute("aria-label") ?? button.textContent ?? "";
103 return typeof name === "string" ? label === name : name.test(label);
104 });
105 return Object.assign(screen, {
106 text: () => container.textContent ?? "",
107 buttons,
108 button: (name: string | RegExp) => {
109 const [match] = buttons(name);
110 if (!match) throw new Error(`Missing button: ${String(name)}`);
111 return match;
112 },
113 });
115​
116function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelineProps> = {}) {
117 return renderElement(
118 <MessagesTimeline {...baseProps()} timelineEntries={entries as Entry[]} {...props} />,
119 );
121​
122async function click(element: HTMLElement) {
123 await act(async () => element.click());
125​
126function setup({ scheduledTasks = [] as ReadonlyArray<{ id: string; title: string }> } = {}) {
127 environmentQuery.data = { tasks: scheduledTasks };
129​
130const TASK_ID = ScheduledTaskId.make("task-1");
131const AUTOMATION_PROMPT = "Triage the inbox\n\nLabel every new issue and close duplicates.";
132​
133describe("MessagesTimeline messages", () => {
134 it("settles when equally long messages have very different rendered heights", async () => {
135 const props = baseProps();
136 const tall = message("a\n\n".repeat(6000), { role: "assistant" }, "tall");
137 const earlier = Array.from({ length: 80 }, (_, index) =>
138 message(
139 `<details><summary>Reply ${index}</summary>${"compact ".repeat(2250)}</details>`,
140 { role: "assistant" },
141 `earlier-${index}`,
142 ),
143 );
144 let nestedCommits = 0;
145 let maxNestedCommits = 0;
146 const onRender = (_id: string, phase: string) => {
147 nestedCommits = phase === "nested-update" ? nestedCommits + 1 : 0;
148 maxNestedCommits = Math.max(maxNestedCommits, nestedCommits);
149 };
150 const timeline = (entries: Entry[]) => (
151 <Profiler id="timeline" onRender={onRender}>
152 <MessagesTimeline {...props} timelineEntries={entries} />
153 </Profiler>
154 );
155 await using screen = await renderElement(timeline([tall]));
156 await vi.waitFor(() =>
157 expect(props.listRef.current?.getState().sizeAtIndex(0)).toBeGreaterThan(100_000),
158 );
159 const viewport = props.listRef.current!.getScrollableNode()!;
160 await act(() => {
161 viewport.scrollTop = 0;
162 viewport.dispatchEvent(new Event("scroll"));
163 });
164 await screen.rerender(timeline([...earlier, tall]));
165 await act(() => {
166 void props.listRef.current!.scrollToIndex({ index: 0, animated: false });
167 });
168 await vi.waitFor(async () => {
169 await act(() => {
170 viewport.scrollTop = 0;
171 viewport.dispatchEvent(new Event("scroll"));
172 });
173 expect(screen.text().includes("Reply 0")).toBe(true);
174 expect(props.listRef.current!.getState().sizeAtIndex(0)).toBeGreaterThan(0);
175 });
176 expect(maxNestedCommits).toBeLessThan(20);
177 });
178​
179 it("preserves XML-like tags and comparisons in user messages as text", async () => {
180 const source = [
181 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
182 'Before <nested data-value="a&b">inside</nested> after',
183 "</global-agent-instructions> in your context?",
184 "Comparison: 2 < 3 and 5 > 4.",
185 ];
186 await using screen = await renderTimeline([message(source.join("\n"))]);
187 for (const line of source) expect(screen.text()).toContain(line);
188 expect(screen.container.querySelector("global-agent-instructions, nested")).toBeNull();
189 });
190​
191 it("renders unsafe user HTML as inert source text", async () => {
192 const source =
193 '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">';
194 await using screen = await renderTimeline([message(source)]);
195 expect(screen.text()).toContain(source);
196 expect(screen.container.querySelector("script, img")).toBeNull();
197 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
198 });
199​
200 it("renders sanitized raw HTML in assistant messages", async () => {
201 await using screen = await renderTimeline([
202 message(
203 [
204 '<details onclick="globalThis.__t3Xss = 1">',
205 "<summary>Safe details</summary>",
206 "<script>globalThis.__t3Xss = 2</script>",
207 '<img src="x" onerror="globalThis.__t3Xss = 3">',
208 '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
209 "</details>",
210 ].join(""),
211 { role: "assistant" },
212 ),
213 ]);
214 expect(screen.container.querySelector("[data-markdown-details]")?.textContent).toContain(
215 "Safe details",
216 );
217 expect(screen.text()).not.toContain("<details");
218 expect(screen.container.querySelector("script, [onclick], [onerror]")).toBeNull();
219 expect(screen.container.innerHTML).not.toContain("javascript:");
220 await click(screen.button("Safe details"));
221 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
222 });
223});
224​
225describe("MessagesTimeline automation prompts", () => {
226 it("folds an automation prompt into a bubble titled by its task", async () => {
227 setup({ scheduledTasks: [{ id: TASK_ID, title: "Nightly triage" }] });
228 await using screen = await renderTimeline([
229 message(AUTOMATION_PROMPT, { scheduledTaskId: TASK_ID }),
230 ]);
231 const row = screen.button(/^Automation/);
232 expect(row.textContent).toContain("Nightly triage");
233 expect(row.getAttribute("aria-expanded")).toBe("false");
234 expect(screen.text()).not.toContain("close duplicates");
235​
236 await click(row);
237 expect(screen.text()).toContain("Label every new issue and close duplicates.");
238 const link = [...screen.container.querySelectorAll("a")].find(
239 (anchor) => anchor.textContent === "Open automation",
240 );
241 expect(link?.getAttribute("href")).toContain(`taskId=${TASK_ID}`);
242 expect(screen.buttons(/copy/i)).not.toHaveLength(0);
243 });
244​
245 it("falls back to the prompt's first line without a task title", async () => {
246 setup();
247 await using screen = await renderTimeline([
248 message(AUTOMATION_PROMPT, { scheduledTaskId: TASK_ID }),
249 ]);
250 expect(screen.button(/^Automation/).textContent).toContain("Triage the inbox");
251 });
252​
253 it("leaves ordinary user messages as full bubbles", async () => {
254 setup();
255 await using screen = await renderTimeline([message(AUTOMATION_PROMPT)]);
256 expect(screen.buttons(/^Automation/)).toHaveLength(0);
257 expect(screen.text()).toContain("Label every new issue and close duplicates.");
258 });
259​
260 it("reveals a find match beyond the folded automation prompt's initial viewport", async () => {
261 setup();
262 const prompt = `${"Inspect the next item.\n\n".repeat(16)}Close duplicates.`;
263 await using screen = await renderTimeline([message(prompt, { scheduledTaskId: TASK_ID })], {
264 findExpanded: true,
265 findQuery: "duplicates",
266 activeFindMatch: { entryId: "entry-message-1", runId: null, occurrence: 0 },
267 });
268 await vi.waitFor(() =>
269 expect(screen.button(/^Automation/).getAttribute("aria-expanded")).toBe("true"),
270 );
271 const { range } = collectThreadFindRanges(screen.container, "duplicates")[0]!;
272 const details = screen.container.querySelector("[data-thread-find-text]")!;
273 expect(range.getBoundingClientRect().top - details.getBoundingClientRect().top).toBeGreaterThan(
274 384,
275 );
276 expect(range.getBoundingClientRect().bottom).toBeLessThanOrEqual(
277 details.getBoundingClientRect().bottom,
278 );
279 });
280​
281 it("shows edit-from-here once an automation prompt is expanded", async () => {
282 setup();
283 const runId = RunId.make("run-1");
284 await using screen = await renderTimeline(
285 [
286 message(
287 AUTOMATION_PROMPT,
288 { scheduledTaskId: TASK_ID, runId, inputIntent: "turn_start" },
289 "user-1",
290 ),
291 message("Done", { role: "assistant", runId }, "assistant-1"),
292 ],
293 {
294 supportsConversationRollback: true,
295 threadStartCheckpointReady: true,
296 turnDiffSummaries: [
297 {
298 runId,
299 checkpointTurnCount: 1,
300 checkpointRef: "checkpoint-1" as never,
301 status: "ready",
302 files: [],
303 assistantMessageId: MessageId.make("assistant-1"),
304 completedAt: CREATED_AT,
305 },
306 ],
307 },
308 );
309 expect(screen.buttons("Edit from here")).toHaveLength(0);
310 await click(screen.button(/^Automation/));
311 expect(screen.buttons("Edit from here")).toHaveLength(1);
312 });
313});
314​
315const SENDER_THREAD_ID = ThreadId.make("thread-sender");
316const AGENT_MESSAGE = "Review finished\n\nThe migration drops the index before backfilling it.";
317​
318describe("MessagesTimeline agent messages", () => {
319 it("folds a message from another agent into a one-line preview", async () => {
320 setup();
321 const onOpenThread = vi.fn();
322 await using screen = await renderTimeline(
323 [message(AGENT_MESSAGE, { createdBy: "agent", senderThreadId: SENDER_THREAD_ID })],
324 { onOpenThread },
325 );
326 const row = screen.button(/^Agent/);
327 expect(row.textContent).toContain("Review finished");
328 expect(row.getAttribute("aria-expanded")).toBe("false");
329 expect(screen.text()).not.toContain("drops the index");
330 expect(screen.buttons("Open thread")).toHaveLength(0);
331​
332 await click(row);
333 expect(screen.text()).toContain("The migration drops the index before backfilling it.");
334 await click(screen.button("Open thread"));
335 expect(onOpenThread).toHaveBeenCalledWith(SENDER_THREAD_ID);
336​
337 await click(screen.button(/^Agent/));
338 expect(screen.text()).not.toContain("drops the index");
339 });
340​
341 it("leaves messages sent by T3 Code as full bubbles", async () => {
342 setup();
343 await using screen = await renderTimeline([
344 message(AGENT_MESSAGE, { createdBy: "agent", creationSource: "server" }),
345 ]);
346 expect(screen.buttons(/^Agent/)).toHaveLength(0);
347 expect(screen.text()).toContain("drops the index");
348 });
349​
350 it("reveals a find match inside a folded agent message", async () => {
351 setup();
352 const text = `${"Checked the next file.\n\n".repeat(16)}The migration drops the index.`;
353 await using screen = await renderTimeline(
354 [message(text, { createdBy: "agent", senderThreadId: SENDER_THREAD_ID })],
355 {
356 findExpanded: true,
357 findQuery: "drops the index",
358 activeFindMatch: { entryId: "entry-message-1", runId: null, occurrence: 0 },
359 },
360 );
361 await vi.waitFor(() =>
362 expect(screen.button(/^Agent/).getAttribute("aria-expanded")).toBe("true"),
363 );
364 const { range } = collectThreadFindRanges(screen.container, "drops the index")[0]!;
365 const body = screen.container.querySelector("[data-user-message-body]")!;
366 expect(range.getBoundingClientRect().height).toBeGreaterThan(0);
367 expect(range.getBoundingClientRect().bottom).toBeLessThanOrEqual(
368 body.getBoundingClientRect().bottom,
369 );
370 });
371});
372​
373describe("compact reasoning math", () => {
374 it("keeps formulas while flattening compact reasoning previews", () => {
375 const tree = parseMarkdownWithMath("## Reasoning\n\nUse **norm** $|x|$ and \\[x^2\\]");
376 remarkThoughtPreview("Reasoning")(tree);
377 expect(tree.children.map((node) => node.type)).toEqual([
378 "text",
379 "inlineMath",
380 "text",
381 "inlineMath",
382 ]);
383 expect(tree.children.map((node) => ("value" in node ? node.value : null))).toEqual([
384 "Reasoning Use norm ",
385 "|x|",
386 " and ",
387 "x^2",
388 ]);
389 });
390});
391​
392it("renders automatic compaction as one live divider that finishes with its reason and token delta", async () => {
393 setup();
394 const fixture = makeStreamingTimelineFixture();
395 const prompt = fixture.visibleTurnItems[3]!;
396 const assistant = fixture.visibleTurnItems[5]!;
397 if (prompt.item.type !== "user_message" || assistant.item.type !== "assistant_message") {
398 throw new Error("Expected streaming fixture messages");
399 }
400 const promptItem = prompt.item;
401 const compaction = {
402 ...assistant,
403 item: {
404 ...assistant.item,
405 type: "compaction" as const,
406 driver: null,
407 beforeTokenCount: 899_000,
408 },
409 };
410 const entries = (completed: boolean) =>
411 deriveTimelineEntriesFromVisibleTurnItems({
412 visibleTurnItems: [
413 {
414 ...prompt,
415 item: { ...promptItem, text: "/compact", idleCompaction: "beforeCacheExpires" },
416 },
417 {
418 ...compaction,
419 item: {
420 ...compaction.item,
421 status: completed ? "completed" : "running",
422 afterTokenCount: completed ? 19_000 : undefined,
423 },
424 },
425 ],
426 optimisticMessages: [],
427 });
428 const props = baseProps();
429 const ui = (completed: boolean) => (
430 <MessagesTimeline
431 {...props}
432 timelineEntries={entries(completed)}
433 isWorking={!completed}
434 isCompacting={!completed}
435 activeTurnInProgress={!completed}
436 activeTurnStartedAt={fixture.time(5)}
437 latestRun={{
438 runId: fixture.runId,
439 status: completed ? "completed" : "running",
440 startedAt: fixture.time(5),
441 completedAt: completed ? fixture.time(9) : null,
442 }}
443 />
444 );
445 const container = document.createElement("div");
446 container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
447 await using screen = await render(ui(false), { container });
448 await expect
449 .element(screen.getByRole("separator", { name: "Compacting before the cache expires…" }))
450 .toBeVisible();
451 expect(container.textContent).not.toContain("/compact");
452 expect(container.textContent).not.toContain("Thinking");
453 expect(container.textContent).not.toContain("Working");
454 expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1);
455 await screen.rerender(ui(true));
456 await expect
457 .element(
458 screen.getByRole("separator", {
459 name: "Context automatically compacted before cache expiry 899K → 19K tokens",
460 }),
461 )
462 .toBeVisible();
463 expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1);
464 expect(container.textContent).not.toContain("Compacting before");
465});