Skip to content
7 changes: 5 additions & 2 deletions .context/TECHSTACK.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <layer>", 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
Expand All @@ -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/<id>.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 `<style media>` are
Expand Down
11 changes: 7 additions & 4 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ import { customAgentsRouter } from './customAgentRoutes.ts'
import { activeAgentTasks } from '../shared/agentActivity.ts'
import { colorFor } from '../shared/types.ts'
import { isPeerViewport } from '../shared/viewport.ts'
import { exportScaleSuffix, fitExportScale, parseExportScale } from '../shared/exportScale.ts'
import { exportScaleSuffix, fitExportScale, fullFrameRenderScale, parseExportScale } from '../shared/exportScale.ts'
import { emailShare } from './canvasShares.ts'
import * as userEvents from './userEvents.ts'
import type { Actor, Canvas, ClientMessage, Presence, ServerMessage } from '../shared/types.ts'
Expand Down Expand Up @@ -555,15 +555,17 @@ app.get('/i/:id.:ext', async (req, res) => {
if (layer === null) return res.status(400).json({ error: 'element must be a data-doop-id; selector a CSS selector' })
/* any multiplier the export picker offers; a missing or unreadable one
is 1x, as before there was a picker */
const scale = fitExportScale(frame, parseExportScale(req.query.scale) ?? 1)
const requested = fitExportScale(frame, parseExportScale(req.query.scale) ?? 1)
const preview = !layer && ext === 'jpg' && req.query.preview !== undefined
const scale = layer || preview ? requested : fullFrameRenderScale(frame, requested)
let result: Awaited<ReturnType<typeof getImage>>
try {
result = await getImage(frame, {
ext,
scale,
quality: Math.min(100, Math.max(1, Number(req.query.quality) || 90)),
/* ?preview — the dashboard-card variant; see previews.ts */
preview: !layer && req.query.preview !== undefined,
preview,
layer: layer ? layerSelector(layer) : undefined,
ip: req.ip ?? 'unknown',
/* the render limit targets anonymous hotlink abuse — a logged-in user
Expand Down Expand Up @@ -3224,7 +3226,8 @@ app.get('/api/frames/:id/screenshot.png', async (req, res) => {
if (!frame) return
try {
const { renderFrame } = await import('./screenshot.ts')
const png = await renderFrame(frame, fitExportScale(frame, parseExportScale(req.query.scale) ?? 1))
const scale = fitExportScale(frame, parseExportScale(req.query.scale) ?? 1)
const png = await renderFrame(frame, fullFrameRenderScale(frame, scale))
res.type('png').send(png)
} catch (e) {
sendRenderFailure(res, e)
Expand Down
5 changes: 1 addition & 4 deletions server/layerExport.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { DEFAULT_EXPORT_SCALE, exportPixelSize, fitExportScale, parseExportScale } from '../shared/exportScale.ts'
import { elementIdSelector, isElementId } from '../shared/elementId.ts'
import { elementIdSelector, isElementId, MAX_LAYER_SELECTOR_CHARS } from '../shared/elementId.ts'
import type { Frame } from '../shared/types.ts'
import { env } from './env.ts'
import { hasElementId } from './elementIds.ts'
Expand All @@ -12,9 +12,6 @@ import { hasElementId } from './elementIds.ts'
* which re-renders when the frame changes, like a frame's image URL.
*/

/** A selector is free text in a public URL: long enough for any real one. */
export const MAX_LAYER_SELECTOR_CHARS = 500

/** The layer an export names: its stamped id, or any CSS selector. */
export type LayerRef = { elementId: string } | { selector: string }

Expand Down
13 changes: 8 additions & 5 deletions server/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,15 @@ import {
takePdfExportSlot,
} from './pdfExport.ts'
import { primeImage } from './previews.ts'
import { MAX_LAYER_SELECTOR_CHARS, layerExport } from './layerExport.ts'
import { MAX_LAYER_SELECTOR_CHARS } from '../shared/elementId.ts'
import { layerExport } from './layerExport.ts'
import {
DEFAULT_EXPORT_SCALE,
MAX_EXPORT_SCALE,
MIN_EXPORT_SCALE,
exportPixelSize,
fitExportScale,
fullFrameRenderScale,
parseExportScale,
} from '../shared/exportScale.ts'
import { COMPOSE_CHECK, GUIDE_TOPIC_SUMMARIES, GUIDE_TOPICS, guideFor } from './guide.ts'
Expand Down Expand Up @@ -1658,11 +1660,12 @@ export function buildMcpServer(owner?: string, ownerId?: string, clientName?: st
if (format === 'pdf') return exportPdf(f, frame_ids ?? [])
const ext = format === 'jpg' ? 'jpg' : 'png'
const q = ext === 'jpg' ? `&quality=${quality ?? 90}` : ''
const density = fitExportScale(f, parseExportScale(scale ?? DEFAULT_EXPORT_SCALE) ?? DEFAULT_EXPORT_SCALE)
const pixels = exportPixelSize(f, density)
const requested = fitExportScale(f, parseExportScale(scale ?? DEFAULT_EXPORT_SCALE) ?? DEFAULT_EXPORT_SCALE)
const density = fullFrameRenderScale(f, requested)
const pixels = exportPixelSize({ width: Math.round(f.width), height: Math.round(f.height) }, density)
return text({
image_url: `${env.BETTER_AUTH_URL}/i/${frame_id}.${ext}?scale=${density}${q}`,
download_url: `${env.BETTER_AUTH_URL}/i/${frame_id}.${ext}?scale=${density}${q}&download`,
image_url: `${env.BETTER_AUTH_URL}/i/${frame_id}.${ext}?scale=${requested}${q}`,
download_url: `${env.BETTER_AUTH_URL}/i/${frame_id}.${ext}?scale=${requested}${q}&download`,
scale: density,
width: pixels.width,
height: pixels.height,
Expand Down
7 changes: 1 addition & 6 deletions server/renderLimits.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
import { MAX_RENDER_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

/** The CSS px height a render of `frame` covers: the frame, cut at
* `maxHeight` and at the pixel budget. */
export function renderedHeight(frame: Pick<Frame, 'width' | 'height'>, scale: number, maxHeight?: number): number {
Expand Down
3 changes: 3 additions & 0 deletions shared/elementId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@

export const ELEMENT_ID_ATTR = 'data-doop-id'

/** A selector is free text in a public URL: long enough for any real one. */
export const MAX_LAYER_SELECTOR_CHARS = 500

const ID_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789'
const ID_LENGTH = 6

Expand Down
17 changes: 17 additions & 0 deletions shared/exportScale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,23 @@ export function fitExportScale(size: { width: number; height: number }, wanted:
return Math.max(DEFAULT_EXPORT_SCALE, fitted)
}

/** Chromium clips screenshots at this many device pixels. */
export const MAX_RENDER_PIXELS = 50_000_000

/** Fit an already-selected scale to a full server screenshot. Layers and
* browser renders have their own output bounds. */
export function fullFrameRenderScale(size: { width: number; height: number }, scale: number): number {
const width = Math.max(1, Math.round(size.width))
const height = Math.max(1, Math.round(size.height))
if (height <= MAX_RENDER_PIXELS / (width * scale * scale)) return scale
const limit = Math.sqrt(MAX_RENDER_PIXELS / width / height)
// Round down so the renderer can capture the final row, including at a
// floating-point boundary. Very large frames can need less than 0.01x.
const rounded = Math.floor(limit * 100) / 100
if (rounded > 0 && height <= MAX_RENDER_PIXELS / (width * rounded * rounded)) return rounded
return limit * (1 - Number.EPSILON)
}

/** `2x`, `1.5x`: how the picker, the toast and the hints name a scale. */
export function formatExportScale(scale: number): string {
return `${scale}x`
Expand Down
95 changes: 58 additions & 37 deletions src/lib/frameExport.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { pdfRenderBudgetMs } from '../../shared/pdfLimits'
import { DEFAULT_EXPORT_SCALE, exportScaleSuffix, fitExportScale, formatExportScale } from '../../shared/exportScale'
import {
DEFAULT_EXPORT_SCALE,
exportScaleSuffix,
fitExportScale,
formatExportScale,
fullFrameRenderScale,
} from '../../shared/exportScale'
import { MAX_LAYER_SELECTOR_CHARS } from '../../shared/elementId'
import type { Frame } from '../../shared/types'
import { isDesktopShell } from './shell'
import { inspectElement } from './frameBridge'
Expand Down Expand Up @@ -136,25 +143,32 @@ async function measureElement(frame: Frame, selector: string): Promise<ClipRect
return info ? clipToFrame(info.rect, frame) : null
}

/** The server's render of the whole frame, cut down to `clip` here. */
async function fetchClipped(frame: Frame, format: RasterFormat, scale: number, clip: ClipRect, fileName: string) {
const label = FORMAT_LABEL[format]
const whole = await fetchFile(frameExportUrl(frame, format, scale), label, fileName)
if (!whole.ok) return whole
try {
const blob = await cropRaster(whole.blob, clip, {
scale,
type: rasterType(format),
quality: JPG_QUALITY,
})
return { ok: true as const, blob, fileName }
} catch {
return { ok: false as const, message: t('panels.exportFailed', { label }) }
/** If a full screenshot would shrink a small selection, let Chromium capture
* the layer directly at its original density. Otherwise keep the live
* document's measured crop, including selectors too long for a public URL. */
function serverRasterTarget(
frame: Frame,
format: RasterFormat,
scale: number,
clip?: ClipRect,
element?: ElementTarget,
) {
const url = frameExportUrl(frame, format, scale)
const fullScale = fullFrameRenderScale(frame, scale)
if (
fullScale < scale &&
clip &&
element &&
element.selector.length <= MAX_LAYER_SELECTOR_CHARS &&
fullFrameRenderScale(clip, scale) === scale
) {
return { url: `${url}&selector=${encodeURIComponent(element.selector)}`, scale }
}
return { url, scale: fullScale, clip }
}

/** Render here first; the server's Chromium is the fallback. A scale the
* frame is too big for comes down to the largest it allows, and says so. */
/** Render here first; the server's Chromium is the fallback. Use the scale
* of the renderer that produced the file for its name and download notice. */
async function fetchExport(
frame: Frame,
format: FrameExportFormat,
Expand All @@ -164,24 +178,30 @@ async function fetchExport(
const clip = element ? await measureElement(frame, element.selector) : undefined
if (clip === null) return { ok: false, message: t('panels.exportElementMissing') }
if (format === 'svg') return svgExport(frame, element, clip)
const scale = fitExportScale(frame, wanted)
const fileName = `${exportName(frame, element)}${exportScaleSuffix(scale)}.${format}`
const fetched = await rasterFetch(frame, format, scale, clip, fileName)
if (!fetched.ok || scale === wanted) return fetched
return { ...fetched, note: t('panels.exportScaledDown', { scale: formatExportScale(scale) }) }
}

async function rasterFetch(
frame: Frame,
format: RasterFormat,
scale: number,
clip: ClipRect | undefined,
fileName: string,
): Promise<Fetched> {
const local = await rasterExport(frame, format, scale, clip)
if (local) return { ok: true, blob: local, fileName }
if (clip) return fetchClipped(frame, format, scale, clip, fileName)
return fetchFile(frameExportUrl(frame, format, scale), FORMAT_LABEL[format], fileName)
let scale = fitExportScale(frame, wanted)
let blob = await rasterExport(frame, format, scale, clip)
let fileName = ''
if (!blob) {
const target = serverRasterTarget(frame, format, scale, clip, element)
scale = target.scale
const fetched = await fetchFile(target.url, FORMAT_LABEL[format], '')
if (!fetched.ok) return fetched
fileName = element ? '' : fetched.fileName
blob = fetched.blob
if (target.clip) {
try {
blob = await cropRaster(blob, target.clip, { scale, type: rasterType(format), quality: JPG_QUALITY })
} catch {
return { ok: false, message: t('panels.exportFailed', { label: FORMAT_LABEL[format] }) }
}
}
}
return {
ok: true,
blob,
fileName: fileName || `${exportName(frame, element)}${exportScaleSuffix(scale)}.${format}`,
note: scale === wanted ? undefined : t('panels.exportScaledDown', { scale: formatExportScale(scale) }),
}
}

/** An SVG has no server fallback: the server's Chromium paints pixels, and
Expand Down Expand Up @@ -346,10 +366,11 @@ async function copyPng(frame: Frame, wanted: number, element?: ElementTarget): P
const local = await rasterExport(frame, 'png', scale, clip)
if (local) return local
try {
const res = await fetch(frameExportUrl(frame, 'png', scale), { signal: AbortSignal.timeout(EXPORT_TIMEOUT_MS) })
const target = serverRasterTarget(frame, 'png', scale, clip, element)
const res = await fetch(target.url, { signal: AbortSignal.timeout(EXPORT_TIMEOUT_MS) })
if (res.ok) {
const whole = await res.blob()
return clip ? await cropRaster(whole, clip, { scale, type: 'png' }) : whole
return target.clip ? await cropRaster(whole, target.clip, { scale: target.scale, type: 'png' }) : whole
}
failure = await failureOf(res, 'png')
} catch (err) {
Expand Down
29 changes: 29 additions & 0 deletions tests/frameExport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,35 @@ it('renders at the picked scale and names the file by it', async () => {
expect(clicked.map((a) => a.download)).toEqual(['Poster@3x.png', 'Poster.jpg', 'Poster@0.5x.png'])
})

it('keeps a local 4x export and names a full server fallback by its actual density', async () => {
const tall = { ...frame, width: 1440, height: 2560 }
vi.mocked(rasterizeFrame).mockResolvedValueOnce(new Blob(['png']))
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('full frame')),
)
await downloadFrameExport(tall, 'png', 4)
await downloadFrameExport(tall, 'png', 4)
expect(clicked.map((a) => a.download)).toEqual(['Poster@4x.png', 'Poster@3.68x.png'])
expect(useStore.getState().notice?.text).toContain('exported at 3.68x')
})

it('downloads and copies a small layer at 2x even at the bottom of an oversized frame', async () => {
const tall = { ...frame, width: 1440, height: 10_000 }
measured({ x: 0, y: 9900, width: 64, height: 64 })
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('layer')),
)
const { written } = stubClipboard()
await downloadElementExport(tall, hero, 'png', 2)
await copyElementPng(tall, hero, 2)
const url = `/i/export-frame.png?scale=2&download&selector=${encodeURIComponent(hero.selector)}`
expect(vi.mocked(fetch).mock.calls.map(([request]) => request)).toEqual([url, url])
expect(clicked[0]?.download).toBe('Poster - divhero@2x.png')
expect(await written[0]?.text()).toBe('layer')
})

it('asks the server for the picked scale when the browser cannot draw the frame', async () => {
vi.stubGlobal(
'fetch',
Expand Down
7 changes: 7 additions & 0 deletions tests/mcpPdfExport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,13 @@ describe('export_frame scale', () => {
expect([out.scale, out.width, out.height]).toEqual([3, 900, 1500])
})

it('reports the full frame dimensions at the density its image URL serves', async () => {
vi.spyOn(store, 'getFrame').mockReturnValue({ ...POSTER, width: 1440, height: 2560 })
const out = await urls({ scale: 4 })
expect(out.image_url).toMatch(/\/i\/poster\.png\?scale=4$/)
expect([out.scale, out.width, out.height]).toEqual([3.68, 5299, 9421])
})

it('refuses a scale past 4x', async () => {
const result = await exportFrame(OWNER_ID, { frame_id: POSTER.id, scale: 8 })
expect(result.isError).toBe(true)
Expand Down
23 changes: 22 additions & 1 deletion tests/renderBrowser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import {
remoteConnectFailure,
type RendererTuning,
} from '../server/renderBrowser.ts'
import { MAX_RENDER_PIXELS, renderedHeight } from '../server/renderLimits.ts'
import { fullFrameRenderScale, MAX_RENDER_PIXELS } from '../shared/exportScale.ts'
import { 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.
Expand Down Expand Up @@ -397,3 +398,23 @@ describe('renderedHeight', () => {
expect(1440 * 2 * tall * 2).toBeLessThanOrEqual(MAX_RENDER_PIXELS)
})
})

describe('fullFrameRenderScale', () => {
it('preserves a requested density whenever the full height fits', () => {
expect(fullFrameRenderScale({ width: 800, height: 12_000 }, 2)).toBe(2)
expect(fullFrameRenderScale({ width: 1000, height: 12_500 }, 4)).toBe(2)
})

it.each([
[1440, 2560, 4],
[1440, 9000, 2],
[3000.7, 3000.8, 3],
[100_000, 100_000, 1],
])('keeps every row of a %i × %i export at %i×', (width, height, wanted) => {
const frame = { width, height }
const scale = fullFrameRenderScale(frame, wanted)
expect(scale).toBeGreaterThan(0)
expect(scale).toBeLessThan(wanted)
expect(renderedHeight(frame, scale)).toBe(Math.round(height))
})
})
Loading