Open History to see the last commit
1import { EnvironmentId, MessageId } 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";
12
13const pullRequestQuery = vi.hoisted(() => ({ error: "Pull request not found" }));
14vi.mock(import("~/state/query"), async (original) => ({
15 ...(await original()),
16 useEnvironmentQuery: (() => ({
17 data: null,
18 dataUpdatedAt: 0,
19 error: pullRequestQuery.error,
20 failure: null,
21 isPending: false,
22 isSuccess: false,
23 refresh: () => {},
24 })) as never,
25}));
26
27const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
28const CREATED_AT = "2026-03-17T19:12:28.000Z";
29
30type TimelineProps = ComponentProps<typeof MessagesTimeline>;
31type Entry = TimelineProps["timelineEntries"][number];
32
33// The timeline remembers scroll position and open disclosures per thread key,
34// so every render gets a fresh thread.
35function baseProps(): Omit<TimelineProps, "timelineEntries"> {
36 return {
37 isWorking: false,
38 activeTurnInProgress: false,
39 listRef: createRef<LegendListRef | null>(),
40 latestRun: null,
41 turnDiffSummaries: [],
42 runs: [],
43 routeThreadKey: `environment-local:thread-${Math.random().toString(36).slice(2)}`,
44 onOpenTurnDiff: () => {},
45 onOpenThread: () => {},
46 onForkFromRun: async () => {},
47 onRollbackCheckpoint: () => {},
48 supportsConversationRollback: false,
49 onRevertToTurnCount: () => {},
50 isRevertingCheckpoint: false,
51 onImageExpand: () => {},
52 activeThreadEnvironmentId: ENVIRONMENT_ID,
53 markdownCwd: undefined,
54 resolvedTheme: "light",
55 timestampFormat: "locale",
56 workspaceRoot: undefined,
57 anchorMessageId: null,
58 onAnchorReady: () => {},
59 onAnchorSizeChanged: () => {},
60 contentInsetEndAdjustment: 0,
61 emptyPlaceholderInset: 0,
62 liveFollowEnabled: true,
63 onIsAtEndChange: () => {},
64 onManualNavigation: () => {},
65 };
66}
67
68function message(
69 text: string,
70 overrides: Partial<Extract<Entry, { kind: "message" }>["message"]> = {},
71 id = "message-1",
72): Entry {
73 return {
74 id: `entry-${id}`,
75 kind: "message",
76 createdAt: CREATED_AT,
77 message: {
78 id: MessageId.make(id),
79 role: "user",
80 text,
81 runId: null,
82 createdAt: CREATED_AT,
83 updatedAt: CREATED_AT,
84 streaming: false,
85 ...overrides,
86 },
87 };
88}
89
90async function renderElement(element: ReactElement) {
91 const container = document.createElement("div");
92 container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
93 const screen = await render(element, { container });
94 const buttons = (name: string | RegExp) =>
95 [...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => {
96 const label = button.getAttribute("aria-label") ?? button.textContent ?? "";
97 return typeof name === "string" ? label === name : name.test(label);
98 });
99 return Object.assign(screen, {
100 text: () => container.textContent ?? "",
101 buttons,
102 button: (name: string | RegExp) => {
103 const [match] = buttons(name);
104 if (!match) throw new Error(`Missing button: ${String(name)}`);
105 return match;
106 },
107 });
108}
109
110function renderTimeline(entries: ReadonlyArray<Entry>, props: Partial<TimelineProps> = {}) {
111 return renderElement(
112 <MessagesTimeline {...baseProps()} timelineEntries={entries as Entry[]} {...props} />,
113 );
114}
115
116async function click(element: HTMLElement) {
117 await act(async () => element.click());
118}
119
120describe("MessagesTimeline messages", () => {
121 it("preserves XML-like tags and comparisons in user messages as text", async () => {
122 const source = [
123 'Without reading a file, do you have <global-agent-instructions scope="workspace">',
124 'Before <nested data-value="a&b">inside</nested> after',
125 "</global-agent-instructions> in your context?",
126 "Comparison: 2 < 3 and 5 > 4.",
127 ];
128 await using screen = await renderTimeline([message(source.join("\n"))]);
129 for (const line of source) expect(screen.text()).toContain(line);
130 expect(screen.container.querySelector("global-agent-instructions, nested")).toBeNull();
131 });
132
133 it("renders unsafe user HTML as inert source text", async () => {
134 const source =
135 '<script>globalThis.__t3Xss = 1</script><img src="x" onerror="globalThis.__t3Xss = 2">';
136 await using screen = await renderTimeline([message(source)]);
137 expect(screen.text()).toContain(source);
138 expect(screen.container.querySelector("script, img")).toBeNull();
139 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
140 });
141
142 it("renders sanitized raw HTML in assistant messages", async () => {
143 await using screen = await renderTimeline([
144 message(
145 [
146 '<details onclick="globalThis.__t3Xss = 1">',
147 "<summary>Safe details</summary>",
148 "<script>globalThis.__t3Xss = 2</script>",
149 '<img src="x" onerror="globalThis.__t3Xss = 3">',
150 '<a href="javascript:globalThis.__t3Xss = 4">Unsafe link</a>',
151 "</details>",
152 ].join(""),
153 { role: "assistant" },
154 ),
155 ]);
156 expect(screen.container.querySelector("[data-markdown-details]")?.textContent).toContain(
157 "Safe details",
158 );
159 expect(screen.text()).not.toContain("<details");
160 expect(screen.container.querySelector("script, [onclick], [onerror]")).toBeNull();
161 expect(screen.container.innerHTML).not.toContain("javascript:");
162 await click(screen.button("Safe details"));
163 expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined();
164 });
165});
166
167describe("compact reasoning math", () => {
168 it("keeps formulas while flattening compact reasoning previews", () => {
169 const tree = parseMarkdownWithMath("## Reasoning\n\nUse **norm** $|x|$ and \\[x^2\\]");
170 remarkThoughtPreview("Reasoning")(tree);
171 expect(tree.children.map((node) => node.type)).toEqual([
172 "text",
173 "inlineMath",
174 "text",
175 "inlineMath",
176 ]);
177 expect(tree.children.map((node) => ("value" in node ? node.value : null))).toEqual([
178 "Reasoning Use norm ",
179 "|x|",
180 " and ",
181 "x^2",
182 ]);
183 });
184});