The best way to control Claude Code, Codex and more from any computer or phone
perf(web): HTML renders show a layout skeleton and reuse cached pages (#19654)
maria committed
Oct 15, 2026 at 21:26 UTC
f798cb299ac9eab9d51ef63b5159de14a2b6aa18
11 files changed
+442
-23
apps/server/src/assets/AssetAccess.test.ts
+28
@@ -1029,6 +1029,34 @@ describe("AssetAccess", () => {
1029
}).pipe(Effect.provide(layerTest)),
1030
);
1031
1032
+ it.effect("signs the same HTML page URL within an expiry window", () =>
1033
+ Effect.gen(function* () {
1034
+ const config = yield* ServerConfig.ServerConfig;
1035
+ const fileSystem = yield* FileSystem.FileSystem;
1036
+ const path = yield* Path.Path;
1037
+ const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-html";
1038
+ yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1039
+ yield* fileSystem.writeFileString(
1040
+ path.join(config.attachmentsDir, `${attachmentId}.html`),
1041
+ "<p>render</p>",
1042
+ );
1043
+ const bucketMs = 30 * 60 * 1000;
1044
+ const issue = issueAssetUrl({
1045
+ resource: { _tag: "attachment", attachmentId, disposition: "inline" },
1046
+ });
1047
+ yield* TestClock.setTime(bucketMs + 1);
1048
+ const first = yield* issue;
1049
+ yield* TestClock.adjust("20 minutes");
1050
+ const second = yield* issue;
1051
+ yield* TestClock.adjust("10 minutes");
1052
+ const next = yield* issue;
1053
+
1054
+ expect(second.relativeUrl).toBe(first.relativeUrl);
1055
+ expect(first.expiresAt).toBe(4 * bucketMs);
1056
+ expect(next.expiresAt).toBe(5 * bucketMs);
1057
+ }).pipe(Effect.provide(layerTest)),
1058
+ );
1059
+
1060
it.effect("serves video attachments inline", () =>
1061
Effect.gen(function* () {
1062
const config = yield* ServerConfig.ServerConfig;
apps/server/src/assets/AssetAccess.ts
+9
@@ -71,6 +71,7 @@ export const ASSET_ROUTE_PREFIX = "/api/assets";
71
const SIGNING_SECRET_NAME = "asset-access-signing-key";
72
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
73
const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
74
+const HTML_ATTACHMENT_TOKEN_BUCKET_MS = 30 * 60 * 1000;
75
const PROJECT_FAVICON_VERSION_PREFIX = "v";
76
// Clients draw project icons from a 96px thumbnail at most.
77
const PROJECT_FAVICON_ICNS_MIN_SIZE = 96;
@@ -825,6 +826,14 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
826
PROJECT_FAVICON_TOKEN_BUCKET_MS;
827
claims = { ...claims, expiresAt };
828
}
829
+ if (claims.kind === "attachment" && claims.mimeType === "text/html") {
830
+ // HTML pages never change, so mints in the same window sign the same URL and a reload
831
+ // can answer it from the browser cache. Images keep a new URL per mint, since their
832
+ // load-error retries rely on one.
833
+ expiresAt =
834
+ Math.ceil(expiresAt / HTML_ATTACHMENT_TOKEN_BUCKET_MS) * HTML_ATTACHMENT_TOKEN_BUCKET_MS;
835
+ claims = { ...claims, expiresAt };
836
+ }
837
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
838
const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
839
return {
apps/server/src/htmlRender/HtmlRender.test.ts
+3
-1
@@ -391,7 +391,7 @@ describe("HtmlRender", () => {
391
// Like a D3 chart, the page sizes itself from the width once, at load.
392
const reference = yield* htmlRender.publish({
393
threadId: ThreadId.make("thread-html-measure"),
394
- html: '<div id="chart"></div><script>document.getElementById("chart").style.height = innerWidth / 2 + "px";</script>',
394
+ html: '<div id="chart" style="background:#888"></div><script>document.getElementById("chart").style.height = innerWidth / 2 + "px";</script>',
395
title: "Chart",
396
height: 600,
397
});
@@ -399,6 +399,8 @@ describe("HtmlRender", () => {
399
expect(reference.heights).toEqual(
400
HTML_RENDER_MEASURE_WIDTHS.map((width) => [width, Math.ceil(width / 2)]),
401
);
402
+ // The chart as the column-width load laid it out, in 4px units.
403
+ expect(reference.outline).toBe("m0,0,182,91,1");
404
}).pipe(Effect.provide(layerHtmlRender(executable)));
405
}),
406
30_000,
apps/server/src/htmlRender/HtmlRender.ts
+5
-4
@@ -372,7 +372,7 @@ const make = Effect.gen(function* () {
372
Effect.gen(function* () {
373
const executable = yield* previewBrowser.installed;
374
if (Option.isNone(executable)) return undefined;
375
- const heights = yield* launching(executable.value, (noSandbox) =>
375
+ const { heights, outline } = yield* launching(executable.value, (noSandbox) =>
376
HeadlessChrome.measureHtmlHeights({
377
executable: executable.value,
378
noSandbox,
@@ -391,7 +391,7 @@ const make = Effect.gen(function* () {
391
),
392
}),
393
);
394
- return heights.toSorted(([left], [right]) => left - right);
394
+ return { heights: heights.toSorted(([left], [right]) => left - right), outline };
395
}).pipe(
396
Effect.catch((cause) =>
397
Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {
@@ -432,7 +432,7 @@ const make = Effect.gen(function* () {
432
if (attachmentId === null || filePath === null) {
433
return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") });
434
}
435
- const heights = yield* fileSystem.writeFileString(filePath, html).pipe(
435
+ const measured = yield* fileSystem.writeFileString(filePath, html).pipe(
436
Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),
437
Effect.andThen(measure(html)),
438
// Only the returned reference lets thread deletion find the page, so a
@@ -443,7 +443,8 @@ const make = Effect.gen(function* () {
443
attachmentId,
444
title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
445
height: clampHtmlRenderHeight(input.height),
446
- ...(heights === undefined ? {} : { heights }),
446
+ ...(measured === undefined ? {} : { heights: measured.heights }),
447
+ ...(measured?.outline === undefined ? {} : { outline: measured.outline }),
448
} satisfies HtmlRenderReference;
449
});
450
apps/server/src/htmlRender/headlessChrome.ts
+127
-4
@@ -9,6 +9,11 @@ import * as Schema from "effect/Schema";
9
import * as Stream from "effect/Stream";
10
import * as ChildProcess from "effect/process/ChildProcess";
11
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12
+import {
13
+ encodeHtmlRenderOutline,
14
+ HTML_RENDER_COLUMN_WIDTH,
15
+ HTML_RENDER_OUTLINE_MAX_BOXES,
16
+} from "@t3tools/shared/htmlRender";
17
18
import { publicProxy } from "./publicProxy.ts";
19
@@ -157,6 +162,90 @@ const SETTLE_EXPRESSION =
162
const MEASURE_EXPRESSION =
163
"(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()";
164
165
+// The page's main blocks in document order, for a client's loading skeleton:
166
+// media and solid shapes, text with its line count, and tables with their row
167
+// count. Boxes that only wrap other blocks are walked through, not drawn.
168
+// Past the detail budget, remaining blocks are kept whole, and once the outline
169
+// is full, one block of text lines stands in for the rest of the page, so the
170
+// skeleton still reaches the bottom.
171
+const OUTLINE_MAX_VISITS = 2_000;
172
+const OUTLINE_EXPRESSION = `(() => {
173
+ const boxes = [], detail = ${HTML_RENDER_OUTLINE_MAX_BOXES - 12}, max = ${HTML_RENDER_OUTLINE_MAX_BOXES};
174
+ const media = "canvas,svg,img,video,picture,iframe,object,embed,input,select,textarea,button";
175
+ const pageBackground = getComputedStyle(document.documentElement).backgroundColor;
176
+ const filled = (s) => (s.backgroundColor !== "rgba(0, 0, 0, 0)" && s.backgroundColor !== pageBackground) || s.backgroundImage !== "none" || parseFloat(s.borderTopWidth) + parseFloat(s.borderBottomWidth) + parseFloat(s.borderLeftWidth) > 0;
177
+ const add = (kind, r, lines) => boxes.push([kind, r.left + scrollX, r.top + scrollY, r.width, r.height, lines]);
178
+ const lineCount = (s, r) => Math.max(1, Math.round(r.height / (parseFloat(s.lineHeight) || parseFloat(s.fontSize) * 1.5 || 20)));
179
+ // Text's own extent, so a short heading in a wide block stays short.
180
+ const addText = (el, s, r) => {
181
+ const range = document.createRange();
182
+ range.selectNodeContents(el);
183
+ const t = range.getBoundingClientRect();
184
+ const box = t.width >= 2 && t.height >= 2 ? t : r;
185
+ add("text", box, lineCount(s, box));
186
+ };
187
+ // Visits are capped too, so a huge generated DOM costs no more than a page.
188
+ let full = false, visits = 0;
189
+ // Whether an element holds text of its own, looking at its first few children only.
190
+ const hasOwnText = (el) => {
191
+ let n = el.firstChild;
192
+ for (let i = 0; n && i < 64; n = n.nextSibling, i++) if (n.nodeType === 3 && n.data.trim() !== "") return true;
193
+ return false;
194
+ };
195
+ const walk = (parent, ps) => {
196
+ for (const el of parent.childNodes) {
197
+ // The last slot is kept for whatever the outline has no room left for.
198
+ if (boxes.length >= max - 1 || ++visits > ${OUTLINE_MAX_VISITS}) { full = true; return; }
199
+ // Bare text only reaches here under body or a display: contents element.
200
+ if (el.nodeType === 3) {
201
+ if (el.data.trim() === "") continue;
202
+ const range = document.createRange();
203
+ range.selectNodeContents(el);
204
+ const t = range.getBoundingClientRect();
205
+ if (t.width >= 2 && t.height >= 2) add("text", t, lineCount(ps, t));
206
+ continue;
207
+ }
208
+ if (el.nodeType !== 1) continue;
209
+ const s = getComputedStyle(el);
210
+ if (s.display === "none" || s.visibility === "hidden" || s.opacity === "0") continue;
211
+ if (s.display === "contents") { walk(el, s); continue; }
212
+ const r = el.getBoundingClientRect();
213
+ // A zero-size box can still show positioned children, unless it clips them.
214
+ if (r.width < 2 || r.height < 2) { if (s.overflow === "visible") walk(el, s); continue; }
215
+ const tag = el.localName;
216
+ if (el.matches(media)) { add("media", r, 1); continue; }
217
+ if (tag === "table") { add("table", r, el.rows.length); continue; }
218
+ const text = hasOwnText(el);
219
+ if (boxes.length >= detail) { if (el.querySelector(media) || (!text && !el.firstElementChild)) add("media", r, 1); else addText(el, s, r); continue; }
220
+ if (text) { addText(el, s, r); continue; }
221
+ if (el.children.length === 0) { if (filled(s)) add("media", r, 1); continue; }
222
+ walk(el, s);
223
+ }
224
+ };
225
+ walk(document.body, getComputedStyle(document.body));
226
+ if (full) {
227
+ const top = Math.max(0, ...boxes.map((b) => b[2] + b[4]));
228
+ const root = document.documentElement;
229
+ const rest = (root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height) - top;
230
+ if (rest >= 8) boxes.push(["text", 0, top, document.documentElement.clientWidth, rest, Math.max(1, Math.round(rest / 28))]);
231
+ }
232
+ return boxes;
233
+})()`;
234
+const Outlined = Schema.Struct({
235
+ result: Schema.Struct({
236
+ value: Schema.Array(
237
+ Schema.Tuple([
238
+ Schema.Literals(["text", "media", "table"]),
239
+ Schema.Finite,
240
+ Schema.Finite,
241
+ Schema.Finite,
242
+ Schema.Finite,
243
+ Schema.Finite,
244
+ ]),
245
+ ),
246
+ }),
247
+});
248
+
249
const Ignored = Schema.Unknown;
250
const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) });
251
const Measured = Schema.Struct({ result: Schema.Struct({ value: Schema.Finite }) });
@@ -511,7 +600,28 @@ const launchBrowser = Effect.fnUntraced(function* (input: {
600
Effect.ignore,
601
);
602
514
- return { load, screenshot, consoleMessages, close };
603
+ /** The loaded page's outline, encoded for an `HtmlRenderReference`. */
604
+ const outline = send(
605
+ "Runtime.evaluate",
606
+ { expression: OUTLINE_EXPRESSION, returnByValue: true },
607
+ Outlined,
608
+ sessionId,
609
+ ).pipe(
610
+ Effect.map(({ result }) =>
611
+ encodeHtmlRenderOutline(
612
+ result.value.map(([kind, x, y, boxWidth, height, lines]) => ({
613
+ kind,
614
+ x,
615
+ y,
616
+ width: boxWidth,
617
+ height,
618
+ lines,
619
+ })),
620
+ ),
621
+ ),
622
+ );
623
+
624
+ return { load, outline, screenshot, consoleMessages, close };
625
});
626
627
return { openPage };
@@ -568,7 +678,8 @@ export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreen
678
/**
679
* Content heights of the page at each width, each from a fresh load, since
680
* pages often lay themselves out from the width once at load. One browser,
571
- * a few widths at a time.
681
+ * a few widths at a time. The load at the column width also reads the page's
682
+ * outline; an outline that cannot be read is left out.
683
*/
684
export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: {
685
readonly executable: string;
@@ -585,15 +696,27 @@ export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")
696
profileDirectory: path.join(directory, "profile"),
697
});
698
const body = pageBody(input.html);
588
- return yield* Effect.forEach(
699
+ let outline: string | undefined;
700
+ const heights = yield* Effect.forEach(
701
input.widths,
702
(width) =>
703
browser.openPage(width).pipe(
704
Effect.flatMap((page) =>
593
- page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)),
705
+ page.load(body, input.urlFragment).pipe(
706
+ Effect.tap(() =>
707
+ width === HTML_RENDER_COLUMN_WIDTH
708
+ ? page.outline.pipe(
709
+ Effect.tap((value) => Effect.sync(() => (outline = value))),
710
+ Effect.ignore,
711
+ )
712
+ : Effect.void,
713
+ ),
714
+ Effect.ensuring(page.close),
715
+ ),
716
),
717
Effect.map((height) => [width, height] as const),
718
),
719
{ concurrency: MEASURE_CONCURRENCY },
720
);
721
+ return { heights, outline };
722
}, Effect.scoped);
apps/server/src/mcp/toolkits/html/tools.ts
+1
@@ -89,6 +89,7 @@ const HtmlRenderTool = Tool.make(HTML_RENDER_TOOL_NAME, {
89
title: Schema.String,
90
height: Schema.Number,
91
heights: Schema.optional(Schema.Array(Schema.Tuple([Schema.Int, Schema.Int]))),
92
+ outline: Schema.optional(Schema.String),
93
}),
94
message: Schema.String,
95
}),
apps/web/src/components/chat/HtmlRenderDialog.test.tsx
+28
-9
@@ -10,7 +10,8 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts";
10
import { HtmlRenderDialog } from "./HtmlRenderDialog";
11
import { HtmlRenderFrame } from "./HtmlRenderFrame";
12
13
-const { refresh, showError, openLink, openChangeRequestLink } = vi.hoisted(() => ({
13
+const { cachedUrl, refresh, showError, openLink, openChangeRequestLink } = vi.hoisted(() => ({
14
+ cachedUrl: { lifeMs: 60 * 60_000 },
15
refresh: vi.fn(),
16
showError: vi.fn(),
17
openLink: vi.fn(),
@@ -24,7 +25,7 @@ vi.mock("~/assets/assetUrls", () => ({
25
useAssetUrlState: () => ({
26
_tag: "Success",
27
url: "https://environment.test/original.html",
27
- expiresAt: Date.now() + 60 * 60_000,
28
+ expiresAt: Date.now() + cachedUrl.lifeMs,
29
}),
30
useAssetUrlRefresh: () => refresh,
31
}));
@@ -50,6 +51,7 @@ beforeEach(async () => {
51
},
52
);
53
refresh.mockReset();
54
+ cachedUrl.lifeMs = 60 * 60_000;
55
openLink.mockReset().mockResolvedValue(undefined);
56
openChangeRequestLink.mockReset().mockReturnValue(false);
57
showError.mockClear();
@@ -109,7 +111,8 @@ it("closes with the close button or Escape", async () => {
111
});
112
113
async function renderInline() {
112
- await act(() =>
114
+ // Async so a URL minted at mount lands inside act.
115
+ await act(async () =>
116
root.render(
117
<HtmlRenderFrame
118
environmentId={EnvironmentId.make("environment")}
@@ -123,7 +126,7 @@ async function renderInline() {
126
);
127
}
128
126
-it("offers only full screen and opens with a fresh URL while keeping the inline page loaded", async () => {
129
+it("offers only full screen and opens with the inline URL while keeping the inline page loaded", async () => {
130
await renderInline();
131
expect(document.querySelector('[aria-label="Open in panel"]')).toBeNull();
132
const inlineFrame = document.querySelector("iframe")!;
@@ -132,11 +135,10 @@ it("offers only full screen and opens with a fresh URL while keeping the inline
135
'[aria-label="Open full screen"]',
136
)!;
137
expandButton.focus();
135
- refresh.mockResolvedValue("https://environment.test/renewed.html");
138
await click("Open full screen");
137
- expect(refresh).toHaveBeenCalledOnce();
139
+ expect(refresh).not.toHaveBeenCalled();
140
expect(document.querySelector('[role="dialog"] iframe')?.getAttribute("src")).toContain(
139
- "https://environment.test/renewed.html#",
141
+ "https://environment.test/original.html#",
142
);
143
expect(inlineFrame.src).toBe(originalSrc);
144
await click("Close");
@@ -145,9 +147,26 @@ it("offers only full screen and opens with a fresh URL while keeping the inline
147
expect(document.activeElement).toBe(expandButton);
148
});
149
148
-it("routes links from the expanded page through its thread", async () => {
150
+// An inline URL near expiry is minted at mount, and full screen mints another.
151
+async function renderInlineNearExpiry() {
152
+ cachedUrl.lifeMs = 60_000;
153
+ refresh.mockResolvedValueOnce("https://environment.test/inline.html");
154
await renderInline();
155
+ expect(refresh).toHaveBeenCalledOnce();
156
+}
157
+
158
+it("opens full screen with a fresh URL when the inline one is near expiry", async () => {
159
+ await renderInlineNearExpiry();
160
refresh.mockResolvedValue("https://environment.test/renewed.html");
161
+ await click("Open full screen");
162
+ expect(refresh).toHaveBeenCalledTimes(2);
163
+ expect(document.querySelector('[role="dialog"] iframe')?.getAttribute("src")).toContain(
164
+ "https://environment.test/renewed.html#",
165
+ );
166
+});
167
+
168
+it("routes links from the expanded page through its thread", async () => {
169
+ await renderInline();
170
openChangeRequestLink.mockReturnValue(true);
171
await click("Open full screen");
172
const frame = document.querySelector<HTMLIFrameElement>('[role="dialog"] iframe')!;
@@ -173,7 +192,7 @@ it("routes links from the expanded page through its thread", async () => {
192
it.each([null, new Error("Disconnected")])(
193
"reports an unavailable URL instead of opening a blank page: %s",
194
async (failure) => {
176
- await renderInline();
195
+ await renderInlineNearExpiry();
196
if (failure === null) refresh.mockResolvedValue(null);
197
else refresh.mockRejectedValue(failure);
198
await click("Open full screen");
apps/web/src/components/chat/HtmlRenderFrame.tsx
+109
-4
@@ -3,15 +3,19 @@ import {
3
HTML_RENDER_COLUMN_WIDTH,
4
htmlRenderFileName,
5
htmlRenderFrameHeight,
6
+ htmlRenderOutlineBoxes,
7
+ type HtmlRenderOutlineBox,
8
type HtmlRenderReference,
9
} from "@t3tools/shared/htmlRender";
10
import { Maximize2Icon } from "lucide-react";
9
-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
11
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
12
13
import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
14
+import { cn } from "~/lib/utils";
15
16
import { HtmlRenderDocument } from "../files/BrowserDocumentFrame";
17
import { Button } from "../ui/button";
18
+import { Skeleton } from "../ui/skeleton";
19
import { toastManager } from "../ui/toast";
20
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
21
import { HtmlRenderDialog } from "./HtmlRenderDialog";
@@ -64,7 +68,17 @@ export function HtmlRenderFrame(props: {
68
// page again; one near expiry is minted afresh, since a frame cannot report a
69
// failed load. The page keeps its first URL for its lifetime.
70
const [src, setSrc] = useState<string | null>(null);
71
+ // Full screen reuses the inline URL while it has life left, so the page
72
+ // comes from the browser's cache instead of a new mint and download.
73
+ const srcExpiresAt = useRef(0);
74
const [expandedSrc, setExpandedSrc] = useState<string | null>(null);
75
+ // The page stays hidden behind a skeleton until it reports its content.
76
+ const [ready, setReady] = useState(false);
77
+ const showPage = useCallback(() => setReady(true), []);
78
+ const fitPage = useCallback((contentHeight: number) => {
79
+ setContentHeight(contentHeight);
80
+ setReady(true);
81
+ }, []);
82
const { onFullscreenChange } = props;
83
useEffect(() => {
84
if (expandedSrc === null) return;
@@ -89,6 +103,7 @@ export function HtmlRenderFrame(props: {
103
}
104
if (cachedUrl === null) return;
105
if (cachedExpiresAt - Date.now() > MIN_URL_LIFE_MS) {
106
+ srcExpiresAt.current = cachedExpiresAt;
107
setSrc(cachedUrl);
108
return;
109
}
@@ -101,14 +116,25 @@ export function HtmlRenderFrame(props: {
116
117
return (
118
<div ref={boxRef} className="group/html-render relative" style={{ height }}>
119
+ {!ready && !failed ? (
120
+ <HtmlRenderSkeleton
121
+ title={title}
122
+ height={height}
123
+ outline={htmlRenderOutlineBoxes(props.htmlRender, width)}
124
+ />
125
+ ) : null}
126
{src !== null ? (
127
<>
128
<HtmlRenderDocument
129
src={src}
130
title={title}
131
threadRef={props.threadRef}
110
- className="block size-full"
111
- onContentHeight={setContentHeight}
132
+ className={cn(
133
+ "block size-full motion-safe:transition-opacity motion-safe:duration-200",
134
+ !ready && "opacity-0",
135
+ )}
136
+ onContentHeight={fitPage}
137
+ onLoad={showPage}
138
/>
139
<div className="absolute end-2 top-2 flex gap-1 opacity-0 transition-opacity duration-150 focus-within:opacity-100 group-hover/html-render:opacity-100 pointer-coarse:opacity-100">
140
<Tooltip>
@@ -119,7 +145,10 @@ export function HtmlRenderFrame(props: {
145
size="icon-xs"
146
variant="glass"
147
onClick={async () => {
122
- const url = await refresh().catch(() => null);
148
+ const url =
149
+ srcExpiresAt.current - Date.now() > MIN_URL_LIFE_MS
150
+ ? src
151
+ : await refresh().catch(() => null);
152
if (url !== null) setExpandedSrc(url);
153
else
154
toastManager.add({
@@ -153,3 +182,79 @@ export function HtmlRenderFrame(props: {
182
</div>
183
);
184
}
185
+
186
+// Without an outline: one heading, a line of text, and a chart-sized block,
187
+// the shape most pages take, repeated to fill the frame's reserved height.
188
+const SKELETON_SECTION_HEIGHT = 264;
189
+
190
+const OUTLINE_BOX_CLASS = {
191
+ media: "rounded-lg bg-muted-foreground/15",
192
+ text: "",
193
+ table: "",
194
+} as const;
195
+
196
+const OUTLINE_BAR = "color-mix(in srgb, var(--color-muted-foreground) 15%, transparent)";
197
+
198
+// Text lines and table rows are bars painted by one gradient per box, so a
199
+// long page costs one element per block rather than one per line.
200
+function outlineBoxStyle(box: HtmlRenderOutlineBox): React.CSSProperties {
201
+ const style: React.CSSProperties = {
202
+ left: box.x,
203
+ top: box.y,
204
+ width: box.width,
205
+ height: box.height,
206
+ };
207
+ if (box.kind !== "text" && box.kind !== "table") return style;
208
+ const step = box.height / box.lines;
209
+ const bar = Math.min(box.kind === "table" ? 12 : 10, step * 0.6);
210
+ const start = (step - bar) / 2;
211
+ return {
212
+ ...style,
213
+ backgroundImage: `repeating-linear-gradient(to bottom, transparent 0 ${start}px, ${OUTLINE_BAR} ${start}px ${start + bar}px, transparent ${start + bar}px ${step}px)`,
214
+ };
215
+}
216
+
217
+/**
218
+ * Holds the frame's place while the page loads: the page's own blocks when the
219
+ * server measured an outline, else a generic page shape. The outline pulses
220
+ * as one layer.
221
+ */
222
+function HtmlRenderSkeleton(props: {
223
+ readonly title: string;
224
+ readonly height: number;
225
+ readonly outline: ReadonlyArray<HtmlRenderOutlineBox>;
226
+}) {
227
+ if (props.outline.length > 0) {
228
+ return (
229
+ <div
230
+ role="status"
231
+ aria-label={`Loading ${props.title}`}
232
+ className="pointer-events-none absolute inset-0 overflow-hidden motion-safe:animate-skeleton"
233
+ >
234
+ {props.outline.map((box) => (
235
+ <div
236
+ key={`${box.kind}:${box.x}:${box.y}:${box.width}:${box.height}`}
237
+ className={cn("absolute", OUTLINE_BOX_CLASS[box.kind])}
238
+ style={outlineBoxStyle(box)}
239
+ />
240
+ ))}
241
+ </div>
242
+ );
243
+ }
244
+ const sections = Math.ceil(props.height / SKELETON_SECTION_HEIGHT);
245
+ return (
246
+ <div
247
+ role="status"
248
+ aria-label={`Loading ${props.title}`}
249
+ className="pointer-events-none absolute inset-0 flex flex-col gap-6 overflow-hidden pt-1"
250
+ >
251
+ {Array.from({ length: sections }, (_, index) => (
252
+ <div key={index} className="flex shrink-0 flex-col gap-2">
253
+ <Skeleton className="h-4 w-2/5" />
254
+ <Skeleton className="h-3 w-3/5" />
255
+ <Skeleton shape="card" className="mt-2 h-40 w-full" />
256
+ </div>
257
+ ))}
258
+ </div>
259
+ );
260
+}
apps/web/src/components/files/BrowserDocumentFrame.tsx
+3
@@ -124,6 +124,8 @@ export function HtmlRenderDocument(props: {
124
readonly threadRef?: ScopedThreadRef | undefined;
125
/** Receives the page's content height whenever it changes, so an inline frame can fit it. */
126
readonly onContentHeight?: (height: number) => void;
127
+ /** Called when the page has loaded. */
128
+ readonly onLoad?: () => void;
129
}) {
130
const theme = useHtmlRenderTheme();
131
const frameRef = useRef<HTMLIFrameElement>(null);
@@ -292,6 +294,7 @@ export function HtmlRenderDocument(props: {
294
// Covers a theme change that landed while the page was loading.
295
postTheme();
296
postShortcuts();
297
+ props.onLoad?.();
298
}}
299
// A frame whose color scheme differs from its document's paints an opaque
300
// canvas, so the blank document a frame starts with would flash white in
packages/shared/src/htmlRender.test.ts
+48
@@ -1,8 +1,10 @@
1
import { describe, expect, it } from "vite-plus/test";
2
3
import {
4
+ encodeHtmlRenderOutline,
5
HTML_RENDER_MAX_HEIGHT,
6
htmlRenderFrameHeight,
7
+ htmlRenderOutlineBoxes,
8
htmlRenderReferencesEqual,
9
htmlRenderTheme,
10
htmlRenderThemeFragment,
@@ -266,3 +268,49 @@ describe("htmlRenderFrameHeight", () => {
268
expect(htmlRenderReferencesEqual(measured, { ...copy, heights: [[390, 1290]] })).toBe(false);
269
});
270
});
271
+
272
+describe("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
+});
packages/shared/src/htmlRender.ts
+81
-1
@@ -30,6 +30,12 @@ export interface HtmlRenderReference {
30
* width. Absent when the preview browser was not installed yet.
31
*/
32
readonly heights?: ReadonlyArray<readonly [width: number, height: number]>;
33
+ /**
34
+ * The page's main blocks at the column width, measured with `heights`, so a
35
+ * client can draw its loading skeleton in the page's shape. See
36
+ * `encodeHtmlRenderOutline`.
37
+ */
38
+ readonly outline?: string;
39
}
40
41
/** Frame widths the server measures a page at, from phones to the wide chat setting. */
@@ -65,7 +71,7 @@ function readMeasuredHeights(value: unknown) {
71
72
export function readHtmlRenderReference(value: unknown): HtmlRenderReference | undefined {
73
if (typeof value !== "object" || value === null) return undefined;
68
- const { attachmentId, title, height, heights } = value as Record<string, unknown>;
74
+ const { attachmentId, title, height, heights, outline } = value as Record<string, unknown>;
75
if (
76
typeof attachmentId !== "string" ||
77
attachmentId.length === 0 ||
@@ -82,6 +88,9 @@ export function readHtmlRenderReference(value: unknown): HtmlRenderReference | u
88
title: title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
89
height: clampHtmlRenderHeight(height),
90
...(measured === undefined ? {} : { heights: measured }),
91
+ ...(measured !== undefined && typeof outline === "string" && OUTLINE_PATTERN.test(outline)
92
+ ? { outline }
93
+ : {}),
94
};
95
}
96
@@ -91,6 +100,7 @@ export function htmlRenderReferencesEqual(left: HtmlRenderReference, right: Html
100
left.attachmentId === right.attachmentId &&
101
left.title === right.title &&
102
left.height === right.height &&
103
+ left.outline === right.outline &&
104
(left.heights ?? []).length === (right.heights ?? []).length &&
105
(left.heights ?? []).every(
106
([width, height], index) =>
@@ -132,6 +142,76 @@ export function htmlRenderFrameHeight(
142
return clampHtmlRenderHeight(Math.min(cap, contentHeight ?? measuredHeight(heights, width)));
143
}
144
145
+/**
146
+ * One block of a page's outline: `text` with its line count, a `media` element
147
+ * or solid shape, or a `table` with its row count.
148
+ */
149
+export interface HtmlRenderOutlineBox {
150
+ readonly kind: "text" | "media" | "table";
151
+ readonly x: number;
152
+ readonly y: number;
153
+ readonly width: number;
154
+ readonly height: number;
155
+ readonly lines: number;
156
+}
157
+
158
+const OUTLINE_KINDS = { t: "text", m: "media", g: "table" } as const;
159
+const OUTLINE_LETTERS = { text: "t", media: "m", table: "g" } as const;
160
+// Coordinates travel in 4px units, which keeps the tool result an agent reads short.
161
+const OUTLINE_UNIT = 4;
162
+export const HTML_RENDER_OUTLINE_MAX_BOXES = 48;
163
+// Sizes and line counts are never zero, so a client never divides by one.
164
+const OUTLINE_BOX = "[tmg]\\d{1,4},\\d{1,4},[1-9]\\d{0,3},[1-9]\\d{0,3},[1-9]\\d{0,2}";
165
+const OUTLINE_PATTERN = new RegExp(
166
+ `^${OUTLINE_BOX}(?:;${OUTLINE_BOX}){0,${HTML_RENDER_OUTLINE_MAX_BOXES - 1}}$`,
167
+);
168
+
169
+/** Packs measured boxes, in CSS pixels at the column width, into an outline string. */
170
+export function encodeHtmlRenderOutline(
171
+ boxes: ReadonlyArray<HtmlRenderOutlineBox>,
172
+): string | undefined {
173
+ const unit = (value: number) => Math.min(9_999, Math.max(0, Math.round(value / OUTLINE_UNIT)));
174
+ const encoded = boxes
175
+ .slice(0, HTML_RENDER_OUTLINE_MAX_BOXES)
176
+ .flatMap((box) =>
177
+ unit(box.width) > 0 && unit(box.height) > 0
178
+ ? [
179
+ `${OUTLINE_LETTERS[box.kind]}${unit(box.x)},${unit(box.y)},${unit(box.width)},${unit(box.height)},${Math.min(999, Math.max(1, Math.round(box.lines)))}`,
180
+ ]
181
+ : [],
182
+ )
183
+ .join(";");
184
+ return encoded === "" ? undefined : encoded;
185
+}
186
+
187
+/**
188
+ * The outline's boxes in CSS pixels for a frame `width` wide, stretched to the
189
+ * page's measured height there. Empty without an outline.
190
+ */
191
+export function htmlRenderOutlineBoxes(
192
+ reference: HtmlRenderReference,
193
+ width: number,
194
+): ReadonlyArray<HtmlRenderOutlineBox> {
195
+ const heights = reference.heights;
196
+ if (reference.outline === undefined || heights === undefined || heights.length === 0) return [];
197
+ const scaleX = width / HTML_RENDER_COLUMN_WIDTH;
198
+ const scaleY = measuredHeight(heights, width) / measuredHeight(heights, HTML_RENDER_COLUMN_WIDTH);
199
+ return reference.outline.split(";").map((entry) => {
200
+ const [x = 0, y = 0, boxWidth = 0, boxHeight = 0, lines = 1] = entry
201
+ .slice(1)
202
+ .split(",")
203
+ .map(Number);
204
+ return {
205
+ kind: OUTLINE_KINDS[entry[0] as keyof typeof OUTLINE_KINDS],
206
+ x: x * OUTLINE_UNIT * scaleX,
207
+ y: y * OUTLINE_UNIT * scaleY,
208
+ width: boxWidth * OUTLINE_UNIT * scaleX,
209
+ height: boxHeight * OUTLINE_UNIT * scaleY,
210
+ lines,
211
+ };
212
+ });
213
+}
214
+
215
/** A readable download name: the title without characters file systems reject. */
216
export function htmlRenderFileName(title: string) {
217
const name = title