Open History to see the last commit
1import { EnvironmentId, MessageId, RunId, ScheduledTaskId } 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 { remarkThoughtPreview } from "./TimelineWorkEntryRow.logic";
11import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
12import { collectThreadFindRanges } from "./threadFindHighlights";
13
14const environmentQuery = vi.hoisted(() => ({
15 error: "Pull request not found",
16 data: null as unknown,
17}));
18vi.mock(import("~/state/query"), async (original) => ({
19 ...(await original()),
20 useEnvironmentQuery: (() => ({
21 data: environmentQuery.data,
22 dataUpdatedAt: 0,
23 error: environmentQuery.error,
24 failure: null,
25 isPending: false,
26 isSuccess: false,
27 refresh: () => {},
28 })) as never,
29}));
30
31const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
32const CREATED_AT = "2026-03-17T19:12:28.000Z";
33
34type TimelineProps = ComponentProps<typeof MessagesTimeline>;
35type Entry = TimelineProps["timelineEntries"][number];
36
37// The timeline remembers scroll position and open disclosures per thread key,
38// so every render gets a fresh thread.
39function baseProps(): Omit<TimelineProps, "timelineEntries"> {
40 return {
41 isWorking: false,
42 activeTurnInProgress: false,
43 listRef: createRef<LegendListRef | null>(),
44 latestRun: null,
45 turnDiffSummaries: [],
46 runs: [],
47 routeThreadKey: `environment-local:thread-${Math.random().toString(36).slice(2)}`,
48 onOpenTurnDiff: () => {},
49 onOpenThread: () => {},
50 onForkFromRun: async () => {},
51 onRollbackCheckpoint: () => {},
52 supportsConversationRollback: false,
53 onRevertToTurnCount: () => {},
54 isRevertingCheckpoint: false,
55 onImageExpand: () => {},
56 activeThreadEnvironmentId: ENVIRONMENT_ID,
57 markdownCwd: undefined,
58 resolvedTheme: "light",
59 timestampFormat: "locale",
60 workspaceRoot: undefined,
61 anchorMessageId: null,
62 onAnchorReady: () => {},
63 onAnchorSizeChanged: () => {},
64 contentInsetEndAdjustment: 0,
65 emptyPlaceholderInset: 0,
66 liveFollowEnabled: true,
67 onIsAtEndChange: () => {},
68 onManualNavigation: () => {},
69 };
70}
71
72function message(
73 text: string,
74 overrides: Partial<Extract<Entry, { kind: "message" }>["message"]> = {},
75 id = "message-1",
76): Entry {
77 return {
78 id: `entry-${id}`,
79 kind: "message",
80 createdAt: CREATED_AT,
81 message: {
82 id: MessageId.make(id),
83 role: "user",
84 text,
85 runId: null,
86 createdAt: CREATED_AT,
87 updatedAt: CREATED_AT,
88 streaming: false,
89 ...overrides,
90 },
91 };
92}
93
94async function renderElement(element: ReactElement) {
95 const container = document.createElement("div");
96 container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
97 const screen = await render(element, { container });
98 const buttons = (name: string | RegExp) =>
99 [...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => {
100 const label = button.getAttribute("aria-label") ?? button.textContent ?? "";
101 return typeof name === "string" ? label === name : name.test(label);
102 });
103 return Object.assign(screen, {
104 text: () => container.textContent ?? "",
105 buttons,
106 button: (name: string | RegExp) => {
107 const [match] = buttons(name);
108 if (!match) throw new Error(`Missing button: ${String(name)}`);
109 return match;
110 },
111 });
112}
113
114function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelineProps> = {}) {
115 return renderElement(
116 <MessagesTimeline {...baseProps()} timelineEntries={entries as Entry[]} {...props} />,
117 );
118}
119
120async function click(element: HTMLElement) {
121 await act(async () => element.click());
122}
123
124function setup({ scheduledTasks = [] as ReadonlyArray<{ id: string; title: string }> } = {}) {
125 environmentQuery.data = { tasks: scheduledTasks };
126}
127
128const TASK_ID = ScheduledTaskId.make("task-1");
129const AUTOMATION_PROMPT = "Triage the inbox\n\nLabel every new issue and close duplicates.";
130
131describe("MessagesTimeline messages", () => {
132 it("settles when equally long messages have very different rendered heights", async () => {
133 const props = baseProps();
134 const tall = message("a\n\n".repeat(6000), { role: "assistant" }, "tall");
135 const earlier = Array.from({ length: 80 }, (_, index) =>
136 message(
137 `<details><summary>Reply ${index}</summary>${"compact ".repeat(2250)}</details>`,
138 { role: "assistant" },
139 `earlier-${index}`,
140 ),
141 );
142 let nestedCommits = 0;
143 let maxNestedCommits = 0;
144 const onRender = (_id: string, phase: string) => {
145 nestedCommits = phase === "nested-update" ? nestedCommits + 1 : 0;
146 maxNestedCommits = Math.max(maxNestedCommits, nestedCommits);
147 };
148 const timeline = (entries: Entry[]) => (
149 <Profiler id="timeline" onRender={onRender}>
150 <MessagesTimeline {...props} timelineEntries={entries} />
151 </Profiler>
152 );
153 await using screen = await renderElement(timeline([tall]));
154 await vi.waitFor(() =>
155 expect(props.listRef.current?.getState().sizeAtIndex(0)).toBeGreaterThan(100_000),
156 );
157 const viewport = props.listRef.current!.getScrollableNode()!;
158 await act(() => {
159 viewport.scrollTop = 0;
160 viewport.dispatchEvent(new Event("scroll"));
161 });
162 await screen.rerender(timeline([...earlier, tall]));
163 await act(() => {
164 void props.listRef.current!.scrollToIndex({ index: 0, animated: false });
165 });
166 await vi.waitFor(async () => {
167 await act(() => {
168 viewport.scrollTop = 0;
169 viewport.dispatchEvent(new Event("scroll"));
170 });
171 expect(screen.text().includes("Reply 0")).toBe(true);
172 expect(props.listRef.current!.getState().sizeAtIndex(0)).toBeGreaterThan(0);
173 });
174 expect(maxNestedCommits).toBeLessThan(20);
175 });
176
177 it("preserves XML-like tags and comparisons in user messages as text", async () => {
178 const source = [
179 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
180 'Before <nested data-value="a&b">inside</nested> after',
181 "</global-agent-instructions> in your context?",
182 "Comparison: 2 < 3 and 5 > 4.",
183 ];
184 await using screen = await renderTimeline([message(source.join("\n"))]);
185 for (const line of source) expect(screen.text()).toContain(line);
186 expect(screen.container.querySelector("global-agent-instructions, nested")).toBeNull();
187 });
188
189 it("renders unsafe user HTML as inert source text", async () => {
190 const source =
191 '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">';
192 await using screen = await renderTimeline([message(source)]);
193 expect(screen.text()).toContain(source);
194 expect(screen.container.querySelector("script, img")).toBeNull();
195 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
196 });
197
198 it("renders sanitized raw HTML in assistant messages", async () => {
199 await using screen = await renderTimeline([
200 message(
201 [
202 '<details onclick="globalThis.__t3Xss = 1">',
203 "<summary>Safe details</summary>",
204 "<script>globalThis.__t3Xss = 2</script>",
205 '<img src="x" onerror="globalThis.__t3Xss = 3">',
206 '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
207 "</details>",
208 ].join(""),
209 { role: "assistant" },
210 ),
211 ]);
212 expect(screen.container.querySelector("[data-markdown-details]")?.textContent).toContain(
213 "Safe details",
214 );
215 expect(screen.text()).not.toContain("<details");
216 expect(screen.container.querySelector("script, [onclick], [onerror]")).toBeNull();
217 expect(screen.container.innerHTML).not.toContain("javascript:");
218 await click(screen.button("Safe details"));
219 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
220 });
221});
222
223describe("MessagesTimeline automation prompts", () => {
224 it("folds an automation prompt into a bubble titled by its task", async () => {
225 setup({ scheduledTasks: [{ id: TASK_ID, title: "Nightly triage" }] });
226 await using screen = await renderTimeline([
227 message(AUTOMATION_PROMPT, { scheduledTaskId: TASK_ID }),
228 ]);
229 const row = screen.button(/^Automation/);
230 expect(row.textContent).toContain("Nightly triage");
231 expect(row.getAttribute("aria-expanded")).toBe("false");
232 expect(screen.text()).not.toContain("close duplicates");
233
234 await click(row);
235 expect(screen.text()).toContain("Label every new issue and close duplicates.");
236 const link = [...screen.container.querySelectorAll("a")].find(
237 (anchor) => anchor.textContent === "Open automation",
238 );
239 expect(link?.getAttribute("href")).toContain(`taskId=${TASK_ID}`);
240 expect(screen.buttons(/copy/i)).not.toHaveLength(0);
241 });
242
243 it("falls back to the prompt's first line without a task title", async () => {
244 setup();
245 await using screen = await renderTimeline([
246 message(AUTOMATION_PROMPT, { scheduledTaskId: TASK_ID }),
247 ]);
248 expect(screen.button(/^Automation/).textContent).toContain("Triage the inbox");
249 });
250
251 it("leaves ordinary user messages as full bubbles", async () => {
252 setup();
253 await using screen = await renderTimeline([message(AUTOMATION_PROMPT)]);
254 expect(screen.buttons(/^Automation/)).toHaveLength(0);
255 expect(screen.text()).toContain("Label every new issue and close duplicates.");
256 });
257
258 it("reveals a find match beyond the folded automation prompt's initial viewport", async () => {
259 setup();
260 const prompt = `${"Inspect the next item.\n\n".repeat(16)}Close duplicates.`;
261 await using screen = await renderTimeline([message(prompt, { scheduledTaskId: TASK_ID })], {
262 findExpanded: true,
263 findQuery: "duplicates",
264 activeFindMatch: { entryId: "entry-message-1", runId: null, occurrence: 0 },
265 });
266 await vi.waitFor(() =>
267 expect(screen.button(/^Automation/).getAttribute("aria-expanded")).toBe("true"),
268 );
269 const { range } = collectThreadFindRanges(screen.container, "duplicates")[0]!;
270 const details = screen.container.querySelector("[data-thread-find-text]")!;
271 expect(range.getBoundingClientRect().top - details.getBoundingClientRect().top).toBeGreaterThan(
272 384,
273 );
274 expect(range.getBoundingClientRect().bottom).toBeLessThanOrEqual(
275 details.getBoundingClientRect().bottom,
276 );
277 });
278
279 it("shows edit-from-here once an automation prompt is expanded", async () => {
280 setup();
281 const runId = RunId.make("run-1");
282 await using screen = await renderTimeline(
283 [
284 message(
285 AUTOMATION_PROMPT,
286 { scheduledTaskId: TASK_ID, runId, inputIntent: "turn_start" },
287 "user-1",
288 ),
289 message("Done", { role: "assistant", runId }, "assistant-1"),
290 ],
291 {
292 supportsConversationRollback: true,
293 threadStartCheckpointReady: true,
294 turnDiffSummaries: [
295 {
296 runId,
297 checkpointTurnCount: 1,
298 checkpointRef: "checkpoint-1" as never,
299 status: "ready",
300 files: [],
301 assistantMessageId: MessageId.make("assistant-1"),
302 completedAt: CREATED_AT,
303 },
304 ],
305 },
306 );
307 expect(screen.buttons("Edit from here")).toHaveLength(0);
308 await click(screen.button(/^Automation/));
309 expect(screen.buttons("Edit from here")).toHaveLength(1);
310 });
311});
312
313describe("compact reasoning math", () => {
314 it("keeps formulas while flattening compact reasoning previews", () => {
315 const tree = parseMarkdownWithMath("## Reasoning\n\nUse **norm** $|x|$ and \\[x^2\\]");
316 remarkThoughtPreview("Reasoning")(tree);
317 expect(tree.children.map((node) => node.type)).toEqual([
318 "text",
319 "inlineMath",
320 "text",
321 "inlineMath",
322 ]);
323 expect(tree.children.map((node) => ("value" in node ? node.value : null))).toEqual([
324 "Reasoning Use norm ",
325 "|x|",
326 " and ",
327 "x^2",
328 ]);
329 });
330});