From 9a61fc3e447a145adfaaa504773edfe7c192b18f Mon Sep 17 00:00:00 2001 From: Fledge Platform Dev-3 Date: Sat, 21 Nov 2026 05:35:24 +0000 Subject: [PATCH 1/4] ci(visual): cache the Chromium layer and refuse a short matrix (#787) --- .github/agent/action-allowlist.json | 1 + .github/workflows/ci.yml | 16 +++ docs/autonomous-dev.md | 7 +- scripts/visual-matrix.ts | 88 ++++++++++++++-- src/lib/visualMatrix.ts | 123 ++++++++++++++++++++++ test/visualJobCeiling.test.ts | 157 ++++++++++++++++++++++++++++ test/visualMatrix.test.ts | 94 ++++++++++++++++- 7 files changed, 478 insertions(+), 8 deletions(-) create mode 100644 test/visualJobCeiling.test.ts diff --git a/.github/agent/action-allowlist.json b/.github/agent/action-allowlist.json index 278f73e9..330a3603 100644 --- a/.github/agent/action-allowlist.json +++ b/.github/agent/action-allowlist.json @@ -1,6 +1,7 @@ { "allowed_actions": [ "actions/attest-build-provenance", + "actions/cache", "actions/checkout", "actions/dependency-review-action", "actions/download-artifact", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cfeafc58..77ff894e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -291,6 +291,22 @@ jobs: node-version: 22 cache: npm - run: npm ci --ignore-scripts + # #787: the Chromium download is the slow half of this job and it is the + # same archive until the Playwright version moves. The key names that + # version, so a bump misses the cache — a cold run — instead of launching + # a browser the lockfile no longer pins. There is deliberately no + # restore-key, for the same reason: an older Playwright's browser under a + # newer key is the wrong cache this card refuses. A hit skips the download + # only; the install step and the matrix below always run, so a cache hit + # never skips an assertion. + - name: Read the Playwright version + id: playwright + run: node -p "'version=' + require('playwright/package.json').version" >> "$GITHUB_OUTPUT" + - name: Cache the Playwright browser layer + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ~/.cache/ms-playwright + key: ${{ runner.os }}-playwright-${{ steps.playwright.outputs.version }} - run: npm run build - run: npx playwright install --with-deps chromium - run: npm run visual:matrix diff --git a/docs/autonomous-dev.md b/docs/autonomous-dev.md index 4e858db0..816a3813 100644 --- a/docs/autonomous-dev.md +++ b/docs/autonomous-dev.md @@ -293,7 +293,12 @@ renames it to `ci-ok-head`. See recorded in `package.json`; one execution per supported Node line, plus the changed-lines floor on the pull request diff) - `build` -- `visual` (the UI matrix, when the diff reaches a rendered surface) +- `visual` (the UI matrix, when the diff reaches a rendered surface; the + Chromium layer is cached under the installed Playwright version — a version + bump is a cold run — and the job summary names every page, viewport and + scheme with its own result. The run compares the cases it recorded against + the set the matrix promises, so a dropped page, or a case that reuses another + case's key and its screenshot, fails the job instead of shrinking the table) - `docker` (image builds, scans and starts) - `audit` (no high-severity advisory in either the runtime set or the full graph) - `changelog` (fragments are well formed) diff --git a/scripts/visual-matrix.ts b/scripts/visual-matrix.ts index d08d2430..0f55ed82 100644 --- a/scripts/visual-matrix.ts +++ b/scripts/visual-matrix.ts @@ -1,6 +1,6 @@ /// import { spawn } from 'node:child_process' -import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' +import { appendFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs' import { randomBytes } from 'node:crypto' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -9,18 +9,23 @@ import { chromium } from 'playwright' import { GATE_SCHEMES, GATE_WIDTHS, + VISUAL_LOCALES, VISUAL_NARROW_CASES, VISUAL_PATHS, VISUAL_WIDTHS, + caseCoverage, + caseKey, + expectedCaseKeys, focusFailures, leftoverFailures, nameFailures, overflowFailure, pageSlug, + summaryMarkdown, touchFailures, viewportHeight, } from '../src/lib/visualMatrix.js' -import type { FocusStyle } from '../src/lib/visualMatrix.js' +import type { FocusStyle, VisualCaseResult } from '../src/lib/visualMatrix.js' const root = fileURLToPath(new URL('..', import.meta.url)) const port = Number(process.env.VISUAL_PORT ?? '18180') @@ -28,6 +33,56 @@ const base = `http://127.0.0.1:${port}` const outDir = process.env.VISUAL_OUT ?? join(root, 'visual-matrix') const dataDir = mkdtempSync(join(tmpdir(), 'fledge-visual-')) const failures: string[] = [] +// #787: the same run also records one row per case, so the job summary names +// every page, viewport and scheme with its own result. +const cases: VisualCaseResult[] = [] +const recordedKeys = new Set() + +/** + * A case is whatever failures appeared while it ran: the counts are taken + * around the call, so the row cannot disagree with the list that decides the + * exit code. A case whose key is already recorded is a red run, not a second + * row: two cases that share a key write one screenshot, so one of them would + * pass on the other's picture. + */ +function record(locale: string, width: number, scheme: string, path: string, from: number): void { + const key = caseKey({ locale, width, scheme, path }) + if (recordedKeys.has(key)) { + failures.push(`visual matrix: case ${key} ran twice; its screenshot would overwrite another case's`) + return + } + recordedKeys.add(key) + cases.push({ locale, width, scheme, path, ok: failures.length === from, detail: failures.slice(from) }) +} + +/** + * What ran has to be what the matrix promised: a page, width or scheme missing + * from `cases` is a dropped case, and the job fails instead of publishing a + * shorter table that reads green. Checked before the exit code is decided. + */ +function checkCoverage(): void { + const coverage = caseCoverage(expectedCaseKeys(), [...recordedKeys]) + if (coverage.missing.length > 0) { + failures.push( + `visual matrix: ${String(coverage.missing.length)} promised case(s) never ran — a page, width or scheme was dropped: ${coverage.missing.slice(0, 3).join(', ')}`, + ) + } + if (coverage.duplicated.length > 0) { + failures.push(`visual matrix: case key reused, so one case overwrote another: ${coverage.duplicated.slice(0, 3).join(', ')}`) + } + if (coverage.unexpected.length > 0) { + failures.push( + `visual matrix: ${String(coverage.unexpected.length)} case(s) ran outside the promised set: ${coverage.unexpected.slice(0, 3).join(', ')}`, + ) + } +} + +/** The summary a reader opens from the run page; absent outside Actions. */ +function writeStepSummary(): void { + const target = process.env.GITHUB_STEP_SUMMARY + if (target === undefined || target === '') return + appendFileSync(target, summaryMarkdown(cases)) +} // `/` is captured signed out above; every other path needs the development login. const SIGNED_IN_PATHS = VISUAL_PATHS.filter((path) => path !== '/') @@ -202,7 +257,7 @@ async function main(): Promise { try { await waitForServer() browser = await chromium.launch() - for (const locale of ['zh', 'en'] as const) { + for (const locale of VISUAL_LOCALES) { mkdirSync(join(outDir, locale), { recursive: true }) // The landing page only exists for a signed-out visitor: src/app.ts answers // `/` with a 302 to /dashboard once a session exists, so signing in first @@ -215,11 +270,13 @@ async function main(): Promise { await guestPage.goto(`${base}/lang/${locale}?next=/`, { waitUntil: 'domcontentloaded' }) for (const width of VISUAL_WIDTHS) { await guestPage.setViewportSize({ width, height: viewportHeight(width) }) + const from = failures.length try { await checkPage(guestPage, locale, width, '/') } catch (error) { failures.push(`${locale} ${width}px /: ${error instanceof Error ? error.message : String(error)}`) } + record(locale, width, 'host', '/', from) } await guest.close() @@ -233,11 +290,13 @@ async function main(): Promise { for (const width of VISUAL_WIDTHS) { await page.setViewportSize({ width, height: viewportHeight(width) }) for (const path of SIGNED_IN_PATHS) { + const from = failures.length try { await checkPage(page, locale, width, path) } catch (error) { failures.push(`${locale} ${width}px ${path}: ${error instanceof Error ? error.message : String(error)}`) } + record(locale, width, 'host', path, from) } } // #950: a page whose narrowest layout needs a width below the sweep is @@ -245,21 +304,28 @@ async function main(): Promise { // clean run because the width was never rendered. for (const narrow of VISUAL_NARROW_CASES) { await page.setViewportSize({ width: narrow.width, height: viewportHeight(narrow.width) }) + const from = failures.length try { await checkPage(page, locale, narrow.width, narrow.path) } catch (error) { failures.push(`${locale} ${narrow.width}px ${narrow.path}: ${error instanceof Error ? error.message : String(error)}`) } + record(locale, narrow.width, 'host', narrow.path, from) } await context.close() // #870: the measured gate runs after the screenshot sweep, so a screenshot // failure and a gate failure are still one job with one list. await runGatePass(browser, locale) } + // After both locales: what ran has to equal what the matrix promised. + checkCoverage() } finally { await browser?.close() await stopServer(child) rmSync(dataDir, { recursive: true, force: true }) + // Written before the exit code is decided, so a red run still tells the + // reader which page, viewport and scheme failed. + writeStepSummary() } if (failures.length > 0) { console.error(`visual matrix: ${failures.length} failure(s)`) @@ -267,8 +333,8 @@ async function main(): Promise { process.exitCode = 1 return } - console.log(`visual matrix: ${VISUAL_PATHS.length} pages x ${VISUAL_WIDTHS.length} widths x 2 locales + ${String(VISUAL_NARROW_CASES.length)} narrow case(s) clean`) - console.log(`visual gate: ${VISUAL_PATHS.length} pages x ${GATE_WIDTHS.length} widths x ${GATE_SCHEMES.length} schemes x 2 locales, touch/focus/name/leftover clean`) + console.log(`visual matrix: ${VISUAL_PATHS.length} pages x ${VISUAL_WIDTHS.length} widths x ${String(VISUAL_LOCALES.length)} locales + ${String(VISUAL_NARROW_CASES.length)} narrow case(s) clean`) + console.log(`visual gate: ${VISUAL_PATHS.length} pages x ${GATE_WIDTHS.length} widths x ${GATE_SCHEMES.length} schemes x ${String(VISUAL_LOCALES.length)} locales, touch/focus/name/leftover clean`) console.log(`screenshots: ${outDir}`) } @@ -455,11 +521,13 @@ async function runGatePass(browser: import('playwright').Browser, locale: string // `/` answers 302 to /dashboard once a session exists; the guest // context below is the only place it can be measured. if (path === '/') continue + const from = failures.length try { await checkGatePage(page, locale, width, scheme, path) } catch (error) { failures.push(`${locale} width=${String(width)} scheme=${scheme} ${path}: ${error instanceof Error ? error.message : String(error)}`) } + record(locale, width, scheme, path, from) } } finally { await signedIn.close() @@ -473,16 +541,24 @@ async function runGatePass(browser: import('playwright').Browser, locale: string try { const page = await guest.newPage() await page.goto(`${base}/lang/${locale}?next=/`, { waitUntil: 'domcontentloaded' }) + const from = failures.length try { await checkGatePage(page, locale, width, scheme, '/') } catch (error) { failures.push(`${locale} width=${String(width)} scheme=${scheme} /: ${error instanceof Error ? error.message : String(error)}`) } + record(locale, width, scheme, '/', from) } finally { await guest.close() } } - await checkExplicitTheme(browser, locale, width) + const from = failures.length + try { + await checkExplicitTheme(browser, locale, width) + } catch (error) { + failures.push(`${locale} width=${String(width)} scheme=explicit-dark /dashboard: ${error instanceof Error ? error.message : String(error)}`) + } + record(locale, width, 'explicit-dark', '/dashboard', from) } } diff --git a/src/lib/visualMatrix.ts b/src/lib/visualMatrix.ts index 244bae1a..083eab98 100644 --- a/src/lib/visualMatrix.ts +++ b/src/lib/visualMatrix.ts @@ -211,3 +211,126 @@ export function leftoverFailures(html: string): string[] { (leftover) => `rendered HTML contains raw template leftover ${leftover}`, ) } + +/** + * #787: one row per measured case. The runner writes this table to + * `GITHUB_STEP_SUMMARY`, so a red job names the page, viewport and scheme that + * failed instead of one line for a whole matrix. `scheme` is `host` for the + * screenshot sweep, which uses the runner's own preference, and the palette name + * for the measured gate. + */ +export interface VisualCaseResult { + readonly locale: string + readonly width: number + readonly scheme: string + readonly path: string + readonly ok: boolean + /** Every failure this case produced, in the order they were recorded. */ + readonly detail: readonly string[] +} + +/** A cell is safe to interpolate: a reason can carry a `|` of its own. */ +function cell(value: string): string { + return value.split('|').join('\\|') +} + +/** + * The summary is the record of what ran, so it lists every case — a failure + * keeps its reasons and a pass is still a row. A cache hit cannot produce a + * green row: the row is written from the assertions this process ran. + */ +export function summaryMarkdown(rows: readonly VisualCaseResult[]): string { + const passed = rows.filter((row) => row.ok).length + const lines = [ + `visual matrix: ${String(passed)}/${String(rows.length)} case(s) passed`, + '', + '| locale | viewport | scheme | page | result |', + '| --- | --- | --- | --- | --- |', + ] + for (const row of rows) { + const result = row.ok ? 'pass' : `fail: ${row.detail.join('; ')}` + lines.push( + `| ${cell(row.locale)} | ${String(row.width)}px | ${cell(row.scheme)} | \`${cell(row.path)}\` | ${cell(result)} |`, + ) + } + return `${lines.join('\n')}\n` +} + +/** The two locales every matrix runs; the promised set and the loops share it. */ +export const VISUAL_LOCALES = ['zh', 'en'] as const + +export type VisualLocale = (typeof VISUAL_LOCALES)[number] + +/** The coordinates that name one measured case. */ +export interface VisualCaseCoordinates { + readonly locale: string + readonly width: number + readonly scheme: string + readonly path: string +} + +/** + * One case, one key. A duplicate key means one case ran twice or one case was + * recorded under another page's identity, and its screenshot (`-.png`) + * would overwrite the other case's file — a dropped page hiding behind a picture + * that is still there. + */ +export function caseKey(coordinates: VisualCaseCoordinates): string { + return `${coordinates.locale}|${String(coordinates.width)}|${coordinates.scheme}|${coordinates.path}` +} + +/** + * Every case the runner promises to run, built from the same constants the + * runner loops over. The runner compares this set against the cases it recorded, + * so a page or viewport removed from a loop is a red job, not a shorter summary. + * `host` is the screenshot sweep's own colour preference; `explicit-dark` is the + * theme the runner pins through the page. + */ +export function expectedCaseKeys(locales: readonly string[] = VISUAL_LOCALES): string[] { + const keys: string[] = [] + const signedIn = VISUAL_PATHS.filter((path) => path !== '/') + for (const locale of locales) { + for (const width of VISUAL_WIDTHS) { + keys.push(caseKey({ locale, width, scheme: 'host', path: '/' })) + for (const path of signedIn) keys.push(caseKey({ locale, width, scheme: 'host', path })) + } + for (const narrow of VISUAL_NARROW_CASES) { + keys.push(caseKey({ locale, width: narrow.width, scheme: 'host', path: narrow.path })) + } + for (const width of GATE_WIDTHS) { + for (const scheme of GATE_SCHEMES) { + keys.push(caseKey({ locale, width, scheme, path: '/' })) + for (const path of signedIn) keys.push(caseKey({ locale, width, scheme, path })) + } + keys.push(caseKey({ locale, width, scheme: 'explicit-dark', path: '/dashboard' })) + } + } + return keys +} + +export interface CaseCoverage { + /** Promised cases that never ran: a page, width or scheme was dropped. */ + readonly missing: readonly string[] + /** Keys recorded more than once: the later case overwrote the earlier cell. */ + readonly duplicated: readonly string[] + /** Cases outside the promised set: the matrix ran something it does not name. */ + readonly unexpected: readonly string[] +} + +/** Compares what ran against what the matrix promised, without trusting order. */ +export function caseCoverage(expected: readonly string[], recorded: readonly string[]): CaseCoverage { + const expectedSet = new Set(expected) + const seen = new Set() + const duplicated: string[] = [] + for (const key of recorded) { + if (seen.has(key)) { + if (!duplicated.includes(key)) duplicated.push(key) + } + seen.add(key) + } + return { + missing: expected.filter((key) => !seen.has(key)), + duplicated, + unexpected: [...seen].filter((key) => !expectedSet.has(key)), + } +} diff --git a/test/visualJobCeiling.test.ts b/test/visualJobCeiling.test.ts new file mode 100644 index 00000000..3ae78668 --- /dev/null +++ b/test/visualJobCeiling.test.ts @@ -0,0 +1,157 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { test } from 'node:test' +import { fileURLToPath } from 'node:url' + +// #787: the visual job's cost is a property of the workflow, not of a page, so +// this suite reads the workflow and the runner as text. It loads on the base +// tree (nothing here is imported from a module the fix adds) and every +// assertion below fails there: there is no browser cache, and the runner writes +// no job summary. + +const root = fileURLToPath(new URL('..', import.meta.url)) + +function read(path: string): string { + return readFileSync(join(root, path), 'utf8') +} + +function visualJob(): string { + const text = read('.github/workflows/ci.yml') + const start = text.indexOf('\n visual:\n') + assert.notEqual(start, -1, 'ci.yml has no visual job') + const end = text.indexOf('\n docker:\n', start) + assert.ok(end > start, 'the visual job is not followed by the docker job') + return text.slice(start, end) +} + +test('the visual job restores the browser layer under the Playwright version', () => { + const job = visualJob() + assert.match(job, /uses: actions\/cache@[0-9a-f]{40}/, 'the visual job does not use actions/cache') + assert.match(job, /path: ~\/\.cache\/ms-playwright/, 'the cache does not cover the Playwright browser directory') + assert.match( + job, + /key: \$\{\{ runner\.os \}\}-playwright-\$\{\{ steps\.playwright\.outputs\.version \}\}/, + 'the cache key does not name the Playwright version', + ) + assert.match( + job, + /require\('playwright\/package\.json'\)\.version/, + 'the version in the cache key does not come from the installed Playwright', + ) +}) + +test('a Playwright bump is a cold run rather than a reused browser', () => { + const job = visualJob() + assert.doesNotMatch(job, /restore-keys:/, 'a restore-key would hand a new Playwright an older browser') +}) + +test('a cache hit cannot skip the matrix', () => { + const job = visualJob() + assert.match(job, /\n {6}- run: npx playwright install --with-deps chromium\n/, 'the install step is missing or guarded') + assert.match(job, /\n {6}- run: npm run visual:matrix\n/, 'the matrix step is missing or guarded') +}) + +test('the runner publishes one row per case to the job summary', () => { + const runner = read('scripts/visual-matrix.ts') + assert.match(runner, /GITHUB_STEP_SUMMARY/, 'the runner never reads GITHUB_STEP_SUMMARY') + assert.match(runner, /appendFileSync\(target, summaryMarkdown\(cases\)\)/, 'the runner does not append the case table') + assert.match(runner, /process\.exitCode = 1/, 'a failure no longer sets a red exit code') +}) + +test('the summary names the page, viewport and scheme of every case', async () => { + const lib = (await import('../src/lib/visualMatrix.js')) as unknown as { + summaryMarkdown?: (rows: readonly { + locale: string + width: number + scheme: string + path: string + ok: boolean + detail: readonly string[] + }[]) => string + } + const formatter = lib.summaryMarkdown + assert.ok(formatter !== undefined, 'summaryMarkdown is not exported') + const out = formatter([ + { locale: 'en', width: 360, scheme: 'dark', path: '/settings', ok: true, detail: [] }, + { + locale: 'zh', + width: 768, + scheme: 'light', + path: '/dashboard', + ok: false, + detail: ['button[name] is 39px tall'], + }, + ]) + assert.match(out, /^visual matrix: 1\/2 case\(s\) passed$/m) + assert.match(out, /^\| locale \| viewport \| scheme \| page \| result \|$/m) + assert.match(out, /^\| en \| 360px \| dark \| `\/settings` \| pass \|$/m) + assert.match(out, /^\| zh \| 768px \| light \| `\/dashboard` \| fail: button\[name\] is 39px tall \|$/m) +}) + +test('a reason with a pipe cannot break the table', async () => { + const lib = (await import('../src/lib/visualMatrix.js')) as unknown as { + summaryMarkdown?: (rows: readonly { + locale: string + width: number + scheme: string + path: string + ok: boolean + detail: readonly string[] + }[]) => string + } + const formatter = lib.summaryMarkdown + assert.ok(formatter !== undefined, 'summaryMarkdown is not exported') + const out = formatter([ + { locale: 'en', width: 1280, scheme: 'host', path: '/', ok: false, detail: ['a | b'] }, + ]) + assert.match(out, /a \\\| b/, 'a pipe in a reason is not escaped') +}) + +// The cache is worth a shortcut only if a red cell still reaches the required +// check. Three negatives, as the card asks: a broken cell is red, a stale cache +// cannot green a failed cell, and a dropped page or a reused baseline key cannot +// pass. The first two are properties of the workflow and the runner below; the +// third is pinned as pure functions in `test/visualMatrix.test.ts`. +test('a broken cell reaches the required check instead of stopping at the job', () => { + const job = visualJob() + assert.match(job, /\n {6}- run: npx playwright install --with-deps chromium\n/, 'the install step is missing') + assert.match(job, /\n {6}- run: npm run visual:matrix\n/, 'the matrix step is missing') + assert.doesNotMatch(job, /continue-on-error/, 'a failing matrix must not be allowed to finish green') + const runner = read('scripts/visual-matrix.ts') + assert.match(runner, /if \(failures\.length > 0\) \{/, 'the runner no longer checks its failure list') + assert.match(runner, /process\.exitCode = 1/, 'a failure no longer sets a red exit code') + const workflow = read('.github/workflows/ci.yml') + assert.match( + workflow, + /needs: \[ci-ok,[^\]]*\bvisual\b[^\]]*\]/, + 'the visual job is not in the aggregate ci-ok needs, so a red matrix would not fail the required check', + ) +}) + +test('a cache hit restores the browser directory and nothing that can green a cell', () => { + const job = visualJob() + const start = job.indexOf('uses: actions/cache@') + assert.notEqual(start, -1, 'the visual job does not use actions/cache') + const stepStart = job.lastIndexOf('\n - ', start) + const stepEnd = job.indexOf('\n - ', start) + assert.ok(stepStart !== -1 && stepEnd > stepStart, 'the cache step is not delimited') + const step = job.slice(stepStart, stepEnd) + const paths = [...step.matchAll(/^\s+path: (.+)$/gm)].map((match) => match[1]) + assert.deepEqual(paths, ['~/.cache/ms-playwright'], 'the cache restores more than the browser download') + // The row's result is taken from the assertions this process ran, so a hit + // cannot produce a green row for a cell that failed. + const runner = read('scripts/visual-matrix.ts') + assert.match(runner, /ok: failures\.length === from/, 'a row no longer takes its result from the failures it produced') + assert.match(runner, /detail: failures\.slice\(from\)/, 'a row no longer carries its own failures') +}) + +test('the runner compares what ran against the promised case set', () => { + const runner = read('scripts/visual-matrix.ts') + assert.match(runner, /function checkCoverage\(\): void \{/, 'the runner has no coverage check') + assert.match(runner, /caseCoverage\(expectedCaseKeys\(\), \[\.\.\.recordedKeys\]\)/, 'the coverage check does not compare against the promised set') + assert.match(runner, /promised case\(s\) never ran/, 'a dropped case does not name itself as a failure') + assert.match(runner, /case key reused/, 'a reused case key does not fail the run') + const workflow = read('.github/workflows/ci.yml') + assert.match(workflow, /actions\/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4\.3\.0/, 'the cache action is not pinned') +}) diff --git a/test/visualMatrix.test.ts b/test/visualMatrix.test.ts index 21aa7dbb..8f157831 100644 --- a/test/visualMatrix.test.ts +++ b/test/visualMatrix.test.ts @@ -2,7 +2,14 @@ import test from 'node:test' import assert from 'node:assert/strict' import { readFileSync } from 'node:fs' import * as visualMatrix from '../src/lib/visualMatrix.js' -import { VISUAL_PATHS, VISUAL_WIDTHS, overflowFailure, pageSlug, viewportHeight } from '../src/lib/visualMatrix.js' +import { + VISUAL_NARROW_CASES, + VISUAL_PATHS, + VISUAL_WIDTHS, + overflowFailure, + pageSlug, + viewportHeight, +} from '../src/lib/visualMatrix.js' test('the matrix covers phones, tablets and desktop widths', () => { assert.deepEqual([...VISUAL_WIDTHS], [360, 390, 430, 640, 768, 1024, 1280, 1440, 1920]) @@ -380,3 +387,88 @@ test('the doc names each limit the gate does not close', () => { assert.ok(section.includes(needle), `the measured-gate section has to name the limit: ${why}`) } }) + +// #787: a faster job is only worth it if a cheaper run cannot pass a page it +// never rendered. The promised case set is the contract: the runner compares it +// against the cases it recorded, so a page dropped from a loop is red, and a +// case that reuses another case's key is red too — two cases share one +// screenshot file (`-.png`), so the second would publish the first +// one's picture. Read through the module object like the gate above: this file +// must load on a tree that does not have these exports yet. +const coverageLib = visualMatrix as unknown as { + VISUAL_LOCALES?: readonly string[] + caseKey?: (coordinates: { locale: string; width: number; scheme: string; path: string }) => string + expectedCaseKeys?: (locales?: readonly string[]) => string[] + caseCoverage?: (expected: readonly string[], recorded: readonly string[]) => { + missing: readonly string[] + duplicated: readonly string[] + unexpected: readonly string[] + } +} + +function promisedCases(): string[] { + assert.equal(typeof coverageLib.expectedCaseKeys, 'function', 'the runner needs a promised case set') + const keys = coverageLib.expectedCaseKeys?.() ?? [] + assert.ok(keys.length > 0, 'the promised case set is empty') + return keys +} + +test('the promised case set names every page of the sweep and of the gate', () => { + const keys = promisedCases() + const locales = coverageLib.VISUAL_LOCALES ?? [] + assert.deepEqual([...locales], ['zh', 'en']) + const perLocale = VISUAL_WIDTHS.length * VISUAL_PATHS.length + + VISUAL_NARROW_CASES.length + + (gate.GATE_WIDTHS?.length ?? 0) * (gate.GATE_SCHEMES?.length ?? 0) * VISUAL_PATHS.length + + (gate.GATE_WIDTHS?.length ?? 0) + assert.equal(keys.length, perLocale * locales.length, 'a promised case is missing from the set') + assert.equal(new Set(keys).size, keys.length, 'two promised cases share a key') + for (const locale of locales) { + for (const path of VISUAL_PATHS) { + assert.ok(keys.includes(`${locale}|360|host|${path}`), `the sweep does not promise ${locale} 360px ${path}`) + assert.ok(keys.includes(`${locale}|1280|light|${path}`), `the gate does not promise ${locale} 1280px light ${path}`) + assert.ok(keys.includes(`${locale}|1280|dark|${path}`), `the gate does not promise ${locale} 1280px dark ${path}`) + } + for (const width of gate.GATE_WIDTHS ?? []) { + assert.ok( + keys.includes(`${locale}|${width}|explicit-dark|/dashboard`), + `the pinned-dark check does not promise ${locale} ${width}px /dashboard`, + ) + } + } +}) + +test('a dropped page reads as a missing case, not a shorter clean run', () => { + const expected = promisedCases() + const lib = coverageLib + assert.equal(typeof lib.caseCoverage, 'function', 'the runner needs a coverage check') + const recorded = expected.filter((key) => key !== 'en|1280|light|/admin') + const coverage = lib.caseCoverage?.(expected, recorded) ?? { missing: [], duplicated: [], unexpected: [] } + assert.deepEqual([...coverage.missing], ['en|1280|light|/admin'], 'a page that never ran has to be named') + assert.deepEqual([...coverage.duplicated], []) + assert.deepEqual([...coverage.unexpected], []) +}) + +test('a case reusing another page key is caught, and the drop behind it stays visible', () => { + const expected = promisedCases() + // The scenario the card names: the admin cell never ran and its slot was + // filled by a second settings row. The summary would still hold one row per + // slot; only the key can tell the two apart. + const recorded = expected + .filter((key) => key !== 'zh|360|dark|/admin') + .concat(['zh|360|dark|/settings']) + const coverage = coverageLib.caseCoverage?.(expected, recorded) + ?? { missing: [], duplicated: [], unexpected: [] } + assert.deepEqual([...coverage.missing], ['zh|360|dark|/admin'], 'the page that never ran is still missing') + assert.deepEqual([...coverage.duplicated], ['zh|360|dark|/settings'], 'the reused key is a duplicate') + assert.equal(coverage.duplicated.length > 0 && coverage.missing.length > 0, true, 'a reused key cannot paper over a dropped page') +}) + +test('a case outside the promised set is unexpected, not silently accepted', () => { + const expected = promisedCases() + const recorded = expected.concat(['en|360|host|/not-a-page']) + const coverage = coverageLib.caseCoverage?.(expected, recorded) + ?? { missing: [], duplicated: [], unexpected: [] } + assert.deepEqual([...coverage.unexpected], ['en|360|host|/not-a-page']) + assert.deepEqual([...coverage.missing], []) +}) From a3b637df6ef5c8ac570792ffc0830473387a25cc Mon Sep 17 00:00:00 2001 From: Fledge Platform Dev-3 Date: Mon, 23 Nov 2026 01:08:10 +0000 Subject: [PATCH 2/4] ci(visual): drop the browser cache from the #787 slice (#787) ADR 0027 settled the pre-approved-action route, so the `actions/cache` half of this card belongs to #1206 and is parked there. This removes the Cache step, the version-reading step it keyed on, the allowlist entry that admitted the action, and the cache claim in the job's doc bullet. No step the matrix depends on is touched. --- .github/agent/action-allowlist.json | 1 - .github/workflows/ci.yml | 16 ---------------- docs/autonomous-dev.md | 11 +++++------ 3 files changed, 5 insertions(+), 23 deletions(-) diff --git a/.github/agent/action-allowlist.json b/.github/agent/action-allowlist.json index 330a3603..278f73e9 100644 --- a/.github/agent/action-allowlist.json +++ b/.github/agent/action-allowlist.json @@ -1,7 +1,6 @@ { "allowed_actions": [ "actions/attest-build-provenance", - "actions/cache", "actions/checkout", "actions/dependency-review-action", "actions/download-artifact", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 77ff894e..cfeafc58 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -291,22 +291,6 @@ jobs: node-version: 22 cache: npm - run: npm ci --ignore-scripts - # #787: the Chromium download is the slow half of this job and it is the - # same archive until the Playwright version moves. The key names that - # version, so a bump misses the cache — a cold run — instead of launching - # a browser the lockfile no longer pins. There is deliberately no - # restore-key, for the same reason: an older Playwright's browser under a - # newer key is the wrong cache this card refuses. A hit skips the download - # only; the install step and the matrix below always run, so a cache hit - # never skips an assertion. - - name: Read the Playwright version - id: playwright - run: node -p "'version=' + require('playwright/package.json').version" >> "$GITHUB_OUTPUT" - - name: Cache the Playwright browser layer - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 - with: - path: ~/.cache/ms-playwright - key: ${{ runner.os }}-playwright-${{ steps.playwright.outputs.version }} - run: npm run build - run: npx playwright install --with-deps chromium - run: npm run visual:matrix diff --git a/docs/autonomous-dev.md b/docs/autonomous-dev.md index 816a3813..787c9f82 100644 --- a/docs/autonomous-dev.md +++ b/docs/autonomous-dev.md @@ -293,12 +293,11 @@ renames it to `ci-ok-head`. See recorded in `package.json`; one execution per supported Node line, plus the changed-lines floor on the pull request diff) - `build` -- `visual` (the UI matrix, when the diff reaches a rendered surface; the - Chromium layer is cached under the installed Playwright version — a version - bump is a cold run — and the job summary names every page, viewport and - scheme with its own result. The run compares the cases it recorded against - the set the matrix promises, so a dropped page, or a case that reuses another - case's key and its screenshot, fails the job instead of shrinking the table) +- `visual` (the UI matrix, when the diff reaches a rendered surface; the job + summary names every page, viewport and scheme with its own result, and the + shard aggregate refuses a run that measured fewer cells than the matrix + promises, so a dropped page or a cell measured twice fails the job instead of + shrinking the table) - `docker` (image builds, scans and starts) - `audit` (no high-severity advisory in either the runtime set or the full graph) - `changelog` (fragments are well formed) From 75553f86c21275aedb22f1cd066181f10c08ed19 Mon Sep 17 00:00:00 2001 From: Fledge Platform Dev-3 Date: Mon, 23 Nov 2026 01:10:10 +0000 Subject: [PATCH 3/4] test(visual): the job summary names every cell, and a missing cell is not a pass (#787) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Red at a3b637df: 8 tests, 3 pass, 5 fail — the three workflow pins pass (the job keeps its name and its needs entry, a broken cell still reds, the aggregate still refuses an empty share, a missing result, a dropped cell and a duplicate). The five failures are the behaviour this card adds: no case table is written to GITHUB_STEP_SUMMARY, and `caseRows`/`summaryMarkdown` do not exist. --- test/visualJobCeiling.test.ts | 114 +++++++++++++++++++++++++++++++--- 1 file changed, 105 insertions(+), 9 deletions(-) diff --git a/test/visualJobCeiling.test.ts b/test/visualJobCeiling.test.ts index dbd86f3b..509c0149 100644 --- a/test/visualJobCeiling.test.ts +++ b/test/visualJobCeiling.test.ts @@ -4,10 +4,10 @@ import { join } from 'node:path' import { test } from 'node:test' import { fileURLToPath } from 'node:url' -// #787: the visual job's cost is a property of the workflow, not of a page, so -// this suite reads the workflow and the runner as text. #1208 sharded the sweep; -// #1214 is the tip this branch rebased onto, so the coverage half here is the -// shared aggregate guard that a shard cannot skip. +// #787: the visual job's cost and its reporting are properties of the workflow +// and the runner, not of a page, so this suite reads both as text. #1208 +// sharded the sweep, so the coverage half here is the shared aggregate guard +// and the summary is built from what the shares reported. const root = fileURLToPath(new URL('..', import.meta.url)) @@ -24,6 +24,36 @@ function visualJob(): string { return text.slice(start, end) } +const lib = (await import('../src/lib/visualMatrix.js')) as unknown as { + visualWorkload?: () => readonly ColumnCell[] + cellLabel?: (cell: ColumnCell) => string + caseRows?: (cells: readonly ColumnCell[], results: readonly (ShardResult | null)[]) => readonly Row[] + summaryMarkdown?: (rows: readonly Row[], notes?: readonly string[]) => string +} + +interface ColumnCell { + readonly kind: 'sweep' | 'narrow' | 'gate' | 'theme' + readonly locale: string + readonly width: number + readonly scheme?: string + readonly path: string +} + +interface ShardResult { + readonly share: number + readonly cells: readonly string[] + readonly failures: readonly string[] +} + +interface Row { + readonly locale: string + readonly width: number + readonly scheme: string + readonly path: string + readonly ok: boolean + readonly detail: readonly string[] +} + test('the visual job keeps its name and its place in the required set', () => { const workflow = read('.github/workflows/ci.yml') assert.match(workflow, /\n {2}visual:\n/, 'the visual job was renamed or removed') @@ -50,9 +80,75 @@ test('the aggregate refuses a matrix that would collapse coverage', () => { // depends on; the rule itself is unit-tested in `visualMatrixShards.test.ts`. const runner = read('scripts/visual-matrix.ts') assert.match(runner, /shardFailures\(/, 'the aggregate no longer uses the shared coverage guard') - const lib = read('src/lib/visualMatrix.ts') - assert.match(lib, /was assigned no cells/, 'an empty share no longer fails the run') - assert.match(lib, /reported no result/, 'a missing share result no longer fails the run') - assert.match(lib, /did not report/, 'a dropped cell no longer fails the run') - assert.match(lib, /was measured .* times/, 'a duplicated cell no longer fails the run') + const text = read('src/lib/visualMatrix.ts') + assert.match(text, /was assigned no cells/, 'an empty share no longer fails the run') + assert.match(text, /reported no result/, 'a missing share result no longer fails the run') + assert.match(text, /did not report/, 'a dropped cell no longer fails the run') + assert.match(text, /was measured .* times/, 'a duplicated cell no longer fails the run') +}) + +test('the coordinator publishes the case table to the job summary', () => { + const runner = read('scripts/visual-matrix.ts') + assert.match(runner, /GITHUB_STEP_SUMMARY/, 'the runner never reads GITHUB_STEP_SUMMARY') + assert.match(runner, /summaryMarkdown\(/, 'the runner does not build the case table') + assert.match(runner, /appendFileSync\(target, summaryMarkdown/, 'the runner does not append the case table') +}) + +test('the summary names the page, viewport and scheme of every case', () => { + const formatter = lib.summaryMarkdown + assert.ok(formatter !== undefined, 'summaryMarkdown is not exported') + const out = formatter!([ + { locale: 'en', width: 360, scheme: 'dark', path: '/settings', ok: true, detail: [] }, + { + locale: 'zh', + width: 768, + scheme: 'light', + path: '/dashboard', + ok: false, + detail: ['button[name] is 39px tall'], + }, + ]) + assert.match(out, /^visual matrix: 1\/2 case\(s\) passed$/m) + assert.match(out, /^\| locale \| viewport \| scheme \| page \| result \|$/m) + assert.match(out, /^\| en \| 360px \| dark \| `\/settings` \| pass \|$/m) + assert.match(out, /^\| zh \| 768px \| light \| `\/dashboard` \| fail: button\[name\] is 39px tall \|$/m) +}) + +test('a reason with a pipe cannot break the table', () => { + const formatter = lib.summaryMarkdown + assert.ok(formatter !== undefined, 'summaryMarkdown is not exported') + const out = formatter!([{ locale: 'en', width: 1280, scheme: 'host', path: '/', ok: false, detail: ['a | b'] }]) + assert.match(out, /a \\\| b/, 'a pipe in a reason is not escaped') +}) + +test('a cell no share reported reads as a failure in the table', () => { + const workload = lib.visualWorkload + const label = lib.cellLabel + const rowsOf = lib.caseRows + assert.ok(workload !== undefined && label !== undefined && rowsOf !== undefined, 'caseRows is not exported') + + const cells = workload!().slice(0, 2) + const measured = label!(cells[0]!) + const results: (ShardResult | null)[] = [ + { share: 1, cells: [measured], failures: [`${measured}: element outside the viewport`] }, + null, + ] + const rows = rowsOf!(cells, results) + assert.equal(rows.length, 2, 'the table has one row per promised cell') + assert.equal(rows[0]!.ok, false, 'a cell whose failure the share reported must read as a failure') + assert.deepEqual(rows[0]!.detail, ['element outside the viewport'], 'the reason keeps its text without the cell prefix') + assert.equal(rows[1]!.ok, false, 'a cell no share reported must not read as a pass') + assert.match(String(rows[1]!.detail[0]), /never measured|reported no result/, 'an unmeasured cell names why it is not verified') +}) + +test('the scheme column says which mode the cell was measured in', () => { + const workload = lib.visualWorkload + const rowsOf = lib.caseRows + assert.ok(workload !== undefined && rowsOf !== undefined, 'caseRows is not exported') + const all = workload!() + const rows = rowsOf!(all, []) + const schemes = new Set(rows.map((row) => row.scheme)) + assert.ok(schemes.has('host'), 'the sweep rows do not name the host colour scheme') + assert.ok(schemes.has('light') && schemes.has('dark'), 'the gate rows do not name their forced scheme') + assert.ok(schemes.has('explicit-dark'), 'the theme probe row does not name its scheme') }) From d00e65b0abacbacf972c075aeece52d7186b02a4 Mon Sep 17 00:00:00 2001 From: Fledge Platform Dev-3 Date: Mon, 23 Nov 2026 01:10:44 +0000 Subject: [PATCH 4/4] feat(visual): the job summary names every cell the matrix promised (#787) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `caseRows` turns the shares' reports into one row per promised cell — the scheme it ran in, its page and viewport, and the reasons it failed — and `summaryMarkdown` renders that table to GITHUB_STEP_SUMMARY from the coordinator, before the exit code is decided. A cell no share reported is a failure row, not a missing one, so a shrunken matrix cannot read green through the table. --- scripts/visual-matrix.ts | 24 +++++++++- src/lib/visualMatrix.ts | 100 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+), 1 deletion(-) diff --git a/scripts/visual-matrix.ts b/scripts/visual-matrix.ts index 7c7319f7..3133bc06 100644 --- a/scripts/visual-matrix.ts +++ b/scripts/visual-matrix.ts @@ -1,13 +1,14 @@ /// import { spawn } from 'node:child_process' import type { ChildProcess } from 'node:child_process' -import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { appendFileSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { randomBytes } from 'node:crypto' import { availableParallelism, tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { chromium } from 'playwright' import { + caseRows, cellLabel, focusFailures, leftoverFailures, @@ -16,6 +17,7 @@ import { pageSlug, partitionWorkload, shardFailures, + summaryMarkdown, touchFailures, viewportHeight, visualWorkload, @@ -538,6 +540,23 @@ function report(summary: string): void { process.exitCode = 1 } +/** The aggregate's reasons that belong to no single row: a share that died, a cell counted twice. */ +function aggregateNotes(problems: readonly string[], cells: readonly VisualCell[]): string[] { + const labels = cells.map((cell) => cellLabel(cell)) + return problems.filter((problem) => !labels.some((label) => problem.startsWith(`${label}: `))) +} + +/** The job summary is optional: a local run has no GITHUB_STEP_SUMMARY to append to. */ +function writeStepSummary(rows: readonly import('../src/lib/visualMatrix.js').VisualCaseResult[], notes: readonly string[]): void { + const target = process.env.GITHUB_STEP_SUMMARY + if (target === undefined || target === '') return + try { + appendFileSync(target, summaryMarkdown(rows, notes)) + } catch (error) { + console.error(`visual matrix: the job summary was not written: ${error instanceof Error ? error.message : String(error)}`) + } +} + async function runCoordinator(): Promise { const workload = visualWorkload() const shares = shardCount(workload.length) @@ -563,6 +582,9 @@ async function runCoordinator(): Promise { } }) failures.push(...problems) + // The table is written before the exit code is decided, so a red run still + // names every page, viewport and scheme instead of one line for the matrix. + writeStepSummary(caseRows(workload, results), aggregateNotes(problems, workload)) report(`${String(workload.length)} cell(s) over ${String(shares)} share(s)`) } diff --git a/src/lib/visualMatrix.ts b/src/lib/visualMatrix.ts index 836fff0d..bdaf6585 100644 --- a/src/lib/visualMatrix.ts +++ b/src/lib/visualMatrix.ts @@ -375,3 +375,103 @@ export function shardFailures( } return failures } + +/** + * One row of the job summary: a cell as a reader sees it, with the mode it was + * measured in and every reason it failed. The row is derived from what the + * shares reported, so a cell that never ran cannot appear as a pass. + */ +export interface VisualCaseResult { + readonly locale: string + readonly width: number + readonly scheme: string + readonly path: string + readonly ok: boolean + readonly detail: readonly string[] +} + +/** The scheme a cell is measured in: the sweep takes the host's, the gate forces one. */ +function caseScheme(cell: VisualCell): string { + switch (cell.kind) { + case 'gate': + return cell.scheme + case 'theme': + return 'explicit-dark' + default: + return 'host' + } +} + +/** + * The rows behind the summary, one per promised cell in workload order. A cell + * is a pass only when a share reported measuring it and no failure carries its + * label; a cell no share reported reads as a failure naming that, so a share + * that skipped work shrinks nothing. + */ +export function caseRows( + cells: readonly VisualCell[], + results: readonly (VisualShardResult | null)[], +): VisualCaseResult[] { + const labels = new Map(cells.map((cell) => [cellLabel(cell), cell])) + const reported = new Set() + const reasons = new Map() + for (const result of results) { + for (const label of result?.cells ?? []) reported.add(label) + for (const failure of result?.failures ?? []) { + for (const [label] of labels) { + const prefix = `${label}: ` + if (!failure.startsWith(prefix)) continue + const list = reasons.get(label) ?? [] + list.push(failure.slice(prefix.length)) + reasons.set(label, list) + break + } + } + } + return cells.map((cell) => { + const label = cellLabel(cell) + const detail = reasons.get(label) ?? [] + const ok = reported.has(label) && detail.length === 0 + return { + locale: cell.locale, + width: cell.width, + scheme: caseScheme(cell), + path: cell.kind === 'theme' ? '/dashboard' : cell.path, + ok, + detail: ok ? [] : detail.length > 0 ? detail : ['the share that owned this cell reported no result'], + } + }) +} + +/** A cell of the table: a reason can carry a `|` of its own. */ +function tableCell(value: string): string { + return value.split('|').join('\\|') +} + +/** + * The summary a reader opens from the run page. Every promised case is a row — + * a pass is a row too — so a red run names the page, viewport and scheme that + * failed and a green run shows the table the matrix actually covered. `notes` + * carries the aggregate's own reasons (a share that died, a cell counted + * twice), which belong to no single row. + */ +export function summaryMarkdown(rows: readonly VisualCaseResult[], notes: readonly string[] = []): string { + const passed = rows.filter((row) => row.ok).length + const lines = [ + `visual matrix: ${String(passed)}/${String(rows.length)} case(s) passed`, + '', + '| locale | viewport | scheme | page | result |', + '| --- | --- | --- | --- | --- |', + ] + for (const row of rows) { + const result = row.ok ? 'pass' : `fail: ${row.detail.join('; ')}` + lines.push( + `| ${tableCell(row.locale)} | ${String(row.width)}px | ${tableCell(row.scheme)} | \`${tableCell(row.path)}\` | ${tableCell(result)} |`, + ) + } + if (notes.length > 0) { + lines.push('', '**Aggregate notes**') + for (const note of notes) lines.push(`- ${tableCell(note)}`) + } + return `${lines.join('\n')}\n` +}