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

MessagesTimeline.browser.test.tsx

183 lines6.3 KB

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