TypeScript
perf(web): HTML renders show a layout skeleton and reuse cached pages (#19654)
mariaf798cb299ac9
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.tsindex e32f4137252..bf0f4431807 100644--- a/apps/server/src/assets/AssetAccess.test.ts+++ b/apps/server/src/assets/AssetAccess.test.ts@@ -1029,6 +1029,34 @@ describe("AssetAccess", () => {}).pipe(Effect.provide(layerTest)),);+ it.effect("signs the same HTML page URL within an expiry window", () =>+ Effect.gen(function* () {+ const config = yield* ServerConfig.ServerConfig;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-html";+ yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });+ yield* fileSystem.writeFileString(+ path.join(config.attachmentsDir, `${attachmentId}.html`),+ "<p>render</p>",+ );+ const bucketMs = 30 * 60 * 1000;+ const issue = issueAssetUrl({+ resource: { _tag: "attachment", attachmentId, disposition: "inline" },+ });+ yield* TestClock.setTime(bucketMs + 1);+ const first = yield* issue;+ yield* TestClock.adjust("20 minutes");+ const second = yield* issue;+ yield* TestClock.adjust("10 minutes");+ const next = yield* issue;++ expect(second.relativeUrl).toBe(first.relativeUrl);+ expect(first.expiresAt).toBe(4 * bucketMs);+ expect(next.expiresAt).toBe(5 * bucketMs);+ }).pipe(Effect.provide(layerTest)),+ );+it.effect("serves video attachments inline", () =>Effect.gen(function* () {const config = yield* ServerConfig.ServerConfig;diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.tsindex 6b736c68f74..4c30f10c3b3 100644--- a/apps/server/src/assets/AssetAccess.ts+++ b/apps/server/src/assets/AssetAccess.ts@@ -71,6 +71,7 @@ export const ASSET_ROUTE_PREFIX = "/api/assets";const SIGNING_SECRET_NAME = "asset-access-signing-key";const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;+const HTML_ATTACHMENT_TOKEN_BUCKET_MS = 30 * 60 * 1000;const PROJECT_FAVICON_VERSION_PREFIX = "v";// Clients draw project icons from a 96px thumbnail at most.const PROJECT_FAVICON_ICNS_MIN_SIZE = 96;@@ -825,6 +826,14 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (iPROJECT_FAVICON_TOKEN_BUCKET_MS;claims = { ...claims, expiresAt };}+ if (claims.kind === "attachment" && claims.mimeType === "text/html") {+ // HTML pages never change, so mints in the same window sign the same URL and a reload+ // can answer it from the browser cache. Images keep a new URL per mint, since their+ // load-error retries rely on one.+ expiresAt =+ Math.ceil(expiresAt / HTML_ATTACHMENT_TOKEN_BUCKET_MS) * HTML_ATTACHMENT_TOKEN_BUCKET_MS;+ claims = { ...claims, expiresAt };+ }const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;return {diff --git a/apps/server/src/htmlRender/HtmlRender.test.ts b/apps/server/src/htmlRender/HtmlRender.test.tsindex aab68c7b187..7ab5bda2e11 100644--- a/apps/server/src/htmlRender/HtmlRender.test.ts+++ b/apps/server/src/htmlRender/HtmlRender.test.ts@@ -391,7 +391,7 @@ describe("HtmlRender", () => {// Like a D3 chart, the page sizes itself from the width once, at load.const reference = yield* htmlRender.publish({threadId: ThreadId.make("thread-html-measure"),- html: '<div id="chart"></div><script>document.getElementById("chart").style.height = innerWidth / 2 + "px";</script>',+ html: '<div id="chart" style="background:#888"></div><script>document.getElementById("chart").style.height = innerWidth / 2 + "px";</script>',title: "Chart",height: 600,});@@ -399,6 +399,8 @@ describe("HtmlRender", () => {expect(reference.heights).toEqual(HTML_RENDER_MEASURE_WIDTHS.map((width) => [width, Math.ceil(width / 2)]),);+ // The chart as the column-width load laid it out, in 4px units.+ expect(reference.outline).toBe("m0,0,182,91,1");}).pipe(Effect.provide(layerHtmlRender(executable)));}),30_000,diff --git a/apps/server/src/htmlRender/HtmlRender.ts b/apps/server/src/htmlRender/HtmlRender.tsindex 47c7238fb47..bf982a3e9ce 100644--- a/apps/server/src/htmlRender/HtmlRender.ts+++ b/apps/server/src/htmlRender/HtmlRender.ts@@ -372,7 +372,7 @@ const make = Effect.gen(function* () {Effect.gen(function* () {const executable = yield* previewBrowser.installed;if (Option.isNone(executable)) return undefined;- const heights = yield* launching(executable.value, (noSandbox) =>+ const { heights, outline } = yield* launching(executable.value, (noSandbox) =>HeadlessChrome.measureHtmlHeights({executable: executable.value,noSandbox,@@ -391,7 +391,7 @@ const make = Effect.gen(function* () {),}),);- return heights.toSorted(([left], [right]) => left - right);+ return { heights: heights.toSorted(([left], [right]) => left - right), outline };}).pipe(Effect.catch((cause) =>Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {@@ -432,7 +432,7 @@ const make = Effect.gen(function* () {if (attachmentId === null || filePath === null) {return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") });}- const heights = yield* fileSystem.writeFileString(filePath, html).pipe(+ const measured = yield* fileSystem.writeFileString(filePath, html).pipe(Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),Effect.andThen(measure(html)),// Only the returned reference lets thread deletion find the page, so a@@ -443,7 +443,8 @@ const make = Effect.gen(function* () {attachmentId,title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",height: clampHtmlRenderHeight(input.height),- ...(heights === undefined ? {} : { heights }),+ ...(measured === undefined ? {} : { heights: measured.heights }),+ ...(measured?.outline === undefined ? {} : { outline: measured.outline }),} satisfies HtmlRenderReference;});diff --git a/apps/server/src/htmlRender/headlessChrome.ts b/apps/server/src/htmlRender/headlessChrome.tsindex ec4aa57515f..60a1ef756cf 100644--- a/apps/server/src/htmlRender/headlessChrome.ts+++ b/apps/server/src/htmlRender/headlessChrome.ts@@ -9,6 +9,11 @@ import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";import * as ChildProcess from "effect/process/ChildProcess";import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";+import {+ encodeHtmlRenderOutline,+ HTML_RENDER_COLUMN_WIDTH,+ HTML_RENDER_OUTLINE_MAX_BOXES,+} from "@t3tools/shared/htmlRender";import { publicProxy } from "./publicProxy.ts";@@ -157,6 +162,90 @@ const SETTLE_EXPRESSION =const MEASURE_EXPRESSION ="(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()";+// The page's main blocks in document order, for a client's loading skeleton:+// media and solid shapes, text with its line count, and tables with their row+// count. Boxes that only wrap other blocks are walked through, not drawn.+// Past the detail budget, remaining blocks are kept whole, and once the outline+// is full, one block of text lines stands in for the rest of the page, so the+// skeleton still reaches the bottom.+const OUTLINE_MAX_VISITS = 2_000;+const OUTLINE_EXPRESSION = `(() => {+ const boxes = [], detail = ${HTML_RENDER_OUTLINE_MAX_BOXES - 12}, max = ${HTML_RENDER_OUTLINE_MAX_BOXES};+ const media = "canvas,svg,img,video,picture,iframe,object,embed,input,select,textarea,button";+ const pageBackground = getComputedStyle(document.documentElement).backgroundColor;+ 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;+ const add = (kind, r, lines) => boxes.push([kind, r.left + scrollX, r.top + scrollY, r.width, r.height, lines]);+ const lineCount = (s, r) => Math.max(1, Math.round(r.height / (parseFloat(s.lineHeight) || parseFloat(s.fontSize) * 1.5 || 20)));+ // Text's own extent, so a short heading in a wide block stays short.+ const addText = (el, s, r) => {+ const range = document.createRange();+ range.selectNodeContents(el);+ const t = range.getBoundingClientRect();+ const box = t.width >= 2 && t.height >= 2 ? t : r;+ add("text", box, lineCount(s, box));+ };+ // Visits are capped too, so a huge generated DOM costs no more than a page.+ let full = false, visits = 0;+ // Whether an element holds text of its own, looking at its first few children only.+ const hasOwnText = (el) => {+ let n = el.firstChild;+ for (let i = 0; n && i < 64; n = n.nextSibling, i++) if (n.nodeType === 3 && n.data.trim() !== "") return true;+ return false;+ };+ const walk = (parent, ps) => {+ for (const el of parent.childNodes) {+ // The last slot is kept for whatever the outline has no room left for.+ if (boxes.length >= max - 1 || ++visits > ${OUTLINE_MAX_VISITS}) { full = true; return; }+ // Bare text only reaches here under body or a display: contents element.+ if (el.nodeType === 3) {+ if (el.data.trim() === "") continue;+ const range = document.createRange();+ range.selectNodeContents(el);+ const t = range.getBoundingClientRect();+ if (t.width >= 2 && t.height >= 2) add("text", t, lineCount(ps, t));+ continue;+ }+ if (el.nodeType !== 1) continue;+ const s = getComputedStyle(el);+ if (s.display === "none" || s.visibility === "hidden" || s.opacity === "0") continue;+ if (s.display === "contents") { walk(el, s); continue; }+ const r = el.getBoundingClientRect();+ // A zero-size box can still show positioned children, unless it clips them.+ if (r.width < 2 || r.height < 2) { if (s.overflow === "visible") walk(el, s); continue; }+ const tag = el.localName;+ if (el.matches(media)) { add("media", r, 1); continue; }+ if (tag === "table") { add("table", r, el.rows.length); continue; }+ const text = hasOwnText(el);+ if (boxes.length >= detail) { if (el.querySelector(media) || (!text && !el.firstElementChild)) add("media", r, 1); else addText(el, s, r); continue; }+ if (text) { addText(el, s, r); continue; }+ if (el.children.length === 0) { if (filled(s)) add("media", r, 1); continue; }+ walk(el, s);+ }+ };+ walk(document.body, getComputedStyle(document.body));+ if (full) {+ const top = Math.max(0, ...boxes.map((b) => b[2] + b[4]));+ const root = document.documentElement;+ const rest = (root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height) - top;+ if (rest >= 8) boxes.push(["text", 0, top, document.documentElement.clientWidth, rest, Math.max(1, Math.round(rest / 28))]);+ }+ return boxes;+})()`;+const Outlined = Schema.Struct({+ result: Schema.Struct({+ value: Schema.Array(+ Schema.Tuple([+ Schema.Literals(["text", "media", "table"]),+ Schema.Finite,+ Schema.Finite,+ Schema.Finite,+ Schema.Finite,+ Schema.Finite,+ ]),+ ),+ }),+});+const Ignored = Schema.Unknown;const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) });const Measured = Schema.Struct({ result: Schema.Struct({ value: Schema.Finite }) });@@ -511,7 +600,28 @@ const launchBrowser = Effect.fnUntraced(function* (input: {Effect.ignore,);- return { load, screenshot, consoleMessages, close };+ /** The loaded page's outline, encoded for an `HtmlRenderReference`. */+ const outline = send(+ "Runtime.evaluate",+ { expression: OUTLINE_EXPRESSION, returnByValue: true },+ Outlined,+ sessionId,+ ).pipe(+ Effect.map(({ result }) =>+ encodeHtmlRenderOutline(+ result.value.map(([kind, x, y, boxWidth, height, lines]) => ({+ kind,+ x,+ y,+ width: boxWidth,+ height,+ lines,+ })),+ ),+ ),+ );++ return { load, outline, screenshot, consoleMessages, close };});return { openPage };@@ -568,7 +678,8 @@ export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreen/*** Content heights of the page at each width, each from a fresh load, since* pages often lay themselves out from the width once at load. One browser,- * a few widths at a time.+ * a few widths at a time. The load at the column width also reads the page's+ * outline; an outline that cannot be read is left out.*/export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: {readonly executable: string;@@ -585,15 +696,27 @@ export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")profileDirectory: path.join(directory, "profile"),});const body = pageBody(input.html);- return yield* Effect.forEach(+ let outline: string | undefined;+ const heights = yield* Effect.forEach(input.widths,(width) =>browser.openPage(width).pipe(Effect.flatMap((page) =>- page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)),+ page.load(body, input.urlFragment).pipe(+ Effect.tap(() =>+ width === HTML_RENDER_COLUMN_WIDTH+ ? page.outline.pipe(+ Effect.tap((value) => Effect.sync(() => (outline = value))),+ Effect.ignore,+ )+ : Effect.void,+ ),+ Effect.ensuring(page.close),+ ),),Effect.map((height) => [width, height] as const),),{ concurrency: MEASURE_CONCURRENCY },);+ return { heights, outline };}, Effect.scoped);diff --git a/apps/server/src/mcp/toolkits/html/tools.ts b/apps/server/src/mcp/toolkits/html/tools.tsindex c92e2e466f0..bdd4513ec2e 100644--- a/apps/server/src/mcp/toolkits/html/tools.ts+++ b/apps/server/src/mcp/toolkits/html/tools.ts@@ -89,6 +89,7 @@ const HtmlRenderTool = Tool.make(HTML_RENDER_TOOL_NAME, {title: Schema.String,height: Schema.Number,heights: Schema.optional(Schema.Array(Schema.Tuple([Schema.Int, Schema.Int]))),+ outline: Schema.optional(Schema.String),}),message: Schema.String,}),diff --git a/apps/web/src/components/chat/HtmlRenderDialog.test.tsx b/apps/web/src/components/chat/HtmlRenderDialog.test.tsxindex fbf0b4b536c..9cd22832f0e 100644--- a/apps/web/src/components/chat/HtmlRenderDialog.test.tsx+++ b/apps/web/src/components/chat/HtmlRenderDialog.test.tsx@@ -10,7 +10,8 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts";import { HtmlRenderDialog } from "./HtmlRenderDialog";import { HtmlRenderFrame } from "./HtmlRenderFrame";-const { refresh, showError, openLink, openChangeRequestLink } = vi.hoisted(() => ({+const { cachedUrl, refresh, showError, openLink, openChangeRequestLink } = vi.hoisted(() => ({+ cachedUrl: { lifeMs: 60 * 60_000 },refresh: vi.fn(),showError: vi.fn(),openLink: vi.fn(),@@ -24,7 +25,7 @@ vi.mock("~/assets/assetUrls", () => ({useAssetUrlState: () => ({_tag: "Success",url: "https://environment.test/original.html",- expiresAt: Date.now() + 60 * 60_000,+ expiresAt: Date.now() + cachedUrl.lifeMs,}),useAssetUrlRefresh: () => refresh,}));@@ -50,6 +51,7 @@ beforeEach(async () => {},);refresh.mockReset();+ cachedUrl.lifeMs = 60 * 60_000;openLink.mockReset().mockResolvedValue(undefined);openChangeRequestLink.mockReset().mockReturnValue(false);showError.mockClear();@@ -109,7 +111,8 @@ it("closes with the close button or Escape", async () => {});async function renderInline() {- await act(() =>+ // Async so a URL minted at mount lands inside act.+ await act(async () =>root.render(<HtmlRenderFrameenvironmentId={EnvironmentId.make("environment")}@@ -123,7 +126,7 @@ async function renderInline() {);}-it("offers only full screen and opens with a fresh URL while keeping the inline page loaded", async () => {+it("offers only full screen and opens with the inline URL while keeping the inline page loaded", async () => {await renderInline();expect(document.querySelector('[aria-label="Open in panel"]')).toBeNull();const inlineFrame = document.querySelector("iframe")!;@@ -132,11 +135,10 @@ it("offers only full screen and opens with a fresh URL while keeping the inline'[aria-label="Open full screen"]',)!;expandButton.focus();- refresh.mockResolvedValue("https://environment.test/renewed.html");await click("Open full screen");- expect(refresh).toHaveBeenCalledOnce();+ expect(refresh).not.toHaveBeenCalled();expect(document.querySelector('[role="dialog"] iframe')?.getAttribute("src")).toContain(- "https://environment.test/renewed.html#",+ "https://environment.test/original.html#",);expect(inlineFrame.src).toBe(originalSrc);await click("Close");@@ -145,9 +147,26 @@ it("offers only full screen and opens with a fresh URL while keeping the inlineexpect(document.activeElement).toBe(expandButton);});-it("routes links from the expanded page through its thread", async () => {+// An inline URL near expiry is minted at mount, and full screen mints another.+async function renderInlineNearExpiry() {+ cachedUrl.lifeMs = 60_000;+ refresh.mockResolvedValueOnce("https://environment.test/inline.html");await renderInline();+ expect(refresh).toHaveBeenCalledOnce();+}++it("opens full screen with a fresh URL when the inline one is near expiry", async () => {+ await renderInlineNearExpiry();refresh.mockResolvedValue("https://environment.test/renewed.html");+ await click("Open full screen");+ expect(refresh).toHaveBeenCalledTimes(2);+ expect(document.querySelector('[role="dialog"] iframe')?.getAttribute("src")).toContain(+ "https://environment.test/renewed.html#",+ );+});++it("routes links from the expanded page through its thread", async () => {+ await renderInline();openChangeRequestLink.mockReturnValue(true);await click("Open full screen");const frame = document.querySelector<HTMLIFrameElement>('[role="dialog"] iframe')!;@@ -173,7 +192,7 @@ it("routes links from the expanded page through its thread", async () => {it.each([null, new Error("Disconnected")])("reports an unavailable URL instead of opening a blank page: %s",async (failure) => {- await renderInline();+ await renderInlineNearExpiry();if (failure === null) refresh.mockResolvedValue(null);else refresh.mockRejectedValue(failure);await click("Open full screen");diff --git a/apps/web/src/components/chat/HtmlRenderFrame.tsx b/apps/web/src/components/chat/HtmlRenderFrame.tsxindex 5133c0ea55c..067ea0d2ba2 100644--- a/apps/web/src/components/chat/HtmlRenderFrame.tsx+++ b/apps/web/src/components/chat/HtmlRenderFrame.tsx@@ -3,15 +3,19 @@ import {HTML_RENDER_COLUMN_WIDTH,htmlRenderFileName,htmlRenderFrameHeight,+ htmlRenderOutlineBoxes,+ type HtmlRenderOutlineBox,type HtmlRenderReference,} from "@t3tools/shared/htmlRender";import { Maximize2Icon } from "lucide-react";-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";+import { cn } from "~/lib/utils";import { HtmlRenderDocument } from "../files/BrowserDocumentFrame";import { Button } from "../ui/button";+import { Skeleton } from "../ui/skeleton";import { toastManager } from "../ui/toast";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { HtmlRenderDialog } from "./HtmlRenderDialog";@@ -64,7 +68,17 @@ export function HtmlRenderFrame(props: {// page again; one near expiry is minted afresh, since a frame cannot report a// failed load. The page keeps its first URL for its lifetime.const [src, setSrc] = useState<string | null>(null);+ // Full screen reuses the inline URL while it has life left, so the page+ // comes from the browser's cache instead of a new mint and download.+ const srcExpiresAt = useRef(0);const [expandedSrc, setExpandedSrc] = useState<string | null>(null);+ // The page stays hidden behind a skeleton until it reports its content.+ const [ready, setReady] = useState(false);+ const showPage = useCallback(() => setReady(true), []);+ const fitPage = useCallback((contentHeight: number) => {+ setContentHeight(contentHeight);+ setReady(true);+ }, []);const { onFullscreenChange } = props;useEffect(() => {if (expandedSrc === null) return;@@ -89,6 +103,7 @@ export function HtmlRenderFrame(props: {}if (cachedUrl === null) return;if (cachedExpiresAt - Date.now() > MIN_URL_LIFE_MS) {+ srcExpiresAt.current = cachedExpiresAt;setSrc(cachedUrl);return;}@@ -101,14 +116,25 @@ export function HtmlRenderFrame(props: {return (<div ref={boxRef} className="group/html-render relative" style={{ height }}>+ {!ready && !failed ? (+ <HtmlRenderSkeleton+ title={title}+ height={height}+ outline={htmlRenderOutlineBoxes(props.htmlRender, width)}+ />+ ) : null}{src !== null ? (<><HtmlRenderDocumentsrc={src}title={title}threadRef={props.threadRef}- className="block size-full"- onContentHeight={setContentHeight}+ className={cn(+ "block size-full motion-safe:transition-opacity motion-safe:duration-200",+ !ready && "opacity-0",+ )}+ onContentHeight={fitPage}+ onLoad={showPage}/><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"><Tooltip>@@ -119,7 +145,10 @@ export function HtmlRenderFrame(props: {size="icon-xs"variant="glass"onClick={async () => {- const url = await refresh().catch(() => null);+ const url =+ srcExpiresAt.current - Date.now() > MIN_URL_LIFE_MS+ ? src+ : await refresh().catch(() => null);if (url !== null) setExpandedSrc(url);elsetoastManager.add({@@ -153,3 +182,79 @@ export function HtmlRenderFrame(props: {</div>);}++// Without an outline: one heading, a line of text, and a chart-sized block,+// the shape most pages take, repeated to fill the frame's reserved height.+const SKELETON_SECTION_HEIGHT = 264;++const OUTLINE_BOX_CLASS = {+ media: "rounded-lg bg-muted-foreground/15",+ text: "",+ table: "",+} as const;++const OUTLINE_BAR = "color-mix(in srgb, var(--color-muted-foreground) 15%, transparent)";++// Text lines and table rows are bars painted by one gradient per box, so a+// long page costs one element per block rather than one per line.+function outlineBoxStyle(box: HtmlRenderOutlineBox): React.CSSProperties {+ const style: React.CSSProperties = {+ left: box.x,+ top: box.y,+ width: box.width,+ height: box.height,+ };+ if (box.kind !== "text" && box.kind !== "table") return style;+ const step = box.height / box.lines;+ const bar = Math.min(box.kind === "table" ? 12 : 10, step * 0.6);+ const start = (step - bar) / 2;+ return {+ ...style,+ backgroundImage: `repeating-linear-gradient(to bottom, transparent 0 ${start}px, ${OUTLINE_BAR} ${start}px ${start + bar}px, transparent ${start + bar}px ${step}px)`,+ };+}++/**+ * Holds the frame's place while the page loads: the page's own blocks when the+ * server measured an outline, else a generic page shape. The outline pulses+ * as one layer.+ */+function HtmlRenderSkeleton(props: {+ readonly title: string;+ readonly height: number;+ readonly outline: ReadonlyArray<HtmlRenderOutlineBox>;+}) {+ if (props.outline.length > 0) {+ return (+ <div+ role="status"+ aria-label={`Loading ${props.title}`}+ className="pointer-events-none absolute inset-0 overflow-hidden motion-safe:animate-skeleton"+ >+ {props.outline.map((box) => (+ <div+ key={`${box.kind}:${box.x}:${box.y}:${box.width}:${box.height}`}+ className={cn("absolute", OUTLINE_BOX_CLASS[box.kind])}+ style={outlineBoxStyle(box)}+ />+ ))}+ </div>+ );+ }+ const sections = Math.ceil(props.height / SKELETON_SECTION_HEIGHT);+ return (+ <div+ role="status"+ aria-label={`Loading ${props.title}`}+ className="pointer-events-none absolute inset-0 flex flex-col gap-6 overflow-hidden pt-1"+ >+ {Array.from({ length: sections }, (_, index) => (+ <div key={index} className="flex shrink-0 flex-col gap-2">+ <Skeleton className="h-4 w-2/5" />+ <Skeleton className="h-3 w-3/5" />+ <Skeleton shape="card" className="mt-2 h-40 w-full" />+ </div>+ ))}+ </div>+ );+}diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsxindex a2fbaa0fb92..944050dd2aa 100644--- a/apps/web/src/components/files/BrowserDocumentFrame.tsx+++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx@@ -124,6 +124,8 @@ export function HtmlRenderDocument(props: {readonly threadRef?: ScopedThreadRef | undefined;/** Receives the page's content height whenever it changes, so an inline frame can fit it. */readonly onContentHeight?: (height: number) => void;+ /** Called when the page has loaded. */+ readonly onLoad?: () => void;}) {const theme = useHtmlRenderTheme();const frameRef = useRef<HTMLIFrameElement>(null);@@ -292,6 +294,7 @@ export function HtmlRenderDocument(props: {// Covers a theme change that landed while the page was loading.postTheme();postShortcuts();+ props.onLoad?.();}}// A frame whose color scheme differs from its document's paints an opaque// canvas, so the blank document a frame starts with would flash white indiff --git a/packages/shared/src/htmlRender.test.ts b/packages/shared/src/htmlRender.test.tsindex 21ff82e1b02..3b88152434e 100644--- a/packages/shared/src/htmlRender.test.ts+++ b/packages/shared/src/htmlRender.test.ts@@ -1,8 +1,10 @@import { describe, expect, it } from "vite-plus/test";import {+ encodeHtmlRenderOutline,HTML_RENDER_MAX_HEIGHT,htmlRenderFrameHeight,+ htmlRenderOutlineBoxes,htmlRenderReferencesEqual,htmlRenderTheme,htmlRenderThemeFragment,@@ -266,3 +268,49 @@ describe("htmlRenderFrameHeight", () => {expect(htmlRenderReferencesEqual(measured, { ...copy, heights: [[390, 1290]] })).toBe(false);});});++describe("htmlRenderOutlineBoxes", () => {+ const outline = encodeHtmlRenderOutline([+ { kind: "text", x: 0, y: 0, width: 300, height: 40, lines: 2 },+ { kind: "media", x: 0, y: 48, width: 728, height: 300, lines: 1 },+ { kind: "media", x: 2, y: 2, width: 0, height: 10, lines: 1 },+ ]);+ const outlined = readHtmlRenderReference({+ ...reference,+ heights: [+ [364, 1600],+ [728, 800],+ ],+ outline,+ })!;++ it("round-trips through a tool result and stretches to the client's width and height", () => {+ // The empty box is dropped when encoded.+ expect(outline).toBe("t0,0,75,10,2;m0,12,182,75,1");+ expect(htmlRenderOutlineBoxes(outlined, 728)).toEqual([+ { kind: "text", x: 0, y: 0, width: 300, height: 40, lines: 2 },+ { kind: "media", x: 0, y: 48, width: 728, height: 300, lines: 1 },+ ]);+ expect(htmlRenderOutlineBoxes(outlined, 364)[1]).toEqual({+ kind: "media",+ x: 0,+ y: 96,+ width: 364,+ height: 600,+ lines: 1,+ });+ });++ it("drops a malformed or unmeasured outline", () => {+ expect(readHtmlRenderReference({ ...outlined, outline: "x1,2" })?.outline).toBeUndefined();+ expect(+ readHtmlRenderReference({ ...outlined, outline: "t0,0,10,10,0" })?.outline,+ ).toBeUndefined();+ expect(+ readHtmlRenderReference({ ...outlined, outline: "m0,0,0,10,1" })?.outline,+ ).toBeUndefined();+ expect(readHtmlRenderReference({ ...reference, outline })?.outline).toBeUndefined();+ expect(htmlRenderOutlineBoxes(reference, 728)).toEqual([]);+ expect(htmlRenderReferencesEqual(outlined, { ...outlined, outline: "m0,0,1,1,1" })).toBe(false);+ });+});diff --git a/packages/shared/src/htmlRender.ts b/packages/shared/src/htmlRender.tsindex 5b4019830f6..befe63a5224 100644--- a/packages/shared/src/htmlRender.ts+++ b/packages/shared/src/htmlRender.ts@@ -30,6 +30,12 @@ export interface HtmlRenderReference {* width. Absent when the preview browser was not installed yet.*/readonly heights?: ReadonlyArray<readonly [width: number, height: number]>;+ /**+ * The page's main blocks at the column width, measured with `heights`, so a+ * client can draw its loading skeleton in the page's shape. See+ * `encodeHtmlRenderOutline`.+ */+ readonly outline?: string;}/** Frame widths the server measures a page at, from phones to the wide chat setting. */@@ -65,7 +71,7 @@ function readMeasuredHeights(value: unknown) {export function readHtmlRenderReference(value: unknown): HtmlRenderReference | undefined {if (typeof value !== "object" || value === null) return undefined;- const { attachmentId, title, height, heights } = value as Record<string, unknown>;+ const { attachmentId, title, height, heights, outline } = value as Record<string, unknown>;if (typeof attachmentId !== "string" ||attachmentId.length === 0 ||@@ -82,6 +88,9 @@ export function readHtmlRenderReference(value: unknown): HtmlRenderReference | utitle: title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",height: clampHtmlRenderHeight(height),...(measured === undefined ? {} : { heights: measured }),+ ...(measured !== undefined && typeof outline === "string" && OUTLINE_PATTERN.test(outline)+ ? { outline }+ : {}),};}@@ -91,6 +100,7 @@ export function htmlRenderReferencesEqual(left: HtmlRenderReference, right: Htmlleft.attachmentId === right.attachmentId &&left.title === right.title &&left.height === right.height &&+ left.outline === right.outline &&(left.heights ?? []).length === (right.heights ?? []).length &&(left.heights ?? []).every(([width, height], index) =>@@ -132,6 +142,76 @@ export function htmlRenderFrameHeight(return clampHtmlRenderHeight(Math.min(cap, contentHeight ?? measuredHeight(heights, width)));}+/**+ * One block of a page's outline: `text` with its line count, a `media` element+ * or solid shape, or a `table` with its row count.+ */+export interface HtmlRenderOutlineBox {+ readonly kind: "text" | "media" | "table";+ readonly x: number;+ readonly y: number;+ readonly width: number;+ readonly height: number;+ readonly lines: number;+}++const OUTLINE_KINDS = { t: "text", m: "media", g: "table" } as const;+const OUTLINE_LETTERS = { text: "t", media: "m", table: "g" } as const;+// Coordinates travel in 4px units, which keeps the tool result an agent reads short.+const OUTLINE_UNIT = 4;+export const HTML_RENDER_OUTLINE_MAX_BOXES = 48;+// Sizes and line counts are never zero, so a client never divides by one.+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}";+const OUTLINE_PATTERN = new RegExp(+ `^${OUTLINE_BOX}(?:;${OUTLINE_BOX}){0,${HTML_RENDER_OUTLINE_MAX_BOXES - 1}}$`,+);++/** Packs measured boxes, in CSS pixels at the column width, into an outline string. */+export function encodeHtmlRenderOutline(+ boxes: ReadonlyArray<HtmlRenderOutlineBox>,+): string | undefined {+ const unit = (value: number) => Math.min(9_999, Math.max(0, Math.round(value / OUTLINE_UNIT)));+ const encoded = boxes+ .slice(0, HTML_RENDER_OUTLINE_MAX_BOXES)+ .flatMap((box) =>+ unit(box.width) > 0 && unit(box.height) > 0+ ? [+ `${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)))}`,+ ]+ : [],+ )+ .join(";");+ return encoded === "" ? undefined : encoded;+}++/**+ * The outline's boxes in CSS pixels for a frame `width` wide, stretched to the+ * page's measured height there. Empty without an outline.+ */+export function htmlRenderOutlineBoxes(+ reference: HtmlRenderReference,+ width: number,+): ReadonlyArray<HtmlRenderOutlineBox> {+ const heights = reference.heights;+ if (reference.outline === undefined || heights === undefined || heights.length === 0) return [];+ const scaleX = width / HTML_RENDER_COLUMN_WIDTH;+ const scaleY = measuredHeight(heights, width) / measuredHeight(heights, HTML_RENDER_COLUMN_WIDTH);+ return reference.outline.split(";").map((entry) => {+ const [x = 0, y = 0, boxWidth = 0, boxHeight = 0, lines = 1] = entry+ .slice(1)+ .split(",")+ .map(Number);+ return {+ kind: OUTLINE_KINDS[entry[0] as keyof typeof OUTLINE_KINDS],+ x: x * OUTLINE_UNIT * scaleX,+ y: y * OUTLINE_UNIT * scaleY,+ width: boxWidth * OUTLINE_UNIT * scaleX,+ height: boxHeight * OUTLINE_UNIT * scaleY,+ lines,+ };+ });+}+/** A readable download name: the title without characters file systems reject. */export function htmlRenderFileName(title: string) {const name = title