Skip to content

Commit 500a52e

Browse files
t3dotggclaude
andauthored
fix(web): HTML visualizations show their full height instead of cropping and scrolling (pingdotgg#22131)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 92a6f6d commit 500a52e

7 files changed

Lines changed: 147 additions & 14 deletions

File tree

‎apps/server/src/htmlRender/HtmlRender.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,28 @@ describe("HtmlRender", () => {
123123
}).pipe(Effect.provide(layerTest)),
124124
);
125125

126+
it.effect("rejects viewport height units, which make the fitted frame grow without end", () =>
127+
Effect.gen(function* () {
128+
const htmlRender = yield* HtmlRender.HtmlRender;
129+
for (const page of [
130+
"<style>main{min-height:100vh}</style>",
131+
"<style media=screen>main{height: calc(100dvh - 2rem)}",
132+
"<div style='top:.5svh'></div>",
133+
"<div style=height:100vh></div>",
134+
]) {
135+
const error = yield* htmlRender.prepare(page).pipe(Effect.flip);
136+
expect(error).toBeInstanceOf(HtmlRender.HtmlRenderViewportHeightError);
137+
}
138+
yield* htmlRender.prepare(
139+
'<style>main{width:100vw;height:320px}</style><img src="data:image/png;base64,AB1vh+2vh/3vhC">',
140+
);
141+
yield* htmlRender.prepare(
142+
"<p>Avoid 100vh here.</p><!-- <div style=\"height:100vh\"></div> --><script>const unit = '100vh';</script>",
143+
);
144+
yield* htmlRender.prepare(`<style>${"1".repeat(200_000)}vx</style>`);
145+
}).pipe(Effect.provide(layerTest)),
146+
);
147+
126148
it.effect("inlines an SVG behind processing instructions and a doctype subset", () =>
127149
Effect.gen(function* () {
128150
const fileSystem = yield* FileSystem.FileSystem;

‎apps/server/src/htmlRender/HtmlRender.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,34 @@ export class HtmlRenderPageTooLargeError extends Schema.TaggedError<HtmlRenderPa
6868
}
6969
}
7070

71+
export class HtmlRenderViewportHeightError extends Schema.TaggedError<HtmlRenderViewportHeightError>()(
72+
"HtmlRenderViewportHeightError",
73+
{ found: Schema.String },
74+
) {
75+
override get message(): string {
76+
return `The page uses a viewport height unit (${this.found}). The frame grows to fit the page, so a size that follows the viewport makes it grow again and again. Let content set the height, or use fixed pixel heights.`;
77+
}
78+
}
79+
80+
// Only stylesheets and style attributes are checked, so page text that mentions
81+
// a unit passes; comments match first so their contents are skipped. Scripts
82+
// are still checked, since markup they insert applies. An unclosed comment,
83+
// tag, or quote runs to the end of the page, which keeps both patterns linear
84+
// on hostile input.
85+
const CSS_SOURCE =
86+
/<!--[\s\S]*?(?:-->|$)|<style\b[^>]*(?:>|$)([\s\S]*?)(?:<\/style\s*>|$)|\sstyle\s*=\s*(?:"([^"]*)(?:"|$)|'([^']*)(?:'|$)|([^\s>]+))/gi;
87+
// The lookbehind skips base64 runs, such as an inlined image that happens to contain "1vh".
88+
const VIEWPORT_HEIGHT_UNIT = /(?<![\w.+/])(?:\d+(?:\.\d+)?|\.\d+)[sld]?vh(?![\w-])/i;
89+
90+
const rejectViewportHeight = (html: string) => {
91+
for (const [, sheet, doubleQuoted, singleQuoted, unquoted] of html.matchAll(CSS_SOURCE)) {
92+
const css = sheet ?? doubleQuoted ?? singleQuoted ?? unquoted ?? "";
93+
const found = VIEWPORT_HEIGHT_UNIT.exec(css)?.[0];
94+
if (found !== undefined) return Effect.fail(new HtmlRenderViewportHeightError({ found }));
95+
}
96+
return Effect.void;
97+
};
98+
7199
export class HtmlRenderStoreError extends Schema.TaggedError<HtmlRenderStoreError>()(
72100
"HtmlRenderStoreError",
73101
{ cause: Schema.Defect() },
@@ -80,7 +108,8 @@ export class HtmlRenderStoreError extends Schema.TaggedError<HtmlRenderStoreErro
80108
export type HtmlRenderPrepareError =
81109
| HtmlRenderImagesNotFoundError
82110
| HtmlRenderImageTooLargeError
83-
| HtmlRenderPageTooLargeError;
111+
| HtmlRenderPageTooLargeError
112+
| HtmlRenderViewportHeightError;
84113

85114
export interface HtmlPreview {
86115
readonly png: string;
@@ -380,6 +409,7 @@ const make = Effect.gen(function* () {
380409
inlineLocalImages(injectHtmlRenderBootstrap(html)).pipe(Effect.provideContext(services));
381410

382411
const prepare = Effect.fn("HtmlRender.prepare")(function* (html: string) {
412+
yield* rejectViewportHeight(html);
383413
const inlined = yield* inline(html);
384414
if (inlined.missing.length > 0) {
385415
return yield* new HtmlRenderImagesNotFoundError({ paths: inlined.missing });
@@ -447,6 +477,7 @@ const make = Effect.gen(function* () {
447477
Math.max(MIN_PREVIEW_WIDTH, Math.round(input.width ?? HTML_RENDER_COLUMN_WIDTH)),
448478
);
449479
const appearance = input.appearance ?? "dark";
480+
yield* rejectViewportHeight(input.html);
450481
const inlined = yield* inline(input.html);
451482
const executable = yield* previewBrowser.executable;
452483
const theme = htmlRenderTheme(

‎apps/server/src/mcp/toolkits/html/handlers.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const INVALID_PAGE_ERRORS = new Set([
1010
"HtmlRenderImagesNotFoundError",
1111
"HtmlRenderImageTooLargeError",
1212
"HtmlRenderPageTooLargeError",
13+
"HtmlRenderViewportHeightError",
1314
]);
1415

1516
const toFailure = (error: { readonly _tag: string; readonly message: string }) =>

‎apps/server/src/mcp/toolkits/html/tools.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { OrchestratorMcpFailure } from "@t3tools/contracts";
22
import {
33
HTML_RENDER_COLUMN_WIDTH,
44
HTML_RENDER_LAYOUT_GUIDE,
5+
HTML_RENDER_MAX_FIT_HEIGHT,
56
HTML_RENDER_MAX_HEIGHT,
67
HTML_RENDER_MAX_TITLE_LENGTH,
78
HTML_RENDER_MIN_HEIGHT,
@@ -71,15 +72,15 @@ export const HtmlPreviewTool = Tool.make("html_preview", {
7172
// Read-only in the MCP sense: it shows a page in the caller's own thread and
7273
// touches no workspace, so plan mode and read-only sandboxes can use it.
7374
const HtmlRenderTool = Tool.make(HTML_RENDER_TOOL_NAME, {
74-
description: `Show a finished HTML page (chart, table, diagram, collage, mockup) inline in this thread, above your final text reply; call it before writing that reply. The reader already sees the page, so the reply should not announce it, say where it is, or restate it: add only what the page doesn't say. Preview with html_preview first. T3 fits the frame to the page's height at each reader's width. A height below the page's contentHeight caps the frame there, and the rest scrolls inside it. ${PAGE_RULES} ${HTML_RENDER_LAYOUT_GUIDE} ${HTML_RENDER_THEME_GUIDE}`,
75+
description: `Show a finished HTML page (chart, table, diagram, collage, mockup) inline in this thread, above your final text reply; call it before writing that reply. The reader already sees the page, so the reply should not announce it, say where it is, or restate it: add only what the page doesn't say. Preview with html_preview first. T3 fits the frame to the page's height at each reader's width. On mobile, a height below the page's contentHeight caps the frame there, and the rest scrolls inside it; web and desktop fit the whole page, up to ${HTML_RENDER_MAX_FIT_HEIGHT}px. ${PAGE_RULES} ${HTML_RENDER_LAYOUT_GUIDE} ${HTML_RENDER_THEME_GUIDE}`,
7576
parameters: Schema.Struct({
7677
html: Html,
7778
title: Schema.String.check(
7879
Schema.isMinLength(1),
7980
Schema.isMaxLength(HTML_RENDER_MAX_TITLE_LENGTH),
8081
).annotate({ description: "Short name for the page." }),
8182
height: Schema.Int.annotate({
82-
description: `The frame height in CSS pixels, ${HTML_RENDER_MIN_HEIGHT}-${HTML_RENDER_MAX_HEIGHT}. Use html_preview's contentHeight, or less to make long content scroll inside the frame.`,
83+
description: `The frame height in CSS pixels, ${HTML_RENDER_MIN_HEIGHT}-${HTML_RENDER_MAX_HEIGHT}. Use html_preview's contentHeight. A lower height makes long content scroll inside the frame on mobile only.`,
8384
}),
8485
}),
8586
success: Schema.Struct({
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import { act } from "react";
2+
import { createRoot, type Root } from "react-dom/client";
3+
import { afterEach, expect, it, vi } from "vite-plus/test";
4+
import { EnvironmentId } from "@t3tools/contracts";
5+
import {
6+
htmlRenderTheme,
7+
HTML_RENDER_DEFAULT_FONTS,
8+
injectHtmlRenderBootstrap,
9+
} from "@t3tools/shared/htmlRender";
10+
import { T3_CODE_DARK_THEME_COLORS } from "@t3tools/shared/themePalettes";
11+
12+
import "~/index.css";
13+
14+
import { HtmlRenderFrame } from "./HtmlRenderFrame";
15+
16+
const page = vi.hoisted(() => ({ url: "" }));
17+
vi.mock(import("~/assets/assetUrls"), async (original) => ({
18+
...(await original()),
19+
useAssetUrlState: () => ({
20+
_tag: "Success",
21+
url: page.url,
22+
expiresAt: Date.now() + 60 * 60_000,
23+
}),
24+
useAssetUrlRefresh: () => vi.fn(),
25+
}));
26+
vi.mock(import("~/hooks/useHtmlRenderTheme"), async (original) => ({
27+
...(await original()),
28+
useHtmlRenderTheme: () =>
29+
htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark", HTML_RENDER_DEFAULT_FONTS),
30+
}));
31+
32+
let root: Root | undefined;
33+
let container: HTMLDivElement | undefined;
34+
35+
afterEach(async () => {
36+
await act(() => root?.unmount());
37+
container?.remove();
38+
URL.revokeObjectURL(page.url);
39+
});
40+
41+
it("grows past the agent's height to fit the page the client lays out", async () => {
42+
page.url = URL.createObjectURL(
43+
new Blob([injectHtmlRenderBootstrap('<div style="height:2345px"></div>')], {
44+
type: "text/html",
45+
}),
46+
);
47+
container = document.createElement("div");
48+
document.body.append(container);
49+
root = createRoot(container);
50+
await act(() =>
51+
root!.render(
52+
<HtmlRenderFrame
53+
environmentId={EnvironmentId.make("environment-1")}
54+
htmlRender={{ attachmentId: "html", title: "Tall page", height: 400 }}
55+
threadRef={undefined}
56+
/>,
57+
),
58+
);
59+
60+
const box = container.firstElementChild as HTMLElement;
61+
await expect.poll(() => box.style.height).toBe("2345px");
62+
expect(box.querySelector("iframe")?.clientHeight).toBe(2345);
63+
});

‎packages/shared/src/htmlRender.test.ts‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { describe, expect, it } from "vite-plus/test";
22

33
import {
4-
HTML_RENDER_MAX_HEIGHT,
4+
HTML_RENDER_MAX_FIT_HEIGHT,
55
htmlRenderFrameHeight,
66
htmlRenderReferencesEqual,
77
htmlRenderTheme,
@@ -267,18 +267,22 @@ describe("htmlRenderFrameHeight", () => {
267267
const fitted = { ...measured, height: 1403 };
268268
expect(htmlRenderFrameHeight(fitted, 728, 1415)).toBe(1415);
269269
expect(htmlRenderFrameHeight(fitted, 1400)).toBe(1660);
270-
expect(htmlRenderFrameHeight(fitted, 728, 5000)).toBe(HTML_RENDER_MAX_HEIGHT);
270+
expect(htmlRenderFrameHeight(fitted, 728, 5000)).toBe(5000);
271+
expect(htmlRenderFrameHeight(fitted, 728, 99_999)).toBe(HTML_RENDER_MAX_FIT_HEIGHT);
271272
});
272273

273-
it("keeps the agent's height when it asked for a scrolling frame or the page is unmeasured", () => {
274+
it("fits the client's measured content over a shorter agent height", () => {
274275
const scrolling = { ...measured, height: 600 };
275-
expect(htmlRenderFrameHeight(scrolling, 728, 1415)).toBe(600);
276-
expect(htmlRenderFrameHeight(scrolling, 1400)).toBe(600);
277-
expect(htmlRenderFrameHeight(reference, 728)).toBe(reference.height);
278-
expect(htmlRenderFrameHeight(reference, 728, 900)).toBe(reference.height);
276+
expect(htmlRenderFrameHeight(scrolling, 728, 1415)).toBe(1415);
277+
expect(htmlRenderFrameHeight(reference, 728, 900)).toBe(900);
279278
expect(htmlRenderFrameHeight(reference, 728, 300)).toBe(300);
280279
});
281280

281+
it("keeps the agent's height without a client measurement", () => {
282+
expect(htmlRenderFrameHeight({ ...measured, height: 600 }, 1400)).toBe(600);
283+
expect(htmlRenderFrameHeight(reference, 728)).toBe(reference.height);
284+
});
285+
282286
it("drops a malformed table and compares tables by value", () => {
283287
expect(readHtmlRenderReference({ ...reference, heights: [[728, "x"]] })?.heights).toBe(
284288
undefined,

‎packages/shared/src/htmlRender.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ import { EVENT_CODE_SHORTCUT_KEYS } from "./keybindings.ts";
99
export const HTML_RENDER_TOOL_NAME = "html_render";
1010
export const HTML_RENDER_MIN_HEIGHT = 80;
1111
export const HTML_RENDER_MAX_HEIGHT = 2000;
12+
// A client fits the frame to the live page up to this height. It only stops a
13+
// page that grows with its frame, since vh units are rejected at publish.
14+
export const HTML_RENDER_MAX_FIT_HEIGHT = 20_000;
1215
export const HTML_RENDER_MAX_TITLE_LENGTH = 200;
1316

1417
export interface HtmlRenderReference {
@@ -90,22 +93,30 @@ function measuredHeight(heights: NonNullable<HtmlRenderReference["heights"]>, wi
9093

9194
/**
9295
* A page even a few pixels taller than its frame scrolls inside it and takes
93-
* the reader's scroll, so the frame fits the page.
96+
* the reader's scroll, so the frame fits the page. A client that measured the
97+
* live page passes `contentHeight`, which wins over the agent's height: client
98+
* fonts often wrap the page taller than the server or agent measured it.
9499
*/
95100
export function htmlRenderFrameHeight(
96101
reference: HtmlRenderReference,
97102
width: number,
98103
contentHeight?: number,
99104
) {
105+
if (contentHeight !== undefined) {
106+
return Math.min(
107+
HTML_RENDER_MAX_FIT_HEIGHT,
108+
Math.max(HTML_RENDER_MIN_HEIGHT, Math.ceil(contentHeight)),
109+
);
110+
}
100111
const heights = reference.heights;
101112
if (heights === undefined || heights.length === 0) {
102-
return clampHtmlRenderHeight(Math.min(reference.height, contentHeight ?? reference.height));
113+
return clampHtmlRenderHeight(reference.height);
103114
}
104115
const cap =
105116
measuredHeight(heights, HTML_RENDER_COLUMN_WIDTH) > reference.height
106117
? reference.height
107118
: HTML_RENDER_MAX_HEIGHT;
108-
return clampHtmlRenderHeight(Math.min(cap, contentHeight ?? measuredHeight(heights, width)));
119+
return clampHtmlRenderHeight(Math.min(cap, measuredHeight(heights, width)));
109120
}
110121

111122
export function htmlRenderFileName(title: string) {
@@ -234,7 +245,7 @@ export const HTML_RENDER_LAYOUT_GUIDE = [
234245
"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.",
235246
"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.",
236247
"Give charts fixed pixel heights rather than heights that scale with width.",
237-
"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.",
248+
"Let content set the page's height. The frame grows to fit the page, so a height that follows the viewport makes it grow again and again: html_preview and html_render reject vh, svh, lvh, and dvh units, and height:100% on html or body has the same problem.",
238249
].join(" ");
239250

240251
const HOST_CONTEXT_CHANGED_METHOD = "ui/notifications/host-context-changed";

0 commit comments

Comments
 (0)