| 1 | // Feed bench (dev tooling, docs/shadow-dom-renderer.md): N chat bubbles with the |
| 2 | // sandboxed iframe renderer vs the Shadow DOM renderer on the same validated |
| 3 | // ops. Two modes: |
| 4 | // ?mode=ops — renderer only: replays pre-validated `ops` batches |
| 5 | // (scripts/feed-bench.ts writes them to bench/ops/ with the Node |
| 6 | // harness); measures build time, time to all rendered, main-thread |
| 7 | // long tasks, memory (measureUserAgentSpecificMemory: the page is |
| 8 | // cross-origin isolated) and scroll frame times. |
| 9 | // ?mode=host — the whole WidgetHost per bubble (QuickJS worker + validator + |
| 10 | // renderer), `parallel` at a time; the sandbox boot dominates. |
| 11 | // ?renderer=iframe|shadow &count=N &cv=1 (content-visibility: auto on bubbles) |
| 12 | // &widgets=a,b (ops files / corpus files) &auto=1 (start on load; otherwise |
| 13 | // the driver calls window.__feed.start() after taking its CDP baseline). |
| 14 | // Results in window.__feed and the HUD. Bubble heights are clamped to the |
| 15 | // WidgetHost range (24–900 px): a `min-height: 100vh` body is a feedback loop |
| 16 | // on both renderers, the clamp is where it stops in the product too. |
| 17 | |
| 18 | import { IframeRenderer } from '@telegram/widget-sandbox/host/iframe-renderer'; |
| 19 | import type { Renderer } from '@telegram/widget-sandbox/host/renderer'; |
| 20 | import { ShadowDomRenderer } from '@telegram/widget-sandbox/host/shadow-renderer'; |
| 21 | import { WidgetHost } from '@telegram/widget-sandbox/host/widget-host'; |
| 22 | import { WorkerPool } from '@telegram/widget-sandbox/host/worker-pool'; |
| 23 | import type { HostToRenderer, RendererToHost } from '@telegram/widget-sandbox/shared/protocol'; |
| 24 | |
| 25 | const params = new URLSearchParams(location.search); |
| 26 | const RENDERER = params.get('renderer') === 'shadow' ? 'shadow' : 'iframe'; |
| 27 | const MODE = params.get('mode') === 'host' ? 'host' : 'ops'; |
| 28 | const COUNT = Math.max(1, Number(params.get('count') ?? 100)); |
| 29 | const CV = params.get('cv') === '1'; |
| 30 | const PARALLEL = Math.max(1, Number(params.get('parallel') ?? 4)); |
| 31 | /** host mode: take sandbox workers from a pool of this many warmed ones (prewarmed before the clock starts, refilled as taken); 0 = boot each. */ |
| 32 | const POOL = Math.max(0, Number(params.get('pool') ?? 0)); |
| 33 | const MIN_HEIGHT = 24, MAX_HEIGHT = 900; // WidgetHost's clamp |
| 34 | const WIDGETS = (params.get('widgets') ?? 'generated/with-profile/01-show-me-a-mortgage-calculator-loan-amount,generated/with-profile/06-show-a-comparison-table-of-three-laptops,generated/with-profile/11-make-a-to-do-list-widget-where-i-can-add,generated/with-profile/19-make-a-step-by-step-recipe-card-for,generated/without-profile/02-make-an-interactive-quiz-about-the-solar').split(','); |
| 35 | |
| 36 | const feed = document.getElementById('feed')!; |
| 37 | const hud = document.getElementById('hud')!; |
| 38 | const factory = RENDERER === 'shadow' ? ShadowDomRenderer.factory : IframeRenderer.factory; |
| 39 | |
| 40 | interface Result { |
| 41 | renderer: string; mode: string; count: number; cv: boolean; pool: number; |
| 42 | /** host mode with a pool: ms to prewarm it (before the clock), pool counters at the end. */ |
| 43 | prewarmMs?: number; poolStats?: { created: number; hits: number; misses: number }; |
| 44 | /** ms: creating N renderers (+ sending ops) — synchronous work on the main thread. */ |
| 45 | build: number; |
| 46 | /** ms: until every bubble has applied its ops and reported a size (ops mode) / every host reported loaded (host mode). */ |
| 47 | ready: number; |
| 48 | /** ms: until the frame after `ready` was painted. */ |
| 49 | painted: number; |
| 50 | /** Long tasks (> 50 ms) on the main thread between start and painted: count and total ms. */ |
| 51 | longTasks: { count: number; total: number }; |
| 52 | /** Bytes from measureUserAgentSpecificMemory, after - before, or null when unavailable. */ |
| 53 | memory: number | null; |
| 54 | memoryBefore: number | null; |
| 55 | /** Scroll through the feed: average and p95 frame interval (ms), frames over 32 ms. */ |
| 56 | scroll: { frames: number; avg: number; p95: number; slow: number }; |
| 57 | /** Total height of the feed content (px): a sanity check that both renderers laid out the same widgets. */ |
| 58 | feedHeight: number; |
| 59 | /** Main-thread CPU per bubble is not observable; wall-clock per bubble = ready / count. */ |
| 60 | perBubble: number; |
| 61 | } |
| 62 | |
| 63 | const memory = async (): Promise<number | null> => { |
| 64 | const p = performance as any; |
| 65 | if (!p.measureUserAgentSpecificMemory) return null; |
| 66 | try { return (await p.measureUserAgentSpecificMemory()).bytes as number; } catch { return null; } |
| 67 | }; |
| 68 | const nextFrame = () => new Promise<number>((r) => requestAnimationFrame((t) => r(t))); |
| 69 | const settle = async () => { await nextFrame(); await nextFrame(); }; |
| 70 | |
| 71 | function bubble(): HTMLElement { |
| 72 | const b = document.createElement('div'); |
| 73 | b.className = 'bubble' + (CV ? ' cv' : ''); |
| 74 | const wrap = document.createElement('div'); |
| 75 | wrap.className = 'frame-wrap'; |
| 76 | b.appendChild(wrap); |
| 77 | feed.appendChild(b); |
| 78 | return wrap; |
| 79 | } |
| 80 | |
| 81 | async function scrollTest(): Promise<Result['scroll']> { |
| 82 | feed.scrollTop = 0; |
| 83 | await settle(); |
| 84 | const total = feed.scrollHeight - feed.clientHeight; |
| 85 | const steps = 60; |
| 86 | const deltas: number[] = []; |
| 87 | let last = await nextFrame(); |
| 88 | for (let i = 1; i <= steps; i++) { |
| 89 | feed.scrollTop = (total * i) / steps; |
| 90 | const t = await nextFrame(); |
| 91 | deltas.push(t - last); |
| 92 | last = t; |
| 93 | } |
| 94 | const sorted = [...deltas].sort((a, b) => a - b); |
| 95 | return { |
| 96 | frames: deltas.length, |
| 97 | avg: deltas.reduce((a, b) => a + b, 0) / deltas.length, |
| 98 | p95: sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95))], |
| 99 | slow: deltas.filter((d) => d > 32).length, |
| 100 | }; |
| 101 | } |
| 102 | |
| 103 | async function runOps(): Promise<Result> { |
| 104 | const opsFiles = await Promise.all(WIDGETS.map(async (w) => (await (await fetch(`/bench/ops/${w |
| 105 | const memoryBefore = await memory(); |
| 106 | const longTasks: PerformanceEntry[] = []; |
| 107 | const po = new PerformanceObserver((l) => longTasks.push(...l.getEntries())); |
| 108 | try { po.observe({ type: 'longtask', buffered: false }); } catch {} |
| 109 | |
| 110 | const t0 = performance.now(); |
| 111 | let readyCount = 0; |
| 112 | let resolveReady!: () => void; |
| 113 | const allReady = new Promise<void>((r) => (resolveReady = r)); |
| 114 | const renderers: Renderer[] = []; |
| 115 | for (let i = 0; i < COUNT; i++) { |
| 116 | const r = factory(bubble(), 'light'); |
| 117 | r.onMessage = (msg: RendererToHost) => { |
| 118 | if (msg.type === 'size') r.element.style.height = Math.min(Math.max(msg.height, MIN_HEIGHT), MAX_HEIGHT) + 'px'; |
| 119 | // The answer to the sentinel query arrives after the ops were applied (messages are ordered). |
| 120 | if (msg.type === 'result' && msg.qid === 1 && ++readyCount === COUNT) resolveReady(); |
| 121 | }; |
| 122 | r.load(); |
| 123 | for (const m of opsFiles[i % opsFiles.length]) r.send(m); |
| 124 | r.send({ type: 'query', qid: 1, query: { q: 'viewport' } }); |
| 125 | renderers.push(r); |
| 126 | } |
| 127 | const build = performance.now() - t0; |
| 128 | await allReady; |
| 129 | const ready = performance.now() - t0; |
| 130 | await nextFrame(); |
| 131 | const painted = performance.now() - t0; |
| 132 | po.disconnect(); |
| 133 | await settle(); |
| 134 | const memoryAfter = await memory(); |
| 135 | const scroll = await scrollTest(); |
| 136 | return { |
| 137 | renderer: RENDERER, mode: MODE, count: COUNT, cv: CV, pool: 0, build, ready, painted, |
| 138 | longTasks: { count: longTasks.length, total: longTasks.reduce((a, e) => a + e.duration, 0) }, |
| 139 | memory: memoryBefore !== null && memoryAfter !== null ? memoryAfter - memoryBefore : null, memoryBefore, |
| 140 | scroll, feedHeight: feed.scrollHeight, perBubble: ready / COUNT, |
| 141 | }; |
| 142 | } |
| 143 | |
| 144 | async function runHost(): Promise<Result> { |
| 145 | const htmls = await Promise.all(WIDGETS.map(async (w) => (await fetch(`/corpus/${w}.html`)). |
| 146 | let pool: WorkerPool | undefined; |
| 147 | let prewarmMs: number | undefined; |
| 148 | if (POOL > 0) { |
| 149 | pool = new WorkerPool(POOL); |
| 150 | const tp = performance.now(); |
| 151 | await pool.prewarm(); |
| 152 | prewarmMs = performance.now() - tp; |
| 153 | } |
| 154 | const memoryBefore = await memory(); |
| 155 | const longTasks: PerformanceEntry[] = []; |
| 156 | const po = new PerformanceObserver((l) => longTasks.push(...l.getEntries())); |
| 157 | try { po.observe({ type: 'longtask', buffered: false }); } catch {} |
| 158 | const t0 = performance.now(); |
| 159 | const hosts: WidgetHost[] = []; |
| 160 | let i = 0; |
| 161 | const one = () => new Promise<void>((resolve) => { |
| 162 | const idx = i++; |
| 163 | const h = new WidgetHost(bubble(), htmls[idx % htmls.length], { |
| 164 | theme: 'light', rendererFactory: factory, workerPool: pool, |
| 165 | onLoaded: resolve, onDead: () => resolve(), |
| 166 | }); |
| 167 | hosts.push(h); |
| 168 | }); |
| 169 | // `parallel` sandboxes boot at a time (more than a few do not fit the boot CPU slice together). |
| 170 | const lanes: Promise<void>[] = []; |
| 171 | for (let lane = 0; lane < PARALLEL; lane++) lanes.push((async () => { while (i < COUNT) await one(); })()); |
| 172 | await Promise.all(lanes); |
| 173 | const ready = performance.now() - t0; |
| 174 | await nextFrame(); |
| 175 | const painted = performance.now() - t0; |
| 176 | po.disconnect(); |
| 177 | await settle(); |
| 178 | const memoryAfter = await memory(); |
| 179 | const scroll = await scrollTest(); |
| 180 | return { |
| 181 | renderer: RENDERER, mode: MODE, count: COUNT, cv: CV, pool: POOL, prewarmMs, poolStats: pool && { ...pool.stats }, build: 0, ready, painted, |
| 182 | longTasks: { count: longTasks.length, total: longTasks.reduce((a, e) => a + e.duration, 0) }, |
| 183 | memory: memoryBefore !== null && memoryAfter !== null ? memoryAfter - memoryBefore : null, memoryBefore, |
| 184 | scroll, feedHeight: feed.scrollHeight, perBubble: ready / COUNT, |
| 185 | }; |
| 186 | } |
| 187 | |
| 188 | hud.textContent = `feed bench: ${RENDERER}, ${MODE}, ${COUNT} bubbles${CV ? ', content-visibility' : ''}…`; |
| 189 | let started = false; |
| 190 | function start() { |
| 191 | if (started) return; |
| 192 | started = true; |
| 193 | (MODE === 'host' ? runHost() : runOps()).then((result) => { |
| 194 | (window as any).__feed = { done: true, result, error: null }; |
| 195 | const mb = (b: number | null) => (b === null ? 'n/a' : (b / 1048576 |
| 196 | hud.textContent = [ |
| 197 | `${result.renderer} · ${result.mode} · ${result.count} bubbles${result.cv ? ' · content-visibility' : ''}${result.pool ? |
| 198 | `build ${result.build.toFixed(0)} ms · ready ${result.ready.toFixed(0)} ms · painted ${result.painted.toFixed(0)} ms`, |
| 199 | `${result.perBubble.toFixed(1)} ms/bubble · long tasks ${result.longTasks.count} (${result.longTasks.total.toFixed(0)} ms)`, |
| 200 | `memory +${mb(result.memory)} (before ${mb(result.memoryBefore)})`, |
| 201 | `scroll: avg ${result.scroll.avg.toFixed(1)} ms, p95 ${result.scroll.p95.toFixed(1)} ms, ${result.scroll.slow}/${result |
| 202 | `feed height ${result.feedHeight} px`, |
| 203 | ].join('\n'); |
| 204 | }, (e) => { |
| 205 | (window as any).__feed = { ...(window as any).__feed, done: true, result: null, error: String(e) }; |
| 206 | hud.textContent = 'error: ' + String(e); |
| 207 | }); |
| 208 | } |
| 209 | (window as any).__feed = { done: false, result: null as Result | null, error: null as string | null, start }; |
| 210 | if (params.get('auto') === '1') start(); |
| 211 | |