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

htmlRender.ts

415 lines19.7 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// The taller of the heights measured at the nearest widths on each side. A
102// breakpoint between two measured widths can make the page as tall as either.
103function measuredHeight(heights: NonNullable<HtmlRenderReference["heights"]>, width: number) {
104 const above = heights.findIndex(([measuredWidth]) => measuredWidth >= width);
105 const high = above === -1 ? heights.length - 1 : above;
106 const low = heights[high]![0] === width ? high : Math.max(0, high - 1);
107 return Math.max(heights[low]![1], heights[high]![1]);
109​
110/**
111 * The frame height for a page at a frame width. It is the page's own reported
112 * `contentHeight` when the client has one, else the server's measurement for
113 * that width. A page even a few pixels taller than its frame scrolls inside it
114 * and takes the reader's scroll, so the frame fits the page. The agent's height
115 * caps it only when it is below the page's height at the column width (the
116 * agent asked for a scrolling frame) or when the page was never measured.
117 */
118export function htmlRenderFrameHeight(
119 reference: HtmlRenderReference,
120 width: number,
121 contentHeight?: number,
122) {
123 const heights = reference.heights;
124 if (heights === undefined || heights.length === 0) {
125 return clampHtmlRenderHeight(Math.min(reference.height, contentHeight ?? reference.height));
126 }
127 const cap =
128 measuredHeight(heights, HTML_RENDER_COLUMN_WIDTH) > reference.height
129 ? reference.height
130 : HTML_RENDER_MAX_HEIGHT;
131 return clampHtmlRenderHeight(Math.min(cap, contentHeight ?? measuredHeight(heights, width)));
133​
134/** A readable download name: the title without characters file systems reject. */
135export function htmlRenderFileName(title: string) {
136 const name = title
137 .replace(/[\\/:*?"<>|\p{Cc}]+/gu, " ")
138 .replace(/\s+/g, " ")
139 .trim()
140 .slice(0, 120)
141 .trim();
142 return `${name || "Page"}.html`;
144​
145export function clampHtmlRenderHeight(height: number): number {
146 return Math.min(HTML_RENDER_MAX_HEIGHT, Math.max(HTML_RENDER_MIN_HEIGHT, Math.round(height)));
148​
149export interface HtmlRenderFonts {
150 readonly sans: string;
151 readonly mono: string;
153​
154export const HTML_RENDER_DEFAULT_FONTS: HtmlRenderFonts = {
155 sans: '-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif',
156 // Concrete names only: some engines alias `ui-monospace` to the proportional UI font.
157 mono: '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace',
158};
159​
160/**
161 * Fonts the server's headless browser lays pages out with. Arial-metric faces
162 * stand in for the system UI fonts readers see, so measured heights and
163 * preview screenshots wrap text close to how a client will.
164 */
165export const HTML_RENDER_MEASURE_FONTS: HtmlRenderFonts = {
166 sans: '"Liberation Sans", Arimo, Arial, Helvetica, sans-serif',
167 mono: '"Liberation Mono", Cousine, Menlo, Consolas, monospace',
168};
169​
170/** The resolved theme a client hands an HTML render. */
171export interface HtmlRenderTheme {
172 readonly appearance: ThemeAppearance;
173 readonly variables: Readonly<Record<string, string>>;
175​
176// Roles themes cannot change (index.css keeps info/success fixed), plus a
177// categorical chart series after the theme's own accent.
178const FIXED_COLORS = {
179 light: {
180 success: "#10b981",
181 successForeground: "#047857",
182 info: "#3b82f6",
183 infoForeground: "#1d4ed8",
184 chart: ["#0d9488", "#d97706", "#9333ea", "#e11d48", "#65a30d"],
185 },
186 dark: {
187 success: "#10b981",
188 successForeground: "#34d399",
189 info: "#3b82f6",
190 infoForeground: "#60a5fa",
191 chart: ["#2dd4bf", "#fbbf24", "#c084fc", "#fb7185", "#a3e635"],
192 },
193} as const;
194​
195/**
196 * Maps a theme palette to the variables HTML renders style against. Names
197 * follow the app's own tokens, except `--accent`, which is the theme's brand
198 * color here rather than the app's neutral hover surface.
199 */
200export function htmlRenderTheme(
201 colors: ThemeColors,
202 appearance: ThemeAppearance,
203 fonts: HtmlRenderFonts = HTML_RENDER_DEFAULT_FONTS,
204): HtmlRenderTheme {
205 const fixed = FIXED_COLORS[appearance];
206 return {
207 appearance,
208 variables: {
209 "--background": colors.canvas,
210 "--foreground": colors.text,
211 "--muted": colors.muted,
212 "--muted-foreground": colors.mutedForeground,
213 "--card": colors.surface,
214 "--card-foreground": colors.text,
215 "--popover": colors.surfaceOverlay,
216 "--popover-foreground": colors.text,
217 "--secondary": colors.secondary,
218 "--secondary-foreground": colors.secondaryForeground,
219 "--border": colors.border,
220 "--input": colors.input,
221 "--ring": colors.focus,
222 "--primary": colors.messageAction,
223 "--primary-foreground": colors.messageActionForeground,
224 "--accent": colors.accent,
225 "--accent-foreground": colors.accentForeground,
226 "--accent-surface": colors.accentSurface,
227 "--accent-surface-foreground": colors.accentSurfaceForeground,
228 "--destructive": colors.error,
229 "--destructive-foreground": colors.errorForeground,
230 "--destructive-surface": colors.errorSurface,
231 "--warning": colors.warning,
232 "--warning-foreground": colors.warningForeground,
233 "--warning-surface": colors.warningSurface,
234 "--success": fixed.success,
235 "--success-foreground": fixed.successForeground,
236 "--info": fixed.info,
237 "--info-foreground": fixed.infoForeground,
238 "--code-background": colors.codeBackground,
239 "--code-foreground": colors.codeForeground,
240 "--chart-1": colors.accent,
241 ...Object.fromEntries(fixed.chart.map((color, index) => [`--chart-${index + 2}`, color])),
242 "--radius": "0.625rem",
243 "--font-sans": fonts.sans,
244 "--font-mono": fonts.mono,
245 },
246 };
248​
249/** Agent-facing reference for the injected variables, used in tool descriptions. */
250export const HTML_RENDER_THEME_GUIDE = [
251 "T3 injects its active theme as CSS custom properties on :root, and they follow the user's theme and light/dark mode live:",
252 "--background (page background, identical to the thread around the frame), --foreground, --muted, --muted-foreground,",
253 "--card, --card-foreground, --popover, --popover-foreground, --secondary, --secondary-foreground, --border, --input, --ring,",
254 "--primary, --primary-foreground (solid buttons), --accent, --accent-foreground (brand accent), --accent-surface, --accent-surface-foreground,",
255 "--destructive, --destructive-foreground, --destructive-surface, --warning, --warning-foreground, --warning-surface,",
256 "--success, --success-foreground, --info, --info-foreground, --code-background, --code-foreground,",
257 "--chart-1 … --chart-6 (categorical series for charts), --radius, --font-sans, --font-mono.",
258 "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.",
259].join(" ");
260​
261/** Agent-facing layout rules for a page that sits inside a reply. */
262export const HTML_RENDER_LAYOUT_GUIDE = [
263 `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.`,
264 "The page sits on the thread's own background, so by default leave html, body, and the outermost element with no background color. This overrides general style preferences such as a fixed black page background.",
265 "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.",
266 "If a box needs its own background (a mock of a specific screen, a panel that must stand apart), give it at least 16px of padding on every side and var(--radius) corners, so content never touches its edge.",
267 "Give charts fixed pixel heights rather than heights that scale with width.",
268 "Let content set the page's height. Avoid viewport-based heights such as 100vh or height:100% on html or body; the frame grows to fit the page, so they can make it grow again and again.",
269].join(" ");
270​
271// The bridge between a render and its client speaks the MCP Apps protocol
272// (JSON-RPC over postMessage), so the same host code can later drive upstream
273// MCP apps: https://github.com/modelcontextprotocol/ext-apps
274const HOST_CONTEXT_CHANGED_METHOD = "ui/notifications/host-context-changed";
275const OPEN_LINK_METHOD = "ui/open-link";
276const SIZE_CHANGED_METHOD = "ui/notifications/size-changed";
277​
278/** The content height in a framed render's `ui/notifications/size-changed` notification. */
279export function readHtmlRenderContentHeight(data: unknown): number | undefined {
280 if (typeof data !== "object" || data === null) return undefined;
281 const { jsonrpc, method, params } = data as Record<string, unknown>;
282 if (jsonrpc !== "2.0" || method !== SIZE_CHANGED_METHOD) return undefined;
283 const height =
284 typeof params === "object" && params !== null
285 ? (params as { height?: unknown }).height
286 : undefined;
287 return typeof height === "number" && Number.isFinite(height) && height > 0 ? height : undefined;
289​
290/** A render's `ui/open-link` request, if `data` is one with an http(s) URL. */
291export function readHtmlRenderLinkRequest(
292 data: unknown,
293): { readonly id: string | number; readonly url: string } | undefined {
294 if (typeof data !== "object" || data === null) return undefined;
295 const { jsonrpc, id, method, params } = data as Record<string, unknown>;
296 if (jsonrpc !== "2.0" || method !== OPEN_LINK_METHOD) return undefined;
297 if (typeof id !== "string" && typeof id !== "number") return undefined;
298 const url =
299 typeof params === "object" && params !== null ? (params as { url?: unknown }).url : undefined;
300 return typeof url === "string" && /^https?:\/\//i.test(url) ? { id, url } : undefined;
302​
303/** The empty result a client sends back for a render's request. */
304export function htmlRenderResult(id: string | number) {
305 return { jsonrpc: "2.0", id, result: {} } as const;
307​
308const THEME_FRAGMENT_KEY = "t3-theme";
309​
310/** URL fragment that hands a render its theme before first paint. */
311export function htmlRenderThemeFragment(theme: HtmlRenderTheme): string {
312 return `#${THEME_FRAGMENT_KEY}=${encodeURIComponent(JSON.stringify(theme))}`;
314​
315/** The `host-context-changed` notification a client posts into a mounted render when the theme changes. */
316export function htmlRenderThemeMessage(theme: HtmlRenderTheme) {
317 return {
318 jsonrpc: "2.0",
319 method: HOST_CONTEXT_CHANGED_METHOD,
320 params: { theme: theme.appearance, styles: { variables: theme.variables } },
321 } as const;
323​
324// The frame scrolls a page taller than itself, but a scrollbar inside the
325// reply reads as a box within the thread, so it stays hidden.
326const BASE_CSS =
327 "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}" +
328 "html::-webkit-scrollbar{display:none}body{margin:0}code,kbd,pre,samp{font-family:var(--font-mono)}";
329​
330function rootRule(theme: HtmlRenderTheme): string {
331 const declarations = Object.entries(theme.variables)
332 .map(([name, value]) => `${name}:${value};`)
333 .join("");
334 return `:root{color-scheme:${theme.appearance};${declarations}}`;
336​
337// Runs synchronously in <head>, before the page's own styles and body, so the
338// first paint is already themed. It rewrites its own <style> element rather
339// than setting inline properties, so a page's later `:root` rules still win,
340// then drops the fragment so a page's own hash routing never sees it. A link
341// the reader clicks to another page never replaces the page inside the thread:
342// a framed page asks its client to open it, and a top-level page (mobile)
343// opens it as a new window, which the client sends to the browser. A framed
344// page also reports its content height, measured as the server measures it,
345// so its client can fit the frame to the page.
346const 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);if(window.parent!==window){var h,o,z=function(){var r=document.documentElement,v=Math.ceil(r.scrollHeight>r.clientHeight?r.scrollHeight:r.getBoundingClientRect().height);if(v===h)return;h=v;window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(SIZE_CHANGED_METHOD)},params:{height:v}},"*");};if(window.ResizeObserver){o=new ResizeObserver(z);o.observe(document.documentElement);}document.addEventListener("DOMContentLoaded",function(){if(o&&document.body)o.observe(document.body);z();});window.addEventListener("load",z);}})();`;
347​
348function bootstrapMarkup(markup: string): string {
349 const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");
350 const light = htmlRenderTheme(T3_CODE_LIGHT_THEME_COLORS, "light");
351 // Without a client-provided theme (a direct download, the headless preview
352 // without a fragment) the page follows the OS appearance.
353 const defaultCss = `${rootRule(dark)}@media (prefers-color-scheme: light){${rootRule(light)}}${BASE_CSS}`;
354 return [
355 /<meta\s[^>]*charset/i.test(markup.slice(0, 4096)) ? "" : '<meta charset="utf-8">',
356 /<meta\s[^>]*name\s*=\s*["']?viewport/i.test(markup)
357 ? ""
358 : '<meta name="viewport" content="width=device-width, initial-scale=1">',
359 `<style id="t3-theme">${defaultCss}</style>`,
360 `<script>${BOOTSTRAP_SCRIPT}</script>`,
361 ].join("");
363​
364// Comments, raw text, and template contents are blanked to the same length,
365// so offsets still line up and inert tags cannot receive the bootstrap.
366const blankNonMarkup = (html: string) => {
367 const scan = html.replace(
368 /<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)\b[\s\S]*?(?:<\/\1\s*>|$)|<plaintext\b[\s\S]*$/gi,
369 (match) => " ".repeat(match.length),
370 );
371 const parts: string[] = [];
372 let depth = 0;
373 let start = 0;
374 let at = 0;
375 for (const match of scan.matchAll(/<(\/?)template(?:\s[^>]*)?\/?>/gi)) {
376 if (!match[1]) {
377 if (depth++ === 0) start = match.index;
378 } else if (depth > 0 && --depth === 0) {
379 const end = match.index + match[0].length;
380 parts.push(scan.slice(at, start), " ".repeat(end - start));
381 at = end;
382 }
383 }
384 if (depth > 0) {
385 parts.push(scan.slice(at, start), " ".repeat(scan.length - start));
386 at = scan.length;
387 }
388 parts.push(scan.slice(at));
389 return parts.join("");
390};
391​
392/**
393 * Inserts the theme bootstrap at the start of the document head, so a page's
394 * own styles and scripts come after it.
395 */
396export function injectHtmlRenderBootstrap(html: string): string {
397 const scan = blankNonMarkup(html);
398 const markup = bootstrapMarkup(scan);
399 const headOpen = /<head(?:\s[^>]*)?>/i.exec(scan);
400 if (headOpen) {
401 const at = headOpen.index + headOpen[0].length;
402 return html.slice(0, at) + markup + html.slice(at);
403 }
404 const htmlOpen = /<html(?:\s[^>]*)?>/i.exec(scan);
405 if (htmlOpen) {
406 const at = htmlOpen.index + htmlOpen[0].length;
407 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
408 }
409 const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
410 if (doctype) {
411 const at = doctype[0].length;
412 return `${html.slice(0, at)}<head>${markup}</head>${html.slice(at)}`;
413 }
414 return `<!doctype html><head>${markup}</head>${html}`;