Open History to see the last commit
1import type { ThreadId } from "@t3tools/contracts";
2import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import { isNetworkPath } from "@t3tools/shared/path";
5import {
6 clampHtmlRenderHeight,
7 HTML_RENDER_COLUMN_WIDTH,
8 HTML_RENDER_MAX_TITLE_LENGTH,
9 HTML_RENDER_MEASURE_FONTS,
10 HTML_RENDER_MEASURE_WIDTHS,
11 htmlRenderTheme,
12 htmlRenderThemeFragment,
13 injectHtmlRenderBootstrap,
14 type HtmlRenderReference,
15} from "@t3tools/shared/htmlRender";
16import {
17 T3_CODE_DARK_THEME_COLORS,
18 T3_CODE_LIGHT_THEME_COLORS,
19 type ThemeAppearance,
20} from "@t3tools/shared/themePalettes";
21import * as Context from "effect/Context";
22import * as Effect from "effect/Effect";
23import * as FileSystem from "effect/FileSystem";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as Path from "effect/Path";
27import * as Schema from "effect/Schema";
28import * as Semaphore from "effect/Semaphore";
29import * as Stream from "effect/Stream";
30import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
31
32import { openMediaFile } from "../assets/MediaFile.ts";
33import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
34import { createAttachmentId } from "../attachmentStore.ts";
35import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
36import { resolveRootCliCommand } from "../cli/invocation.ts";
37import * as ServerConfig from "../config.ts";
38import * as HeadlessChrome from "./headlessChrome.ts";
39import * as PreviewBrowser from "../preview/PreviewBrowser.ts";
40import * as PreviewBrowserHost from "../preview/PreviewBrowserHost.ts";
41
42const MIB = 1024 * 1024;
43const MAX_IMAGE_BYTES = 10 * MIB;
44const MAX_PAGE_BYTES = 25 * MIB;
45const HTML_FILE_EXTENSION = /\.html?$/i;
46// Like the image check, judge the bytes: a renamed .env or key does not start like a page.
47const HTML_DOCUMENT_START = /^\s*<(?:!doctype\s+html|html)[\s>]/i;
48const formatMib = (bytes: number) => `${(bytes / MIB).toFixed(1)} MiB`;
49
50export class HtmlRenderFileError extends Schema.TaggedError<HtmlRenderFileError>()(
51 "HtmlRenderFileError",
52 { path: Schema.String, cause: Schema.optional(Schema.Defect()) },
53) {
54 override get message(): string {
55 return `${this.path} is not a readable HTML document. Pass an absolute path to a regular .html file that starts with <!doctype html> or <html>, or pass html instead.`;
56 }
57}
58
59export class HtmlRenderFileTooLargeError extends Schema.TaggedError<HtmlRenderFileTooLargeError>()(
60 "HtmlRenderFileTooLargeError",
61 { path: Schema.String, sizeBytes: Schema.Number },
62) {
63 override get message(): string {
64 return `${this.path} is ${formatMib(this.sizeBytes)}; a page must be at most ${formatMib(MAX_PAGE_BYTES)}.`;
65 }
66}
67
68export class HtmlRenderImagesNotFoundError extends Schema.TaggedError<HtmlRenderImagesNotFoundError>()(
69 "HtmlRenderImagesNotFoundError",
70 { paths: Schema.Array(Schema.String) },
71) {
72 override get message(): string {
73 return `These local images could not be read: ${this.paths.join(", ")}. Use absolute paths to existing image files, or remove them.`;
74 }
75}
76
77export class HtmlRenderImageTooLargeError extends Schema.TaggedError<HtmlRenderImageTooLargeError>()(
78 "HtmlRenderImageTooLargeError",
79 { path: Schema.String, sizeBytes: Schema.Number },
80) {
81 override get message(): string {
82 return `${this.path} is ${formatMib(this.sizeBytes)}; each local image must be at most ${formatMib(MAX_IMAGE_BYTES)}.`;
83 }
84}
85
86export class HtmlRenderPageTooLargeError extends Schema.TaggedError<HtmlRenderPageTooLargeError>()(
87 "HtmlRenderPageTooLargeError",
88 { sizeBytes: Schema.Number },
89) {
90 override get message(): string {
91 return `With its images inlined the page is ${formatMib(this.sizeBytes)}; the limit is ${formatMib(MAX_PAGE_BYTES)}. Use smaller images.`;
92 }
93}
94
95export class HtmlRenderViewportHeightError extends Schema.TaggedError<HtmlRenderViewportHeightError>()(
96 "HtmlRenderViewportHeightError",
97 { found: Schema.String },
98) {
99 override get message(): string {
100 return `The page uses a viewport height unit (${this.found}). The frame grows to fit the page, so a size that follows the viewport makes it grow again and again. Let content set the height, or use fixed pixel heights.`;
101 }
102}
103
104// Check only stylesheets and style attributes, even inside scripts; skip comments whole.
105// Consume unclosed comments, tags, or quotes through EOF to keep both patterns linear.
106const CSS_SOURCE =
107 /<!--[\s\S]*?(?:-->|$)|<style\b[^>]*(?:>|$)([\s\S]*?)(?:<\/style\s*>|$)|\sstyle\s*=\s*(?:"([^"]*)(?:"|$)|'([^']*)(?:'|$)|([^\s>]+))/gi;
108// The lookbehind skips base64 runs, such as an inlined image that happens to contain "1vh".
109const VIEWPORT_HEIGHT_UNIT = /(?<![\w.+/])(?:\d+(?:\.\d+)?|\.\d+)[sld]?vh(?![\w-])/i;
110
111const rejectViewportHeight = (html: string) => {
112 for (const [, sheet, doubleQuoted, singleQuoted, unquoted] of html.matchAll(CSS_SOURCE)) {
113 const css = sheet ?? doubleQuoted ?? singleQuoted ?? unquoted ?? "";
114 const found = VIEWPORT_HEIGHT_UNIT.exec(css)?.[0];
115 if (found !== undefined) return Effect.fail(new HtmlRenderViewportHeightError({ found }));
116 }
117 return Effect.void;
118};
119
120export class HtmlRenderStoreError extends Schema.TaggedError<HtmlRenderStoreError>()(
121 "HtmlRenderStoreError",
122 { cause: Schema.Defect() },
123) {
124 override get message(): string {
125 return "The HTML render could not be saved.";
126 }
127}
128
129export type HtmlRenderPrepareError =
130 | HtmlRenderImagesNotFoundError
131 | HtmlRenderImageTooLargeError
132 | HtmlRenderPageTooLargeError
133 | HtmlRenderViewportHeightError;
134
135export type HtmlRenderSource = { readonly html: string } | { readonly path: string };
136
137export interface HtmlPreview {
138 readonly png: string;
139 readonly width: number;
140 readonly contentHeight: number;
141 readonly capturedHeight: number;
142 readonly consoleMessages: ReadonlyArray<HeadlessChrome.ConsoleMessage>;
143 readonly missingImages?: ReadonlyArray<string>;
144}
145
146export class HtmlRender extends Context.Service<
147 HtmlRender,
148 {
149 readonly prepare: (html: string) => Effect.Effect<string, HtmlRenderPrepareError>;
150 readonly publish: (
151 input: HtmlRenderSource & {
152 readonly threadId: ThreadId;
153 readonly title: string;
154 readonly height: number;
155 },
156 ) => Effect.Effect<
157 HtmlRenderReference,
158 | HtmlRenderFileError
159 | HtmlRenderFileTooLargeError
160 | HtmlRenderPrepareError
161 | HtmlRenderStoreError
162 >;
163 readonly preview: (
164 input: HtmlRenderSource & {
165 readonly width?: number | undefined;
166 readonly appearance?: ThemeAppearance | undefined;
167 },
168 ) => Effect.Effect<
169 HtmlPreview,
170 | HtmlRenderFileError
171 | HtmlRenderFileTooLargeError
172 | Exclude<HtmlRenderPrepareError, HtmlRenderImagesNotFoundError>
173 | PreviewBrowser.PreviewBrowserInstallError
174 | PreviewBrowser.PreviewBrowserInstallingError
175 | PreviewBrowser.PreviewBrowserUnsupportedError
176 | PreviewBrowserHost.PreviewBrowserHostError
177 | HeadlessChrome.HtmlRenderBrowserError
178 >;
179 }
180>()("t3/htmlRender/HtmlRender") {}
181
182const IMAGE_MIME_TYPES: Record<string, string> = {
183 png: "image/png",
184 jpg: "image/jpeg",
185 jpeg: "image/jpeg",
186 gif: "image/gif",
187 webp: "image/webp",
188 avif: "image/avif",
189 svg: "image/svg+xml",
190 bmp: "image/bmp",
191 ico: "image/x-icon",
192};
193const IMAGE_EXTENSIONS = Object.keys(IMAGE_MIME_TYPES).join("|");
194const ABSOLUTE_PATH = String.raw`(?:/(?!/)|[a-z]:[\\/])`;
195const LOCAL_IMAGE_PATTERN = new RegExp(
196 String.raw`(["'\x60])(${ABSOLUTE_PATH}(?:(?!\1)[^\r\n]){0,2048}?\.(?:${IMAGE_EXTENSIONS}))\1` +
197 String.raw`|url\(\s*(${ABSOLUTE_PATH}[^\s"'\x60()]{0,2048}?\.(?:${IMAGE_EXTENSIONS}))\s*\)`,
198 "gid",
199);
200const HTML_TAG_END = String.raw`(?:[^"'<>]|"[^"]*(?:"|$)|'[^']*(?:'|$))*(?:>|$)`;
201const HTML_COMMENT_CONTEXT = new RegExp(
202 String.raw`<!--(?:-?>|[\s\S]*?(?:--!?>|$))|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript)(?=[\s/>])${HTML_TAG_END}[\s\S]*?(?:</\1(?=[\s/>])${HTML_TAG_END}|$)|<plaintext(?=[\s/>])[\s\S]*$|<[a-z!/]${HTML_TAG_END}`,
203 "gi",
204);
205
206const findLocalImages = (html: string) =>
207 Array.from(
208 // Preserve raw text and quoted attributes; blank only comments without shifting offsets.
209 html
210 .replace(HTML_COMMENT_CONTEXT, (source) =>
211 source.startsWith("<!--") ? source.replace(/[^\r\n]/g, " ") : source,
212 )
213 .matchAll(LOCAL_IMAGE_PATTERN),
214 ).flatMap((match) => {
215 const span = match.indices?.[2] ?? match.indices?.[3];
216 return span ? [{ start: span[0], end: span[1], path: html.slice(span[0], span[1]) }] : [];
217 });
218
219// Inside a JS string literal a Windows path's backslashes are escaped.
220const filePathFor = (reference: string) =>
221 /^[a-z]:/i.test(reference) ? reference.replaceAll("\\\\", "\\") : reference;
222
223const dataUriPrefix = (path: string) =>
224 `data:${IMAGE_MIME_TYPES[path.slice(path.lastIndexOf(".") + 1).toLowerCase()] ?? "application/octet-stream"};base64,`;
225
226const latin1 = (bytes: Uint8Array, start: number, end: number) =>
227 String.fromCharCode(...bytes.subarray(start, end));
228
229// Validate bytes, not filenames, so renamed files or symlinks cannot inline secrets.
230const isImageBytes = (bytes: Uint8Array) => {
231 const head = latin1(bytes, 0, 12);
232 if (
233 head.startsWith("\x89PNG") ||
234 head.startsWith("\xff\xd8\xff") ||
235 head.startsWith("GIF8") ||
236 head.startsWith("\0\0\x01\0") ||
237 (head.startsWith("BM") && head.slice(6, 10) === "\0\0\0\0") ||
238 (head.startsWith("RIFF") && head.slice(8, 12) === "WEBP") ||
239 /^ftyp(?:avif|avis|mif1)$/.test(head.slice(4, 12))
240 ) {
241 return true;
242 }
243 return hasSvgRoot(new TextDecoder().decode(bytes.subarray(0, 4096)));
244};
245
246const after = (text: string, token: string, from: number) => {
247 const at = text.indexOf(token, from);
248 return at === -1 ? -1 : at + token.length;
249};
250
251const hasSvgRoot = (text: string) => {
252 let at = 0;
253 while (at !== -1) {
254 while (/\s/.test(text.charAt(at))) at += 1;
255 if (text.startsWith("<?", at)) at = after(text, "?>", at + 2);
256 else if (text.startsWith("<!--", at)) at = after(text, "-->", at + 4);
257 else if (text.slice(at, at + 9).toLowerCase() === "<!doctype") at = afterDoctype(text, at + 9);
258 // XML names are case-sensitive, and only these characters can end one here.
259 else return /^<svg[ \t\r\n/>]/.test(text.slice(at, at + 5));
260 }
261 return false;
262};
263
264const afterDoctype = (text: string, from: number) => {
265 let inSubset = false;
266 let at = from;
267 while (at !== -1 && at < text.length) {
268 const char = text[at];
269 if (char === '"' || char === "'") at = after(text, char, at + 1);
270 else if (inSubset && text.startsWith("<!--", at)) at = after(text, "-->", at + 4);
271 else if (inSubset && text.startsWith("<?", at)) at = after(text, "?>", at + 2);
272 else if (char === ">" && !inSubset) return at + 1;
273 else {
274 if (char === "[") inSubset = true;
275 else if (char === "]") inSubset = false;
276 at += 1;
277 }
278 }
279 return -1;
280};
281
282const inlineLocalImages = Effect.fn("HtmlRender.inlineLocalImages")(function* (html: string) {
283 const fileSystem = yield* FileSystem.FileSystem;
284 const references = findLocalImages(html);
285 const files = yield* Effect.forEach(
286 [...new Set(references.map((reference) => reference.path))],
287 (path) =>
288 fileSystem.stat(filePathFor(path)).pipe(
289 Effect.map((info) => ({
290 path,
291 size: info.type === "File" ? Number(info.size) : undefined,
292 })),
293 Effect.orElseSucceed(() => ({ path, size: undefined })),
294 ),
295 { concurrency: 8 },
296 );
297 const oversized = files.find((file) => file.size !== undefined && file.size > MAX_IMAGE_BYTES);
298 if (oversized?.size !== undefined) {
299 return yield* new HtmlRenderImageTooLargeError({
300 path: oversized.path,
301 sizeBytes: oversized.size,
302 });
303 }
304 const sizes = new Map(files.map((file) => [file.path, file.size]));
305 const pageBytes = references.reduce((total, reference) => {
306 const size = sizes.get(reference.path);
307 return size === undefined
308 ? total
309 : total +
310 dataUriPrefix(reference.path).length +
311 Math.ceil(size / 3) * 4 -
312 Buffer.byteLength(reference.path);
313 }, Buffer.byteLength(html));
314 if (pageBytes > MAX_PAGE_BYTES) {
315 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: pageBytes });
316 }
317 // Files can grow after stat; bound each read and stop when accumulated images cannot fit.
318 let readBytes = 0;
319 const images = yield* Effect.forEach(
320 files.filter((file) => file.size !== undefined),
321 (file) =>
322 Effect.gen(function* () {
323 const read = yield* fileSystem
324 .stream(filePathFor(file.path), { bytesToRead: MAX_IMAGE_BYTES + 1 })
325 .pipe(Stream.mkUint8Array, Effect.option);
326 if (Option.isNone(read) || !isImageBytes(read.value)) return [];
327 const bytes = read.value;
328 if (bytes.byteLength > MAX_IMAGE_BYTES) {
329 return yield* new HtmlRenderImageTooLargeError({
330 path: file.path,
331 sizeBytes: bytes.byteLength,
332 });
333 }
334 readBytes += Math.ceil(bytes.byteLength / 3) * 4;
335 if (readBytes > MAX_PAGE_BYTES) {
336 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: readBytes });
337 }
338 return [{ path: file.path, bytes }];
339 }),
340 { concurrency: 4 },
341 ).pipe(Effect.map((entries) => entries.flat()));
342 const dataUris = new Map(
343 images.map(
344 (image) =>
345 [
346 image.path,
347 dataUriPrefix(image.path) + Buffer.from(image.bytes).toString("base64"),
348 ] as const,
349 ),
350 );
351 const parts: Array<string> = [];
352 let cursor = 0;
353 for (const reference of references) {
354 const dataUri = dataUris.get(reference.path);
355 if (dataUri === undefined) continue;
356 parts.push(html.slice(cursor, reference.start), dataUri);
357 cursor = reference.end;
358 }
359 parts.push(html.slice(cursor));
360 const inlined = parts.join("");
361 const inlinedBytes = Buffer.byteLength(inlined);
362 if (inlinedBytes > MAX_PAGE_BYTES) {
363 return yield* new HtmlRenderPageTooLargeError({ sizeBytes: inlinedBytes });
364 }
365 return {
366 html: inlined,
367 missing: files.filter((file) => !dataUris.has(file.path)).map((file) => file.path),
368 };
369});
370
371const MIN_PREVIEW_WIDTH = 240;
372const MAX_PREVIEW_WIDTH = 1_600;
373const MAX_CONCURRENT_BROWSERS = 2;
374const MEASURE_TIMEOUT = "6 seconds";
375
376const MEASURE_FRAGMENT = htmlRenderThemeFragment(
377 htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark", HTML_RENDER_MEASURE_FONTS),
378);
379
380const make = Effect.gen(function* () {
381 const fileSystem = yield* FileSystem.FileSystem;
382 const path = yield* Path.Path;
383 const config = yield* ServerConfig.ServerConfig;
384 const isServerInternalPath = yield* makeIsServerInternalPath;
385 const previewBrowser = yield* PreviewBrowser.PreviewBrowser;
386 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
387 const services = yield* Effect.context<
388 FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
389 >();
390 const browsers = yield* Semaphore.make(MAX_CONCURRENT_BROWSERS);
391 // Keep Chrome sandboxed unless explicitly disabled; root must opt out to run.
392 const noSandbox = PreviewBrowserHost.sandboxDisabled(yield* HostProcess.Environment);
393 // sudo resets the environment, so the command has to name this server's home.
394 const setupCommand = yield* resolveRootCliCommand(PreviewBrowserHost.SETUP_SUBCOMMAND, [
395 "--base-dir",
396 config.baseDir,
397 ]);
398
399 const launching = <A>(
400 executable: string,
401 run: (noSandbox: boolean) => Effect.Effect<A, HeadlessChrome.HtmlRenderBrowserError>,
402 ) =>
403 browsers.withPermits(1)(
404 run(noSandbox).pipe(
405 Effect.catchTags({
406 HtmlRenderBrowserError: (error) =>
407 error.output === undefined
408 ? Effect.fail(error)
409 : PreviewBrowserHost.diagnoseLaunchFailure({
410 executable,
411 setupCommand,
412 output: error.output,
413 }).pipe(
414 Effect.provideContext(services),
415 Effect.flatMap((hostError) => Effect.fail(hostError ?? error)),
416 ),
417 }),
418 ),
419 );
420
421 const measure = Effect.fn("HtmlRender.measure")(
422 function* (html: string) {
423 const executable = yield* previewBrowser.installed;
424 if (Option.isNone(executable)) return undefined;
425 const heights = yield* launching(executable.value, (noSandbox) =>
426 HeadlessChrome.measureHtmlHeights({
427 executable: executable.value,
428 noSandbox,
429 html,
430 widths: HTML_RENDER_MEASURE_WIDTHS,
431 urlFragment: MEASURE_FRAGMENT,
432 }).pipe(Effect.provideContext(services)),
433 ).pipe(
434 Effect.timeoutOrElse({
435 duration: MEASURE_TIMEOUT,
436 orElse: () =>
437 Effect.fail(
438 new HeadlessChrome.HtmlRenderBrowserError({
439 reason: `measuring took longer than ${MEASURE_TIMEOUT}`,
440 }),
441 ),
442 }),
443 );
444 return heights.toSorted(([left], [right]) => left - right);
445 },
446 Effect.catch((cause) =>
447 Effect.logWarning("Could not measure an HTML render; publishing it without heights.", {
448 cause,
449 }).pipe(Effect.as(undefined)),
450 ),
451 );
452
453 const readPageFile = Effect.fn("HtmlRender.readPageFile")(function* (filePath: string) {
454 const unreadable = new HtmlRenderFileError({ path: filePath });
455 if (!path.isAbsolute(filePath) || isNetworkPath(filePath)) return yield* unreadable;
456 // Check the resolved file, so a symlink named .html cannot reach another file.
457 const realPath = yield* fileSystem
458 .realPath(filePath)
459 .pipe(Effect.mapError((cause) => new HtmlRenderFileError({ path: filePath, cause })));
460 if (!HTML_FILE_EXTENSION.test(realPath) || (yield* isServerInternalPath(realPath))) {
461 return yield* unreadable;
462 }
463 // Open without following links and recheck the path, so a link or FIFO swapped in is refused.
464 const html = yield* Effect.scoped(
465 Effect.gen(function* () {
466 const file = yield* openMediaFile(realPath).pipe(
467 Effect.mapError((cause) => new HtmlRenderFileError({ path: filePath, cause })),
468 );
469 // Unlike client reads, the caller may be sandboxed: a second hard link could give any
470 // file an .html name.
471 if (file === null || file.info.nlink !== 1n) return yield* unreadable;
472 if (file.info.size > BigInt(MAX_PAGE_BYTES)) {
473 return yield* new HtmlRenderFileTooLargeError({
474 path: filePath,
475 sizeBytes: Number(file.info.size),
476 });
477 }
478 // One read may return fewer bytes, so fill up to the checked size; growth past it is ignored.
479 return yield* Effect.tryPromise({
480 try: async () => {
481 const buffer = Buffer.alloc(Number(file.info.size));
482 let filled = 0;
483 while (filled < buffer.length) {
484 const { bytesRead } = await file.handle.read(buffer, filled, buffer.length - filled);
485 if (bytesRead === 0) break;
486 filled += bytesRead;
487 }
488 return buffer.toString("utf8", 0, filled);
489 },
490 catch: (cause) => new HtmlRenderFileError({ path: filePath, cause }),
491 });
492 }),
493 );
494 return HTML_DOCUMENT_START.test(html) ? html : yield* unreadable;
495 });
496
497 const readSource = (input: HtmlRenderSource) =>
498 "path" in input ? readPageFile(input.path) : Effect.succeed(input.html);
499
500 // The bootstrap goes in first so its head scan never runs over inlined image data.
501 const inline = (html: string) =>
502 inlineLocalImages(injectHtmlRenderBootstrap(html)).pipe(Effect.provideContext(services));
503
504 const prepare = Effect.fn("HtmlRender.prepare")(function* (html: string) {
505 yield* rejectViewportHeight(html);
506 const inlined = yield* inline(html);
507 if (inlined.missing.length > 0) {
508 return yield* new HtmlRenderImagesNotFoundError({ paths: inlined.missing });
509 }
510 return inlined.html;
511 });
512
513 const publish = Effect.fn("HtmlRender.publish")(function* (
514 input: HtmlRenderSource & {
515 readonly threadId: ThreadId;
516 readonly title: string;
517 readonly height: number;
518 },
519 ) {
520 const source = yield* readSource(input);
521 const html = yield* prepare(source);
522 // The `-html` id suffix makes the asset route serve it as a sandboxed text/html document.
523 const attachmentId = createAttachmentId(input.threadId, "html");
524 const filePath =
525 attachmentId === null
526 ? null
527 : resolveAttachmentRelativePath({
528 attachmentsDir: config.attachmentsDir,
529 relativePath: `${attachmentId}.html`,
530 });
531 if (attachmentId === null || filePath === null) {
532 return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") });
533 }
534 const baseReference: HtmlRenderReference = {
535 attachmentId,
536 title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML",
537 height: clampHtmlRenderHeight(input.height),
538 };
539 return yield* fileSystem.writeFileString(filePath, html).pipe(
540 Effect.mapError((cause) => new HtmlRenderStoreError({ cause })),
541 Effect.uninterruptible,
542 Effect.andThen(measure(html)),
543 Effect.andThen((heights) => {
544 const reference: HtmlRenderReference = {
545 ...baseReference,
546 ...(heights === undefined ? {} : { heights }),
547 };
548 return mcpSessions
549 .recordHtmlRender(
550 input.threadId,
551 {
552 html: source,
553 path: "path" in input ? input.path : undefined,
554 title: input.title,
555 height: input.height,
556 },
557 reference,
558 )
559 .pipe(Effect.as(reference));
560 }),
561 // An interrupted publish must leave neither an attachment nor a recoverable reference.
562 Effect.onError(() =>
563 Effect.all(
564 [
565 fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore),
566 mcpSessions.takeHtmlRender(input.threadId, input, baseReference).pipe(Effect.ignore),
567 ],
568 { discard: true },
569 ),
570 ),
571 );
572 });
573
574 const preview = Effect.fn("HtmlRender.preview")(function* (
575 input: HtmlRenderSource & {
576 readonly width?: number | undefined;
577 readonly appearance?: ThemeAppearance | undefined;
578 },
579 ) {
580 const width = Math.min(
581 MAX_PREVIEW_WIDTH,
582 Math.max(MIN_PREVIEW_WIDTH, Math.round(input.width ?? HTML_RENDER_COLUMN_WIDTH)),
583 );
584 const appearance = input.appearance ?? "dark";
585 const source = yield* readSource(input);
586 yield* rejectViewportHeight(source);
587 const inlined = yield* inline(source);
588 const executable = yield* previewBrowser.executable;
589 const theme = htmlRenderTheme(
590 appearance === "light" ? T3_CODE_LIGHT_THEME_COLORS : T3_CODE_DARK_THEME_COLORS,
591 appearance,
592 HTML_RENDER_MEASURE_FONTS,
593 );
594 const screenshot = yield* launching(executable, (noSandbox) =>
595 HeadlessChrome.captureHtmlScreenshot({
596 executable,
597 noSandbox,
598 html: inlined.html,
599 width,
600 urlFragment: htmlRenderThemeFragment(theme),
601 appearance,
602 }).pipe(Effect.provideContext(services)),
603 );
604 return {
605 ...screenshot,
606 width,
607 ...(inlined.missing.length === 0 ? {} : { missingImages: inlined.missing }),
608 } satisfies HtmlPreview;
609 });
610
611 return HtmlRender.of({ prepare, publish, preview });
612});
613
614export const layer = Layer.effect(HtmlRender, make);