Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

Visual regression testing, as a release gate (#5372)

Cindy Zhang674b8b8bb456
diff --git a/.github/scripts/lib/visual-format.js b/.github/scripts/lib/visual-format.js
new file mode 100644
index 0000000000..e0a3b34366
--- /dev/null
+++ b/.github/scripts/lib/visual-format.js
@@ -0,0 +1,67 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Shared visual-gate formatting for PR enrichment.
+ * Used by generate-pr-comment.js and test-pr-enrichment.js.
+ */
+
+/**
+ * Build the visual-regression section of the PR comment.
+ *
+ * The section has to survive four states, and the awkward one is `skipped`:
+ * a check that quietly vanishes on the PRs most likely to break something
+ * visually is worse than no check, so a skip states its reason and points at
+ * the daily gate.
+ *
+ * @param {object|null} verdict - the gate's verdict.json, or null when the job did not run
+ * @param {string} [reportUrl] - published report for this PR, if there is one
+ * @returns {string} markdown
+ */
+function buildVisualSection(verdict, reportUrl) {
+ if (!verdict) return '';
+
+ const link = reportUrl
+ ? ` <a href="${reportUrl}" target="_blank" rel="noopener noreferrer">View the report</a>`
+ : '';
+
+ if (verdict.status === 'skipped') {
+ return `### Visual Regression\n\n**Status:** Skipped — ${verdict.reason}\n\n`;
+ }
+ if (verdict.status === 'failed') {
+ return `### Visual Regression\n\n**Status:** ${verdict.counts.failed} shot(s) could not be captured.${link}\n\n`;
+ }
+ if (!verdict.changes || verdict.changes.length === 0) {
+ const added = verdict.counts?.added
+ ? ` ${verdict.counts.added} new shot(s) had no baseline to compare against.`
+ : '';
+ return `### Visual Regression\n\n**Status:** No visual change across ${verdict.counts.total} shot(s).${added}\n\n`;
+ }
+
+ const rows = verdict.changes
+ .slice(0, 20)
+ .map(
+ change =>
+ `| ${change.component || change.title} | ${change.name} | ${change.theme} | ${change.mode} | ${change.diffPixels.toLocaleString()} |`,
+ )
+ .join('\n');
+ const more =
+ verdict.changes.length > 20
+ ? `\n\n_and ${verdict.changes.length - 20} more._`
+ : '';
+
+ return `### Visual Regression
+
+**${verdict.changes.length} of ${verdict.counts.total} shot(s) changed.**${link}
+
+A change here is a question, not a failure: check whether the *after* is the
+picture you intended. If it is, say so in the PR — the release gate's baseline
+is updated deliberately, and this check never rewrites it.
+
+| component | story | theme | mode | pixels |
+|---|---|---|---|---|
+${rows}${more}
+
+`;
+}
+
+module.exports = {buildVisualSection};
diff --git a/.github/scripts/visual-gate/README.md b/.github/scripts/visual-gate/README.md
new file mode 100644
index 0000000000..65be917322
--- /dev/null
+++ b/.github/scripts/visual-gate/README.md
@@ -0,0 +1,153 @@
+# Visual gate
+
+Screenshots every theming target the design system claims to support, compares
+them against an accepted baseline, and answers one question before a release
+goes out: **did anything change on screen, and did we mean it?**
+
+Not part of PR CI — it costs minutes, not seconds. It runs once a day
+(`.github/workflows/release-gate.yml`, 07:10 PT) ahead of the 08:00 PT release
+cut, and on demand.
+
+## Why it exists
+
+A theme binds to components through theming targets: a stable class plus the
+variant and state data on it. `astryx theme build` validates that an override
+KEY exists, so a renamed target is caught at build time. Nothing catches an
+override that silently stops _painting_ — the element moves behind a wrapper,
+a state stops being reflected, the cascade order shifts. The theme still
+compiles, the component still renders, and the theme quietly stops applying.
+That failure is only visible in pixels.
+
+## The three outcomes
+
+| status | meaning | what to do |
+| --------- | --------------------------------------------------------------- | --------------------------------------- |
+| `pass` | nothing moved | ship |
+| `changed` | pixels moved somewhere | look at the report and decide, per shot |
+| `failed` | a shot could not be captured, or the baseline is not comparable | fix the gate before trusting it |
+
+`changed` is a question, not a failure. **"The after is correct" is a valid
+answer** — a deliberate restyle _should_ move pixels. Recording that answer is
+what `visual-baseline.yml` does, and it writes who decided, when, against which
+run, and why, into the baseline's decision log.
+
+## What gets photographed
+
+Both tiers are derived, never hand-listed, so coverage tracks the system:
+
+- **surface** — one story per component in the default theme, light and dark.
+ The broad regression net.
+- **theme-matrix** — for every component override a theme actually authors, a
+ story that _renders that state_. A scout pass loads the candidate stories
+ and reads the DOM first, so `badge` in its `warning` variant is photographed
+ in a story that has one, rather than assuming the default story covers it.
+ On this repo that is the difference between 200 overrides no shot could
+ verify and 49.
+
+`--tiers full` widens `surface` to every story in the index (~1,770 shots).
+
+Anything the matrix still cannot reach is named in the report under **theme
+overrides that bound to nothing** — either the plan cannot get there, or the
+component stopped rendering what the theme aims at. Both are worth knowing.
+
+## Running it locally
+
+```bash
+pnpm build && pnpm -F @astryxdesign/storybook build
+
+# what would be captured, and why
+node .github/scripts/visual-gate/gate.mjs plan
+
+# capture, compare, write .visual-run/{verdict.json,report/index.html}
+node .github/scripts/visual-gate/gate.mjs check \
+ --baseline .visual-baseline --out .visual-run
+
+open .visual-run/report/index.html
+```
+
+Exit codes are the contract: `0` pass, `1` crashed, `2` changed.
+
+`--sample 24` takes an even slice of the plan for a quick smoke test.
+`--observations <file>` caches the scout pass between runs.
+
+**A local baseline is for local work only.** Rendering differs by platform and
+by browser build, so a baseline captured on a Mac and a capture from an Ubuntu
+runner would read as "everything changed". The gate refuses that comparison
+instead of showing you 500 false diffs, and the shared baseline is only ever
+written by CI, from the pinned runner label.
+
+## How the release cut uses it
+
+The daily cut (08:00 PT) reads the gate's verdict before it merges the version
+bump:
+
+```
+https://facebook.github.io/astryx/visual-gate/latest/release-gate.json
+```
+
+| verdict | the cut does |
+| --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| visual `pass`, a11y `clean` | cut, no comment |
+| visual `changed` | open the report and judge every change. Intentional → dispatch **Visual Baseline** with those keys and a reason, then cut, naming the accepted changes in the release note. Not intentional → hold the cut, say what regressed in chat, fix it first |
+| a11y `failed` (new violations against the baseline) | hold the cut and fix, or baseline the violation deliberately |
+| either `crashed` | hold. A gate that cannot run is not a green gate |
+
+The one thing that must not happen is a release going out through a diff nobody
+looked at — including a "changed" nobody read.
+
+## Accepting a change
+
+From the report, note the shot keys, then dispatch **Visual Baseline** with the
+gate run id, the keys (or `all`), and a reason. The promoted PNGs come out of
+that run's capture artifact, so the picture that becomes the baseline is
+exactly the picture that was reviewed.
+
+**Bootstrapping**: the first gate run has nothing to compare against — it
+reports every shot as `added` and passes. Dispatch **Visual Baseline** against
+that run with `keys=all` to make it the reference. Do the same after a
+deliberate system-wide restyle.
+
+A browser bump moves antialiasing everywhere at once; the gate detects it and
+tells you to refresh rather than reporting hundreds of regressions.
+
+## Determinism
+
+Every shot is taken with animations and transitions forced to their end state,
+carets hidden, a fixed viewport at device scale 1, fonts awaited, and **all
+off-origin requests blocked** — nothing that renders may depend on a CDN being
+up. Theme and colour mode are switched over Storybook's own channel rather than
+by reloading, which is what keeps 514 shots inside a few minutes;
+`--no-fast-globals` forces a reload per shot if a story's state ever turns out
+to survive the re-render.
+
+## Where the images live
+
+| what | where | size / retention |
+| ------------------------------------------- | ---------------------------------------------- | -------------------- |
+| baseline PNGs | `gh-pages:visual-gate/baseline/` | ~10 MB, permanent |
+| reports (changed shots only) | `gh-pages:visual-gate/<run_id>/` and `latest/` | last 20 runs, pruned |
+| full capture (what a promotion copies from) | Actions artifact `visual-capture` | 14 days |
+
+Nothing lands in `main`.
+
+**gh-pages is shared, and it is rebuilt as an orphan commit.** `deploy.yml`
+materializes only `storybook`, `sandbox` and `assets`, and carries every other
+path forward by SHA — `visual-gate/` survives by that mechanism, exactly as
+`pr/` and `reports/` do. **Never add `visual-gate` to that sparse-checkout
+set**: paths inside the cone are wiped and republished on every deploy, which
+would destroy the baseline and silently disarm the gate. `cleanup-previews.yml`
+only removes `pr/<number>/` and legacy 7-hex directories, so it does not touch
+it either.
+
+## Files
+
+| file | role |
+| ------------------------- | ------------------------------------------------------------------------ |
+| `gate.mjs` | CLI: `plan`, `capture`, `check`, `accept` |
+| `lib/plan.mjs` | which shots exist, and why each one does |
+| `lib/capture.mjs` | Playwright capture and the scout pass |
+| `lib/compare.mjs` | pixel comparison, targeting analysis, the verdict |
+| `lib/report.mjs` | the before / after / diff report |
+| `lib/baseline.mjs` | the baseline store and the one operation that writes it |
+| `lib/sources.mjs` | theming targets and theme overrides, from the product's own enumerations |
+| `visual-gate.config.json` | viewport, tolerances, and story exclusions with reasons |
diff --git a/.github/scripts/visual-gate/gate.mjs b/.github/scripts/visual-gate/gate.mjs
new file mode 100644
index 0000000000..fa1e8c4ed2
--- /dev/null
+++ b/.github/scripts/visual-gate/gate.mjs
@@ -0,0 +1,384 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The visual gate CLI.
+ *
+ * @input a built Storybook, a baseline directory
+ * @output a verdict (JSON), a report (HTML), and — only ever through `accept`
+ * — a new baseline
+ *
+ * Commands:
+ * plan what would be captured, and why
+ * capture take the shots
+ * check capture, compare against the baseline, write verdict + report
+ * accept record that the after is the correct picture, for named shots
+ *
+ * Exit codes are the contract for automation: 0 clean, 1 crashed, 2 changed.
+ * `changed` is separated from `crashed` precisely because a change is a
+ * question ("is this what you meant?") and a crash is not.
+ *
+ * Usage:
+ * node .github/scripts/visual-gate/gate.mjs check \
+ * --storybook-dir apps/storybook/dist --baseline .visual-baseline --out .visual-run
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+import {capture, scout} from './lib/capture.mjs';
+import {analyzeTargeting, buildVerdict, compareCaptures} from './lib/compare.mjs';
+import {buildPlan, readStoryIndex} from './lib/plan.mjs';
+import {renderReport} from './lib/report.mjs';
+import {accept, incomparable, readBaseline} from './lib/baseline.mjs';
+import {loadConfig, loadThemeOverrides, loadThemingTargets} from './lib/sources.mjs';
+
+const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
+
+const EXIT = {clean: 0, crashed: 1, changed: 2};
+
+const argv = process.argv.slice(2);
+const command = argv[0];
+const flag = name => {
+ const index = argv.indexOf(`--${name}`);
+ return index === -1 ? null : argv[index + 1];
+};
+const has = name => argv.includes(`--${name}`);
+
+const config = loadConfig(REPO_ROOT);
+const storybookDir = path.resolve(flag('storybook-dir') ?? 'apps/storybook/dist');
+const baselineDir = path.resolve(flag('baseline') ?? '.visual-baseline');
+let outDir = path.resolve(flag('out') ?? '.visual-run');
+const tiers = (flag('tiers') ?? config.tiers.join(',')).split(',').filter(Boolean);
+const sample = flag('sample') ? Number(flag('sample')) : null;
+/** Restrict the plan to story ids containing any of these — for debugging a shot, never for a gate run. */
+const only = (flag('only') ?? '').split(',').filter(Boolean);
+
+/**
+ * Which stories the scout needs to look at: every story of a component some
+ * theme overrides. Scouting the whole index would cost more than it returns —
+ * the surface tier photographs one story per component regardless.
+ *
+ * @param {ReturnType<typeof readStoryIndex>} stories
+ * @param {Array<{key: string, component: string}>} targets
+ * @param {Record<string, Record<string, string[]>>} themeOverrides
+ * @returns {string[]}
+ */
+function storiesToScout(stories, targets, themeOverrides) {
+ const overridden = new Set(Object.values(themeOverrides).flatMap(keys => Object.keys(keys)));
+ const components = new Set(
+ targets.filter(target => overridden.has(target.key)).map(target => target.component),
+ );
+ return stories.filter(story => components.has(story.component)).map(story => story.id);
+}
+
+/** @returns {Promise<import('./lib/plan.mjs').Shot[]>} */
+async function plan() {
+ const [targets, themeOverrides] = await Promise.all([
+ loadThemingTargets(REPO_ROOT),
+ loadThemeOverrides(REPO_ROOT),
+ ]);
+ const stories = readStoryIndex(storybookDir, Object.keys(config.excludeStories));
+
+ let observations;
+ if (!has('no-scout') && tiers.includes('theme-matrix')) {
+ const cachePath = flag('observations');
+ if (cachePath && fs.existsSync(cachePath)) {
+ observations = JSON.parse(fs.readFileSync(cachePath, 'utf8'));
+ } else {
+ const storyIds = storiesToScout(stories, targets, themeOverrides);
+ process.stderr.write(`Scouting ${storyIds.length} stories for theming targets…\n`);
+ observations = await scout({
+ storyIds,
+ storybookDir,
+ theme: config.defaultTheme,
+ viewport: config.viewport,
+ });
+ if (cachePath) fs.writeFileSync(cachePath, `${JSON.stringify(observations)}\n`);
+ }
+ }
+
+ const shots = buildPlan({
+ stories,
+ targets,
+ themeOverrides,
+ observations,
+ defaultTheme: config.defaultTheme,
+ tiers,
+ });
+ // A sample is for trying the rig out, never for a gate run: it is taken
+ // evenly across the plan so it spans components rather than the first few.
+ const filtered = only.length
+ ? shots.filter(shot => only.some(fragment => shot.storyId.includes(fragment)))
+ : shots;
+ if (!sample || sample >= filtered.length) return filtered;
+ const step = filtered.length / sample;
+ return Array.from({length: sample}, (_, index) => filtered[Math.floor(index * step)]);
+}
+
+async function runCapture(shots) {
+ fs.rmSync(outDir, {recursive: true, force: true});
+ fs.mkdirSync(outDir, {recursive: true});
+ let last = 0;
+ const {manifest, failures} = await capture({
+ plan: shots,
+ storybookDir,
+ outDir,
+ viewport: config.viewport,
+ settleMs: config.settleMs,
+ fastGlobals: !has('no-fast-globals'),
+ onProgress: ({done, total}) => {
+ if (done === total || done - last >= 50) {
+ last = done;
+ process.stderr.write(` captured ${done}/${total}\n`);
+ }
+ },
+ });
+ manifest.context = {
+ sha: process.env.GITHUB_SHA ?? null,
+ ref: process.env.GITHUB_REF ?? null,
+ runId: process.env.GITHUB_RUN_ID ?? null,
+ };
+ fs.writeFileSync(
+ path.join(outDir, 'manifest.json'),
+ `${JSON.stringify(manifest, null, 2)}\n`,
+ );
+ return {manifest, failures};
+}
+
+/** Copy the three image sets the report links to, next to the report itself. */
+function stageReportImages({reportDir, keys, currentDir, baselinePath}) {
+ for (const [name, source] of [
+ ['before', baselinePath],
+ ['after', path.join(currentDir, 'shots')],
+ ]) {
+ fs.mkdirSync(path.join(reportDir, name), {recursive: true});
+ for (const key of keys) {
+ const from = path.join(source, `${key}.png`);
+ if (fs.existsSync(from)) fs.copyFileSync(from, path.join(reportDir, name, `${key}.png`));
+ }
+ }
+}
+
+async function check() {
+ const shots = await plan();
+ process.stderr.write(`Visual gate: ${shots.length} shots (${tiers.join(', ')})\n`);
+ const {manifest, failures} = await runCapture(shots);
+
+ const {manifest: baselineManifest, exists} = readBaseline(baselineDir);
+ const blocker = exists ? incomparable(baselineManifest, manifest) : null;
+ if (blocker) {
+ process.stderr.write(`::error::Baseline is not comparable — ${blocker}\n`);
+ return EXIT.crashed;
+ }
+
+ const reportDir = path.join(outDir, 'report');
+ const comparison = await compareCaptures({
+ baselineDir: path.join(baselineDir, 'shots'),
+ currentDir: path.join(outDir, 'shots'),
+ baselineManifest,
+ currentManifest: manifest,
+ diffDir: path.join(reportDir, 'diff'),
+ threshold: config.threshold,
+ maxDiffPixels: config.maxDiffPixels,
+ });
+
+ const [targets, themeOverrides] = await Promise.all([
+ loadThemingTargets(REPO_ROOT),
+ loadThemeOverrides(REPO_ROOT),
+ ]);
+ const targeting = analyzeTargeting({
+ observedTargets: manifest.observedTargets,
+ targets,
+ themeOverrides,
+ });
+
+ const verdict = buildVerdict({
+ comparison,
+ currentManifest: manifest,
+ baselineManifest,
+ targeting,
+ failures,
+ context: {...manifest.context, tiers, baselineExists: exists},
+ });
+
+ stageReportImages({
+ reportDir,
+ keys: comparison.changes.map(change => change.key),
+ currentDir: outDir,
+ baselinePath: path.join(baselineDir, 'shots'),
+ });
+ fs.writeFileSync(path.join(reportDir, 'index.html'), renderReport(verdict));
+ const verdictJson = `${JSON.stringify(verdict, null, 2)}\n`;
+ fs.writeFileSync(path.join(outDir, 'verdict.json'), verdictJson);
+ // Also inside the report, so the published report directory is self-contained
+ // and the verdict has a stable URL next to the pictures it describes.
+ fs.writeFileSync(path.join(reportDir, 'verdict.json'), verdictJson);
+
+ const summary = summarize(verdict, exists);
+ process.stdout.write(summary);
+ if (flag('summary-output')) fs.writeFileSync(flag('summary-output'), summary);
+ if (process.env.GITHUB_OUTPUT) {
+ fs.appendFileSync(
+ process.env.GITHUB_OUTPUT,
+ [
+ `status=${verdict.status}`,
+ `changed=${verdict.counts.changed}`,
+ `added=${verdict.counts.added}`,
+ `failed=${verdict.counts.failed}`,
+ `total=${verdict.counts.total}`,
+ ].join('\n') + '\n',
+ );
+ }
+
+ if (verdict.status === 'failed') return EXIT.crashed;
+ return verdict.status === 'changed' ? EXIT.changed : EXIT.clean;
+}
+
+/** @param {object} verdict @param {boolean} baselineExists */
+function summarize(verdict, baselineExists) {
+ const lines = [`## Visual gate: ${verdict.status}`, ''];
+ if (!baselineExists) {
+ lines.push('No baseline existed — this run establishes one. Nothing was compared.', '');
+ }
+ lines.push(
+ `| shots | changed | added | removed | failed |`,
+ `|---|---|---|---|---|`,
+ `| ${verdict.counts.total} | ${verdict.counts.changed} | ${verdict.counts.added} | ${verdict.counts.removed} | ${verdict.counts.failed} |`,
+ '',
+ );
+ if (verdict.changes.length > 0) {
+ lines.push('### Changed', '', '| shot | theme | mode | diff px | why it is in the plan |', '|---|---|---|---|---|');
+ for (const change of verdict.changes.slice(0, 40)) {
+ lines.push(
+ `| \`${change.key}\` | ${change.theme} | ${change.mode} | ${change.diffPixels} | ${(change.reasons ?? []).join(', ')} |`,
+ );
+ }
+ if (verdict.changes.length > 40) lines.push(`| … | | | | ${verdict.changes.length - 40} more |`);
+ lines.push('');
+ }
+ const unexercised = verdict.targeting?.unexercisedOverrides ?? [];
+ if (unexercised.length > 0) {
+ lines.push(
+ `### Theme overrides that bound to nothing (${unexercised.length})`,
+ '',
+ ...unexercised
+ .slice(0, 25)
+ .map(finding => `- \`${finding.theme}\` → \`${finding.key}${finding.selector ? `.${finding.selector}` : ''}\``),
+ '',
+ );
+ }
+ return `${lines.join('\n')}\n`;
+}
+
+async function main() {
+ switch (command) {
+ case 'plan': {
+ const shots = await plan();
+ if (has('json')) {
+ process.stdout.write(`${JSON.stringify(shots, null, 2)}\n`);
+ return EXIT.clean;
+ }
+ const byReason = {};
+ for (const shot of shots) {
+ for (const reason of shot.reasons) {
+ const bucket = reason.split(':').slice(0, 2).join(':');
+ byReason[bucket] = (byReason[bucket] ?? 0) + 1;
+ }
+ }
+ process.stdout.write(`${shots.length} shots\n`);
+ for (const [reason, count] of Object.entries(byReason).sort((a, b) => b[1] - a[1])) {
+ process.stdout.write(` ${String(count).padStart(5)} ${reason}\n`);
+ }
+ return EXIT.clean;
+ }
+ case 'capture': {
+ const shots = await plan();
+ const {failures} = await runCapture(shots);
+ process.stdout.write(`Captured ${shots.length - failures.length}/${shots.length} into ${outDir}\n`);
+ return failures.length > 0 ? EXIT.crashed : EXIT.clean;
+ }
+ case 'check':
+ return check();
+ case 'flaky': {
+ // A gate that cries wolf gets ignored, so the exclusion list is
+ // evidence, not guesswork: capture the same build twice and name every
+ // shot that could not reproduce itself.
+ const shots = await plan();
+ const passes = Number(flag('passes') ?? 2);
+ /** @type {Map<string, Set<string>>} */
+ const seen = new Map();
+ const passRoot = outDir;
+ for (let pass = 0; pass < passes; pass += 1) {
+ process.stderr.write(`Pass ${pass + 1}/${passes}\n`);
+ // Each pass keeps its own directory: when a shot turns out to be
+ // unstable, the evidence of how it differed has to survive the run.
+ outDir = path.join(passRoot, `pass-${pass + 1}`);
+ const {manifest} = await runCapture(shots);
+ for (const [key, shot] of Object.entries(manifest.shots)) {
+ if (!seen.has(key)) seen.set(key, new Set());
+ seen.get(key).add(shot.sha256);
+ }
+ }
+ outDir = passRoot;
+ const unstable = [...seen.entries()]
+ .filter(([, hashes]) => hashes.size > 1)
+ .map(([key]) => key);
+ const stories = [...new Set(unstable.map(key => key.split('__')[0]))].sort();
+ process.stdout.write(
+ `${unstable.length} unstable shot(s) across ${passes} passes, in ${stories.length} stor${stories.length === 1 ? 'y' : 'ies'}\n`,
+ );
+ for (const story of stories) process.stdout.write(` ${story}\n`);
+ if (unstable.length > 0) {
+ process.stdout.write(
+ `\nEach pass is kept under ${passRoot} — diff them to see what moved, then add these to excludeStories in visual-gate.config.json with the reason each one cannot reproduce.\n`,
+ );
+ }
+ return unstable.length > 0 ? EXIT.changed : EXIT.clean;
+ }
+ case 'accept': {
+ const manifestPath = path.join(outDir, 'manifest.json');
+ if (!fs.existsSync(manifestPath)) {
+ throw new Error(`No capture at ${outDir} — run check or capture first.`);
+ }
+ const currentManifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
+ const verdictPath = path.join(outDir, 'verdict.json');
+ const verdict = fs.existsSync(verdictPath)
+ ? JSON.parse(fs.readFileSync(verdictPath, 'utf8'))
+ : null;
+ const requested = flag('keys');
+ const keys =
+ !requested || requested === 'all'
+ ? Object.keys(currentManifest.shots)
+ : requested.split(',').filter(Boolean);
+ const result = accept({
+ baselineDir,
+ captureDir: outDir,
+ currentManifest,
+ keys,
+ reason: flag('reason') ?? '',
+ actor: flag('actor') ?? process.env.GITHUB_ACTOR ?? process.env.USER ?? 'unknown',
+ runId: process.env.GITHUB_RUN_ID ?? null,
+ prune: has('prune') ? (verdict?.removed ?? []) : [],
+ });
+ process.stdout.write(
+ `Promoted ${result.promoted.length} shot(s), pruned ${result.pruned.length}, into ${baselineDir}\n`,
+ );
+ return EXIT.clean;
+ }
+ default:
+ process.stderr.write(
+ 'Usage: gate.mjs <flaky|plan|capture|check|accept> [--storybook-dir dir] [--baseline dir] [--out dir] [--tiers a,b] [--sample n]\n',
+ );
+ return EXIT.crashed;
+ }
+}
+
+main().then(
+ code => process.exit(code),
+ error => {
+ process.stderr.write(`::error::${error?.stack ?? error}\n`);
+ process.exit(EXIT.crashed);
+ },
+);
diff --git a/.github/scripts/visual-gate/lib/baseline.mjs b/.github/scripts/visual-gate/lib/baseline.mjs
new file mode 100644
index 0000000000..f17437b57a
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/baseline.mjs
@@ -0,0 +1,145 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The baseline store, and the one operation that changes it.
+ *
+ * @input a baseline directory (manifest + shots) and a capture
+ * @output an updated baseline, with every promotion recorded
+ *
+ * "The after is correct" is a decision, not a retry. Promoting a shot writes
+ * a line into the manifest's decision log saying which shots moved, who moved
+ * them, against which run, and why — so a baseline can always be read back to
+ * the change that justified it. Nothing else in the gate writes to the
+ * baseline: a capture never quietly becomes the new truth.
+ *
+ * Baselines are per-platform. A shot captured on macOS and a shot captured on
+ * an Ubuntu runner differ in font rasterisation everywhere at once, which
+ * reads as "everything changed" and teaches everyone to accept blindly. The
+ * gate refuses the comparison instead.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+export const EMPTY_MANIFEST = {version: 1, shots: {}, decisions: []};
+
+/**
+ * @param {string} baselineDir
+ * @returns {{manifest: object, exists: boolean}}
+ */
+export function readBaseline(baselineDir) {
+ const manifestPath = path.join(baselineDir, 'manifest.json');
+ if (!fs.existsSync(manifestPath)) return {manifest: {...EMPTY_MANIFEST}, exists: false};
+ return {manifest: JSON.parse(fs.readFileSync(manifestPath, 'utf8')), exists: true};
+}
+
+/**
+ * @param {string} baselineDir
+ * @param {object} manifest
+ */
+export function writeBaseline(baselineDir, manifest) {
+ fs.mkdirSync(path.join(baselineDir, 'shots'), {recursive: true});
+ fs.writeFileSync(
+ path.join(baselineDir, 'manifest.json'),
+ `${JSON.stringify(manifest, null, 2)}\n`,
+ );
+}
+
+/**
+ * Refuse a comparison the numbers cannot support.
+ * @param {object} baselineManifest
+ * @param {object} currentManifest
+ * @returns {string | null} the reason the comparison is invalid, or null
+ */
+export function incomparable(baselineManifest, currentManifest) {
+ if (!baselineManifest.platform) return null;
+ if (baselineManifest.platform !== currentManifest.platform) {
+ return `baseline was captured on ${baselineManifest.platform}, this run on ${currentManifest.platform} — rendering differs by platform, so the diff would be noise. Recapture the baseline on ${currentManifest.platform}.`;
+ }
+ if (
+ baselineManifest.browser &&
+ currentManifest.browser &&
+ baselineManifest.browser !== currentManifest.browser
+ ) {
+ // A browser bump moves antialiasing and font metrics everywhere at once.
+ // Saying so is far more useful than a report claiming 400 regressions.
+ return `baseline was captured with ${baselineManifest.browser}, this run with ${currentManifest.browser} — refresh the baseline (gate.mjs accept --keys all --reason "browser bump").`;
+ }
+ const a = baselineManifest.viewport;
+ const b = currentManifest.viewport;
+ if (a && b && (a.width !== b.width || a.height !== b.height)) {
+ return `baseline viewport ${a.width}x${a.height} does not match this run's ${b.width}x${b.height}.`;
+ }
+ return null;
+}
+
+/**
+ * Promote captured shots into the baseline.
+ *
+ * @param {object} options
+ * @param {string} options.baselineDir
+ * @param {string} options.captureDir - directory holding the capture's shots/
+ * @param {object} options.currentManifest
+ * @param {string[]} options.keys - shot keys to promote
+ * @param {string} options.reason - why the new rendering is the correct one
+ * @param {string} options.actor
+ * @param {string | null} [options.runId]
+ * @param {string[]} [options.prune] - shot keys to drop (stories that no longer exist)
+ * @returns {{promoted: string[], pruned: string[], manifest: object}}
+ */
+export function accept({
+ baselineDir,
+ captureDir,
+ currentManifest,
+ keys,
+ reason,
+ actor,
+ runId = null,
+ prune = [],
+}) {
+ if (!reason?.trim()) throw new Error('accept requires a reason — it is the record of the decision');
+ const {manifest} = readBaseline(baselineDir);
+ const shotsDir = path.join(baselineDir, 'shots');
+ fs.mkdirSync(shotsDir, {recursive: true});
+
+ const promoted = [];
+ for (const key of keys) {
+ const source = path.join(captureDir, 'shots', `${key}.png`);
+ if (!fs.existsSync(source)) continue;
+ fs.copyFileSync(source, path.join(shotsDir, `${key}.png`));
+ manifest.shots[key] = currentManifest.shots[key];
+ promoted.push(key);
+ }
+
+ const pruned = [];
+ for (const key of prune) {
+ const target = path.join(shotsDir, `${key}.png`);
+ if (fs.existsSync(target)) fs.rmSync(target);
+ if (manifest.shots[key]) {
+ delete manifest.shots[key];
+ pruned.push(key);
+ }
+ }
+
+ manifest.version = 1;
+ manifest.platform = currentManifest.platform;
+ manifest.browser = currentManifest.browser;
+ manifest.viewport = currentManifest.viewport;
+ manifest.capturedAt = currentManifest.capturedAt;
+ manifest.context = currentManifest.context ?? null;
+ manifest.decisions = [
+ ...(manifest.decisions ?? []),
+ {
+ at: new Date().toISOString(),
+ actor,
+ runId,
+ reason: reason.trim(),
+ promoted,
+ pruned,
+ },
+ // A decision log that grows without bound is a decision log nobody reads.
+ ].slice(-200);
+
+ writeBaseline(baselineDir, manifest);
+ return {promoted, pruned, manifest};
+}
diff --git a/.github/scripts/visual-gate/lib/baseline.test.mjs b/.github/scripts/visual-gate/lib/baseline.test.mjs
new file mode 100644
index 0000000000..38c4da2f1a
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/baseline.test.mjs
@@ -0,0 +1,91 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+
+import {accept, incomparable, readBaseline} from './baseline.mjs';
+
+let root;
+let baselineDir;
+let captureDir;
+
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'visual-baseline-'));
+ baselineDir = path.join(root, 'baseline');
+ captureDir = path.join(root, 'capture');
+ fs.mkdirSync(path.join(captureDir, 'shots'), {recursive: true});
+ fs.writeFileSync(path.join(captureDir, 'shots', 'a.png'), 'new-a');
+ fs.writeFileSync(path.join(captureDir, 'shots', 'b.png'), 'new-b');
+});
+afterEach(() => fs.rmSync(root, {recursive: true, force: true}));
+
+const currentManifest = {
+ platform: 'linux-arm64',
+ viewport: {width: 1024, height: 768},
+ capturedAt: '2026-08-23T00:00:00.000Z',
+ shots: {a: {sha256: 'aa'}, b: {sha256: 'bb'}},
+};
+
+const promote = overrides =>
+ accept({
+ baselineDir,
+ captureDir,
+ currentManifest,
+ keys: ['a'],
+ reason: 'Button radius changed on purpose',
+ actor: 'tester',
+ ...overrides,
+ });
+
+describe('accept', () => {
+ it('refuses to promote without a reason, because the reason is the record', () => {
+ expect(() => promote({reason: ' '})).toThrow(/reason/);
+ });
+
+ it('copies only the named shots into the baseline', () => {
+ promote();
+ expect(fs.readFileSync(path.join(baselineDir, 'shots', 'a.png'), 'utf8')).toBe('new-a');
+ expect(fs.existsSync(path.join(baselineDir, 'shots', 'b.png'))).toBe(false);
+ expect(Object.keys(readBaseline(baselineDir).manifest.shots)).toEqual(['a']);
+ });
+
+ it('records who promoted what, and why', () => {
+ promote();
+ const [decision] = readBaseline(baselineDir).manifest.decisions;
+ expect(decision).toMatchObject({actor: 'tester', promoted: ['a'], reason: 'Button radius changed on purpose'});
+ });
+
+ it('keeps earlier decisions when promoting again', () => {
+ promote();
+ promote({keys: ['b'], reason: 'Badge padding, intentional'});
+ expect(readBaseline(baselineDir).manifest.decisions).toHaveLength(2);
+ });
+
+ it('drops pruned shots from both the manifest and disk', () => {
+ promote({keys: ['a', 'b']});
+ promote({keys: [], prune: ['b'], reason: 'story deleted'});
+ expect(fs.existsSync(path.join(baselineDir, 'shots', 'b.png'))).toBe(false);
+ expect(Object.keys(readBaseline(baselineDir).manifest.shots)).toEqual(['a']);
+ });
+});
+
+describe('incomparable', () => {
+ it('refuses a baseline from another platform', () => {
+ expect(incomparable({platform: 'darwin-arm64'}, {platform: 'linux-arm64'})).toMatch(/darwin-arm64/);
+ });
+
+ it('refuses a baseline captured at another viewport', () => {
+ const reason = incomparable(
+ {platform: 'linux-arm64', viewport: {width: 800, height: 600}},
+ {platform: 'linux-arm64', viewport: {width: 1024, height: 768}},
+ );
+ expect(reason).toMatch(/viewport/);
+ });
+
+ it('allows a first run against an empty baseline', () => {
+ expect(incomparable({}, {platform: 'linux-arm64'})).toBeNull();
+ });
+});
diff --git a/.github/scripts/visual-gate/lib/capture.mjs b/.github/scripts/visual-gate/lib/capture.mjs
new file mode 100644
index 0000000000..e41b1f8f7a
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/capture.mjs
@@ -0,0 +1,412 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Capture: turn a shot plan into PNGs, plus the theming evidence needed
+ * to explain a diff.
+ *
+ * @input a built Storybook directory and a shot plan
+ * @output one PNG per shot under <out>/shots, a capture manifest, and the set
+ * of theming targets actually observed in the DOM
+ *
+ * Two things here are load-bearing and easy to get wrong:
+ *
+ * Determinism. A visual gate that flickers is worse than no gate — every
+ * false diff costs a human judgement and teaches everyone to ignore it. So
+ * the page is pinned: no external network (nothing that renders may depend on
+ * a CDN being up), animations and transitions forced to their end state,
+ * carets hidden, a fixed viewport and device scale factor, and a wait on
+ * `document.fonts.ready` before the shutter. Even so, a baseline is only
+ * comparable against a capture from the same OS and browser build, which is
+ * why the manifest records the platform and the comparison refuses to cross it.
+ *
+ * Speed. Storybook applies the theme through a global, so a theme change is a
+ * re-render, not a reload: the plan is walked grouped by story, and the theme
+ * and color mode are switched over Storybook's own channel while the page
+ * stays put (~130ms per shot against ~1s for a reload). `--no-fast-globals`
+ * forces a reload per shot for the case where a story's own state would
+ * survive the re-render and make the shot depend on the one before it.
+ */
+
+import * as fs from 'node:fs';
+import * as http from 'node:http';
+import * as path from 'node:path';
+import * as crypto from 'node:crypto';
+
+const CONTENT_TYPES = {
+ '.css': 'text/css',
+ '.html': 'text/html',
+ '.js': 'application/javascript',
+ '.json': 'application/json',
+ '.map': 'application/json',
+ '.mjs': 'application/javascript',
+ '.png': 'image/png',
+ '.svg': 'image/svg+xml',
+ '.ttf': 'font/ttf',
+ '.woff': 'font/woff',
+ '.woff2': 'font/woff2',
+};
+
+/** Injected before every shot: hold animation at its end state, hide carets. */
+const FREEZE_CSS = `
+*, *::before, *::after {
+ animation-duration: 0s !important;
+ animation-delay: 0s !important;
+ animation-iteration-count: 1 !important;
+ transition-duration: 0s !important;
+ transition-delay: 0s !important;
+ caret-color: transparent !important;
+}
+html { scrollbar-width: none !important; }
+::-webkit-scrollbar { display: none !important; }
+`;
+
+/** Injected before every story script: a seeded PRNG in place of Math.random.
+ *
+ * Most of the stories that could not reproduce themselves were charts built on
+ * random sample data — nothing about them is unstable except the numbers. A
+ * fixed seed turns them back into ordinary regression subjects instead of
+ * entries on an exclusion list. Stories whose instability is real (GPU
+ * rasterisation, streaming animation) stay unstable and belong in
+ * `excludeStories`.
+ */
+const SEEDED_RANDOM = `(() => {
+ let state = 0x2f6e2b1 >>> 0;
+ Math.random = () => {
+ state = (state + 0x6d2b79f5) >>> 0;
+ let t = state;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+})();`;
+
+/**
+ * Serve a directory over loopback. The gate never talks to the network, so
+ * this is the only origin the browser can reach.
+ * @param {string} dir
+ * @returns {Promise<{port: number, close: () => Promise<void>}>}
+ */
+export function serveDirectory(dir) {
+ const server = http.createServer((req, res) => {
+ const requested = path.join(dir, req.url === '/' ? 'index.html' : req.url.split('?')[0]);
+ if (!path.resolve(requested).startsWith(path.resolve(dir))) {
+ res.writeHead(403);
+ res.end('Forbidden');
+ return;
+ }
+ fs.readFile(requested, (error, data) => {
+ if (error) {
+ res.writeHead(404);
+ res.end('Not found');
+ return;
+ }
+ res.writeHead(200, {
+ 'Content-Type': CONTENT_TYPES[path.extname(requested)] ?? 'application/octet-stream',
+ 'Cache-Control': 'no-store',
+ });
+ res.end(data);
+ });
+ });
+ return new Promise(resolve => {
+ server.listen(0, () => {
+ resolve({
+ port: server.address().port,
+ close: () => new Promise(done => server.close(done)),
+ });
+ });
+ });
+}
+
+/**
+ * Every `astryx-*` class present in the document, with the theming data each
+ * one carries. This is what turns "these pixels moved" into "the `selected`
+ * state stopped reaching `astryx-top-nav-item`", and what proves a theme
+ * override had something to bind to at all.
+ * @param {import('playwright').Page} page
+ * @returns {Promise<Record<string, string[]>>}
+ */
+async function observeTargets(page) {
+ return page.evaluate(() => {
+ /** @type {Record<string, Set<string>>} */
+ const observed = {};
+ for (const element of document.querySelectorAll('[class*="astryx-"]')) {
+ for (const className of element.classList) {
+ if (!className.startsWith('astryx-')) continue;
+ const key = className.slice('astryx-'.length);
+ observed[key] ??= new Set();
+ for (const attribute of element.attributes) {
+ if (!attribute.name.startsWith('data-')) continue;
+ const name = attribute.name.slice('data-'.length);
+ // themeProps emits bare names for states and name/value for props.
+ observed[key].add(attribute.value === '' || attribute.value === 'true' ? name : `${name}:${attribute.value}`);
+ }
+ }
+ }
+ return Object.fromEntries(Object.entries(observed).map(([key, values]) => [key, [...values]]));
+ });
+}
+
+/**
+ * @param {import('playwright').Page} page
+ * @param {{astryxTheme: string, colorMode: string}} globals
+ */
+async function applyGlobals(page, globals) {
+ await page.evaluate(async next => {
+ const channel = globalThis.__STORYBOOK_ADDONS_CHANNEL__;
+ if (!channel) throw new Error('Storybook preview channel unavailable');
+ await new Promise((resolve, reject) => {
+ const settle = () => {
+ channel.off('storyRendered', settle);
+ resolve(undefined);
+ };
+ channel.on('storyRendered', settle);
+ channel.emit('updateGlobals', {globals: next});
+ setTimeout(() => {
+ channel.off('storyRendered', settle);
+ reject(new Error('timed out waiting for storyRendered'));
+ }, 15000);
+ });
+ }, globals);
+}
+
+/**
+ * A theme Storybook does not know about silently renders as the default one,
+ * which would quietly compare the wrong picture against the baseline forever.
+ * `<Theme>` reflects what it actually applied, so ask the DOM.
+ * @param {import('playwright').Page} page
+ * @param {{theme: string, mode: string}} expected
+ */
+async function verifyApplied(page, expected) {
+ const applied = await page.evaluate(() => {
+ const themed = document.querySelector('[data-astryx-theme]');
+ return {
+ theme: themed?.getAttribute('data-astryx-theme') ?? null,
+ mode: document.documentElement.getAttribute('data-theme'),
+ };
+ });
+ if (applied.theme !== expected.theme) {
+ throw new Error(
+ `requested theme "${expected.theme}" but the story rendered "${applied.theme}" — register it in apps/storybook/.storybook/preview.tsx`,
+ );
+ }
+ if (applied.mode !== expected.mode) {
+ throw new Error(`requested mode "${expected.mode}" but the story rendered "${applied.mode}"`);
+ }
+}
+
+/**
+ * Wait until the page has stopped moving.
+ *
+ * Fonts and CSS transitions are the easy half; the half that actually bites is
+ * layout a component computes in an effect — a selection indicator that
+ * measures its target and then positions itself. Under load that lands after
+ * the shutter, and the shot differs from the same shot on a quieter run. So
+ * the geometry of every themed element is sampled until two consecutive
+ * frames agree.
+ *
+ * @param {import('playwright').Page} page
+ * @param {number} settleMs
+ */
+async function settle(page, settleMs) {
+ await page.evaluate(
+ ms =>
+ new Promise(resolve => {
+ requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(resolve, ms)));
+ }),
+ settleMs,
+ );
+ await page.evaluate(() => document.fonts.ready);
+
+ let previous = null;
+ for (let attempt = 0; attempt < 12; attempt += 1) {
+ const geometry = await page.evaluate(() =>
+ [...document.querySelectorAll('[class*="astryx-"]')]
+ .map(element => {
+ const box = element.getBoundingClientRect();
+ return `${Math.round(box.x)},${Math.round(box.y)},${Math.round(box.width)},${Math.round(box.height)}`;
+ })
+ .join('|'),
+ );
+ if (geometry === previous) return;
+ previous = geometry;
+ await page.waitForTimeout(25);
+ }
+}
+
+/**
+ * Load stories without photographing them, and report what each one rendered.
+ *
+ * A screenshot is expensive; a page load and a DOM read are not. Scouting is
+ * how the theme matrix finds a story that actually renders `badge` in its
+ * `warning` variant, instead of assuming the component's default story covers
+ * every state a theme styles. Without it the matrix photographs the same
+ * default over and over and leaves most overrides unverified.
+ *
+ * @param {object} options
+ * @param {string[]} options.storyIds
+ * @param {string} options.storybookDir
+ * @param {string} options.theme - any theme; observed targets do not depend on it
+ * @param {{width: number, height: number}} options.viewport
+ * @param {(progress: {done: number, total: number}) => void} [options.onProgress]
+ * @returns {Promise<Record<string, Record<string, string[]>>>} story id → observed targets
+ */
+export async function scout({storyIds, storybookDir, theme, viewport, onProgress}) {
+ const {chromium} = await import('playwright');
+ const server = await serveDirectory(storybookDir);
+ const origin = `http://127.0.0.1:${server.port}`;
+ const browser = await chromium.launch();
+ const context = await browser.newContext({viewport, deviceScaleFactor: 1});
+ await context.addInitScript(SEEDED_RANDOM);
+ await context.route('**', route =>
+ route.request().url().startsWith(origin) ? route.continue() : route.abort(),
+ );
+ const page = await context.newPage();
+
+ /** @type {Record<string, Record<string, string[]>>} */
+ const observations = {};
+ let done = 0;
+ for (const storyId of storyIds) {
+ try {
+ await page.goto(
+ `${origin}/iframe.html?id=${encodeURIComponent(storyId)}&viewMode=story&globals=astryxTheme:${theme};colorMode:light`,
+ {waitUntil: 'load', timeout: 30000},
+ );
+ await page.waitForSelector('#storybook-root > *', {timeout: 20000});
+ observations[storyId] = await observeTargets(page);
+ } catch {
+ // A story that will not render is the capture's problem to report, not
+ // the scout's; it simply contributes no observations.
+ observations[storyId] = {};
+ }
+ onProgress?.({done: ++done, total: storyIds.length});
+ }
+
+ await browser.close();
+ await server.close();
+ return observations;
+}
+
+/**
+ * @param {object} options
+ * @param {import('./plan.mjs').Shot[]} options.plan
+ * @param {string} options.storybookDir
+ * @param {string} options.outDir
+ * @param {{width: number, height: number}} options.viewport
+ * @param {number} options.settleMs
+ * @param {boolean} options.fastGlobals
+ * @param {(progress: {done: number, total: number, key: string}) => void} [options.onProgress]
+ * @returns {Promise<{manifest: object, failures: Array<{key: string, error: string}>}>}
+ */
+export async function capture({
+ plan,
+ storybookDir,
+ outDir,
+ viewport,
+ settleMs,
+ fastGlobals,
+ onProgress,
+}) {
+ const {chromium} = await import('playwright');
+ const shotsDir = path.join(outDir, 'shots');
+ fs.mkdirSync(shotsDir, {recursive: true});
+
+ const server = await serveDirectory(storybookDir);
+ const origin = `http://127.0.0.1:${server.port}`;
+ const browser = await chromium.launch();
+ const browserVersion = browser.version();
+ const context = await browser.newContext({
+ viewport,
+ deviceScaleFactor: 1,
+ reducedMotion: 'reduce',
+ colorScheme: 'light',
+ });
+ await context.addInitScript(SEEDED_RANDOM);
+ // Anything off-origin is a determinism hazard, and nothing in a component
+ // story legitimately needs it.
+ await context.route('**', route =>
+ route.request().url().startsWith(origin) ? route.continue() : route.abort(),
+ );
+ const page = await context.newPage();
+ await page.addStyleTag({content: FREEZE_CSS}).catch(() => {});
+
+ /** @type {Record<string, {sha256: string, width: number, height: number, storyId: string, theme: string, mode: string, reasons: string[]}>} */
+ const shots = {};
+ /** @type {Record<string, Set<string>>} */
+ const observed = {};
+ /** @type {Array<{key: string, error: string}>} */
+ const failures = [];
+
+ let currentStory = null;
+ let done = 0;
+
+ for (const shot of plan) {
+ try {
+ const globals = {astryxTheme: shot.theme, colorMode: shot.mode};
+ const needsLoad = !fastGlobals || currentStory !== shot.storyId;
+ if (needsLoad) {
+ const globalsParam = `astryxTheme:${shot.theme};colorMode:${shot.mode}`;
+ await page.goto(
+ `${origin}/iframe.html?id=${encodeURIComponent(shot.storyId)}&viewMode=story&globals=${globalsParam}`,
+ {waitUntil: 'load', timeout: 30000},
+ );
+ await page.waitForSelector('#storybook-root > *', {timeout: 30000});
+ currentStory = shot.storyId;
+ } else {
+ await applyGlobals(page, globals);
+ }
+ await page.addStyleTag({content: FREEZE_CSS});
+ await settle(page, settleMs);
+ await verifyApplied(page, {theme: shot.theme, mode: shot.mode});
+
+ const png = await page.screenshot({fullPage: true, animations: 'disabled'});
+ fs.writeFileSync(path.join(shotsDir, `${shot.key}.png`), png);
+ const size = await page.evaluate(() => ({
+ width: document.documentElement.scrollWidth,
+ height: document.documentElement.scrollHeight,
+ }));
+ shots[shot.key] = {
+ sha256: crypto.createHash('sha256').update(png).digest('hex'),
+ width: size.width,
+ height: size.height,
+ storyId: shot.storyId,
+ title: shot.title,
+ name: shot.name,
+ component: shot.component,
+ theme: shot.theme,
+ mode: shot.mode,
+ reasons: shot.reasons,
+ };
+
+ for (const [key, values] of Object.entries(await observeTargets(page))) {
+ observed[key] ??= new Set();
+ for (const value of values) observed[key].add(value);
+ }
+ } catch (error) {
+ failures.push({key: shot.key, error: String(error?.message ?? error).slice(0, 400)});
+ // A story that will not render poisons the page for the next shot in the
+ // same story group.
+ currentStory = null;
+ }
+ done += 1;
+ onProgress?.({done, total: plan.length, key: shot.key});
+ }
+
+ await browser.close();
+ await server.close();
+
+ return {
+ manifest: {
+ version: 1,
+ platform: `${process.platform}-${process.arch}`,
+ browser: `chromium-${browserVersion}`,
+ viewport,
+ settleMs,
+ capturedAt: new Date().toISOString(),
+ shots,
+ observedTargets: Object.fromEntries(
+ Object.entries(observed).map(([key, values]) => [key, [...values].sort()]),
+ ),
+ },
+ failures,
+ };
+}
diff --git a/.github/scripts/visual-gate/lib/compare.mjs b/.github/scripts/visual-gate/lib/compare.mjs
new file mode 100644
index 0000000000..f57d1685ef
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/compare.mjs
@@ -0,0 +1,235 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Compare a capture against a baseline, and read the theming evidence.
+ *
+ * @input two capture directories and their manifests
+ * @output a verdict — the machine-readable answer the release cron acts on —
+ * plus a diff PNG per changed shot
+ *
+ * The verdict is deliberately three-valued. `pass` and `failed` are the
+ * obvious ones; `changed` is NOT a failure, because a visual change is only a
+ * regression if nobody meant it. Every changed shot therefore carries its
+ * before, its after, and its diff, and the answer "the after is correct" is a
+ * first-class outcome that gets recorded (see baseline.mjs `accept`) rather
+ * than a red run someone re-runs until it goes away.
+ *
+ * A new shot has no before, so it cannot regress: it is reported as `added`
+ * and adopted the first time it is seen. A shot whose story disappeared is
+ * `removed` and pruned. Neither blocks.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+/**
+ * @typedef {object} Change
+ * @property {string} key
+ * @property {number} diffPixels
+ * @property {number} diffRatio
+ * @property {boolean} sizeChanged
+ */
+
+/**
+ * Widen an image to the given canvas, transparent-padded from the top left, so
+ * two shots of different heights can still be diffed pixel for pixel.
+ * @param {{width: number, height: number, data: Buffer}} png
+ * @param {number} width
+ * @param {number} height
+ * @param {typeof import('pngjs').PNG} PNG
+ */
+function pad(png, width, height, PNG) {
+ if (png.width === width && png.height === height) return png;
+ const padded = new PNG({width, height});
+ padded.data.fill(0);
+ PNG.bitblt(png, padded, 0, 0, Math.min(png.width, width), Math.min(png.height, height), 0, 0);
+ return padded;
+}
+
+/**
+ * @param {object} options
+ * @param {string} options.baselineDir - directory of baseline PNGs
+ * @param {string} options.currentDir - directory of freshly captured PNGs
+ * @param {object} options.baselineManifest
+ * @param {object} options.currentManifest
+ * @param {string} options.diffDir - where diff PNGs are written
+ * @param {number} options.threshold - pixelmatch per-pixel colour threshold
+ * @param {number} options.maxDiffPixels - pixels allowed to differ before a shot counts as changed
+ * @returns {Promise<{changes: Change[], added: string[], removed: string[], unchanged: string[]}>}
+ */
+export async function compareCaptures({
+ baselineDir,
+ currentDir,
+ baselineManifest,
+ currentManifest,
+ diffDir,
+ threshold,
+ maxDiffPixels,
+}) {
+ const {PNG} = await import('pngjs');
+ const pixelmatch = (await import('pixelmatch')).default;
+
+ const baselineKeys = new Set(Object.keys(baselineManifest.shots ?? {}));
+ const currentKeys = Object.keys(currentManifest.shots ?? {});
+
+ /** @type {Change[]} */
+ const changes = [];
+ /** @type {string[]} */
+ const added = [];
+ /** @type {string[]} */
+ const unchanged = [];
+
+ fs.mkdirSync(diffDir, {recursive: true});
+
+ for (const key of currentKeys) {
+ if (!baselineKeys.has(key)) {
+ added.push(key);
+ continue;
+ }
+ const current = currentManifest.shots[key];
+ const baseline = baselineManifest.shots[key];
+ // The bytes are the cheapest possible comparison and the common case.
+ if (current.sha256 === baseline.sha256) {
+ unchanged.push(key);
+ continue;
+ }
+
+ const baselinePng = PNG.sync.read(fs.readFileSync(path.join(baselineDir, `${key}.png`)));
+ const currentPng = PNG.sync.read(fs.readFileSync(path.join(currentDir, `${key}.png`)));
+ const width = Math.max(baselinePng.width, currentPng.width);
+ const height = Math.max(baselinePng.height, currentPng.height);
+ const sizeChanged = baselinePng.width !== currentPng.width || baselinePng.height !== currentPng.height;
+
+ const a = pad(baselinePng, width, height, PNG);
+ const b = pad(currentPng, width, height, PNG);
+ const diff = new PNG({width, height});
+ const diffPixels = pixelmatch(a.data, b.data, diff.data, width, height, {
+ threshold,
+ includeAA: false,
+ alpha: 0.2,
+ diffMask: false,
+ });
+
+ if (diffPixels <= maxDiffPixels && !sizeChanged) {
+ unchanged.push(key);
+ continue;
+ }
+ fs.writeFileSync(path.join(diffDir, `${key}.png`), PNG.sync.write(diff));
+ changes.push({
+ key,
+ diffPixels,
+ diffRatio: Number((diffPixels / (width * height)).toFixed(6)),
+ sizeChanged,
+ });
+ }
+
+ const removed = [...baselineKeys].filter(key => !currentManifest.shots[key]);
+ changes.sort((a, b) => b.diffPixels - a.diffPixels);
+ return {changes, added, removed, unchanged};
+}
+
+/**
+ * What the DOM said about theming, against what the themes and the components
+ * claim. These are the findings a pixel diff cannot give you: an override that
+ * binds to nothing is invisible in a screenshot precisely because it does
+ * nothing.
+ *
+ * @param {object} options
+ * @param {Record<string, string[]>} options.observedTargets - key → props/states seen in the DOM
+ * @param {Array<{key: string, component: string, props: string[], states: string[]}>} options.targets
+ * @param {Record<string, Record<string, string[]>>} options.themeOverrides - theme → key → override selectors
+ * @returns {{unexercisedOverrides: Array<{theme: string, key: string, selector?: string}>, undeclaredTargets: string[], uncoveredTargets: string[]}}
+ */
+export function analyzeTargeting({observedTargets, targets, themeOverrides}) {
+ const declared = new Set(targets.map(target => target.key));
+ const seen = new Set(Object.keys(observedTargets));
+
+ /** @type {Array<{theme: string, key: string, selector?: string}>} */
+ const unexercisedOverrides = [];
+ for (const [theme, keys] of Object.entries(themeOverrides)) {
+ for (const [key, selectors] of Object.entries(keys)) {
+ if (!seen.has(key)) {
+ unexercisedOverrides.push({theme, key});
+ continue;
+ }
+ const observedData = new Set(observedTargets[key] ?? []);
+ for (const selector of selectors) {
+ // `base` and pseudo-class selectors are not reflected as data; only
+ // variant and state keys can be checked against the DOM.
+ if (selector === 'base' || selector.startsWith(':')) continue;
+ if (!observedData.has(selector)) unexercisedOverrides.push({theme, key, selector});
+ }
+ }
+ }
+
+ return {
+ unexercisedOverrides,
+ undeclaredTargets: [...seen].filter(key => !declared.has(key)).sort(),
+ uncoveredTargets: [...declared].filter(key => !seen.has(key)).sort(),
+ };
+}
+
+/**
+ * The verdict document. The release cron reads `status` and, when it is
+ * `changed`, walks `changes` with the report open.
+ *
+ * @param {object} input
+ * @returns {object}
+ */
+export function buildVerdict({
+ comparison,
+ currentManifest,
+ baselineManifest,
+ targeting,
+ failures,
+ context,
+}) {
+ const changes = comparison.changes.map(change => ({
+ ...change,
+ ...pick(currentManifest.shots[change.key], [
+ 'storyId',
+ 'title',
+ 'name',
+ 'component',
+ 'theme',
+ 'mode',
+ 'reasons',
+ ]),
+ }));
+
+ const status = failures.length > 0 ? 'failed' : changes.length > 0 ? 'changed' : 'pass';
+
+ return {
+ version: 1,
+ status,
+ generatedAt: new Date().toISOString(),
+ context,
+ platform: currentManifest.platform,
+ baseline: {
+ capturedAt: baselineManifest.capturedAt ?? null,
+ sha: baselineManifest.context?.sha ?? null,
+ platform: baselineManifest.platform ?? null,
+ },
+ counts: {
+ total: Object.keys(currentManifest.shots).length,
+ unchanged: comparison.unchanged.length,
+ changed: changes.length,
+ added: comparison.added.length,
+ removed: comparison.removed.length,
+ failed: failures.length,
+ },
+ changes,
+ added: comparison.added,
+ removed: comparison.removed,
+ failures,
+ targeting,
+ };
+}
+
+/**
+ * @param {Record<string, unknown>} source
+ * @param {string[]} keys
+ */
+function pick(source, keys) {
+ return Object.fromEntries(keys.map(key => [key, source?.[key]]));
+}
diff --git a/.github/scripts/visual-gate/lib/compare.test.mjs b/.github/scripts/visual-gate/lib/compare.test.mjs
new file mode 100644
index 0000000000..42c77ada56
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/compare.test.mjs
@@ -0,0 +1,193 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {PNG} from 'pngjs';
+
+import {analyzeTargeting, buildVerdict, compareCaptures} from './compare.mjs';
+
+/** A solid rectangle, so a change is unambiguous. */
+function png(width, height, [r, g, b]) {
+ const image = new PNG({width, height});
+ for (let index = 0; index < image.data.length; index += 4) {
+ image.data[index] = r;
+ image.data[index + 1] = g;
+ image.data[index + 2] = b;
+ image.data[index + 3] = 255;
+ }
+ return PNG.sync.write(image);
+}
+
+let root;
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'visual-gate-'));
+ fs.mkdirSync(path.join(root, 'baseline'), {recursive: true});
+ fs.mkdirSync(path.join(root, 'current'), {recursive: true});
+});
+afterEach(() => fs.rmSync(root, {recursive: true, force: true}));
+
+function write(dir, key, buffer) {
+ fs.writeFileSync(path.join(root, dir, `${key}.png`), buffer);
+}
+
+function manifest(shots) {
+ return {
+ platform: 'linux-arm64',
+ viewport: {width: 100, height: 100},
+ shots: Object.fromEntries(
+ Object.entries(shots).map(([key, value]) => [
+ key,
+ {sha256: value.sha256, width: 10, height: 10, theme: 'neutral', mode: 'light', reasons: ['surface'], ...value},
+ ]),
+ ),
+ };
+}
+
+const compare = (baseline, current) =>
+ compareCaptures({
+ baselineDir: path.join(root, 'baseline'),
+ currentDir: path.join(root, 'current'),
+ baselineManifest: baseline,
+ currentManifest: current,
+ diffDir: path.join(root, 'diff'),
+ threshold: 0.1,
+ maxDiffPixels: 0,
+ });
+
+describe('compareCaptures', () => {
+ it('calls an identical shot unchanged without decoding it', async () => {
+ write('baseline', 'a', png(10, 10, [255, 0, 0]));
+ write('current', 'a', png(10, 10, [255, 0, 0]));
+ const result = await compare(manifest({a: {sha256: 'same'}}), manifest({a: {sha256: 'same'}}));
+ expect(result).toMatchObject({unchanged: ['a'], changes: [], added: [], removed: []});
+ });
+
+ it('reports a changed shot with its pixel count and writes a diff image', async () => {
+ write('baseline', 'a', png(10, 10, [255, 0, 0]));
+ write('current', 'a', png(10, 10, [0, 0, 255]));
+ const result = await compare(manifest({a: {sha256: 'one'}}), manifest({a: {sha256: 'two'}}));
+ expect(result.changes).toHaveLength(1);
+ expect(result.changes[0]).toMatchObject({key: 'a', diffPixels: 100, sizeChanged: false});
+ expect(fs.existsSync(path.join(root, 'diff', 'a.png'))).toBe(true);
+ });
+
+ it('treats a size change as a change even when the shared pixels match', async () => {
+ write('baseline', 'a', png(10, 10, [255, 0, 0]));
+ write('current', 'a', png(10, 20, [255, 0, 0]));
+ const result = await compare(manifest({a: {sha256: 'one'}}), manifest({a: {sha256: 'two'}}));
+ expect(result.changes[0].sizeChanged).toBe(true);
+ });
+
+ it('adopts a shot with no baseline instead of failing it', async () => {
+ write('current', 'new', png(10, 10, [0, 255, 0]));
+ const result = await compare(manifest({}), manifest({new: {sha256: 'x'}}));
+ expect(result).toMatchObject({added: ['new'], changes: []});
+ });
+
+ it('reports a baseline shot whose story is gone as removed', async () => {
+ write('baseline', 'gone', png(10, 10, [0, 255, 0]));
+ const result = await compare(manifest({gone: {sha256: 'x'}}), manifest({}));
+ expect(result.removed).toEqual(['gone']);
+ });
+
+ it('ranks the biggest change first', async () => {
+ write('baseline', 'small', png(10, 10, [255, 0, 0]));
+ write('current', 'small', png(10, 10, [255, 0, 10]));
+ write('baseline', 'big', png(10, 10, [255, 0, 0]));
+ write('current', 'big', png(10, 10, [0, 0, 255]));
+ const before = manifest({small: {sha256: '1'}, big: {sha256: '2'}});
+ const after = manifest({small: {sha256: '3'}, big: {sha256: '4'}});
+ const result = await compare(before, after);
+ expect(result.changes[0].key).toBe('big');
+ });
+});
+
+describe('analyzeTargeting', () => {
+ const targets = [{key: 'button', component: 'Button', props: ['variant:primary'], states: []}];
+
+ it('flags a theme override whose target never rendered', () => {
+ const result = analyzeTargeting({
+ observedTargets: {button: ['variant:primary']},
+ targets,
+ themeOverrides: {y2k: {button: ['base'], 'top-nav-item': ['selected']}},
+ });
+ expect(result.unexercisedOverrides).toEqual([{theme: 'y2k', key: 'top-nav-item'}]);
+ });
+
+ it('flags a state the theme styles but the DOM never reflected', () => {
+ const result = analyzeTargeting({
+ observedTargets: {button: ['variant:primary']},
+ targets,
+ themeOverrides: {y2k: {button: ['base', 'variant:ghost']}},
+ });
+ expect(result.unexercisedOverrides).toEqual([{theme: 'y2k', key: 'button', selector: 'variant:ghost'}]);
+ });
+
+ it('ignores base and pseudo-class selectors, which the DOM cannot confirm', () => {
+ const result = analyzeTargeting({
+ observedTargets: {button: []},
+ targets,
+ themeOverrides: {y2k: {button: ['base', ':hover']}},
+ });
+ expect(result.unexercisedOverrides).toEqual([]);
+ });
+
+ it('separates a documented target nothing rendered from a rendered class nothing documents', () => {
+ const result = analyzeTargeting({
+ observedTargets: {surprise: []},
+ targets,
+ themeOverrides: {},
+ });
+ expect(result).toMatchObject({uncoveredTargets: ['button'], undeclaredTargets: ['surprise']});
+ });
+});
+
+describe('buildVerdict', () => {
+ const base = {
+ currentManifest: manifest({a: {sha256: 'x', component: 'Button'}}),
+ baselineManifest: {capturedAt: 'then', platform: 'linux-arm64'},
+ targeting: {unexercisedOverrides: []},
+ context: {sha: 'abc'},
+ };
+
+ it('is pass when nothing moved', () => {
+ const verdict = buildVerdict({
+ ...base,
+ comparison: {changes: [], added: [], removed: [], unchanged: ['a']},
+ failures: [],
+ });
+ expect(verdict.status).toBe('pass');
+ });
+
+ it('is changed — not failed — when a shot moved', () => {
+ const verdict = buildVerdict({
+ ...base,
+ comparison: {changes: [{key: 'a', diffPixels: 9, diffRatio: 0.1, sizeChanged: false}], added: [], removed: [], unchanged: []},
+ failures: [],
+ });
+ expect(verdict.status).toBe('changed');
+ expect(verdict.changes[0].component).toBe('Button');
+ });
+
+ it('is failed when a shot could not be captured at all', () => {
+ const verdict = buildVerdict({
+ ...base,
+ comparison: {changes: [], added: [], removed: [], unchanged: []},
+ failures: [{key: 'a', error: 'boom'}],
+ });
+ expect(verdict.status).toBe('failed');
+ });
+
+ it('does not fail a run just because shots were added', () => {
+ const verdict = buildVerdict({
+ ...base,
+ comparison: {changes: [], added: ['b'], removed: ['c'], unchanged: []},
+ failures: [],
+ });
+ expect(verdict.status).toBe('pass');
+ expect(verdict.counts).toMatchObject({added: 1, removed: 1});
+ });
+});
diff --git a/.github/scripts/visual-gate/lib/plan.mjs b/.github/scripts/visual-gate/lib/plan.mjs
new file mode 100644
index 0000000000..cfec7ab145
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/plan.mjs
@@ -0,0 +1,313 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The shot plan: which (story, theme, mode) combinations the visual gate
+ * captures, and why each one is in the set.
+ *
+ * @input the Storybook index, the theming-target enumeration
+ * (packages/cli/foundation/discovery/theming-targets.mjs), and the
+ * built theme packages
+ * @output a deterministic, ordered list of shots, each carrying the reason it
+ * exists
+ *
+ * A theme binds to components through theming targets — a class name plus the
+ * variant/state data on it. Nothing in the type system notices when a
+ * component stops rendering the element a theme targets: `astryx theme build`
+ * validates that an override KEY exists, so a renamed class is caught, but an
+ * override that silently stops painting (element moved behind a wrapper, state
+ * no longer reflected, cascade order changed) is invisible until someone looks
+ * at the pixels. That is what this plan aims the camera at.
+ *
+ * Two tiers, both derived rather than hand-listed, so coverage tracks the
+ * system instead of drifting from it:
+ *
+ * theme-matrix — for every component override a theme actually authors, the
+ * components declaring that target, in that theme, light and dark. This is
+ * the targeted net: one shot per (theme, target, component) the system
+ * claims to support.
+ * surface — one representative story per component in the default theme.
+ * The broad net for ordinary visual regressions, and the reason a
+ * component with no theme override still has a before/after.
+ *
+ * `full` widens `surface` to every story in the index; it is the same tier
+ * with the representative-story filter removed.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+/** Storybook globals the preview reads. Keep in sync with apps/storybook/.storybook/preview.tsx. */
+export const MODES = ['light', 'dark'];
+
+/** Story names preferred as a component's representative, most preferred first. */
+const REPRESENTATIVE_NAMES = ['Default', 'Basic', 'Primary', 'Overview', 'Example'];
+
+/** A story carrying this tag is never captured (see visual-gate.config.json for the reasoned list). */
+export const SKIP_TAG = 'no-visual';
+
+/**
+ * @typedef {object} Shot
+ * @property {string} key - stable identity of the shot; also its file name
+ * @property {string} storyId
+ * @property {string} title - Storybook title, for the report
+ * @property {string} name - story name, for the report
+ * @property {string} component - the component this story renders
+ * @property {string} theme
+ * @property {'light'|'dark'} mode
+ * @property {string[]} reasons - why the shot is in the plan
+ */
+
+/**
+ * Read the story entries of a built Storybook index, dropping docs pages and
+ * anything opted out.
+ *
+ * An exclusion may name one story id, or end in `*` to cover a whole story
+ * file — a component whose every story streams live data has no stable story
+ * to fall back to, and excluding them one at a time just promotes the next
+ * unstable one into the plan.
+ *
+ * @param {string} storybookDir
+ * @param {Iterable<string>} excluded - story ids (or `prefix*`) excluded by config
+ * @returns {Array<{id: string, title: string, name: string, component: string, tags: string[]}>}
+ */
+export function readStoryIndex(storybookDir, excluded = []) {
+ const exclusions = [...excluded];
+ const isExcluded = id =>
+ exclusions.some(rule =>
+ rule.endsWith('*') ? id.startsWith(rule.slice(0, -1)) : id === rule,
+ );
+ const indexPath = path.join(storybookDir, 'index.json');
+ if (!fs.existsSync(indexPath)) {
+ throw new Error(
+ `No Storybook index at ${indexPath} — build Storybook first (pnpm storybook:build).`,
+ );
+ }
+ const index = JSON.parse(fs.readFileSync(indexPath, 'utf8'));
+ return Object.values(index.entries ?? {})
+ .filter(entry => entry.type === 'story')
+ .filter(entry => !(entry.tags ?? []).includes(SKIP_TAG))
+ .filter(entry => !isExcluded(entry.id))
+ .map(entry => ({
+ id: entry.id,
+ title: entry.title ?? '',
+ name: entry.name ?? '',
+ component: componentOf(entry),
+ tags: entry.tags ?? [],
+ }));
+}
+
+/**
+ * The component a story renders. `componentPath` is authoritative
+ * (`../../packages/core/src/Button/index.ts` → `Button`); the title's last
+ * segment is the fallback for stories that declare no component.
+ * @param {{componentPath?: string, title?: string}} entry
+ * @returns {string}
+ */
+function componentOf(entry) {
+ const fromPath = entry.componentPath?.match(/\/src\/([^/]+)\//)?.[1];
+ if (fromPath) return fromPath;
+ const segments = (entry.title ?? '').split('/');
+ return segments[segments.length - 1] ?? '';
+}
+
+/**
+ * One story per component: the first match against REPRESENTATIVE_NAMES, else
+ * the first story in index order (which is source order, so it is stable).
+ * @param {ReturnType<typeof readStoryIndex>} stories
+ * @returns {Map<string, (typeof stories)[number]>}
+ */
+export function representativeStories(stories) {
+ /** @type {Map<string, (typeof stories)[number]>} */
+ const byComponent = new Map();
+ for (const story of stories) {
+ if (!story.component) continue;
+ const current = byComponent.get(story.component);
+ if (!current || rank(story.name) < rank(current.name)) byComponent.set(story.component, story);
+ }
+ return byComponent;
+}
+
+/**
+ * @param {string} name
+ * @returns {number}
+ */
+function rank(name) {
+ const index = REPRESENTATIVE_NAMES.indexOf(name);
+ return index === -1 ? REPRESENTATIVE_NAMES.length : index;
+}
+
+/**
+ * Build the plan.
+ *
+ * @param {object} options
+ * @param {ReturnType<typeof readStoryIndex>} options.stories
+ * @param {import('../../../../packages/cli/foundation/discovery/theming-targets.mjs').ThemingTarget[]} options.targets
+ * @param {Record<string, Record<string, string[]>>} options.themeOverrides - theme → component key → override selectors
+ * @param {Record<string, Record<string, string[]>>} [options.observations] - story id → targets it rendered, from a scout pass
+ * @param {string} options.defaultTheme
+ * @param {string[]} options.tiers - any of 'theme-matrix', 'surface', 'full'
+ * @returns {Shot[]}
+ */
+export function buildPlan({stories, targets, themeOverrides, observations, defaultTheme, tiers}) {
+ /** @type {Map<string, Shot>} */
+ const shots = new Map();
+ const representatives = representativeStories(stories);
+
+ /** @param {Omit<Shot, 'key' | 'reasons'>} shot @param {string} reason */
+ const add = (shot, reason) => {
+ const key = shotKey(shot);
+ const existing = shots.get(key);
+ if (existing) {
+ if (!existing.reasons.includes(reason)) existing.reasons.push(reason);
+ return;
+ }
+ shots.set(key, {...shot, key, reasons: [reason]});
+ };
+
+ if (tiers.includes('surface') || tiers.includes('full')) {
+ const subject = tiers.includes('full') ? stories : [...representatives.values()];
+ for (const story of subject) {
+ for (const mode of MODES) {
+ add({...toShotBase(story), theme: defaultTheme, mode}, 'surface');
+ }
+ }
+ }
+
+ if (tiers.includes('theme-matrix')) {
+ for (const shot of themeMatrix({stories, targets, themeOverrides, observations})) {
+ add(shot.shot, shot.reason);
+ }
+ }
+
+ return [...shots.values()].sort((a, b) => a.key.localeCompare(b.key));
+}
+
+/**
+ * The targeted net: for every selector a theme overrides, one story that
+ * actually renders it.
+ *
+ * Selection is a small greedy set cover per (theme, target key). A component's
+ * "Variants" story usually renders every variant at once, so covering the six
+ * `badge` overrides costs one shot rather than six — and a selector no story
+ * renders is simply left uncovered, where the report can name it, instead of
+ * being papered over with the default story.
+ *
+ * With no observations (no scout pass), it falls back to the component's
+ * representative story: coverage is thinner, but the matrix still exists.
+ *
+ * @param {object} options
+ * @param {ReturnType<typeof readStoryIndex>} options.stories
+ * @param {Array<{key: string, component: string}>} options.targets
+ * @param {Record<string, Record<string, string[]>>} options.themeOverrides
+ * @param {Record<string, Record<string, string[]>>} [options.observations]
+ * @returns {Array<{shot: Omit<Shot, 'key'|'reasons'>, reason: string}>}
+ */
+function themeMatrix({stories, targets, themeOverrides, observations}) {
+ const componentsByKey = new Map();
+ for (const target of targets) {
+ if (!componentsByKey.has(target.key)) componentsByKey.set(target.key, new Set());
+ componentsByKey.get(target.key).add(target.component);
+ }
+ const representatives = representativeStories(stories);
+ const storiesByComponent = new Map();
+ for (const story of stories) {
+ if (!storiesByComponent.has(story.component)) storiesByComponent.set(story.component, []);
+ storiesByComponent.get(story.component).push(story);
+ }
+
+ const planned = [];
+ for (const [theme, keys] of Object.entries(themeOverrides)) {
+ for (const [key, selectors] of Object.entries(keys)) {
+ for (const component of componentsByKey.get(key) ?? []) {
+ for (const story of chooseStories({
+ candidates: storiesByComponent.get(component) ?? [],
+ fallback: representatives.get(component),
+ key,
+ selectors,
+ observations,
+ })) {
+ for (const mode of MODES) {
+ planned.push({
+ shot: {...toShotBase(story), theme, mode},
+ reason: `theme:${theme}:${key}`,
+ });
+ }
+ }
+ }
+ }
+ }
+ return planned;
+}
+
+/**
+ * @param {object} options
+ * @param {ReturnType<typeof readStoryIndex>} options.candidates
+ * @param {ReturnType<typeof readStoryIndex>[number] | undefined} options.fallback
+ * @param {string} options.key
+ * @param {string[]} options.selectors
+ * @param {Record<string, Record<string, string[]>>} [options.observations]
+ */
+function chooseStories({candidates, fallback, key, selectors, observations}) {
+ if (!observations) return fallback ? [fallback] : [];
+
+ const renders = story => Boolean(observations[story.id]?.[key]);
+ const rendering = candidates.filter(renders);
+ if (rendering.length === 0) return [];
+
+ // `base` and pseudo-class overrides need no particular state — any story
+ // rendering the target proves they had something to bind to.
+ const wanted = new Set(
+ selectors.filter(selector => selector !== 'base' && !selector.startsWith(':')),
+ );
+ const chosen = [];
+ const covers = story => new Set(observations[story.id]?.[key] ?? []);
+
+ while (wanted.size > 0) {
+ let best = null;
+ let bestCount = 0;
+ for (const story of rendering) {
+ const count = [...covers(story)].filter(selector => wanted.has(selector)).length;
+ if (count > bestCount) {
+ best = story;
+ bestCount = count;
+ }
+ }
+ if (!best) break;
+ chosen.push(best);
+ for (const selector of covers(best)) wanted.delete(selector);
+ }
+
+ // Always keep one plain shot of the target, for `base` and for the case
+ // where every override is a pseudo-class.
+ if (chosen.length === 0) chosen.push(rendering.find(renders) ?? rendering[0]);
+ return [...new Set(chosen)];
+}
+
+/** @param {ReturnType<typeof readStoryIndex>[number]} story */
+function toShotBase(story) {
+ return {storyId: story.id, title: story.title, name: story.name, component: story.component};
+}
+
+/**
+ * Shot identity. Doubles as the PNG file name, so it stays filesystem-safe and
+ * stable across runs — a baseline is only comparable if its key is.
+ * @param {{storyId: string, theme: string, mode: string}} shot
+ * @returns {string}
+ */
+export function shotKey({storyId, theme, mode}) {
+ return `${storyId}__${theme}-${mode}`.replace(/[^a-zA-Z0-9._-]/g, '_');
+}
+
+/**
+ * Theming targets declared by components but never reachable through the plan
+ * — the coverage gap in what the camera can see.
+ * @param {import('../../../../packages/cli/foundation/discovery/theming-targets.mjs').ThemingTarget[]} targets
+ * @param {Shot[]} plan
+ * @returns {Array<{key: string, component: string}>}
+ */
+export function uncoveredTargets(targets, plan) {
+ const photographed = new Set(plan.map(shot => shot.component));
+ return targets
+ .filter(target => !photographed.has(target.component))
+ .map(target => ({key: target.key, component: target.component}));
+}
diff --git a/.github/scripts/visual-gate/lib/plan.test.mjs b/.github/scripts/visual-gate/lib/plan.test.mjs
new file mode 100644
index 0000000000..135e8bb57d
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/plan.test.mjs
@@ -0,0 +1,129 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+import {describe, expect, it} from 'vitest';
+
+import {buildPlan, readStoryIndex, representativeStories, shotKey, uncoveredTargets} from './plan.mjs';
+
+const stories = [
+ {id: 'core-button--primary', title: 'Core/Button', name: 'Primary', component: 'Button', tags: []},
+ {id: 'core-button--default', title: 'Core/Button', name: 'Default', component: 'Button', tags: []},
+ {id: 'core-badge--solid', title: 'Core/Badge', name: 'Solid', component: 'Badge', tags: []},
+];
+
+const targets = [
+ {key: 'button', className: 'astryx-button', component: 'Button', props: ['variant:primary'], states: []},
+ {key: 'badge', className: 'astryx-badge', component: 'Badge', props: [], states: []},
+ {key: 'tooltip', className: 'astryx-tooltip', component: 'Tooltip', props: [], states: []},
+];
+
+const themeOverrides = {
+ neutral: {button: ['base']},
+ y2k: {button: ['base', 'variant:primary'], badge: ['base']},
+};
+
+describe('representativeStories', () => {
+ it('prefers a conventionally named story over source order', () => {
+ expect(representativeStories(stories).get('Button').id).toBe('core-button--default');
+ });
+
+ it('falls back to the first story when no name is conventional', () => {
+ expect(representativeStories(stories).get('Badge').id).toBe('core-badge--solid');
+ });
+});
+
+describe('buildPlan', () => {
+ it('photographs one story per component in the default theme for the surface tier', () => {
+ const plan = buildPlan({stories, targets, themeOverrides, defaultTheme: 'neutral', tiers: ['surface']});
+ expect(plan.map(shot => shot.key).sort()).toEqual([
+ 'core-badge--solid__neutral-dark',
+ 'core-badge--solid__neutral-light',
+ 'core-button--default__neutral-dark',
+ 'core-button--default__neutral-light',
+ ]);
+ });
+
+ it('adds a shot for every theme that overrides a component the story renders', () => {
+ const plan = buildPlan({stories, targets, themeOverrides, defaultTheme: 'neutral', tiers: ['theme-matrix']});
+ const y2k = plan.filter(shot => shot.theme === 'y2k').map(shot => shot.key);
+ expect(y2k).toContain('core-button--default__y2k-light');
+ expect(y2k).toContain('core-badge--solid__y2k-dark');
+ });
+
+ it('records why a shot is in the plan, merging the reasons of a shot both tiers want', () => {
+ const plan = buildPlan({stories, targets, themeOverrides, defaultTheme: 'neutral', tiers: ['surface', 'theme-matrix']});
+ const shot = plan.find(candidate => candidate.key === 'core-button--default__neutral-light');
+ expect(shot.reasons).toEqual(['surface', 'theme:neutral:button']);
+ });
+
+ it('captures every story, not just the representative, in the full tier', () => {
+ const plan = buildPlan({stories, targets, themeOverrides, defaultTheme: 'neutral', tiers: ['full']});
+ expect(plan.filter(shot => shot.component === 'Button' && shot.mode === 'light')).toHaveLength(2);
+ });
+
+ it('skips a target whose component has no story rather than planning an unshootable shot', () => {
+ const plan = buildPlan({
+ stories,
+ targets,
+ themeOverrides: {gothic: {tooltip: ['base']}},
+ defaultTheme: 'neutral',
+ tiers: ['theme-matrix'],
+ });
+ expect(plan).toEqual([]);
+ });
+
+ it('is deterministic — same input, same order', () => {
+ const args = {stories, targets, themeOverrides, defaultTheme: 'neutral', tiers: ['surface', 'theme-matrix']};
+ expect(buildPlan(args)).toEqual(buildPlan(args));
+ });
+});
+
+describe('shotKey', () => {
+ it('stays filesystem-safe', () => {
+ expect(shotKey({storyId: 'core-a/b--c d', theme: 'y2k', mode: 'light'})).toBe('core-a_b--c_d__y2k-light');
+ });
+});
+
+describe('readStoryIndex exclusions', () => {
+ const index = {
+ entries: {
+ a: {type: 'story', id: 'lab-stream--one', title: 'Lab/Stream', name: 'One', tags: []},
+ b: {type: 'story', id: 'lab-stream--two', title: 'Lab/Stream', name: 'Two', tags: []},
+ c: {type: 'story', id: 'core-button--default', title: 'Core/Button', name: 'Default', tags: []},
+ d: {type: 'docs', id: 'core-button--docs', title: 'Core/Button', name: 'Docs', tags: []},
+ e: {type: 'story', id: 'core-thing--skipped', title: 'Core/Thing', name: 'S', tags: ['no-visual']},
+ },
+ };
+
+ const read = exclusions => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'visual-index-'));
+ fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify(index));
+ try {
+ return readStoryIndex(dir, exclusions).map(story => story.id);
+ } finally {
+ fs.rmSync(dir, {recursive: true, force: true});
+ }
+ };
+
+ it('drops docs entries and stories tagged out', () => {
+ expect(read([])).toEqual(['lab-stream--one', 'lab-stream--two', 'core-button--default']);
+ });
+
+ it('drops one story by id', () => {
+ expect(read(['lab-stream--one'])).not.toContain('lab-stream--one');
+ });
+
+ it('drops a whole story file with a trailing star', () => {
+ expect(read(['lab-stream--*'])).toEqual(['core-button--default']);
+ });
+});
+
+describe('uncoveredTargets', () => {
+ it('names targets no shot can reach', () => {
+ const plan = buildPlan({stories, targets, themeOverrides, defaultTheme: 'neutral', tiers: ['surface']});
+ expect(uncoveredTargets(targets, plan)).toEqual([{key: 'tooltip', component: 'Tooltip'}]);
+ });
+});
diff --git a/.github/scripts/visual-gate/lib/report.mjs b/.github/scripts/visual-gate/lib/report.mjs
new file mode 100644
index 0000000000..865cefd25d
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/report.mjs
@@ -0,0 +1,222 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The report a human (or the release cron) actually looks at.
+ *
+ * @input a verdict and the three image sets it refers to
+ * @output one self-contained index.html
+ *
+ * The report exists to make one judgement fast: for each changed shot, is the
+ * AFTER the correct picture? So every change shows before, after and diff
+ * together, defaults to a wipe between before and after (the view that makes a
+ * 3px shift obvious), and carries the exact command that records "yes, the
+ * after is right". No build step and no CDN: it is copied onto gh-pages as-is
+ * and has to render from a file:// path too.
+ */
+
+/** @param {unknown} value */
+function escapeHtml(value) {
+ return String(value ?? '').replace(
+ /[&<>"']/g,
+ character =>
+ ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'})[character],
+ );
+}
+
+/** @param {import('./compare.mjs').Change & Record<string, any>} change */
+function changeSection(change) {
+ const key = escapeHtml(change.key);
+ const reasons = (change.reasons ?? [])
+ .map(reason => `<span class="tag">${escapeHtml(reason)}</span>`)
+ .join(' ');
+ return `
+<section class="change" id="${key}">
+ <header>
+ <h3>${escapeHtml(change.component || change.title)} <span class="muted">·</span> ${escapeHtml(change.name)}</h3>
+ <div class="meta">
+ <span class="chip">${escapeHtml(change.theme)}</span>
+ <span class="chip">${escapeHtml(change.mode)}</span>
+ <span class="muted">${change.diffPixels.toLocaleString()} px (${(change.diffRatio * 100).toFixed(3)}%)</span>
+ ${change.sizeChanged ? '<span class="chip warn">size changed</span>' : ''}
+ ${reasons}
+ </div>
+ </header>
+ <div class="views" data-key="${key}">
+ <div class="tabs">
+ <button data-view="wipe" class="active">Wipe</button>
+ <button data-view="before">Before</button>
+ <button data-view="after">After</button>
+ <button data-view="diff">Diff</button>
+ <button data-view="side">Side by side</button>
+ </div>
+ <div class="stage" data-view="wipe">
+ <div class="wipe">
+ <img class="after" src="after/${key}.png" alt="after">
+ <div class="before-clip"><img class="before" src="before/${key}.png" alt="before"></div>
+ <input type="range" min="0" max="100" value="50" aria-label="wipe between before and after">
+ </div>
+ <div class="single before"><img src="before/${key}.png" alt="before"></div>
+ <div class="single after"><img src="after/${key}.png" alt="after"></div>
+ <div class="single diff"><img src="diff/${key}.png" alt="diff"></div>
+ <div class="side">
+ <figure><figcaption>Before</figcaption><img src="before/${key}.png" alt="before"></figure>
+ <figure><figcaption>After</figcaption><img src="after/${key}.png" alt="after"></figure>
+ <figure><figcaption>Diff</figcaption><img src="diff/${key}.png" alt="diff"></figure>
+ </div>
+ </div>
+ </div>
+ <footer><code>${key}</code></footer>
+</section>`;
+}
+
+/** @param {string[]} keys @param {string} title @param {string} note */
+function keyList(keys, title, note) {
+ if (keys.length === 0) return '';
+ return `
+<section class="list">
+ <h2>${escapeHtml(title)} <span class="muted">(${keys.length})</span></h2>
+ <p class="muted">${escapeHtml(note)}</p>
+ <ul>${keys.map(key => `<li><code>${escapeHtml(key)}</code></li>`).join('')}</ul>
+</section>`;
+}
+
+/** @param {object} targeting */
+function targetingSection(targeting) {
+ const rows = [
+ [
+ 'Theme overrides that bound to nothing',
+ 'A theme styles this target, but no shot in this run rendered it. Either the plan cannot reach it, or the component stopped rendering the target the theme aims at.',
+ (targeting.unexercisedOverrides ?? []).map(
+ finding =>
+ `${finding.theme} → ${finding.key}${finding.selector ? ` (${finding.selector})` : ''}`,
+ ),
+ ],
+ [
+ 'Declared targets never seen',
+ 'Documented as themeable, absent from every shot. A coverage gap, not necessarily a bug.',
+ targeting.uncoveredTargets ?? [],
+ ],
+ [
+ 'Rendered but undeclared',
+ 'An astryx-* class in the DOM that no component doc declares as a theming target.',
+ targeting.undeclaredTargets ?? [],
+ ],
+ ].filter(([, , items]) => items.length > 0);
+
+ if (rows.length === 0) {
+ return '<section class="list"><h2>Theming targets</h2><p class="ok">Every theme override bound to a rendered target.</p></section>';
+ }
+ return rows
+ .map(
+ ([title, note, items]) => `
+<section class="list">
+ <h2>${escapeHtml(title)} <span class="muted">(${items.length})</span></h2>
+ <p class="muted">${escapeHtml(note)}</p>
+ <ul>${items.map(item => `<li><code>${escapeHtml(item)}</code></li>`).join('')}</ul>
+</section>`,
+ )
+ .join('');
+}
+
+/**
+ * @param {object} verdict
+ * @param {{acceptHint?: string}} [options]
+ * @returns {string}
+ */
+export function renderReport(verdict, options = {}) {
+ const {counts, status} = verdict;
+ const acceptHint =
+ options.acceptHint ??
+ 'node .github/scripts/visual-gate/gate.mjs accept --keys <key,key> --reason "<why the after is correct>"';
+
+ return `<!doctype html>
+<html lang="en">
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Visual gate — ${escapeHtml(status)}</title>
+<style>
+ :root { color-scheme: light dark; --line: color-mix(in oklab, currentColor 15%, transparent); }
+ body { font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 0; padding: 24px; max-width: 1200px; }
+ h1 { font-size: 20px; margin: 0 0 4px; }
+ h2 { font-size: 15px; margin: 32px 0 4px; }
+ h3 { font-size: 14px; margin: 0; }
+ .muted { opacity: .6; }
+ .ok { color: #1a7f37; }
+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
+ .status { display: inline-block; padding: 2px 10px; border-radius: 999px; font-weight: 600; }
+ .status.pass { background: #1a7f3722; color: #1a7f37; }
+ .status.changed { background: #9a670022; color: #9a6700; }
+ .status.failed { background: #cf222e22; color: #cf222e; }
+ .summary { display: flex; gap: 16px; flex-wrap: wrap; margin: 12px 0 8px; }
+ .summary div { border: 1px solid var(--line); border-radius: 8px; padding: 8px 12px; min-width: 84px; }
+ .summary b { display: block; font-size: 18px; }
+ .howto { border: 1px solid var(--line); border-radius: 8px; padding: 12px 16px; margin: 16px 0; }
+ .change { border: 1px solid var(--line); border-radius: 10px; padding: 16px; margin: 16px 0; }
+ .change header { display: flex; justify-content: space-between; gap: 16px; flex-wrap: wrap; align-items: baseline; }
+ .meta { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
+ .chip, .tag { border: 1px solid var(--line); border-radius: 999px; padding: 1px 8px; font-size: 12px; }
+ .tag { opacity: .7; }
+ .chip.warn { border-color: #9a6700; color: #9a6700; }
+ .tabs { display: flex; gap: 4px; margin: 12px 0 8px; }
+ .tabs button { font: inherit; font-size: 12px; padding: 3px 10px; border-radius: 6px; border: 1px solid var(--line); background: transparent; cursor: pointer; }
+ .tabs button.active { background: color-mix(in oklab, currentColor 12%, transparent); font-weight: 600; }
+ .stage img { max-width: 100%; display: block; border: 1px solid var(--line); border-radius: 6px; background: #fff; }
+ .stage > div { display: none; }
+ .stage[data-view="wipe"] .wipe, .stage[data-view="before"] .single.before,
+ .stage[data-view="after"] .single.after, .stage[data-view="diff"] .single.diff,
+ .stage[data-view="side"] .side { display: block; }
+ .side { display: none; grid-template-columns: repeat(3, 1fr); gap: 12px; }
+ .stage[data-view="side"] .side { display: grid; }
+ .side figure { margin: 0; }
+ .side figcaption { font-size: 12px; opacity: .6; margin-bottom: 4px; }
+ .wipe { position: relative; }
+ .wipe .before-clip { position: absolute; inset: 0; overflow: hidden; width: 50%; }
+ .wipe .before-clip img { max-width: none; }
+ .wipe input { position: absolute; left: 0; right: 0; bottom: -6px; width: 100%; }
+ .list ul { margin: 4px 0; padding-left: 20px; }
+ footer code { opacity: .5; }
+</style>
+<h1>Visual gate <span class="status ${escapeHtml(status)}">${escapeHtml(status)}</span></h1>
+<p class="muted">
+ ${escapeHtml(verdict.context?.sha ?? 'unknown commit')} on ${escapeHtml(verdict.platform ?? '?')}
+ · baseline ${escapeHtml(verdict.baseline?.sha ?? 'none')}
+ · ${escapeHtml(verdict.generatedAt)}
+</p>
+<div class="summary">
+ <div><b>${counts.total}</b>shots</div>
+ <div><b>${counts.changed}</b>changed</div>
+ <div><b>${counts.added}</b>added</div>
+ <div><b>${counts.removed}</b>removed</div>
+ <div><b>${counts.failed}</b>failed</div>
+</div>
+<div class="howto">
+ <b>Changed is not the same as broken.</b> For each change below, decide whether the <em>after</em> is the picture you want.
+ If it is, promote it — that is a valid, recorded outcome:
+ <p><code>${escapeHtml(acceptHint)}</code></p>
+ If it is not, the change is a regression: fix it before the release goes out.
+</div>
+${verdict.failures?.length ? `<section class="list"><h2>Failed to capture <span class="muted">(${verdict.failures.length})</span></h2><ul>${verdict.failures
+ .map(f => `<li><code>${escapeHtml(f.key)}</code> — ${escapeHtml(f.error)}</li>`)
+ .join('')}</ul></section>` : ''}
+${verdict.changes.length ? `<h2>Changed (${verdict.changes.length})</h2>` : '<p class="ok">No shot changed against the baseline.</p>'}
+${verdict.changes.map(changeSection).join('')}
+${keyList(verdict.added ?? [], 'Added', 'New shots with no baseline to regress against — adopted on the next promotion.')}
+${keyList(verdict.removed ?? [], 'Removed', 'Baseline shots whose story no longer exists.')}
+${targetingSection(verdict.targeting ?? {})}
+<script>
+ for (const views of document.querySelectorAll('.views')) {
+ const stage = views.querySelector('.stage');
+ views.querySelectorAll('.tabs button').forEach((button) => {
+ button.addEventListener('click', () => {
+ views.querySelectorAll('.tabs button').forEach((b) => b.classList.toggle('active', b === button));
+ stage.dataset.view = button.dataset.view;
+ });
+ });
+ const range = views.querySelector('.wipe input');
+ const clip = views.querySelector('.before-clip');
+ range?.addEventListener('input', () => { clip.style.width = range.value + '%'; });
+ }
+</script>
+</html>
+`;
+}
diff --git a/.github/scripts/visual-gate/lib/sources.mjs b/.github/scripts/visual-gate/lib/sources.mjs
new file mode 100644
index 0000000000..354cad354b
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/sources.mjs
@@ -0,0 +1,89 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Where the gate gets its facts: the theming targets components declare,
+ * and the component overrides themes actually author.
+ *
+ * @input the repo
+ * @output the two enumerations the plan and the targeting analysis are built
+ * from
+ *
+ * Both come from the same places the product does — `collectThemingTargets`
+ * is the CLI's own enumeration (the one `astryx theme targets` prints and
+ * `astryx theme build` validates against), and theme overrides are read out of
+ * the built theme packages rather than parsed out of their source. Nothing
+ * here is a second registry: if the gate and the compiler ever disagree about
+ * what is themeable, that is a bug in one shared function, not a drift between
+ * two lists.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {pathToFileURL} from 'node:url';
+
+/**
+ * @param {string} repoRoot
+ * @returns {Promise<import('../../../../packages/cli/foundation/discovery/theming-targets.mjs').ThemingTarget[]>}
+ */
+export async function loadThemingTargets(repoRoot) {
+ const module = await import(
+ pathToFileURL(
+ path.join(repoRoot, 'packages/cli/foundation/discovery/theming-targets.mjs'),
+ ).href
+ );
+ return module.collectThemingTargets(path.join(repoRoot, 'packages/core/src'));
+}
+
+/**
+ * Every shipped theme's component overrides, as theme name → target key →
+ * the selectors it styles (`base`, `variant:primary`, `selected`, …).
+ *
+ * Reads the built packages: a theme's `components` map is the product of
+ * `defineTheme`, not a literal in its source, so the built artifact is the
+ * only honest answer.
+ *
+ * @param {string} repoRoot
+ * @returns {Promise<Record<string, Record<string, string[]>>>}
+ */
+export async function loadThemeOverrides(repoRoot) {
+ const themesDir = path.join(repoRoot, 'packages/themes');
+ /** @type {Record<string, Record<string, string[]>>} */
+ const overrides = {};
+
+ for (const entry of fs.readdirSync(themesDir, {withFileTypes: true}).sort()) {
+ if (!entry.isDirectory()) continue;
+ const built = path.join(themesDir, entry.name, 'dist/source.mjs');
+ if (!fs.existsSync(built)) {
+ throw new Error(
+ `Theme ${entry.name} is not built (${built} missing) — run pnpm build before the visual gate.`,
+ );
+ }
+ const module = await import(pathToFileURL(built).href);
+ const theme = Object.values(module).find(value => value?.name && value?.components);
+ if (!theme) continue;
+ overrides[theme.name] = Object.fromEntries(
+ Object.entries(theme.components).map(([key, styles]) => [key, Object.keys(styles ?? {})]),
+ );
+ }
+
+ return overrides;
+}
+
+/**
+ * @param {string} repoRoot
+ * @returns {{excludeStories: Record<string, string>, viewport: {width: number, height: number}, settleMs: number, threshold: number, maxDiffPixels: number, defaultTheme: string, tiers: string[]}}
+ */
+export function loadConfig(repoRoot) {
+ const defaults = {
+ excludeStories: {},
+ viewport: {width: 1024, height: 768},
+ settleMs: 50,
+ threshold: 0.1,
+ maxDiffPixels: 0,
+ defaultTheme: 'neutral',
+ tiers: ['surface', 'theme-matrix'],
+ };
+ const configPath = path.join(repoRoot, '.github/scripts/visual-gate/visual-gate.config.json');
+ if (!fs.existsSync(configPath)) return defaults;
+ return {...defaults, ...JSON.parse(fs.readFileSync(configPath, 'utf8'))};
+}
diff --git a/.github/scripts/visual-gate/lib/theme-matrix.test.mjs b/.github/scripts/visual-gate/lib/theme-matrix.test.mjs
new file mode 100644
index 0000000000..7da788effe
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/theme-matrix.test.mjs
@@ -0,0 +1,66 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+
+import {buildPlan} from './plan.mjs';
+
+const stories = [
+ {id: 'core-badge--default', title: 'Core/Badge', name: 'Default', component: 'Badge', tags: []},
+ {id: 'core-badge--variants', title: 'Core/Badge', name: 'Variants', component: 'Badge', tags: []},
+ {id: 'core-badge--error', title: 'Core/Badge', name: 'Error', component: 'Badge', tags: []},
+];
+
+const targets = [{key: 'badge', className: 'astryx-badge', component: 'Badge', props: [], states: []}];
+
+const themeOverrides = {
+ butter: {badge: ['base', 'variant:success', 'variant:warning', 'variant:error']},
+};
+
+const observations = {
+ 'core-badge--default': {badge: []},
+ 'core-badge--variants': {badge: ['variant:success', 'variant:warning']},
+ 'core-badge--error': {badge: ['variant:error']},
+};
+
+const matrix = extra =>
+ buildPlan({
+ stories,
+ targets,
+ themeOverrides,
+ defaultTheme: 'neutral',
+ tiers: ['theme-matrix'],
+ ...extra,
+ });
+
+describe('theme matrix with scout observations', () => {
+ it('picks the stories that actually render the overridden states', () => {
+ const ids = [...new Set(matrix({observations}).map(shot => shot.storyId))].sort();
+ expect(ids).toEqual(['core-badge--error', 'core-badge--variants']);
+ });
+
+ it('covers several overrides with one story when one story renders them all', () => {
+ const plan = matrix({observations});
+ const variants = plan.filter(shot => shot.storyId === 'core-badge--variants' && shot.mode === 'light');
+ expect(variants).toHaveLength(1);
+ });
+
+ it('leaves an override no story renders uncovered rather than photographing the default', () => {
+ const plan = matrix({
+ observations: {'core-badge--default': {badge: []}},
+ });
+ expect(plan.map(shot => shot.storyId)).toEqual(['core-badge--default', 'core-badge--default']);
+ });
+
+ it('skips a component whose stories never render the target at all', () => {
+ expect(matrix({observations: {'core-badge--default': {}}})).toEqual([]);
+ });
+
+ it('falls back to the representative story when no scout ran', () => {
+ const ids = [...new Set(matrix({}).map(shot => shot.storyId))];
+ expect(ids).toEqual(['core-badge--default']);
+ });
+
+ it('is deterministic across runs', () => {
+ expect(matrix({observations})).toEqual(matrix({observations}));
+ });
+});
diff --git a/.github/scripts/visual-gate/visual-gate.config.json b/.github/scripts/visual-gate/visual-gate.config.json
new file mode 100644
index 0000000000..00e034e74d
--- /dev/null
+++ b/.github/scripts/visual-gate/visual-gate.config.json
@@ -0,0 +1,15 @@
+{
+ "$comment": "Configuration for .github/scripts/visual-gate. Every excludeStories entry needs the reason the story cannot reproduce itself — the list stays reviewable instead of growing quietly, and `gate.mjs flaky` is how entries are found (run it, do not guess). A key ending in * covers a whole story file.",
+ "defaultTheme": "neutral",
+ "tiers": ["surface", "theme-matrix"],
+ "viewport": {"width": 1024, "height": 768},
+ "settleMs": 50,
+ "threshold": 0.1,
+ "maxDiffPixels": 0,
+ "excludeStories": {
+ "lab-chartstreamgl--*": "Streams live data on a setInterval; every frame is a different chart.",
+ "lab-chartstreamperf--*": "Renders measured fps and frame times, which differ every run by construction.",
+ "lab-codeeditorperf--*": "Renders performance.now() mount timings on screen.",
+ "lab-usechartrange--*": "Advances its own domain on a setInterval while the shot is taken."
+ }
+}
diff --git a/.github/workflows/cleanup-previews.yml b/.github/workflows/cleanup-previews.yml
index ffa5b0d1d1..e682e5e89d 100644
--- a/.github/workflows/cleanup-previews.yml
+++ b/.github/workflows/cleanup-previews.yml
@@ -77,6 +77,11 @@ jobs:
# /sandbox/ — stable (managed by deploy.yml, never cleaned)
# /pr/<number>/ — PR previews (cleaned when PR closes)
# /reports/ — vibe test reports (never cleaned)
+ # /visual-gate/ — visual baseline + gate reports (never cleaned
+ # here; release-gate.yml prunes its own old runs,
+ # and the baseline under visual-gate/baseline/ is
+ # the reference the gate compares against — losing
+ # it silently disarms visual regression testing)
# /assets/ — landing page CSS (never cleaned)
# /index.html — landing page (never cleaned)
# /latest — deploy hash pointer (never cleaned)
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index b96b4302be..8f3ff9b049 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -338,10 +338,18 @@ jobs:
# full rationale:
# --filter=blob:none → clone fetches trees but NO file contents
# sparse-checkout → only the stable paths are materialized;
- # /pr/ & /reports/ stay in the index as
- # skip-worktree entries (never written out)
+ # every other path (/pr/, /reports/,
+ # /visual-gate/) stays in the index as a
+ # skip-worktree entry (never written out)
# git write-tree → rebuilds the full tree from the index, so
- # /pr/ & /reports/ are reused by SHA
+ # those paths are reused by SHA
+ #
+ # This is an allow-BY-DEFAULT mechanism: anything outside the cone
+ # below survives automatically. Adding a path to the sparse-checkout
+ # set makes it a MANAGED path, wiped and republished each deploy — so
+ # never add a path that another workflow owns. /visual-gate/ holds the
+ # visual-regression baseline (owned by visual-baseline.yml); wiping it
+ # would silently disarm the release gate.
# commit-tree (no -p) → one ORPHAN commit == force_orphan, produced
# without a full local copy of gh-pages
REPO_URL="https://x-access-token:${GITHUB_TOKEN}@github.com/${{ github.repository }}.git"
@@ -375,9 +383,9 @@ jobs:
cp -r "$WORK_DIR"/staged/. ./
touch .nojekyll
- # git add -A respects skip-worktree, so /pr/ & /reports/ are NOT
- # staged for deletion — they stay in the index and are carried
- # forward by write-tree.
+ # git add -A respects skip-worktree, so /pr/, /reports/ and
+ # /visual-gate/ are NOT staged for deletion — they stay in the
+ # index and are carried forward by write-tree.
git add -A
if git diff --cached --quiet; then
echo "Nothing to publish"; echo "::endgroup::"; exit 0
diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml
new file mode 100644
index 0000000000..73a4e54030
--- /dev/null
+++ b/.github/workflows/release-gate.yml
@@ -0,0 +1,287 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+
+# Release gate — the checks a release must clear, run before the daily cut.
+#
+# Two of them, and they answer different questions:
+# visual — did anything on screen change, in any theme, since the last
+# accepted baseline? (.github/scripts/visual-gate)
+# a11y — did any NEW accessibility violation appear against the baseline?
+# (the same full-suite audit a11y-weekly runs, run daily here)
+#
+# Why this is not in ci.yml: capturing several hundred screenshots and running
+# axe over every story costs ~15 minutes, which is the wrong tax on every push
+# to every PR. It runs once a day instead, at 07:10 PT — fifty minutes before
+# the 08:00 PT release cut — so the release has a fresh verdict to read, and on
+# demand for anyone who wants one sooner.
+#
+# THE VERDICT IS ADVICE WITH TEETH, NOT A VETO. `changed` is not `failed`: a
+# visual change is only a regression if nobody meant it. The release cut reads
+# verdict.json, opens the report (before / after / diff per shot), and decides
+# per change — "the after is correct" is a valid outcome, recorded by promoting
+# that shot through visual-baseline.yml. What must never happen is a release
+# going out through a diff nobody looked at.
+#
+# Consumed by the release cron as:
+# https://facebook.github.io/astryx/visual-gate/latest/verdict.json (status, changes)
+# https://facebook.github.io/astryx/visual-gate/latest/ (the report)
+
+name: Release Gate
+
+on:
+ schedule:
+ # 14:10 UTC = 07:10 PT — before the 08:00 PT release cut, off the hour.
+ - cron: '10 14 * * *'
+ workflow_dispatch:
+ inputs:
+ tiers:
+ description: 'Shot tiers: surface, theme-matrix, full'
+ required: false
+ default: 'surface,theme-matrix'
+
+permissions: {}
+
+concurrency:
+ group: release-gate
+ cancel-in-progress: false
+
+jobs:
+ visual:
+ name: Visual regression
+ # Pinned label, deliberately: a baseline is only comparable against the
+ # same platform and browser build. The gate refuses the comparison rather
+ # than reporting a runner change as hundreds of regressions.
+ runs-on: 2-core-ubuntu-arm
+ timeout-minutes: 45
+ permissions:
+ contents: read
+ outputs:
+ status: ${{ steps.gate.outputs.status }}
+ changed: ${{ steps.gate.outputs.changed }}
+ added: ${{ steps.gate.outputs.added }}
+ total: ${{ steps.gate.outputs.total }}
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v7
+
+ - name: Setup Node and pnpm
+ uses: ./.github/actions/setup
+
+ - name: Build packages
+ run: pnpm build
+
+ - name: Build Storybook
+ run: pnpm -F @astryxdesign/storybook build
+
+ - name: Install Playwright browser
+ run: npx playwright install chromium
+
+ # Only the baseline, not the whole gh-pages tree (which carries every PR
+ # preview): sparse + blob:none keeps this to the PNGs actually needed.
+ - name: Fetch visual baseline from gh-pages
+ run: |
+ set -eu
+ rm -rf /tmp/gh-pages
+ git clone --depth=1 --filter=blob:none --sparse --single-branch --branch gh-pages \
+ "https://github.com/${GITHUB_REPOSITORY}.git" /tmp/gh-pages
+ git -C /tmp/gh-pages sparse-checkout set visual-gate/baseline
+ mkdir -p .visual-baseline
+ if [ -d /tmp/gh-pages/visual-gate/baseline ]; then
+ cp -r /tmp/gh-pages/visual-gate/baseline/. .visual-baseline/
+ echo "Baseline: $(ls .visual-baseline/shots 2>/dev/null | wc -l) shots"
+ else
+ echo "::notice::No baseline on gh-pages yet — this run establishes one."
+ fi
+
+ # Exit 2 means "changed", which is a question for the release cut, not a
+ # broken run. Exit 1 (crashed) still fails the job.
+ - name: Run the visual gate
+ id: gate
+ run: |
+ set +e
+ node .github/scripts/visual-gate/gate.mjs check \
+ --storybook-dir apps/storybook/dist \
+ --baseline .visual-baseline \
+ --out .visual-run \
+ --tiers "${{ inputs.tiers || 'surface,theme-matrix' }}" \
+ --summary-output visual-summary.md
+ code=$?
+ cat visual-summary.md >> "$GITHUB_STEP_SUMMARY" || true
+ [ "$code" -eq 1 ] && exit 1
+ exit 0
+
+ # The capture is what a promotion copies from, so it has to outlive the
+ # run: visual-baseline.yml promotes shots out of this artifact by run id.
+ - name: Upload capture
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: visual-capture
+ path: |
+ .visual-run/shots/
+ .visual-run/manifest.json
+ .visual-run/verdict.json
+ retention-days: 14
+ if-no-files-found: warn
+
+ - name: Upload report
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: visual-report
+ path: .visual-run/report/
+ retention-days: 30
+ if-no-files-found: warn
+
+ a11y:
+ name: Accessibility
+ runs-on: 2-core-ubuntu-arm
+ timeout-minutes: 45
+ permissions:
+ contents: read
+ outputs:
+ status: ${{ steps.summarize.outputs.status }}
+ total_violations: ${{ steps.summarize.outputs.total_violations }}
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v7
+
+ - name: Setup Node and pnpm
+ uses: ./.github/actions/setup
+
+ - name: Build packages
+ run: pnpm build
+
+ - name: Build Storybook
+ run: pnpm -F @astryxdesign/storybook build
+
+ - name: Install Playwright browser
+ run: npx playwright install chromium
+
+ - name: Run full-suite accessibility audit
+ id: audit
+ continue-on-error: true
+ run: |
+ BASELINE_FLAGS=""
+ if [ -f .github/a11y-baseline.json ]; then
+ BASELINE_FLAGS="--baseline .github/a11y-baseline.json --fail-on-new"
+ fi
+ node .github/scripts/accessibility-audit.js \
+ --storybook-dir apps/storybook/dist \
+ --output a11y-report.json \
+ $BASELINE_FLAGS
+
+ - name: Summarize
+ id: summarize
+ env:
+ AUDIT_OUTCOME: ${{ steps.audit.outcome }}
+ run: |
+ node .github/scripts/weekly-a11y-summary.js \
+ --report a11y-report.json \
+ --audit-outcome "$AUDIT_OUTCOME" \
+ --summary-output a11y-summary.md \
+ --github-output "$GITHUB_OUTPUT"
+ cat a11y-summary.md >> "$GITHUB_STEP_SUMMARY"
+
+ - name: Upload report
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: a11y-gate-report
+ path: |
+ a11y-report.json
+ a11y-summary.md
+ retention-days: 30
+ if-no-files-found: warn
+
+ publish:
+ name: Publish verdict
+ needs: [visual, a11y]
+ if: ${{ !cancelled() }}
+ runs-on: ubuntu-slim
+ permissions:
+ contents: write
+ # Not the pages-deploy group: GitHub keeps only the newest pending run per
+ # group, so joining it could cancel a pending site deploy (see
+ # cleanup-previews.yml for the same reasoning).
+ concurrency:
+ group: release-gate-publish
+ cancel-in-progress: false
+ steps:
+ - name: Download report
+ uses: actions/download-artifact@v8
+ with:
+ name: visual-report
+ path: report
+
+ - name: Compose the release-gate verdict
+ env:
+ VISUAL_STATUS: ${{ needs.visual.result == 'success' && needs.visual.outputs.status || 'crashed' }}
+ A11Y_STATUS: ${{ needs.a11y.outputs.status || 'crashed' }}
+ A11Y_VIOLATIONS: ${{ needs.a11y.outputs.total_violations || '0' }}
+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
+ run: |
+ set -eu
+ REPORT_URL="https://facebook.github.io/astryx/visual-gate/${GITHUB_RUN_ID}/"
+ cat > report/release-gate.json <<JSON
+ {
+ "generatedAt": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
+ "sha": "${GITHUB_SHA}",
+ "runId": "${GITHUB_RUN_ID}",
+ "runUrl": "${RUN_URL}",
+ "reportUrl": "${REPORT_URL}",
+ "visual": {"status": "${VISUAL_STATUS}"},
+ "a11y": {"status": "${A11Y_STATUS}", "violations": ${A11Y_VIOLATIONS}}
+ }
+ JSON
+ cat report/release-gate.json
+
+ - name: Publish to gh-pages
+ run: |
+ set -eu
+ REPO_URL="https://x-access-token:${{ github.token }}@github.com/${GITHUB_REPOSITORY}.git"
+ for attempt in 1 2 3; do
+ rm -rf /tmp/gh-pages
+ git clone --depth=1 --filter=blob:none --sparse --single-branch --branch gh-pages "$REPO_URL" /tmp/gh-pages
+ git -C /tmp/gh-pages sparse-checkout set visual-gate
+ RUN_DIR="/tmp/gh-pages/visual-gate/${GITHUB_RUN_ID}"
+ rm -rf "$RUN_DIR" /tmp/gh-pages/visual-gate/latest
+ mkdir -p "$RUN_DIR" /tmp/gh-pages/visual-gate/latest
+ cp -r report/. "$RUN_DIR"/
+ cp -r report/. /tmp/gh-pages/visual-gate/latest/
+
+ # Keep the twenty most recent run directories; the report images are
+ # only useful while the change they describe is still a live question.
+ ls -1d /tmp/gh-pages/visual-gate/*/ 2>/dev/null \
+ | grep -Ev '/(baseline|latest)/$' \
+ | sort -V | head -n -20 | xargs -r rm -rf
+
+ cd /tmp/gh-pages
+ git config user.name "github-actions[bot]"
+ git config user.email "github-actions[bot]@users.noreply.github.com"
+ git add -A visual-gate
+ git commit -m "release gate: ${GITHUB_RUN_ID}" || { echo "Nothing to publish"; exit 0; }
+ if git push origin gh-pages; then
+ echo "Published https://facebook.github.io/astryx/visual-gate/${GITHUB_RUN_ID}/"
+ exit 0
+ fi
+ echo "Push failed (attempt $attempt), retrying"
+ sleep $((attempt * 10))
+ done
+ echo "::error::Could not publish the release-gate report to gh-pages"
+ exit 1
+
+ - name: Summary
+ env:
+ VISUAL_STATUS: ${{ needs.visual.outputs.status }}
+ A11Y_STATUS: ${{ needs.a11y.outputs.status }}
+ run: |
+ {
+ echo "## Release gate"
+ echo ""
+ echo "| check | status |"
+ echo "|---|---|"
+ echo "| visual | ${VISUAL_STATUS:-crashed} |"
+ echo "| a11y | ${A11Y_STATUS:-crashed} |"
+ echo ""
+ echo "Report: https://facebook.github.io/astryx/visual-gate/${GITHUB_RUN_ID}/"
+ } >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/workflows/visual-baseline.yml b/.github/workflows/visual-baseline.yml
new file mode 100644
index 0000000000..c2b72941dd
--- /dev/null
+++ b/.github/workflows/visual-baseline.yml
@@ -0,0 +1,123 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+
+# Promote captured shots into the visual baseline — the "the after is correct"
+# outcome of the release gate, made explicit.
+#
+# Separate from release-gate.yml on purpose. The gate only ever READS the
+# baseline; this is the one workflow that writes it, it runs only when a human
+# or the release cut dispatches it, and it refuses to run without a reason.
+# Every promotion appends to the decision log in the baseline manifest (who,
+# when, which run, why, which shots), so any baseline can be read back to the
+# change that justified it.
+#
+# Shots are promoted OUT OF A SPECIFIC GATE RUN's capture artifact, never
+# re-captured here: the picture that becomes the baseline is exactly the
+# picture that was reviewed.
+#
+# Typical uses:
+# keys=core-button--default__y2k-light,core-badge--solid__y2k-light
+# reason="Y2K button radius went square on purpose (#5123)"
+# keys=all reason="Playwright chromium bump — every shot re-rendered"
+
+name: Visual Baseline
+
+on:
+ workflow_dispatch:
+ inputs:
+ run_id:
+ description: 'Release Gate run id whose capture to promote from'
+ required: true
+ keys:
+ description: 'Comma-separated shot keys, or "all"'
+ required: true
+ reason:
+ description: 'Why the new rendering is the correct one'
+ required: true
+ prune:
+ description: 'Also drop baseline shots whose story no longer exists'
+ required: false
+ default: true
+ type: boolean
+
+permissions: {}
+
+concurrency:
+ group: visual-baseline
+ cancel-in-progress: false
+
+jobs:
+ promote:
+ runs-on: ubuntu-slim
+ timeout-minutes: 20
+ permissions:
+ contents: write
+ actions: read # download-artifact from another run
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v7
+
+ - name: Setup Node and pnpm
+ uses: ./.github/actions/setup
+
+ - name: Download the capture being promoted
+ uses: actions/download-artifact@v8
+ with:
+ name: visual-capture
+ run-id: ${{ inputs.run_id }}
+ github-token: ${{ github.token }}
+ path: .visual-run
+
+ - name: Fetch the current baseline
+ run: |
+ set -eu
+ rm -rf /tmp/gh-pages
+ git clone --depth=1 --filter=blob:none --sparse --single-branch --branch gh-pages \
+ "https://x-access-token:${{ github.token }}@github.com/${GITHUB_REPOSITORY}.git" /tmp/gh-pages
+ git -C /tmp/gh-pages sparse-checkout set visual-gate/baseline
+ mkdir -p /tmp/gh-pages/visual-gate/baseline
+
+ - name: Promote
+ env:
+ KEYS: ${{ inputs.keys }}
+ REASON: ${{ inputs.reason }}
+ PROMOTER: ${{ github.actor }}
+ run: |
+ set -eu
+ node .github/scripts/visual-gate/gate.mjs accept \
+ --baseline /tmp/gh-pages/visual-gate/baseline \
+ --out .visual-run \
+ --keys "$KEYS" \
+ --reason "$REASON" \
+ --actor "$PROMOTER" \
+ ${{ inputs.prune && '--prune' || '' }}
+
+ - name: Push the baseline
+ run: |
+ set -eu
+ cd /tmp/gh-pages
+ git config user.name "github-actions[bot]"
+ git config user.email "github-actions[bot]@users.noreply.github.com"
+ git add -A visual-gate/baseline
+ git commit -m "visual baseline: ${{ inputs.keys }} (run ${{ inputs.run_id }})" || {
+ echo "Baseline unchanged"; exit 0;
+ }
+ for attempt in 1 2 3; do
+ if git push origin gh-pages; then
+ echo "Baseline updated"
+ exit 0
+ fi
+ git fetch origin gh-pages && git rebase origin/gh-pages || true
+ sleep $((attempt * 10))
+ done
+ echo "::error::Could not push the updated baseline"
+ exit 1
+
+ - name: Summary
+ run: |
+ {
+ echo "## Visual baseline updated"
+ echo ""
+ echo "- promoted: \`${{ inputs.keys }}\`"
+ echo "- from run: ${{ inputs.run_id }}"
+ echo "- reason: ${{ inputs.reason }}"
+ } >> "$GITHUB_STEP_SUMMARY"
diff --git a/apps/storybook/.storybook/main.ts b/apps/storybook/.storybook/main.ts
index 0b03da91fe..3c5800ea2e 100644
--- a/apps/storybook/.storybook/main.ts
+++ b/apps/storybook/.storybook/main.ts
@@ -98,6 +98,18 @@ const config: StorybookConfig = {
'@astryxdesign/richtext': [
path.join(rootDir, 'packages/richtext/src'),
],
+ '@astryxdesign/theme-butter/*': [
+ path.join(rootDir, 'packages/themes/butter/src/*'),
+ ],
+ '@astryxdesign/theme-chocolate/*': [
+ path.join(rootDir, 'packages/themes/chocolate/src/*'),
+ ],
+ '@astryxdesign/theme-gothic/*': [
+ path.join(rootDir, 'packages/themes/gothic/src/*'),
+ ],
+ '@astryxdesign/theme-matcha/*': [
+ path.join(rootDir, 'packages/themes/matcha/src/*'),
+ ],
'@astryxdesign/theme-neutral/*': [
path.join(rootDir, 'packages/themes/neutral/src/*'),
],
@@ -130,6 +142,22 @@ const config: StorybookConfig = {
rootDir,
'packages/richtext/src',
),
+ '@astryxdesign/theme-butter': path.resolve(
+ rootDir,
+ 'packages/themes/butter/src/source.ts',
+ ),
+ '@astryxdesign/theme-chocolate': path.resolve(
+ rootDir,
+ 'packages/themes/chocolate/src/source.ts',
+ ),
+ '@astryxdesign/theme-gothic': path.resolve(
+ rootDir,
+ 'packages/themes/gothic/src/source.ts',
+ ),
+ '@astryxdesign/theme-matcha': path.resolve(
+ rootDir,
+ 'packages/themes/matcha/src/source.ts',
+ ),
'@astryxdesign/theme-neutral': path.resolve(
rootDir,
'packages/themes/neutral/src/source.ts',
diff --git a/apps/storybook/.storybook/preview.tsx b/apps/storybook/.storybook/preview.tsx
index 02c6e8b6cf..61e6231134 100644
--- a/apps/storybook/.storybook/preview.tsx
+++ b/apps/storybook/.storybook/preview.tsx
@@ -2,7 +2,15 @@
import type {Preview, Decorator} from '@storybook/react';
import * as React from 'react';
-import {Theme, LayerProvider, InternationalizationProvider} from '@astryxdesign/core';
+import {
+ Theme,
+ LayerProvider,
+ InternationalizationProvider,
+} from '@astryxdesign/core';
+import {butterTheme} from '@astryxdesign/theme-butter';
+import {chocolateTheme} from '@astryxdesign/theme-chocolate';
+import {gothicTheme} from '@astryxdesign/theme-gothic';
+import {matchaTheme} from '@astryxdesign/theme-matcha';
import {neutralTheme} from '@astryxdesign/theme-neutral';
import {stoneTheme} from '@astryxdesign/theme-stone';
import {y2kTheme} from '@astryxdesign/theme-y2k';
@@ -10,9 +18,15 @@ import {y2kTheme} from '@astryxdesign/theme-y2k';
import '@astryxdesign/core/reset.css';
/**
- * Map of available themes
+ * Every shipped theme, so the toolbar can reach them and the visual gate can
+ * photograph a component under each theme that overrides it. A theme missing
+ * here is a theme nothing renders and nothing verifies.
*/
const themes = {
+ butter: butterTheme,
+ chocolate: chocolateTheme,
+ gothic: gothicTheme,
+ matcha: matchaTheme,
neutral: neutralTheme,
stone: stoneTheme,
y2k: y2kTheme,
@@ -99,6 +113,10 @@ const preview: Preview = {
{value: 'none', title: 'None (base tokens)', icon: 'close'},
{value: 'neutral', title: 'Neutral', icon: 'circle'},
{value: 'stone', title: 'Stone', icon: 'circlehollow'},
+ {value: 'butter', title: 'Butter', icon: 'sun'},
+ {value: 'chocolate', title: 'Chocolate', icon: 'circle'},
+ {value: 'gothic', title: 'Gothic', icon: 'moon'},
+ {value: 'matcha', title: 'Matcha', icon: 'circlehollow'},
{value: 'y2k', title: 'Y2K', icon: 'lightning'},
],
dynamicTitle: true,
diff --git a/apps/storybook/package.json b/apps/storybook/package.json
index 646942bddb..7713d6612b 100644
--- a/apps/storybook/package.json
+++ b/apps/storybook/package.json
@@ -13,6 +13,10 @@
"@astryxdesign/core": "*",
"@astryxdesign/lab": "*",
"@astryxdesign/richtext": "*",
+ "@astryxdesign/theme-butter": "*",
+ "@astryxdesign/theme-chocolate": "*",
+ "@astryxdesign/theme-gothic": "*",
+ "@astryxdesign/theme-matcha": "*",
"@astryxdesign/theme-neutral": "*",
"@astryxdesign/theme-stone": "*",
"@astryxdesign/theme-y2k": "*",
diff --git a/package.json b/package.json
index 2bd5edb318..a544d4f03d 100644
--- a/package.json
+++ b/package.json
@@ -24,7 +24,10 @@
"check:use-client": "node scripts/check-use-client.mjs",
"lint": "pnpm check:repo && eslint . --cache",
"lint:strict": "pnpm check:repo && ASTRYX_STRICT_LINT=1 eslint . --cache",
- "a11y:audit": "node .github/scripts/accessibility-audit.js --baseline .github/a11y-baseline.json --fail-on-new",
+ "visual:plan": "node .github/scripts/visual-gate/gate.mjs plan",
+ "visual:check": "node .github/scripts/visual-gate/gate.mjs check",
+ "visual:flaky": "node .github/scripts/visual-gate/gate.mjs flaky",
+ "a11y:audit": "node .github/scripts/accessibility-audit.js --baseline .github/a11y-baseline.json --fail-on-new",
"a11y:baseline": "node .github/scripts/accessibility-audit.js --baseline .github/a11y-baseline.json --update-baseline",
"rtl:audit": "node apps/storybook/rtl-audit/rtl-audit.mjs",
"lab:readiness": "node internal/lab-readiness/audit.mjs",
@@ -73,6 +76,8 @@
"husky": "^9.1.7",
"jsdom": "^27.4.0",
"lint-staged": "^17.0.8",
+ "pixelmatch": "^7.2.0",
+ "pngjs": "^7.0.0",
"prettier": "catalog:",
"react": "^19.2.7",
"react-dom": "^19.2.7",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1f9e339f81..188fdac5c1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -97,6 +97,12 @@ importers:
lint-staged:
specifier: ^17.0.8
version: 17.0.8
+ pixelmatch:
+ specifier: ^7.2.0
+ version: 7.2.0
+ pngjs:
+ specifier: ^7.0.0
+ version: 7.0.0
prettier:
specifier: 'catalog:'
version: 3.9.4
@@ -333,6 +339,18 @@ importers:
'@astryxdesign/richtext':
specifier: '*'
version: link:../../packages/richtext
+ '@astryxdesign/theme-butter':
+ specifier: '*'
+ version: link:../../packages/themes/butter
+ '@astryxdesign/theme-chocolate':
+ specifier: '*'
+ version: link:../../packages/themes/chocolate
+ '@astryxdesign/theme-gothic':
+ specifier: '*'
+ version: link:../../packages/themes/gothic
+ '@astryxdesign/theme-matcha':
+ specifier: '*'
+ version: link:../../packages/themes/matcha
'@astryxdesign/theme-neutral':
specifier: '*'
version: link:../../packages/themes/neutral
@@ -5351,6 +5369,10 @@ packages:
resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==}
engines: {node: '>= 6'}
+ resolution: {integrity: sha512-xhcb4yHu9sM/G7foGzoLtXYcC0zHEaOXXjRKhGup0fw78Nf2Tkiapv4EQyMzrbcmQPsllAI7DbFY2UT7PlI9Pg==}
+ hasBin: true
+
resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==}
engines: {node: '>=16.20.0'}
@@ -5372,6 +5394,10 @@ packages:
engines: {node: '>=18'}
hasBin: true
+ resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==}
+ engines: {node: '>=14.19.0'}
+
resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==}
engines: {node: '>= 18'}
@@ -10720,6 +10746,10 @@ snapshots:
+ dependencies:
+ pngjs: 7.0.0
+
@@ -10740,6 +10770,8 @@ snapshots:
optionalDependencies:
fsevents: 2.3.2
+
dependencies:
lilconfig: 3.1.3