Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - plain local servers stand in for LAN services.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, describe, expect, it } from "@effect/vitest";
4import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
5import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Base64 from "effect/encoding/Base64";
12import * as Fiber from "effect/Fiber";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Path from "effect/Path";
17import * as Stream from "effect/Stream";
18import * as NodeDgram from "node:dgram";
19import * as NodeHttp from "node:http";
20import * as NodeURL from "node:url";
21
22import { resolveAttachmentPathById } from "../attachmentStore.ts";
23import * as ServerConfig from "../config.ts";
24import * as HtmlRender from "./HtmlRender.ts";
25import * as ThreadViewers from "../orchestration-v2/ThreadViewers.ts";
26import { HtmlRenderBrowserError } from "./headlessChrome.ts";
27import * as PreviewBrowser from "../preview/PreviewBrowser.ts";
28import * as PreviewBrowserHost from "../preview/PreviewBrowserHost.ts";
29
30const TEST_BROWSER_ENV = "T3CODE_TEST_HEADLESS_SHELL";
31
32const layerHtmlRender = (
33 executable?: string,
34 installed: Effect.Effect<Option.Option<string>> = Effect.succeed(
35 Option.fromUndefinedOr(executable),
36 ),
37) =>
38 HtmlRender.layer.pipe(
39 Layer.provideMerge(ThreadViewers.layer),
40 Layer.provide(
41 Layer.succeed(
42 PreviewBrowser.PreviewBrowser,
43 PreviewBrowser.PreviewBrowser.of({
44 executable:
45 executable === undefined
46 ? Effect.die("This test has no preview browser.")
47 : Effect.succeed(executable),
48 installed,
49 }),
50 ),
51 ),
52 Layer.provideMerge(McpProviderSessions.layer),
53 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-html-render-" })),
54 Layer.provideMerge(NodeServices.layer),
55 );
56const layerTest = layerHtmlRender();
57
58const PNG_BYTES = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
59
60describe("HtmlRender", () => {
61 it.effect("inlines local images by absolute path and leaves URLs and relative paths alone", () =>
62 Effect.gen(function* () {
63 const fileSystem = yield* FileSystem.FileSystem;
64 const path = yield* Path.Path;
65 const htmlRender = yield* HtmlRender.HtmlRender;
66 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
67 const png = path.join(directory, "shot.png");
68 const ampersandPng = path.join(directory, "a&b.png");
69 const copyPng = path.join(directory, "a©.png");
70 const literalEntityPng = path.join(directory, "a&b.png");
71 const svg = path.join(directory, "logo.svg");
72 const encodedPng = path.join(directory, "sh%6Ft.png");
73 const literalPercent = path.join(directory, "100%25.png");
74 const ampersandPngBytes = new Uint8Array([...PNG_BYTES, 0x01]);
75 const commented = `<!-- 📸\r\n<img src="/t3-missing/shot.png"> -->`;
76 const quotedInText = `<p>Saved as "${png}"; delete '/t3-missing/old.png' first.</p>`;
77 yield* fileSystem.writeFile(png, PNG_BYTES);
78 yield* fileSystem.writeFile(ampersandPng, ampersandPngBytes);
79 yield* fileSystem.writeFile(copyPng, PNG_BYTES);
80 yield* fileSystem.writeFile(literalEntityPng, PNG_BYTES);
81 yield* fileSystem.writeFile(literalPercent, PNG_BYTES);
82 yield* fileSystem.writeFileString(svg, "<svg/>");
83 const kept = [
84 "https://example.com/a.png",
85 "//cdn.example.com/b.png",
86 "./c.png",
87 "data:image/png;base64,AAAA",
88 ];
89
90 const prepared = yield* htmlRender.prepare(
91 [
92 "<!doctype html><html><head><title>Shots</title></head><body>",
93 `${commented}<img src="${path.join(directory, "shot.png")}"><img src="${encodedPng}"><img src="${svg}#svgView(viewBox(0,0,64,64))"><div style="background:url(${svg})"></div><div style="background:url(${svg}#mark)"></div>`,
94 `<img src="${literalEntityPng}"><div style="background:url(${literalEntityPng})"></div>`,
95 `<img alt="literal ampersand" src="${path.join(directory, "a&copy.png")}">`,
96 `<style>.shot{background:url(${literalEntityPng})}</style>`,
97 `${quotedInText}<style data-base=/assets/>.hero{background:url(${png})}</style>`,
98 `<textarea style="background:url(${png})">Notes</textarea>`,
99 `<svg xmlns="http://www.w3.org/2000/svg"><title/></svg><img alt="after svg" src="${png}">`,
100 `<!--><img src="${png}"><!-- note --!><img src="${png}">`,
101 `<script>const marker = '<!--'; const shots = ['${png}', \`${svg}\`, '${literalPercent}', '${literalEntityPng}'];</script>`,
102 ...kept.map((src) => `<img src="${src}">`),
103 "</body></html>",
104 ].join(""),
105 );
106
107 const pngUri = `data:image/png;base64,${Base64.encode(PNG_BYTES)}`;
108 const ampersandPngUri = `data:image/png;base64,${Base64.encode(ampersandPngBytes)}`;
109 const svgUri = `data:image/svg+xml;base64,${Base64.encode("<svg/>")}`;
110 expect(prepared).toContain(`${commented}<img src="${pngUri}"><img src="${pngUri}">`);
111 expect(prepared).toContain(`<img src="${ampersandPngUri}">`);
112 expect(prepared).toContain(`<img alt="literal ampersand" src="${pngUri}">`);
113 expect(prepared).toContain(`<img src="${svgUri}#svgView(viewBox(0,0,64,64))">`);
114 expect(prepared).toContain(`<!--><img src="${pngUri}"><!-- note --!><img src="${pngUri}">`);
115 expect(prepared).toContain(`url(${svgUri})`);
116 expect(prepared).toContain(`url(${svgUri}#mark)`);
117 expect(prepared).toContain(`<div style="background:url(${ampersandPngUri})"></div>`);
118 expect(prepared).toContain(`<style>.shot{background:url(${pngUri})}</style>`);
119 expect(prepared).toContain(
120 `${quotedInText}<style data-base=/assets/>.hero{background:url(${pngUri})}</style>`,
121 );
122 expect(prepared).toContain(`['${pngUri}', \`${svgUri}\`, '${pngUri}', '${pngUri}']`);
123 expect(prepared).toContain(`<textarea style="background:url(${pngUri})">Notes</textarea>`);
124 expect(prepared).toContain(`<img alt="after svg" src="${pngUri}">`);
125 expect(prepared.replace(quotedInText, "")).not.toContain(directory);
126 for (const src of kept) expect(prepared).toContain(`<img src="${src}">`);
127 expect(prepared.indexOf("<head>")).toBeLessThan(prepared.indexOf('<style id="t3-theme">'));
128 expect(prepared.indexOf('<style id="t3-theme">')).toBeLessThan(prepared.indexOf("<title>"));
129 }).pipe(Effect.provide(layerTest)),
130 );
131
132 it.effect("rejects viewport height units, which make the fitted frame grow without end", () =>
133 Effect.gen(function* () {
134 const htmlRender = yield* HtmlRender.HtmlRender;
135 for (const page of [
136 "<style>main{min-height:100vh}</style>",
137 "<style media=screen>main{height: calc(100dvh - 2rem)}",
138 "<div style='top:.5svh'></div>",
139 "<div style=height:100vh></div>",
140 "<style>main{min-height:100vmax}</style>",
141 "<div style='height:calc(100dvmax - 1rem)'></div>",
142 "<style>main{block-size:100vb}</style>",
143 "<div style='margin-top:-50vh'></div>",
144 "<style-guide style='height:100vh'><p>hi</p></style-guide>",
145 "<script>box.innerHTML = \"<div style='height:100vh'></div>\";</script>",
146 '<script type="text/plain" style="display:block;height:100vh">example</script>',
147 `<div title=it's style="height:100vh">hi</div>`,
148 '<div data-x=foo="bar style="height:100vh">hi</div>',
149 "<main style='min-height:+100vh'></main>",
150 "<main style='min-height:1e2vh'></main>",
151 "<style>main{min-height:1e+2vh}</style>",
152 '<style>p::after{content:"\\\\"}main{height:100vh}</style>',
153 "<style>/* don't */main{height:100vh}/* it's */</style>",
154 "<style>main{background:url(https://example.com/*);height:100vh}</style>",
155 "<style>.x\\'y{height:100vh;--label:'ok'}</style>",
156 `<main style="--a:"'";height:100vh;--b:"'"">x</main>`,
157 `<script>document.write("<style>" + 'main{height:100vh}' + "</style>");</script>`,
158 ]) {
159 const error = yield* htmlRender.prepare(page).pipe(Effect.flip);
160 expect(error).toBeInstanceOf(HtmlRender.HtmlRenderViewportHeightError);
161 }
162 yield* htmlRender.prepare(
163 '<style>main{width:100vw;height:320px}</style><img src="data:image/png;base64,AB1vh+2vh/3vhC">',
164 );
165 yield* htmlRender.prepare(
166 '<style>.h-100vmax,.min-h-100vb,.h\\+100vh{height:200px}</style><main class="h-100vmax">hi</main>',
167 );
168 yield* htmlRender.prepare(
169 "<p>Avoid 100vh here.</p><!-- <div style=\"height:100vh\"></div> --><script>const unit = '100vh';</script>",
170 );
171 yield* htmlRender.prepare(
172 "<!doctype html><html><body><style-guide><p>Avoid 100vh here.</p></style-guide></body></html>",
173 );
174 yield* htmlRender.prepare(
175 "<style-guide title=\"Example style='height:100vh'\">ok</style-guide>",
176 );
177 yield* htmlRender.prepare(
178 "<script>const markup = '<!-- <div style=\"height:100vh\"></div> -->';</script>",
179 );
180 yield* htmlRender.prepare(`<style>${"1".repeat(200_000)}vx</style>`);
181 yield* htmlRender.prepare(`<style>p::after{content:"\\"100vh\\""}</style><p>Unit: </p>`);
182 }).pipe(Effect.provide(layerTest)),
183 );
184
185 it.effect("inlines an SVG behind processing instructions and a doctype subset", () =>
186 Effect.gen(function* () {
187 const fileSystem = yield* FileSystem.FileSystem;
188 const path = yield* Path.Path;
189 const htmlRender = yield* HtmlRender.HtmlRender;
190 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
191 const svg = path.join(directory, "styled.svg");
192 const source = [
193 '<?xml version="1.0"?>',
194 '<?xml-stylesheet href="theme.css"?>',
195 '<!DOCTYPE svg [ <!ENTITY fill "red"> ]>',
196 '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"/>',
197 ].join("\n");
198 yield* fileSystem.writeFileString(svg, source);
199
200 const prepared = yield* htmlRender.prepare(`<img src="${svg}">`);
201
202 expect(prepared).toContain(`data:image/svg+xml;base64,${Base64.encode(source)}`);
203 }).pipe(Effect.provide(layerTest)),
204 );
205
206 it.effect("lists every local image it cannot read", () =>
207 Effect.gen(function* () {
208 const fileSystem = yield* FileSystem.FileSystem;
209 const path = yield* Path.Path;
210 const htmlRender = yield* HtmlRender.HtmlRender;
211 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
212 const folder = path.join(directory, "folder.png");
213 yield* fileSystem.makeDirectory(folder);
214 const missing = path.join(directory, "missing.jpg");
215 const missingSvg = path.join(directory, "missing.svg");
216 const secret = path.join(directory, "secret.png");
217 yield* fileSystem.writeFileString(secret, "API_KEY=abc123");
218 const report = path.join(directory, "report.svg");
219 yield* fileSystem.writeFileString(report, "<!doctype html><body><svg></svg>API_KEY=abc123");
220 const config = path.join(directory, "config.svg");
221 yield* fileSystem.writeFileString(
222 config,
223 '<!DOCTYPE config [<!ENTITY a "a"><!ENTITY b "]><svg/>">]><config>API_KEY=abc123</config>',
224 );
225 const stalling = path.join(directory, "stalling.svg");
226 yield* fileSystem.writeFileString(stalling, `${"<?p?>".repeat(40)}<config><svg/></config>`);
227 const unclosed = path.join(directory, "unclosed.svg");
228 yield* fileSystem.writeFileString(unclosed, '<!DOCTYPE svg [<!ENTITY a "x><svg/>');
229 const upper = path.join(directory, "upper.svg");
230 yield* fileSystem.writeFileString(upper, "<SVG/>API_KEY=abc123");
231 const longer = path.join(directory, "longer.svg");
232 yield* fileSystem.writeFileString(longer, "<svg\u00e9/>API_KEY=abc123");
233
234 const error = yield* htmlRender
235 .prepare(
236 `<img title="<!--" src="${missing}"><img src="${missingSvg}#svgView(viewBox(0,0,64,64))"><img src='${folder}'><img src="C:\\nope\\shot.webp"><img src="${secret}"><img src="${report}"><img src="${config}"><img src="${stalling}"><img src="${unclosed}"><img src="${upper}"><img src="${longer}"><img src="/%2Fattacker/share/shot.png">`,
237 )
238 .pipe(Effect.flip);
239
240 expect(error).toBeInstanceOf(HtmlRender.HtmlRenderImagesNotFoundError);
241 expect(error._tag === "HtmlRenderImagesNotFoundError" && error.paths).toEqual([
242 missing,
243 missingSvg,
244 folder,
245 "C:\\nope\\shot.webp",
246 secret,
247 report,
248 config,
249 stalling,
250 unclosed,
251 upper,
252 longer,
253 "/%2Fattacker/share/shot.png",
254 ]);
255 }).pipe(Effect.provide(layerTest)),
256 );
257
258 it.effect("publishes the prepared page as an html thread attachment", () =>
259 Effect.gen(function* () {
260 const fileSystem = yield* FileSystem.FileSystem;
261 const config = yield* ServerConfig.ServerConfig;
262 const htmlRender = yield* HtmlRender.HtmlRender;
263 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
264 const threadId = ThreadId.make("thread-html-render");
265 const session = {
266 environmentId: EnvironmentId.make("html-render-environment"),
267 threadId,
268 providerSessionId: "first-credential",
269 providerInstanceId: ProviderInstanceId.make("claude"),
270 endpoint: "http://localhost:8311/mcp",
271 authorizationHeader: "Bearer first-token",
272 browserToolsAvailable: false,
273 };
274 yield* mcpSessions.set(session);
275
276 const reference = yield* htmlRender.publish({
277 threadId,
278 html: `<p>Quarterly revenue</p>${" ".repeat(8_000)}`,
279 title: " Revenue ",
280 height: 9_000,
281 });
282
283 expect(reference).toEqual({
284 attachmentId: expect.any(String),
285 title: "Revenue",
286 height: 2_000,
287 });
288 const stored = resolveAttachmentPathById({
289 attachmentsDir: config.attachmentsDir,
290 attachmentId: reference.attachmentId,
291 });
292 expect(stored?.endsWith(".html")).toBe(true);
293 const html = yield* fileSystem.readFileString(stored ?? "");
294 expect(html).toContain('<style id="t3-theme">');
295 expect(html).toContain("<p>Quarterly revenue</p>");
296 // Antigravity reports the call without its result, so the thread's
297 // provider session keeps the page for one call with these arguments.
298 const page = {
299 html: `<p>Quarterly revenue</p>${" ".repeat(8_000)}`,
300 title: " Revenue ",
301 height: 9_000,
302 };
303 expect(
304 yield* mcpSessions.takeHtmlRender(threadId, {
305 ...page,
306 html: page.html.replace("revenue", "expense"),
307 }),
308 ).toBe(undefined);
309 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(reference);
310 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
311 const reused = yield* htmlRender.publish({ threadId, ...page });
312 yield* mcpSessions.set({ ...session, browserToolsAvailable: true });
313 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(reused);
314 const first = yield* htmlRender.publish({ threadId, ...page });
315 const second = yield* htmlRender.publish({ threadId, ...page });
316 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(first);
317 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(second);
318 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
319
320 yield* htmlRender.publish({ threadId, ...page });
321 yield* mcpSessions.set({
322 ...session,
323 providerSessionId: "replacement-credential",
324 providerInstanceId: ProviderInstanceId.make("antigravity"),
325 authorizationHeader: "Bearer replacement-token",
326 });
327 const replacement = yield* htmlRender.publish({ threadId, ...page });
328 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(replacement);
329 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
330 // Clearing the thread's MCP session drops the pages it kept.
331 yield* htmlRender.publish({ threadId, ...page });
332 yield* mcpSessions.clear(threadId);
333 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
334 }).pipe(Effect.provide(layerTest)),
335 );
336
337 it.effect("publishes a page from an .html file as a snapshot that path calls recover", () =>
338 Effect.gen(function* () {
339 const fileSystem = yield* FileSystem.FileSystem;
340 const path = yield* Path.Path;
341 const config = yield* ServerConfig.ServerConfig;
342 const htmlRender = yield* HtmlRender.HtmlRender;
343 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
344 const threadId = ThreadId.make("thread-html-path");
345 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-page-" });
346 const file = path.join(directory, "report.html");
347 yield* fileSystem.writeFileString(file, "<!doctype html><p>First draft</p>");
348 const page = { path: file, title: "Report", height: 300 };
349
350 const first = yield* htmlRender.publish({ threadId, ...page });
351 yield* fileSystem.writeFileString(file, "<!doctype html><p>Second draft</p>");
352 const second = yield* htmlRender.publish({ threadId, ...page });
353 const inline = { html: "<!doctype html><p>First draft</p>", title: "Report", height: 300 };
354 const inlineReference = yield* htmlRender.publish({ threadId, ...inline });
355
356 const stored = yield* fileSystem.readFileString(
357 resolveAttachmentPathById({
358 attachmentsDir: config.attachmentsDir,
359 attachmentId: first.attachmentId,
360 }) ?? "",
361 );
362 expect(stored).toContain("<p>First draft</p>");
363 expect(yield* mcpSessions.takeHtmlRender(threadId, { ...page, path: `${file}x` })).toBe(
364 undefined,
365 );
366 for (const html of [inline.html, false]) {
367 expect(yield* mcpSessions.takeHtmlRender(threadId, { ...page, html })).toBe(undefined);
368 }
369 expect(yield* mcpSessions.takeHtmlRender(threadId, { ...inline, path: null })).toEqual(
370 inlineReference,
371 );
372 expect(yield* mcpSessions.takeHtmlRender(threadId, { ...page, html: null })).toEqual(first);
373 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(second);
374 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
375 }).pipe(Effect.provide(layerTest)),
376 );
377
378 it.effect("refuses anything but a regular, singly linked .html file of at most 25 MiB", () =>
379 Effect.gen(function* () {
380 const fileSystem = yield* FileSystem.FileSystem;
381 const path = yield* Path.Path;
382 const config = yield* ServerConfig.ServerConfig;
383 const htmlRender = yield* HtmlRender.HtmlRender;
384 const threadId = ThreadId.make("thread-html-path-guard");
385 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-page-" });
386 const secret = path.join(directory, "id_rsa");
387 yield* fileSystem.writeFileString(secret, "PRIVATE KEY");
388 const page = path.join(directory, "page.html");
389 yield* fileSystem.writeFileString(page, "<!doctype html><p>linked</p>");
390 const hardLinked = path.join(directory, "linked.html");
391 yield* fileSystem.link(page, hardLinked);
392 // `mv .env renamed.html` keeps one link and an .html name; only its bytes give it away.
393 const renamed = path.join(directory, "renamed.html");
394 yield* fileSystem.writeFileString(renamed, "API_KEY=abc123\n");
395 const folder = path.join(directory, "folder.html");
396 yield* fileSystem.makeDirectory(folder);
397 const internal = path.join(config.secretsDir, "page.html");
398 yield* fileSystem.makeDirectory(config.secretsDir, { recursive: true });
399 yield* fileSystem.writeFileString(internal, "<!doctype html><p>internal</p>");
400
401 for (const file of [
402 "page.html",
403 "//attacker/share/page.html",
404 path.join(directory, "missing.html"),
405 secret,
406 hardLinked,
407 renamed,
408 folder,
409 internal,
410 ]) {
411 const error = yield* htmlRender
412 .publish({ threadId, path: file, title: "X", height: 200 })
413 .pipe(Effect.flip);
414 expect(error, file).toBeInstanceOf(HtmlRender.HtmlRenderFileError);
415 }
416 const huge = path.join(directory, "huge.html");
417 yield* fileSystem.writeFileString(huge, "");
418 yield* fileSystem.truncate(huge, 25 * 1024 * 1024 + 1);
419 const tooLarge = yield* htmlRender
420 .publish({ threadId, path: huge, title: "X", height: 200 })
421 .pipe(Effect.flip);
422 expect(tooLarge).toBeInstanceOf(HtmlRender.HtmlRenderFileTooLargeError);
423 }).pipe(Effect.provide(layerTest)),
424 );
425
426 it.effect.skipIf(!symlinksSupported)("refuses an .html symlink to another file", () =>
427 Effect.gen(function* () {
428 const fileSystem = yield* FileSystem.FileSystem;
429 const path = yield* Path.Path;
430 const htmlRender = yield* HtmlRender.HtmlRender;
431 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-page-" });
432 const secret = path.join(directory, "id_rsa");
433 yield* fileSystem.writeFileString(secret, "PRIVATE KEY");
434 const symlinked = path.join(directory, "symlinked.html");
435 yield* fileSystem.symlink(secret, symlinked);
436
437 const error = yield* htmlRender
438 .publish({
439 threadId: ThreadId.make("thread-html-path-link"),
440 path: symlinked,
441 title: "X",
442 height: 200,
443 })
444 .pipe(Effect.flip);
445
446 expect(error).toBeInstanceOf(HtmlRender.HtmlRenderFileError);
447 }).pipe(Effect.provide(layerTest)),
448 );
449
450 it.effect("removes the page when publishing is interrupted", () =>
451 Effect.gen(function* () {
452 const threadId = ThreadId.make("thread-html-cancel");
453 const page = { html: "<p>x</p>", title: "X", height: 200 };
454 const measuring = yield* Deferred.make<void>();
455 yield* Effect.gen(function* () {
456 const fileSystem = yield* FileSystem.FileSystem;
457 const config = yield* ServerConfig.ServerConfig;
458 const htmlRender = yield* HtmlRender.HtmlRender;
459 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
460 const storedPages = fileSystem
461 .readDirectory(config.attachmentsDir, { recursive: true })
462 .pipe(Effect.map((names) => names.filter((name) => name.endsWith(".html"))));
463
464 const publishing = yield* htmlRender.publish({ threadId, ...page }).pipe(Effect.forkChild);
465 yield* Deferred.await(measuring);
466 expect(yield* storedPages).toHaveLength(1);
467 yield* Fiber.interrupt(publishing);
468 expect(yield* storedPages).toEqual([]);
469 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
470 }).pipe(
471 Effect.provide(
472 layerHtmlRender(
473 undefined,
474 Deferred.succeed(measuring, undefined).pipe(Effect.andThen(Effect.never)),
475 ),
476 ),
477 );
478 }),
479 );
480
481 // Windows reports ENOENT asynchronously for this path instead of throwing ENOTDIR.
482 describe.skipIf(HostProcess.Platform.defaultValue() === "win32")(
483 "when the browser spawn throws synchronously",
484 () => {
485 it.live("reports a typed preview error", () =>
486 Effect.gen(function* () {
487 const fileSystem = yield* FileSystem.FileSystem;
488 const path = yield* Path.Path;
489 const file = yield* fileSystem.makeTempFileScoped({ prefix: "t3-browser-spawn-" });
490 const outcome = yield* HtmlRender.HtmlRender.use((htmlRender) =>
491 htmlRender.preview({ html: "<p>x</p>" }).pipe(Effect.flip),
492 ).pipe(
493 Effect.provide(layerHtmlRender(path.join(file, "chrome-headless-shell"))),
494 Effect.exit,
495 );
496 assert(Exit.isSuccess(outcome), "Expected a typed preview error.");
497 const error = outcome.value;
498 expect(error).toBeInstanceOf(HtmlRenderBrowserError);
499 expect(error.message).toBe(
500 "Headless Chrome could not render the page: the browser could not be started.",
501 );
502 expect(error).toMatchObject({ cause: { cause: { code: "ENOTDIR" } } });
503 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
504 );
505 },
506 );
507
508 // The fake browser is a shebang script, which Windows cannot execute.
509 describe.skipIf(HostProcess.Platform.defaultValue() === "win32")(
510 "when the browser cannot be signalled",
511 () => {
512 // A browser T3 cannot signal, as under AppArmor in an LXC container, must still exit.
513 it.live("asks the browser to close when the preview finishes instead of signalling it", () =>
514 Effect.gen(function* () {
515 const fileSystem = yield* FileSystem.FileSystem;
516 const path = yield* Path.Path;
517 const directory = yield* fileSystem.makeTempDirectoryScoped({
518 prefix: "t3-fake-browser-",
519 });
520 const executable = path.join(directory, "chrome-headless-shell");
521 const exitRecord = path.join(directory, "exited");
522 yield* fileSystem.writeFileString(
523 executable,
524 `#!${process.execPath}
525const fs = require("node:fs");
526process.on("SIGTERM", () => {});
527const quit = () => { fs.writeFileSync(${JSON.stringify(exitRecord)}, "asked to close"); process.exit(0); };
528const reply = (message) => fs.writeSync(4, JSON.stringify(message) + "\\0");
529const results = {
530 "Target.createBrowserContext": { browserContextId: "context" },
531 "Target.createTarget": { targetId: "page" },
532 "Target.attachToTarget": { sessionId: "session" },
533 "Runtime.evaluate": { result: { value: 100 } },
534 "Page.captureScreenshot": { data: "iVBORw0KGgo=" },
535};
536let buffered = "";
537fs.createReadStream(null, { fd: 3 }).on("end", quit).on("data", (chunk) => {
538 const messages = (buffered + chunk).split("\\0");
539 buffered = messages.pop();
540 for (const { id, method, sessionId } of messages.map((raw) => JSON.parse(raw))) {
541 if (method === "Browser.close") quit();
542 reply({ id, sessionId, result: results[method] ?? {} });
543 if (method === "Page.navigate") {
544 const value = "x" + "\u{1F600}".repeat(300);
545 const params = { type: "log", args: [{ type: "string", value }] };
546 reply({ sessionId, method: "Runtime.consoleAPICalled", params });
547 reply({ sessionId, method: "Page.loadEventFired", params: {} });
548 }
549 }
550});
551`,
552 { mode: 0o755 },
553 );
554
555 const preview = yield* HtmlRender.HtmlRender.use((htmlRender) =>
556 htmlRender.preview({ html: "<p>x</p>" }),
557 ).pipe(Effect.provide(layerHtmlRender(executable)));
558 const logged = preview.consoleMessages[0]?.text ?? "";
559 expect(logged.isWellFormed()).toBe(true);
560 expect(logged).toHaveLength(500);
561
562 const exitedBy = yield* fileSystem.readFileString(exitRecord).pipe(Effect.option);
563 expect(Option.getOrElse(exitedBy, () => "killed by a signal")).toBe("asked to close");
564 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
565 );
566
567 it.live("names this server's home in the browser setup command", () =>
568 Effect.gen(function* () {
569 const fileSystem = yield* FileSystem.FileSystem;
570 const path = yield* Path.Path;
571 const directory = yield* fileSystem.makeTempDirectoryScoped({
572 prefix: "t3-fake-browser-",
573 });
574 const executable = path.join(directory, "chrome-headless-shell");
575 yield* fileSystem.writeFileString(
576 executable,
577 `#!${process.execPath}\nprocess.stderr.write(${JSON.stringify(PreviewBrowserHost.NO_SANDBOX_SIGNATURE)});\nprocess.exit(1);\n`,
578 { mode: 0o755 },
579 );
580
581 const { error, baseDir } = yield* Effect.gen(function* () {
582 const { baseDir } = yield* ServerConfig.ServerConfig;
583 const htmlRender = yield* HtmlRender.HtmlRender;
584 const error = yield* htmlRender.preview({ html: "<p>x</p>" }).pipe(Effect.flip);
585 return { error, baseDir };
586 }).pipe(
587 Effect.provide(layerHtmlRender(executable)),
588 Effect.provideService(HostProcess.UserId, 1000),
589 );
590 expect(error).toBeInstanceOf(PreviewBrowserHost.PreviewBrowserSandboxError);
591 expect(error.message).toContain(`browser setup --base-dir ${baseDir}`);
592 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
593 );
594
595 it.live("reports a root server's sandbox refusal as a root error", () =>
596 Effect.gen(function* () {
597 const fileSystem = yield* FileSystem.FileSystem;
598 const path = yield* Path.Path;
599 const directory = yield* fileSystem.makeTempDirectoryScoped({
600 prefix: "t3-fake-browser-",
601 });
602 const executable = path.join(directory, "chrome-headless-shell");
603 const refusal =
604 "[1123/040735.447156:ERROR:content/browser/zygote_host/zygote_host_impl_linux.cc:103] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.\n";
605 yield* fileSystem.writeFileString(
606 executable,
607 `#!${process.execPath}\nprocess.stderr.write(${JSON.stringify(refusal)});\nprocess.exit(1);\n`,
608 { mode: 0o755 },
609 );
610
611 const error = yield* HtmlRender.HtmlRender.use((htmlRender) =>
612 htmlRender.preview({ html: "<p>hello</p>" }),
613 ).pipe(
614 Effect.flip,
615 Effect.provide(layerHtmlRender(executable)),
616 Effect.provideService(HostProcess.UserId, 0),
617 );
618 expect(error).toBeInstanceOf(PreviewBrowserHost.PreviewBrowserRootError);
619 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
620 );
621 },
622 );
623
624 it.live("matches preview media queries and text colors to the requested appearance", (ctx) =>
625 Effect.gen(function* () {
626 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
627 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
628 yield* Effect.gen(function* () {
629 const htmlRender = yield* HtmlRender.HtmlRender;
630 for (const appearance of [undefined, "dark", "light"] as const) {
631 const preview = yield* htmlRender.preview({
632 appearance,
633 html: [
634 "<style>h1{color:#18181b}@media(prefers-color-scheme:dark){h1{color:#fafafa}}</style>",
635 "<h1>The moon garden opens at dusk</h1>",
636 '<script>console.log(matchMedia("(prefers-color-scheme:dark)").matches,',
637 'getComputedStyle(document.querySelector("h1")).color);</script>',
638 ].join(""),
639 });
640 expect(preview.consoleMessages).toContainEqual({
641 level: "log",
642 text: appearance === "light" ? "false rgb(24, 24, 27)" : "true rgb(250, 250, 250)",
643 });
644 }
645 }).pipe(Effect.provide(layerHtmlRender(executable)));
646 }),
647 );
648
649 it.live("uses the viewing client's palette for a preview of its thread", (ctx) =>
650 Effect.gen(function* () {
651 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
652 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
653 yield* Effect.gen(function* () {
654 const htmlRender = yield* HtmlRender.HtmlRender;
655 const viewers = yield* ThreadViewers.ThreadViewers;
656 const threadId = ThreadId.make("themed-thread");
657 const ready = yield* Deferred.make<void>();
658 const viewer = yield* viewers
659 .watchPreviewTheme(threadId, {
660 appearance: "light",
661 colors: { "--background": "#f5e8fe", "--chart-1": "#98329b" },
662 })
663 .pipe(
664 Stream.runForEach(() => Deferred.succeed(ready, undefined)),
665 Effect.forkChild,
666 );
667 yield* Deferred.await(ready);
668
669 const html = [
670 "<p>Palette preview</p>",
671 "<script>const root = getComputedStyle(document.documentElement);",
672 'console.log(root.getPropertyValue("--background").trim(),',
673 'root.getPropertyValue("--chart-1").trim(),',
674 'matchMedia("(prefers-color-scheme: light)").matches);</script>',
675 ].join("");
676 const matchesViewer = { level: "log", text: "#f5e8fe #98329b true" };
677 const preview = yield* htmlRender.preview({ threadId, html });
678 expect(preview.consoleMessages).toContainEqual(matchesViewer);
679 const override = yield* htmlRender.preview({ threadId, html, appearance: "dark" });
680 expect(override.consoleMessages).not.toContainEqual(matchesViewer);
681 expect(override.consoleMessages[0]?.text.endsWith(" false")).toBe(true);
682 expect(viewers.previewTheme(ThreadId.make("other-thread"))).toBeUndefined();
683 yield* Fiber.interrupt(viewer);
684 expect(viewers.previewTheme(threadId)).toBeUndefined();
685 }).pipe(Effect.provide(layerHtmlRender(executable)));
686 }),
687 );
688
689 it.live("keeps every local file but the page itself out of the browser", (ctx) =>
690 Effect.gen(function* () {
691 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
692 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
693 yield* Effect.gen(function* () {
694 const fileSystem = yield* FileSystem.FileSystem;
695 const path = yield* Path.Path;
696 const htmlRender = yield* HtmlRender.HtmlRender;
697 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-files-" });
698 const secret = path.join(directory, "secret.js");
699 yield* fileSystem.writeFileString(secret, 'window.secret = "abc123";');
700 const secretUrl = NodeURL.pathToFileURL(secret).href;
701
702 const preview = yield* htmlRender.preview({
703 html: [
704 `<script src="${secretUrl}"></script>`,
705 `<iframe src="${secretUrl}" onload="console.log('frame loaded')"></iframe>`,
706 '<script>addEventListener("load", () => console.log("secret:", window.secret ?? "none"));</script>',
707 ].join(""),
708 });
709
710 const texts = preview.consoleMessages.map((message) => message.text);
711 expect(texts).toContain("secret: none");
712 expect(texts.join(" ")).not.toContain("abc123");
713 }).pipe(Effect.scoped, Effect.provide(layerHtmlRender(executable)));
714 }),
715 );
716
717 it.live("keeps the page off this machine's local network", (ctx) =>
718 Effect.gen(function* () {
719 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
720 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
721 const requests: Array<string> = [];
722 const server = yield* Effect.acquireRelease(
723 Effect.callback<NodeHttp.Server>((resume) => {
724 const listening = NodeHttp.createServer((request, response) => {
725 requests.push(`${request.url} ${request.headers["sec-purpose"] ?? ""}`);
726 response.end("<p>LOCAL</p>");
727 });
728 listening.listen(0, "127.0.0.1", () => resume(Effect.succeed(listening)));
729 }),
730 (listening) =>
731 Effect.callback<void>((resume) => {
732 listening.close(() => resume(Effect.void));
733 }),
734 );
735 const datagrams: Array<string> = [];
736 const udp = yield* Effect.acquireRelease(
737 Effect.callback<NodeDgram.Socket>((resume) => {
738 const socket = NodeDgram.createSocket("udp4");
739 socket.on("message", (message) => datagrams.push(message.toString("hex")));
740 socket.bind(0, "127.0.0.1", () => resume(Effect.succeed(socket)));
741 }),
742 (socket) =>
743 Effect.callback<void>((resume) => {
744 socket.close(() => resume(Effect.void));
745 }),
746 );
747 const address = server.address();
748 const origin = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`;
749 const stun = `stun:127.0.0.1:${udp.address().port}`;
750 yield* Effect.gen(function* () {
751 const htmlRender = yield* HtmlRender.HtmlRender;
752 yield* htmlRender.preview({
753 html: [
754 `<img src="${origin}/x.png"><iframe src="${origin}/"></iframe>`,
755 `<script type="speculationrules">{"prefetch":[{"source":"list","urls":["${origin}/prefetch"]}]}</script>`,
756 `<script>fetch("${origin}/").catch(() => {}); new WebSocket("ws${origin.slice(4)}/socket");`,
757 `try { const peer = new RTCPeerConnection({ iceServers: [{ urls: "${stun}" }] });`,
758 `peer.createDataChannel("x"); peer.createOffer().then((offer) => peer.setLocalDescription(offer));`,
759 `} catch {}`,
760 `window.open("${origin}/popup"); location.href = "${origin}/navigate";</script>`,
761 ].join(""),
762 });
763 }).pipe(Effect.provide(layerHtmlRender(executable)));
764 expect(requests).toEqual([]);
765 expect(datagrams).toEqual([]);
766 }),
767 );
768});