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

MessagesTimeline.browser.test.tsx

285 lines10.2 KB

1import { EnvironmentId, MessageId, RunId, ScheduledTaskId } from "@t3tools/contracts";
2import type { LegendListRef } from "@legendapp/list/react";
3import { createRef, 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 };
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 };
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 });
113​
114function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelineProps> = {}) {
115 return renderElement(
116 <MessagesTimeline {...baseProps()} timelineEntries={entries as Entry[]} {...props} />,
117 );
119​
120async function click(element: HTMLElement) {
121 await act(async () => element.click());
123​
124function setup({ scheduledTasks = [] as ReadonlyArray<{ id: string; title: string }> } = {}) {
125 environmentQuery.data = { tasks: scheduledTasks };
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("preserves XML-like tags and comparisons in user messages as text", async () => {
133 const source = [
134 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
135 'Before <nested data-value="a&b">inside</nested> after',
136 "</global-agent-instructions> in your context?",
137 "Comparison: 2 < 3 and 5 > 4.",
138 ];
139 await using screen = await renderTimeline([message(source.join("\n"))]);
140 for (const line of source) expect(screen.text()).toContain(line);
141 expect(screen.container.querySelector("global-agent-instructions, nested")).toBeNull();
142 });
143​
144 it("renders unsafe user HTML as inert source text", async () => {
145 const source =
146 '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">';
147 await using screen = await renderTimeline([message(source)]);
148 expect(screen.text()).toContain(source);
149 expect(screen.container.querySelector("script, img")).toBeNull();
150 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
151 });
152​
153 it("renders sanitized raw HTML in assistant messages", async () => {
154 await using screen = await renderTimeline([
155 message(
156 [
157 '<details onclick="globalThis.__t3Xss = 1">',
158 "<summary>Safe details</summary>",
159 "<script>globalThis.__t3Xss = 2</script>",
160 '<img src="x" onerror="globalThis.__t3Xss = 3">',
161 '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
162 "</details>",
163 ].join(""),
164 { role: "assistant" },
165 ),
166 ]);
167 expect(screen.container.querySelector("[data-markdown-details]")?.textContent).toContain(
168 "Safe details",
169 );
170 expect(screen.text()).not.toContain("<details");
171 expect(screen.container.querySelector("script, [onclick], [onerror]")).toBeNull();
172 expect(screen.container.innerHTML).not.toContain("javascript:");
173 await click(screen.button("Safe details"));
174 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
175 });
176});
177​
178describe("MessagesTimeline automation prompts", () => {
179 it("folds an automation prompt into a bubble titled by its task", async () => {
180 setup({ scheduledTasks: [{ id: TASK_ID, title: "Nightly triage" }] });
181 await using screen = await renderTimeline([
182 message(AUTOMATION_PROMPT, { scheduledTaskId: TASK_ID }),
183 ]);
184 const row = screen.button(/^Automation/);
185 expect(row.textContent).toContain("Nightly triage");
186 expect(row.getAttribute("aria-expanded")).toBe("false");
187 expect(screen.text()).not.toContain("close duplicates");
188​
189 await click(row);
190 expect(screen.text()).toContain("Label every new issue and close duplicates.");
191 const link = [...screen.container.querySelectorAll("a")].find(
192 (anchor) => anchor.textContent === "Open automation",
193 );
194 expect(link?.getAttribute("href")).toContain(`taskId=${TASK_ID}`);
195 expect(screen.buttons(/copy/i)).not.toHaveLength(0);
196 });
197​
198 it("falls back to the prompt's first line without a task title", async () => {
199 setup();
200 await using screen = await renderTimeline([
201 message(AUTOMATION_PROMPT, { scheduledTaskId: TASK_ID }),
202 ]);
203 expect(screen.button(/^Automation/).textContent).toContain("Triage the inbox");
204 });
205​
206 it("leaves ordinary user messages as full bubbles", async () => {
207 setup();
208 await using screen = await renderTimeline([message(AUTOMATION_PROMPT)]);
209 expect(screen.buttons(/^Automation/)).toHaveLength(0);
210 expect(screen.text()).toContain("Label every new issue and close duplicates.");
211 });
212​
213 it("reveals a find match beyond the folded automation prompt's initial viewport", async () => {
214 setup();
215 const prompt = `${"Inspect the next item.\n\n".repeat(16)}Close duplicates.`;
216 await using screen = await renderTimeline([message(prompt, { scheduledTaskId: TASK_ID })], {
217 findExpanded: true,
218 findQuery: "duplicates",
219 activeFindMatch: { entryId: "entry-message-1", runId: null, occurrence: 0 },
220 });
221 await vi.waitFor(() =>
222 expect(screen.button(/^Automation/).getAttribute("aria-expanded")).toBe("true"),
223 );
224 const { range } = collectThreadFindRanges(screen.container, "duplicates")[0]!;
225 const details = screen.container.querySelector("[data-thread-find-text]")!;
226 expect(range.getBoundingClientRect().top - details.getBoundingClientRect().top).toBeGreaterThan(
227 384,
228 );
229 expect(range.getBoundingClientRect().bottom).toBeLessThanOrEqual(
230 details.getBoundingClientRect().bottom,
231 );
232 });
233​
234 it("shows edit-from-here once an automation prompt is expanded", async () => {
235 setup();
236 const runId = RunId.make("run-1");
237 await using screen = await renderTimeline(
238 [
239 message(
240 AUTOMATION_PROMPT,
241 { scheduledTaskId: TASK_ID, runId, inputIntent: "turn_start" },
242 "user-1",
243 ),
244 message("Done", { role: "assistant", runId }, "assistant-1"),
245 ],
246 {
247 supportsConversationRollback: true,
248 threadStartCheckpointReady: true,
249 turnDiffSummaries: [
250 {
251 runId,
252 checkpointTurnCount: 1,
253 checkpointRef: "checkpoint-1" as never,
254 status: "ready",
255 files: [],
256 assistantMessageId: MessageId.make("assistant-1"),
257 completedAt: CREATED_AT,
258 },
259 ],
260 },
261 );
262 expect(screen.buttons("Edit from here")).toHaveLength(0);
263 await click(screen.button(/^Automation/));
264 expect(screen.buttons("Edit from here")).toHaveLength(1);
265 });
266});
267​
268describe("compact reasoning math", () => {
269 it("keeps formulas while flattening compact reasoning previews", () => {
270 const tree = parseMarkdownWithMath("## Reasoning\n\nUse **norm** $|x|$ and \\[x^2\\]");
271 remarkThoughtPreview("Reasoning")(tree);
272 expect(tree.children.map((node) => node.type)).toEqual([
273 "text",
274 "inlineMath",
275 "text",
276 "inlineMath",
277 ]);
278 expect(tree.children.map((node) => ("value" in node ? node.value : null))).toEqual([
279 "Reasoning Use norm ",
280 "|x|",
281 " and ",
282 "x^2",
283 ]);
284 });
285});