Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,8 @@ renderdiff http://localhost:3000 https://example.com / /about --rerun-failed
to the config, or in cwd); commit it. Later, a shot whose every difference matches an entry is
listed on an `accepted:` line and doesn't count toward the exit code; anything new on the same
page still shows. `--rerun-failed` reruns only what the last run in `--out` didn't find clean
or accepted (with the same `--only`, if it had one). Against a slow reference, `--cache-right`
or accepted (with the same `--only`, if it had one), keeping a shot with no differing pixels
and at most 100 unstable ones. Against a slow reference, `--cache-right`
replays the right side's recorded traffic for up to an hour; drop it for the final run.
Matching rules, why to accept on the platform that checks, and the cache:
[docs/accepted.md](https://github.com/tmashara/renderdiff/blob/main/docs/accepted.md).
Expand Down
4 changes: 3 additions & 1 deletion docs/accepted.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ fingerprint covers it.
`--rerun-failed` reads `results.json` in `--out`, keeps every shot that was clean or is
accepted (against the accepted file as it is now), reruns the rest — differences, unstable
shots, errors — and merges them back into `results.json` and `report.html` in route and width
order. The out dir is kept rather than wiped; only a rerun shot's own old files are replaced.
order. A shot with no differing pixels and at most 100 unstable ones (anti-aliased corners,
which recur on every load) is kept too, and is still not clean.
The out dir is kept rather than wiped; only a rerun shot's own old files are replaced.
A `rerun:` line says how many shots it reran on how many routes, and how many it reused.
`meta` describes the rerun (its clock, browser and time); a reused shot was taken under the
earlier run's. It must repeat the previous run: different origins, routes, widths, config
Expand Down
4 changes: 3 additions & 1 deletion docs/how-it-works.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ honestly. This is what renderdiff does to make sure of that.
(server-sent events and beacons don't count), then re-injects the stylesheet to
catch late-injected chrome. Stylesheets that failed or answered ≥ 400 (blocked URLs
aside) and font faces that failed (blocked font files included) are recorded per side as
`failed`, and keep the route off the `clean:` line.
`failed`, and keep the route off the `clean:` line. When only one side failed, that side is
loaded again once, and reported only if it fails again; a failure that recurred isn't retried
on later shots.
- **Shoots until stable** — repeats the screenshot until two in a row match (at most 3; 2
for tiled pages). Pixels still changing between the last two shots of the same load are
noise from that origin: they're painted magenta on both sides, reported per comparison
Expand Down
27 changes: 15 additions & 12 deletions skills/renderdiff/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ the § named at each step. Setting up a project (`/renderdiff init`): [init.md](

| Change | Run |
| --- | --- |
| CSS only, markup untouched (refactor, dead-CSS removal, token swap) | pixels + `--computed`. First diff the two builds (§ Reference and routes): if only asset hashes differ, no shots are needed; otherwise shoot the routes the changed rules reach. Expect `dom identical` on every route: then each `computed:` finding is a real style change, even on a clean route. `dom differs`: often a wrapper's class changed, re-keying its subtree (§ `--computed`). Hover menus and open menus aren't shot without a `before` hook that ends waiting for the open state, and dead-CSS removal breaks exactly those. |
| CSS only, markup untouched (refactor, dead-CSS removal, token swap) | pixels + `--computed`. First diff the two builds (§ Reference and routes): if only asset hashes differ, or every changed rule means the same, no shots are needed; otherwise shoot the routes the changed rules reach. Expect `dom identical` on every route: then each `computed:` finding is a real style change, even on a clean route. `dom differs`: often a wrapper's class changed, re-keying its subtree (§ `--computed`). Hover menus and open menus aren't shot without a `before` hook that ends waiting for the open state, and dead-CSS removal breaks exactly those. |
| Markup changes (framework, template or component migration) | pixels, plus `--aria`: `aria: identical` means a screen reader gets the same page. `--computed` findings would only be hints. |
| Dependency or build upgrade | pixels, plus `--computed` if the markup should be identical. |
| One component | pixels with `--selector <sel>` or `'/route @sel'`. |
Expand All @@ -37,16 +37,19 @@ Pixels decide the score and the exit code in every mode.
replace this step and step 2's masks. None, and the project will be run more than once:
offer `/renderdiff init` ([init.md](init.md)) after this check.
2. **Baseline**: base vs base. Before changing code, the untouched change side against the
reference; if the change is already made, the base build served on two ports. Whatever
differs varies per load: mask it (a `varies` line prints the mask; `--mask-media` for
iframes, `--mask <sel>` or a config mask with a `reason`; video is already frozen; a
looping carousel: stop it with a `before` hook on both sides, or mask it), and rerun
until clean; `--only <route>` reruns some of a config's routes with their hooks, which
routes typed on the command line don't get. A difference with no `varies` line and
nothing unstable: `renderdiff probe <right><route> --width <w>` names what varies
between loads; mask that. Against production instead: open each difference, then
`--accept "differs before the change"`. § Masks, accepts and thresholds.
3. **Change, run all routes at default widths, read each row in this order**: `ERROR` →
reference. If the change is already made, run step 3 first (its recheck already reloads each
differing shot's right side), then base vs base on only the routes that still differ, the
right origin on both sides (§ Reference and routes). Whatever differs varies per load: mask
it (a `varies` line prints the mask; `--mask-media` for iframes, `--mask <sel>` or a config
mask with a `reason`; video is already frozen; a looping carousel: stop it with a `before`
hook on both sides, or mask it), and rerun until clean; `--only <route>` reruns some of a
config's routes with their hooks, which routes typed on the command line don't get. A
difference with no `varies` line and nothing unstable:
`renderdiff probe <right><route> --width <w>` names what varies between loads; mask that. Against production instead: open
each difference, then `--accept "differs before the change"`. § Masks, accepts and
thresholds.
3. **Change, run every route in scope (CSS only: the routes the changed rules reach) at
default widths, read each row in this order**: `ERROR` →
`failed` (a missing stylesheet or font explains the whole row: fix, rerun) → `fonts` → `text` →
`h`/`w`, `band`, `aligned`, `line` → `dom` (`sel prop l→r` is a computed value: find the
*rule*) → `findings:` (one cause on many routes: fix it once) → `computed:` → `Read` the
Expand All @@ -65,7 +68,7 @@ Pixels decide the score and the exit code in every mode.

Before you mask, accept, set `--threshold`, drop a route or skip a width: § Rationalizations.
5. **Iterate** with `--rerun-failed` (same arguments) and optionally `--cache-right`
(§ Iterating). **Finish** with a fresh full run: all routes, default widths, neither flag.
(§ Iterating). **Finish** with a fresh full run: the same routes, default widths, neither flag.
All clean? Confirm both sides actually rendered.

Exit 0 is not verified: unstable pixels or a failed asset alone exit 0, so report them. 1: an
Expand Down
23 changes: 18 additions & 5 deletions skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,27 @@ results.json · Gotchas.
- **CSS-only change:** diff the two build outputs first: every CSS file, plus the HTML and JS
(minified CSS: `tr '}' '\n'` gives one rule per line; pair hashed file names by their stem;
ignore `.map` files and `sourceMappingURL`). If they match apart from asset hashes, no route
needs shots; say so in the report. If HTML or JS differ too, the change isn't CSS-only. For
needs shots; say so in the report. The same if every changed rule means the same:
declarations only reordered (unless a shorthand and its longhand swap, `margin` and
`margin-top`), or values only re-notated (`rgb(0 0 0 / 50%)` for `rgba(0,0,0,.5)`, hex case
and short form, `0` for `0px`, `::before` for `:before`, `(width >= 60em)` for
`(min-width: 60em)`); name the rules you checked. If HTML or JS differ too, the change isn't
CSS-only, unless only inlined CSS differs: Astro, Svelte, Vue and similar builds copy
`<style>` blocks and `style=""` into every page, so diff those as CSS. For
each changed or removed rule, list every page where its selectors could match: grep the
built HTML for its classes and ids. Element-only, `:root`/`html`/`body` and custom-property
rules reach every route. Classes that exist only after JS runs (`.is-open`,
client-rendered components) aren't in the HTML: shoot those states with a `before` hook,
or list them under Not verified.
- **Baseline when the change is already made:** serve the base build twice, on two ports, and
diff it against itself; whatever differs varies per load.
- **Baseline when the change is already made:** run the change first; its recheck reloads the
right side of each differing shot (`varies`). Then base vs base on the routes still
differing, with the right origin on both sides:
`jq -r '[.results[] | select(.diffPixels > 0 and (.accepted | not)) | .url] | unique[]' <out>/results.json > differ.txt`,
then `renderdiff <right> <right> --only differ.txt --out renderdiff-baseline` with a config
(its hooks kept). `--only` picks only config routes and is refused with `--sitemap`, so a
run whose routes came from the command line or `--sitemap` passes `$(cat differ.txt)` as
the routes instead. A moved pair is listed as `/a::/b`: keep its right path, `/b`. Whatever
differs there varies per load.
- **States:** only the loaded state is shot. Hover, focus, open menus and dialogs need a
`before` hook (§ Scoping); dead-CSS removal often breaks exactly those. `--computed` diffs
links' and controls' hover and focus styles without shooting them.
Expand Down Expand Up @@ -77,7 +90,7 @@ on stderr: `✗ 2 routes differ (10 shots).` (`below 97.00%` with `--threshold`)
| `accepted: /a` | Every difference on every width matches `renderdiff.accepted.json`. Known, not re-verified: say so. |
| `/a clean @… accepted @…` | A route with something to read; the widths that are clean or accepted. |
| ` @1440,896 <row>` | Widths agreeing on height and width delta, bands (side and height), aligned score and text; score and region count become ranges, `unstable` the largest. |
| ` failed left: …` | Stylesheets (`stylesheet <url>`) and font faces (`font Inter 700`) that side didn't load (404, CORS, a CDN refusing localhost). Fix first: a fallback font reflows every line. |
| ` failed left: …` | Stylesheets (`stylesheet <url>`) and font faces (`font Inter 700`) that side didn't load (404, CORS, a CDN refusing localhost); one side only: it failed again on a reload. Fix first: a fallback font reflows every line. |
| ` fonts -"Inter 600" +"X"` | Web font faces (`@font-face`, `FontFace`) only one side requested: `-` the reference, `+` your change. System fallbacks aren't listed. Not a reason a shot isn't clean; pixels decide. |
| ` dom …` | Up to three elements behind the changes, two properties each. `dom @1440 …`: from the first width of the row. |
| ` crops …` | At most three crop PNGs per shot (bands first, tallest first, then largest regions), relative to `results.json`. |
Expand Down Expand Up @@ -269,7 +282,7 @@ aria: identical on 2 of 3 route(s), differs /pricing
## Iterating

- **`--rerun-failed`** keeps the out dir and reruns only what wasn't clean or accepted
(differences, unstable shots, failed assets, errors), merging back into results.json. Same
(differences, over 100 unstable px, failed assets, errors), merging back into results.json. Same
origins, routes, widths, config (masks, hooks, hidden selectors, CSS, storage state,
`--computed`) and version as the run it continues, or it exits 2.
- **Hand-picked reruns with a changed config** (a new mask for a few routes): run them into a
Expand Down
3 changes: 2 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,8 @@ const HELP = `
That side's storage state, over --storage-state.
--accept <reason> Accept this run's differences, scoped by its routes and widths.
--rerun-failed Rerun what the last run in --out didn't find clean or accepted,
keeping the rest. Same origins, routes and widths as that run.
keeping the rest (and matching shots with at most 100 unstable
px). Same origins, routes and widths as that run.
--only <route|file> Run only the config's routes with this path (or pair), their
hooks and selectors kept; '/a @sel' narrows to that selector.
Repeatable. A value naming a file in cwd lists one per line,
Expand Down
47 changes: 39 additions & 8 deletions src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ const SHOT_TIMEOUT = (Math.max(0, Number(process.env.RENDERDIFF_SHOT_TIMEOUT)) |
/** Past this share of a page unstable, too little was measured for a score to mean anything. */
const MAX_UNSTABLE_SHARE = 0.25;

/** Unstable px a rerun reuses a matching shot under: anti-aliased corners recur on every load. */
const REUSE_UNSTABLE = 100;

export const BLANK_HINT =
"under 200 chars of text and no visible image, SVG, canvas, video, iframe or form control; " +
"if the page is meant to be this sparse, add data-renderdiff-rendered to a visible element its own " +
Expand Down Expand Up @@ -273,7 +276,13 @@ export async function run({
// A shot measured against a replay stands only for a run that would replay it too.
const replay = had?.status === "compared" && had.rightReplayedFrom;
const fresh = !replay || (cacheRight && Date.now() - Date.parse(replay) < REPLAY_TTL);
if (had && reusable(had) && fresh) results.push(had);
const noise =
had?.status === "compared" &&
had.diffPixels === 0 &&
had.unstablePixels <= REUSE_UNSTABLE &&
!had.varies &&
!broken(had);
if (had && (reusable(had) || noise) && fresh) results.push(had);
else jobs.push({ route, width });
}
}
Expand All @@ -300,6 +309,7 @@ export async function run({
jobs.map((j) => shotId(j.route, j.width)),
);
const recorded: string[] = [];
const lasting = new Set<string>();
if (har && !replayedAt) fs.mkdirSync(path.dirname(har), { recursive: true });
const part = (i: number) => `${har}.${i}.part`;

Expand Down Expand Up @@ -356,16 +366,37 @@ export async function run({
let frames: string[] | undefined;
try {
missed = 0;
const take = (side: "left" | "right", on = pages) =>
shoot(on, cfg[side] + route[side], route, side, width, cfg, now);
// allSettled, not all: a page must not start the next job while still loading this one.
const settled = await Promise.allSettled([
shoot(pages, cfg.left + route.left, route, "left", width, cfg, now),
shoot(pages, cfg.right + route.right, route, "right", width, cfg, now),
]);
const settled = await Promise.allSettled([take("left"), take("right")]);
const failed = settled.find((r) => r.status === "rejected");
if (failed) throw failed.reason;
const [leftShot, rightShot] = settled.map(
(r) => (r as PromiseFulfilledResult<Shot>).value,
) as [Shot, Shot];
const value = (s: PromiseSettledResult<Shot>) => (s as PromiseFulfilledResult<Shot>).value;
const shots = { left: value(settled[0]), right: value(settled[1]) };
// One side alone failing an asset is likely load; once it recurs on a retry, it's the build.
const [lone, ...both] = (["left", "right"] as const).filter((s) => shots[s].failed.length);
if (lone && !both.length && !shots[lone].failed.every((f) => lasting.has(`${lone} ${f}`))) {
const was = missed;
if (lone === "right") missed = 0;
// A spare page: a retry that throws must leave this shot's document for locate and --computed.
const spare = { ...pages };
const again = await (async () => {
spare[lone] = await pages[lone].context().newPage();
await prepare(spare[lone], cfg, now);
return take(lone, spare);
})().catch(() => null);
if (again) {
await pages[lone].close();
pages[lone] = spare[lone];
shots[lone] = again;
for (const f of again.failed) lasting.add(`${lone} ${f}`);
} else {
missed = was;
if (spare[lone] !== pages[lone]) await spare[lone].close().catch(() => {});
}
}
const { left: leftShot, right: rightShot } = shots;
// A blank page matches any other blank page, so refuse rather than score two of
// them. One blank side is left to the diff, which shows it plainly.
if (leftShot.blank && rightShot.blank) {
Expand Down
24 changes: 24 additions & 0 deletions tests/visual/accepted.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,30 @@ describe("--rerun-failed", () => {
assert.doesNotMatch(run.stdout, /^varies /m, context(run));
});

test("reuses a matching shot with a few unstable pixels, and reruns a larger unstable area", async () => {
// An 8x8 ticking box at 375 only: anti-aliasing-sized noise, which a rerun measures again.
const file = path.join(tempDir(), "tiny.mjs");
fs.writeFileSync(
file,
`export default { before: async (page, { width }) => { if (width === 375) await page.addStyleTag({ content: ".tick { width: 8px !important; height: 8px !important }" }); } };\n`,
);
const a = args(["/ticker"], ["--config", file], [1440, 375]);
const first = await runCli(a);
assert.equal(first.code, 0, context(first));
const was = results(first.outDir);
assert.deepEqual(
[result(was, "/ticker", 1440).unstablePixels, result(was, "/ticker", 375).unstablePixels],
[148_480, 64],
context(first),
);
const run = await runCli([...a, "--rerun-failed"], { outDir: first.outDir });
assert.equal(run.code, 0, context(run));
const s = parseSummary(run.stdout);
assert.deepEqual(s.rerun, { shots: 1, routes: 1, reused: 1, untouched: 0 }, context(run));
assert.deepEqual(result(results(run.outDir), "/ticker", 375), result(was, "/ticker", 375));
assert.deepEqual(s.clean, [], "a reused unstable shot is still not clean");
});

test("a run that doesn't repeat the previous one is refused", async () => {
const first = await runCli(args(["/color"]));
assert.equal(first.code, 1, context(first));
Expand Down
Loading
Loading