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

htmlRender.test.ts

316 lines12.6 KB

1import { describe, expect, it } from "vite-plus/test";
2​
3import {
4 encodeHtmlRenderOutline,
5 HTML_RENDER_MAX_HEIGHT,
6 htmlRenderFrameHeight,
7 htmlRenderOutlineBoxes,
8 htmlRenderReferencesEqual,
9 htmlRenderTheme,
10 htmlRenderThemeFragment,
11 injectHtmlRenderBootstrap,
12 htmlRenderThemeMessage,
13 readHtmlRenderContentHeight,
14 readHtmlRenderKeyDown,
15 readHtmlRenderLinkRequest,
16 readHtmlRenderReference,
17} from "./htmlRender.ts";
18import { T3_CODE_DARK_THEME_COLORS, T3_CODE_LIGHT_THEME_COLORS } from "./themePalettes.ts";
19import { htmlRenderFromToolItem } from "./toolOutput.ts";
20​
21const reference = { attachmentId: "thread-abc-123.html", title: "Chart", height: 420 };
22​
23describe("injectHtmlRenderBootstrap", () => {
24 it("puts the theme ahead of the page's own head content", () => {
25 const html =
26 "<!doctype html><html><head><style>:root{--background:red}</style></head><body>x</body></html>";
27 const injected = injectHtmlRenderBootstrap(html);
28 const themeAt = injected.indexOf('<style id="t3-theme">');
29 expect(themeAt).toBeGreaterThan(injected.indexOf("<head>"));
30 expect(themeAt).toBeLessThan(injected.indexOf(":root{--background:red}"));
31 expect(injected).toContain('<meta charset="utf-8">');
32 expect(injected).toContain('name="viewport"');
33 });
34​
35 it("wraps fragments without a head and keeps existing meta tags", () => {
36 const fragment =
37 '<meta charset="utf-8"><meta name="viewport" content="width=device-width"><p>hi</p>';
38 const injected = injectHtmlRenderBootstrap(fragment);
39 expect(injected.startsWith("<!doctype html><head>")).toBe(true);
40 expect(injected.match(/charset/g)).toHaveLength(1);
41 expect(injected.match(/name="viewport"/g)).toHaveLength(1);
42 expect(injected.endsWith("<p>hi</p>")).toBe(true);
43 });
44​
45 it.each(["textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript", "plaintext"])(
46 "keeps the bootstrap outside %s content",
47 (tag) => {
48 const fragment = `<${tag}><head><meta name="viewport"></head></${tag}>`;
49 const injected = injectHtmlRenderBootstrap(fragment);
50 expect(injected.startsWith("<!doctype html><head>")).toBe(true);
51 expect(injected.indexOf('<style id="t3-theme">')).toBeLessThan(injected.indexOf(`<${tag}>`));
52 expect(injected).toContain('<meta name="viewport" content="width=device-width');
53 expect(injected.endsWith(fragment)).toBe(true);
54 },
55 );
56​
57 it.each([
58 '<template><head><meta name="viewport"></head></template>',
59 '<template><template>inner</template><head><meta name="viewport"></head></template>',
60 ])("keeps the bootstrap outside inert template content: %s", (fragment) => {
61 const injected = injectHtmlRenderBootstrap(fragment);
62 expect(injected.startsWith("<!doctype html><head>")).toBe(true);
63 expect(injected.indexOf('<style id="t3-theme">')).toBeLessThan(injected.indexOf("<template>"));
64 expect(injected).toContain('<meta name="viewport" content="width=device-width');
65 expect(injected.endsWith(fragment)).toBe(true);
66 });
67​
68 it("ignores tags written inside comments and scripts", () => {
69 const html =
70 '<!-- copy <head> and <meta name="viewport"> here --><html><head>' +
71 "<script>const tag = '<meta name=\"viewport\">';</script></head><body>x</body></html>";
72 const injected = injectHtmlRenderBootstrap(html);
73 expect(injected.indexOf('<style id="t3-theme">')).toBeGreaterThan(
74 injected.indexOf("<html><head>"),
75 );
76 expect(injected).toContain('<meta name="viewport" content="width=device-width');
77 });
78});
79​
80describe("readHtmlRenderLinkRequest", () => {
81 it("accepts only http(s) URLs in an MCP Apps ui/open-link request", () => {
82 const link = (url: unknown, modifiers = {}) => ({
83 jsonrpc: "2.0",
84 id: 1,
85 method: "ui/open-link",
86 params: { url, ...modifiers },
87 });
88 expect(readHtmlRenderLinkRequest(link("https://example.com/a"))).toEqual({
89 id: 1,
90 url: "https://example.com/a",
91 metaKey: false,
92 ctrlKey: false,
93 });
94 expect(
95 readHtmlRenderLinkRequest(link("https://example.com/a", { metaKey: true, ctrlKey: "yes" })),
96 ).toEqual({ id: 1, url: "https://example.com/a", metaKey: true, ctrlKey: false });
97 expect(readHtmlRenderLinkRequest(link("javascript:alert(1)"))).toBeUndefined();
98 expect(readHtmlRenderLinkRequest(link("file:///etc/passwd"))).toBeUndefined();
99 expect(
100 readHtmlRenderLinkRequest({
101 jsonrpc: "2.0",
102 method: "ui/open-link",
103 params: { url: "https://example.com" },
104 }),
105 ).toBeUndefined();
106 expect(
107 readHtmlRenderLinkRequest({ type: "t3-html-render-link", url: "https://example.com" }),
108 ).toBeUndefined();
109 });
110});
111​
112describe("readHtmlRenderKeyDown", () => {
113 it("reads the key of a keydown notification and nothing else", () => {
114 const notification = (params: unknown) => ({
115 jsonrpc: "2.0",
116 method: "t3/notifications/keydown",
117 params,
118 });
119 expect(readHtmlRenderKeyDown(notification({ key: "k", code: "KeyK", metaKey: true }))).toEqual({
120 key: "k",
121 code: "KeyK",
122 metaKey: true,
123 ctrlKey: false,
124 shiftKey: false,
125 altKey: false,
126 repeat: false,
127 });
128 expect(readHtmlRenderKeyDown(notification({ key: 1, code: "KeyK" }))).toBeUndefined();
129 expect(
130 readHtmlRenderKeyDown({ jsonrpc: "2.0", method: "ui/open-link", params: { key: "k" } }),
131 ).toBeUndefined();
132 });
133});
134​
135describe("readHtmlRenderContentHeight", () => {
136 it("reads only the height of an MCP Apps size-changed notification", () => {
137 const notification = (params: unknown) => ({
138 jsonrpc: "2.0",
139 method: "ui/notifications/size-changed",
140 params,
141 });
142 expect(readHtmlRenderContentHeight(notification({ height: 412 }))).toBe(412);
143 expect(readHtmlRenderContentHeight(notification({ height: "412" }))).toBe(undefined);
144 expect(readHtmlRenderContentHeight(notification({ height: 0 }))).toBe(undefined);
145 expect(readHtmlRenderContentHeight({ ...notification({ height: 412 }), method: "x" })).toBe(
146 undefined,
147 );
148 });
149});
150​
151describe("htmlRenderThemeMessage", () => {
152 it("is an MCP Apps host-context-changed notification carrying the theme variables", () => {
153 const theme = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");
154 expect(htmlRenderThemeMessage(theme)).toEqual({
155 jsonrpc: "2.0",
156 method: "ui/notifications/host-context-changed",
157 params: { theme: "dark", styles: { variables: theme.variables } },
158 });
159 });
160});
161​
162describe("htmlRenderTheme", () => {
163 it("exposes the brand accent as --accent and keeps the fragment decodable", () => {
164 const theme = htmlRenderTheme(T3_CODE_LIGHT_THEME_COLORS, "light");
165 expect(theme.variables["--accent"]).toBe(T3_CODE_LIGHT_THEME_COLORS.accent);
166 expect(theme.variables["--chart-1"]).toBe(T3_CODE_LIGHT_THEME_COLORS.accent);
167 expect(theme.variables["--chart-6"]).toBeDefined();
168 const fragment = htmlRenderThemeFragment(theme);
169 expect(JSON.parse(decodeURIComponent(fragment.slice("#t3-theme=".length)))).toEqual(theme);
170 expect(fragment).not.toContain("&");
171 expect(htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark").variables["--background"]).toBe(
172 T3_CODE_DARK_THEME_COLORS.canvas,
173 );
174 });
175});
176​
177describe("readHtmlRenderReference", () => {
178 it("clamps height and rejects malformed references", () => {
179 expect(readHtmlRenderReference({ ...reference, height: 99_999 })?.height).toBe(2000);
180 expect(readHtmlRenderReference({ ...reference, title: " " })?.title).toBe("HTML");
181 expect(readHtmlRenderReference({ ...reference, attachmentId: 4 })).toBeUndefined();
182 expect(readHtmlRenderReference({ ...reference, height: Number.NaN })).toBeUndefined();
183 });
184});
185​
186describe("htmlRenderFromToolItem", () => {
187 const result = { htmlRender: reference, message: "Rendered above your reply." };
188​
189 it("reads the reference from each provider's result envelope", () => {
190 for (const [toolName, output] of [
191 ["mcp__t3-code__html_render", [{ type: "text", text: JSON.stringify(result) }]],
192 ["t3-code.html_render", { structuredContent: result, content: [] }],
193 ["t3-code-thread_1_html_render", JSON.stringify(result)],
194 ["html_render", result],
195 ] as const) {
196 expect(htmlRenderFromToolItem({ toolName, output })).toEqual(reference);
197 }
198 });
199​
200 it("ignores other tools and failed calls", () => {
201 expect(htmlRenderFromToolItem({ toolName: "mcp__t3-code__html_preview", output: result })).toBe(
202 undefined,
203 );
204 expect(htmlRenderFromToolItem({ toolName: "mcp__other__html_render", output: result })).toBe(
205 undefined,
206 );
207 expect(
208 htmlRenderFromToolItem({ toolName: "html_render", output: { ...result, isError: true } }),
209 ).toBeUndefined();
210 });
211});
212​
213describe("htmlRenderFrameHeight", () => {
214 const measured = readHtmlRenderReference({
215 ...reference,
216 height: 1500,
217 heights: [
218 [728, 1403],
219 [390, 1290],
220 [1000, 1660],
221 ],
222 })!;
223​
224 it("takes the taller neighbor between measured widths and holds the ends", () => {
225 expect(measured.heights?.map(([width]) => width)).toEqual([390, 728, 1000]);
226 expect(htmlRenderFrameHeight(measured, 728)).toBe(1403);
227 expect(htmlRenderFrameHeight(measured, 559)).toBe(1403);
228 expect(htmlRenderFrameHeight(measured, 320)).toBe(1290);
229 });
230​
231 it("takes the taller layout when a breakpoint falls between measured widths", () => {
232 // 900px tall below a 600px media query, 450px above it.
233 const responsive = readHtmlRenderReference({
234 ...reference,
235 height: 2000,
236 heights: [
237 [520, 900],
238 [640, 450],
239 ],
240 })!;
241 expect(htmlRenderFrameHeight(responsive, 590)).toBe(900);
242 expect(htmlRenderFrameHeight(responsive, 640)).toBe(450);
243 });
244​
245 it("fits a page the client lays out taller than the server measured", () => {
246 // The agent passed contentHeight at the column width, so the page should never scroll.
247 const fitted = { ...measured, height: 1403 };
248 expect(htmlRenderFrameHeight(fitted, 728, 1415)).toBe(1415);
249 expect(htmlRenderFrameHeight(fitted, 1400)).toBe(1660);
250 expect(htmlRenderFrameHeight(fitted, 728, 5000)).toBe(HTML_RENDER_MAX_HEIGHT);
251 });
252​
253 it("keeps the agent's height when it asked for a scrolling frame or the page is unmeasured", () => {
254 const scrolling = { ...measured, height: 600 };
255 expect(htmlRenderFrameHeight(scrolling, 728, 1415)).toBe(600);
256 expect(htmlRenderFrameHeight(scrolling, 1400)).toBe(600);
257 expect(htmlRenderFrameHeight(reference, 728)).toBe(reference.height);
258 expect(htmlRenderFrameHeight(reference, 728, 900)).toBe(reference.height);
259 expect(htmlRenderFrameHeight(reference, 728, 300)).toBe(300);
260 });
261​
262 it("drops a malformed table and compares tables by value", () => {
263 expect(readHtmlRenderReference({ ...reference, heights: [[728, "x"]] })?.heights).toBe(
264 undefined,
265 );
266 const copy = readHtmlRenderReference(JSON.parse(JSON.stringify(measured)))!;
267 expect(htmlRenderReferencesEqual(measured, copy)).toBe(true);
268 expect(htmlRenderReferencesEqual(measured, { ...copy, heights: [[390, 1290]] })).toBe(false);
269 });
270});
271​
272describe("htmlRenderOutlineBoxes", () => {
273 const outline = encodeHtmlRenderOutline([
274 { kind: "text", x: 0, y: 0, width: 300, height: 40, lines: 2 },
275 { kind: "media", x: 0, y: 48, width: 728, height: 300, lines: 1 },
276 { kind: "media", x: 2, y: 2, width: 0, height: 10, lines: 1 },
277 ]);
278 const outlined = readHtmlRenderReference({
279 ...reference,
280 heights: [
281 [364, 1600],
282 [728, 800],
283 ],
284 outline,
285 })!;
286​
287 it("round-trips through a tool result and stretches to the client's width and height", () => {
288 // The empty box is dropped when encoded.
289 expect(outline).toBe("t0,0,75,10,2;m0,12,182,75,1");
290 expect(htmlRenderOutlineBoxes(outlined, 728)).toEqual([
291 { kind: "text", x: 0, y: 0, width: 300, height: 40, lines: 2 },
292 { kind: "media", x: 0, y: 48, width: 728, height: 300, lines: 1 },
293 ]);
294 expect(htmlRenderOutlineBoxes(outlined, 364)[1]).toEqual({
295 kind: "media",
296 x: 0,
297 y: 96,
298 width: 364,
299 height: 600,
300 lines: 1,
301 });
302 });
303​
304 it("drops a malformed or unmeasured outline", () => {
305 expect(readHtmlRenderReference({ ...outlined, outline: "x1,2" })?.outline).toBeUndefined();
306 expect(
307 readHtmlRenderReference({ ...outlined, outline: "t0,0,10,10,0" })?.outline,
308 ).toBeUndefined();
309 expect(
310 readHtmlRenderReference({ ...outlined, outline: "m0,0,0,10,1" })?.outline,
311 ).toBeUndefined();
312 expect(readHtmlRenderReference({ ...reference, outline })?.outline).toBeUndefined();
313 expect(htmlRenderOutlineBoxes(reference, 728)).toEqual([]);
314 expect(htmlRenderReferencesEqual(outlined, { ...outlined, outline: "m0,0,1,1,1" })).toBe(false);
315 });
316});