From 10a37c9ce768275d63d42e46aeb492aff89beda4 Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Thu, 5 Nov 2026 20:15:57 -0800 Subject: [PATCH 1/6] fix(screenshot): recover from a wedged Chromium and bound every render (#456) * fix(screenshot): recover from a wedged Chromium and bound every render On 2026-11-05 prod's one shared headless Chromium stopped creating pages from 17:41 UTC: its DevTools socket stayed open, so `connected` stayed true, and every render (frame images, MCP screenshots, the resident's checks, exports, imports) waited out puppeteer's 30s target timeout for two hours until a manual restart. getBrowser only ever checked `connected`, nothing bounded concurrent pages, and a stuck DevTools call held its caller for puppeteer's default 180s. server/renderBrowser.ts now owns the browser's lifecycle: - a gate of RENDER_CONCURRENCY pages (default 4), background thumbnails capped at 2 and served after waiting agents, with a bounded, timed queue that refuses with RendererBusyError (HTTP 503 + Retry-After) - opening a page has a 15s deadline; a browser that cannot open one is killed with its process group (a stalled graceful close no longer prevents the SIGKILL) and the open retried once on one shared replacement launch - a render that fails like a browser failure runs a health probe outside the gate; a browser that fails it is killed and the render rerun once, a frame that is merely slow is not retried - every page has a 120s lease, so a stuck caller cannot starve the gate - browsers are recycled after 500 pages or an hour, drained first - DevTools commands time out at 60s instead of 180s - screenshots are capped at 50M device pixels (renderLimits.ts); the MCP tool says when it cropped - GET /healthz/renderer reports kills, queue depth, lastOpenedAt and failed opens in a row for an uptime check Builds on kgoedecke/doop#399 (deadline, retry on a fresh launch) and fixes its two open review findings. Co-Authored-By: Claude Opus 5.5 (1M context) * fix(screenshot): address review on the render pool - importPage gives its capture page back before opening the preview page, so view_website and import_webpage no longer wait on themselves when RENDER_CONCURRENCY=1. - Tall renders keep the full frame height as the viewport (100vh, height media queries and bottom-fixed elements lay out as on the canvas); the pixel budget only bounds the captured clip. - A page whose context will not close kills its browser instead of handing its slot to the next render while it may still be alive. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) (cherry picked from commit 8bfec4dffbf2f862cca00278bcf7a19516b9d38a) --- .context/TECHSTACK.md | 13 + .env.example | 3 + server/env.ts | 2 + server/importer.ts | 12 +- server/index.ts | 25 +- server/mcp.ts | 9 +- server/renderBrowser.ts | 555 ++++++++++++++++++++++++++++++++++++ server/renderLimits.ts | 16 ++ server/screenshot.ts | 223 ++++++++------- server/thumbs.ts | 2 + tests/importer.test.ts | 5 + tests/renderBrowser.test.ts | 343 ++++++++++++++++++++++ 12 files changed, 1095 insertions(+), 113 deletions(-) create mode 100644 server/renderBrowser.ts create mode 100644 server/renderLimits.ts create mode 100644 tests/renderBrowser.test.ts diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index e73283998..9e7006872 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -247,6 +247,19 @@ data-doop-webfonts>` for the roster families the frame names and does not load i fallback. Tests: `exportScale.test.ts`, the scale and SVG cases in `frameExport.test.ts`, `frameRasterBrowser.test.ts` (the SVG opened as a page in a wide window), `exportOptions.test.tsx` and `mcpPdfExport.test.ts`. +- Server-side renderer (`server/renderBrowser.ts`, used by `server/screenshot.ts`): every headless + Chromium page (frame images, MCP screenshots, the resident's checks, PDF + exports, website imports) goes through one gate of `RENDER_CONCURRENCY` pages (default 4; + background thumbnails get at most 2, a waiting agent goes before a waiting thumbnail), a bounded + queue that refuses with `RendererBusyError` (HTTP 503 + Retry-After) and a lease that closes a + page held past 120s. A browser that cannot open a page within 15s is killed with its process + group and the open retried once on a fresh launch; a render that fails like a browser failure + runs a health probe outside the gate and is retried once if the probe kills the browser; a + browser is recycled after 500 pages or an hour. DevTools commands time out at 60s, not 180s. + Screenshots are capped at 50M device px (`server/renderLimits.ts`; MCP says when it cropped). + `GET /healthz/renderer` reports the counters (`kills`, `lastOpenedAt`, `failedOpensInARow`, + queue depth) for an uptime check. Context: the 2026-11-05 wedge, where one browser stopped + making pages for two hours. Tests: `renderBrowser.test.ts`. - `pdf-lib` 1.17.1 - joins the vector PDF export (`server/pdfExport.ts`): headless Chrome prints each frame onto a page of its own size (inside an iframe of the frame's size, as the canvas shows it, so content taller than the frame is clipped rather than paginated: bare, Chrome moved a block diff --git a/.env.example b/.env.example index 02b4a5c63..733c43143 100644 --- a/.env.example +++ b/.env.example @@ -309,6 +309,9 @@ #CHROME_PATH= # Set to 1 to pass --no-sandbox (needed in most containers; the Dockerfile does). #CHROME_NO_SANDBOX= +# Pages the shared Chromium renders at once (default 4); more wait in a +# bounded queue and are refused with a 503 when it is full. +#RENDER_CONCURRENCY=4 # ------------------------------------------------- analytics (optional, OFF) # PostHog product analytics + session replay. Entirely disabled unless diff --git a/server/env.ts b/server/env.ts index 715fe491d..3231e7033 100644 --- a/server/env.ts +++ b/server/env.ts @@ -232,6 +232,8 @@ const schema = { /* ---------------------------------------------------- screenshots */ CHROME_PATH: str({ default: undefined }), CHROME_NO_SANDBOX: bool({ default: false }), + /* pages the shared Chromium renders at once (renderBrowser.ts) */ + RENDER_CONCURRENCY: nonNegativeInt({ default: 4 }), /* ------------------------------------------------------ analytics */ POSTHOG_KEY: str({ default: undefined }), diff --git a/server/importer.ts b/server/importer.ts index 83bf75356..b9a555b10 100644 --- a/server/importer.ts +++ b/server/importer.ts @@ -510,6 +510,12 @@ export async function importPage(rawUrl: string, options: { includePreview?: boo else await assertPublicNetworkUrl(requestedUrl) const isolated = await openIsolatedPage() const { page } = isolated + let captureOpen = true + const releaseCapture = async () => { + if (!captureOpen) return + captureOpen = false + await isolated.close() + } try { await guardPublicPageRequests(page) await page.setViewport({ width: VIEWPORT_WIDTH, height: 900 }) @@ -655,6 +661,10 @@ export async function importPage(rawUrl: string, options: { includePreview?: boo throw new WebsiteCaptureUnavailableError('The captured webpage is too large to import safely') } + /* the capture is done: give its render slot back before the preview asks + for one, or a one-slot renderer waits on itself */ + await releaseCapture() + let preview: ImportedPage['preview'] let renderedHeight = snap.height if (options.includePreview) { @@ -736,6 +746,6 @@ export async function importPage(rawUrl: string, options: { includePreview?: boo if (error instanceof WebsiteCaptureUnavailableError) throw error throw new WebsiteCaptureUnavailableError('Doop could not finish rendering the webpage HTML') } finally { - await isolated.close() + await releaseCapture() } } diff --git a/server/index.ts b/server/index.ts index 274d08e27..4ea3b3e6e 100644 --- a/server/index.ts +++ b/server/index.ts @@ -59,6 +59,7 @@ import { encryptionConfigured } from './secretBox.ts' import * as authSchema from './db/auth-schema.ts' import * as persist from './db/persist.ts' import { handleMcpRequest } from './mcp.ts' +import { RendererBusyError } from './renderBrowser.ts' import { getAsset, reconcileAssetRefs, @@ -359,6 +360,14 @@ app.set('trust proxy', 1) app.get('/healthz', (_req, res) => res.json({ ok: true })) +/* The headless renderer's counters, for an uptime check that alerts when + renders stop (kills climbing, a queue that never drains). Lazy, so a boot + never pays for puppeteer-core just to answer it. */ +app.get('/healthz/renderer', async (_req, res) => { + const { rendererStatus } = await import('./screenshot.ts') + res.json(rendererStatus()) +}) + /* ------------------------------------------------------------------ */ /* PostHog relay: the client sends analytics + session-replay traffic */ /* to this origin (/relay/...) and we forward it, so ad blockers that */ @@ -424,6 +433,16 @@ app.use('/relay', async (req, res) => { /* render dispatch live in previews.ts — this route is HTTP only. */ /* ------------------------------------------------------------------ */ +/** A full render queue is a 503 with Retry-After, not a 500: the renderer is + * healthy, only busy, and the client should come back in a few seconds. */ +function sendRenderFailure(res: express.Response, error: unknown, fallback = 'render failed') { + if (error instanceof RendererBusyError) { + res.set('Retry-After', '10') + return res.status(503).json({ error: error.message }) + } + return res.status(500).json({ error: error instanceof Error ? error.message : fallback }) +} + app.get('/i/:id.:ext', async (req, res) => { const { id, ext } = req.params as { id: string; ext: string } if (ext !== 'png' && ext !== 'jpg') return res.status(404).end() @@ -450,7 +469,7 @@ app.get('/i/:id.:ext', async (req, res) => { !!(await auth.api.getSession({ headers: fromNodeHeaders(req.headers) }).catch(() => null)), }) } catch (e) { - return res.status(500).json({ error: e instanceof Error ? e.message : 'render failed' }) + return sendRenderFailure(res, e) } if (result.status === 'rate-limited') { res.set('Retry-After', '60') @@ -2463,7 +2482,7 @@ app.get('/api/frames/:id/screenshot.png', async (req, res) => { const png = await renderFrame(frame, fitExportScale(frame, parseExportScale(req.query.scale) ?? 1)) res.type('png').send(png) } catch (e) { - res.status(500).json({ error: e instanceof Error ? e.message : 'render failed' }) + sendRenderFailure(res, e) } }) @@ -2494,7 +2513,7 @@ app.get('/api/canvases/:id/export.pdf', async (req, res) => { return res.send(buf) } catch (e) { if (e instanceof pdf.PdfRendererUnavailableError) return res.status(503).json({ error: e.message }) - return res.status(500).json({ error: e instanceof Error ? e.message : 'PDF export failed' }) + return sendRenderFailure(res, e, 'PDF export failed') } }) diff --git a/server/mcp.ts b/server/mcp.ts index 72ada16d7..96084767f 100644 --- a/server/mcp.ts +++ b/server/mcp.ts @@ -34,6 +34,7 @@ import * as workspaces from './workspaces.ts' import { auth, getUserName, isBanned } from './auth.ts' import { capture, captureThrottled } from './analytics.ts' import { renderFrame } from './screenshot.ts' +import { renderedHeight } from './renderLimits.ts' import { MAX_PDF_FRAMES, PDF_UNAVAILABLE_MESSAGE, @@ -163,6 +164,12 @@ function withEscapeNote(work: Promise, ms: number, step: string): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new RenderTimeoutError(step, ms)), ms) + work.then( + (value) => { + clearTimeout(timer) + resolve(value) + }, + (error: unknown) => { + clearTimeout(timer) + reject(error) + }, + ) + }) +} + +/* ------------------------------------------------------------------ gate */ + +interface Waiter { + priority: RenderPriority + admit: () => void + refuse: (error: Error) => void +} + +/** Counting semaphore with two priorities and a bounded, timed queue. */ +export class RenderGate { + private active = 0 + private background = 0 + private readonly waiting: Waiter[] = [] + + constructor( + private readonly tuning: Pick, + ) {} + + get stats() { + return { active: this.active, background: this.background, queued: this.waiting.length } + } + + /** Resolves with the slot's release function, which is safe to call twice. */ + acquire(priority: RenderPriority): Promise<() => void> { + if (this.canAdmit(priority) && !this.waiting.some((w) => this.outranks(w, priority))) + return Promise.resolve(this.take(priority)) + if (this.waiting.length >= this.tuning.maxQueued) + return Promise.reject(new RendererBusyError(`${this.waiting.length} renders already queued`)) + return new Promise((resolve, reject) => { + const waiter: Waiter = { + priority, + admit: () => { + clearTimeout(timer) + resolve(this.take(priority)) + }, + refuse: reject, + } + const timer = setTimeout(() => { + this.remove(waiter) + reject(new RendererBusyError(`no render slot within ${this.tuning.queueTimeoutMs}ms`)) + }, this.tuning.queueTimeoutMs) + timer.unref?.() + this.waiting.push(waiter) + }) + } + + private canAdmit(priority: RenderPriority): boolean { + if (this.active >= this.tuning.maxConcurrent) return false + return priority === 'interactive' || this.background < this.tuning.maxBackground + } + + /** an interactive waiter goes before background work, whatever the order */ + private outranks(waiter: Waiter, priority: RenderPriority): boolean { + return priority === 'background' || waiter.priority === 'interactive' + } + + private take(priority: RenderPriority): () => void { + this.active++ + if (priority === 'background') this.background++ + let released = false + return () => { + if (released) return + released = true + this.active-- + if (priority === 'background') this.background-- + this.pump() + } + } + + private pump(): void { + while (this.waiting.length) { + const next = + this.waiting.find((w) => w.priority === 'interactive' && this.canAdmit('interactive')) ?? + this.waiting.find((w) => this.canAdmit(w.priority)) + if (!next) return + this.remove(next) + next.admit() + } + } + + private remove(waiter: Waiter): void { + const at = this.waiting.indexOf(waiter) + if (at >= 0) this.waiting.splice(at, 1) + } +} + +/* --------------------------------------------------------------- browser */ + +type GenerationState = 'live' | 'draining' | 'dead' + +interface Generation { + id: number + browser: Promise + resolved: Browser | null + launchedAt: number + pagesOpen: number + pagesServed: number + state: GenerationState + probing: Promise | null +} + +export interface RenderPage { + page: Page + /** which browser launch served the page (tests and logs) */ + generation: number + /** closes the page's context and returns its slot; bounded, idempotent */ + close: () => Promise +} + +export interface PageOptions { + priority?: RenderPriority +} + +export interface Renderer { + openPage(options?: PageOptions): Promise + /** open a page, run `work` under `timeoutMs`, always close; a browser + * failure that kills the browser is retried once on a fresh launch */ + withPage(step: string, timeoutMs: number, work: (page: Page) => Promise, options?: PageOptions): Promise + /** the live browser, launched if need be (tests and one-off callers) */ + browser(): Promise + status(): RendererStatus + shutdown(): Promise +} + +export interface RendererStatus { + generation: number | null + state: GenerationState | null + pagesOpen: number + pagesServed: number + ageMs: number + active: number + background: number + queued: number + kills: number + recycles: number + /** when a page last opened; an uptime check alerts when this goes stale + * while the queue is not empty */ + lastOpenedAt: number | null + /** page opens that failed in a row (reset by the next success) */ + failedOpensInARow: number +} + +export interface RendererDeps { + launch: () => Promise + tuning?: Partial + now?: () => number + log?: Pick +} + +export function createRenderer(deps: RendererDeps): Renderer { + const tuning: RendererTuning = { ...DEFAULT_RENDERER_TUNING, ...deps.tuning } + const now = deps.now ?? Date.now + const log = deps.log ?? console + const gate = new RenderGate(tuning) + let current: Generation | null = null + let sequence = 0 + let kills = 0 + let recycles = 0 + let lastOpenedAt: number | null = null + let failedOpensInARow = 0 + + function launchGeneration(): Generation { + const generation: Generation = { + id: ++sequence, + browser: deps.launch(), + resolved: null, + launchedAt: now(), + pagesOpen: 0, + pagesServed: 0, + state: 'live', + probing: null, + } + current = generation + generation.browser.then( + (browser) => { + generation.resolved = browser + if (generation.state === 'dead') void terminate(browser) + }, + () => { + /* a failed launch (a cold start past its timeout) must not be handed + to every later caller: the next one launches again */ + generation.state = 'dead' + if (current === generation) current = null + }, + ) + return generation + } + + function outlived(generation: Generation): boolean { + return ( + generation.pagesServed >= tuning.maxPagesPerBrowser || now() - generation.launchedAt >= tuning.maxBrowserAgeMs + ) + } + + function liveGeneration(): Generation { + const generation = current + if (generation && generation.state === 'live') { + if (generation.resolved && !generation.resolved.connected) { + kill(generation, 'the browser disconnected') + } else if (outlived(generation)) { + recycles++ + drain(generation) + } else { + return generation + } + } + return launchGeneration() + } + + /** stop handing the browser out; close it once its last page is done */ + function drain(generation: Generation): void { + generation.state = 'draining' + if (current === generation) current = null + if (generation.pagesOpen === 0) retire(generation) + } + + /** a wedged or disconnected browser: kill it now, pages and all */ + function kill(generation: Generation, reason: string): void { + if (generation.state === 'dead') return + kills++ + log.error(`[renderer] browser #${generation.id} killed: ${reason}`) + retire(generation) + } + + function retire(generation: Generation): void { + generation.state = 'dead' + if (current === generation) current = null + if (generation.resolved) void terminate(generation.resolved) + } + + async function terminate(browser: Browser): Promise { + const child = browser.process() + await withDeadline(browser.close(), tuning.closeTimeoutMs, 'closing the browser').catch(() => {}) + if (child && child.exitCode === null && child.signalCode === null) killProcessTree(child) + } + + function releasePage(generation: Generation): void { + generation.pagesOpen-- + if (generation.state === 'draining' && generation.pagesOpen === 0) retire(generation) + } + + /** Is the browser still able to make a page? Runs outside the gate, since + * the slots may all be held by the renders that stalled. Single-flight per + * browser; kills it when the answer is no. */ + function checkHealth(generation: Generation, cause: unknown): Promise { + if (generation.state === 'dead') return Promise.resolve(false) + generation.probing ??= probe(generation) + .then((healthy) => { + if (!healthy) kill(generation, `failed its health probe after: ${describe(cause)}`) + return healthy + }) + .finally(() => { + generation.probing = null + }) + return generation.probing + } + + async function probe(generation: Generation): Promise { + const attempt = (async () => { + const browser = await generation.browser + const context = await browser.createBrowserContext() + try { + const page = await context.newPage() + await page.evaluate('1') + } finally { + void closeContext(context) + } + })() + return withDeadline(attempt, tuning.probeTimeoutMs, 'the browser health probe').then( + () => true, + () => false, + ) + } + + /** Resolves true once the context is gone; false when closing threw or + * outlived its deadline, i.e. the page may still be alive. */ + function closeContext(context: BrowserContext): Promise { + return withDeadline(context.close(), tuning.closeTimeoutMs, 'closing the page').then( + () => true, + () => false, + ) + } + + async function openOn(generation: Generation): Promise<{ context: BrowserContext; page: Page }> { + const browser = await generation.browser + const opening = browser.createBrowserContext() + const context = await withDeadline(opening, tuning.openTimeoutMs, 'opening a browser context').catch( + (error: unknown) => { + /* a context that arrives after its deadline must not leak */ + opening.then( + (late) => void closeContext(late), + () => {}, + ) + throw error + }, + ) + try { + const page = await withDeadline(context.newPage(), tuning.openTimeoutMs, 'opening a page') + return { context, page } + } catch (error) { + void closeContext(context) + throw error + } + } + + async function openOnLiveBrowser(): Promise<{ generation: Generation; context: BrowserContext; page: Page }> { + const generation = liveGeneration() + generation.pagesOpen++ + generation.pagesServed++ + try { + const opened = await openOn(generation) + lastOpenedAt = now() + failedOpensInARow = 0 + return { generation, ...opened } + } catch (error) { + failedOpensInARow++ + releasePage(generation) + /* a healthy browser opens a page in milliseconds, and the gate keeps it + from being swamped: failing to open one is the wedge itself */ + if (isBrowserFailure(error)) kill(generation, `could not open a page: ${describe(error)}`) + throw error + } + } + + async function openPage(options: PageOptions = {}): Promise { + const release = await gate.acquire(options.priority ?? 'interactive') + let opened: Awaited> + try { + opened = await openOnLiveBrowser().catch((error: unknown) => { + if (!isBrowserFailure(error)) throw error + log.warn(`[renderer] retrying on a fresh browser after: ${describe(error)}`) + return openOnLiveBrowser() + }) + } catch (error) { + release() + throw error + } + const { generation, context, page } = opened + let closing: Promise | null = null + const close = () => { + closing ??= (async () => { + clearTimeout(lease) + const closed = await closeContext(context) + releasePage(generation) + /* a page that would not close is still holding the browser; killing + the browser is the only way to be sure it is gone before its slot + goes to the next render */ + if (!closed) kill(generation, 'a page would not close') + release() + })() + return closing + } + const lease = setTimeout(() => { + log.warn(`[renderer] a page on browser #${generation.id} outlived its ${tuning.leaseMs}ms lease; closing it`) + void close() + void checkHealth(generation, new RenderTimeoutError('a page lease', tuning.leaseMs)) + }, tuning.leaseMs) + lease.unref?.() + return { page, generation: generation.id, close } + } + + async function withPage( + step: string, + timeoutMs: number, + work: (page: Page) => Promise, + options: PageOptions = {}, + ): Promise { + for (let attempt = 0; ; attempt++) { + const handle = await openPage(options) + let failure: unknown + try { + return await withDeadline(work(handle.page), timeoutMs, step) + } catch (error) { + failure = error + } finally { + await handle.close() + } + if (!isBrowserFailure(failure) || attempt > 0) throw failure + const generation = findGeneration(handle.generation) + const healthy = generation ? await checkHealth(generation, failure) : false + /* a healthy browser means the frame itself is too slow: no retry */ + if (healthy) throw failure + log.warn(`[renderer] ${step}: retrying on a fresh browser after: ${describe(failure)}`) + } + } + + /* only the current generation can be probed; an older one is already + draining or dead, and its failure says nothing about the live one */ + function findGeneration(id: number): Generation | null { + return current && current.id === id ? current : null + } + + return { + openPage, + withPage, + browser: () => liveGeneration().browser, + status: () => ({ + generation: current?.id ?? null, + state: current?.state ?? null, + pagesOpen: current?.pagesOpen ?? 0, + pagesServed: current?.pagesServed ?? 0, + ageMs: current ? now() - current.launchedAt : 0, + ...gate.stats, + kills, + recycles, + lastOpenedAt, + failedOpensInARow, + }), + shutdown: async () => { + const generation = current + if (!generation) return + retire(generation) + await generation.browser.then(terminate, () => {}) + }, + } +} + +interface ChildLike { + pid?: number + kill: (signal?: NodeJS.Signals) => boolean +} + +/** Chromium's renderers and GPU process are children of the browser + * process; puppeteer launches it as a process-group leader off Windows, so + * the group goes down together and no orphaned renderer keeps its memory. */ +function killProcessTree(child: ChildLike): void { + try { + if (process.platform !== 'win32' && child.pid) { + process.kill(-child.pid, 'SIGKILL') + return + } + } catch { + /* not a group leader: fall through to the process itself */ + } + try { + child.kill('SIGKILL') + } catch { + /* already gone */ + } +} + +function describe(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} diff --git a/server/renderLimits.ts b/server/renderLimits.ts new file mode 100644 index 000000000..c3dbf8e5f --- /dev/null +++ b/server/renderLimits.ts @@ -0,0 +1,16 @@ +import type { Frame } from '../shared/types.ts' + +/** The device pixels one screenshot may hold. A 1440px frame at 2x keeps + * about 8,600 CSS px of height; past that the image is cut at the bottom + * rather than asking Chromium for a bitmap big enough to stall the browser + * every other render shares. */ +export const MAX_RENDER_PIXELS = 50_000_000 + +/** The CSS px height a render of `frame` covers: the frame, cut at + * `maxHeight` and at the pixel budget. */ +export function renderedHeight(frame: Pick, scale: number, maxHeight?: number): number { + const width = Math.max(1, Math.round(frame.width)) + const budget = Math.max(1, Math.floor(MAX_RENDER_PIXELS / (width * scale * scale))) + const cap = maxHeight ? Math.round(maxHeight) : Infinity + return Math.max(1, Math.min(Math.round(frame.height), cap, budget)) +} diff --git a/server/screenshot.ts b/server/screenshot.ts index f7e576840..7c8fd2f29 100644 --- a/server/screenshot.ts +++ b/server/screenshot.ts @@ -4,6 +4,8 @@ import path from 'node:path' import puppeteer, { type Browser, type Page } from 'puppeteer-core' import type { Frame } from '../shared/types.ts' import { guardPublicPageRequests } from './publicUrl.ts' +import { renderedHeight } from './renderLimits.ts' +import { createRenderer, type PageOptions, type RenderPage, type RendererStatus } from './renderBrowser.ts' /** * Render a frame's HTML in headless Chrome so agents can *see* their work. @@ -45,31 +47,16 @@ function findBrowser(): string { return path } -let browserPromise: Promise | null = null - -export async function getBrowser(): Promise { - if (browserPromise) { - const b = await browserPromise - if (b.connected) return b - browserPromise = null - } - const launching = launchBrowser() - browserPromise = launching - /* a launch that failed (a slow cold start past puppeteer's timeout) must not - be handed to every later caller: the next one tries again */ - launching.catch(() => { - if (browserPromise === launching) browserPromise = null - }) - return launching -} - /** A fresh headless Chrome with the server's flags. `timeout` bounds the wait - * for its DevTools endpoint (puppeteer's default, 30s, unless given). */ -export function launchBrowser(timeout?: number): Promise { + * for its DevTools endpoint (puppeteer's default, 30s, unless given); + * `protocolTimeout` bounds every DevTools command (puppeteer's 180s unless + * given). */ +export function launchBrowser(timeout?: number, protocolTimeout?: number): Promise { return puppeteer.launch({ executablePath: findBrowser(), headless: true, timeout, + protocolTimeout, args: [ '--no-first-run', '--disable-extensions', @@ -83,76 +70,84 @@ export function launchBrowser(timeout?: number): Promise { }) } -export interface IsolatedPage { - page: Page - close: () => Promise +/* a stuck DevTools command fails in a minute rather than puppeteer's three, + so the renderer's health probe gets to judge the browser sooner */ +const PROTOCOL_TIMEOUT_MS = 60_000 + +/** One render attempt, page open to encoded bytes. */ +const RENDER_TIMEOUT_MS = 45_000 + +const renderer = createRenderer({ + launch: () => launchBrowser(undefined, PROTOCOL_TIMEOUT_MS), + tuning: { maxConcurrent: Math.max(1, env.RENDER_CONCURRENCY) }, +}) + +/** The live shared browser, launched if need be. */ +export function getBrowser(): Promise { + return renderer.browser() +} + +/** Counters for logs and health checks. */ +export function rendererStatus(): RendererStatus { + return renderer.status() } +export type IsolatedPage = Pick + /** External pages never share cookies, cache or service workers across users - * or imports. Closing the wrapper tears down the entire browser context. */ -export async function openIsolatedPage(): Promise { - const browser = await getBrowser() - const context = await browser.createBrowserContext() + * or imports. Closing the wrapper tears down the entire browser context and + * returns the page's render slot; a page that is never closed is closed for + * its caller when its lease runs out (see renderBrowser.ts). */ +export function openIsolatedPage(options?: PageOptions): Promise { + return renderer.openPage(options) +} + +export async function loadFramePage(frame: Frame, options?: PageOptions): Promise { + const loaded = await openIsolatedPage(options) try { - const page = await context.newPage() - let closed = false - return { - page, - close: async () => { - if (closed) return - closed = true - await context.close().catch(() => {}) - }, - } + await loadFrameInto(loaded.page, frame) + return loaded } catch (error) { - await context.close().catch(() => {}) + await loaded.close() throw error } } -export async function loadFramePage(frame: Frame): Promise { - const loaded = await openIsolatedPage() - const { page } = loaded +async function loadFrameInto(page: Page, frame: Frame): Promise { + const assetOrigin = new URL(env.BETTER_AUTH_URL).origin + await guardPublicPageRequests(page, { + allowUrl: (url) => + (url.origin === assetOrigin && url.pathname.startsWith('/a/')) || + /* webfonts referenced by imported frames (imports request the + source design's families from Google Fonts) */ + url.origin === 'https://fonts.googleapis.com' || + url.origin === 'https://fonts.gstatic.com', + }) + await page.setViewport({ + width: Math.max(1, Math.round(frame.width)), + /* A viewport does not need to span an entire imported landing page for + layout/computed-style inspection; full-page content remains in the DOM. */ + height: Math.max(1, Math.min(Math.round(frame.height), 4000)), + deviceScaleFactor: 1, + }) + /* setContent leaves the page on about:blank, where the relative /a/... + asset URLs of imported frames resolve nowhere. In the app an iframe + inherits the page origin; here a stands in for it — unless the + frame brought its own (website imports do). */ + let html = frame.html || '' + if (!/` + html = /]*>/i.test(html) ? html.replace(/]*)>/i, `${baseTag}`) : baseTag + html + } try { - const assetOrigin = new URL(env.BETTER_AUTH_URL).origin - await guardPublicPageRequests(page, { - allowUrl: (url) => - (url.origin === assetOrigin && url.pathname.startsWith('/a/')) || - /* webfonts referenced by imported frames (imports request the - source design's families from Google Fonts) */ - url.origin === 'https://fonts.googleapis.com' || - url.origin === 'https://fonts.gstatic.com', + await page.setContent(html, { + waitUntil: 'load', + timeout: 8000, }) - await page.setViewport({ - width: Math.max(1, Math.round(frame.width)), - /* A viewport does not need to span an entire imported landing page for - layout/computed-style inspection; full-page content remains in the DOM. */ - height: Math.max(1, Math.min(Math.round(frame.height), 4000)), - deviceScaleFactor: 1, - }) - /* setContent leaves the page on about:blank, where the relative /a/... - asset URLs of imported frames resolve nowhere. In the app an iframe - inherits the page origin; here a stands in for it — unless the - frame brought its own (website imports do). */ - let html = frame.html || '' - if (!/` - html = /]*>/i.test(html) ? html.replace(/]*)>/i, `${baseTag}`) : baseTag + html - } - try { - await page.setContent(html, { - waitUntil: 'load', - timeout: 8000, - }) - } catch { - /* Slow external resources: inspect whatever has rendered. */ - } - await new Promise((resolve) => setTimeout(resolve, 120)) - return loaded - } catch (error) { - await loaded.close() - throw error + } catch { + /* Slow external resources: inspect whatever has rendered. */ } + await new Promise((resolve) => setTimeout(resolve, 120)) } export interface FrameInspection { @@ -178,10 +173,13 @@ export interface FrameInspection { /** A compact, rendered representation for agents. It intentionally relies on * visible text, semantics, geometry and computed styles rather than classes. */ -export async function inspectFrame(frame: Frame): Promise { - const loaded = await loadFramePage(frame) - const { page } = loaded - try { +export function inspectFrame(frame: Frame): Promise { + return renderer.withPage('inspecting the frame', RENDER_TIMEOUT_MS, (page) => inspectOn(page, frame)) +} + +async function inspectOn(page: Page, frame: Frame): Promise { + await loadFrameInto(page, frame) + { /* tsx/esbuild annotates nested functions with __name; page.evaluate serializes the callback without that runtime helper. A tiny in-page identity shim keeps the evaluated code independent of the loader. */ @@ -374,37 +372,46 @@ export async function inspectFrame(frame: Frame): Promise { design: inspection.design, elements: inspection.elements, } - } finally { - await loaded.close() } } -export async function renderFrame( +export interface RenderOptions extends PageOptions { + type?: 'png' | 'jpeg' + quality?: number + maxHeight?: number +} + +export function renderFrame( frame: Frame, /* output pixel density — fractional values downscale huge frames */ scale: number = 1, - opts: { type?: 'png' | 'jpeg'; quality?: number; maxHeight?: number } = {}, + opts: RenderOptions = {}, ): Promise { - const loaded = await loadFramePage(frame) - const { page } = loaded - try { - await page.setViewport({ - width: Math.max(1, Math.round(frame.width)), - height: Math.max(1, Math.round(frame.height)), - deviceScaleFactor: scale, - }) - const type = opts.type ?? 'png' - const clip = - opts.maxHeight && frame.height > opts.maxHeight - ? { x: 0, y: 0, width: Math.round(frame.width), height: Math.round(opts.maxHeight) } - : undefined - const buf = await page.screenshot({ - type, - ...(type === 'jpeg' ? { quality: opts.quality ?? 90 } : {}), - ...(clip ? { clip } : {}), - }) - return Buffer.from(buf) - } finally { - await loaded.close() - } + return renderer.withPage( + 'rendering the frame', + RENDER_TIMEOUT_MS, + async (page) => { + await loadFrameInto(page, frame) + return screenshotOn(page, frame, scale, opts) + }, + { priority: opts.priority }, + ) +} + +async function screenshotOn(page: Page, frame: Frame, scale: number, opts: RenderOptions): Promise { + const width = Math.max(1, Math.round(frame.width)) + const fullHeight = Math.max(1, Math.round(frame.height)) + const height = renderedHeight(frame, scale, opts.maxHeight) + /* the viewport always spans the whole frame, so 100vh, height media + queries and bottom-fixed elements lay out as they do on the canvas; the + pixel budget bounds only the captured image below */ + await page.setViewport({ width, height: fullHeight, deviceScaleFactor: scale }) + const type = opts.type ?? 'png' + const clip = height < fullHeight ? { x: 0, y: 0, width, height } : undefined + const buf = await page.screenshot({ + type, + ...(type === 'jpeg' ? { quality: opts.quality ?? 90 } : {}), + ...(clip ? { clip } : {}), + }) + return Buffer.from(buf) } diff --git a/server/thumbs.ts b/server/thumbs.ts index d805ec927..35981c269 100644 --- a/server/thumbs.ts +++ b/server/thumbs.ts @@ -52,6 +52,8 @@ async function render(frame: Frame): Promise { type: 'jpeg', quality: 70, maxHeight: PREVIEW_MAX_HEIGHT, + /* a dashboard tile can wait; an agent's screenshot should not */ + priority: 'background', }) } finally { active-- diff --git a/tests/importer.test.ts b/tests/importer.test.ts index d9c76be11..cc18249cd 100644 --- a/tests/importer.test.ts +++ b/tests/importer.test.ts @@ -454,6 +454,11 @@ describe('webpage capture', () => { }) expect(browserMocks.openIsolatedPage).toHaveBeenCalledTimes(2) expect(page.close).toHaveBeenCalledTimes(2) + /* the capture's render slot is back before the preview asks for one, so + a one-slot renderer cannot wait on itself */ + const [, previewOpen] = browserMocks.openIsolatedPage.mock.invocationCallOrder + const [captureClose] = page.close.mock.invocationCallOrder + expect(captureClose).toBeLessThan(previewOpen!) }) it('renders the Context.dev HTML locally for the agent preview', async () => { diff --git a/tests/renderBrowser.test.ts b/tests/renderBrowser.test.ts new file mode 100644 index 000000000..7e9baf82f --- /dev/null +++ b/tests/renderBrowser.test.ts @@ -0,0 +1,343 @@ +import { describe, expect, it, vi } from 'vitest' +import type { Browser } from 'puppeteer-core' +import { + RenderGate, + RenderTimeoutError, + RendererBusyError, + createRenderer, + isBrowserFailure, + type RendererTuning, +} from '../server/renderBrowser.ts' +import { MAX_RENDER_PIXELS, renderedHeight } from '../server/renderLimits.ts' + +/* On 2026-11-05 prod's one shared Chromium stopped creating pages while its + DevTools socket stayed open, and every render timed out for two hours. + These tests drive the renderer's lifecycle against fake browsers that + stall the way that one did. */ + +const never = () => new Promise(() => {}) +const tick = (ms = 5) => new Promise((resolve) => setTimeout(resolve, ms)) + +const FAST: Partial = { + maxConcurrent: 4, + maxBackground: 2, + maxQueued: 8, + queueTimeoutMs: 200, + openTimeoutMs: 40, + leaseMs: 5_000, + probeTimeoutMs: 40, + closeTimeoutMs: 20, +} + +interface FakeBrowser { + label: string + connected: boolean + stallContexts: boolean + stallClose: boolean + stallContextClose: boolean + contextsOpen: number + close: ReturnType + child: { pid: undefined; exitCode: number | null; signalCode: string | null; kill: ReturnType } + createBrowserContext: () => Promise + process: () => FakeBrowser['child'] +} + +function fakeBrowser( + label: string, + options: { stallContexts?: boolean; stallClose?: boolean; stallContextClose?: boolean } = {}, +): FakeBrowser { + const browser: FakeBrowser = { + label, + connected: true, + stallContexts: options.stallContexts ?? false, + stallClose: options.stallClose ?? false, + stallContextClose: options.stallContextClose ?? false, + contextsOpen: 0, + /* pid undefined: the kill falls back to child.kill, never a real group */ + child: { pid: undefined, exitCode: null, signalCode: null, kill: vi.fn(() => true) }, + close: vi.fn(() => (browser.stallClose ? never() : Promise.resolve())), + createBrowserContext: () => { + if (browser.stallContexts) return never() + browser.contextsOpen++ + let closed = false + return Promise.resolve({ + newPage: async () => ({ label, evaluate: async () => 1 }), + close: async () => { + if (browser.stallContextClose) return never() + if (closed) return + closed = true + browser.contextsOpen-- + }, + }) + }, + process: () => browser.child, + } + return browser +} + +function rig(browsers: FakeBrowser[], tuning: Partial = {}) { + const queue = [...browsers] + const launch = vi.fn(async () => { + const next = queue.shift() + if (!next) throw new Error('no more fake browsers') + return next as unknown as Browser + }) + const log = { warn: vi.fn(), error: vi.fn() } + const renderer = createRenderer({ launch, tuning: { ...FAST, ...tuning }, log }) + return { renderer, launch, log } +} + +const label = (page: unknown) => (page as { label: string }).label + +describe('a wedged browser', () => { + it('is killed when it cannot open a page, and the page opens on a fresh launch', async () => { + const stuck = fakeBrowser('stuck', { stallContexts: true }) + const fresh = fakeBrowser('fresh') + const { renderer, launch, log } = rig([stuck, fresh]) + + const handle = await renderer.openPage() + + expect(label(handle.page)).toBe('fresh') + expect(launch).toHaveBeenCalledTimes(2) + expect(stuck.close).toHaveBeenCalled() + expect(log.error).toHaveBeenCalledWith(expect.stringMatching(/killed: could not open a page/)) + await handle.close() + expect(renderer.status()).toMatchObject({ kills: 1, active: 0, pagesOpen: 0 }) + }) + + it('reports a timeout when the relaunch stalls too, instead of hanging', async () => { + const { renderer, launch } = rig([ + fakeBrowser('a', { stallContexts: true }), + fakeBrowser('b', { stallContexts: true }), + ]) + + await expect(renderer.openPage()).rejects.toBeInstanceOf(RenderTimeoutError) + expect(launch).toHaveBeenCalledTimes(2) + expect(renderer.status()).toMatchObject({ active: 0, failedOpensInARow: 2 }) + }) + + it('is SIGKILLed even when its graceful close stalls too', async () => { + const stuck = fakeBrowser('stuck', { stallContexts: true, stallClose: true }) + const { renderer } = rig([stuck, fakeBrowser('fresh')]) + + const handle = await renderer.openPage() + await tick(FAST.closeTimeoutMs! * 3) + + expect(stuck.child.kill).toHaveBeenCalledWith('SIGKILL') + await handle.close() + }) + + it('is replaced by one launch however many callers saw it fail at once', async () => { + const stuck = fakeBrowser('stuck', { stallContexts: true }) + const fresh = fakeBrowser('fresh') + const { renderer, launch } = rig([stuck, fresh]) + + const handles = await Promise.all([renderer.openPage(), renderer.openPage(), renderer.openPage()]) + + expect(handles.map((h) => label(h.page))).toEqual(['fresh', 'fresh', 'fresh']) + expect(launch).toHaveBeenCalledTimes(2) + await Promise.all(handles.map((h) => h.close())) + }) + + it('that stalls mid-render fails the health probe, is killed, and the render reruns once', async () => { + const turning = fakeBrowser('turning') + const fresh = fakeBrowser('fresh') + const { renderer, launch } = rig([turning, fresh]) + + let attempts = 0 + const result = await renderer.withPage('rendering', 40, async (page) => { + attempts++ + if (label(page) === 'turning') { + turning.stallContexts = true /* the probe will not get a page either */ + return never() + } + return 'png' + }) + + expect(result).toBe('png') + expect(attempts).toBe(2) + expect(launch).toHaveBeenCalledTimes(2) + expect(turning.close).toHaveBeenCalled() + }) + + it('is replaced once it disconnects', async () => { + const first = fakeBrowser('first') + const { renderer, launch } = rig([first, fakeBrowser('second')]) + await (await renderer.openPage()).close() + + first.connected = false + const handle = await renderer.openPage() + + expect(label(handle.page)).toBe('second') + expect(launch).toHaveBeenCalledTimes(2) + await handle.close() + }) +}) + +describe('a healthy browser', () => { + it('keeps serving when one frame is too slow: the render times out, nothing is relaunched', async () => { + const browser = fakeBrowser('ok') + const { renderer, launch } = rig([browser]) + + await expect(renderer.withPage('rendering', 30, () => never())).rejects.toBeInstanceOf(RenderTimeoutError) + + expect(launch).toHaveBeenCalledTimes(1) + expect(browser.close).not.toHaveBeenCalled() + expect(browser.contextsOpen).toBe(0) + expect(renderer.status().active).toBe(0) + }) + + it('does not relaunch for a failure that is the frame’s own', async () => { + const browser = fakeBrowser('ok') + const { renderer, launch } = rig([browser]) + + await expect( + renderer.withPage('rendering', 1_000, async () => { + throw new Error('Unable to capture screenshot: image too large') + }), + ).rejects.toThrow(/too large/) + expect(launch).toHaveBeenCalledTimes(1) + expect(browser.close).not.toHaveBeenCalled() + }) + + it('is recycled after its page budget, once its last page closes', async () => { + const old = fakeBrowser('old') + const { renderer, launch } = rig([old, fakeBrowser('new')], { maxPagesPerBrowser: 2 }) + const first = await renderer.openPage() + const second = await renderer.openPage() + + const third = await renderer.openPage() + expect(label(third.page)).toBe('new') + expect(old.close).not.toHaveBeenCalled() /* still serving two pages */ + + await first.close() + await second.close() + expect(old.close).toHaveBeenCalled() + expect(launch).toHaveBeenCalledTimes(2) + expect(renderer.status().recycles).toBe(1) + await third.close() + }) + + it('closes a page held past its lease and gives the slot back', async () => { + const browser = fakeBrowser('ok') + const { renderer, log } = rig([browser], { leaseMs: 30, maxConcurrent: 1 }) + + await renderer.openPage() /* never closed by its caller */ + const next = await renderer.openPage() + + expect(log.warn).toHaveBeenCalledWith(expect.stringMatching(/outlived its 30ms lease/)) + expect(browser.contextsOpen).toBe(1) + await next.close() + }) +}) + +describe('a page that will not close', () => { + it('takes its browser down with it, and the slot goes to a fresh browser', async () => { + const stuck = fakeBrowser('stuck', { stallContextClose: true }) + const fresh = fakeBrowser('fresh') + const { renderer, log } = rig([stuck, fresh], { maxConcurrent: 1 }) + + const first = await renderer.openPage() + await first.close() + + expect(log.error).toHaveBeenCalledWith(expect.stringMatching(/killed: a page would not close/)) + expect(stuck.close).toHaveBeenCalled() + expect(renderer.status()).toMatchObject({ kills: 1, active: 0, pagesOpen: 0 }) + const second = await renderer.openPage() + expect(label(second.page)).toBe('fresh') + await second.close() + }) +}) + +describe('RenderGate', () => { + const tuning = { maxConcurrent: 2, maxBackground: 1, maxQueued: 2, queueTimeoutMs: 100 } + + it('admits up to the limit and queues the rest', async () => { + const gate = new RenderGate(tuning) + const a = await gate.acquire('interactive') + await gate.acquire('interactive') + let admitted = false + const waiting = gate.acquire('interactive').then((release) => { + admitted = true + return release + }) + await tick() + expect(admitted).toBe(false) + + a() + a() /* releasing twice frees one slot, not two */ + ;(await waiting)() + expect(gate.stats).toMatchObject({ active: 1, queued: 0 }) + }) + + it('keeps background work to its share', async () => { + const gate = new RenderGate(tuning) + await gate.acquire('background') + let second = false + void gate + .acquire('background') + .then(() => (second = true)) + .catch(() => {}) /* refused by the queue timeout after the test */ + await tick() + + expect(second).toBe(false) + await gate.acquire('interactive') /* the other slot is still open to people */ + expect(gate.stats.active).toBe(2) + }) + + it('serves a waiting agent before a waiting thumbnail', async () => { + const gate = new RenderGate({ ...tuning, maxBackground: 2 }) + const first = await gate.acquire('interactive') + await gate.acquire('interactive') + const order: string[] = [] + void gate + .acquire('background') + .then(() => order.push('background')) + .catch(() => {}) + void gate + .acquire('interactive') + .then(() => order.push('interactive')) + .catch(() => {}) + await tick() + + first() + await tick() + expect(order).toEqual(['interactive']) + }) + + it('refuses when the queue is full, and when a slot does not free up in time', async () => { + const gate = new RenderGate(tuning) + await gate.acquire('interactive') + await gate.acquire('interactive') + const timedOut = gate.acquire('interactive') + void gate.acquire('interactive').catch(() => {}) + + await expect(gate.acquire('interactive')).rejects.toBeInstanceOf(RendererBusyError) + await expect(timedOut).rejects.toThrow(/no render slot within 100ms/) + }) +}) + +describe('isBrowserFailure', () => { + it('knows the errors a wedged browser throws', () => { + const timeout = Object.assign(new Error('Timed out after waiting 30000ms'), { name: 'TimeoutError' }) + const protocol = Object.assign( + new Error("Network.enable timed out. Increase the 'protocolTimeout' setting in launch/connect calls"), + { name: 'ProtocolError' }, + ) + expect(isBrowserFailure(timeout)).toBe(true) + expect(isBrowserFailure(protocol)).toBe(true) + expect(isBrowserFailure(new RenderTimeoutError('rendering', 1))).toBe(true) + expect(isBrowserFailure(new Error('Unable to capture screenshot'))).toBe(false) + expect(isBrowserFailure(new RendererBusyError('full'))).toBe(false) + }) +}) + +describe('renderedHeight', () => { + it('keeps ordinary frames whole and cuts runaway ones at the pixel budget', () => { + expect(renderedHeight({ width: 1440, height: 900 }, 2)).toBe(900) + expect(renderedHeight({ width: 1440, height: 900 }, 1, 400)).toBe(400) + const tall = renderedHeight({ width: 1440, height: 40_000 }, 2) + expect(tall).toBeLessThan(40_000) + expect(1440 * 2 * tall * 2).toBeLessThanOrEqual(MAX_RENDER_PIXELS) + }) +}) From 9d62ccfb3a3edb6e3d1205b4c7234b770cde74cc Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Thu, 5 Nov 2026 22:46:05 -0800 Subject: [PATCH 2/6] feat(screenshot): render in a remote Chrome over CDP (Cloudflare Browser Run) (#458) * feat(screenshot): render in a remote Chrome over CDP, e.g. Cloudflare Browser Run REMOTE_BROWSER_URL (+ REMOTE_BROWSER_TOKEN as a Bearer header) swaps the local Chromium launch for puppeteer.connect; the gate, deadlines, probe and recycling from the render pool stay in front of it. A remote browser is closed 30s after its last page, since providers bill open sessions, and one whose close stalls is disconnected. Provider-neutral: Cloudflare, browserless or our own renderer service are each just a URL. Co-Authored-By: Claude Opus 5.5 (1M context) * fix(screenshot): name a refused remote connection, and let PDF export run on a remote browser only A provider refusing the CDP upgrade rejects with a ws ErrorEvent, not an Error, so routes answered a bare 500; a 429 now surfaces as RendererBusyError (503 + Retry-After) and anything else keeps its message. PDF availability asked only for a local Chrome binary. Co-Authored-By: Claude Opus 5.5 (1M context) * fix(screenshot): let a remote browser fetch public resources itself The pinned proxy in guardPublicPageRequests keeps a local browser off the server's private network by fetching every resource in Node and handing the body back over CDP. A remote browser is not on that network, and shipping every body across the internet timed heavy website imports out (stripe.com, doop.design). Off the network, public http(s) requests continue in the browser; private addresses and other schemes are still refused. Closing a remote page gets 15s, since a heavy import's teardown outlived 5s. Co-Authored-By: Claude Opus 5.5 (1M context) * test(pdf): count a remote browser on a server without a local Chrome Co-Authored-By: Claude Opus 5.5 (1M context) * fix(screenshot): fetch directly only from a remote browser declared isolated Being remote does not mean being off our network: a self-hosted renderer can sit beside private services, and continuing its requests would let an imported page reach them through a hostname that resolves privately. REMOTE_BROWSER_ISOLATED is the explicit declaration (a hosted provider such as Cloudflare); without it a remote browser stays on the DNS-pinned proxy. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) (cherry picked from commit af873bed1d6d16ebe6da53f01d466cdcbaba03a2) --- .context/TECHSTACK.md | 10 ++++++ .env.example | 17 ++++++++++ server/env.ts | 8 +++++ server/pdfExport.ts | 4 +-- server/publicUrl.ts | 17 +++++++++- server/renderBrowser.ts | 43 +++++++++++++++++++++++-- server/screenshot.ts | 55 ++++++++++++++++++++++++++++++-- tests/pdfExport.test.ts | 34 ++++++++++++++++++-- tests/publicUrl.test.ts | 47 ++++++++++++++++++++++++++++ tests/renderBrowser.test.ts | 62 +++++++++++++++++++++++++++++++++++-- 10 files changed, 284 insertions(+), 13 deletions(-) diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index 9e7006872..80b73aede 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -260,6 +260,16 @@ data-doop-webfonts>` for the roster families the frame names and does not load i `GET /healthz/renderer` reports the counters (`kills`, `lastOpenedAt`, `failedOpensInARow`, queue depth) for an uptime check. Context: the 2026-11-05 wedge, where one browser stopped making pages for two hours. Tests: `renderBrowser.test.ts`. + `REMOTE_BROWSER_URL` (+ `REMOTE_BROWSER_TOKEN`, sent as a Bearer header) swaps the local launch + for `puppeteer.connect` to a remote Chrome over CDP: Cloudflare Browser Run + (`wss://api.cloudflare.com/client/v4/accounts//browser-run/devtools/browser`), browserless + or a renderer service; everything past the connect is unchanged, so switching provider is an env + change. A remote browser is closed 30s after its last page (`idleCloseMs`; providers bill open + sessions), and one whose close stalls is disconnected, having no process to kill. Assets load + from `BETTER_AUTH_URL`, which the remote browser must reach. `REMOTE_BROWSER_ISOLATED` declares the + browser cannot reach our private network (a hosted provider): it then fetches public URLs itself + instead of through `guardPublicPageRequests`' DNS-pinned proxy; never set it for a self-hosted + renderer. - `pdf-lib` 1.17.1 - joins the vector PDF export (`server/pdfExport.ts`): headless Chrome prints each frame onto a page of its own size (inside an iframe of the frame's size, as the canvas shows it, so content taller than the frame is clipped rather than paginated: bare, Chrome moved a block diff --git a/.env.example b/.env.example index 733c43143..d386f29f5 100644 --- a/.env.example +++ b/.env.example @@ -312,6 +312,23 @@ # Pages the shared Chromium renders at once (default 4); more wait in a # bounded queue and are refused with a 503 when it is full. #RENDER_CONCURRENCY=4 +# Render in a remote Chrome over the DevTools protocol instead of a local one. +# Assets load from BETTER_AUTH_URL, so the remote browser must be able to +# reach it (not localhost). A browser with no page open for 30s is closed, +# since remote browsers bill while their session is open. Cloudflare Browser +# Run, with an API token holding "Browser Rendering - Edit": +# REMOTE_BROWSER_URL=wss://api.cloudflare.com/client/v4/accounts//browser-run/devtools/browser?keep_alive=60000 +# REMOTE_BROWSER_TOKEN= +# REMOTE_BROWSER_ISOLATED=1 +# Any other CDP endpoint (browserless, our own renderer) works the same way; +# the token is sent as `Authorization: Bearer`. +#REMOTE_BROWSER_URL= +#REMOTE_BROWSER_TOKEN= +# Set to 1 only when the remote browser cannot reach this server's private +# network (a hosted provider). It then fetches public URLs itself instead of +# through the server's DNS-pinned proxy, which is much faster for website +# imports. Leave unset for a self-hosted renderer on your own network. +#REMOTE_BROWSER_ISOLATED= # ------------------------------------------------- analytics (optional, OFF) # PostHog product analytics + session replay. Entirely disabled unless diff --git a/server/env.ts b/server/env.ts index 3231e7033..e91f6948f 100644 --- a/server/env.ts +++ b/server/env.ts @@ -234,6 +234,14 @@ const schema = { CHROME_NO_SANDBOX: bool({ default: false }), /* pages the shared Chromium renders at once (renderBrowser.ts) */ RENDER_CONCURRENCY: nonNegativeInt({ default: 4 }), + /* a remote Chrome over the DevTools protocol instead of the local one + (Cloudflare Browser Run, browserless, a renderer service) */ + REMOTE_BROWSER_URL: str({ default: undefined }), + REMOTE_BROWSER_TOKEN: str({ default: undefined }), + /* the remote browser cannot reach this server's private network (a hosted + provider such as Cloudflare): it may fetch public URLs itself instead of + through the DNS-pinned proxy. Never set it for a self-hosted renderer */ + REMOTE_BROWSER_ISOLATED: bool({ default: false }), /* ------------------------------------------------------ analytics */ POSTHOG_KEY: str({ default: undefined }), diff --git a/server/pdfExport.ts b/server/pdfExport.ts index 61d4a3e4c..807d54d1b 100644 --- a/server/pdfExport.ts +++ b/server/pdfExport.ts @@ -4,7 +4,7 @@ import type { Canvas, Frame } from '../shared/types.ts' import { readingOrder } from '../shared/frameOrder.ts' import { canvasPages, pageFrames } from '../shared/pages.ts' import { MAX_PDF_FRAMES, PDF_RENDER_CONCURRENCY } from '../shared/pdfLimits.ts' -import { findBrowserPath, loadFramePage } from './screenshot.ts' +import { loadFramePage, rendererAvailable } from './screenshot.ts' /** * Vector PDF export: each frame prints through headless Chrome onto one page @@ -36,7 +36,7 @@ export class PdfRendererUnavailableError extends Error { } export function pdfRendererAvailable(): boolean { - return findBrowserPath() !== null + return rendererAvailable() } interface PageSize { diff --git a/server/publicUrl.ts b/server/publicUrl.ts index 177cb8284..af4e48623 100644 --- a/server/publicUrl.ts +++ b/server/publicUrl.ts @@ -3,6 +3,7 @@ import net from 'node:net' import type { LookupFunction } from 'node:net' import type { Page } from 'puppeteer-core' import { Agent, fetch as undiciFetch, type RequestInit as UndiciRequestInit } from 'undici' +import { env } from './env.ts' export interface PublicAddress { address: string @@ -230,15 +231,25 @@ function browserResponseHeaders(response: Response, document: boolean): Record boolean fetchUrl?: typeof fetchPinnedPublicUrl + offNetwork?: boolean } = {}, ): Promise { const fetchUrl = options.fetchUrl ?? fetchPinnedPublicUrl + const offNetwork = options.offNetwork ?? (!!env.REMOTE_BROWSER_URL && env.REMOTE_BROWSER_ISOLATED) let pageBytes = 0 await page.setBypassServiceWorker(true) const client = await page.createCDPSession() @@ -260,6 +271,10 @@ export async function guardPublicPageRequests( return } parsePublicHttpUrl(raw) + if (offNetwork) { + await request.continue() + return + } const method = request.method().toUpperCase() if (!['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'].includes(method)) { throw new Error('unsupported browser request method') diff --git a/server/renderBrowser.ts b/server/renderBrowser.ts index 2c5cb469c..abfef056d 100644 --- a/server/renderBrowser.ts +++ b/server/renderBrowser.ts @@ -52,6 +52,9 @@ export interface RendererTuning { maxPagesPerBrowser: number /** how long one browser lives before it is recycled */ maxBrowserAgeMs: number + /** close a browser that has had no page open this long; unset keeps it. + * A remote browser is billed while its session is open, so it gets one */ + idleCloseMs?: number } export const DEFAULT_RENDERER_TUNING: RendererTuning = { @@ -82,6 +85,20 @@ export class RendererBusyError extends Error { } } +/** A remote browser that would not connect. The WebSocket library rejects + * with an event, not an Error, so its message would be lost on the way to + * the caller; a provider turning new sessions away (HTTP 429) is the + * renderer being busy, which callers already answer with a 503. */ +export function remoteConnectFailure(error: unknown): Error { + if (error instanceof Error) return error + const message = + typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string' + ? error.message + : String(error) + if (/\b429\b/.test(message)) return new RendererBusyError('the remote browser is refusing new sessions') + return new Error(`could not connect to the remote browser: ${message}`) +} + /** Did the failure come from the browser rather than the frame? A stall, a * closed target or a broken DevTools session all point at the browser. */ export function isBrowserFailure(error: unknown): boolean { @@ -208,6 +225,7 @@ interface Generation { pagesServed: number state: GenerationState probing: Promise | null + idleTimer: ReturnType | null } export interface RenderPage { @@ -280,6 +298,7 @@ export function createRenderer(deps: RendererDeps): Renderer { pagesServed: 0, state: 'live', probing: null, + idleTimer: null, } current = generation generation.browser.then( @@ -334,6 +353,7 @@ export function createRenderer(deps: RendererDeps): Renderer { } function retire(generation: Generation): void { + if (generation.idleTimer) clearTimeout(generation.idleTimer) generation.state = 'dead' if (current === generation) current = null if (generation.resolved) void terminate(generation.resolved) @@ -341,13 +361,32 @@ export function createRenderer(deps: RendererDeps): Renderer { async function terminate(browser: Browser): Promise { const child = browser.process() - await withDeadline(browser.close(), tuning.closeTimeoutMs, 'closing the browser').catch(() => {}) + const closed = await withDeadline(browser.close(), tuning.closeTimeoutMs, 'closing the browser').then( + () => true, + () => false, + ) if (child && child.exitCode === null && child.signalCode === null) killProcessTree(child) + /* a remote browser has no process to kill: drop the socket, and its + session ends on the provider's idle timeout */ + if (!child && !closed) await browser.disconnect().catch(() => {}) } function releasePage(generation: Generation): void { generation.pagesOpen-- - if (generation.state === 'draining' && generation.pagesOpen === 0) retire(generation) + if (generation.pagesOpen > 0) return + if (generation.state === 'draining') retire(generation) + else if (generation.state === 'live') scheduleIdleClose(generation) + } + + function scheduleIdleClose(generation: Generation): void { + const idleMs = tuning.idleCloseMs + if (idleMs === undefined) return + if (generation.idleTimer) clearTimeout(generation.idleTimer) + generation.idleTimer = setTimeout(() => { + generation.idleTimer = null + if (generation.state === 'live' && generation.pagesOpen === 0) drain(generation) + }, idleMs) + generation.idleTimer.unref?.() } /** Is the browser still able to make a page? Runs outside the gate, since diff --git a/server/screenshot.ts b/server/screenshot.ts index 7c8fd2f29..734cb5cd0 100644 --- a/server/screenshot.ts +++ b/server/screenshot.ts @@ -5,7 +5,14 @@ import puppeteer, { type Browser, type Page } from 'puppeteer-core' import type { Frame } from '../shared/types.ts' import { guardPublicPageRequests } from './publicUrl.ts' import { renderedHeight } from './renderLimits.ts' -import { createRenderer, type PageOptions, type RenderPage, type RendererStatus } from './renderBrowser.ts' +import { + createRenderer, + remoteConnectFailure, + withDeadline, + type PageOptions, + type RenderPage, + type RendererStatus, +} from './renderBrowser.ts' /** * Render a frame's HTML in headless Chrome so agents can *see* their work. @@ -41,6 +48,12 @@ export function findBrowserPath(): string | null { return null } +/** Whether the server has a browser to render with: a remote one + * (REMOTE_BROWSER_URL) or a local executable. */ +export function rendererAvailable(): boolean { + return !!env.REMOTE_BROWSER_URL || findBrowserPath() !== null +} + function findBrowser(): string { const path = findBrowserPath() if (!path) throw new Error('No Chrome/Chromium found. Set CHROME_PATH to a browser executable.') @@ -77,9 +90,45 @@ const PROTOCOL_TIMEOUT_MS = 60_000 /** One render attempt, page open to encoded bytes. */ const RENDER_TIMEOUT_MS = 45_000 +/* a remote session is billed while it is open: close it this long after its + last page, well inside the provider's own idle timeout (Cloudflare: 60s) */ +const REMOTE_IDLE_CLOSE_MS = 30_000 +const REMOTE_CONNECT_TIMEOUT_MS = 30_000 +/* closing a heavy page's context is a round trip that waits on the page's + teardown: a remote one took over 5s after a full website import */ +const REMOTE_CLOSE_TIMEOUT_MS = 15_000 + +/** A Chrome somewhere else, over the DevTools protocol (REMOTE_BROWSER_URL). + * Everything past the connect is the same puppeteer API a local one has. */ +export function connectRemoteBrowser(url: string, token: string | undefined): Promise { + const connecting = puppeteer.connect({ + browserWSEndpoint: url, + headers: token ? { Authorization: `Bearer ${token}` } : undefined, + protocolTimeout: PROTOCOL_TIMEOUT_MS, + }) + return withDeadline(connecting, REMOTE_CONNECT_TIMEOUT_MS, 'connecting to the remote browser').catch( + (error: unknown) => { + /* a session that opens after its deadline is still billed: close it */ + connecting.then( + (late) => void late.close().catch(() => {}), + () => {}, + ) + throw remoteConnectFailure(error) + }, + ) +} + +const remoteBrowserUrl = env.REMOTE_BROWSER_URL + const renderer = createRenderer({ - launch: () => launchBrowser(undefined, PROTOCOL_TIMEOUT_MS), - tuning: { maxConcurrent: Math.max(1, env.RENDER_CONCURRENCY) }, + launch: () => + remoteBrowserUrl + ? connectRemoteBrowser(remoteBrowserUrl, env.REMOTE_BROWSER_TOKEN) + : launchBrowser(undefined, PROTOCOL_TIMEOUT_MS), + tuning: { + maxConcurrent: Math.max(1, env.RENDER_CONCURRENCY), + ...(remoteBrowserUrl ? { idleCloseMs: REMOTE_IDLE_CLOSE_MS, closeTimeoutMs: REMOTE_CLOSE_TIMEOUT_MS } : {}), + }, }) /** The live shared browser, launched if need be. */ diff --git a/tests/pdfExport.test.ts b/tests/pdfExport.test.ts index 4c0a8d5f4..652ccd4a3 100644 --- a/tests/pdfExport.test.ts +++ b/tests/pdfExport.test.ts @@ -1,7 +1,16 @@ -import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import fs from 'node:fs' +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' import { decodePDFRawStream, PDFArray, PDFDocument, PDFName, PDFRawStream } from 'pdf-lib' import { readingOrder } from '../shared/frameOrder.ts' -import { mapLimited, pageSizeFor, renderFramePdfPage, selectPdfFrames, takePdfExportSlot } from '../server/pdfExport.ts' +import { + mapLimited, + pageSizeFor, + pdfRendererAvailable, + renderFramePdfPage, + selectPdfFrames, + takePdfExportSlot, +} from '../server/pdfExport.ts' +import { reloadEnv } from '../server/env.ts' import { findBrowserPath } from '../server/screenshot.ts' import type { Canvas, Frame } from '../shared/types.ts' import { Client, startServer, type Server } from './harness.ts' @@ -136,6 +145,27 @@ function visibleFills(pdf: PDFDocument, color: string): Box[] { return fills } +describe('pdfRendererAvailable', () => { + afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllEnvs() + reloadEnv() + }) + + it('counts a remote browser on a server with no local Chrome', () => { + vi.spyOn(fs, 'accessSync').mockImplementation(() => { + throw new Error('ENOENT') + }) + vi.stubEnv('REMOTE_BROWSER_URL', undefined) + reloadEnv() + expect(pdfRendererAvailable()).toBe(false) + + vi.stubEnv('REMOTE_BROWSER_URL', 'wss://browser.example/devtools/browser') + reloadEnv() + expect(pdfRendererAvailable()).toBe(true) + }) +}) + describe('renderFramePdfPage', () => { it.skipIf(!findBrowserPath())( 'keeps a block that straddles the frame’s bottom edge, with viewport units at the frame’s size', diff --git a/tests/publicUrl.test.ts b/tests/publicUrl.test.ts index 7fb550616..c7b52a641 100644 --- a/tests/publicUrl.test.ts +++ b/tests/publicUrl.test.ts @@ -1,5 +1,6 @@ import type { Page } from 'puppeteer-core' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { reloadEnv } from '../server/env.ts' const dnsMocks = vi.hoisted(() => ({ lookup: vi.fn() })) @@ -147,6 +148,52 @@ describe('public Chromium request guard', () => { expect(request.continue).not.toHaveBeenCalled() }) + it('lets a browser off the server network fetch public URLs itself, still refusing private ones', async () => { + const fetchUrl = vi.fn() + const harness = pageHarness() + await guardPublicPageRequests(harness.page, { fetchUrl, offNetwork: true }) + const page = requestStub('https://example.com/style.css', 'stylesheet') + const internal = requestStub('http://169.254.169.254/latest/meta-data/') + const socket = requestStub('file:///etc/passwd') + + harness.dispatch(page) + harness.dispatch(internal) + harness.dispatch(socket) + await vi.waitFor(() => expect(page.continue).toHaveBeenCalledOnce()) + await vi.waitFor(() => expect(internal.abort).toHaveBeenCalledOnce()) + await vi.waitFor(() => expect(socket.abort).toHaveBeenCalledOnce()) + + expect(fetchUrl).not.toHaveBeenCalled() + expect(harness.client.send).toHaveBeenCalledWith('Network.setBlockedURLs', { urls: ['ws://*', 'wss://*'] }) + }) + + it('keeps a remote browser on the pinned proxy unless it is declared isolated', async () => { + vi.stubEnv('REMOTE_BROWSER_URL', 'wss://renderer.internal/devtools/browser') + vi.stubEnv('REMOTE_BROWSER_ISOLATED', undefined) + reloadEnv() + try { + const fetchUrl = vi.fn(async () => new Response('ok', { status: 200 })) + const harness = pageHarness() + await guardPublicPageRequests(harness.page, { fetchUrl }) + const request = requestStub('https://rebind.example/') + + harness.dispatch(request) + await vi.waitFor(() => expect(request.respond).toHaveBeenCalledOnce()) + expect(request.continue).not.toHaveBeenCalled() + + vi.stubEnv('REMOTE_BROWSER_ISOLATED', '1') + reloadEnv() + const isolated = pageHarness() + await guardPublicPageRequests(isolated.page, { fetchUrl }) + const direct = requestStub('https://example.com/') + isolated.dispatch(direct) + await vi.waitFor(() => expect(direct.continue).toHaveBeenCalledOnce()) + } finally { + vi.unstubAllEnvs() + reloadEnv() + } + }) + it('continues only an explicitly trusted local asset URL directly in Chromium', async () => { const fetchUrl = vi.fn() const harness = pageHarness() diff --git a/tests/renderBrowser.test.ts b/tests/renderBrowser.test.ts index 7e9baf82f..faac1f0a5 100644 --- a/tests/renderBrowser.test.ts +++ b/tests/renderBrowser.test.ts @@ -6,6 +6,7 @@ import { RendererBusyError, createRenderer, isBrowserFailure, + remoteConnectFailure, type RendererTuning, } from '../server/renderBrowser.ts' import { MAX_RENDER_PIXELS, renderedHeight } from '../server/renderLimits.ts' @@ -37,14 +38,15 @@ interface FakeBrowser { stallContextClose: boolean contextsOpen: number close: ReturnType + disconnect: ReturnType child: { pid: undefined; exitCode: number | null; signalCode: string | null; kill: ReturnType } createBrowserContext: () => Promise - process: () => FakeBrowser['child'] + process: () => FakeBrowser['child'] | null } function fakeBrowser( label: string, - options: { stallContexts?: boolean; stallClose?: boolean; stallContextClose?: boolean } = {}, + options: { stallContexts?: boolean; stallClose?: boolean; stallContextClose?: boolean; remote?: boolean } = {}, ): FakeBrowser { const browser: FakeBrowser = { label, @@ -56,6 +58,7 @@ function fakeBrowser( /* pid undefined: the kill falls back to child.kill, never a real group */ child: { pid: undefined, exitCode: null, signalCode: null, kill: vi.fn(() => true) }, close: vi.fn(() => (browser.stallClose ? never() : Promise.resolve())), + disconnect: vi.fn(() => Promise.resolve()), createBrowserContext: () => { if (browser.stallContexts) return never() browser.contextsOpen++ @@ -70,7 +73,8 @@ function fakeBrowser( }, }) }, - process: () => browser.child, + /* a remote browser (REMOTE_BROWSER_URL) has no local process */ + process: () => (options.remote ? null : browser.child), } return browser } @@ -249,6 +253,58 @@ describe('a page that will not close', () => { }) }) +describe('a remote browser', () => { + it('is closed once it has had no page for its idle time, and the next page connects afresh', async () => { + const first = fakeBrowser('first', { remote: true }) + const second = fakeBrowser('second', { remote: true }) + const { renderer, launch } = rig([first, second], { idleCloseMs: 30 }) + + const a = await renderer.openPage() + await a.close() + const b = await renderer.openPage() + await tick(50) + /* a page is open: the idle clock does not run */ + expect(first.close).not.toHaveBeenCalled() + await b.close() + await tick(50) + expect(first.close).toHaveBeenCalled() + + const c = await renderer.openPage() + expect(label(c.page)).toBe('second') + expect(launch).toHaveBeenCalledTimes(2) + await c.close() + }) + + it('is disconnected when closing its session stalls, having no process to kill', async () => { + const stuck = fakeBrowser('stuck', { remote: true, stallContexts: true, stallClose: true }) + const { renderer } = rig([stuck, fakeBrowser('fresh', { remote: true })]) + + const handle = await renderer.openPage() + await tick(40) + + expect(stuck.disconnect).toHaveBeenCalled() + await handle.close() + }) +}) + +describe('remoteConnectFailure', () => { + /* what the ws library rejects with when the provider answers the upgrade + with an HTTP error: an ErrorEvent, not an Error */ + const refused = (status: number) => ({ type: 'error', message: `Unexpected server response: ${status}` }) + + it('turns a provider rate limit into a busy renderer', () => { + expect(remoteConnectFailure(refused(429))).toBeInstanceOf(RendererBusyError) + }) + + it('keeps the message of any other refusal, and passes real errors through', () => { + const error = remoteConnectFailure(refused(401)) + expect(error).toBeInstanceOf(Error) + expect(error.message).toBe('could not connect to the remote browser: Unexpected server response: 401') + const timeout = new RenderTimeoutError('connecting to the remote browser', 30_000) + expect(remoteConnectFailure(timeout)).toBe(timeout) + }) +}) + describe('RenderGate', () => { const tuning = { maxConcurrent: 2, maxBackground: 1, maxQueued: 2, queueTimeoutMs: 100 } From 824a1a10ba0404d0cdd9f8d2d6bc829ad956db03 Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Sun, 8 Nov 2026 12:35:47 -0800 Subject: [PATCH 3/6] fix(replay): record prototype player screens in PostHog (#464) The frame replay bridge only reached iframe[data-doop-frame], so the prototype player's screens (data-doop-proto-frame) stayed opaque sandboxed documents and replayed blank. Co-authored-by: Claude Opus 5.5 (1M context) (cherry picked from commit cebc050ac93202eddeb0b470f63be6fe93c1fc56) --- src/lib/frameReplay.ts | 12 +++++++++--- tests/fixtures/frameReplay.html | 4 ++-- tests/frameReplay.test.ts | 14 +++++++++++++- 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/lib/frameReplay.ts b/src/lib/frameReplay.ts index 0dcfee106..574922507 100644 --- a/src/lib/frameReplay.ts +++ b/src/lib/frameReplay.ts @@ -5,11 +5,17 @@ import type { serializedNodeWithId } from 'posthog-js/dist/rrweb-types' type Recorder = typeof record type Options = NonNullable[0]> +/** Every sandboxed design document: canvas frames and prototype player screens. */ +const FRAME_ATTRIBUTES = ['data-doop-frame', 'data-doop-proto-frame'] as const +const FRAME_SELECTOR = FRAME_ATTRIBUTES.map((name) => `iframe[${name}]`).join(', ') +const isFrameElement = (element: unknown): element is HTMLIFrameElement => + element instanceof HTMLIFrameElement && element.matches(FRAME_SELECTOR) + /** Replay must rebuild the recorded DOM, not navigate back to our empty * bootstrap. These attributes are changed only in snapshots; the live iframe * retains its opaque-origin sandbox. The replay sandbox still blocks scripts. */ function prepareFrameNode(node: serializedNodeWithId) { - if ('attributes' in node && node.tagName === 'iframe' && 'data-doop-frame' in node.attributes) { + if ('attributes' in node && node.tagName === 'iframe' && FRAME_ATTRIBUTES.some((name) => name in node.attributes)) { delete node.attributes.srcdoc node.attributes.sandbox = 'allow-same-origin' } @@ -28,7 +34,7 @@ export function installFrameReplay( const original = rrweb.record let options: Options | null = null let generation = 0 - const frames = () => document.querySelectorAll('iframe[data-doop-frame]') + const frames = () => document.querySelectorAll(FRAME_SELECTOR) function send(frame: HTMLIFrameElement, snapshot = false) { frame.contentWindow?.postMessage( { type: 'doop:replay', options, generation, snapshot, url: new URL(recorderUrl, location.href).href }, @@ -81,7 +87,7 @@ export function installFrameReplay( event.data.adds.forEach(({ node }) => prepareFrameNode(node)) for (const mutation of event.data.attributes) { const element = original.mirror.getNode(mutation.id) - if (element instanceof HTMLIFrameElement && element.hasAttribute('data-doop-frame')) { + if (isFrameElement(element)) { delete mutation.attributes.srcdoc if ('sandbox' in mutation.attributes) mutation.attributes.sandbox = 'allow-same-origin' } diff --git a/tests/fixtures/frameReplay.html b/tests/fixtures/frameReplay.html index ecad2ce0c..5d9812aa7 100644 --- a/tests/fixtures/frameReplay.html +++ b/tests/fixtures/frameReplay.html @@ -16,9 +16,9 @@ window.events = [] window.messages = [] window.addEventListener('message', (ev) => window.messages.push(ev.data)) - window.addFrame = () => { + window.addFrame = (attribute = 'data-doop-frame') => { const frame = document.createElement('iframe') - frame.setAttribute('data-doop-frame', '') + frame.setAttribute(attribute, '') frame.sandbox = 'allow-scripts' frame.srcdoc = FRAME_BOOTSTRAP document.body.appendChild(frame) diff --git a/tests/frameReplay.test.ts b/tests/frameReplay.test.ts index 31956e7e0..aa50b8185 100644 --- a/tests/frameReplay.test.ts +++ b/tests/frameReplay.test.ts @@ -13,7 +13,7 @@ declare global { stopReplay: () => void snapshot: () => void renderReplay: (events: ReplayEvent[]) => void - addFrame: () => void + addFrame: (attribute?: string) => void } } @@ -157,6 +157,18 @@ describe.skipIf(!findBrowserPath())('sandboxed frame replay', () => { await captured('Presentation frame') }) + it('records prototype player screens', async () => { + await page.evaluate(() => window.addFrame('data-doop-proto-frame')) + await page.waitForFunction(() => window.messages.filter((m) => m.type === 'doop:frame-ready').length === 3) + await render('

Prototype screen

', 2) + await captured('Prototype screen') + const frame = await page.evaluate( + () => JSON.stringify(window.events).match(/"data-doop-proto-frame":""[^}]*}/)?.[0], + ) + expect(frame).toContain('"sandbox":"allow-same-origin"') + expect(frame).not.toContain('srcdoc') + }) + it('stops child recording, resumes with current content, and applies updated privacy settings', async () => { await page.evaluate(() => window.stopReplay()) await page.evaluate(() => { From 2bfe8f4922cf3f7f6f54664bae08778c3bc05ebf Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Sun, 8 Nov 2026 17:19:36 -0800 Subject: [PATCH 4/6] feat(logos): read .ico favicons and store logo favicons as PNG (#453) search_logos' keyless fallback handed agents DuckDuckGo .ico URLs, which sharp cannot decode. A small decoder now reads the icon's largest entry, PNG or bitmap, with its transparency; the favicon is converted to PNG and stored as a Doop asset (one per domain per process), so frames hold a plain image on our own origin. When an open-source vector mark exists and the only brand hit is a favicon, the vector marks come first and the favicon is labelled as one, in both the MCP tool and the resident agent. (cherry picked from commit b42dc426a05555e4a40f81eb452ba963f4c6cbbe, without the Figma and Canva export paths, which OSS does not ship) Co-Authored-By: Claude Opus 5.5 (1M context) --- server/assets.ts | 12 ++-- server/icoImage.ts | 116 +++++++++++++++++++++++++++++++++++++ server/imageSearch.ts | 82 +++++++++++++++++++++++--- server/mcp.ts | 26 +++++---- server/resident.ts | 32 ++++++---- tests/faviconLogos.test.ts | 77 ++++++++++++++++++++++++ tests/icoFixture.ts | 53 +++++++++++++++++ tests/icoImage.test.ts | 51 ++++++++++++++++ tests/inspiration.test.ts | 11 ++++ 9 files changed, 425 insertions(+), 35 deletions(-) create mode 100644 server/icoImage.ts create mode 100644 tests/faviconLogos.test.ts create mode 100644 tests/icoFixture.ts create mode 100644 tests/icoImage.test.ts diff --git a/server/assets.ts b/server/assets.ts index 9820fb2a1..2790ec0e5 100644 --- a/server/assets.ts +++ b/server/assets.ts @@ -144,9 +144,11 @@ export async function getAsset(id: string): Promise<{ meta: AssetMeta; buf: Buff } /** Fetch a remote image through the SSRF guard, validating every redirect - * hop, with a hard size cap enforced while streaming. */ -export async function fetchRemote(rawUrl: string): Promise { + * hop, with a hard size cap enforced while streaming. A caller that only + * reads a small file (a favicon) may pass a tighter cap than the store's. */ +export async function fetchRemote(rawUrl: string, maxBytes: number = MAX_ASSET_BYTES): Promise { const { fetchPinnedPublicUrl, parsePublicHttpUrl } = await import('./publicUrl.ts') + const tooBig = new Error(`file exceeds the ${Math.round(maxBytes / 1024 / 1024)} MB limit`) let url = parsePublicHttpUrl(rawUrl) for (let hop = 0; hop < 4; hop++) { const res = await fetchPinnedPublicUrl(url, { @@ -161,7 +163,7 @@ export async function fetchRemote(rawUrl: string): Promise { continue } if (!res.ok) throw new Error(`fetch failed: HTTP ${res.status}`) - if (Number(res.headers.get('content-length') || 0) > MAX_ASSET_BYTES) throw new Error('file exceeds the 5 MB limit') + if (Number(res.headers.get('content-length') || 0) > maxBytes) throw tooBig if (!res.body) throw new Error('empty response') const chunks: Uint8Array[] = [] let total = 0 @@ -170,9 +172,9 @@ export async function fetchRemote(rawUrl: string): Promise { const { done, value } = await reader.read() if (done) break total += value.byteLength - if (total > MAX_ASSET_BYTES) { + if (total > maxBytes) { await reader.cancel() - throw new Error('file exceeds the 5 MB limit') + throw tooBig } chunks.push(value) } diff --git a/server/icoImage.ts b/server/icoImage.ts new file mode 100644 index 000000000..0b05b1eb7 --- /dev/null +++ b/server/icoImage.ts @@ -0,0 +1,116 @@ +import sharp from 'sharp' + +/** Windows icon (.ico): what favicon services such as DuckDuckGo's serve, and the one web image format + * libvips cannot read. An entry is either a whole PNG or a headerless BMP (a DIB) with a 1-bit mask. */ + +const PNG_SIGNATURE = 0x474e5089 +const MAX_SIDE = 256 + +interface Entry { + width: number + height: number + bitCount: number + offset: number + size: number +} + +export function isIco(buf: Buffer): boolean { + return buf.length >= 6 && buf.readUInt16LE(0) === 0 && buf.readUInt16LE(2) === 1 && buf.readUInt16LE(4) > 0 +} + +function entries(buf: Buffer): Entry[] { + const count = buf.readUInt16LE(4) + if (buf.length < 6 + count * 16) throw new Error('Truncated icon') + const list: Entry[] = [] + for (let i = 0; i < count; i++) { + const at = 6 + i * 16 + const entry = { + width: buf[at] || 256, + height: buf[at + 1] || 256, + bitCount: buf.readUInt16LE(at + 6), + size: buf.readUInt32LE(at + 8), + offset: buf.readUInt32LE(at + 12), + } + if (entry.size > 0 && entry.offset + entry.size <= buf.length) list.push(entry) + } + if (!list.length) throw new Error('Icon has no readable images') + return list +} + +/** RGBA pixels of a DIB entry, top row first. */ +function decodeDib(dib: Buffer): { data: Buffer; width: number; height: number } { + if (dib.length < 40) throw new Error('Truncated icon image') + const headerSize = dib.readUInt32LE(0) + const width = dib.readInt32LE(4) + const height = Math.abs(dib.readInt32LE(8)) / 2 // the XOR image and the AND mask, stacked + const bitCount = dib.readUInt16LE(14) + const compression = dib.readUInt32LE(16) + const colorsUsed = dib.readUInt32LE(32) + if (width < 1 || width > MAX_SIDE || height < 1 || height > MAX_SIDE || !Number.isInteger(height)) + throw new Error('Unsupported icon size') + if (![1, 4, 8, 24, 32].includes(bitCount) || (compression !== 0 && !(compression === 3 && bitCount === 32))) + throw new Error('Unsupported icon encoding') + + const paletteAt = headerSize + (compression === 3 ? 12 : 0) + const paletteSize = bitCount <= 8 ? colorsUsed || 1 << bitCount : 0 + const pixelsAt = paletteAt + paletteSize * 4 + const stride = Math.ceil((width * bitCount) / 32) * 4 + const maskAt = pixelsAt + stride * height + const maskStride = Math.ceil(width / 32) * 4 + const hasMask = dib.length >= maskAt + maskStride * height + if (dib.length < maskAt) throw new Error('Truncated icon image') + + const data = Buffer.alloc(width * height * 4) + let anyAlpha = false + for (let y = 0; y < height; y++) { + const row = pixelsAt + (height - 1 - y) * stride // rows are stored bottom-up + for (let x = 0; x < width; x++) { + const out = (y * width + x) * 4 + let b: number, g: number, r: number, a: number + if (bitCount === 32 || bitCount === 24) { + const at = row + x * (bitCount / 8) + b = dib[at]! + g = dib[at + 1]! + r = dib[at + 2]! + a = bitCount === 32 ? dib[at + 3]! : 255 + } else { + const bit = x * bitCount + const index = (dib[row + (bit >> 3)]! >> (8 - bitCount - (bit & 7))) & ((1 << bitCount) - 1) + if (index >= paletteSize) throw new Error('Corrupt icon palette') + const at = paletteAt + index * 4 + b = dib[at]! + g = dib[at + 1]! + r = dib[at + 2]! + a = 255 + } + if (bitCount === 32 && a) anyAlpha = true + data[out] = r + data[out + 1] = g + data[out + 2] = b + data[out + 3] = a + } + } + // Transparency comes from the AND mask unless a 32-bit image carries its own alpha. + if (hasMask && !(bitCount === 32 && anyAlpha)) { + for (let y = 0; y < height; y++) { + const row = maskAt + (height - 1 - y) * maskStride + for (let x = 0; x < width; x++) { + const transparent = (dib[row + (x >> 3)]! >> (7 - (x & 7))) & 1 + data[(y * width + x) * 4 + 3] = transparent ? 0 : 255 + } + } + } else if (bitCount === 32 && !anyAlpha) { + for (let i = 3; i < data.length; i += 4) data[i] = 255 + } + return { data, width, height } +} + +/** sharp over any web image, ICO included: the icon's largest, deepest entry. */ +export function readImage(buf: Buffer, options?: sharp.SharpOptions): sharp.Sharp { + if (!isIco(buf)) return sharp(buf, options) + const [best] = entries(buf).sort((a, b) => b.width * b.height - a.width * a.height || b.bitCount - a.bitCount) + const bytes = buf.subarray(best!.offset, best!.offset + best!.size) + if (bytes.length >= 4 && bytes.readUInt32LE(0) === PNG_SIGNATURE) return sharp(bytes, options) + const { data, width, height } = decodeDib(bytes) + return sharp(data, { ...options, raw: { width, height, channels: 4 } }) +} diff --git a/server/imageSearch.ts b/server/imageSearch.ts index 4598156b8..734a08329 100644 --- a/server/imageSearch.ts +++ b/server/imageSearch.ts @@ -1,4 +1,6 @@ import { env } from './env.ts' +import { createAsset, fetchRemote } from './assets.ts' +import { readImage } from './icoImage.ts' /** * Image sourcing for design agents: stock photo search (Pexels) and icon / * brand-logo search (Iconify). Both power the search_images / search_icons @@ -130,6 +132,10 @@ export interface LogoResult { logo_url: string /** Small square icon rendition used for the visual thumbnail. */ thumb_url: string + /** `favicon`: a small raster, the fallback when nothing better exists. */ + source: 'brandfetch' | 'favicon' + /** The thumbnail's bytes when already in hand, so callers need not fetch thumb_url. */ + thumb?: { data: string; mime: string } } interface BrandfetchHit { @@ -157,14 +163,51 @@ export async function searchLogos(query: string, count = 5): Promise>() + +/** DuckDuckGo serves .ico, which few renderers and exporters read; agents get a PNG on our own origin instead. */ +function storeFavicon(domain: string): Promise { + const cached = storedFavicons.get(domain) + if (cached) return cached + const stored = (async () => { + let bytes: Buffer + try { + bytes = await fetchRemote(`${DDG_ICON_ENDPOINT}/${domain}.ico`, MAX_FAVICON_BYTES) + } catch { + return null // DDG 404s for unknown domains + } + const png = await readImage(bytes).png().toBuffer() + const asset = await createAsset(png, { uploadedBy: 'search_logos' }) + return { url: `${env.BETTER_AUTH_URL}/a/${asset.id}.${asset.ext}`, png } + })() + storedFavicons.set(domain, stored) + stored.then( + (result) => { + if (!result) storedFavicons.delete(domain) + }, + () => storedFavicons.delete(domain), + ) + if (storedFavicons.size > FAVICON_CACHE_SIZE) storedFavicons.delete(storedFavicons.keys().next().value!) + return stored +} /** Keyless any-company fallback: the DuckDuckGo favicon service. Resolves the - * query to a domain (used directly if it looks like one, else .com) and - * verifies the icon exists — DDG 404s for unknown domains. Favicons are small + * query to a domain (used directly if it looks like one, else .com), + * converts the icon to PNG and stores it as an asset. Favicons are small * raster images (16–48px), so callers should render them small. */ export async function faviconLogos(query: string): Promise { const q = query @@ -175,16 +218,39 @@ export async function faviconLogos(query: string): Promise { const wasDomain = /^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/.test(q) const domain = wasDomain ? q : `${q.replace(/[^a-z0-9]/g, '')}.com` if (domain === '.com') return [] - const url = `${DDG_ICON_ENDPOINT}/${domain}.ico` try { - const res = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }) - if (!res.ok) return [] - return [{ name: wasDomain ? domain : query.trim(), domain, logo_url: url, thumb_url: url }] + const stored = await storeFavicon(domain) + if (!stored) return [] + return [ + { + name: wasDomain ? domain : query.trim(), + domain, + logo_url: stored.url, + thumb_url: stored.url, + source: 'favicon', + thumb: { data: stored.png.toString('base64'), mime: 'image/png' }, + }, + ] } catch { return [] } } +/** Favicons are the last resort: when an open-source vector mark exists, agents should see it first. */ +export function vectorFirst(brands: LogoResult[], vector: IconResult[]): boolean { + return vector.length > 0 && brands.every((b) => b.source === 'favicon') +} + +/** The brand in a query, for the vector icon search, which matches names, not domains: "visa.com" → "visa". */ +export function brandName(query: string): string { + const q = query + .trim() + .replace(/^https?:\/\//i, '') + .replace(/\/.*$/, '') + .replace(/^www\./i, '') + return /^[a-z0-9][a-z0-9-]*\.[a-z.]{2,}$/i.test(q) ? q.split('.')[0]! : query.trim() +} + /** The full logo lookup behind search_logos: Brandfetch when configured * (high-res, searchable by name), DuckDuckGo favicons as the keyless * any-company fallback, open-source vector marks alongside either way. */ @@ -196,10 +262,10 @@ export async function lookupLogos( (logoSearchEnabled() ? searchLogos(query, count).catch(() => [] as LogoResult[]) : Promise.resolve([])).then((b) => b.length > 0 ? b : faviconLogos(query), ), - searchIcons(query, { logos: true, limit: 6 }).catch(() => [] as IconResult[]), + searchIcons(brandName(query), { logos: true, limit: 6 }).catch(() => [] as IconResult[]), ]) return { brands, vector } } export const LOGO_USAGE_NOTE = - 'Hotlink logo_url directly in . URLs from icons.duckduckgo.com are the company\'s favicon — a SMALL raster (16–48px): display at 32px or less (logo rows, avatars, list bullets) and never scale up; if the design needs a large logo, prefer a vector mark below or ask your human for a logo file. URLs from cdn.brandfetch.io are high-res and stay current if the brand rebrands; size with CSS (height + width: auto). Vector marks are open-source SVG: "logos:" ids are full-color, "simple-icons:" ids are monochrome glyphs that take ?color=%23.' + 'Hotlink logo_url directly in . Prefer a vector mark over a result marked "favicon" whenever one exists. A favicon is a SMALL raster (16–48px PNG): display it at 32px or less (logo rows, avatars, list bullets) and never scale up; if the design needs a large logo and no vector mark exists, ask your human for a logo file. URLs from cdn.brandfetch.io are high-res and stay current if the brand rebrands; size with CSS (height + width: auto). Vector marks are open-source SVG: "logos:" ids are full-color, "simple-icons:" ids are monochrome glyphs that take ?color=%23.' diff --git a/server/mcp.ts b/server/mcp.ts index 96084767f..560131e37 100644 --- a/server/mcp.ts +++ b/server/mcp.ts @@ -1815,23 +1815,29 @@ export function buildMcpServer( }) type ResultBlock = { type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string } const content: ResultBlock[] = [{ type: 'text' as const, text: `Logo results for "${query}":` }] + const brandBlocks: ResultBlock[] = [] if (brands.length > 0) { - const thumbs = await Promise.all(brands.map((b) => imageSearch.fetchThumb(b.thumb_url))) + const thumbs = await Promise.all(brands.map((b) => b.thumb ?? imageSearch.fetchThumb(b.thumb_url))) brands.forEach((b, i) => { const thumb = thumbs[i] - if (thumb) content.push({ type: 'image' as const, data: thumb.data, mimeType: thumb.mime }) - content.push({ + if (thumb) brandBlocks.push({ type: 'image' as const, data: thumb.data, mimeType: thumb.mime }) + brandBlocks.push({ type: 'text' as const, - text: `#${i + 1} — ${b.name} (${b.domain})\nlogo_url: ${b.logo_url}`, + text: `#${i + 1} — ${b.name} (${b.domain})${b.source === 'favicon' ? ' · favicon' : ''}\nlogo_url: ${b.logo_url}`, }) }) } - if (vector.length > 0) { - content.push({ - type: 'text' as const, - text: `Open-source vector marks:\n${vector.map((v) => `${v.id} → ${v.svg_url}`).join('\n')}`, - }) - } + const vectorBlocks: ResultBlock[] = + vector.length > 0 + ? [ + { + type: 'text' as const, + text: `Open-source vector marks:\n${vector.map((v) => `${v.id} → ${v.svg_url}`).join('\n')}`, + }, + ] + : [] + if (imageSearch.vectorFirst(brands, vector)) content.push(...vectorBlocks, ...brandBlocks) + else content.push(...brandBlocks, ...vectorBlocks) content.push({ type: 'text' as const, text: imageSearch.LOGO_USAGE_NOTE }) const result = { content } return canvas_id ? withFeedbackNotice(result, canvas_id, actorFrom(agent_name)) : result diff --git a/server/resident.ts b/server/resident.ts index b1a359a8c..3797aa623 100644 --- a/server/resident.ts +++ b/server/resident.ts @@ -1888,15 +1888,15 @@ export async function execTool( `no logo found for "${query}" — retry with the company's exact domain (e.g. "acme.io"); if that also fails, search a different real brand instead of drawing a placeholder or guessing a logo URL`, ) } - const blocks: NonNullable> = [ - { type: 'text', text: `Logo results for "${query}":` }, - ] + type Blocks = NonNullable> + const blocks: Blocks = [{ type: 'text', text: `Logo results for "${query}":` }] + const brandBlocks: Blocks = [] if (brands.length > 0) { - const thumbs = await Promise.all(brands.map((b) => imageSearch.fetchThumb(b.thumb_url))) + const thumbs = await Promise.all(brands.map((b) => b.thumb ?? imageSearch.fetchThumb(b.thumb_url))) brands.forEach((b, i) => { const thumb = thumbs[i] if (thumb) - blocks.push({ + brandBlocks.push({ type: 'image', source: { type: 'base64', @@ -1904,15 +1904,23 @@ export async function execTool( data: thumb.data, }, }) - blocks.push({ type: 'text', text: `#${i + 1} — ${b.name} (${b.domain})\nlogo_url: ${b.logo_url}` }) - }) - } - if (vector.length > 0) { - blocks.push({ - type: 'text', - text: `Open-source vector marks:\n${vector.map((v) => `${v.id} → ${v.svg_url}`).join('\n')}`, + brandBlocks.push({ + type: 'text', + text: `#${i + 1} — ${b.name} (${b.domain})${b.source === 'favicon' ? ' · favicon' : ''}\nlogo_url: ${b.logo_url}`, + }) }) } + const vectorBlocks: Blocks = + vector.length > 0 + ? [ + { + type: 'text', + text: `Open-source vector marks:\n${vector.map((v) => `${v.id} → ${v.svg_url}`).join('\n')}`, + }, + ] + : [] + if (imageSearch.vectorFirst(brands, vector)) blocks.push(...vectorBlocks, ...brandBlocks) + else blocks.push(...brandBlocks, ...vectorBlocks) blocks.push({ type: 'text', text: imageSearch.LOGO_USAGE_NOTE }) return ok(blocks) } diff --git a/tests/faviconLogos.test.ts b/tests/faviconLogos.test.ts new file mode 100644 index 000000000..db6ca5bf6 --- /dev/null +++ b/tests/faviconLogos.test.ts @@ -0,0 +1,77 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import sharp from 'sharp' +import { dibIcon } from './icoFixture.ts' + +const fetchRemote = vi.fn<(url: string, maxBytes?: number) => Promise>() +const createAsset = + vi.fn<(buf: Buffer, meta: object) => Promise<{ id: string; ext: string; mime: string; size: number }>>() +vi.mock('../server/assets.ts', () => ({ fetchRemote, createAsset })) + +const { brandName, faviconLogos, vectorFirst } = await import('../server/imageSearch.ts') + +describe('faviconLogos', () => { + beforeEach(() => { + fetchRemote.mockReset() + createAsset.mockReset() + createAsset.mockImplementation(async (buf) => ({ + id: `asset${createAsset.mock.calls.length}`, + ext: 'png', + mime: 'image/png', + size: buf.length, + })) + }) + + it('stores the icon as a PNG asset and hands out that URL', async () => { + fetchRemote.mockResolvedValue(dibIcon(2, 32, () => [255, 0, 0, 255])) + const [logo] = await faviconLogos('visa.com') + expect(fetchRemote.mock.calls[0]?.[0]).toBe('https://icons.duckduckgo.com/ip3/visa.com.ico') + expect(logo?.logo_url).toMatch(/\/a\/asset1\.png$/) + expect(logo?.source).toBe('favicon') + const stored = createAsset.mock.calls[0]![0] + const meta = await sharp(stored).metadata() + expect([meta.format, meta.width, meta.height]).toEqual(['png', 2, 2]) + expect(logo?.thumb).toEqual({ data: stored.toString('base64'), mime: 'image/png' }) + }) + + it('reuses one asset per domain', async () => { + fetchRemote.mockResolvedValue(dibIcon(2, 32, () => [255, 0, 0, 255])) + const [first] = await faviconLogos('stripe') + const [second] = await faviconLogos('stripe.com') + expect(second?.logo_url).toBe(first?.logo_url) + expect(createAsset).toHaveBeenCalledTimes(1) + }) + + it('finds nothing for a domain DuckDuckGo does not know, and asks again next time', async () => { + fetchRemote.mockRejectedValue(new Error('fetch failed: HTTP 404')) + expect(await faviconLogos('nosuchco.io')).toEqual([]) + expect(await faviconLogos('nosuchco.io')).toEqual([]) + expect(fetchRemote).toHaveBeenCalledTimes(2) + expect(createAsset).not.toHaveBeenCalled() + }) + + it('finds nothing when the bytes are not an image', async () => { + fetchRemote.mockResolvedValue(Buffer.from('not an icon')) + expect(await faviconLogos('broken.dev')).toEqual([]) + expect(createAsset).not.toHaveBeenCalled() + }) +}) + +describe('vectorFirst', () => { + const favicon = { name: 'Visa', domain: 'visa.com', logo_url: '', thumb_url: '', source: 'favicon' as const } + const vector = [{ id: 'logos:visa', svg_url: 'https://api.iconify.design/logos/visa.svg' }] + + it('puts vector marks ahead of favicons only', () => { + expect(vectorFirst([favicon], vector)).toBe(true) + expect(vectorFirst([{ ...favicon, source: 'brandfetch' }], vector)).toBe(false) + expect(vectorFirst([favicon], [])).toBe(false) + }) +}) + +describe('brandName', () => { + it('searches vector marks by the name in a domain', () => { + expect(brandName('visa.com')).toBe('visa') + expect(brandName('https://www.linear.app/pricing')).toBe('linear') + expect(brandName('bbc.co.uk')).toBe('bbc') + expect(brandName('Stripe Climate')).toBe('Stripe Climate') + }) +}) diff --git a/tests/icoFixture.ts b/tests/icoFixture.ts new file mode 100644 index 000000000..fe7165e2f --- /dev/null +++ b/tests/icoFixture.ts @@ -0,0 +1,53 @@ +/** Windows icons built byte by byte, the shape favicon services such as DuckDuckGo's serve. */ + +/** One-entry .ico around a DIB: BGRA (32-bit) or palette indexes (8-bit), bottom-up, plus an AND mask. */ +export function dibIcon( + size: number, + bitCount: 32 | 8, + pixel: (x: number, y: number) => [number, number, number, number], +) { + const palette: number[][] = [] + const stride = Math.ceil((size * bitCount) / 32) * 4 + const maskStride = Math.ceil(size / 32) * 4 + const pixels = Buffer.alloc(stride * size) + const mask = Buffer.alloc(maskStride * size) + for (let y = 0; y < size; y++) { + const row = size - 1 - y + for (let x = 0; x < size; x++) { + const [r, g, b, a] = pixel(x, y) + if (bitCount === 32) pixels.set([b, g, r, a], row * stride + x * 4) + else { + let index = palette.findIndex((c) => c[0] === r && c[1] === g && c[2] === b) + if (index < 0) index = palette.push([r, g, b]) - 1 + pixels[row * stride + x] = index + if (!a) mask[row * maskStride + (x >> 3)]! |= 0x80 >> (x & 7) + } + } + } + const header = Buffer.alloc(40) + header.writeUInt32LE(40, 0) + header.writeInt32LE(size, 4) + header.writeInt32LE(size * 2, 8) + header.writeUInt16LE(1, 12) + header.writeUInt16LE(bitCount, 14) + header.writeUInt32LE(bitCount === 8 ? palette.length : 0, 32) + const colors = Buffer.from(palette.flatMap(([r, g, b]) => [b!, g!, r!, 0])) + return icon([Buffer.concat([header, colors, pixels, mask])], [size]) +} + +export function icon(images: Buffer[], sizes: number[]) { + const dir = Buffer.alloc(6 + images.length * 16) + dir.writeUInt16LE(1, 2) + dir.writeUInt16LE(images.length, 4) + let offset = dir.length + images.forEach((image, i) => { + const at = 6 + i * 16 + dir[at] = sizes[i]! % 256 + dir[at + 1] = sizes[i]! % 256 + dir.writeUInt16LE(32, at + 6) + dir.writeUInt32LE(image.length, at + 8) + dir.writeUInt32LE(offset, at + 12) + offset += image.length + }) + return Buffer.concat([dir, ...images]) +} diff --git a/tests/icoImage.test.ts b/tests/icoImage.test.ts new file mode 100644 index 000000000..62edb2eca --- /dev/null +++ b/tests/icoImage.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest' +import sharp from 'sharp' +import { isIco, readImage } from '../server/icoImage.ts' +import { dibIcon, icon } from './icoFixture.ts' + +async function rgba(buf: Buffer) { + const { data, info } = await readImage(buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true }) + const at = (x: number, y: number) => [...data.subarray((y * info.width + x) * 4, (y * info.width + x) * 4 + 4)] + return { width: info.width, height: info.height, at } +} + +describe('readImage', () => { + it('decodes a 32-bit icon top row first, keeping its alpha', async () => { + const buf = dibIcon(4, 32, (x, y) => (y === 0 ? [255, 0, 0, 255] : x === 3 ? [0, 0, 0, 0] : [0, 0, 255, 128])) + expect(isIco(buf)).toBe(true) + const image = await rgba(buf) + expect([image.width, image.height]).toEqual([4, 4]) + expect(image.at(0, 0)).toEqual([255, 0, 0, 255]) + expect(image.at(1, 2)).toEqual([0, 0, 255, 128]) + expect(image.at(3, 3)[3]).toBe(0) + }) + + it('reads a palette icon with its transparency mask', async () => { + const image = await rgba(dibIcon(9, 8, (x) => (x < 4 ? [0, 128, 0, 255] : [0, 0, 0, 0]))) + expect(image.at(1, 5)).toEqual([0, 128, 0, 255]) + expect(image.at(8, 5)[3]).toBe(0) + }) + + it('picks the largest entry, PNG entries included', async () => { + const png = await sharp({ create: { width: 48, height: 48, channels: 4, background: '#123456' } }) + .png() + .toBuffer() + const small = dibIcon(16, 32, () => [255, 255, 255, 255]).subarray(22) + const image = await rgba(icon([small, png], [16, 48])) + expect([image.width, image.height]).toEqual([48, 48]) + expect(image.at(10, 10)).toEqual([0x12, 0x34, 0x56, 255]) + }) + + it('leaves every other format to sharp', async () => { + const png = await sharp({ create: { width: 2, height: 2, channels: 3, background: '#fff' } }) + .png() + .toBuffer() + expect(isIco(png)).toBe(false) + expect((await rgba(png)).width).toBe(2) + }) + + it('rejects a truncated icon instead of reading past it', () => { + const buf = dibIcon(4, 32, () => [0, 0, 0, 255]) + expect(() => readImage(buf.subarray(0, 40))).toThrow() + }) +}) diff --git a/tests/inspiration.test.ts b/tests/inspiration.test.ts index 1da5c6219..20295a992 100644 --- a/tests/inspiration.test.ts +++ b/tests/inspiration.test.ts @@ -2,6 +2,15 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js' import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { reloadEnv } from '../server/env.ts' + +// search_logos' favicon fallback downloads through fetchRemote and stores an asset; keep both offline. +const fetchRemote = vi.hoisted(() => vi.fn(async () => Promise.reject(new Error('fetch failed: HTTP 404')))) +const createAsset = vi.hoisted(() => vi.fn()) +vi.mock('../server/assets.ts', async (original) => ({ + ...(await original()), + fetchRemote, + createAsset, +})) import { buildMcpServer } from '../server/mcp.ts' import { clearInspirationCache, @@ -195,6 +204,8 @@ describe('search_logos without an inspiration key', () => { arguments: { query: 'vercel.com', agent_name: 'Tester' }, })) as { content: { text?: string }[] } expect(JSON.stringify(result.content)).not.toContain(INSPIRATION_UNAVAILABLE_NOTE) + expect(fetchRemote).toHaveBeenCalledWith('https://icons.duckduckgo.com/ip3/vercel.com.ico', expect.any(Number)) + expect(createAsset).not.toHaveBeenCalled() } finally { await client.close() await server.close() From 0c01ed93d2cbdb5680ea184194d79f2bf8e3e9dc Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Sun, 8 Nov 2026 17:28:02 -0800 Subject: [PATCH 5/6] fix(export): fit every export scale to the renderer's pixel budget fitExportScale allowed 64 MP and never went below 2x, while the server renderer cuts a screenshot at 50 MP, so a 1440x2560 frame at 4x (or a tall frame at 2x) downloaded with its bottom silently missing. One budget now serves both, and any scale comes down to fit it. Co-Authored-By: Claude Opus 5.5 (1M context) --- .context/TECHSTACK.md | 5 +++-- server/renderLimits.ts | 6 ++++-- shared/exportScale.ts | 29 ++++++++++++++++------------- tests/exportScale.test.ts | 34 +++++++++++++++++++++++++++++----- 4 files changed, 52 insertions(+), 22 deletions(-) diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index 80b73aede..cd1e4ab03 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -234,8 +234,9 @@ data-doop-webfonts>` for the roster families the frame names and does not load i `ExportOptions.tsx`): the Inspector's Export group and the Export… dialog (frames, and elements from their menu) pick 0.5x / 1x / 2x / 3x / 4x or a typed multiplier (0.1-4, two decimals) and PNG / JPG / SVG, remembered per browser under `doop:export-settings` (2x PNG by default) and - named `Name@2x.png` as Figma does. Up to 2x a scale is honoured as before; above it, - `fitExportScale` brings a huge frame down to 16,384 px a side and 64 MP, the same limit + named `Name@2x.png` as Figma does. `fitExportScale` brings any scale a huge frame cannot + take down to 16,384 px a side and 50 MP (below 2x too), the budget the server's renderer + cuts a screenshot at (`renderedHeight`), so no export is cut short; the same limit for the browser render, `/i/.png?scale=` (any parsed scale, 1x when unreadable) and MCP `export_frame`'s `scale`, and the toast says so. SVG is `frameSvg`: the inlined document `inlineDocument` already builds, cropped by `viewBox` for an element, on white, settled for diff --git a/server/renderLimits.ts b/server/renderLimits.ts index c3dbf8e5f..b5595cfa6 100644 --- a/server/renderLimits.ts +++ b/server/renderLimits.ts @@ -1,10 +1,12 @@ +import { MAX_EXPORT_PIXELS } from '../shared/exportScale.ts' import type { Frame } from '../shared/types.ts' /** The device pixels one screenshot may hold. A 1440px frame at 2x keeps * about 8,600 CSS px of height; past that the image is cut at the bottom * rather than asking Chromium for a bitmap big enough to stall the browser - * every other render shares. */ -export const MAX_RENDER_PIXELS = 50_000_000 + * every other render shares. Exports never reach it: `fitExportScale` + * brings their scale down to this same budget first. */ +export const MAX_RENDER_PIXELS = MAX_EXPORT_PIXELS /** The CSS px height a render of `frame` covers: the frame, cut at * `maxHeight` and at the pixel budget. */ diff --git a/shared/exportScale.ts b/shared/exportScale.ts index f1b46c9c9..1315929e4 100644 --- a/shared/exportScale.ts +++ b/shared/exportScale.ts @@ -9,12 +9,15 @@ export const MAX_EXPORT_SCALE = 4 /** Every export before the picker was 2x, and it stays the default. */ export const DEFAULT_EXPORT_SCALE = 2 -/* What one render may cost above the old 2x: a canvas side engines still - draw, and a pixel budget (about 256 MB of RGBA) that keeps the public - image route from rendering anything vast. 4x of a 1080 x 1350 poster is - 23 MP, of a 1920 x 1080 slide 33 MP. */ +/* What one render may cost: a canvas side engines still draw, and a pixel + budget (about 200 MB of RGBA) that keeps the public image route from + rendering anything vast. The server's renderer cuts a screenshot at the + same budget (`renderedHeight`), so an export fitted here is never cut. + 4x of a 1080 x 1350 poster is 23 MP, of a 1920 x 1080 slide 33 MP. */ export const MAX_EXPORT_SIDE = 16_384 -export const MAX_EXPORT_PIXELS = 64_000_000 +export const MAX_EXPORT_PIXELS = 50_000_000 +/* the floor a vast frame comes down to; its render is cut below that */ +const MIN_FITTED_SCALE = 0.01 /** A multiplier as typed or sent: `2`, `"2"`, `"1.5x"`, `"3×"`, and a * decimal comma as Portuguese writes it (`"0,5"`). Kept to two decimals @@ -29,16 +32,16 @@ export function parseExportScale(raw: unknown): number | null { return scale } -/** The scale a box of this size actually renders at. Up to 2x it is what - * was asked, as every export was before; above, it comes down until the - * image fits `MAX_EXPORT_SIDE` and `MAX_EXPORT_PIXELS`, never below 2x. */ +/** The scale a box of this size actually renders at: what was asked, or + * less until the image fits `MAX_EXPORT_SIDE` and `MAX_EXPORT_PIXELS`, so + * the whole frame is in it rather than a top cut off at the budget. */ export function fitExportScale(size: { width: number; height: number }, wanted: number): number { - if (wanted <= DEFAULT_EXPORT_SCALE) return wanted - const width = Math.max(1, size.width) - const height = Math.max(1, size.height) + /* rounded as the renderers round, so a fitted scale stays within their budget */ + const width = Math.max(1, Math.round(size.width)) + const height = Math.max(1, Math.round(size.height)) const largest = Math.min(MAX_EXPORT_SIDE / Math.max(width, height), Math.sqrt(MAX_EXPORT_PIXELS / (width * height))) - const fitted = Math.floor(Math.min(wanted, largest) * 100) / 100 - return Math.max(DEFAULT_EXPORT_SCALE, fitted) + if (wanted <= largest) return wanted + return Math.max(MIN_FITTED_SCALE, Math.floor(largest * 100) / 100) } /** `2x`, `1.5x`: how the picker, the toast and the hints name a scale. */ diff --git a/tests/exportScale.test.ts b/tests/exportScale.test.ts index fe52b4938..0b9043340 100644 --- a/tests/exportScale.test.ts +++ b/tests/exportScale.test.ts @@ -8,6 +8,7 @@ import { MAX_EXPORT_SIDE, parseExportScale, } from '../shared/exportScale' +import { renderedHeight } from '../server/renderLimits' import { readExportSettings } from '../src/lib/exportSettings' describe('parseExportScale', () => { @@ -34,8 +35,8 @@ describe('parseExportScale', () => { }) describe('fitExportScale', () => { - it('gives what was asked up to 2x, however large the frame, as every export did before', () => { - expect(fitExportScale({ width: 1440, height: 30_000 }, 2)).toBe(2) + it('gives an ordinary frame what was asked', () => { + expect(fitExportScale({ width: 1440, height: 900 }, 2)).toBe(2) expect(fitExportScale({ width: 1440, height: 30_000 }, 0.5)).toBe(0.5) }) @@ -44,14 +45,21 @@ describe('fitExportScale', () => { expect(fitExportScale({ width: 1920, height: 1080 }, 4)).toBe(4) }) - it('brings a large pick down to the pixel budget, never below 2x', () => { - const page = { width: 1440, height: 6000 } + it('brings a large pick down to the pixel budget', () => { + const page = { width: 1440, height: 2560 } const fitted = fitExportScale(page, 4) expect(fitted).toBeLessThan(4) expect(fitted).toBeGreaterThan(2) const { width, height } = exportPixelSize(page, fitted) expect(width * height).toBeLessThanOrEqual(MAX_EXPORT_PIXELS) - expect(fitExportScale({ width: 1440, height: 20_000 }, 4)).toBe(2) + }) + + it('goes below 2x for a frame too tall for it, rather than leaving the renderer to cut it', () => { + const tall = { width: 1440, height: 20_000 } + const fitted = fitExportScale(tall, 2) + expect(fitted).toBeLessThan(2) + const { width, height } = exportPixelSize(tall, fitted) + expect(width * height).toBeLessThanOrEqual(MAX_EXPORT_PIXELS) }) it('keeps the longest side drawable', () => { @@ -59,6 +67,22 @@ describe('fitExportScale', () => { const fitted = fitExportScale(strip, 4) expect(exportPixelSize(strip, fitted).height).toBeLessThanOrEqual(MAX_EXPORT_SIDE) }) + + it('never hands the server renderer a scale it would crop', () => { + const sizes = [ + { width: 1440, height: 2560 }, + { width: 1440, height: 9000 }, + { width: 1440, height: 40_000 }, + { width: 375.4, height: 12_345.6 }, + { width: 3000, height: 3000 }, + ] + for (const size of sizes) { + for (const wanted of [0.5, 1, 2, 3, 4]) { + const scale = fitExportScale(size, wanted) + expect(renderedHeight(size, scale)).toBe(Math.round(size.height)) + } + } + }) }) it('names a scale and its file suffix as Figma does', () => { From 61d0bbcab5288e39d8d00993f7826630ff3fa358 Mon Sep 17 00:00:00 2001 From: Kevin Goedecke Date: Sat, 21 Nov 2026 02:18:33 -0800 Subject: [PATCH 6/6] fix(export): preserve full frames within the server screenshot budget --- .context/TECHSTACK.md | 7 ++- server/index.ts | 11 +++-- server/layerExport.ts | 5 +- server/mcp.ts | 13 +++-- server/renderLimits.ts | 7 +-- shared/elementId.ts | 3 ++ shared/exportScale.ts | 17 +++++++ src/lib/frameExport.ts | 95 ++++++++++++++++++++++--------------- tests/frameExport.test.ts | 29 +++++++++++ tests/mcpPdfExport.test.ts | 7 +++ tests/renderBrowser.test.ts | 23 ++++++++- 11 files changed, 158 insertions(+), 59 deletions(-) diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index 609c42c44..09dc0c436 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -396,7 +396,8 @@ data-doop-webfonts>` for the roster families the frame names and does not load i `copyElementPng`): the frame is rendered whole and cut to the element's live box (`doop:inspect` rect, `clipToFrame`, the raster's `clip` option), so every style it inherits and whatever paints behind it stay in the picture; a server render is cropped here the same - way (`cropRaster`), and a frame off screen says so. The element panel's Design tab ends with the same + way (`cropRaster`), unless a full screenshot would reduce a small layer’s density, in which case Chromium captures + the layer by selector. A frame off screen says so. The element panel's Design tab ends with the same Export section (`LayerExportSection.tsx`: the shared scale and format, "Export ", Copy as PNG), as Figma ends a layer's properties. Agents export a layer with `export_layer` (MCP and the resident, `server/layerExport.ts`), named by `element_id` (its `data-doop-id`) or a CSS @@ -412,7 +413,9 @@ data-doop-webfonts>` for the roster families the frame names and does not load i named `Name@2x.png` as Figma does. Up to 2x a scale is honoured as before; above it, `fitExportScale` brings a huge frame down to 16,384 px a side and 64 MP, the same limit for the browser render, `/i/.png?scale=` (any parsed scale, 1x when unreadable) and MCP - `export_frame`'s `scale`, and the toast says so. SVG is `frameSvg`: the inlined document + `export_frame`'s `scale`. Full-frame server exports then reduce density only when the + screenshot would otherwise lose rows at Chromium’s 50 MP capture limit. The download names + the density actually used, and the toast reports a reduction. SVG is `frameSvg`: the inlined document `inlineDocument` already builds, cropped by `viewBox` for an element, on white, settled for a file opened as a page, where the viewer's window would be the viewport (`standalone`, `FrameViewport`): viewport units become the frame's px, `@media` rules and `