| 1 | // Chat feed demo (dev tooling for the web dev app, `?feed=1`; nothing here ships |
| 2 | // in a native build). The web port of the idea behind ios/DemoApp/Sources/ChatFeed |
| 3 | // (docs/chat-feed-ios.md): a vertical feed of 60–80 bubbles, each a WidgetHost |
| 4 | // on corpus/showcase (the interactive, animated demos; `corpus=common` for the |
| 5 | // renderer-comparison corpus, `corpus=gestures` for the drag claims, `corpus=safe-area` for the client's time over the |
| 6 | // corner), driven by the list's own lifecycle — a host is created when |
| 7 | // a bubble comes near the viewport, hidden (`setVisible(false)`) when it leaves |
| 8 | // it, and dropped when it is screens away (the height is remembered so the |
| 9 | // layout does not jump; a host from the pool replaces it when it comes back). |
| 10 | // Four things to see, not click: |
| 11 | // 1. the warmed worker pool on/off while scrolling: with the pool a bubble |
| 12 | // shows content as it arrives, without it the bubble sits blank through |
| 13 | // the QuickJS + sandbox-bundle boot (the striped placeholder counts the ms); |
| 14 | // 2. the renderer swapped live on the same feed — iframe → shadow DOM → |
| 15 | // canvas (litehtml / Blitz): same HTML, same sandbox, same validator, the |
| 16 | // renderer seam (src/host/renderer.ts) is the only thing that changes; |
| 17 | // 3. one hostile bubble (corpus/attacks) among the normal ones: it is |
| 18 | // stopped or throttled by the runtime limits, the canary stays at 0, the |
| 19 | // feed keeps scrolling; |
| 20 | // 4. a metrics overlay: booted, time to content (median / p90) per pool |
| 21 | // setting, memory, canary; |
| 22 | // 5. the bench panel (feed-bench.ts, the **bench** button / `?bench=1`): the |
| 23 | // same feed run N passes per renderer × pool setting with the scripted |
| 24 | // scroll, every boot recorded (`BootRecord`), two live tables and a JSON |
| 25 | // report — the web twin of the iOS feed-report.json. |
| 26 | // Trusted glue only: the sandbox, the validator and the renderers are untouched, |
| 27 | // every bubble is an ordinary WidgetHost. |
| 28 | |
| 29 | import { startBench, measureMemory, type BenchApi, type MemorySample } from './feed-bench'; |
| 30 | import { BlitzRenderer } from './renderers/blitz-renderer'; |
| 31 | import { IframeRenderer } from '@telegram/widget-sandbox/host/iframe-renderer'; |
| 32 | import { LitehtmlRenderer } from './renderers/litehtml-renderer'; |
| 33 | import type { Renderer, RendererFactory } from '@telegram/widget-sandbox/host/renderer'; |
| 34 | import { ShadowDomRenderer } from '@telegram/widget-sandbox/host/shadow-renderer'; |
| 35 | import { WidgetHost } from '@telegram/widget-sandbox/host/widget-host'; |
| 36 | import { WorkerPool } from '@telegram/widget-sandbox/host/worker-pool'; |
| 37 | import { WIDGET_FEATURES, WIDGET_POLICY } from './policy'; |
| 38 | import { bubbleGesturesOption, showBubbleGesture, type GestureMode } from './bubble-gestures'; |
| 39 | import { DEFAULT_RESIZE_ANCHOR, type ResizeAnchor } from '@telegram/widget-sandbox/shared/sdk-policy'; |
| 40 | import { REFERENCE_TIME_LABEL, referenceSafeArea, timeCornerStyle } from '@telegram/widget-sandbox/shared/reference'; |
| 41 | |
| 42 | export type FeedRenderer = 'iframe' | 'shadow' | 'blitz' | 'litehtml'; |
| 43 | /** Which corpus fills the widget bubbles; `BATCH_ORDER` is the round-robin over its batches (light first). */ |
| 44 | export type FeedCorpus = 'showcase' | 'common' | 'gestures' | 'resize' | 'safe-area'; |
| 45 | const CORPORA: { kind: FeedCorpus; title: string }[] = [ |
| 46 | { kind: 'showcase', title: 'corpus/showcase: 21 interactive, animated demos on the full web profile (boarding pass, ride tracking, smart home, kanban, live poll …)' }, |
| 47 | { kind: 'common', title: 'corpus/common: the 32 widgets on the profile every renderer shares, for like-for-like renderer timings' }, |
| 48 | { kind: 'gestures', title: 'corpus/gestures: what the horizontal-only rule removed (v0.1.3: games on touch-action none and the same games on pan-y, joystick and 2048, now alike; a wheel picker that no longer turns) and what is fine with horizontal only (paddle, card carousel, range slider)' }, |
| 49 | { kind: 'resize', title: 'corpus/resize: one widget per resize anchor (setResizeAnchor, v0.1.3): an FAQ that grows downward (the default, top), a support thread that grows upward (bottom), results that grow downward (top)' }, |
| 50 | { kind: 'safe-area', title: 'corpus/safe-area: the client\'s time over the bottom corner of a widget with no caption below it (docs/sdk-v1.md §2.17): every bubble gets the reference band and the time drawn over it; a diagnostic, full-bleed cards (one right-to-left), an unstyled note, CSS as models write it, a canvas chart, the caption pair' }, |
| 51 | ]; |
| 52 | const BATCH_ORDER: Record<FeedCorpus, string[]> = { |
| 53 | showcase: ['travel', 'commerce', 'life', 'work'], common: ['cards', 'interactive', 'live', 'heavy'], gestures: ['1-pairs', '2-horizontal', '3-vertical'], |
| 54 | resize: ['1-default', '2-grows-up', '3-grows-down'], |
| 55 | 'safe-area': ['1-diagnostic', '2-cards', '3-css', '4-script', '5-caption'], |
| 56 | }; |
| 57 | const RENDERERS: { kind: FeedRenderer; label: string; title: string }[] = [ |
| 58 | { kind: 'iframe', label: 'iframe', title: 'sandboxed srcdoc iframe per bubble (product renderer)' }, |
| 59 | { kind: 'shadow', label: 'shadow', title: 'the same renderer core on a shadow root in this page, no iframe (prototype)' }, |
| 60 | { kind: 'litehtml', label: 'litehtml', title: 'litehtml (wasm) painting validated ops on a canvas — needs pnpm build:litehtml-web' }, |
| 61 | { kind: 'blitz', label: 'blitz', title: 'Blitz (wasm) painting validated ops on a canvas — needs pnpm build:blitz-web' }, |
| 62 | ]; |
| 63 | const FACTORIES: Record<FeedRenderer, RendererFactory> = { |
| 64 | iframe: IframeRenderer.factory, shadow: ShadowDomRenderer.factory, blitz: BlitzRenderer.factory, litehtml: LitehtmlRenderer.factory, |
| 65 | }; |
| 66 | /** Hostile bubbles on offer (corpus/attacks); each is stopped or contained by a different runtime limit. */ |
| 67 | const HOSTILE: { name: string; title: string }[] = [ |
| 68 | { name: 'none', title: 'no hostile bubble' }, |
| 69 | { name: 'fallback-at-boot', title: 'infinite loop in the first script: killed by the boot CPU slice (500 ms), the static markup stays as the frozen fallback' }, |
| 70 | { name: 'cpu-raf-burn', title: 'a 30 ms rAF loop: throttled by the 300 ms/s CPU quota, not killed' }, |
| 71 | { name: 'cpu-greedy-timer', title: 'greedy timers: deferred by the CPU quota' }, |
| 72 | { name: 'timer-flood', title: '100 000 setTimeout calls: refused past 256 timers' }, |
| 73 | { name: 'api-fetch', title: 'fetch() to the canary: NetworkDisabledError in the sandbox, nothing leaves' }, |
| 74 | { name: 'markup-img-src', title: 'an <img src=http://…> to the canary: the validator drops the URL' }, |
| 75 | { name: 'mem-steady-growth', title: 'keeps 8 MB of typed arrays per tick; watch the QuickJS heap line (the web QuickJS build does not cap typed-array growth today: a sandbox gap, not a feed one)' }, |
| 76 | { name: 'mem-burst-alloc', title: 'one huge allocation' }, |
| 77 | ]; |
| 78 | /** The hostile bubble's position among the widget bubbles: the third one, on the first screen. */ |
| 79 | const HOSTILE_INDEX = 2; |
| 80 | const MIN_HEIGHT = 24; // WidgetHost's clamp: an empty document reports exactly this |
| 81 | const TEXTS = [ |
| 82 | 'Here, have a look at this one', 'can you make it a card?', 'ok that works', 'and the live one?', 'nice', 'try scrolling faster', |
| 83 | 'this is the heavy batch', 'same file, other renderer', 'what does the dashboard look like now', 'ship it', 'one more', 'let me check the poll', |
| 84 | ]; |
| 85 | |
| 86 | interface Bubble { |
| 87 | /** Index among the widget bubbles (the head line shows it). */ |
| 88 | idx: number; |
| 89 | file: string; |
| 90 | hostile: boolean; |
| 91 | el: HTMLElement; |
| 92 | head: HTMLElement; |
| 93 | wrap: HTMLElement; |
| 94 | foot: HTMLElement; |
| 95 | host: WidgetHost | null; |
| 96 | state: 'idle' | 'queued' | 'booting' | 'live' | 'dead' | 'parked' | 'stopped'; |
| 97 | near: boolean; |
| 98 | visible: boolean; |
| 99 | /** Remembered bubble height (px): the placeholder while parked or booting, so the layout holds still. */ |
| 100 | height: number; |
| 101 | /** The edge that stays put when the height changes (the widget's `setResizeAnchor`, from the last size report; kept with the height). */ |
| 102 | anchor: ResizeAnchor; |
| 103 | /** The bubble's laid-out height (head and foot included) at the last anchoring pass. */ |
| 104 | laidOut: number; |
| 105 | /** When the current blank stretch started (visible, no content yet); 0 when not blank. */ |
| 106 | blankSince: number; |
| 107 | createdAt: number; |
| 108 | loadedAt: number; |
| 109 | contentAt: number; |
| 110 | /** When the bubble first came into view since this boot (0 until then; reset when the host is dropped). */ |
| 111 | shownAt: number; |
| 112 | shownSampled: boolean; |
| 113 | /** A size report arrived in this boot (the remembered height from an earlier boot does not count as content). */ |
| 114 | sized: boolean; |
| 115 | poolOn: boolean; |
| 116 | renderer: FeedRenderer; |
| 117 | boots: number; |
| 118 | blocked: number; |
| 119 | throttled: number; |
| 120 | timerLimit: boolean; |
| 121 | heap: number; |
| 122 | deadReason: string | null; |
| 123 | /** Killed once: never re-run (a product keeps the frozen fallback, not a second attempt). */ |
| 124 | killed: boolean; |
| 125 | lastError: string | null; |
| 126 | /** The record of the current boot (feed-bench.ts reads them per pass). */ |
| 127 | rec: BootRecord | null; |
| 128 | } |
| 129 | |
| 130 | /** |
| 131 | * One boot of one bubble, every clock in `performance.now()` ms. What the |
| 132 | * bench aggregates; nothing here is typed in by hand. `blankMs` is the time |
| 133 | * the bubble was inside the viewport without content (it accumulates while |
| 134 | * the bubble is visible and stops at content or when the host is dropped). |
| 135 | */ |
| 136 | export interface BootRecord { |
| 137 | idx: number; |
| 138 | file: string; |
| 139 | renderer: FeedRenderer; |
| 140 | poolOn: boolean; |
| 141 | /** The pool had a warm worker when this host took one (false = booted a fresh one, pool or not). */ |
| 142 | poolHit: boolean; |
| 143 | /** The first boot of the feed since `reset` (the cold path: the first bubble the reader sees). */ |
| 144 | cold: boolean; |
| 145 | createdAt: number; |
| 146 | /** `new WidgetHost` on the main thread: renderer construction + validator + worker handoff, synchronous. */ |
| 147 | hostCreateMs: number; |
| 148 | /** The renderer factory + `load()`, synchronous part. */ |
| 149 | rendererCreateMs: number; |
| 150 | /** Renderer construction → its first message (the canvas renderers' `ready` after the wasm init; the iframe's and the shadow root's first size report, after the document load for the iframe); null until it arrives. */ |
| 151 | rendererReadyMs: number | null; |
| 152 | /** Creation → first content (the time-to-first-paint of the bubble). */ |
| 153 | contentMs: number | null; |
| 154 | loadedMs: number | null; |
| 155 | /** First time the bubble was inside the viewport in this boot (0 = never). */ |
| 156 | shownAt: number; |
| 157 | blankMs: number; |
| 158 | dead: string | null; |
| 159 | } |
| 160 | |
| 161 | interface Samples { boot: number[]; shown: number[]; loaded: number[]; misses: number } |
| 162 | const newSamples = (): Samples => ({ boot: [], shown: [], loaded: [], misses: 0 }); |
| 163 | |
| 164 | export interface FeedOptions { |
| 165 | theme: 'light' | 'dark'; |
| 166 | params: URLSearchParams; |
| 167 | /** The bubbles' own presses (bubble-gestures.ts); `phone` when absent. */ |
| 168 | gestures?: GestureMode; |
| 169 | } |
| 170 | |
| 171 | export interface FeedApi { |
| 172 | setTheme(theme: 'light' | 'dark'): void; |
| 173 | /** Who gets a press: the bubble of a phone or a desktop client unless touch-action claims it, or (`off`) the widget. */ |
| 174 | setGestures(mode: GestureMode): void; |
| 175 | setRenderer(kind: FeedRenderer): void; |
| 176 | setPool(on: boolean): void; |
| 177 | /** `rebuild` false: only the setting changes, the next `reset` applies it (the bench sets several at once). */ |
| 178 | setHostile(name: string, rebuild?: boolean): void; |
| 179 | setCorpus(kind: FeedCorpus, rebuild?: boolean): void; |
| 180 | setCount(n: number, rebuild?: boolean): void; |
| 181 | reset(): Promise<void>; |
| 182 | /** Drop every host and empty the feed (a `reset` without the rebuild): the bench measures its memory baseline here. */ |
| 183 | clear(): void; |
| 184 | /** Scripted scroll like the iOS `step` run: one screen, pause, repeat, down and back up. Resolves when done. */ |
| 185 | autoScroll(): Promise<void>; |
| 186 | stop(): void; |
| 187 | /** Pause the demo's own periodic work (overlay refresh, memory and canary polls) while the bench measures. */ |
| 188 | quiet(on: boolean): void; |
| 189 | /** A snapshot of the metrics the overlay shows. */ |
| 190 | readonly summary: FeedSummary; |
| 191 | readonly bubbles: readonly Bubble[]; |
| 192 | readonly pool: WorkerPool | null; |
| 193 | /** Every boot since the last `reset`, in creation order. */ |
| 194 | readonly records: readonly BootRecord[]; |
| 195 | readonly settings: { corpus: FeedCorpus; renderer: FeedRenderer; poolOn: boolean; poolSize: number; hostile: string; |
| 196 | /** The scroll container's size (the bench records it: the step scroll is one screen of it). */ |
| 197 | readonly viewport: { width: number; height: number }; |
| 198 | /** The scroll container itself (the bench's memory ramp scrolls it). */ |
| 199 | readonly scroller: HTMLElement; |
| 200 | /** Drop distance in screens (`keep`), changeable live; the bench lifts it for the memory ramp and puts it back. */ |
| 201 | setKeep(screens: number): void; |
| 202 | bench: BenchApi; |
| 203 | } |
| 204 | |
| 205 | export interface FeedSummary { |
| 206 | corpus: FeedCorpus; |
| 207 | renderer: FeedRenderer; |
| 208 | pool: { size: number; warm: number; created: number; hits: number; misses: number } | |
| 209 | count: number; |
| 210 | live: number; |
| 211 | booted: number; |
| 212 | booting: number; |
| 213 | parked: number; |
| 214 | dead: number; |
| 215 | samples: { on: Samples; off: Samples }; |
| 216 | memory: { total: number | null; workers: number | null; frames: number | null; |
| 217 | canary: { state: 'unknown' | 'ok' | 'off'; hits: number }; |
| 218 | blocked: number; |
| 219 | scroll: { p95: number; slow: number; frames: number }; |
| 220 | } |
| 221 | |
| 222 | const now = () => performance.now(); |
| 223 | const quantile = (xs: number[], q: number) => { |
| 224 | if (!xs.length) return NaN; |
| 225 | const s = [...xs].sort((a, b) => a - b); |
| 226 | return s[Math.min(s.length - 1, Math.floor(s.length * q))]; |
| 227 | }; |
| 228 | const fmtMs = (v: number) => (Number.isNaN(v) ? '—' : `${v < 0 ? '−' |
| 229 | const fmtMb = (b: number | null) => (b === null ? 'n/a' : `${(b |
| 230 | const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms)); |
| 231 | /** Seeded shuffle (an LCG, like the corpus files use) so two runs show the same feed. */ |
| 232 | function shuffled<T>(xs: T[], seed: number): T[] { |
| 233 | const out = [...xs]; |
| 234 | let s = seed >>> 0; |
| 235 | for (let i = out.length - 1; i > 0; i--) { |
| 236 | s = (s * 1664525 + 1013904223) >>> 0; |
| 237 | const j = s % (i + 1); |
| 238 | [out[i], out[j]] = [out[j], out[i]]; |
| 239 | } |
| 240 | return out; |
| 241 | } |
| 242 | |
| 243 | export function startFeed(view: HTMLElement, opts: FeedOptions): FeedApi { |
| 244 | const params = opts.params; |
| 245 | let theme = opts.theme; |
| 246 | let gestures: GestureMode = opts.gestures ?? 'phone'; |
| 247 | let renderer: FeedRenderer = (RENDERERS.find((r) => r.kind === params.get('renderer'))?.kind) ?? 'iframe'; |
| 248 | let corpus: FeedCorpus = (CORPORA.find((c) => c.kind === params.get('corpus'))?.kind) ?? 'showcase'; |
| 249 | const poolSize = Math.max(1, Number(params.get('poolSize') ?? 6)); |
| 250 | let poolOn = params.get('pool') !== '0'; |
| 251 | let hostile = HOSTILE.find((h) => h.name === params.get('hostile'))?.name ?? 'fallback-at-boot'; |
| 252 | let count = Math.min(200, Math.max(1, Number(params.get('count') ?? 72))); |
| 253 | /** How many sandboxes boot at once (a QuickJS worker each); more than a few contend for the boot CPU slice. */ |
| 254 | const lanes = Math.max(1, Number(params.get('lanes') ?? 4)); |
| 255 | /** Prefetch distance and the drop distance, in screens. */ |
| 256 | const ahead = Math.max(0, Number(params.get('ahead') ?? 0.5)); |
| 257 | let keep = Math.max(ahead, Number(params.get('keep') ?? 2)); |
| 258 | |
| 259 | let pool: WorkerPool | null = null; |
| 260 | let bubbles: Bubble[] = []; |
| 261 | const htmls = new Map<string, string>(); |
| 262 | const queue: Bubble[] = []; |
| 263 | let booting = 0; |
| 264 | let booted = 0; |
| 265 | let samples = { on: newSamples(), off: newSamples() }; |
| 266 | let generation = 0; |
| 267 | let records: BootRecord[] = []; |
| 268 | let quietMode = false; |
| 269 | |
| 270 | // ───────────── DOM ───────────── |
| 271 | |
| 272 | view.replaceChildren(); |
| 273 | const bar = document.createElement('div'); |
| 274 | bar.className = 'feed-bar'; |
| 275 | const corpusLabel = document.createElement('label'); |
| 276 | corpusLabel.className = 'feed-group'; |
| 277 | corpusLabel.append('corpus '); |
| 278 | const corpusSelect = document.createElement('select'); |
| 279 | for (const c of CORPORA) { |
| 280 | const o = document.createElement('option'); |
| 281 | o.value = c.kind; |
| 282 | o.textContent = c.kind; |
| 283 | o.title = c.title; |
| 284 | corpusSelect.appendChild(o); |
| 285 | } |
| 286 | corpusSelect.value = corpus; |
| 287 | corpusSelect.title = CORPORA.find((c) => c.kind === corpus)!.title; |
| 288 | corpusSelect.addEventListener('change', () => setCorpus(corpusSelect.value as FeedCorpus)); |
| 289 | corpusLabel.appendChild(corpusSelect); |
| 290 | const rendererGroup = document.createElement('span'); |
| 291 | rendererGroup.className = 'feed-group'; |
| 292 | rendererGroup.append('renderer '); |
| 293 | const rendererInputs: HTMLInputElement[] = []; |
| 294 | for (const r of RENDERERS) { |
| 295 | const label = document.createElement('label'); |
| 296 | label.title = r.title; |
| 297 | const input = document.createElement('input'); |
| 298 | input.type = 'radio'; |
| 299 | input.name = 'feed-renderer'; |
| 300 | input.value = r.kind; |
| 301 | input.checked = r.kind === renderer; |
| 302 | input.addEventListener('change', () => { if (input.checked) setRenderer(r.kind); }); |
| 303 | label.append(input, r.label); |
| 304 | rendererGroup.appendChild(label); |
| 305 | rendererInputs.push(input); |
| 306 | } |
| 307 | const poolLabel = document.createElement('label'); |
| 308 | poolLabel.className = 'feed-group'; |
| 309 | poolLabel.title = `a pool of ${poolSize} warmed sandbox workers (QuickJS + sandbox bundle evaluated, waiting for a widget); off = every bubble boots its own`; |
| 310 | const poolInput = document.createElement('input'); |
| 311 | poolInput.type = 'checkbox'; |
| 312 | poolInput.checked = poolOn; |
| 313 | poolInput.addEventListener('change', () => setPool(poolInput.checked)); |
| 314 | poolLabel.append(poolInput, ` pool ×${poolSize}`); |
| 315 | const hostileLabel = document.createElement('label'); |
| 316 | hostileLabel.className = 'feed-group'; |
| 317 | hostileLabel.append('hostile '); |
| 318 | const hostileSelect = document.createElement('select'); |
| 319 | for (const h of HOSTILE) { |
| 320 | const o = document.createElement('option'); |
| 321 | o.value = h.name; |
| 322 | o.textContent = h.name; |
| 323 | o.title = h.title; |
| 324 | hostileSelect.appendChild(o); |
| 325 | } |
| 326 | hostileSelect.value = hostile; |
| 327 | hostileSelect.addEventListener('change', () => setHostile(hostileSelect.value)); |
| 328 | hostileLabel.appendChild(hostileSelect); |
| 329 | const countLabel = document.createElement('label'); |
| 330 | countLabel.className = 'feed-group'; |
| 331 | countLabel.append('bubbles '); |
| 332 | const countInput = document.createElement('input'); |
| 333 | countInput.type = 'number'; |
| 334 | countInput.min = '1'; |
| 335 | countInput.max = '200'; |
| 336 | countInput.value = String(count); |
| 337 | countInput.addEventListener('change', () => setCount(Number(countInput.value) || 72)); |
| 338 | countLabel.appendChild(countInput); |
| 339 | const resetBtn = document.createElement('button'); |
| 340 | resetBtn.type = 'button'; |
| 341 | resetBtn.textContent = 'reset'; |
| 342 | resetBtn.title = 'drop every host, clear the metrics, scroll to the top (the pool setting stays): run the same scroll with the pool on and off'; |
| 343 | resetBtn.addEventListener('click', () => void reset()); |
| 344 | const scrollBtn = document.createElement('button'); |
| 345 | scrollBtn.type = 'button'; |
| 346 | scrollBtn.textContent = '▶ auto-scroll'; |
| 347 | scrollBtn.title = 'scripted scroll like the iOS feed run: one screen, pause 0.9 s, repeat to the bottom and back'; |
| 348 | scrollBtn.addEventListener('click', () => { if (autoRunning) stop(); else void autoScroll(); }); |
| 349 | const benchBtn = document.createElement('button'); |
| 350 | benchBtn.type = 'button'; |
| 351 | benchBtn.textContent = '📊 bench'; |
| 352 | benchBtn.title = 'the measurement panel: N passes of the scripted scroll per renderer × pool setting, two live tables, a JSON report (feed-bench.ts)'; |
| 353 | bar.append(corpusLabel, rendererGroup, poolLabel, hostileLabel, countLabel, resetBtn, scrollBtn, benchBtn); |
| 354 | |
| 355 | const main = document.createElement('div'); |
| 356 | main.className = 'feed-main'; |
| 357 | const benchPanel = document.createElement('div'); |
| 358 | benchPanel.className = 'feed-bench hidden'; |
| 359 | const scroller = document.createElement('div'); |
| 360 | scroller.className = 'feed-scroll'; |
| 361 | const column = document.createElement('div'); |
| 362 | column.className = 'feed-col'; |
| 363 | scroller.appendChild(column); |
| 364 | main.append(benchPanel, scroller); |
| 365 | const overlay = document.createElement('div'); |
| 366 | overlay.className = 'feed-overlay'; |
| 367 | view.append(bar, main, overlay); |
| 368 | benchBtn.addEventListener('click', () => { benchPanel.classList.toggle('hidden'); benchBtn.classList.toggle('on', !benchPanel.classList.contains('hidden')); }); |
| 369 | |
| 370 | // ───────────── lifecycle: three observers on the scroller ───────────── |
| 371 | |
| 372 | const byEl = new Map<Element, Bubble>(); |
| 373 | const ioNear = new IntersectionObserver((entries) => { |
| 374 | for (const e of entries) { |
| 375 | const b = byEl.get(e.target); |
| 376 | if (!b) continue; |
| 377 | b.near = e.isIntersecting; |
| 378 | if (b.near && !b.host && b.state !== 'queued' && !b.killed) enqueue(b); |
| 379 | else if (!b.near && b.state === 'queued') { b.state = 'idle'; const i = queue.indexOf(b); if (i >= 0) queue. |
| 380 | } |
| 381 | pump(); |
| 382 | }, { root: scroller, rootMargin: `${Math.round(ahead * 100)}% 0px` }); |
| 383 | const ioVisible = new IntersectionObserver((entries) => { |
| 384 | for (const e of entries) { |
| 385 | const b = byEl.get(e.target); |
| 386 | if (!b || b.visible === e.isIntersecting) continue; |
| 387 | b.visible = e.isIntersecting; |
| 388 | // `shownAt` is the first time the bubble was seen since its host was created (or dropped): one sample per boot. |
| 389 | if (b.visible && !b.shownAt) { b.shownAt = now(); trySampleShown(b); } |
| 390 | // The record: first sight of the bubble in this boot, and the blank time (visible without content: starts when a |
| 391 | // content-less bubble comes in, stops when it leaves or at content). |
| 392 | if (b.rec && b.visible && !b.rec.shownAt) b.rec.shownAt = now(); |
| 393 | if (b.rec && !b.rec.contentMs) { |
| 394 | if (b.visible) b.blankSince = now(); |
| 395 | else stopBlank(b); |
| 396 | } |
| 397 | b.host?.setVisible(b.visible); |
| 398 | } |
| 399 | }, { root: scroller, rootMargin: '0px' }); |
| 400 | const farObserver = () => new IntersectionObserver((entries) => { |
| 401 | for (const e of entries) { |
| 402 | const b = byEl.get(e.target); |
| 403 | if (b && !e.isIntersecting && b.host && b.state !== 'dead' && b.state !== 'booting') park(b); |
| 404 | } |
| 405 | }, { root: scroller, rootMargin: `${Math.round(keep * 100)}% 0px` }); |
| 406 | let ioFar = farObserver(); |
| 407 | /** The drop distance, live: the bench lifts it for its memory ramp (every bubble boots and stays). */ |
| 408 | function setKeep(screens: number) { |
| 409 | keep = Math.max(ahead, screens); |
| 410 | ioFar.disconnect(); |
| 411 | ioFar = farObserver(); |
| 412 | for (const b of bubbles) ioFar.observe(b.el); |
| 413 | } |
| 414 | |
| 415 | // ───────────── the resize anchor (docs/sdk-v1.md §5.6): the anchored edge stays put on screen ───────────── |
| 416 | |
| 417 | // The list compensates its scroll itself (the browser's own scroll anchoring is off: .feed-scroll in style.css): a |
| 418 | // bubble on screen anchored at the bottom keeps its bottom edge, the content above it moves; anchored at the top it |
| 419 | // keeps its top edge, the content below moves; a bubble above the viewport never moves what is on screen. The same |
| 420 | // for every height change: a size report, the boot placeholder (the cached height) giving way, a re-created bubble. |
| 421 | const anchorObserver = new ResizeObserver((entries) => { |
| 422 | const view = scroller.getBoundingClientRect(); |
| 423 | let shift = 0; |
| 424 | for (const e of entries) { |
| 425 | const b = byEl.get(e.target); |
| 426 | if (!b) continue; |
| 427 | const h = b.el.offsetHeight, delta = h - b.laidOut; |
| 428 | if (!b.laidOut || !delta) { b.laidOut = h; continue; } |
| 429 | b.laidOut = h; |
| 430 | const r = b.el.getBoundingClientRect(); |
| 431 | const top = r.top, oldBottom = top + h - delta; |
| 432 | if (oldBottom <= view.top) shift += delta; |
| 433 | else if (top < view.bottom && b.anchor === 'bottom') shift += delta; |
| 434 | } |
| 435 | if (shift) scroller.scrollTop += shift; |
| 436 | }); |
| 437 | |
| 438 | function enqueue(b: Bubble) { |
| 439 | b.state = 'queued'; |
| 440 | queue.push(b); |
| 441 | renderHead(b); |
| 442 | } |
| 443 | |
| 444 | /** Starts boots up to `lanes` at a time, nearest to the viewport first. */ |
| 445 | function pump() { |
| 446 | if (queue.length > 1) { |
| 447 | const mid = scroller.scrollTop + scroller.clientHeight / 2; |
| 448 | const dist = (b: Bubble) => Math.abs(b.el.offsetTop + b.el.offsetHeight / 2 - mid); |
| 449 | queue.sort((a, b) => dist(a) - dist(b)); |
| 450 | } |
| 451 | while (booting < lanes && queue.length) { |
| 452 | const b = queue.shift()!; |
| 453 | if (b.near && !b.host && !b.killed) boot(b); |
| 454 | else b.state = b.killed ? 'stopped' : 'idle'; |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | function boot(b: Bubble) { |
| 459 | const html = htmls.get(b.file); |
| 460 | if (html === undefined) { b.state = 'idle'; return; } |
| 461 | const gen = generation; |
| 462 | b.state = 'booting'; |
| 463 | b.boots++; |
| 464 | b.createdAt = now(); |
| 465 | b.loadedAt = b.contentAt = 0; |
| 466 | b.shownSampled = false; |
| 467 | b.sized = false; |
| 468 | // On screen already (the first screen, a renderer switch): the reader has been looking at it since now; otherwise the visible observer sets it. |
| 469 | b.shownAt = b.visible ? b.createdAt : 0; |
| 470 | b.poolOn = !!pool; |
| 471 | b.renderer = renderer; |
| 472 | b.blocked = 0; b.throttled = 0; b.timerLimit = false; b.heap = 0; b.deadReason = null; b.lastError = null; |
| 473 | b.wrap.replaceChildren(); |
| 474 | b.wrap.classList.add('booting'); |
| 475 | b.wrap.dataset.ms = '0 ms'; |
| 476 | b.wrap.style.minHeight = (b.height || 72) + 'px'; |
| 477 | const col = b.poolOn ? samples.on : samples.off; |
| 478 | if (pool && pool.warm === 0) col.misses++; |
| 479 | const rec: BootRecord = { |
| 480 | idx: b.idx, file: b.file, renderer, poolOn: b.poolOn, poolHit: !!pool && pool.warm > 0, cold: records.length === 0, |
| 481 | createdAt: b.createdAt, hostCreateMs: 0, rendererCreateMs: 0, rendererReadyMs: null, contentMs: null, loadedMs: null, |
| 482 | shownAt: b.shownAt, blankMs: 0, dead: null, |
| 483 | }; |
| 484 | b.rec = rec; |
| 485 | b.blankSince = b.visible ? b.createdAt : 0; |
| 486 | records.push(rec); |
| 487 | booting++; |
| 488 | startBootTicker(); |
| 489 | let released = false; |
| 490 | const release = () => { if (!released) { released = true; booting--; pump(); } }; |
| 491 | const timeout = setTimeout(release, 20_000); |
| 492 | const content = () => { |
| 493 | if (b.contentAt || gen !== generation) return; |
| 494 | b.contentAt = now(); |
| 495 | b.state = 'live'; |
| 496 | booted++; |
| 497 | b.wrap.classList.remove('booting'); |
| 498 | b.wrap.style.minHeight = ''; |
| 499 | col.boot.push(b.contentAt - b.createdAt); |
| 500 | rec.contentMs = b.contentAt - b.createdAt; |
| 501 | stopBlank(b); |
| 502 | trySampleShown(b); |
| 503 | renderHead(b); |
| 504 | }; |
| 505 | const t0 = now(); |
| 506 | b.host = new WidgetHost(b.wrap, html, { |
| 507 | policy: WIDGET_POLICY, |
| 508 | features: WIDGET_FEATURES, |
| 509 | theme, |
| 510 | rendererFactory: timedFactory(FACTORIES[renderer], rec), |
| 511 | workerPool: pool ?? undefined, |
| 512 | visible: b.visible, |
| 513 | // corpus/safe-area: messages with no caption below the widget, the client's time over their corner. |
| 514 | ...(corpus === 'safe-area' ? { contentSafeArea: referenceSafeArea() } : {}), |
| 515 | bubbleGestures: bubbleGesturesOption(gestures), |
| 516 | onBubbleGesture: (g) => { if (b.wrap.parentElement) showBubbleGesture(b.wrap.parentElement, g); }, |
| 517 | onLoaded: () => { |
| 518 | if (gen !== generation) return; |
| 519 | b.loadedAt = now(); |
| 520 | col.loaded.push(b.loadedAt - b.createdAt); |
| 521 | rec.loadedMs = b.loadedAt - b.createdAt; |
| 522 | clearTimeout(timeout); |
| 523 | release(); |
| 524 | // Content that arrived before `loaded` (the first size report) was already counted; a widget with no size report yet gets it on the next one. |
| 525 | if (b.sized && b.height > MIN_HEIGHT) content(); |
| 526 | renderHead(b); |
| 527 | }, |
| 528 | onResize: (h, anchor) => { |
| 529 | if (gen !== generation) return; |
| 530 | b.height = h; |
| 531 | b.anchor = anchor; |
| 532 | b.sized = true; |
| 533 | // The first size report of an empty document is exactly MIN_HEIGHT; content is anything taller, or any report after the scripts ran. |
| 534 | if (!b.contentAt && (b.loadedAt || h > MIN_HEIGHT)) content(); |
| 535 | }, |
| 536 | onDead: (reason) => { |
| 537 | if (gen !== generation) return; |
| 538 | b.state = 'dead'; |
| 539 | b.killed = true; |
| 540 | b.deadReason = reason; |
| 541 | rec.dead = reason; |
| 542 | stopBlank(b); |
| 543 | b.wrap.classList.remove('booting'); |
| 544 | b.wrap.style.minHeight = ''; |
| 545 | clearTimeout(timeout); |
| 546 | release(); |
| 547 | renderHead(b); |
| 548 | renderFoot(b); |
| 549 | }, |
| 550 | onError: (text) => { b.lastError = text; renderFoot(b); }, |
| 551 | onDiag: (kind) => { |
| 552 | if (kind.endsWith('-blocked')) b.blocked++; |
| 553 | else if (kind === 'cpu-throttled') b.throttled++; |
| 554 | else if (kind.startsWith('timer-limit')) b.timerLimit = true; |
| 555 | else return; |
| 556 | renderHead(b); |
| 557 | }, |
| 558 | onStats: (s) => { b.heap = s.memoryBytes; }, |
| 559 | }); |
| 560 | rec.hostCreateMs = now() - t0; |
| 561 | renderHead(b); |
| 562 | } |
| 563 | |
| 564 | /** Closes the bubble's current blank stretch (content arrived, it left the viewport, the host is dropped). */ |
| 565 | function stopBlank(b: Bubble) { |
| 566 | if (b.rec && b.blankSince) b.rec.blankMs += now() - b.blankSince; |
| 567 | b.blankSince = 0; |
| 568 | } |
| 569 | |
| 570 | /** Wraps a renderer factory so the record gets the renderer's synchronous creation cost and its creation → first message time. */ |
| 571 | function timedFactory(factory: RendererFactory, rec: BootRecord): RendererFactory { |
| 572 | return (container, t) => { |
| 573 | const t0 = now(); |
| 574 | const inner = factory(container, t); |
| 575 | rec.rendererCreateMs = now() - t0; |
| 576 | const wrapper: Renderer = { |
| 577 | element: inner.element, |
| 578 | cssScope: inner.cssScope, |
| 579 | onMessage: null, |
| 580 | onDiag: null, |
| 581 | load() { const l0 = now(); inner.load(); rec.rendererCreateMs += now() - l0; }, |
| 582 | send: (m) => inner.send(m), |
| 583 | setTheme: (th) => inner.setTheme(th), |
| 584 | destroy: () => inner.destroy(), |
| 585 | }; |
| 586 | inner.onMessage = (m) => { |
| 587 | if (rec.rendererReadyMs === null) rec.rendererReadyMs = now() - t0; |
| 588 | wrapper.onMessage?.(m); |
| 589 | }; |
| 590 | inner.onDiag = (k, d) => wrapper.onDiag?.(k, d); |
| 591 | return wrapper; |
| 592 | }; |
| 593 | } |
| 594 | |
| 595 | function trySampleShown(b: Bubble) { |
| 596 | if (b.shownSampled || !b.contentAt || !b.shownAt || b.state === 'parked') return; |
| 597 | b.shownSampled = true; |
| 598 | (b.poolOn ? samples.on : samples.off).shown.push(b.contentAt - b.shownAt); |
| 599 | } |
| 600 | |
| 601 | /** The bubble is screens away: drop the host, keep the height (a product would keep a snapshot too). */ |
| 602 | function park(b: Bubble) { |
| 603 | stopBlank(b); |
| 604 | b.rec = null; |
| 605 | b.host?.destroy(); |
| 606 | b.host = null; |
| 607 | b.state = 'parked'; |
| 608 | b.shownSampled = false; |
| 609 | b.shownAt = 0; |
| 610 | const ph = document.createElement('div'); |
| 611 | ph.className = 'feed-parked'; |
| 612 | ph.style.height = (b.height || 72) + 'px'; |
| 613 | ph.textContent = 'parked — host dropped, height remembered'; |
| 614 | b.wrap.replaceChildren(ph); |
| 615 | b.wrap.classList.remove('booting'); |
| 616 | renderHead(b); |
| 617 | } |
| 618 | |
| 619 | /** A killed widget after its host is gone (renderer switch / reset): a product shows the frozen fallback, we show the stop line. */ |
| 620 | function stopped(b: Bubble) { |
| 621 | stopBlank(b); |
| 622 | b.rec = null; |
| 623 | b.host?.destroy(); |
| 624 | b.host = null; |
| 625 | b.state = 'stopped'; |
| 626 | const ph = document.createElement('div'); |
| 627 | ph.className = 'feed-parked feed-stopped'; |
| 628 | ph.style.height = (b.height || 72) + 'px'; |
| 629 | ph.textContent = 'Widget stopped'; |
| 630 | b.wrap.replaceChildren(ph); |
| 631 | b.wrap.classList.remove('booting'); |
| 632 | renderHead(b); |
| 633 | renderFoot(b); |
| 634 | } |
| 635 | |
| 636 | // ───────────── bubble chrome ───────────── |
| 637 | |
| 638 | function renderHead(b: Bubble) { |
| 639 | const parts = [`#${b.idx + 1}`, b.file]; |
| 640 | if (b.hostile) parts.push('⚠ hostile'); |
| 641 | if (b.state === 'queued') parts.push('queued'); |
| 642 | else if (b.state === 'booting') parts.push(`booting (${b.renderer}${b.poolOn ? ', pooled' : ', cold'})`); |
| 643 | else if (b.state === 'parked') parts.push(`parked · booted ${b.boots}×`); |
| 644 | else if (b.state === 'stopped') parts.push('stopped'); |
| 645 | else if (b.contentAt) parts.push(`${b.renderer}${b.poolOn ? ' · pooled' : ' · cold'} · content in ${(b.contentAt - b |
| 646 | if (b.blocked) parts.push(`blocked ×${b.blocked}`); |
| 647 | if (b.throttled) parts.push(`CPU deferred ×${b.throttled}`); |
| 648 | if (b.timerLimit) parts.push('timers capped'); |
| 649 | if (b.state === 'dead') parts.push('✖ stopped'); |
| 650 | b.head.textContent = parts.join(' · '); |
| 651 | b.el.classList.toggle('dead', b.state === 'dead' || b.state === 'stopped'); |
| 652 | } |
| 653 | function renderFoot(b: Bubble) { |
| 654 | const line = b.deadReason ? `Widget stopped: ${b.deadReason.split('\n')[0]}` : b.lastError ? b.lastError.split(' |
| 655 | b.foot.textContent = line; |
| 656 | b.foot.classList.toggle('hidden', !line); |
| 657 | } |
| 658 | |
| 659 | function makeBubble(idx: number, file: string, isHostile: boolean): Bubble { |
| 660 | const el = document.createElement('div'); |
| 661 | el.className = 'feed-bubble widget'; |
| 662 | const head = document.createElement('div'); |
| 663 | head.className = 'bubble-head'; |
| 664 | const bubble = document.createElement('div'); |
| 665 | bubble.className = 'bubble'; // the widget's canvas: no padding, the radius clips (style.css) |
| 666 | const wrap = document.createElement('div'); |
| 667 | wrap.className = 'frame-wrap feed-wrap'; |
| 668 | bubble.appendChild(wrap); |
| 669 | if (corpus === 'safe-area') { |
| 670 | // The client's time over a widget with no caption below it: a view over the widget, its taps the client's. |
| 671 | const time = document.createElement('div'); |
| 672 | time.setAttribute('style', timeCornerStyle(referenceSafeArea())); |
| 673 | time.textContent = REFERENCE_TIME_LABEL; |
| 674 | bubble.appendChild(time); |
| 675 | } |
| 676 | const foot = document.createElement('div'); |
| 677 | foot.className = 'feed-foot hidden'; |
| 678 | el.append(head, bubble, foot); |
| 679 | const b: Bubble = { |
| 680 | idx, file, hostile: isHostile, el, head, wrap, foot, host: null, state: 'idle', near: false, visible: false, height: 0, anchor: DEFAULT_RESIZE_ANCHOR, laidOut: 0, |
| 681 | createdAt: 0, loadedAt: 0, contentAt: 0, shownAt: 0, shownSampled: false, sized: false, poolOn: false, renderer, boots: 0, |
| 682 | blocked: 0, throttled: 0, timerLimit: false, heap: 0, deadReason: null, killed: false, lastError: null, rec: null, blankSince: 0, |
| 683 | }; |
| 684 | renderHead(b); |
| 685 | return b; |
| 686 | } |
| 687 | function makeText(i: number): HTMLElement { |
| 688 | const el = document.createElement('div'); |
| 689 | el.className = 'feed-bubble text' + (i % 3 === 1 ? ' out' : ''); |
| 690 | const bubble = document.createElement('div'); |
| 691 | bubble.className = 'bubble'; |
| 692 | bubble.textContent = TEXTS[i % TEXTS.length]; |
| 693 | el.appendChild(bubble); |
| 694 | return el; |
| 695 | } |
| 696 | |
| 697 | // ───────────── building the feed ───────────── |
| 698 | |
| 699 | let files: string[] = []; |
| 700 | async function fetchHtml(file: string) { |
| 701 | if (htmls.has(file)) return; |
| 702 | const res = await fetch('/corpus/' + file); |
| 703 | if (!res.ok) throw new Error('no such corpus file: ' + file); |
| 704 | htmls.set(file, await res.text()); |
| 705 | } |
| 706 | |
| 707 | async function build() { |
| 708 | const gen = ++generation; |
| 709 | if (!files.length) { |
| 710 | const all: string[] = await (await fetch('/api/corpus')).json(); |
| 711 | files = all.filter((f) => f.startsWith(`${corpus}/`)); |
| 712 | } |
| 713 | // One of each batch in turn (travel, commerce, life, work, travel, … — or cards, interactive, live, heavy for `common`), each batch in a seeded order: a mixed feed that starts light. |
| 714 | const batches = BATCH_ORDER[corpus].map((g, i) => shuffled(files.filter((f) => f.startsWith(`${corpus}/${g |
| 715 | const order: string[] = []; |
| 716 | for (let i = 0; order.length < files.length; i++) for (const b of batches) if (i < b.length) order. |
| 717 | const plan: { file: string; hostile: boolean }[] = []; |
| 718 | for (let i = 0; i < count; i++) plan.push({ file: order[i % order.length], hostile: false }); |
| 719 | if (hostile !== 'none' && count > HOSTILE_INDEX) plan[HOSTILE_INDEX] = { file: `attacks/${hostile}.html`, hostile: true }; |
| 720 | await Promise.all([...new Set(plan.map((p) => p.file))].map(fetchHtml)); |
| 721 | if (gen !== generation) return; |
| 722 | bubbles = plan.map((p, i) => makeBubble(i, p.file, p.hostile)); |
| 723 | const frag = document.createDocumentFragment(); |
| 724 | bubbles.forEach((b, i) => { |
| 725 | if (i % 2 === 0) frag.appendChild(makeText(i)); |
| 726 | frag.appendChild(b.el); |
| 727 | byEl.set(b.el, b); |
| 728 | }); |
| 729 | column.replaceChildren(frag); |
| 730 | for (const b of bubbles) { ioNear.observe(b.el); ioVisible.observe(b.el); ioFar.observe(b.el); anchorObserver.observe(b.el); } |
| 731 | } |
| 732 | |
| 733 | function teardown() { |
| 734 | generation++; |
| 735 | ioNear.disconnect(); ioVisible.disconnect(); ioFar.disconnect(); anchorObserver.disconnect(); |
| 736 | for (const b of bubbles) { stopBlank(b); b.rec = null; b.host?.destroy(); } |
| 737 | bubbles = []; |
| 738 | byEl.clear(); |
| 739 | queue.length = 0; |
| 740 | booting = 0; |
| 741 | booted = 0; |
| 742 | column.replaceChildren(); |
| 743 | } |
| 744 | |
| 745 | function clear() { |
| 746 | stop(); |
| 747 | teardown(); |
| 748 | samples = { on: newSamples(), off: newSamples() }; |
| 749 | records = []; |
| 750 | scrollDeltas.length = 0; |
| 751 | scroller.scrollTop = 0; |
| 752 | renderOverlay(); |
| 753 | } |
| 754 | |
| 755 | async function reset() { |
| 756 | clear(); |
| 757 | await build(); |
| 758 | syncUrl(); |
| 759 | renderOverlay(); |
| 760 | } |
| 761 | |
| 762 | // ───────────── the switches ───────────── |
| 763 | |
| 764 | function setRenderer(kind: FeedRenderer) { |
| 765 | if (kind === renderer) return; |
| 766 | renderer = kind; |
| 767 | for (const i of rendererInputs) i.checked = i.value === kind; |
| 768 | // Every live bubble swaps its renderer in place: the same HTML boots again behind the new seam; the height is remembered so nothing jumps. |
| 769 | for (const b of bubbles) { |
| 770 | if (b.state === 'queued') { b.state = 'idle'; } |
| 771 | if (!b.host) continue; |
| 772 | if (b.killed) { stopped(b); continue; } |
| 773 | stopBlank(b); |
| 774 | b.rec = null; |
| 775 | b.host.destroy(); |
| 776 | b.host = null; |
| 777 | b.state = 'idle'; |
| 778 | b.shownSampled = false; |
| 779 | b.shownAt = 0; |
| 780 | } |
| 781 | queue.length = 0; |
| 782 | booting = 0; |
| 783 | for (const b of bubbles) if (b.near && !b.killed) enqueue(b); |
| 784 | pump(); |
| 785 | syncUrl(); |
| 786 | renderOverlay(); |
| 787 | } |
| 788 | |
| 789 | function setPool(on: boolean) { |
| 790 | poolOn = on; |
| 791 | poolInput.checked = on; |
| 792 | if (on && !pool) { |
| 793 | pool = new WorkerPool(poolSize); |
| 794 | void pool.prewarm().then(renderOverlay); |
| 795 | } else if (!on && pool) { |
| 796 | pool.destroy(); |
| 797 | pool = null; |
| 798 | } |
| 799 | syncUrl(); |
| 800 | renderOverlay(); |
| 801 | } |
| 802 | |
| 803 | function setHostile(name: string, rebuild = true) { |
| 804 | hostile = HOSTILE.find((h) => h.name === name)?.name ?? 'none'; |
| 805 | hostileSelect.value = hostile; |
| 806 | if (rebuild) void reset(); |
| 807 | } |
| 808 | |
| 809 | function setCorpus(kind: FeedCorpus, rebuild = true) { |
| 810 | const next = CORPORA.find((c) => c.kind === kind)?.kind ?? 'showcase'; |
| 811 | if (next !== corpus) files = []; |
| 812 | corpus = next; |
| 813 | corpusSelect.value = corpus; |
| 814 | corpusSelect.title = CORPORA.find((c) => c.kind === corpus)!.title; |
| 815 | if (rebuild) void reset(); |
| 816 | } |
| 817 | |
| 818 | function setCount(n: number, rebuild = true) { |
| 819 | count = Math.min(200, Math.max(1, Math.round(n) || 72)); |
| 820 | countInput.value = String(count); |
| 821 | if (rebuild) void reset(); |
| 822 | } |
| 823 | |
| 824 | function quiet(on: boolean) { |
| 825 | quietMode = on; |
| 826 | if (!on) { renderOverlay(); void measureMemoryInto(); } |
| 827 | } |
| 828 | |
| 829 | function setTheme(t: 'light' | 'dark') { |
| 830 | theme = t; |
| 831 | for (const b of bubbles) b.host?.setTheme(t); |
| 832 | syncUrl(); |
| 833 | } |
| 834 | function setGestures(mode: GestureMode) { |
| 835 | gestures = mode; |
| 836 | for (const b of bubbles) b.host?.setBubbleGestures(bubbleGesturesOption(mode)); |
| 837 | syncUrl(); |
| 838 | } |
| 839 | |
| 840 | function syncUrl() { |
| 841 | const p = new URLSearchParams(); |
| 842 | p.set('feed', '1'); |
| 843 | if (theme === 'dark') p.set('theme', 'dark'); |
| 844 | if (gestures !== 'phone') p.set('gestures', gestures); |
| 845 | if (corpus !== 'showcase') p.set('corpus', corpus); |
| 846 | if (renderer !== 'iframe') p.set('renderer', renderer); |
| 847 | if (!poolOn) p.set('pool', '0'); |
| 848 | if (poolSize !== 6) p.set('poolSize', String(poolSize)); |
| 849 | if (hostile !== 'fallback-at-boot') p.set('hostile', hostile); |
| 850 | if (count !== 72) p.set('count', String(count)); |
| 851 | for (const k of ['lanes', 'ahead', 'keep', 'canary'] as const) if (params.has(k)) p.set(k, params.get(k)!); |
| 852 | history.replaceState(null, '', '?' + p.toString()); |
| 853 | } |
| 854 | |
| 855 | // ───────────── scripted scroll ───────────── |
| 856 | |
| 857 | let autoRunning = false; |
| 858 | let autoGen = 0; |
| 859 | async function autoScroll() { |
| 860 | if (autoRunning) return; |
| 861 | autoRunning = true; |
| 862 | const gen = ++autoGen; |
| 863 | scrollBtn.textContent = '■ stop'; |
| 864 | let dir = 1; |
| 865 | while (autoRunning && gen === autoGen) { |
| 866 | scroller.scrollBy({ top: dir * scroller.clientHeight * 0.9, behavior: 'smooth' }); |
| 867 | await sleep(900); |
| 868 | const atBottom = scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 2; |
| 869 | if (dir > 0 && atBottom) dir = -1; |
| 870 | else if (dir < 0 && scroller.scrollTop <= 1) break; |
| 871 | } |
| 872 | if (gen === autoGen) stop(); |
| 873 | } |
| 874 | function stop() { |
| 875 | autoRunning = false; |
| 876 | autoGen++; |
| 877 | scrollBtn.textContent = '▶ auto-scroll'; |
| 878 | } |
| 879 | |
| 880 | // ───────────── metrics ───────────── |
| 881 | |
| 882 | /** Frame intervals while the feed scrolls (the last ~3 s of scrolling). */ |
| 883 | const scrollDeltas: number[] = []; |
| 884 | let measuring = false; |
| 885 | let scrollUntil = 0; |
| 886 | scroller.addEventListener('scroll', () => { |
| 887 | scrollUntil = now() + 400; |
| 888 | if (measuring) return; |
| 889 | measuring = true; |
| 890 | let last = now(); |
| 891 | const tick = (t: number) => { |
| 892 | scrollDeltas.push(t - last); |
| 893 | last = t; |
| 894 | if (scrollDeltas.length > 180) scrollDeltas.splice(0, scrollDeltas.length - 180); |
| 895 | if (now() < scrollUntil) requestAnimationFrame(tick); else measuring = false; |
| 896 | }; |
| 897 | requestAnimationFrame(tick); |
| 898 | }, { passive: true }); |
| 899 | |
| 900 | // The booting placeholders count the milliseconds the reader waits (a frame loop only while something boots). |
| 901 | let bootTicker = false; |
| 902 | function startBootTicker() { |
| 903 | if (bootTicker) return; |
| 904 | bootTicker = true; |
| 905 | const tick = () => { |
| 906 | let any = false; |
| 907 | for (const b of bubbles) if (b.state === 'booting') { any = true; b.wrap.dataset.ms = `${(now() - b.createdAt). |
| 908 | if (any) requestAnimationFrame(tick); else bootTicker = false; |
| 909 | }; |
| 910 | requestAnimationFrame(tick); |
| 911 | } |
| 912 | |
| 913 | const memory: FeedSummary['memory'] = { total: null, workers: null, frames: null, heaps: 0, source: '' }; |
| 914 | let measuringMemory = false; |
| 915 | /** The overlay's memory line (feed-bench.ts's `measureMemory` does the reading; the bench calls it itself, on its own clock). */ |
| 916 | async function measureMemoryInto() { |
| 917 | if (measuringMemory) return; |
| 918 | measuringMemory = true; |
| 919 | const m: MemorySample = await measureMemory(); |
| 920 | Object.assign(memory, { total: m.total, workers: m.workers, frames: m.frames, source: m.source }); |
| 921 | memory.heaps = bubbles.reduce((a, b) => a + (b.host ? b.heap : 0), 0); |
| 922 | measuringMemory = false; |
| 923 | } |
| 924 | setInterval(() => { if (!quietMode) void measureMemoryInto(); }, 4000); |
| 925 | void measureMemoryInto(); |
| 926 | |
| 927 | // The canary of the attack suite (tests/canary-server.ts, `corepack pnpm canary`): every hostile widget points at it. |
| 928 | const canary: FeedSummary['canary'] = { state: 'unknown', hits: 0 }; |
| 929 | async function pollCanary() { |
| 930 | try { |
| 931 | const hits = (await (await fetch('http://127.0.0.1:9999/__hits', { cache: 'no-store' })).json()) as unknown[]; |
| 932 | canary.state = 'ok'; |
| 933 | canary.hits = hits.length; |
| 934 | } catch { |
| 935 | canary.state = 'off'; |
| 936 | } |
| 937 | } |
| 938 | const canaryTimer = setInterval(() => { if (canary.state !== 'off' && !quietMode) void pollCanary(); }, 3000); |
| 939 | void pollCanary().then(() => { if (canary.state === 'off') clearInterval(canaryTimer); }); |
| 940 | |
| 941 | function summary(): FeedSummary { |
| 942 | return { |
| 943 | corpus, |
| 944 | renderer, |
| 945 | pool: pool ? { size: pool.size, warm: pool.warm, ...pool.stats } : null, |
| 946 | count: bubbles.length, |
| 947 | live: bubbles.filter((b) => b.host).length, |
| 948 | booted, |
| 949 | booting, |
| 950 | parked: bubbles.filter((b) => b.state === 'parked').length, |
| 951 | dead: bubbles.filter((b) => b.state === 'dead' || b.state === 'stopped').length, |
| 952 | samples, |
| 953 | memory: { ...memory }, |
| 954 | canary: { ...canary }, |
| 955 | blocked: bubbles.reduce((a, b) => a + b.blocked, 0), |
| 956 | scroll: { p95: quantile(scrollDeltas, 0.95), slow: scrollDeltas.filter((d) => d > 32).length, frames: scrollDeltas.length }, |
| 957 | }; |
| 958 | } |
| 959 | |
| 960 | function renderOverlay() { |
| 961 | const s = summary(); |
| 962 | const line = (text: string, cls = '') => { const d = document.createElement('div'); d.textContent = |
| 963 | const table = document.createElement('table'); |
| 964 | const row = (cells: string[], head = false) => { |
| 965 | const tr = document.createElement('tr'); |
| 966 | for (const c of cells) { const td = document.createElement(head ? 'th' : 'td'); td.textContent = c; tr.appendChild(td); } |
| 967 | table.appendChild(tr); |
| 968 | }; |
| 969 | const on = s.samples.on, off = s.samples.off; |
| 970 | row(['', 'pool on', 'pool off'], true); |
| 971 | row(['bubbles booted', String(on.boot.length), String(off.boot.length)]); |
| 972 | row(['create → content, median', fmtMs(quantile(on.boot, 0.5)), fmtMs(quantile(off.boot, 0.5))]); |
| 973 | row(['create → content, p90', fmtMs(quantile(on.boot, 0.9)), fmtMs(quantile(off.boot, 0.9))]); |
| 974 | row(['shown → content, median', fmtMs(quantile(on.shown, 0.5)), fmtMs(quantile(off.shown, 0.5))]); |
| 975 | row(['shown → content, p90', fmtMs(quantile(on.shown, 0.9)), fmtMs(quantile(off.shown, 0.9))]); |
| 976 | row(['pool empty when taken', String(on.misses), '—']); |
| 977 | const poolText = s.pool ? `pool ${s.pool.size}: ${s.pool.warm} warm · hits ${s.pool.hits} · misses ${s.pool |
| 978 | const mem = s.memory.total === null |
| 979 | ? `memory ${s.memory.source || 'n/a'}` |
| 980 | : `memory ${fmtMb(s.memory.total)}${s.memory.workers !== null ? ` (workers ${fmtMb(s.memory |
| 981 | const canaryText = s.canary.state === 'ok' ? `canary 127.0.0.1:9999: ${s.canary.hits} hits` : s.canary.state === 'off' ? 'canary not running (corepack pnpm canary)' |
| 982 | overlay.replaceChildren( |
| 983 | line(`corpus/${s.corpus} · ${s.renderer} renderer · ${s.count} bubbles · ${s.live} live · ${s.booting} booting · ${s.parked} parked · ${s. |
| 984 | line(poolText, s.pool ? 'ok' : 'warn'), |
| 985 | table, |
| 986 | line('negative shown → content: the widget was ready before the bubble scrolled in', 'muted'), |
| 987 | line(mem), |
| 988 | line(`${canaryText} · blocked by validator/shim ×${s.blocked}`, s.canary.hits ? 'bad' : s.blocked || s.dead ? 'ok' : ''), |
| 989 | line(s.scroll.frames ? `scroll frames: p95 ${s.scroll.p95.toFixed(0)} ms, ${s.scroll.slow}/${s.scroll.frames} over 32 ms` |
| 990 | ); |
| 991 | } |
| 992 | setInterval(() => { if (!quietMode) renderOverlay(); }, 250); |
| 993 | |
| 994 | // ───────────── go ───────────── |
| 995 | |
| 996 | if (poolOn) { pool = new WorkerPool(poolSize); void pool.prewarm().then(renderOverlay); } |
| 997 | void build().then(() => { syncUrl(); renderOverlay(); }); |
| 998 | |
| 999 | const api: FeedApi = { |
| 1000 | setTheme, setGestures, setRenderer, setPool, setHostile, setCorpus, setCount, reset, clear, autoScroll, stop, quiet, setKeep, scroller, |
| 1001 | get summary() { return summary(); }, |
| 1002 | get bubbles() { return bubbles; }, |
| 1003 | get pool() { return pool; }, |
| 1004 | get records() { return records; }, |
| 1005 | get settings() { return { corpus, renderer, poolOn, poolSize, hostile, count, lanes, ahead, keep, theme }; }, |
| 1006 | get viewport() { return { width: scroller.clientWidth, height: scroller.clientHeight }; }, |
| 1007 | bench: null as unknown as BenchApi, |
| 1008 | }; |
| 1009 | api.bench = startBench(benchPanel, api, { |
| 1010 | renderers: RENDERERS.map((r) => r.kind), |
| 1011 | params, |
| 1012 | onOpen: () => { benchPanel.classList.remove('hidden'); benchBtn.classList.add('on'); }, |
| 1013 | }); |
| 1014 | return api; |
| 1015 | } |
| 1016 | |