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

htmlRender.ts

382 lines17.2 KB

1import {
2 T3_CODE_DARK_THEME_COLORS,
3 T3_CODE_LIGHT_THEME_COLORS,
4 type ThemeAppearance,
5 type ThemeColors,
6} from "./themePalettes.ts";
7​
8/**
9 * Agent-authored HTML pages ("HTML renders") are self-contained documents an
10 * agent publishes into a thread with T3's `html_render` MCP tool. The server
11 * stores each one as a thread attachment with a small bootstrap injected into
12 * its head; clients show it in a sandboxed iframe (web, desktop) or WebView
13 * (mobile) and hand it the active theme as CSS custom properties.
14 */
15​
16export const HTML_RENDER_TOOL_NAME = "html_render";
17export const HTML_RENDER_MIN_HEIGHT = 80;
18export const HTML_RENDER_MAX_HEIGHT = 2000;
19export const HTML_RENDER_MAX_TITLE_LENGTH = 200;
20​
21/** What the `html_render` tool result carries so clients can show the page. */
22export interface HtmlRenderReference {
23 readonly attachmentId: string;
24 readonly title: string;
25 /** The agent's frame height in CSS pixels, and the cap on any measured height. */
26 readonly height: number;
27 /**
28 * `[width, contentHeight]` pairs the server measured at publish, ascending by
29 * width. Absent when the preview browser was not installed yet.
30 */
31 readonly heights?: ReadonlyArray<readonly [width: number, height: number]>;
33​
34/** Frame widths the server measures a page at, from phones to the wide chat setting. */
35export const HTML_RENDER_MEASURE_WIDTHS = [320, 375, 430, 520, 640, 728, 860, 1000, 1144] as const;
36​
37/**
38 * The reply column's frame width at the default chat width. Agents preview at
39 * it, and it picks the measured height when a client cannot know its width.
40 */
41export const HTML_RENDER_COLUMN_WIDTH = 728;
42​
43const MAX_MEASURED_HEIGHTS = 24;
44​
45function readMeasuredHeights(value: unknown) {
46 if (!Array.isArray(value) || value.length === 0 || value.length > MAX_MEASURED_HEIGHTS) {
47 return undefined;
48 }
49 const heights = value.flatMap((entry) =>
50 Array.isArray(entry) &&
51 entry.length === 2 &&
52 Number.isInteger(entry[0]) &&
53 entry[0] >= 1 &&
54 entry[0] <= 10_000 &&
55 typeof entry[1] === "number" &&
56 Number.isFinite(entry[1])
57 ? [[entry[0] as number, clampHtmlRenderHeight(entry[1])] as const]
58 : [],
59 );
60 return heights.length === value.length
61 ? [...heights].sort((left, right) => left[0] - right[0])
62 : undefined;
64​
65export function readHtmlRenderReference(value: unknown): HtmlRenderReference | undefined {
66 if (typeof value !== "object" || value === null) return undefined;
67 const { attachmentId, title, height, heights } = value as Record<string, unknown>;
68 if (
69 typeof attachmentId !== "string" ||
70 attachmentId.length === 0 ||
71 attachmentId.length > 256 ||
72 typeof title !== "string" ||
73 typeof height !== "number" ||
74 !Number.isFinite(height)
75 ) {
76 return undefined;
77 }
78 const measured = readMeasuredHeights(heights);
79 return {
80 attachmentId,
81 title: title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
82 height: clampHtmlRenderHeight(height),
83 ...(measured === undefined ? {} : { heights: measured }),
84 };
86​
87/** Whether two references show the same page at the same sizes. */
88export function htmlRenderReferencesEqual(left: HtmlRenderReference, right: HtmlRenderReference) {
89 return (
90 left.attachmentId === right.attachmentId &&
91 left.title === right.title &&
92 left.height === right.height &&
93 (left.heights ?? []).length === (right.heights ?? []).length &&
94 (left.heights ?? []).every(
95 ([width, height], index) =>
96 right.heights?.[index]?.[0] === width && right.heights[index][1] === height,
97 )
98 );
100​
101/**
102 * The frame height for a page at a frame width: the taller of the heights
103 * measured at the nearest widths on each side, capped at the agent's height.
104 * A breakpoint between two measured widths can make the page as tall as
105 * either, so the frame takes the taller. A page whose height grows with its
106 * width inside one layout can still run slightly past the frame between
107 * measured widths.
108 */
109export function htmlRenderFrameHeight(reference: HtmlRenderReference, width: number) {
110 const heights = reference.heights;
111 if (heights === undefined || heights.length === 0) return reference.height;
112 const above = heights.findIndex(([measuredWidth]) => measuredWidth >= width);
113 const high = above === -1 ? heights.length - 1 : above;
114 const low = heights[high]![0] === width ? high : Math.max(0, high - 1);
115 const measured = Math.max(heights[low]![1], heights[high]![1]);
116 return clampHtmlRenderHeight(Math.min(reference.height, measured));
118​
119/** A readable download name: the title without characters file systems reject. */
120export function htmlRenderFileName(title: string) {
121 const name = title
122 .replace(/[\\/:*?"<>|\p{Cc}]+/gu, " ")
123 .replace(/\s+/g, " ")
124 .trim()
125 .slice(0, 120)
126 .trim();
127 return `${name || "Page"}.html`;
129​
130export function clampHtmlRenderHeight(height: number): number {
131 return Math.min(HTML_RENDER_MAX_HEIGHT, Math.max(HTML_RENDER_MIN_HEIGHT, Math.round(height)));
133​
134export interface HtmlRenderFonts {
135 readonly sans: string;
136 readonly mono: string;
138​
139export const HTML_RENDER_DEFAULT_FONTS: HtmlRenderFonts = {
140 sans: '-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',
141 // Concrete names only: some engines alias `ui-monospace` to the proportional UI font.
142 mono: '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace',
143};
144​
145/**
146 * Fonts the server's headless browser lays pages out with. Arial-metric faces
147 * stand in for the system UI fonts readers see, so measured heights and
148 * preview screenshots wrap text close to how a client will.
149 */
150export const HTML_RENDER_MEASURE_FONTS: HtmlRenderFonts = {
151 sans: '"Liberation Sans", Arimo, Arial, Helvetica, sans-serif',
152 mono: '"Liberation Mono", Cousine, Menlo, Consolas, monospace',
153};
154​
155/** The resolved theme a client hands an HTML render. */
156export interface HtmlRenderTheme {
157 readonly appearance: ThemeAppearance;
158 readonly variables: Readonly<Record<string, string>>;
160​
161// Roles themes cannot change (index.css keeps info/success fixed), plus a
162// categorical chart series after the theme's own accent.
163const FIXED_COLORS = {
164 light: {
165 success: "#10b981",
166 successForeground: "#047857",
167 info: "#3b82f6",
168 infoForeground: "#1d4ed8",
169 chart: ["#0d9488", "#d97706", "#9333ea", "#e11d48", "#65a30d"],
170 },
171 dark: {
172 success: "#10b981",
173 successForeground: "#34d399",
174 info: "#3b82f6",
175 infoForeground: "#60a5fa",
176 chart: ["#2dd4bf", "#fbbf24", "#c084fc", "#fb7185", "#a3e635"],
177 },
178} as const;
179​
180/**
181 * Maps a theme palette to the variables HTML renders style against. Names
182 * follow the app's own tokens, except `--accent`, which is the theme's brand
183 * color here rather than the app's neutral hover surface.
184 */
185export function htmlRenderTheme(
186 colors: ThemeColors,
187 appearance: ThemeAppearance,
188 fonts: HtmlRenderFonts = HTML_RENDER_DEFAULT_FONTS,
189): HtmlRenderTheme {
190 const fixed = FIXED_COLORS[appearance];
191 return {
192 appearance,
193 variables: {
194 "--background": colors.canvas,
195 "--foreground": colors.text,
196 "--muted": colors.muted,
197 "--muted-foreground": colors.mutedForeground,
198 "--card": colors.surface,
199 "--card-foreground": colors.text,
200 "--popover": colors.surfaceOverlay,
201 "--popover-foreground": colors.text,
202 "--secondary": colors.secondary,
203 "--secondary-foreground": colors.secondaryForeground,
204 "--border": colors.border,
205 "--input": colors.input,
206 "--ring": colors.focus,
207 "--primary": colors.messageAction,
208 "--primary-foreground": colors.messageActionForeground,
209 "--accent": colors.accent,
210 "--accent-foreground": colors.accentForeground,
211 "--accent-surface": colors.accentSurface,
212 "--accent-surface-foreground": colors.accentSurfaceForeground,
213 "--destructive": colors.error,
214 "--destructive-foreground": colors.errorForeground,
215 "--destructive-surface": colors.errorSurface,
216 "--warning": colors.warning,
217 "--warning-foreground": colors.warningForeground,
218 "--warning-surface": colors.warningSurface,
219 "--success": fixed.success,
220 "--success-foreground": fixed.successForeground,
221 "--info": fixed.info,
222 "--info-foreground": fixed.infoForeground,
223 "--code-background": colors.codeBackground,
224 "--code-foreground": colors.codeForeground,
225 "--chart-1": colors.accent,
226 ...Object.fromEntries(fixed.chart.map((color, index) => [`--chart-${index + 2}`, color])),
227 "--radius": "0.625rem",
228 "--font-sans": fonts.sans,
229 "--font-mono": fonts.mono,
230 },
231 };
233​
234/** Agent-facing reference for the injected variables, used in tool descriptions. */
235export const HTML_RENDER_THEME_GUIDE = [
236 "T3 injects its active theme as CSS custom properties on :root, and they follow the user's theme and light/dark mode live:",
237 "--background (page background, identical to the thread around the frame), --foreground, --muted, --muted-foreground,",
238 "--card, --card-foreground, --popover, --popover-foreground, --secondary, --secondary-foreground, --border, --input, --ring,",
239 "--primary, --primary-foreground (solid buttons), --accent, --accent-foreground (brand accent), --accent-surface, --accent-surface-foreground,",
240 "--destructive, --destructive-foreground, --destructive-surface, --warning, --warning-foreground, --warning-surface,",
241 "--success, --success-foreground, --info, --info-foreground, --code-background, --code-foreground,",
242 "--chart-1 … --chart-6 (categorical series for charts), --radius, --font-sans, --font-mono.",
243 "The base stylesheet sets html background/color/font from these, body margin to 0, and hides the page's scrollbar; your own CSS overrides it.",
244].join(" ");
245​
246/** Agent-facing layout rules for a page that sits inside a reply. */
247export const HTML_RENDER_LAYOUT_GUIDE = [
248 `The frame is borderless on the thread's background, as wide as the reply column (${HTML_RENDER_COLUMN_WIDTH}px on desktop by default, wider if the reader widens chat, about 360px on phones), and its left edge lines up with your reply text.`,
249 "Use a fluid width with no horizontal padding on the outermost element, and no outer card, border, or banner title: the page is part of your reply.",
250 "Give charts fixed pixel heights rather than heights that scale with width.",
251].join(" ");
252​
253// The bridge between a render and its client speaks the MCP Apps protocol
254// (JSON-RPC over postMessage), so the same host code can later drive upstream
255// MCP apps: https://github.com/modelcontextprotocol/ext-apps
256const HOST_CONTEXT_CHANGED_METHOD = "ui/notifications/host-context-changed";
257const OPEN_LINK_METHOD = "ui/open-link";
258​
259/** A render's `ui/open-link` request, if `data` is one with an http(s) URL. */
260export function readHtmlRenderLinkRequest(
261 data: unknown,
262): { readonly id: string | number; readonly url: string } | undefined {
263 if (typeof data !== "object" || data === null) return undefined;
264 const { jsonrpc, id, method, params } = data as Record<string, unknown>;
265 if (jsonrpc !== "2.0" || method !== OPEN_LINK_METHOD) return undefined;
266 if (typeof id !== "string" && typeof id !== "number") return undefined;
267 const url =
268 typeof params === "object" && params !== null ? (params as { url?: unknown }).url : undefined;
269 return typeof url === "string" && /^https?:\/\//i.test(url) ? { id, url } : undefined;
271​
272/** The empty result a client sends back for a render's request. */
273export function htmlRenderResult(id: string | number) {
274 return { jsonrpc: "2.0", id, result: {} } as const;
276​
277const THEME_FRAGMENT_KEY = "t3-theme";
278​
279/** URL fragment that hands a render its theme before first paint. */
280export function htmlRenderThemeFragment(theme: HtmlRenderTheme): string {
281 return `#${THEME_FRAGMENT_KEY}=${encodeURIComponent(JSON.stringify(theme))}`;
283​
284/** The `host-context-changed` notification a client posts into a mounted render when the theme changes. */
285export function htmlRenderThemeMessage(theme: HtmlRenderTheme) {
286 return {
287 jsonrpc: "2.0",
288 method: HOST_CONTEXT_CHANGED_METHOD,
289 params: { theme: theme.appearance, styles: { variables: theme.variables } },
290 } as const;
292​
293// The frame scrolls a page taller than itself, but a scrollbar inside the
294// reply reads as a box within the thread, so it stays hidden.
295const BASE_CSS =
296 "html{background:var(--background);color:var(--foreground);font-family:var(--font-sans);font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;scrollbar-width:none}" +
297 "html::-webkit-scrollbar{display:none}body{margin:0}code,kbd,pre,samp{font-family:var(--font-mono)}";
298​
299function rootRule(theme: HtmlRenderTheme): string {
300 const declarations = Object.entries(theme.variables)
301 .map(([name, value]) => `${name}:${value};`)
302 .join("");
303 return `:root{color-scheme:${theme.appearance};${declarations}}`;
305​
306// Runs synchronously in <head>, before the page's own styles and body, so the
307// first paint is already themed. It rewrites its own <style> element rather
308// than setting inline properties, so a page's later `:root` rules still win,
309// then drops the fragment so a page's own hash routing never sees it. A link
310// the reader clicks to another page never replaces the page inside the thread:
311// a framed page asks its client to open it, and a top-level page (mobile)
312// opens it as a new window, which the client sends to the browser.
313const BOOTSTRAP_SCRIPT = `(function(){var s=document.getElementById("t3-theme"),n=0;if(!s)return;var b=${JSON.stringify(BASE_CSS)};function a(t){if(!t||typeof t!=="object"||!t.variables||typeof t.variables!=="object")return;var c=":root{color-scheme:"+(t.appearance==="light"?"light":"dark")+";";for(var k in t.variables){if(/^--[a-z0-9-]+$/.test(k))c+=k+":"+String(t.variables[k]).replace(/[;{}<>]/g,"")+";";}s.textContent=c+"}"+b;}try{var m=/[#&]${THEME_FRAGMENT_KEY}=([^&]*)/.exec(location.hash);if(m){a(JSON.parse(decodeURIComponent(m[1])));history.replaceState(history.state,"",location.pathname+location.search);}}catch(e){}window.addEventListener("message",function(e){var d=e.data,p=d&&d.params;if(d&&d.jsonrpc==="2.0"&&d.method===${JSON.stringify(HOST_CONTEXT_CHANGED_METHOD)}&&p&&p.styles)a({appearance:p.theme,variables:p.styles.variables});});document.addEventListener("click",function(e){var l=e.isTrusted?e.composedPath().find(function(t){return t&&t.matches&&t.matches("a[href]");}):null,u;if(!l)return;try{u=new URL(l.getAttribute("href"),document.baseURI);}catch(x){return;}if(!/^https?:$/.test(u.protocol)||u.href.split("#")[0]===location.href.split("#")[0])return;if(window.parent!==window){e.preventDefault();window.parent.postMessage({jsonrpc:"2.0",id:"t3-link-"+(++n),method:${JSON.stringify(OPEN_LINK_METHOD)},params:{url:u.href}},"*");}else{l.setAttribute("target","_blank");l.setAttribute("rel","noopener");}},true);})();`;
314​
315function bootstrapMarkup(markup: string): string {
316 const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");
317 const light = htmlRenderTheme(T3_CODE_LIGHT_THEME_COLORS, "light");
318 // Without a client-provided theme (a direct download, the headless preview
319 // without a fragment) the page follows the OS appearance.
320 const defaultCss = `${rootRule(dark)}@media (prefers-color-scheme: light){${rootRule(light)}}${BASE_CSS}`;
321 return [
322 /<meta\s[^>]*charset/i.test(markup.slice(0, 4096)) ? "" : '<meta charset="utf-8">',
323 /<meta\s[^>]*name\s*=\s*["']?viewport/i.test(markup)
324 ? ""
325 : '<meta name="viewport" content="width=device-width, initial-scale=1">',
326 `<style id="t3-theme">${defaultCss}</style>`,
327 `<script>${BOOTSTRAP_SCRIPT}</script>`,
328 ].join("");
330​
331// Comments, raw text, and template contents are blanked to the same length,
332// so offsets still line up and inert tags cannot receive the bootstrap.
333const blankNonMarkup = (html: string) => {
334 const scan = html.replace(
335 /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)\b[\s\S]*?(?:<\/\1\s*>|$)|<plaintext\b[\s\S]*$/gi,
336 (match) => " ".repeat(match.length),
337 );
338 const parts: string[] = [];
339 let depth = 0;
340 let start = 0;
341 let at = 0;
342 for (const match of scan.matchAll(/<(\/?)template(?:\s[^>]*)?\/?>/gi)) {
343 if (!match[1]) {
344 if (depth++ === 0) start = match.index;
345 } else if (depth > 0 && --depth === 0) {
346 const end = match.index + match[0].length;
347 parts.push(scan.slice(at, start), " ".repeat(end - start));
348 at = end;
349 }
350 }
351 if (depth > 0) {
352 parts.push(scan.slice(at, start), " ".repeat(scan.length - start));
353 at = scan.length;
354 }
355 parts.push(scan.slice(at));
356 return parts.join("");
357};
358​
359/**
360 * Inserts the theme bootstrap at the start of the document head, so a page's
361 * own styles and scripts come after it.
362 */
363export function injectHtmlRenderBootstrap(html: string): string {
364 const scan = blankNonMarkup(html);
365 const markup = bootstrapMarkup(scan);
366 const headOpen = /<head(?:\s[^>]*)?>/i.exec(scan);
367 if (headOpen) {
368 const at = headOpen.index + headOpen[0].length;
369 return html.slice(0, at) + markup + html.slice(at);
370 }
371 const htmlOpen = /<html(?:\s[^>]*)?>/i.exec(scan);
372 if (htmlOpen) {
373 const at = htmlOpen.index + htmlOpen[0].length;
374 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
375 }
376 const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
377 if (doctype) {
378 const at = doctype[0].length;
379 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
380 }
381 return `<!doctype html><head>${markup}</head>${html}`;