From 8d27539fd41b667898ec3f75e8fa745d1b9e8ba2 Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:59:27 +0700 Subject: [PATCH 1/3] feat(frames): forward-port frame culling, stored preview and first-paint signal (CHE-8976) Re-implements fork main's culling chain (PR 8), stored preview and measure-lag (PR 65) and the doop-load first-paint marks on the cheese/main FrameView and Stage. Adds playwright-core as a devDependency for the perf scripts. --- bun.lock | 3 + package.json | 1 + scripts/perf/measure-lag.ts | 255 +++++++++++++++++++++++++++++ scripts/perf/paintValidation.ts | 251 ++++++++++++++++++++++++++++ scripts/perf/referenceRender.ts | 113 +++++++++++++ scripts/perf/throttle-proxy.ts | 126 ++++++++++++++ src/components/FramePreview.tsx | 5 +- src/components/FrameView.tsx | 113 +++++++++---- src/components/Stage.tsx | 18 +- src/components/useCulledFrames.ts | 48 ++++++ src/lib/frameCulling.ts | 54 ++++++ src/lib/frameRuntime.ts | 14 +- src/lib/ws.ts | 8 + tests/fixtures/elementPanel.html | 12 +- tests/frameCullEditBrowser.test.ts | 139 ++++++++++++++++ tests/frameCulling.test.ts | 80 +++++++++ tests/framePaintSignal.test.ts | 113 +++++++++++++ tests/paintValidation.test.ts | 245 +++++++++++++++++++++++++++ tests/throttleProxy.test.ts | 120 ++++++++++++++ 19 files changed, 1678 insertions(+), 40 deletions(-) create mode 100644 scripts/perf/measure-lag.ts create mode 100644 scripts/perf/paintValidation.ts create mode 100644 scripts/perf/referenceRender.ts create mode 100644 scripts/perf/throttle-proxy.ts create mode 100644 src/components/useCulledFrames.ts create mode 100644 src/lib/frameCulling.ts create mode 100644 tests/frameCullEditBrowser.test.ts create mode 100644 tests/frameCulling.test.ts create mode 100644 tests/framePaintSignal.test.ts create mode 100644 tests/paintValidation.test.ts create mode 100644 tests/throttleProxy.test.ts diff --git a/bun.lock b/bun.lock index 2cd58a4ac..006816bce 100644 --- a/bun.lock +++ b/bun.lock @@ -80,6 +80,7 @@ "mcp-remote": "0.15.1", "oxlint": "^1.87.0", "oxlint-tsgolint": "^7.0.2003", + "playwright-core": "1.65.0", "prettier": "^3.9.6", "shadcn": "^4.19.0", "storybook": "10.6.3", @@ -1549,6 +1550,8 @@ "pkg-up": ["pkg-up@3.1.0", "", { "dependencies": { "find-up": "^3.0.0" } }, "sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA=="], + "playwright-core": ["playwright-core@1.65.0", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA=="], + "postcss": ["postcss@8.5.26", "", { "dependencies": { "nanoid": "^3.3.17", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ=="], "postcss-selector-parser": ["postcss-selector-parser@7.1.5", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-KvvtD7SrlBP7dlgkBghEE3r84CABm5SmV2aNcG4oCA+qDnJ/tvKonFVvwWAyyWUEwxuNawdfEAZKP9zM3oZ2Uw=="], diff --git a/package.json b/package.json index dfa39e7dc..2d1d08030 100644 --- a/package.json +++ b/package.json @@ -107,6 +107,7 @@ "mcp-remote": "0.15.1", "oxlint": "^1.87.0", "oxlint-tsgolint": "^7.0.2003", + "playwright-core": "1.65.0", "prettier": "^3.9.6", "shadcn": "^4.19.0", "storybook": "10.6.3", diff --git a/scripts/perf/measure-lag.ts b/scripts/perf/measure-lag.ts new file mode 100644 index 000000000..99f726f9e --- /dev/null +++ b/scripts/perf/measure-lag.ts @@ -0,0 +1,255 @@ +/* Zoomed-out lag on a big file (CHE-7019; load method of CHE-6196). Local, no human credential. + * + * bun run build + * npx tsx scripts/perf/measure-lag.ts [--export | --erus-like] [--sizes <[[w,h],...].json>] [--runs 3] [--viewport 1440x900] [--max-live 24] [--shots ] + * + * Starts the production server from this checkout (withLocalDoop), imports the file, opens it, presses + * Shift+1 (fit all) and reports, per run: + * - iframes mounted at fit-all (the done-when 1 browser check: exits 1 when above --max-live) + * - long tasks (count, total ms) and frame time (rAF delta p50, p95, max) while panning and zooming for 6 s + * - paintedMs: first zoom-in wheel to a live frame whose screenshot is at least 5% non-white pixels + * - gestureMs: first zoom-in wheel on one frame until it is 300 px wide; zoomInMs: from then to its iframe being ready with no preview over it + * --erus-like builds a stand-in with the reported size mix of the erus file (645 frames; 207 390x844, + * 154 1440x900, 87 390x867, 18 1440x1800, the other 179 split between 1440x1024 and 390x800). */ +import { pathToFileURL } from 'node:url' +import { readFileSync } from 'node:fs' +import { parseArgs } from 'node:util' +import { mkdirSync } from 'node:fs' +import path from 'node:path' +import { chromium } from 'playwright-core' +import sharp from 'sharp' +import { importCanvasExport, type CanvasExport } from './import-canvas-export.ts' +import { withLocalDoop } from './measure-local.ts' +import { median, parseViewport } from './measure-canvas-load.ts' + +/** `sizes`: one `[width, height]` per frame (the real file's size list); default is the reported mix plus a guess */ +export function erusLike(sizes?: [number, number][]): CanvasExport { + const mix: [number, number, number][] = [ + [390, 844, 207], + [1440, 900, 154], + [390, 867, 87], + [1440, 1800, 18], + [1440, 1024, 100], + [390, 800, 79], + ] + const list = sizes ?? mix.flatMap(([w, h, n]) => Array.from({ length: n }, (): [number, number] => [w, h])) + const frames: CanvasExport['frames'] = [] + const COLS = 30 + const GAP = 80 + let i = 0 + for (const [width, height] of list) { + const row = Math.floor(i / COLS) + const col = i % COLS + frames.push({ + name: `f${i}`, + x: col * (1440 + GAP), + y: row * (1800 + GAP), + width, + height, + html: `

Frame ${i}

${'

lorem ipsum dolor sit amet

'.repeat(20)}`, + }) + i++ + } + return { id: 'erus', name: 'erus-like', pages: [{ id: 'erus:page1', name: 'Page 1' }], frames } +} + +const pct = (xs: number[], p: number) => + [...xs].sort((a, b) => a - b)[Math.min(xs.length - 1, Math.floor(xs.length * p))] ?? NaN + +async function once( + base: string, + canvasId: string, + cookie: string, + viewport: { width: number; height: number }, + shots?: { dir: string; run: number }, +) { + const browser = await chromium.launch() + try { + const context = await browser.newContext({ viewport }) + await context.addCookies([ + { name: cookie.split('=')[0]!, value: cookie.split(';')[0]!.slice(cookie.indexOf('=') + 1), url: base }, + ]) + const page = await context.newPage() + // a string, not a function: tsx's keepNames would inject a `__name` helper the page does not have + await page.addInitScript(`{ + const ready = new Set() + const lag = { frames: [], tasks: [], on: false } + Object.assign(window, { __ready: ready, __lag: lag }) + window.addEventListener('message', (e) => { + if (e.data && e.data.type === 'doop:frame-ready' && e.source) ready.add(e.source) + }) + new PerformanceObserver((l) => { + if (lag.on) for (const t of l.getEntries()) lag.tasks.push(t.duration) + }).observe({ type: 'longtask' }) + let last = performance.now() + const tick = (now) => { + if (lag.on) lag.frames.push(now - last) + last = now + requestAnimationFrame(tick) + } + requestAnimationFrame(tick) + }`) + await page.goto(`${base}/c/${canvasId}`) + await page.waitForSelector('[data-frame-surface]', { timeout: 120_000 }) + await page.keyboard.press('Shift+Digit1') + await page.waitForTimeout(4000) // let mounts and previews settle at fit-all + const iframesAtFitAll = await page.locator('iframe[data-doop-frame]').count() + + // pan and zoom for 6 s + await page.evaluate(() => ((window as never as { __lag: { on: boolean } }).__lag.on = true)) + await page.mouse.move(viewport.width / 2, viewport.height / 2) + const end = Date.now() + 6000 + for (let k = 0; Date.now() < end; k++) { + await page.mouse.wheel(k % 2 ? 80 : -80, 40) + if (k % 5 === 0) { + await page.keyboard.down('Control') + await page.mouse.wheel(0, (k / 5) % 2 ? -30 : 30) + await page.keyboard.up('Control') + } + await page.waitForTimeout(16) + } + const lag = await page.evaluate(() => { + const l = (window as never as { __lag: { frames: number[]; tasks: number[]; on: boolean } }).__lag + l.on = false + return { frames: l.frames, tasks: l.tasks } + }) + + // zoom in on the frame nearest the centre; time to a ready, preview-free iframe + await page.keyboard.press('Shift+Digit1') + await page.waitForTimeout(2000) + // a wide frame near the centre (a 1440-wide frame is ~115 px at fit-all); zoom on its centre + const target = await page.evaluate( + ([cx, cy]) => { + let best: { x: number; y: number; d: number } | null = null + for (const el of document.querySelectorAll('[data-frame-surface]')) { + const r = el.getBoundingClientRect() + if (r.width < 100 || r.right < 0 || r.left > innerWidth) continue + const x = r.left + r.width / 2 + const y = r.top + r.height / 2 + const d = (x - cx!) ** 2 + (y - cy!) ** 2 + if (!best || d < best.d) best = { x, y, d } + } + return best + }, + [viewport.width / 2, viewport.height / 2] as const, + ) + if (!target) throw new Error('no frame wide enough to zoom on after fit-all') + const probe = (cx: number, cy: number) => + page.evaluate( + ([x, y]) => { + const ready = (window as never as { __ready: Set }).__ready + const el = document.elementFromPoint(x!, y!)?.closest('[data-frame-surface]') + if (!el) return { width: 0, live: false, rect: null } + const iframe = el.querySelector('iframe') + const r = el.getBoundingClientRect() + // live: its runtime posted frame-ready and no preview image covers it + return { + width: r.width, + live: !!iframe && ready.has(iframe.contentWindow) && !el.querySelector('img'), + rect: { x: Math.max(0, r.left), y: Math.max(0, r.top), width: r.width, height: r.height }, + } + }, + [cx, cy] as const, + ) + /** pixels, not signals: a screenshot of the frame's visible box where at least 5% of the pixels are not white + * (the fixture page is mostly tinted blocks and text; a blank or loading frame is white) */ + const painted = async (rect: { x: number; y: number; width: number; height: number }) => { + const w = Math.floor(Math.min(rect.width, viewport.width - rect.x)) + const h = Math.floor(Math.min(rect.height, viewport.height - rect.y)) + if (w < 50 || h < 50) return { ok: false, png: undefined } + const png = await page.screenshot({ clip: { x: rect.x, y: rect.y, width: w, height: h } }) + const { data } = await sharp(png).removeAlpha().raw().toBuffer({ resolveWithObject: true }) + let ink = 0 + for (let k = 0; k < data.length; k += 3) if (data[k]! < 245 || data[k + 1]! < 245 || data[k + 2]! < 245) ink++ + return { ok: ink / (data.length / 3) >= 0.05, png } + } + const t0 = Date.now() + let gestureMs = NaN + let zoomInMs = NaN + let paintedMs = NaN + await page.mouse.move(target.x, target.y) + await page.keyboard.down('Control') + for (const deadline = t0 + 20_000; Date.now() < deadline;) { + await page.mouse.wheel(0, -40) + const s = await probe(target.x, target.y) + if (Number.isNaN(gestureMs) && s.width >= 300) gestureMs = Date.now() - t0 // the frame is big enough to read + if (s.live && s.rect && !Number.isNaN(gestureMs)) { + const px = await painted(s.rect) + if (px.ok) { + paintedMs = Date.now() - t0 // first wheel to a live frame with painted pixels + zoomInMs = paintedMs - gestureMs + if (shots && px.png) { + mkdirSync(shots.dir, { recursive: true }) + await page.screenshot({ path: path.join(shots.dir, `zoom-in-run${shots.run}.png`) }) + } + break + } + } + await page.waitForTimeout(16) + } + await page.keyboard.up('Control') + return { + iframesAtFitAll, + longTasks: lag.tasks.length, + longTaskMs: Math.round(lag.tasks.reduce((a, b) => a + b, 0)), + frameP50: Math.round(pct(lag.frames, 0.5)), + frameP95: Math.round(pct(lag.frames, 0.95)), + frameMax: Math.round(Math.max(...lag.frames)), + framesSampled: lag.frames.length, + gestureMs, + zoomInMs, + paintedMs, + } + } finally { + await browser.close() + } +} + +async function main() { + const { values } = parseArgs({ + options: { + export: { type: 'string' }, + 'erus-like': { type: 'boolean' }, + runs: { type: 'string', default: '3' }, + viewport: { type: 'string' }, + 'max-live': { type: 'string', default: '24' }, + sizes: { type: 'string' }, + shots: { type: 'string' }, + }, + }) + const exported = values.export + ? (JSON.parse(readFileSync(values.export, 'utf8')) as CanvasExport) + : erusLike(values.sizes ? (JSON.parse(readFileSync(values.sizes, 'utf8')) as [number, number][]) : undefined) + const viewport = parseViewport(values.viewport) + const runs = await withLocalDoop(async (base, cookie) => { + const id = await importCanvasExport(base, cookie, exported) + console.error(`imported ${exported.frames.length} frames as ${id}`) + const out = [] + for (let i = 0; i < Number(values.runs); i++) { + out.push(await once(base, id, cookie, viewport, values.shots ? { dir: values.shots, run: i + 1 } : undefined)) + console.error(`run ${i + 1}: ${JSON.stringify(out[i])}`) + } + return out + }) + const medians = Object.fromEntries( + (Object.keys(runs[0]!) as (keyof (typeof runs)[0])[]).map((k) => [k, median(runs.map((r) => r[k]))]), + ) + console.log( + JSON.stringify( + { frames: exported.frames.length, viewport: `${viewport.width}x${viewport.height}`, runs, medians }, + null, + 2, + ), + ) + if (medians.iframesAtFitAll! > Number(values['max-live'])) { + console.error(`FAIL: ${medians.iframesAtFitAll} iframes mounted at fit-all, limit ${values['max-live']}`) + process.exit(1) + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch((err) => { + console.error(err instanceof Error ? err.message : err) + process.exit(1) + }) +} diff --git a/scripts/perf/paintValidation.ts b/scripts/perf/paintValidation.ts new file mode 100644 index 000000000..d36719072 --- /dev/null +++ b/scripts/perf/paintValidation.ts @@ -0,0 +1,251 @@ +/* Paint validation rules for the doop first-frame metric (CHE-6942 plan r4, contract C1; CHE-6954). + * + * Pure functions on RGBA rasters and plain numbers, so the rules are testable without a browser. + * No script uses them yet: step 5 wires them into the measure scripts. Times are ms on one + * clock (from navigation start); the caller converts CDP screencast timestamps and frame + * paint signals to that clock before it calls in. + * + * Completeness phase: classify each frame as empty / stalled / blank / unchecked, decided + * before any validation sampling. Validation: screencast windows V0 (completeness), V1 + * (headline) and V2 (per frame). Method B: the headline is the first screencast frame in + * which a sampled box painted. */ + +export interface Raster { + width: number + height: number + /** RGBA, row-major */ + data: Uint8Array | Uint8ClampedArray +} +export interface Region { + x: number + y: number + w: number + h: number +} + +/** a pixel is changed when any channel differs by more than this (of 255) */ +export const CHANGE_THRESHOLD = 16 +/** a screencast box is inset by this many px, so edges and borders do not count */ +export const BOX_INSET = 2 +/** a box has painted at min(this, N) changed pixels */ +export const PAINTED_PIXELS = 10 +/** V1/V2: the signal may lie this long (one display frame) after the first painted frame */ +export const DISPLAY_FRAME_MS = 17 +/** a window wider than this is inconclusive */ +export const MAX_WINDOW_MS = 100 +/** `validateWithRepeats` makes at most this many attempts */ +export const MAX_ATTEMPTS = 3 + +export function solid(width: number, height: number, rgb: [number, number, number]): Raster { + const data = new Uint8Array(width * height * 4) + for (let i = 0; i < width * height; i++) data.set([rgb[0], rgb[1], rgb[2], 255], i * 4) + return { width, height, data } +} + +/** pixels in `region` (default: all; whole pixels inside it when fractional) where any channel of `a` and `b` differs by more than 16 */ +export function changedPixels(a: Raster, b: Raster, region?: Region): number { + if (a.width !== b.width || a.height !== b.height) { + throw new Error(`raster size mismatch: ${a.width}x${a.height} vs ${b.width}x${b.height}`) + } + // a region may be fractional (zoomed, positioned boxes): count the whole pixels inside it + const x0 = Math.max(0, Math.ceil(region?.x ?? 0)) + const y0 = Math.max(0, Math.ceil(region?.y ?? 0)) + const x1 = Math.min(a.width, Math.floor(region ? region.x + region.w : a.width)) + const y1 = Math.min(a.height, Math.floor(region ? region.y + region.h : a.height)) + let n = 0 + for (let y = y0; y < y1; y++) { + for (let x = x0; x < x1; x++) { + const i = (y * a.width + x) * 4 + for (let c = 0; c < 4; c++) { + if (Math.abs(a.data[i + c]! - b.data[i + c]!) > CHANGE_THRESHOLD) { + n++ + break + } + } + } + } + return n +} + +/** area-average downscale to zoom z (z >= 1 returns the raster as is: the completeness phase caps zoom at 100%) */ +export function downscale(r: Raster, z: number): Raster { + if (z >= 1) return r + const w = Math.max(1, Math.round(r.width * z)) + const h = Math.max(1, Math.round(r.height * z)) + const sx = r.width / w + const sy = r.height / h + const data = new Uint8Array(w * h * 4) + for (let dy = 0; dy < h; dy++) { + for (let dx = 0; dx < w; dx++) { + const sum = [0, 0, 0, 0] + let weight = 0 + for (let y = Math.floor(dy * sy); y < Math.min(r.height, Math.ceil((dy + 1) * sy)); y++) { + const wy = Math.min((dy + 1) * sy, y + 1) - Math.max(dy * sy, y) + for (let x = Math.floor(dx * sx); x < Math.min(r.width, Math.ceil((dx + 1) * sx)); x++) { + const wt = wy * (Math.min((dx + 1) * sx, x + 1) - Math.max(dx * sx, x)) + for (let c = 0; c < 4; c++) sum[c]! += r.data[(y * r.width + x) * 4 + c]! * wt + weight += wt + } + } + for (let c = 0; c < 4; c++) data[(dy * w + dx) * 4 + c] = Math.round(sum[c]! / weight) + } + } + return { width: w, height: h, data } +} + +/* ---------- completeness phase ---------- */ + +export interface FrameObservation { + id: string + /** reference render: at least one pixel changed (referenceRender.ts) */ + visible: boolean + /** time of the frame paint signal; null when none arrived by the end of the run */ + signalMs: number | null + /** the frame box intersects the visible stage in the load view (no culling margin) */ + inViewport: boolean + /** changed pixels of the reference after the downscale to zoom z, against the empty fill */ + nRef: number + /** changed pixels of the app screenshot of the frame box against the empty fill */ + nApp: number +} + +export interface Completeness { + complete: boolean + emptyFrames: string[] + stalledFrames: string[] + blankFrames: string[] + uncheckedFrames: string[] + /** every visible viewport frame has a paint signal: the latest one; null if the run is incomplete */ + viewportPaintMs: number | null +} + +/** One class per frame, first match wins: empty (not visible, excluded), stalled (visible, no + * signal), blank (visible, Nref >= 1, Napp = 0, even with a signal), unchecked (visible, + * Nref = 0). A stalled, blank or unchecked frame makes the run incomplete. */ +export function completeness(frames: FrameObservation[]): Completeness { + const out: Completeness = { + complete: true, + emptyFrames: [], + stalledFrames: [], + blankFrames: [], + uncheckedFrames: [], + viewportPaintMs: null, + } + for (const f of frames) { + if (!f.visible) out.emptyFrames.push(f.id) + else if (f.signalMs === null) out.stalledFrames.push(f.id) + else if (f.nRef >= 1 && f.nApp === 0) out.blankFrames.push(f.id) + else if (f.nRef === 0) out.uncheckedFrames.push(f.id) + } + out.complete = !(out.stalledFrames.length || out.blankFrames.length || out.uncheckedFrames.length) + if (out.complete) { + const t = frames.filter((f) => f.visible && f.inViewport).map((f) => f.signalMs!) + out.viewportPaintMs = t.length ? Math.max(...t) : null + } + return out +} + +/* ---------- screencast windows ---------- */ + +export interface ScreencastFrame { + t: number + raster: Raster +} +export interface Box extends Region { + id: string + /** this frame's paint signal */ + signalMs: number | null +} +export interface ValidationInput { + /** screencast frames in time order, the first one taken after the iframes mounted */ + frames: ScreencastFrame[] + boxes: Box[] + headlineMs: number + completeness: Completeness +} +export interface ValidationResult { + status: 'pass' | 'fail' | 'inconclusive' + failures: { check: 'V0' | 'V1' | 'V2'; frameId?: string; reason: string }[] + /** ids of the boxes that were sampled */ + sampled: string[] +} + +interface Sampled { + id: string + signalMs: number | null + /** index of the first screencast frame in which the box had painted (>= 1) */ + paintedAt: number +} + +/** boxes with N >= 1 changed pixels in the last frame (against the first), and when each painted */ +function sample(frames: ScreencastFrame[], boxes: Box[]): Sampled[] { + if (frames.length < 2) return [] + const empty = frames[0]!.raster + const last = frames[frames.length - 1]!.raster + const out: Sampled[] = [] + for (const b of boxes) { + const r = { x: b.x + BOX_INSET, y: b.y + BOX_INSET, w: b.w - 2 * BOX_INSET, h: b.h - 2 * BOX_INSET } + if (r.w < 1 || r.h < 1) continue + const n = changedPixels(last, empty, r) + if (n < 1) continue + const need = Math.min(PAINTED_PIXELS, n) + const k = frames.findIndex((f) => changedPixels(f.raster, empty, r) >= need) + out.push({ id: b.id, signalMs: b.signalMs, paintedAt: k }) + } + return out +} + +/** V0, then V1 (headline) and V2 (per frame): the signal lies after the last frame before the + * box painted and at most 17 ms after the first frame in which it had. A window wider than + * 100 ms is inconclusive. */ +export function validateScreencast(i: ValidationInput): ValidationResult { + if (!i.completeness.complete) { + const c = i.completeness + const ids = [...c.stalledFrames, ...c.blankFrames, ...c.uncheckedFrames] + return { status: 'fail', failures: [{ check: 'V0', reason: `run incomplete: ${ids.join(', ')}` }], sampled: [] } + } + const boxes = sample(i.frames, i.boxes) + const sampled = boxes.map((b) => b.id) + if (!boxes.length) { + return { + status: 'fail', + failures: [{ check: 'V1', reason: 'no sampled box: nothing to validate against' }], + sampled, + } + } + const failures: ValidationResult['failures'] = [] + let wide = false + const check = (name: 'V1' | 'V2', signal: number | null, k: number, frameId?: string) => { + const after = i.frames[k - 1]!.t + const until = i.frames[k]!.t + if (until - after > MAX_WINDOW_MS) { + wide = true + return + } + if (signal === null || !(signal > after && signal <= until + DISPLAY_FRAME_MS)) { + failures.push({ + check: name, + frameId, + reason: `signal ${signal} outside (${after}, ${until + DISPLAY_FRAME_MS}]`, + }) + } + } + check('V1', i.headlineMs, Math.min(...boxes.map((b) => b.paintedAt))) + for (const b of boxes) check('V2', b.signalMs, b.paintedAt, b.id) + return { status: failures.length ? 'fail' : wide ? 'inconclusive' : 'pass', failures, sampled } +} + +/** Method B: the headline is the first screencast frame in which a sampled box painted; null + * when the run is incomplete (same completeness phase) or no box can be sampled. */ +export function methodBHeadline(i: Omit): number | null { + if (!i.completeness.complete) return null + const boxes = sample(i.frames, i.boxes) + return boxes.length ? i.frames[Math.min(...boxes.map((b) => b.paintedAt))]!.t : null +} + +/** Runs `attempt` until its result is not inconclusive, at most 3 attempts. */ +export async function validateWithRepeats(attempt: () => Promise): Promise { + let r = await attempt() + for (let n = 1; n < MAX_ATTEMPTS && r.status === 'inconclusive'; n++) r = await attempt() + return r +} diff --git a/scripts/perf/referenceRender.ts b/scripts/perf/referenceRender.ts new file mode 100644 index 000000000..fd20994e8 --- /dev/null +++ b/scripts/perf/referenceRender.ts @@ -0,0 +1,113 @@ +/* Reference render for the doop first-frame metric (CHE-6942 plan r4, contract C1; CHE-6954). + * + * Decides whether a frame's HTML has visible content, from a real render and never from a + * missing paint signal. Run once per fixture, outside every timed run; the cache key is the + * SHA256 of the frame HTML plus the frame size (the size changes the render, the HTML alone + * would not). A blank page holds one sandboxed `srcdoc` iframe with the real FRAME_BOOTSTRAP + * at the frame's size. The frame HTML goes in through `doop:html`; the render waits for fonts, + * images and finite animations (at most 5 s), then the iframe is screenshotted at scale 1 and + * compared with the same iframe before the HTML was posted. No script calls this yet (step 5). */ +import { createHash } from 'node:crypto' +import type { Browser } from 'playwright-core' +import sharp from 'sharp' +import { FRAME_BOOTSTRAP } from '../../src/lib/frameRuntime.ts' +import { changedPixels, type Raster } from './paintValidation.ts' + +export interface ReferenceInput { + html: string + width: number + height: number +} +export interface Reference { + /** at least one pixel changed once the HTML was applied */ + visible: boolean + /** the iframe after the HTML settled */ + raster: Raster + /** the same iframe before the HTML was posted */ + empty: Raster +} + +export const SETTLE_LIMIT_MS = 5000 + +export function referenceKey(i: ReferenceInput): string { + return `${createHash('sha256').update(i.html).digest('hex')}:${i.width}x${i.height}` +} + +async function decode(png: Buffer): Promise { + const { data, info } = await sharp(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true }) + return { width: info.width, height: info.height, data: new Uint8Array(data) } +} + +export async function renderReference( + browser: Browser, + input: ReferenceInput, + cache: Map = new Map(), +): Promise { + const key = referenceKey(input) + const hit = cache.get(key) + if (hit) return hit + const page = await browser.newPage({ + viewport: { width: Math.max(input.width, 1), height: Math.max(input.height, 1) }, + deviceScaleFactor: 1, + }) + try { + await page.setContent( + ``, + ) + // listen first: the bootstrap posts frame-ready as soon as the srcdoc loads + await page.evaluate((boot) => { + const f = document.getElementById('f') as HTMLIFrameElement + ;(window as unknown as { __ready: Promise }).__ready = new Promise((resolve) => { + window.addEventListener('message', (e) => { + if (e.source === f.contentWindow && e.data?.type === 'doop:frame-ready') resolve() + }) + }) + f.srcdoc = boot + }, FRAME_BOOTSTRAP) + await page.evaluate(() => (window as unknown as { __ready: Promise }).__ready) + const handle = (await page.$('#f'))! + const empty = await decode(await handle.screenshot()) + + await page.evaluate((html) => { + const f = document.getElementById('f') as HTMLIFrameElement + return new Promise((resolve) => { + window.addEventListener('message', function on(e) { + if (e.source === f.contentWindow && e.data?.reqId === 'ref') { + window.removeEventListener('message', on) + resolve() + } + }) + f.contentWindow!.postMessage({ type: 'doop:html', html, reqId: 'ref' }, '*') + }) + }, input.html) + const frame = (await handle.contentFrame())! + await frame.evaluate(async (limit) => { + const settle = (async () => { + await document.fonts.ready + await Promise.all( + [...document.images].map((img) => + img.complete + ? 0 + : new Promise((r) => { + img.addEventListener('load', r) + img.addEventListener('error', r) + }), + ), + ) + await Promise.all( + document + .getAnimations() + .filter((a) => Number.isFinite(a.effect?.getComputedTiming().endTime)) + .map((a) => a.finished.catch(() => undefined)), + ) + })() + await Promise.race([settle, new Promise((r) => setTimeout(r, limit))]) + }, SETTLE_LIMIT_MS) + const raster = await decode(await handle.screenshot()) + const ref = { visible: changedPixels(raster, empty) > 0, raster, empty } + cache.set(key, ref) + return ref + } finally { + await page.close() + } +} diff --git a/scripts/perf/throttle-proxy.ts b/scripts/perf/throttle-proxy.ts new file mode 100644 index 000000000..7eb8901c1 --- /dev/null +++ b/scripts/perf/throttle-proxy.ts @@ -0,0 +1,126 @@ +/* Userspace TCP proxy that shapes the `c00` network profile (CHE-6942 contract C2). + * + * const proxy = await startThrottleProxy({ target: { host: '127.0.0.1', port: 4400 }, rttMs: 80, downBitsPerSec: 8e6 }) + * // point Chrome at 127.0.0.1:${proxy.port} + * + * Every byte between Chrome and the server passes through here, WebSocket frames included, so no + * browser-side throttling is needed. Each direction adds rttMs / 2 of one-way delay and shares one + * bandwidth cap across all connections (one access link for HTML, bundle, WebSocket and images). + * Connection setup (the TCP handshake) is not shaped; only payload bytes are. */ +import { connect, createServer, type Socket } from 'node:net' + +export interface ThrottleOptions { + /** where the proxy forwards to */ + target: { host: string; port: number } + /** round-trip time; each direction adds rttMs / 2 */ + rttMs: number + /** cap server to client, bits per second, shared by all connections; omitted means unlimited */ + downBitsPerSec?: number + /** cap client to server, bits per second, shared by all connections; omitted means unlimited */ + upBitsPerSec?: number +} + +export interface ThrottleProxy { + port: number + close(): Promise +} + +/* a slice is the unit of serialization on the link: small enough that a long transfer streams + instead of arriving in one lump, large enough to keep timer count low (16 KiB = 16 ms at 8 Mbit/s) */ +const SLICE_BYTES = 16 * 1024 + +/* One direction of the access link. `busyUntil` is shared by every connection using it: a slice + starts serializing when the link is free and occupies it for bytes * 8 / bps. */ +class Link { + private busyUntil = 0 + constructor( + private readonly bitsPerSec: number | undefined, + private readonly oneWayMs: number, + ) {} + + /** the time (performance.now clock) at which `bytes` sent now are delivered */ + schedule(bytes: number): number { + const now = performance.now() + if (!this.bitsPerSec) return now + this.oneWayMs + this.busyUntil = Math.max(now, this.busyUntil) + (bytes * 8000) / this.bitsPerSec + return this.busyUntil + this.oneWayMs + } +} + +interface Item { + at: number + data: Buffer | null // null: the sender closed its side +} + +/* Copies `from` to `to` through `link`, in order. Delivery times only grow, so a FIFO queue with + one timer on its head keeps byte order without per-item timers. */ +function shape(from: Socket, to: Socket, link: Link, timers: Set): void { + const queue: Item[] = [] + let timer: NodeJS.Timeout | undefined + const pump = (): void => { + if (timer) timers.delete(timer) + timer = undefined + for (;;) { + const head = queue[0] + if (!head) return + const wait = head.at - performance.now() + if (wait > 0) { + timer = setTimeout(pump, wait) + timers.add(timer) + return + } + queue.shift() + if (to.destroyed) return + if (head.data) to.write(head.data) + else to.end() + } + } + const push = (item: Item): void => { + queue.push(item) + if (!timer) pump() + } + from.on('data', (chunk: Buffer) => { + for (let i = 0; i < chunk.length; i += SLICE_BYTES) { + const slice = chunk.subarray(i, i + SLICE_BYTES) + push({ at: link.schedule(slice.length), data: slice }) + } + }) + from.on('end', () => push({ at: link.schedule(0), data: null })) +} + +export async function startThrottleProxy(opts: ThrottleOptions): Promise { + const oneWayMs = opts.rttMs / 2 + const down = new Link(opts.downBitsPerSec, oneWayMs) + const up = new Link(opts.upBitsPerSec, oneWayMs) + const sockets = new Set() + const timers = new Set() + + const server = createServer({ allowHalfOpen: true }, (client) => { + const upstream = connect({ host: opts.target.host, port: opts.target.port, allowHalfOpen: true }) + for (const socket of [client, upstream]) { + sockets.add(socket) + socket.on('close', () => { + sockets.delete(socket) + // a dropped or reset side takes the pair down; a clean half-close is carried by shape() + if (socket.errored) (socket === client ? upstream : client).destroy() + }) + socket.on('error', () => socket.destroy()) + } + shape(client, upstream, up, timers) + shape(upstream, client, down, timers) + }) + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(0, '127.0.0.1', resolve) + }) + + return { + port: (server.address() as { port: number }).port, + close: () => + new Promise((resolve) => { + for (const timer of timers) clearTimeout(timer) + for (const socket of sockets) socket.destroy() + server.close(() => resolve()) + }), + } +} diff --git a/src/components/FramePreview.tsx b/src/components/FramePreview.tsx index 0aee596e1..72f4c63ed 100644 --- a/src/components/FramePreview.tsx +++ b/src/components/FramePreview.tsx @@ -13,12 +13,15 @@ export function FramePreview({ frameId, empty = 'empty canvas', className, + quietFail = false, }: { frameId?: string | null /** what an empty box says; `null` for a plain blank (a tiny thumb) */ empty?: ReactNode /** the fallback text's size and colour; the image itself always fills the box */ className?: string + /** a failed render shows nothing instead of the failure text: for a preview that only covers a live frame while it loads */ + quietFail?: boolean }) { const [failedId, setFailedId] = useState(null) const fallback = (text: ReactNode) => @@ -26,7 +29,7 @@ export function FramePreview({ {text} ) if (!frameId) return fallback(empty) - if (failedId === frameId) return fallback('preview unavailable') + if (failedId === frameId) return quietFail ? null : fallback('preview unavailable') return ( (null) + /* a frame that lost its iframe is not ready: the next one starts from the bootstrap */ + const [wasKept, setWasKept] = useState(keepIframe) + if (keepIframe !== wasKept) { + setWasKept(keepIframe) + if (!keepIframe) { + setRuntimeReady(false) + setRuntimeDocument(null) + setBleed(0) + } + } + useEffect(() => { + if (keepIframe) return + localHtml.current = null + /* the key port belonged to the removed document; the next one is offered a fresh port */ + keyPort.current?.close() + keyPort.current = null + }, [keepIframe]) /* saves a document the runtime serialized after a text edit (set below) */ const saveEditedRef = useRef<(html: string, discrete: boolean) => void>(() => {}) useEffect(() => { @@ -872,6 +898,13 @@ export const FrameView = memo(function FrameView({ const px = Number((ev.data as { px?: unknown }).px) setBleed(Number.isFinite(px) ? Math.min(1024, Math.max(0, px)) : 0) } + /* the frame posts absolute time; convert with this document's origin (CHE-6942 C1) */ + if (ev.data?.type === 'doop:paint' && win && ev.source === win && typeof ev.data.time === 'number') { + performance.mark('doop:paint', { + startTime: ev.data.time - performance.timeOrigin, + detail: { frameId: frame.id, name: ev.data.name }, + }) + } } window.addEventListener('message', onMsg) return () => { @@ -879,7 +912,7 @@ export const FrameView = memo(function FrameView({ keyPort.current?.close() keyPort.current = null } - }, []) + }, [frame.id]) /* the runtime insets its body by the margin once the iframe has grown by it */ useLayoutEffect(() => { if (runtimeReady) iframeRef.current?.contentWindow?.postMessage({ type: 'doop:bleed', px: bleed }, '*') @@ -898,6 +931,7 @@ export const FrameView = memo(function FrameView({ noteFrameDocument(frame.id, null) let cancelled = false void requestFrame(frame.id, 'doop:html', { html }).then((reply) => { + if (reply) performance.mark('doop:html-result', { detail: { frameId: frame.id } }) if (!reply || request !== htmlRequest.current) return /* the runtime shows it whether or not this effect is still current */ noteFrameDocument(frame.id, html) @@ -1512,6 +1546,7 @@ export const FrameView = memo(function FrameView({ ) } setEditing(true) + setEverEdited(true) /* the point goes along so the runtime edits the text under it straight away, all of it selected, as a double-click does in Figma */ iframeRef.current?.contentWindow?.postMessage({ type: 'doop:edit', on: true, x: at?.x, y: at?.y }, '*') @@ -1904,42 +1939,52 @@ export const FrameView = memo(function FrameView({ belong to the canvas, so neither this box nor the iframe takes them */ style={{ left: -bleed, top: -bleed, ...(bleed ? { pointerEvents: 'none' } : null) }} > -