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

htmlRender.test.ts

282 lines11.5 KB

1import { describe, expect, it } from "vite-plus/test";
2​
3import {
4 htmlRenderFileName,
5 htmlRenderFrameHeight,
6 injectHtmlRenderBootstrap,
7 readHtmlRenderImageRequest,
8 readHtmlRenderLinkRequest,
9 htmlRenderTheme,
10} from "./htmlRender.ts";
11import { T3_CODE_DARK_THEME_COLORS } from "./themePalettes.ts";
12import { htmlRenderFromToolItem } from "./toolOutput.ts";
13​
14const reference = { attachmentId: "thread-abc-123.html", title: "Chart", height: 420 };
15​
16describe("htmlRenderFileName", () => {
17 it("never ends on half of an emoji at the length limit", () => {
18 const fits = "a".repeat(118);
19 const crosses = "a".repeat(119);
20 expect(htmlRenderFileName(`${fits}🚀 report`)).toBe(`${fits}🚀.html`);
21 expect(htmlRenderFileName(`${crosses}🚀 report`)).toBe(`${crosses}.html`);
22 });
23});
24​
25describe("htmlRenderFrameHeight", () => {
26 const responsive = {
27 attachmentId: "a",
28 title: "Report",
29 height: 600,
30 heights: [
31 [728, 350],
32 [1000, 700],
33 [1144, 250],
34 ],
35 } as const;
36​
37 it("uses the last measured height at and above the widest sampled width", () => {
38 expect(
39 [1143, 1144, 1145, 1300].map((width) => htmlRenderFrameHeight(responsive, width)),
40 ).toEqual([700, 250, 250, 250]);
41 });
42});
43​
44describe("injectHtmlRenderBootstrap", () => {
45 it("puts the theme ahead of the page's own head content", () => {
46 const html =
47 "<!doctype html><html><head><style>:root{--background:red}</style></head><body>x</body></html>";
48 const injected = injectHtmlRenderBootstrap(html);
49 const themeAt = injected.indexOf('<style id="t3-theme">');
50 expect(themeAt).toBeGreaterThan(injected.indexOf("<head>"));
51 expect(themeAt).toBeLessThan(injected.indexOf(":root{--background:red}"));
52 expect(injected).toContain('<meta charset="utf-8">');
53 expect(injected).toContain('name="viewport"');
54 });
55​
56 it.each([
57 "<html><head data-condition='x > 0'>",
58 '<html><head data-condition="x > 0" data-label=\'it "works"\'>',
59 "<html data-condition='x > 0'>",
60 '<html data-condition="x > 0" data-label="it \'works\'">',
61 ])("keeps the bootstrap after the complete opening tag: %s", (opening) => {
62 const prefix = `<!doctype html>${opening}`;
63 const head = opening.startsWith("<html><head") ? "" : "<head>";
64 const content = `${head ? "" : "<title>Report</title></head>"}<body><p>Report</p></body></html>`;
65 const injected = injectHtmlRenderBootstrap(prefix + content);
66 expect(injected.startsWith(`${prefix}${head}<meta charset="utf-8">`)).toBe(true);
67 expect(injected.indexOf('<style id="t3-theme">')).toBeGreaterThan(prefix.length);
68 expect(injected).toContain("<script>");
69 expect(injected.endsWith(content)).toBe(true);
70 });
71​
72 it("wraps fragments without a head and keeps existing meta tags", () => {
73 const fragment =
74 '<meta charset="utf-8"><meta data-if="a<b" name="viewport" content="width=device-width"><p>hi</p>';
75 const injected = injectHtmlRenderBootstrap(fragment);
76 expect(injected.startsWith("<!doctype html><head>")).toBe(true);
77 expect(injected.match(/charset/g)).toHaveLength(1);
78 expect(injected.match(/name="viewport"/g)).toHaveLength(1);
79 expect(injected.endsWith("<p>hi</p>")).toBe(true);
80 });
81​
82 it.each([
83 '<meta data-name="viewport" content="card">',
84 '<meta name="viewport-fit" content="cover">',
85 "<meta name=viewport-fit content=cover>",
86 ])("injects a default viewport when metadata is only viewport-like: %s", (fragment) => {
87 const injected = injectHtmlRenderBootstrap(fragment);
88 expect(injected).toContain(
89 '<meta name="viewport" content="width=device-width, initial-scale=1">',
90 );
91 expect(injected.endsWith(fragment)).toBe(true);
92 });
93​
94 it.each([
95 "<meta name='viewport' content='width=600'>",
96 "<meta name=viewport />",
97 '<meta data-x="1"name="viewport" content="width=600">',
98 '<meta data-if="a>b" name="viewport" content="width=600">',
99 ])("preserves a genuine viewport declaration: %s", (fragment) => {
100 const injected = injectHtmlRenderBootstrap(fragment);
101 expect(injected).not.toContain(
102 '<meta name="viewport" content="width=device-width, initial-scale=1">',
103 );
104 expect(injected.endsWith(fragment)).toBe(true);
105 });
106​
107 it.each(["textarea", "iframe", "plaintext"])("keeps the bootstrap outside %s content", (tag) => {
108 const fragment = `<${tag}><head><meta name="viewport"></head></${tag}>`;
109 const injected = injectHtmlRenderBootstrap(fragment);
110 expect(injected.startsWith("<!doctype html><head>")).toBe(true);
111 expect(injected.indexOf('<style id="t3-theme">')).toBeLessThan(injected.indexOf(`<${tag}>`));
112 expect(injected).toContain('<meta name="viewport" content="width=device-width');
113 expect(injected.endsWith(fragment)).toBe(true);
114 });
115​
116 it.each([
117 '<template><head><meta name="viewport"></head></template>',
118 '<template><template>inner</template><head><meta name="viewport"></head></template>',
119 '<template data-if="a<b"><head><meta name="viewport"></head></template>',
120 ])("keeps the bootstrap outside inert template content: %s", (fragment) => {
121 const injected = injectHtmlRenderBootstrap(fragment);
122 expect(injected.startsWith("<!doctype html><head>")).toBe(true);
123 expect(injected.indexOf('<style id="t3-theme">')).toBeLessThan(injected.indexOf("<template"));
124 expect(injected).toContain('<meta name="viewport" content="width=device-width');
125 expect(injected.endsWith(fragment)).toBe(true);
126 });
127​
128 it.each([
129 "<template ",
130 "<template '",
131 "<meta ",
132 "<meta name ",
133 '<meta "',
134 "<head ",
135 "<head '",
136 '<html a="b" ',
137 ])("scans a run of unclosed %s tags in one pass", (tag) => {
138 const fragment = tag.repeat(2_000_000 / tag.length);
139 const injected = injectHtmlRenderBootstrap(fragment);
140 expect(injected.startsWith("<!doctype html><head>")).toBe(true);
141 expect(injected.endsWith(fragment)).toBe(true);
142 });
143​
144 it("ignores tags written inside comments and scripts", () => {
145 const html =
146 '<!-- copy <head> and <meta name="viewport"> here --><html><head>' +
147 "<script>const tag = '<meta name=\"viewport\">';</script></head><body>x</body></html>";
148 const injected = injectHtmlRenderBootstrap(html);
149 expect(injected.indexOf('<style id="t3-theme">')).toBeGreaterThan(
150 injected.indexOf("<html><head>"),
151 );
152 expect(injected).toContain('<meta name="viewport" content="width=device-width');
153 });
154});
155​
156describe("readHtmlRenderLinkRequest", () => {
157 it("accepts only http(s) URLs in an MCP Apps ui/open-link request", () => {
158 const link = (url: unknown, modifiers = {}) => ({
159 jsonrpc: "2.0",
160 id: 1,
161 method: "ui/open-link",
162 params: { url, ...modifiers },
163 });
164 expect(readHtmlRenderLinkRequest(link("https://example.com/a"))).toEqual({
165 id: 1,
166 url: "https://example.com/a",
167 metaKey: false,
168 ctrlKey: false,
169 });
170 expect(
171 readHtmlRenderLinkRequest(link("https://example.com/a", { metaKey: true, ctrlKey: "yes" })),
172 ).toEqual({ id: 1, url: "https://example.com/a", metaKey: true, ctrlKey: false });
173 expect(readHtmlRenderLinkRequest(link("javascript:alert(1)"))).toBeUndefined();
174 expect(readHtmlRenderLinkRequest(link("file:///etc/passwd"))).toBeUndefined();
175 expect(
176 readHtmlRenderLinkRequest({
177 jsonrpc: "2.0",
178 method: "ui/open-link",
179 params: { url: "https://example.com" },
180 }),
181 ).toBeUndefined();
182 expect(
183 readHtmlRenderLinkRequest({ type: "t3-html-render-link", url: "https://example.com" }),
184 ).toBeUndefined();
185 });
186});
187​
188describe("readHtmlRenderImageRequest", () => {
189 it("accepts http(s) and inline image URLs in an open-image notification", () => {
190 const image = (params: unknown) => ({
191 jsonrpc: "2.0",
192 method: "t3/notifications/open-image",
193 params,
194 });
195 expect(
196 readHtmlRenderImageRequest(image({ src: "data:image/png;base64,AA", name: " Chart " })),
197 ).toEqual({ images: [{ src: "data:image/png;base64,AA", name: "Chart" }], index: 0 });
198 expect(readHtmlRenderImageRequest(image({ src: "https://example.com/a.png" }))).toEqual({
199 images: [{ src: "https://example.com/a.png", name: "Image" }],
200 index: 0,
201 });
202 const boundaryImage = readHtmlRenderImageRequest(
203 image({ src: "https://example.com/a.png", name: "a".repeat(199) + "😀" }),
204 );
205 expect(boundaryImage?.images[0]?.name.isWellFormed()).toBe(true);
206 expect(boundaryImage?.images[0]?.name).toBe("a".repeat(199));
207 expect(readHtmlRenderImageRequest(image({ src: "javascript:alert(1)" }))).toBeUndefined();
208 expect(readHtmlRenderImageRequest(image({ src: "data:text/html,<p>" }))).toBeUndefined();
209 expect(readHtmlRenderImageRequest(image({ src: "blob:null/1" }))).toBeUndefined();
210 });
211​
212 it("keeps the page's other images, dropping unsafe ones, around the clicked image", () => {
213 const b = { src: "https://example.com/b.png", name: "B" };
214 const params = {
215 ...b,
216 images: [{ src: "https://example.com/a.png", name: "A" }, { src: "blob:null/1" }, b, null],
217 index: 2,
218 };
219 const request = (overrides: object) =>
220 readHtmlRenderImageRequest({
221 jsonrpc: "2.0",
222 method: "t3/notifications/open-image",
223 params: { ...params, ...overrides },
224 });
225 expect(request({})).toEqual({
226 images: [{ src: "https://example.com/a.png", name: "A" }, b],
227 index: 1,
228 });
229 // An index that does not point at the clicked image falls back to that image alone.
230 expect(request({ index: 0 })).toEqual({ images: [b], index: 0 });
231 expect(request({ index: -1 })).toEqual({ images: [b], index: 0 });
232 });
233});
234​
235describe("htmlRenderFromToolItem", () => {
236 const result = { htmlRender: reference, message: "Rendered above your reply." };
237​
238 it("reads the reference from each provider's result envelope", () => {
239 for (const [toolName, output] of [
240 ["mcp__t3-code__html_render", [{ type: "text", text: JSON.stringify(result) }]],
241 ["t3-code.html_render", { structuredContent: result, content: [] }],
242 ["t3-code-thread_1_html_render", JSON.stringify(result)],
243 ["html_render", result],
244 // OpenCode 2 Code Mode reports a script's nested html_render call as one `execute` item.
245 ["execute", JSON.stringify(result)],
246 // Antigravity runs the `acp-mcp-call` terminal fallback and wraps its stdout.
247 [
248 "t3-code.html_render",
249 {
250 output: `Created At: 2026-11-19T02:54:02Z\nCompleted At: 2026-11-19T02:54:02Z\nCommand exited with code 0.\n\nCommand output:\n${JSON.stringify({ content: [], structuredContent: result, isError: false })}\r\n`,
251 exit_code: 0,
252 },
253 ],
254 ] as const) {
255 expect(htmlRenderFromToolItem({ toolName, output })).toEqual(reference);
256 }
257 });
258});
259​
260function contrastRatio(a: string, b: string): number {
261 const luminance = (hex: string) => {
262 const [r, g, b] = [1, 3, 5].map((i) => {
263 const c = Number.parseInt(hex.slice(i, i + 2), 16) / 255;
264 return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
265 });
266 return 0.2126 * r! + 0.7152 * g! + 0.0722 * b!;
267 };
268 const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
269 return (hi! + 0.05) / (lo! + 0.05);
271​
272describe("htmlRenderTheme", () => {
273 it("keeps accent-based graphic colors visible on the canvas when the theme accent is dark", () => {
274 const { variables } = htmlRenderTheme(
275 { ...T3_CODE_DARK_THEME_COLORS, canvas: "#161515", accent: "#21180e" },
276 "dark",
277 );
278 for (const name of ["--chart-1", "--accent"]) {
279 expect(contrastRatio(variables[name]!, variables["--background"]!)).toBeGreaterThanOrEqual(3);
280 }
281 });
282});