| 1 | // Web runner of the conformance set: every widget of packages/conformance on the |
| 2 | // web dev app (apps/web) through the real pipeline (QuickJS worker → validator |
| 3 | // → renderer), on each renderer: iframe and shadow (Shadow DOM, the web product |
| 4 | // renderer); the frozen blitz and litehtml prototypes (wasm) only when named in |
| 5 |
| 6 | // - reads the result from the validated ops: it taps the renderer's `send` |
| 7 | // and keeps the last `data-conformance` attribute set on the element the |
| 8 | // `el` op adopted as <html> (what any host can do with its own ops); |
| 9 | // - performs the widget's scripted actions (taps, drags, hover, theme) at the |
| 10 | // target rects the widget published, then waits for the result again; |
| 11 | // - screenshots the bubble at DPR 2, crops each stage of the auto set and |
| 12 | // diffs it against the Chromium/WebKit references; |
| 13 | // - checks the host-side expectations (bridge calls, height). |
| 14 | // Output: reports/conformance/<renderer>/<widget>.json (+ stage crops and diffs) |
| 15 | // and the per-renderer report reports/conformance/<renderer>.json; report.ts |
| 16 | // writes the run files, packages/conformance/tools/report.mjs judges them (the |
| 17 | // same tool every client runs on its own run files). |
| 18 | // |
| 19 | // Needs the dev server of this checkout: corepack pnpm dev --port 5175 |
| 20 | // corepack pnpm tsx scripts/conformance/run-web.ts --origin http://127.0.0.1:5175 \ |
| 21 | // [--renderers iframe,shadow] [--set auto,visual] [--only 03-layout-a] \ |
| 22 | // [--themes light,dark] [--widths 390] [--features webAnimations] [--policy strict] |
| 23 |
| 24 | import { execSync } from 'node:child_process'; |
| 25 | import fs from 'node:fs'; |
| 26 | import path from 'node:path'; |
| 27 | import { chromium, type Page } from '@playwright/test'; |
| 28 | import { PNG } from 'pngjs'; |
| 29 | import { ROOT, autoStagePos, crop, judgeStage, listWidgets, perform, refPath, type Published, type Widget } from './lib'; |
| 30 |
| 31 | const args = process.argv.slice(2); |
| 32 | const opt = (name: string, def?: string) => (args.includes('--' + name) ? args[args.indexOf('--' + name) + 1] : def); |
| 33 | const ORIGIN = opt('origin', `http://127.0.0.1:${process.env.TW_PORT ?? 5175}`)!; |
| 34 | const RENDERERS = opt('renderers', 'iframe,shadow')!.split(','); |
| 35 | const SETS = opt('set', 'auto,visual')!.split(','); |
| 36 | const THEMES = opt('themes'); |
| 37 | const WIDTHS = opt('widths', '390')!.split(',').map(Number); |
| 38 | const FEATURES = opt('features', 'webAnimations')!; |
| 39 | const POLICY = opt('policy', 'strict')!; |
| 40 | const ONLY = opt('only'); |
| 41 | const DPR = 2; |
| 42 | const OUT = path.join(ROOT, 'reports', 'conformance'); |
| 43 |
| 44 | /** One run in the run-file format of packages/conformance/run.schema.json (plus a few web-only extras). */ |
| 45 | export interface WidgetRun { |
| 46 | id: string; set: string; renderer: string; theme: string; width: number; |
| 47 | loaded: boolean; dead: string | null; status: string; ms: number; |
| 48 | checks: [string, string, string, string][]; |
| 49 | /** Stage crops (paths relative to the run file); report.mjs judges them against the references. */ |
| 50 | stages: { name: string; crop: string }[]; |
| 51 | /** What the host saw, for the manifest's host checks. */ |
| 52 | observed: { bridge: { method: string; args: unknown[] }[]; height: number; chatFocused: boolean; focusHolder: string; syntheticInput: boolean }; |
| 53 | /** Indices into the manifest's actions that this renderer could not deliver. */ |
| 54 | skippedActions: number[]; |
| 55 | errors: string[]; diags: Record<string, number>; |
| 56 | /** Stage rects as the widget measured them in this renderer (CSS px). */ |
| 57 | stageRects?: Record<string, number[]>; |
| 58 | } |
| 59 |
| 60 | const commit = () => { try { return execSync('git rev-parse --short HEAD', { cwd: ROOT }).toString().trim(); } catch { return ''; } }; |
| 61 | const canvasRenderer = (r: string) => r === 'blitz' || r === 'litehtml'; |
| 62 |
| 63 | async function setup(page: Page, renderer: string, theme: string) { |
| 64 | const q = new URLSearchParams({ theme, features: FEATURES, policy: POLICY }); |
| 65 | if (renderer !== 'iframe') q.set(renderer, '1'); |
| 66 | await page.goto(`${ORIGIN}/?${q}`); |
| 67 | await page.waitForFunction(() => !!(window as any).__tw, null, { timeout: 30_000 }); |
| 68 | } |
| 69 |
| 70 | /** Load the widget into the dev app and tap the renderer's ops for the result attribute. */ |
| 71 | async function load(page: Page, w: Widget, width: number) { |
| 72 | await page.evaluate(({ html, name, width, message, safeArea }) => { |
| 73 | const wrap = document.querySelector('#sandbox-wrap') as HTMLElement; |
| 74 | const chat = wrap.closest('.chat') as HTMLElement; |
| 75 | const bubble = wrap.closest('.bubble') as HTMLElement; |
| 76 | chat.style.width = width + 'px'; |
| 77 | bubble.style.padding = '0'; |
| 78 | bubble.style.borderRadius = '0'; |
| 79 | bubble.style.boxShadow = 'none'; |
| 80 | // A stand-in for the chat's input field, focused while the widget boots (host check `focus: 'chat'`). |
| 81 | let chatInput = document.getElementById('conf-chat-input') as HTMLInputElement | null; |
| 82 | if (!chatInput) { |
| 83 | chatInput = document.createElement('input'); |
| 84 | chatInput.id = 'conf-chat-input'; |
| 85 | chatInput.placeholder = 'chat input'; |
| 86 | chatInput.style.cssText = 'position:fixed;left:8px;bottom:8px;width:200px;z-index:10'; |
| 87 | document.body.appendChild(chatInput); |
| 88 | } |
| 89 | chatInput.focus(); |
| 90 | const tw = (window as any).__tw; |
| 91 | const conf: any = ((window as any).__conf = { html: null as number | null, attr: null as string | null, ops: 0 }); |
| 92 | // The message context of the header's first message spec (lib.ts MessageSpec) as the mock bot's: the kind (and so |
| 93 | // the server's flags) and the state the test bot sends with; the private chat with no state otherwise. |
| 94 | Object.assign(tw.bot.context, { message: message?.kind ?? 'private', chatType: null, viewer: 1001 }); |
| 95 | tw.bot.edit(name, { chatData: message?.chat_data ?? null, publicData: message?.public_data ?? null }); |
| 96 | // The header's content safe area (lib.ts WidgetMeta.safeArea): the time over the corner, as a client without a caption draws it. |
| 97 | tw.setSafeArea(safeArea); |
| 98 | tw.load(html, name); |
| 99 | tw.host.element.setAttribute('data-conf-el', ''); |
| 100 | const r = tw.host.renderer; |
| 101 | const send = r.send.bind(r); |
| 102 | r.send = (m: any) => { |
| 103 | if (m && m.type === 'ops') { |
| 104 | for (const op of m.ops) { |
| 105 | conf.ops++; |
| 106 | if (op.op === 'el' && op.adopt === 'html') { |
| 107 | conf.html = op.id; |
| 108 | for (const [n, v] of op.attrs) if (n === 'data-conformance') conf.attr = v; |
| 109 | } else if (op.op === 'attr' && op.id === conf.html && op.name === 'data-conformance') conf.attr = op.value; |
| 110 | } |
| 111 | } |
| 112 | return send(m); |
| 113 | }; |
| 114 | }, { html: w.html, name: `conformance/${w.id}.html`, width, message: w.meta.message?.[0] ?? null, safeArea: w.meta.safeArea ?? null }); |
| 115 | } |
| 116 |
| 117 | async function published(page: Page): Promise<Published | null> { |
| 118 | return page.evaluate(() => { const a = (window as any).__conf?.attr; try { return a ? JSON.parse(a) : null; } catch { return null; } }); |
| 119 | } |
| 120 |
| 121 | async function waitStatus(page: Page, want: string[], timeout: number): Promise<Published | null> { |
| 122 | const t0 = Date.now(); |
| 123 | let last: Published | null = null; |
| 124 | while (Date.now() - t0 < timeout) { |
| 125 | last = await published(page); |
| 126 | if (last && want.includes(last.status)) return last; |
| 127 | const dead = await page.evaluate(() => (window as any).__tw.state.dead); |
| 128 | if (dead) return last; |
| 129 | await page.waitForTimeout(100); |
| 130 | } |
| 131 | return last; |
| 132 | } |
| 133 |
| 134 | async function runWidget(page: Page, w: Widget, renderer: string, theme: 'light' | 'dark', width: number): Promise<WidgetRun> { |
| 135 | const t0 = Date.now(); |
| 136 | await load(page, w, width); |
| 137 | await page.waitForFunction(() => { const s = (window as any).__tw.state; return s.loaded || s.dead; }, null, { timeout: 60_000 }).catch(() => {}); |
| 138 | let pub = await waitStatus(page, ['done', 'awaiting'], 20_000); |
| 139 | // Before any input: does the chat input still have the focus? |
| 140 | const chatFocused = await page.evaluate(() => document.activeElement?.id === 'conf-chat-input'); |
| 141 | const focusHolder = await page.evaluate(() => { const a = document.activeElement; return a ? a.tagName.toLowerCase() + (a.id ? '#' + a.id : '') + (a.className && typeof a.className === 'string' ? '.' + a.className.split(' ')[0] : '') : 'none'; }); |
| 142 | let skippedNames: string[] = []; |
| 143 | let skippedActions: number[] = []; |
| 144 | if (w.meta.actions?.length && pub) { |
| 145 | const wrap = page.locator('[data-conf-el]'); |
| 146 | ({ skipped: skippedNames, indices: skippedActions } = await perform(page, w.meta.actions, { |
| 147 | origin: async () => { const b = await wrap.boundingBox(); return { x: b?.x ?? 0, y: b?.y ?? 0 }; }, |
| 148 | setTheme: async (t) => { await page.evaluate((t) => (window as any).__tw.setTheme(t), t); }, |
| 149 | setVisible: async (v) => { await page.evaluate((v) => (window as any).__tw.setVisible(v), v); }, |
| 150 | tapOnly: canvasRenderer(renderer) ? async (x, y) => { await page.evaluate(([x, y]) => (window as any).__tw.tap(x, y), [x, y]); } : undefined, |
| 151 | }, () => published(page))); |
| 152 | pub = await waitStatus(page, ['done'], skippedNames.length ? 3_000 : 10_000); |
| 153 | } |
| 154 | // Raw checks: report.mjs skips the ones fed by skippedActions (input this renderer cannot receive). |
| 155 | const checks = pub?.checks ?? []; |
| 156 | if (canvasRenderer(renderer)) await page.waitForFunction((r) => ((window as any).__tw[r]?.paints ?? 0) > 0, renderer, { timeout: 15_000 }).catch(() => {}); |
| 157 | await page.waitForTimeout(250); |
| 158 | const state = await page.evaluate(() => { const s = (window as any).__tw.state; return { loaded: s.loaded, dead: s.dead, diags: s.diags, logs: s.logs, bridge: s.bridge, height: s.height }; }); |
| 159 |
| 160 | const dir = path.join(OUT, renderer, w.set); |
| 161 | fs.mkdirSync(dir, { recursive: true }); |
| 162 | const tag = `${w.stem}.${theme}.${width}`; |
| 163 | fs.mkdirSync(path.dirname(path.join(dir, tag)), { recursive: true }); // grouped widgets (visual/sdk/…) |
| 164 | const stages: { name: string; crop: string }[] = []; |
| 165 | /** For the console only: the run file carries the crops, report.mjs judges them. */ |
| 166 | const preview: string[] = []; |
| 167 | if (w.set === 'auto' && w.stages.length) { |
| 168 | // The renderer element can sit at a fractional CSS position; its content is snapped to device pixels, |
| 169 | // an element screenshot is clipped at whole CSS pixels: crop from the viewport at the snapped origin. |
| 170 | const box = await page.locator('[data-conf-el]').boundingBox(); |
| 171 | const shot = PNG.sync.read(await page.screenshot({ animations: 'allow', caret: 'hide' })); |
| 172 | const ox = Math.round((box?.x ?? 0) * DPR), oy = Math.round((box?.y ?? 0) * DPR); |
| 173 | w.stages.forEach((s, i) => { |
| 174 | if (!s.themes.includes(theme)) return; |
| 175 | const pos = autoStagePos(i); |
| 176 | const got = crop(shot, pos[0], pos[1], s.w, s.h, DPR, ox, oy); |
| 177 | const file = path.join(dir, `${tag}.${s.name}.png`); |
| 178 | fs.writeFileSync(file, PNG.sync.write(got)); |
| 179 | stages.push({ name: s.name, crop: path.relative(OUT, file) }); |
| 180 | const refs = ['chromium', 'webkit'].map((engine) => ({ engine, file: refPath(w, s.name, engine, theme) })).filter((r) => fs.existsSync(r.file)).map((r) => ({ engine: r.engine, png: PNG.sync.read(fs.readFileSync(r.file)) })); |
| 181 | const j = judgeStage(got, refs, s); |
| 182 | preview.push(`${s.name} ${j.diff === null ? '?' : (j.diff * 100).toFixed(1) + '%'}${j.status === 'pass' ? '' : ' ' + j.status}`); |
| 183 | }); |
| 184 | } |
| 185 |
| 186 | const run: WidgetRun = { |
| 187 | id: w.id, set: w.set, renderer, theme, width, |
| 188 | loaded: !!state.loaded && !state.dead, dead: state.dead, status: pub?.status ?? 'no result', ms: Date.now() - t0, |
| 189 | checks, stages, skippedActions, |
| 190 | observed: { bridge: state.bridge, height: state.height, chatFocused, focusHolder, syntheticInput: canvasRenderer(renderer) }, |
| 191 | errors: (state.logs as { level: string; text: string }[]).filter((l) => l.level === 'error').map((l) => String(l.text).split('\n')[0].slice(0, 200)), |
| 192 | diags: Object.fromEntries(Object.entries(state.diags as Record<string, { count: number }>).map(([k, v]) => [k, v.count])), |
| 193 | stageRects: pub?.stages, |
| 194 | }; |
| 195 | fs.writeFileSync(path.join(dir, `${tag}.json`), JSON.stringify(run, null, 1)); |
| 196 | return Object.assign(run, { preview }); |
| 197 | } |
| 198 |
| 199 | async function main() { |
| 200 | const widgets = listWidgets(ONLY).filter((w) => SETS.includes(w.set)); |
| 201 | const browser = await chromium.launch(); |
| 202 | for (const renderer of RENDERERS) { |
| 203 | const ctx = await browser.newContext({ viewport: { width: 1400, height: 1100 }, deviceScaleFactor: DPR }); |
| 204 | const page = await ctx.newPage(); |
| 205 | const runs: WidgetRun[] = []; |
| 206 | // --themes widens the default; a widget that declares its themes (a scenario that starts in light) keeps to them. |
| 207 | const themes = (w: Widget) => (w.meta.themes ?? (THEMES ? THEMES.split(',') : w.stages.some((s) => s.themes.includes('dark')) ? ['light', 'dark'] : ['light'])) as ('light' | 'dark')[]; |
| 208 | let current = ''; |
| 209 | let available = true; |
| 210 | for (const w of widgets) { |
| 211 | for (const theme of themes(w)) { |
| 212 | for (const width of WIDTHS) { |
| 213 | if (current !== theme) { await setup(page, renderer, theme); current = theme; } |
| 214 | try { |
| 215 | const r = await runWidget(page, w, renderer, theme, width); |
| 216 | if (canvasRenderer(renderer) && r.diags[`${renderer}-init`] && !r.loaded) available = false; |
| 217 | const { preview: _p, ...entry } = r as WidgetRun & { preview: string[] }; |
| 218 | runs.push(entry); |
| 219 | const n = r.checks.reduce((m: Record<string, number>, c) => ({ ...m, [c[2]]: (m[c[2]] ?? 0) + 1 }), {}); |
| 220 | const st = (r as WidgetRun & { preview: string[] }).preview.join(', '); |
| 221 | console.log(`${renderer.padEnd(8)} ${w.id.padEnd(28)} ${theme.padEnd(5)} ${width} ${r.status.padEnd(8)} ${Object.entries(n).map(([k, v]) => `${k} ${v}`).join(' ')}${st ? ' | ' + st : ''}${r.dead ? ' DEAD ' + r.dead.slice(0, 80) : ''}${r.errors.length ? ` | ${r.errors.length} errors` : ''}`); |
| 222 | } catch (e) { |
| 223 | console.log(`${renderer} ${w.id} ${theme} ${width}: runner error ${(e as Error).message.split('\n')[0]}`); |
| 224 | current = ''; |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 | if (!available) { console.log(`${renderer}: not available (wasm not built?), skipping the rest`); break; } |
| 229 | } |
| 230 | fs.mkdirSync(OUT, { recursive: true }); |
| 231 | // A partial run (--only, --set) updates its entries and keeps the rest of the renderer's last run. |
| 232 | const prevFile = path.join(OUT, `${renderer}.json`); |
| 233 | if (fs.existsSync(prevFile)) { |
| 234 | const key = (r: WidgetRun) => `${r.id}|${r.theme}|${r.width}`; |
| 235 | const fresh = new Set(runs.map(key)); |
| 236 | const prev = (JSON.parse(fs.readFileSync(prevFile, 'utf8')).runs ?? []) as WidgetRun[]; |
| 237 | runs.unshift(...prev.filter((r) => !fresh.has(key(r)))); |
| 238 | runs.sort((a, b) => key(a).localeCompare(key(b))); |
| 239 | } |
| 240 | fs.writeFileSync(path.join(OUT, `${renderer}.json`), JSON.stringify({ renderer, platform: 'web', engine: `Chromium ${browser.version()} (headless, Playwright)`, framework: commit(), commit: commit(), origin: ORIGIN, features: FEATURES.split(',').filter(Boolean), policy: POLICY, date: new Date().toISOString(), runs }, null, 1)); |
| 241 | await ctx.close(); |
| 242 | } |
| 243 | await browser.close(); |
| 244 | } |
| 245 |
| 246 | main().catch((e) => { console.error(e); process.exit(1); }); |
| 247 |