Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

HtmlRender.test.ts

782 lines37.3 KB

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&copy.png");
70 const literalEntityPng = path.join(directory, "a&amp;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, "sh&#111;t.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&amp;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:&quot;'&quot;;height:100vh;--b:&quot;'&quot;">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("rejects viewport height units after abruptly closed or bang-closed comments", () =>
186 Effect.gen(function* () {
187 const htmlRender = yield* HtmlRender.HtmlRender;
188 for (const page of [
189 "<!--><style>body{height:100vh}</style>",
190 "<!---><style>body{height:100vh}</style>",
191 '<!-- note --!><div style="height:100vh">hi</div>',
192 ]) {
193 const error = yield* htmlRender.prepare(page).pipe(Effect.flip);
194 expect(error).toBeInstanceOf(HtmlRender.HtmlRenderViewportHeightError);
195 }
196 }).pipe(Effect.provide(layerTest)),
197 );
198​
199 it.effect("inlines an SVG behind processing instructions and a doctype subset", () =>
200 Effect.gen(function* () {
201 const fileSystem = yield* FileSystem.FileSystem;
202 const path = yield* Path.Path;
203 const htmlRender = yield* HtmlRender.HtmlRender;
204 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
205 const svg = path.join(directory, "styled.svg");
206 const source = [
207 '<?xml version="1.0"?>',
208 '<?xml-stylesheet href="theme.css"?>',
209 '<!DOCTYPE svg [ <!ENTITY fill "red"> ]>',
210 '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"/>',
211 ].join("\n");
212 yield* fileSystem.writeFileString(svg, source);
213​
214 const prepared = yield* htmlRender.prepare(`<img src="${svg}">`);
215​
216 expect(prepared).toContain(`data:image/svg+xml;base64,${Base64.encode(source)}`);
217 }).pipe(Effect.provide(layerTest)),
218 );
219​
220 it.effect("lists every local image it cannot read", () =>
221 Effect.gen(function* () {
222 const fileSystem = yield* FileSystem.FileSystem;
223 const path = yield* Path.Path;
224 const htmlRender = yield* HtmlRender.HtmlRender;
225 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-images-" });
226 const folder = path.join(directory, "folder.png");
227 yield* fileSystem.makeDirectory(folder);
228 const missing = path.join(directory, "missing.jpg");
229 const missingSvg = path.join(directory, "missing.svg");
230 const secret = path.join(directory, "secret.png");
231 yield* fileSystem.writeFileString(secret, "API_KEY=abc123");
232 const report = path.join(directory, "report.svg");
233 yield* fileSystem.writeFileString(report, "<!doctype html><body><svg></svg>API_KEY=abc123");
234 const config = path.join(directory, "config.svg");
235 yield* fileSystem.writeFileString(
236 config,
237 '<!DOCTYPE config [<!ENTITY a "a"><!ENTITY b "]><svg/>">]><config>API_KEY=abc123</config>',
238 );
239 const stalling = path.join(directory, "stalling.svg");
240 yield* fileSystem.writeFileString(stalling, `${"<?p?>".repeat(40)}<config><svg/></config>`);
241 const unclosed = path.join(directory, "unclosed.svg");
242 yield* fileSystem.writeFileString(unclosed, '<!DOCTYPE svg [<!ENTITY a "x><svg/>');
243 const upper = path.join(directory, "upper.svg");
244 yield* fileSystem.writeFileString(upper, "<SVG/>API_KEY=abc123");
245 const longer = path.join(directory, "longer.svg");
246 yield* fileSystem.writeFileString(longer, "<svg\u00e9/>API_KEY=abc123");
247​
248 const error = yield* htmlRender
249 .prepare(
250 `<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">`,
251 )
252 .pipe(Effect.flip);
253​
254 expect(error).toBeInstanceOf(HtmlRender.HtmlRenderImagesNotFoundError);
255 expect(error._tag === "HtmlRenderImagesNotFoundError" && error.paths).toEqual([
256 missing,
257 missingSvg,
258 folder,
259 "C:\\nope\\shot.webp",
260 secret,
261 report,
262 config,
263 stalling,
264 unclosed,
265 upper,
266 longer,
267 "/%2Fattacker/share/shot.png",
268 ]);
269 }).pipe(Effect.provide(layerTest)),
270 );
271​
272 it.effect("publishes the prepared page as an html thread attachment", () =>
273 Effect.gen(function* () {
274 const fileSystem = yield* FileSystem.FileSystem;
275 const config = yield* ServerConfig.ServerConfig;
276 const htmlRender = yield* HtmlRender.HtmlRender;
277 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
278 const threadId = ThreadId.make("thread-html-render");
279 const session = {
280 environmentId: EnvironmentId.make("html-render-environment"),
281 threadId,
282 providerSessionId: "first-credential",
283 providerInstanceId: ProviderInstanceId.make("claude"),
284 endpoint: "http://localhost:8311/mcp",
285 authorizationHeader: "Bearer first-token",
286 browserToolsAvailable: false,
287 };
288 yield* mcpSessions.set(session);
289​
290 const reference = yield* htmlRender.publish({
291 threadId,
292 html: `<p>Quarterly revenue</p>${" ".repeat(8_000)}`,
293 title: " Revenue ",
294 height: 9_000,
295 });
296​
297 expect(reference).toEqual({
298 attachmentId: expect.any(String),
299 title: "Revenue",
300 height: 2_000,
301 });
302 const stored = resolveAttachmentPathById({
303 attachmentsDir: config.attachmentsDir,
304 attachmentId: reference.attachmentId,
305 });
306 expect(stored?.endsWith(".html")).toBe(true);
307 const html = yield* fileSystem.readFileString(stored ?? "");
308 expect(html).toContain('<style id="t3-theme">');
309 expect(html).toContain("<p>Quarterly revenue</p>");
310 // Antigravity reports the call without its result, so the thread's
311 // provider session keeps the page for one call with these arguments.
312 const page = {
313 html: `<p>Quarterly revenue</p>${" ".repeat(8_000)}`,
314 title: " Revenue ",
315 height: 9_000,
316 };
317 expect(
318 yield* mcpSessions.takeHtmlRender(threadId, {
319 ...page,
320 html: page.html.replace("revenue", "expense"),
321 }),
322 ).toBe(undefined);
323 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(reference);
324 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
325 const reused = yield* htmlRender.publish({ threadId, ...page });
326 yield* mcpSessions.set({ ...session, browserToolsAvailable: true });
327 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(reused);
328 const first = yield* htmlRender.publish({ threadId, ...page });
329 const second = yield* htmlRender.publish({ threadId, ...page });
330 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(first);
331 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(second);
332 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
333​
334 yield* htmlRender.publish({ threadId, ...page });
335 yield* mcpSessions.set({
336 ...session,
337 providerSessionId: "replacement-credential",
338 providerInstanceId: ProviderInstanceId.make("antigravity"),
339 authorizationHeader: "Bearer replacement-token",
340 });
341 const replacement = yield* htmlRender.publish({ threadId, ...page });
342 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(replacement);
343 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
344 // Clearing the thread's MCP session drops the pages it kept.
345 yield* htmlRender.publish({ threadId, ...page });
346 yield* mcpSessions.clear(threadId);
347 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
348 }).pipe(Effect.provide(layerTest)),
349 );
350​
351 it.effect("publishes a page from an .html file as a snapshot that path calls recover", () =>
352 Effect.gen(function* () {
353 const fileSystem = yield* FileSystem.FileSystem;
354 const path = yield* Path.Path;
355 const config = yield* ServerConfig.ServerConfig;
356 const htmlRender = yield* HtmlRender.HtmlRender;
357 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
358 const threadId = ThreadId.make("thread-html-path");
359 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-page-" });
360 const file = path.join(directory, "report.html");
361 yield* fileSystem.writeFileString(file, "<!doctype html><p>First draft</p>");
362 const page = { path: file, title: "Report", height: 300 };
363​
364 const first = yield* htmlRender.publish({ threadId, ...page });
365 yield* fileSystem.writeFileString(file, "<!doctype html><p>Second draft</p>");
366 const second = yield* htmlRender.publish({ threadId, ...page });
367 const inline = { html: "<!doctype html><p>First draft</p>", title: "Report", height: 300 };
368 const inlineReference = yield* htmlRender.publish({ threadId, ...inline });
369​
370 const stored = yield* fileSystem.readFileString(
371 resolveAttachmentPathById({
372 attachmentsDir: config.attachmentsDir,
373 attachmentId: first.attachmentId,
374 }) ?? "",
375 );
376 expect(stored).toContain("<p>First draft</p>");
377 expect(yield* mcpSessions.takeHtmlRender(threadId, { ...page, path: `${file}x` })).toBe(
378 undefined,
379 );
380 for (const html of [inline.html, false]) {
381 expect(yield* mcpSessions.takeHtmlRender(threadId, { ...page, html })).toBe(undefined);
382 }
383 expect(yield* mcpSessions.takeHtmlRender(threadId, { ...inline, path: null })).toEqual(
384 inlineReference,
385 );
386 expect(yield* mcpSessions.takeHtmlRender(threadId, { ...page, html: null })).toEqual(first);
387 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toEqual(second);
388 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
389 }).pipe(Effect.provide(layerTest)),
390 );
391​
392 it.effect("refuses anything but a regular, singly linked .html file of at most 25 MiB", () =>
393 Effect.gen(function* () {
394 const fileSystem = yield* FileSystem.FileSystem;
395 const path = yield* Path.Path;
396 const config = yield* ServerConfig.ServerConfig;
397 const htmlRender = yield* HtmlRender.HtmlRender;
398 const threadId = ThreadId.make("thread-html-path-guard");
399 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-page-" });
400 const secret = path.join(directory, "id_rsa");
401 yield* fileSystem.writeFileString(secret, "PRIVATE KEY");
402 const page = path.join(directory, "page.html");
403 yield* fileSystem.writeFileString(page, "<!doctype html><p>linked</p>");
404 const hardLinked = path.join(directory, "linked.html");
405 yield* fileSystem.link(page, hardLinked);
406 // `mv .env renamed.html` keeps one link and an .html name; only its bytes give it away.
407 const renamed = path.join(directory, "renamed.html");
408 yield* fileSystem.writeFileString(renamed, "API_KEY=abc123\n");
409 const folder = path.join(directory, "folder.html");
410 yield* fileSystem.makeDirectory(folder);
411 const internal = path.join(config.secretsDir, "page.html");
412 yield* fileSystem.makeDirectory(config.secretsDir, { recursive: true });
413 yield* fileSystem.writeFileString(internal, "<!doctype html><p>internal</p>");
414​
415 for (const file of [
416 "page.html",
417 "//attacker/share/page.html",
418 path.join(directory, "missing.html"),
419 secret,
420 hardLinked,
421 renamed,
422 folder,
423 internal,
424 ]) {
425 const error = yield* htmlRender
426 .publish({ threadId, path: file, title: "X", height: 200 })
427 .pipe(Effect.flip);
428 expect(error, file).toBeInstanceOf(HtmlRender.HtmlRenderFileError);
429 }
430 const huge = path.join(directory, "huge.html");
431 yield* fileSystem.writeFileString(huge, "");
432 yield* fileSystem.truncate(huge, 25 * 1024 * 1024 + 1);
433 const tooLarge = yield* htmlRender
434 .publish({ threadId, path: huge, title: "X", height: 200 })
435 .pipe(Effect.flip);
436 expect(tooLarge).toBeInstanceOf(HtmlRender.HtmlRenderFileTooLargeError);
437 }).pipe(Effect.provide(layerTest)),
438 );
439​
440 it.effect.skipIf(!symlinksSupported)("refuses an .html symlink to another file", () =>
441 Effect.gen(function* () {
442 const fileSystem = yield* FileSystem.FileSystem;
443 const path = yield* Path.Path;
444 const htmlRender = yield* HtmlRender.HtmlRender;
445 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-page-" });
446 const secret = path.join(directory, "id_rsa");
447 yield* fileSystem.writeFileString(secret, "PRIVATE KEY");
448 const symlinked = path.join(directory, "symlinked.html");
449 yield* fileSystem.symlink(secret, symlinked);
450​
451 const error = yield* htmlRender
452 .publish({
453 threadId: ThreadId.make("thread-html-path-link"),
454 path: symlinked,
455 title: "X",
456 height: 200,
457 })
458 .pipe(Effect.flip);
459​
460 expect(error).toBeInstanceOf(HtmlRender.HtmlRenderFileError);
461 }).pipe(Effect.provide(layerTest)),
462 );
463​
464 it.effect("removes the page when publishing is interrupted", () =>
465 Effect.gen(function* () {
466 const threadId = ThreadId.make("thread-html-cancel");
467 const page = { html: "<p>x</p>", title: "X", height: 200 };
468 const measuring = yield* Deferred.make<void>();
469 yield* Effect.gen(function* () {
470 const fileSystem = yield* FileSystem.FileSystem;
471 const config = yield* ServerConfig.ServerConfig;
472 const htmlRender = yield* HtmlRender.HtmlRender;
473 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
474 const storedPages = fileSystem
475 .readDirectory(config.attachmentsDir, { recursive: true })
476 .pipe(Effect.map((names) => names.filter((name) => name.endsWith(".html"))));
477​
478 const publishing = yield* htmlRender.publish({ threadId, ...page }).pipe(Effect.forkChild);
479 yield* Deferred.await(measuring);
480 expect(yield* storedPages).toHaveLength(1);
481 yield* Fiber.interrupt(publishing);
482 expect(yield* storedPages).toEqual([]);
483 expect(yield* mcpSessions.takeHtmlRender(threadId, page)).toBe(undefined);
484 }).pipe(
485 Effect.provide(
486 layerHtmlRender(
487 undefined,
488 Deferred.succeed(measuring, undefined).pipe(Effect.andThen(Effect.never)),
489 ),
490 ),
491 );
492 }),
493 );
494​
495 // Windows reports ENOENT asynchronously for this path instead of throwing ENOTDIR.
496 describe.skipIf(HostProcess.Platform.defaultValue() === "win32")(
497 "when the browser spawn throws synchronously",
498 () => {
499 it.live("reports a typed preview error", () =>
500 Effect.gen(function* () {
501 const fileSystem = yield* FileSystem.FileSystem;
502 const path = yield* Path.Path;
503 const file = yield* fileSystem.makeTempFileScoped({ prefix: "t3-browser-spawn-" });
504 const outcome = yield* HtmlRender.HtmlRender.use((htmlRender) =>
505 htmlRender.preview({ html: "<p>x</p>" }).pipe(Effect.flip),
506 ).pipe(
507 Effect.provide(layerHtmlRender(path.join(file, "chrome-headless-shell"))),
508 Effect.exit,
509 );
510 assert(Exit.isSuccess(outcome), "Expected a typed preview error.");
511 const error = outcome.value;
512 expect(error).toBeInstanceOf(HtmlRenderBrowserError);
513 expect(error.message).toBe(
514 "Headless Chrome could not render the page: the browser could not be started.",
515 );
516 expect(error).toMatchObject({ cause: { cause: { code: "ENOTDIR" } } });
517 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
518 );
519 },
520 );
521​
522 // The fake browser is a shebang script, which Windows cannot execute.
523 describe.skipIf(HostProcess.Platform.defaultValue() === "win32")(
524 "when the browser cannot be signalled",
525 () => {
526 // A browser T3 cannot signal, as under AppArmor in an LXC container, must still exit.
527 it.live("asks the browser to close when the preview finishes instead of signalling it", () =>
528 Effect.gen(function* () {
529 const fileSystem = yield* FileSystem.FileSystem;
530 const path = yield* Path.Path;
531 const directory = yield* fileSystem.makeTempDirectoryScoped({
532 prefix: "t3-fake-browser-",
533 });
534 const executable = path.join(directory, "chrome-headless-shell");
535 const exitRecord = path.join(directory, "exited");
536 yield* fileSystem.writeFileString(
537 executable,
538 `#!${process.execPath}
539const fs = require("node:fs");
540process.on("SIGTERM", () => {});
541const quit = () => { fs.writeFileSync(${JSON.stringify(exitRecord)}, "asked to close"); process.exit(0); };
542const reply = (message) => fs.writeSync(4, JSON.stringify(message) + "\\0");
543const results = {
544 "Target.createBrowserContext": { browserContextId: "context" },
545 "Target.createTarget": { targetId: "page" },
546 "Target.attachToTarget": { sessionId: "session" },
547 "Runtime.evaluate": { result: { value: 100 } },
548 "Page.captureScreenshot": { data: "iVBORw0KGgo=" },
549};
550let buffered = "";
551fs.createReadStream(null, { fd: 3 }).on("end", quit).on("data", (chunk) => {
552 const messages = (buffered + chunk).split("\\0");
553 buffered = messages.pop();
554 for (const { id, method, sessionId } of messages.map((raw) => JSON.parse(raw))) {
555 if (method === "Browser.close") quit();
556 reply({ id, sessionId, result: results[method] ?? {} });
557 if (method === "Page.navigate") {
558 const value = "x" + "\u{1F600}".repeat(300);
559 const params = { type: "log", args: [{ type: "string", value }] };
560 reply({ sessionId, method: "Runtime.consoleAPICalled", params });
561 reply({ sessionId, method: "Page.loadEventFired", params: {} });
562 }
563 }
564});
565`,
566 { mode: 0o755 },
567 );
568​
569 const preview = yield* HtmlRender.HtmlRender.use((htmlRender) =>
570 htmlRender.preview({ html: "<p>x</p>" }),
571 ).pipe(Effect.provide(layerHtmlRender(executable)));
572 const logged = preview.consoleMessages[0]?.text ?? "";
573 expect(logged.isWellFormed()).toBe(true);
574 expect(logged).toHaveLength(500);
575​
576 const exitedBy = yield* fileSystem.readFileString(exitRecord).pipe(Effect.option);
577 expect(Option.getOrElse(exitedBy, () => "killed by a signal")).toBe("asked to close");
578 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
579 );
580​
581 it.live("names this server's home in the browser setup command", () =>
582 Effect.gen(function* () {
583 const fileSystem = yield* FileSystem.FileSystem;
584 const path = yield* Path.Path;
585 const directory = yield* fileSystem.makeTempDirectoryScoped({
586 prefix: "t3-fake-browser-",
587 });
588 const executable = path.join(directory, "chrome-headless-shell");
589 yield* fileSystem.writeFileString(
590 executable,
591 `#!${process.execPath}\nprocess.stderr.write(${JSON.stringify(PreviewBrowserHost.NO_SANDBOX_SIGNATURE)});\nprocess.exit(1);\n`,
592 { mode: 0o755 },
593 );
594​
595 const { error, baseDir } = yield* Effect.gen(function* () {
596 const { baseDir } = yield* ServerConfig.ServerConfig;
597 const htmlRender = yield* HtmlRender.HtmlRender;
598 const error = yield* htmlRender.preview({ html: "<p>x</p>" }).pipe(Effect.flip);
599 return { error, baseDir };
600 }).pipe(
601 Effect.provide(layerHtmlRender(executable)),
602 Effect.provideService(HostProcess.UserId, 1000),
603 );
604 expect(error).toBeInstanceOf(PreviewBrowserHost.PreviewBrowserSandboxError);
605 expect(error.message).toContain(`browser setup --base-dir ${baseDir}`);
606 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
607 );
608​
609 it.live("reports a root server's sandbox refusal as a root error", () =>
610 Effect.gen(function* () {
611 const fileSystem = yield* FileSystem.FileSystem;
612 const path = yield* Path.Path;
613 const directory = yield* fileSystem.makeTempDirectoryScoped({
614 prefix: "t3-fake-browser-",
615 });
616 const executable = path.join(directory, "chrome-headless-shell");
617 const refusal =
618 "[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";
619 yield* fileSystem.writeFileString(
620 executable,
621 `#!${process.execPath}\nprocess.stderr.write(${JSON.stringify(refusal)});\nprocess.exit(1);\n`,
622 { mode: 0o755 },
623 );
624​
625 const error = yield* HtmlRender.HtmlRender.use((htmlRender) =>
626 htmlRender.preview({ html: "<p>hello</p>" }),
627 ).pipe(
628 Effect.flip,
629 Effect.provide(layerHtmlRender(executable)),
630 Effect.provideService(HostProcess.UserId, 0),
631 );
632 expect(error).toBeInstanceOf(PreviewBrowserHost.PreviewBrowserRootError);
633 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
634 );
635 },
636 );
637​
638 it.live("matches preview media queries and text colors to the requested appearance", (ctx) =>
639 Effect.gen(function* () {
640 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
641 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
642 yield* Effect.gen(function* () {
643 const htmlRender = yield* HtmlRender.HtmlRender;
644 for (const appearance of [undefined, "dark", "light"] as const) {
645 const preview = yield* htmlRender.preview({
646 appearance,
647 html: [
648 "<style>h1{color:#18181b}@media(prefers-color-scheme:dark){h1{color:#fafafa}}</style>",
649 "<h1>The moon garden opens at dusk</h1>",
650 '<script>console.log(matchMedia("(prefers-color-scheme:dark)").matches,',
651 'getComputedStyle(document.querySelector("h1")).color);</script>',
652 ].join(""),
653 });
654 expect(preview.consoleMessages).toContainEqual({
655 level: "log",
656 text: appearance === "light" ? "false rgb(24, 24, 27)" : "true rgb(250, 250, 250)",
657 });
658 }
659 }).pipe(Effect.provide(layerHtmlRender(executable)));
660 }),
661 );
662​
663 it.live("uses the viewing client's palette for a preview of its thread", (ctx) =>
664 Effect.gen(function* () {
665 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
666 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
667 yield* Effect.gen(function* () {
668 const htmlRender = yield* HtmlRender.HtmlRender;
669 const viewers = yield* ThreadViewers.ThreadViewers;
670 const threadId = ThreadId.make("themed-thread");
671 const ready = yield* Deferred.make<void>();
672 const viewer = yield* viewers
673 .watchPreviewTheme(threadId, {
674 appearance: "light",
675 colors: { "--background": "#f5e8fe", "--chart-1": "#98329b" },
676 })
677 .pipe(
678 Stream.runForEach(() => Deferred.succeed(ready, undefined)),
679 Effect.forkChild,
680 );
681 yield* Deferred.await(ready);
682​
683 const html = [
684 "<p>Palette preview</p>",
685 "<script>const root = getComputedStyle(document.documentElement);",
686 'console.log(root.getPropertyValue("--background").trim(),',
687 'root.getPropertyValue("--chart-1").trim(),',
688 'matchMedia("(prefers-color-scheme: light)").matches);</script>',
689 ].join("");
690 const matchesViewer = { level: "log", text: "#f5e8fe #98329b true" };
691 const preview = yield* htmlRender.preview({ threadId, html });
692 expect(preview.consoleMessages).toContainEqual(matchesViewer);
693 const override = yield* htmlRender.preview({ threadId, html, appearance: "dark" });
694 expect(override.consoleMessages).not.toContainEqual(matchesViewer);
695 expect(override.consoleMessages[0]?.text.endsWith(" false")).toBe(true);
696 expect(viewers.previewTheme(ThreadId.make("other-thread"))).toBeUndefined();
697 yield* Fiber.interrupt(viewer);
698 expect(viewers.previewTheme(threadId)).toBeUndefined();
699 }).pipe(Effect.provide(layerHtmlRender(executable)));
700 }),
701 );
702​
703 it.live("keeps every local file but the page itself out of the browser", (ctx) =>
704 Effect.gen(function* () {
705 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
706 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
707 yield* Effect.gen(function* () {
708 const fileSystem = yield* FileSystem.FileSystem;
709 const path = yield* Path.Path;
710 const htmlRender = yield* HtmlRender.HtmlRender;
711 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-files-" });
712 const secret = path.join(directory, "secret.js");
713 yield* fileSystem.writeFileString(secret, 'window.secret = "abc123";');
714 const secretUrl = NodeURL.pathToFileURL(secret).href;
715​
716 const preview = yield* htmlRender.preview({
717 html: [
718 `<script src="${secretUrl}"></script>`,
719 `<iframe src="${secretUrl}" onload="console.log('frame loaded')"></iframe>`,
720 '<script>addEventListener("load", () => console.log("secret:", window.secret ?? "none"));</script>',
721 ].join(""),
722 });
723​
724 const texts = preview.consoleMessages.map((message) => message.text);
725 expect(texts).toContain("secret: none");
726 expect(texts.join(" ")).not.toContain("abc123");
727 }).pipe(Effect.scoped, Effect.provide(layerHtmlRender(executable)));
728 }),
729 );
730​
731 it.live("keeps the page off this machine's local network", (ctx) =>
732 Effect.gen(function* () {
733 const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV];
734 if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`);
735 const requests: Array<string> = [];
736 const server = yield* Effect.acquireRelease(
737 Effect.callback<NodeHttp.Server>((resume) => {
738 const listening = NodeHttp.createServer((request, response) => {
739 requests.push(`${request.url} ${request.headers["sec-purpose"] ?? ""}`);
740 response.end("<p>LOCAL</p>");
741 });
742 listening.listen(0, "127.0.0.1", () => resume(Effect.succeed(listening)));
743 }),
744 (listening) =>
745 Effect.callback<void>((resume) => {
746 listening.close(() => resume(Effect.void));
747 }),
748 );
749 const datagrams: Array<string> = [];
750 const udp = yield* Effect.acquireRelease(
751 Effect.callback<NodeDgram.Socket>((resume) => {
752 const socket = NodeDgram.createSocket("udp4");
753 socket.on("message", (message) => datagrams.push(message.toString("hex")));
754 socket.bind(0, "127.0.0.1", () => resume(Effect.succeed(socket)));
755 }),
756 (socket) =>
757 Effect.callback<void>((resume) => {
758 socket.close(() => resume(Effect.void));
759 }),
760 );
761 const address = server.address();
762 const origin = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`;
763 const stun = `stun:127.0.0.1:${udp.address().port}`;
764 yield* Effect.gen(function* () {
765 const htmlRender = yield* HtmlRender.HtmlRender;
766 yield* htmlRender.preview({
767 html: [
768 `<img src="${origin}/x.png"><iframe src="${origin}/"></iframe>`,
769 `<script type="speculationrules">{"prefetch":[{"source":"list","urls":["${origin}/prefetch"]}]}</script>`,
770 `<script>fetch("${origin}/").catch(() => {}); new WebSocket("ws${origin.slice(4)}/socket");`,
771 `try { const peer = new RTCPeerConnection({ iceServers: [{ urls: "${stun}" }] });`,
772 `peer.createDataChannel("x"); peer.createOffer().then((offer) => peer.setLocalDescription(offer));`,
773 `} catch {}`,
774 `window.open("${origin}/popup"); location.href = "${origin}/navigate";</script>`,
775 ].join(""),
776 });
777 }).pipe(Effect.provide(layerHtmlRender(executable)));
778 expect(requests).toEqual([]);
779 expect(datagrams).toEqual([]);
780 }),
781 );
782});