@devries-cameron20 / t3code-1 / commits / 5b91a5a00e
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): HTML file previews no longer flash white after agent commands (#37950)

Julius Marminge committed Nov 16, 2026 at 22:41 UTC 5b91a5a00e05f9eeaf7ea06bee68a858a06df34e
7 files changed +319 -16
apps/server/src/assets/AssetAccess.test.ts
+3
@@ -1059,10 +1059,12 @@ describe("AssetAccess", () => {
1059 expect(yield* resolveAsset(token, "report.html")).toEqual({
1060 kind: "file",
1061 path: canonicalHtmlPath,
1062 + renderIntent: "file-preview",
1063 });
1064 expect(yield* resolveAsset(token, "report.css")).toEqual({
1065 kind: "file",
1066 path: canonicalCssPath,
1067 + renderIntent: "file-preview",
1068 });
1069 yield* fileSystem.makeDirectory(path.join(root, "clips"));
1070 for (const mediaName of ["clips/clip.mp4", "clips/clip.webm", "clips/clip.mp3"]) {
@@ -1087,6 +1089,7 @@ describe("AssetAccess", () => {
1089 expect(yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), fontName)).toEqual({
1090 kind: "file",
1091 path: canonicalFontPath,
1092 + renderIntent: "file-preview",
1093 });
1094 }
1095 }
apps/server/src/assets/AssetAccess.ts
+4 -2
@@ -214,7 +214,7 @@ export type ResolvedAsset =
214 readonly fileName?: string;
215 readonly mimeType?: string;
216 readonly file?: OpenMediaFile;
217 - readonly renderIntent?: "mcp-app";
217 + readonly renderIntent?: "mcp-app" | "file-preview";
218 }
219 | {
220 readonly kind: "bytes";
@@ -1091,5 +1091,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
1091 relativePath: joinedRelativePath,
1092 previewDependency: true,
1093 });
1094 - return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
1094 + return workspaceFile
1095 + ? ({ kind: "file", path: workspaceFile, renderIntent: "file-preview" } satisfies ResolvedAsset)
1096 + : null;
1097 });
apps/server/src/http.test.ts
+34
@@ -26,6 +26,7 @@ import {
26 MCP_APP_MAX_HTML_BYTES,
27 } from "@t3tools/shared/mcpApp";
28 import { ORCHESTRATION_PROTOCOL_HEADER } from "@t3tools/contracts";
29 +import { FILE_PREVIEW_SCROLL_SCRIPT } from "@t3tools/shared/htmlRender";
30
31 import * as ServerConfig from "./config.ts";
32
@@ -96,6 +97,39 @@ describe("MCP app asset responses", () => {
97 );
98 });
99
100 +describe("workspace page preview responses", () => {
101 + it.effect("append the scroll script only to inline HTML previews", () =>
102 + Effect.gen(function* () {
103 + const fs = yield* FileSystem.FileSystem;
104 + const path = yield* Path.Path;
105 + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-file-preview-" });
106 + const page = path.join(directory, "report.html");
107 + const style = path.join(directory, "report.css");
108 + const html = "<!doctype html><html><body>☃</body></html>";
109 + yield* fs.writeFileString(page, html);
110 + yield* fs.writeFileString(style, "body{}");
111 + const read = (asset: Parameters<typeof assetFileResponse>[0]) =>
112 + assetFileResponse(asset).pipe(
113 + Effect.flatMap((response) =>
114 + Effect.promise(() => HttpServerResponse.toWeb(response).text()),
115 + ),
116 + );
117 + const response = HttpServerResponse.toWeb(
118 + yield* assetFileResponse({ path: page, renderIntent: "file-preview" }, "bytes=0-1"),
119 + );
120 + const expected = html + FILE_PREVIEW_SCROLL_SCRIPT;
121 + expect(response.status).toBe(200);
122 + expect(response.headers.get("content-length")).toBe(
123 + String(new TextEncoder().encode(expected).byteLength),
124 + );
125 + expect(yield* Effect.promise(() => response.text())).toBe(expected);
126 + expect(yield* read({ path: page, renderIntent: "file-preview", download: true })).toBe(html);
127 + expect(yield* read({ path: page })).toBe(html);
128 + expect(yield* read({ path: style, renderIntent: "file-preview" })).toBe("body{}");
129 + }).pipe(Effect.provide(layerFileResponse)),
130 + );
131 +});
132 +
133 describe("browser API CORS", () => {
134 it("accepts protocol negotiation with authenticated browser headers", async () => {
135 const layerRoute = Layer.effectDiscard(
apps/server/src/http.ts
+20 -1
@@ -6,6 +6,7 @@ import {
6 } from "@t3tools/contracts";
7 import { isDevProxiedPath } from "@t3tools/shared/devProxy";
8 import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp";
9 +import { FILE_PREVIEW_SCROLL_SCRIPT } from "@t3tools/shared/htmlRender";
10 import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
11 import * as ByteSize from "effect/ByteSize";
12 import * as Effect from "effect/Effect";
@@ -166,7 +167,7 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* (
167 readonly fileName?: string;
168 readonly mimeType?: string;
169 readonly file?: OpenMediaFile;
169 - readonly renderIntent?: "mcp-app";
170 + readonly renderIntent?: "mcp-app" | "file-preview";
171 },
172 rangeHeader?: string,
173 ifRangeHeader?: string,
@@ -193,6 +194,24 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* (
194 ? HttpServerResponse.empty({ status: 200, headers })
195 : HttpServerResponse.uint8Array(body, { headers });
196 }
197 + if (
198 + asset.renderIntent === "file-preview" &&
199 + !asset.download &&
200 + headers["Content-Type"] === "text/html; charset=utf-8"
201 + ) {
202 + const bytes = yield* readMcpAppHtml(asset.path);
203 + // A page too large to buffer is served as is, without scroll restoration.
204 + if (bytes !== null) {
205 + const script = new TextEncoder().encode(FILE_PREVIEW_SCROLL_SCRIPT);
206 + const body = new Uint8Array(bytes.byteLength + script.byteLength);
207 + body.set(bytes);
208 + body.set(script, bytes.byteLength);
209 + headers["Content-Length"] = String(body.byteLength);
210 + return method === "HEAD"
211 + ? HttpServerResponse.empty({ status: 200, headers })
212 + : HttpServerResponse.uint8Array(body, { headers });
213 + }
214 + }
215 const mediaFile = asset.file;
216 const mediaInfo = mediaFile ? yield* statMediaFile(asset.path, mediaFile) : undefined;
217 const isMedia = /^(?:audio|video)\//i.test(headers["Content-Type"] ?? "");
apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx
+101 -2
@@ -1,11 +1,15 @@
1 -import { injectHtmlRenderBootstrap } from "@t3tools/shared/htmlRender";
1 +import {
2 + FILE_PREVIEW_SCROLL_SCRIPT,
3 + injectHtmlRenderBootstrap,
4 + readFilePreviewScroll,
5 +} from "@t3tools/shared/htmlRender";
6 import { describe, expect, it, vi } from "vite-plus/test";
7 import { page } from "vite-plus/test/browser";
8
9 import "~/index.css";
10 import { render } from "../../../test/render";
11
8 -import { HtmlRenderDocument } from "./BrowserDocumentFrame";
12 +import { BrowserDocumentFrame, HtmlRenderDocument } from "./BrowserDocumentFrame";
13
14 const sizeChanged = (height: number) => ({
15 jsonrpc: "2.0",
@@ -219,3 +223,98 @@ it("keeps the first and last selected card rings inside the fitted renderer fram
223 expect(bounds.scrollWidth).toBeLessThanOrEqual(bounds.viewportWidth);
224 }
225 });
226 +
227 +describe("BrowserDocumentFrame", () => {
228 + it("keeps a page on screen until its next revision has loaded", async () => {
229 + using pages = (() => {
230 + const urls = ["first", "second", "third"].map((name) =>
231 + URL.createObjectURL(new Blob([`<p>${name}</p>`], { type: "text/html" })),
232 + );
233 + return { urls, [Symbol.dispose]: () => urls.forEach((url) => URL.revokeObjectURL(url)) };
234 + })();
235 + const [first, second, third] = pages.urls as [string, string, string];
236 + const frame = (revision: string, src: string) => (
237 + <div className="flex h-75 w-100 flex-col">
238 + <BrowserDocumentFrame
239 + src={src}
240 + title="Report"
241 + pdf={false}
242 + documentKey={`report:${revision}`}
243 + documentId="report"
244 + />
245 + </div>
246 + );
247 + await using screen = await render(frame("1", first));
248 + const srcs = () => Array.from(screen.container.querySelectorAll("iframe"), (f) => f.src);
249 + const onScreen = () => {
250 + const box = screen.container.getBoundingClientRect();
251 + const hit = document.elementFromPoint(box.left + box.width / 2, box.top + 10);
252 + return hit instanceof HTMLIFrameElement ? hit.src : null;
253 + };
254 + await vi.waitFor(() => expect(onScreen()).toBe(first));
255 +
256 + // The incoming frame cannot have loaded when it is inserted, so the current page must cover it.
257 + const atInsertion = new Promise<string | null>((resolve) => {
258 + const observer = new MutationObserver(() => {
259 + if (!srcs().includes(second)) return;
260 + observer.disconnect();
261 + resolve(onScreen());
262 + });
263 + observer.observe(screen.container, { childList: true, subtree: true });
264 + });
265 + await screen.rerender(frame("2", second));
266 + expect(await atInsertion).toBe(first);
267 + await vi.waitFor(() => expect(srcs()).toEqual([second]));
268 + expect(onScreen()).toBe(second);
269 +
270 + await screen.rerender(frame("3", third));
271 + await screen.rerender(frame("2", second));
272 + expect(srcs(), "returning to the shown revision kept the pending frame").toEqual([second]);
273 + await screen.rerender(frame("3", third));
274 + await vi.waitFor(() => expect(onScreen()).toBe(third));
275 + });
276 +
277 + it("opens the next revision where the reader left the page", async () => {
278 + // The first page scrolls itself, as a reader would; the second is served without scrolling.
279 + const tall = '<div style="height:5000px">report</div>';
280 + using pages = (() => {
281 + const urls = [
282 + `${tall}<script>addEventListener("load",()=>scrollTo(0,1200))</script>`,
283 + tall,
284 + ].map((body) =>
285 + URL.createObjectURL(new Blob([body + FILE_PREVIEW_SCROLL_SCRIPT], { type: "text/html" })),
286 + );
287 + return { urls, [Symbol.dispose]: () => urls.forEach((url) => URL.revokeObjectURL(url)) };
288 + })();
289 + const [first, second] = pages.urls as [string, string];
290 + const reports: Array<{ source: MessageEventSource | null; y: number }> = [];
291 + const onMessage = (event: MessageEvent) => {
292 + const scroll = readFilePreviewScroll(event.data);
293 + if (scroll !== undefined) reports.push({ source: event.source, y: scroll.y });
294 + };
295 + window.addEventListener("message", onMessage);
296 + using _listener = { [Symbol.dispose]: () => window.removeEventListener("message", onMessage) };
297 + const frame = (revision: string, src: string) => (
298 + <div className="flex h-75 w-100 flex-col">
299 + <BrowserDocumentFrame
300 + src={src}
301 + title="Report"
302 + pdf={false}
303 + documentKey={`report:${revision}`}
304 + documentId="report"
305 + />
306 + </div>
307 + );
308 + await using screen = await render(frame("1", first));
309 + const iframes = () => Array.from(screen.container.querySelectorAll("iframe"));
310 + await vi.waitFor(() => expect(reports.map((report) => report.y)).toContain(1200));
311 +
312 + await screen.rerender(frame("2", second));
313 + await vi.waitFor(() => expect(iframes().map((element) => element.src)).toEqual([second]));
314 + const shown = iframes()[0]!.contentWindow;
315 + expect(
316 + reports.filter((report) => report.source === shown).map((report) => report.y),
317 + "the next revision was uncovered before it took the reader's position",
318 + ).toContain(1200);
319 + });
320 +});
apps/web/src/components/files/BrowserDocumentFrame.tsx
+113 -11
@@ -7,6 +7,10 @@ import {
7 THREAD_JUMP_KEYBINDING_COMMANDS,
8 } from "@t3tools/contracts";
9 import {
10 + type FilePreviewScroll,
11 + filePreviewRestoreScrollMessage,
12 + isFilePreviewScrollRestored,
13 + readFilePreviewScroll,
14 type HtmlRenderShortcut,
15 htmlRenderShortcutsMessage,
16 htmlRenderThemeFragment,
@@ -157,21 +161,119 @@ export function BrowserDocumentFrame(props: {
161 className="min-h-0 flex-1"
162 />
163 ) : (
160 - <FileDocument key={key} src={props.src} title={props.title} />
164 + <FileDocument
165 + key={props.documentId ?? key}
166 + documentKey={key}
167 + src={props.src}
168 + title={props.title}
169 + />
170 );
171 }
172
164 -// URL renewals must not discard form input or scroll; a new key mounts a fresh document.
165 -function FileDocument(props: { readonly src: string; readonly title: string }) {
166 - const [src] = useState(props.src);
173 +interface FileDocumentRevision {
174 + readonly key: string;
175 + readonly src: string;
176 +}
177 +
178 +interface FileDocumentFrames {
179 + readonly shown: FileDocumentRevision;
180 + readonly next: FileDocumentRevision | null;
181 +}
182 +
183 +// Identity, not key, so a late load from a replaced frame cannot uncover a newer unloaded one.
184 +const showRevision =
185 + (next: FileDocumentRevision) =>
186 + (current: FileDocumentFrames): FileDocumentFrames =>
187 + current.next === next ? { shown: next, next: null } : current;
188 +
189 +// A page whose load never fires (a stalled subresource) must not pin the previous revision.
190 +const FILE_DOCUMENT_SWAP_TIMEOUT_MS = 5_000;
191 +
192 +// URL renewals keep a revision's first URL, so they do not discard form input or scroll. A new
193 +// revision loads beneath the page on screen, takes its scroll position and replaces it once
194 +// painted, so no blank frame shows and the reader keeps their place.
195 +function FileDocument(props: {
196 + readonly documentKey: string;
197 + readonly src: string;
198 + readonly title: string;
199 +}) {
200 + const [frames, setFrames] = useState<FileDocumentFrames>(() => ({
201 + shown: { key: props.documentKey, src: props.src },
202 + next: null,
203 + }));
204 + if ((frames.next ?? frames.shown).key !== props.documentKey) {
205 + setFrames({
206 + shown: frames.shown,
207 + next:
208 + frames.shown.key === props.documentKey ? null : { key: props.documentKey, src: props.src },
209 + });
210 + }
211 + const { next } = frames;
212 + const shownFrame = useRef<HTMLIFrameElement>(null);
213 + const nextFrame = useRef<HTMLIFrameElement>(null);
214 + // The page reports its scroll position (see FILE_PREVIEW_SCROLL_SCRIPT); the next revision
215 + // scrolls there before it is uncovered.
216 + const scroll = useRef<FilePreviewScroll | null>(null);
217 + // Two frames let the browser paint the incoming page before it is uncovered.
218 + const reveal = (revision: FileDocumentRevision) =>
219 + requestAnimationFrame(() => requestAnimationFrame(() => setFrames(showRevision(revision))));
220 + const onFrameMessage = useEffectEvent((event: MessageEvent) => {
221 + const position = readFilePreviewScroll(event.data);
222 + if (position !== undefined) {
223 + if (event.source === shownFrame.current?.contentWindow) scroll.current = position;
224 + } else if (
225 + next !== null &&
226 + event.source === nextFrame.current?.contentWindow &&
227 + isFilePreviewScrollRestored(event.data)
228 + ) {
229 + reveal(next);
230 + }
231 + });
232 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- listens for the frames' scroll reports
233 + useEffect(() => {
234 + const onMessage = (event: MessageEvent) => onFrameMessage(event);
235 + window.addEventListener("message", onMessage);
236 + return () => window.removeEventListener("message", onMessage);
237 + }, []);
238 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- swaps in a revision whose load event never arrives
239 + useEffect(() => {
240 + if (next === null) return;
241 + const timer = setTimeout(() => setFrames(showRevision(next)), FILE_DOCUMENT_SWAP_TIMEOUT_MS);
242 + return () => clearTimeout(timer);
243 + }, [next]);
244 + // The shown frame stays last so it paints on top and is never moved, which would reload it.
245 return (
168 - <iframe
169 - src={src}
170 - title={props.title}
171 - className="min-h-0 flex-1 border-0"
172 - style={{ backgroundColor: "Canvas" }}
173 - sandbox="allow-scripts allow-forms allow-popups allow-downloads"
174 - />
246 + <div className="relative min-h-0 flex-1">
247 + {[next, frames.shown].map((revision) =>
248 + revision === null ? null : (
249 + <iframe
250 + key={revision.key}
251 + ref={revision === next ? nextFrame : shownFrame}
252 + src={revision.src}
253 + title={props.title}
254 + className="absolute inset-0 size-full border-0"
255 + style={{ backgroundColor: "Canvas" }}
256 + sandbox="allow-scripts allow-forms allow-popups allow-downloads"
257 + inert={revision === next}
258 + aria-hidden={revision === next ? true : undefined}
259 + onLoad={
260 + revision === next
261 + ? (event) => {
262 + if (scroll.current === null) {
263 + reveal(revision);
264 + return;
265 + }
266 + event.currentTarget.contentWindow?.postMessage(
267 + filePreviewRestoreScrollMessage(scroll.current),
268 + "*",
269 + );
270 + }
271 + : undefined
272 + }
273 + />
274 + ),
275 + )}
276 + </div>
277 );
278 }
279
packages/shared/src/htmlRender.ts
+44
@@ -466,3 +466,47 @@ export function injectHtmlRenderBootstrap(html: string): string {
466 }
467 return `<!doctype html><head>${markup}</head>${html}`;
468 }
469 +
470 +const FILE_PREVIEW_SCROLL_METHOD = "t3/notifications/file-preview-scroll";
471 +const FILE_PREVIEW_RESTORE_SCROLL_METHOD = "t3/file-preview/restore-scroll";
472 +const FILE_PREVIEW_SCROLL_RESTORED_METHOD = "t3/notifications/file-preview-scroll-restored";
473 +
474 +export interface FilePreviewScroll {
475 + readonly x: number;
476 + readonly y: number;
477 +}
478 +
479 +/**
480 + * Appended after a served workspace page so it lands at the end of the body without changing
481 + * the doctype. A preview frame is an opaque origin, so only the page can report and restore its
482 + * scroll position across the reload that follows each workspace change.
483 + */
484 +export const FILE_PREVIEW_SCROLL_SCRIPT = `<script>(function(){var p=window.parent,f=0;if(p===window)return;addEventListener("scroll",function(){if(!f)f=requestAnimationFrame(function(){f=0;p.postMessage({jsonrpc:"2.0",method:${JSON.stringify(FILE_PREVIEW_SCROLL_METHOD)},params:{x:scrollX,y:scrollY}},"*");});},{passive:true});addEventListener("message",function(e){var d=e.data,q=d&&d.params;if(e.source!==p||!d||d.jsonrpc!=="2.0"||d.method!==${JSON.stringify(FILE_PREVIEW_RESTORE_SCROLL_METHOD)}||!q||typeof q.x!=="number"||typeof q.y!=="number")return;scrollTo({left:q.x,top:q.y,behavior:"instant"});p.postMessage({jsonrpc:"2.0",method:${JSON.stringify(FILE_PREVIEW_SCROLL_RESTORED_METHOD)}},"*");});})();</script>`;
485 +
486 +export function readFilePreviewScroll(data: unknown): FilePreviewScroll | undefined {
487 + if (typeof data !== "object" || data === null) return undefined;
488 + const { jsonrpc, method, params } = data as Record<string, unknown>;
489 + if (jsonrpc !== "2.0" || method !== FILE_PREVIEW_SCROLL_METHOD) return undefined;
490 + if (typeof params !== "object" || params === null) return undefined;
491 + const { x, y } = params as Record<string, unknown>;
492 + return typeof x === "number" && Number.isFinite(x) && typeof y === "number" && Number.isFinite(y)
493 + ? { x, y }
494 + : undefined;
495 +}
496 +
497 +export function isFilePreviewScrollRestored(data: unknown): boolean {
498 + return (
499 + typeof data === "object" &&
500 + data !== null &&
501 + (data as Record<string, unknown>).jsonrpc === "2.0" &&
502 + (data as Record<string, unknown>).method === FILE_PREVIEW_SCROLL_RESTORED_METHOD
503 + );
504 +}
505 +
506 +export function filePreviewRestoreScrollMessage(scroll: FilePreviewScroll) {
507 + return {
508 + jsonrpc: "2.0",
509 + method: FILE_PREVIEW_RESTORE_SCROLL_METHOD,
510 + params: { x: scroll.x, y: scroll.y },
511 + } as const;
512 +}