diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index fc5545c..0412b2f 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -8,7 +8,7 @@ { "name": "renderdiff", "source": "./", - "description": "Visual-parity loop for coding agents doing website migrations: screenshot-diff your branch against production at several widths and explain every change down to the DOM element and CSS property." + "description": "Visual-parity loop for coding agents doing website migrations: screenshot-diff your change against a local build of the base (or production) at several widths and explain every change down to the DOM element and CSS property." } ] } diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 6be1354..0fae670 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "renderdiff", - "description": "Visual-parity loop for coding agents doing website migrations: screenshot-diff your branch against production at several widths and explain every change down to the DOM element and CSS property.", + "description": "Visual-parity loop for coding agents doing website migrations: screenshot-diff your change against a local build of the base (or production) at several widths and explain every change down to the DOM element and CSS property.", "version": "0.3.2", "author": { "name": "Timur Mashara" }, "repository": "https://github.com/tmashara/renderdiff" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bcc727e..f5df3ab 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,7 +7,7 @@ npm install # builds via the prepare script npm run build # tsc → dist/ npm run typecheck # src + tests, no emit npm run lint # oxlint -npm run format # oxfmt +npm run format # oxfmt; format:check is what CI runs npm install -g . # install this working copy globally ``` @@ -35,22 +35,24 @@ formats it depends on are parsed in exactly one place, `tests/helpers/parse.ts`. validation and precedence. All of it through `--dry-run`, which exits before the browser. **`tests/visual/`** — real captures against `tests/fixtures/`, a two-origin site served on -ephemeral ports. Three groups: +ephemeral ports. Three groups, plus `accepted.test.ts` (`--accept`, `--rerun-failed`, +`--cache-right`) and `computed.test.ts` (`--computed`): - *Equivalence* — six pairs of pages that are visually identical but built with different CSS: - flex against grid, floats against flex, CSS tables against grid, transform-centring against - `place-items`, inline-block against flex. These assert a **zero-pixel** diff, not a + the home page, flex against grid, floats against flex, CSS tables against grid, + transform-centring against `place-items`, inline-block against flex. These assert a **zero-pixel** diff, not a threshold. They are the corpus's central claim: the score tracks pixels, not markup, so a refactor that changed nothing visible reads as nothing changed. -- *Controls* — an 8px shift, an extra section, one recoloured box, one changed margin. These - must score low. Without them a tool that returned 100% unconditionally would pass the +- *Controls* — an 8px shift, an extra section, a recoloured box, a subtle tint, a missing nav + link, a changed margin, a lost divider. These must score low. Without them a tool that returned 100% unconditionally would pass the suite. They also pin the elements each change names. - *Guard rails* — one per defence in [docs/how-it-works.md](docs/how-it-works.md): the blank-page refusal (and a short sign-in page that must not be refused), the 18,000px tiled capture with masks in both tiles, animation stilling, the shared clock start and seeded randomness, the unstable-pixel check, lazy-image settling (native and script-driven, - 4,800px below the fold), consent hiding, masks, network blocking, `before` hooks, storage - state, and naming fixed chrome over what it covers. Masks and blocking each run twice, + 4,800px below the fold), consent hiding, masks, video freezing, the area ceiling, failed + assets, network blocking, `before` hooks, storage state, and naming fixed chrome over what it + covers. Masks and blocking each run twice, with and without their config, so the mechanism is shown doing something rather than a page merely happening to match. diff --git a/README.md b/README.md index e6107bc..7302b63 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,9 @@ ![renderdiff output for a page missing a nav link, next to the crop it wrote](https://raw.githubusercontent.com/tmashara/renderdiff/main/docs/img/hero.png) -renderdiff screenshots the same routes on two running copies of a site (your branch on -localhost, and production) at five viewport widths and pixel-diffs each pair. For every +renderdiff screenshots the same routes on two running copies of a site (your change, and a +reference: a local build of the base commit, or production) at five viewport widths and +pixel-diffs each pair. For every change it tells you where on the page it is, which DOM element and CSS property is behind it, and what text differs. It also writes small crops sized for an LLM's context. It refuses to score what it can't trust: blank pages, error pages, pages still moving. A clean result @@ -63,7 +64,8 @@ exists only on the reference (`-`). Open `renderdiff-out/about.1440.c1.png` to s ### For coding agents -Install the skill so the agent runs the loop and reports a verdict, not a bare score: +Install the skill so the agent runs the loop (base build vs change build, a baseline before +the change, pixels plus `--computed` for CSS-only work) and reports a verdict, not a bare score: ``` /plugin marketplace add tmashara/renderdiff # Claude Code @@ -104,8 +106,8 @@ renderdiff [options] | `--selector ` | Compare the one element this Playwright selector matches, on both sides, instead of the whole page. Applies to every route, over the config's per-route `selector`. | | `--left-selector `, `--right-selector ` | That side's selector, over `--selector`. One without the other side (or `--selector`) is an error. | | `--mask ` | Paint this Playwright selector over on both sides, on every route; repeatable. Added to the config's masks and listed in the report as coverage given up. | -| `--mask-media` | Mask every `iframe` on every route, as config `maskMedia: true` does. Video isn't masked: it is frozen by default, so the player's box and styles are still compared. | -| `--no-freeze-video` | Leave videos playing and video.js overlays visible, as config `freezeVideo: false` does. By default no `video` plays, from the page's first script on, so each shows its poster (one that started anyway is paused at frame 0), and `.vjs-text-track-display` / `.vjs-control-bar` are hidden. Without freezing, videos play through the lazy-load scroll and the shots, so expect unstable pixels or `did not settle`; with `--mask-media` too, they are neither masked nor frozen. | +| `--mask-media` | Mask every `iframe` on every route, as config `maskMedia: true` does. Video isn't masked: it is frozen by default, so the player's box is still compared. | +| `--no-freeze-video` | Leave videos playing and video.js overlays visible, as config `freezeVideo: false` does. By default every video shows its poster ([how it works](https://github.com/tmashara/renderdiff/blob/main/docs/how-it-works.md)); unfrozen, expect unstable pixels or `did not settle`. `--mask-media` doesn't mask them either. | | `--storage-state ` | Start both sides with this Playwright storage state (cookies, localStorage), e.g. signed in. Relative to cwd. Over the config's `storageState`. | | `--left-storage-state `, `--right-storage-state ` | That side's storage state, over `--storage-state`. One side alone is fine. | | `--accept ` | Record this run's differences as accepted, with a reason. See **Accepted differences and reruns**. | @@ -128,7 +130,7 @@ range rather than on a boundary, so a layout switch never flaps between runs. | --- | --- | | `0` | No route errored and no shot differs (with `--threshold`: none scored below it). Accepted differences don't count; nor do unstable pixels or a failed asset alone, which still get their own row. | | `1` | A shot differs, or with `--threshold` scored below it. Wins over `3` when both happen. A difference that can't be accepted (unstable pixels beside it, a width change, a height change whose rows don't align) exits 1 even on the `--accept` run. | -| `2` | Bad arguments, bad config, or an origin that isn't responding. | +| `2` | Bad arguments or config, an origin that isn't responding, an unreadable storage state or `renderdiff.accepted.json`, an out dir holding files renderdiff didn't write, or a `--rerun-failed` that doesn't repeat the last run. | | `3` | A route errored, so it went unmeasured, or the run crashed (e.g. no Chromium). | ### Moved pages, components, interactions, sign-in @@ -178,38 +180,21 @@ only. ## Reading the output **Signs always point at your change:** `+` = only in or more in the left (your change); -`-` = only in or more in the right (the reference). +`-` = only in or more in the right (the reference). A row reads: score, `h`/`w` height and +width delta, `band`s (rows only one side has), `aligned` (the score without them), `line`s +(a 1–2px border or divider), `N reg` (regions), `unstable` pixels, `text` lines. Under it, +`failed` assets, the `dom` elements and properties behind the changes, and the `crops`. -| Token | Meaning | -| --- | --- | -| `97.41%` | Share of measured pixels that match. A range (`99.12%–99.87%`) when one row covers several widths. A triage signal, not a verdict. | -| `@1440,1152` | The widths a row covers. They agree on height and width delta, bands, aligned score and text; score and region count are ranges. | -| `h-24` / `w+8` | Height / width delta, left − right. The smaller image is padded with magenta, and the padding counts against the score on purpose. | -| `band -24@y196` | 24 rows only the reference has, at y=196 (`+`: only your change has them). `@y~196`: the row's widths put it at different y; the first width's is shown. | -| `aligned 100.00%` | The score with the bands cut out. 100% means the band is the whole difference. | -| `unaligned` | Heights differ but too few rows match to find bands. Use the height delta and regions. | -| `3 reg` | Regions: connected patches of differing pixels. A missing link barely moves the score, but it is still a region. | -| `unstable 1,204px` | Pixels that kept changing between shots of the same load (a ticker, a carousel). Excluded from the score, so the route is never clean. | -| `failed left: font Inter 700` | A stylesheet or font face that side failed to load (blocked URLs aside). Fix that first: a fallback font changes every line of text. | -| `text -"Pricing"` | A line of visible text only the reference has (`+`: only your change). Up to three, then `(+N more)`. | -| `dom sel prop a→b` | Element on both sides whose computed `prop` differs, left value first. | -| `dom +sel` / `-sel` | Element only on the left / only on the right. | -| `dom sel x+8` | It moved without its own style changing; the neighbour or parent listed after it is the cause. | -| `dom sel` | On both sides and unchanged in style or position, so its own pixels changed (an image or canvas). | -| `computed: N findings` | With `--computed`: each `key prop left→right` once, with the routes and widths it was seen at; `dom identical`: the markup matches apart from asset hashes and generated class names, so look at CSS or script. | -| `crops …` | Up to 3 PNGs per comparison, bands first, relative to `results.json`. Left is on top or on the left, and the change is boxed in red. | -| `ERROR …` | Unmeasured, which is neither a pass nor a fail. Exits 3. | -| `accepted:` / `stale accepted:` | Shots whose every difference was accepted, and accepted entries the run no longer saw. See below. | -| `rerun:` | With `--rerun-failed`: how many shots were rerun and how many reused. | -| `right:` | With `--cache-right`: whether the right side was replayed, and from when, or loaded live and recorded. | - -Read text first, then `dom`, then the crops for anything `dom` doesn't explain. Full -detail, including the `--progress` and report forms: [docs/output.md](https://github.com/tmashara/renderdiff/blob/main/docs/output.md). +Read text first, then `dom`, then the crops for anything `dom` doesn't explain. Every token, +the `--computed` block, the `--progress` and report forms and `results.json`: +[docs/output.md](https://github.com/tmashara/renderdiff/blob/main/docs/output.md). ## Accepted differences and reruns -A migration starts with differences that already exist between the untouched local build -and production. Record them once, then change code and re-check only what's red: +Run once before changing code. Against a local build of the base that is base vs base, so +whatever differs varies per load: mask it. Against production, the untouched build already +differs (deploy drift, one-sided embeds); look, record it once, then change code and re-check +only what's red: ``` renderdiff http://localhost:3000 https://example.com / /about --accept "differs before the migration" @@ -219,19 +204,13 @@ renderdiff http://localhost:3000 https://example.com / /about --rerun-failed `--accept ""` writes every difference the run saw to `renderdiff.accepted.json` (next to the config, or in cwd); commit it. Later, a shot whose every difference matches an entry is -listed on an `accepted:` line and counts neither as differing nor 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 and merges it back; it exits 2 if the run differs from -the previous one. Matching rules, what can still hide, and stale entries: +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. 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). -Against a slow reference, add `--cache-right` while iterating: it records the right side's -network traffic in `/.cache/` and replays it for up to an hour. The page still renders -and is shot fresh, so only the round trips are skipped. A replay can't see a deploy, so the run -says `right: replayed from …`; drop the flag for the final run. With `--rerun-failed`, a new -recording covers only the rerun shots. It holds a signed-in session's responses: keep the out -dir out of git. - ## Output Everything lands in the out dir (`./renderdiff-out` by default): @@ -243,66 +222,8 @@ Everything lands in the out dir (`./renderdiff-out` by default): - `{slug}.{width}.c{n}.png`: up to three crops per comparison, left on top or on the left, change boxed in red. - `results.json`: everything above as data, written on every run, errors included, one - result per line, scores rounded down to four decimals (so a shot that differs never - reads as `1`). Its types (`Results` and friends) are exported from the package. - -```jsonc -{ - "meta": { - "tool": "renderdiff", "version": "0.3.2", "generatedAt": "…", - "left": "http://localhost:3000", "right": "https://example.com", - "widths": [1440, 375], "threshold": null, - "clock": "…", // the instant both sides' clocks start at - "blockUrlPatterns": ["…"], "hideSelectors": ["…"], - "masks": [{ "urlPath": "/pricing", "reason": "live star count" }], // no urlPath: every route - "browser": { "name": "chromium", "version": "…" }, // "chrome" when it fell back - "storageState": { "left": "auth.json", "right": null }, // file names only - "rightReplayedFrom": null // --cache-right: when the replayed recording was made - }, - "results": [ - { - "url": "/about", "left": "/about", "right": "/about", // a pair: "/a::/b", "/a", "/b" - "selector": null, "hook": false, // hook: a before hook ran - "width": 1440, "status": "compared", - "score": 0.9714, // share of measured pixels that match - "alignedScore": 1, // score over the aligned rows; null unless there are bands - "diffPixels": 33120, "totalPixels": 1158000, "unstablePixels": 0, - "heightDelta": -24, "widthDelta": 0, // left − right - "regions": [], // left-page px; with bands, from the realigned rows - "bands": [{ "side": "right", "y": 196, "h": 24, // null: too different to align - "elements": [{ // regions have them too; absent: not looked at - "selector": "nav > a[href=\"/pricing\"]", "side": "right", // or "left", "both" - "left": null, "right": { "x": 256, "y": 192, "w": 928, "h": 24 }, - "changed": {}, // "margin-left": ["24px", "16px"], left first; "text" too - "text": "Pricing" // "rightSelector" when the right one differs - }] - }], - "text": { "added": [], "removed": ["Pricing"] }, // added: left only; removed: right only - "failed": { "left": [], "right": [] }, // stylesheets and font faces that didn't load: "font Inter 700", "stylesheet https://…" - "computed": { "dom": 1, "changes": [], "truncated": 0, "unmatched": { "left": [], "right": ["body > nav > a[href=\"/pricing\"]"] } }, // --computed only; null: snapshot failed, "computedError" says why - "images": { "left": "about.1440.left.png", "right": "about.1440.right.png", "diff": "about.1440.diff.png" }, - "crops": [{ - "path": "about.1440.c1.png", "kind": "band", // or "region" - "left": { "x": 256, "y": 196, "w": 68, "h": 0 }, // h 0: where the rows would go - "right": { "x": 256, "y": 196, "w": 68, "h": 24 }, - "layout": "stacked", "scale": 1, "clipped": false // left on top, or on the left ("side") - }] - }, - { "url": "/blank", "left": "/blank", "right": "/blank", "width": 1440, "status": "error", "error": "page did not render …" } - ], - "summary": { - "compared": 1, "errors": 1, "mean": 0.9714, - "worst": { "url": "/about", "width": 1440, "score": 0.9714 }, - "belowThreshold": 0, // accepted shots aside - "differing": 1, // shots with any differing pixel, accepted ones aside - "accepted": 0, // shots whose every difference was accepted - "stale": [], // accepted entries the run measured but didn't see - "computed": [] // --computed: { key, prop, values: [left, right], at: [{ url, widths }] } - } -} -``` - -Paths are relative to the out dir. Results are in route-then-width order. + result per line. Its types (`Results` and friends) are exported from the package; fields: + [docs/output.md](https://github.com/tmashara/renderdiff/blob/main/docs/output.md#resultsjson). ## Why a clean result is trustworthy diff --git a/action.yml b/action.yml index 02f5f0c..828b18c 100644 --- a/action.yml +++ b/action.yml @@ -25,16 +25,16 @@ inputs: description: Fail only when a comparison scores below this (0..1). Without it any difference fails the job; 0 never fails on one. default: "" concurrency: - description: Parallel workers, which is also the most loads production sees at once. + description: Parallel workers, which is also the most loads production sees at once. Default half the cores, 2 to 8 (2 on a hosted runner). default: "" storage-state: - description: Contents of a Playwright storage-state JSON for both sides, from a secret. + description: Contents of a Playwright storage-state JSON for both sides, from a secret. Written to a 0600 temp file, deleted after the run. default: "" accept: description: Record this run's differences as accepted, with this reason. Commit the renderdiff.accepted.json from the artifact. default: "" wait-timeout: - description: Seconds to wait for left to answer before running. + description: Whole seconds to wait for left to answer (any status under 500) before running. Past it, exit-code is 2. default: "300" out: description: Output directory. Overrides the config's outDir. diff --git a/docs/accepted.md b/docs/accepted.md index 3b6524a..fbfc952 100644 --- a/docs/accepted.md +++ b/docs/accepted.md @@ -1,7 +1,10 @@ # Accepted differences and reruns -A migration starts with differences that already exist between the untouched local build -and production. Record them once, then change code and re-check only what's red: +Before changing code, run the untouched build against the reference. Against a local build +of the base commit (the default reference) that is base vs base, so whatever differs varies +per load: mask it rather than accept it. Against production, the untouched build already +differs (deploy drift, one-sided embeds). Look at those differences, record them once, then +change code and re-check only what's red: ``` renderdiff http://localhost:3000 https://example.com / /about --accept "differs before the migration" @@ -63,3 +66,15 @@ earlier run's. It must repeat the previous run: different origins, routes, width (`meta.config` hashes masks, `before` hooks and `locate` sources, hidden selectors, block patterns, extra CSS and storage state file names) or renderdiff version exit 2, as does a missing `results.json`. + +## Replaying the reference (`--cache-right`) + +Against a slow reference, add `--cache-right` while iterating: it records the right side's +network traffic in `/.cache/` (kept when the out dir is wiped) and replays it for up to +an hour, when the recording covers every shot. The page still renders and is shot fresh, so +only the round trips are skipped. A replay can't see a deploy, so the run says +`right: replayed from …`; drop the flag for the final run. With `--rerun-failed`, a new +recording covers only the rerun shots. A request the recording lacks loads live and the shot +lists `failed right: N request(s) not in the recording, loaded live`. The recording holds a +signed-in session's responses: keep the out dir out of git. Exact rules: +[how-it-works.md](how-it-works.md). diff --git a/docs/output.md b/docs/output.md index 3d6e629..f6cd3ed 100644 --- a/docs/output.md +++ b/docs/output.md @@ -1,8 +1,7 @@ # Reading renderdiff's output Left is your change, right is the reference. `+` means only in or more in your change, -`-` only in or more in the reference. The [README](../README.md#reading-the-output) has the -short glossary; this is the full version. +`-` only in or more in the reference. ## The summary @@ -24,20 +23,44 @@ clean: / renderdiff: 2 of 3 routes differ (6 of 15 shots), 0 errors, worst 97.41% /about@1440 — /Users/you/site/renderdiff-out/results.json ``` -A row covers the widths that agree on height and width delta (`h`, `w`), bands, aligned -score and text; the score and region count are then shown as ranges, and `unstable` as the -largest. Bands are `+` for rows only the left has and `-` for rows only the right has, at -`y`, with `~` when the widths put it in different places. A region that is a thin line -across the page shows as `line -1px@y812` instead of counting toward `reg`; past three, `(+N more)`. Up to three text-diff lines -follow (`-"x"` only on the right, `+"x"` only on the left, `(+N more)` past that). Under a -row, `failed` lists stylesheets and font faces a side failed to load (fix those first), -`dom` names up to three elements behind the changes (`@w` when the row covers several -widths: the first one's), and `crops` lists that row's crop files, relative to the -directory `results.json` is in. Errors print in full, grouped across the widths that share -a message. Clean means not one pixel differs, none went unmeasured as unstable and no -stylesheet or font failed; a route with unstable pixels or a failed asset gets its own row. With `--threshold`, the verdict line ends -`, B below 97.00%`. `--progress` gets the per-shot output when piped, `--no-progress` the -summary on a terminal. +A row covers the widths that agree on height and width delta, bands (side and height), +aligned score and text; the score and region count are then shown as ranges, and `unstable` +as the largest. Under a row, `failed` lists stylesheets and font faces a side failed to load +(fix those first), `dom` names up to three elements behind the changes, two properties each +(`@w` when the row covers several widths: the first one's), and `crops` lists that row's crop +files. Errors print in full, grouped across the widths that share a message. Clean means not +one pixel differs, none went unmeasured as unstable and no stylesheet or font failed; a route +with unstable pixels or a failed asset gets its own row. `--progress` gets the per-shot output +when piped, `--no-progress` the summary on a terminal. + +## Tokens + +| Token | Meaning | +| --- | --- | +| `97.41%` | Share of measured pixels that match. A range (`99.12%–99.87%`) when one row covers several widths. A triage signal, not a verdict. | +| `@1440,1152` | The widths a row covers. They agree on height and width delta, bands, aligned score and text; score and region count are ranges. | +| `h-24` / `w+8` | Height / width delta, left − right. The smaller image is padded with magenta, and the padding counts against the score on purpose. | +| `band -24@y196` | 24 rows only the reference has, at y=196 (`+`: only your change has them). `@y~196`: the row's widths put it at different y; the first width's is shown. | +| `aligned 100.00%` | The score with the bands cut out. 100% means the band is the whole difference. | +| `unaligned` | Heights differ but too few rows match to find bands. Use the height delta and regions. | +| `line -1px@y812` | A 1–2px line across the page only the right draws (`+`: only the left; no sign: both, differently). A lost border or divider; not counted in `reg`. | +| `3 reg` | Regions: connected patches of differing pixels. A missing link barely moves the score, but it is still a region. | +| `unstable 1,204px` | Pixels that kept changing between shots of the same load (a ticker, a carousel). Excluded from the score, so the route is never clean. | +| `failed left: font Inter 700` | A stylesheet or font face that side failed to load (blocked URLs aside). Fix that first: a fallback font changes every line of text. | +| `text -"Pricing"` | A line of visible text only the reference has (`+`: only your change). Up to three, then `(+N more)`. | +| `dom sel prop a→b` | Element on both sides whose computed `prop` differs, left value first. | +| `dom +sel` / `-sel` | Element only on the left / only on the right. `+sel::before` / `-sel::after`: a pseudo-element only that side generates. | +| `dom sel x+8` | It moved without its own style changing; the neighbour or parent listed after it is the cause. | +| `dom sel` | On both sides and unchanged in style or position, so its own pixels changed (an image or canvas). | +| `(re-parented)` | After a `dom` entry: paired across a structure change, so its properties may not be the cause. | +| `1 accepted` | That many of the shot's changes are accepted; the rest are new. | +| `computed: N findings` | With `--computed`: each `key prop left→right` once, with the routes and widths it was seen at; `dom identical`: the markup matches apart from asset hashes and generated class names, so look at CSS or script. See [below](#computed-styles---computed). | +| `crops …` | Up to 3 PNGs per comparison, bands first, relative to `results.json`. Left is on top or on the left, and the change is boxed in red. | +| `ERROR …` | Unmeasured, which is neither a pass nor a fail. Exits 3. | +| `renderdiff: …` | The verdict line: routes and shots that differ (accepted ones aside), errors, the worst score, and with `--threshold` how many scored below it. | +| `accepted:` / `stale accepted:` | Routes whose every difference was accepted, and accepted entries the run no longer saw. See [accepted.md](accepted.md). | +| `rerun:` | With `--rerun-failed`: how many shots were rerun and how many reused. | +| `right:` | With `--cache-right`: whether the right side was replayed, and from when, or loaded live and recorded. | ## Scores @@ -63,7 +86,7 @@ because an unmeasured route is not a verified one. | Band | `band -24px at y=196 (right)` | `band -24@y196` | `bands: [{ side: "right", y: 196, h: 24 }]` | | Can't align | `rows too different to align` | `unaligned` | `bands: null` | | Text | `text: 0 added, 1 removed` | `text -"Pricing"` | `text: { added: [], removed: ["Pricing"] }` | -| Regions | (on the report card) | `3 reg` | `regions: [...]` | +| Regions | `3 regions, largest 64×32 at (256,192)` | `3 reg` | `regions: [...]` | | Line | `line -1px@y812` | `line -1px@y812` | `regions[i].line: { y: 812, h: 1, side: "right" }` | | Unstable | `(unstable 1,204px)` | `unstable 1,204px` | `unstablePixels: 1204` | | Failed assets | `failed left: font Inter 700` | `failed left: font Inter 700` | `failed: { left: ["font Inter 700"], right: [] }` | @@ -222,3 +245,68 @@ top (`stacked`, for wide changes) or on the left (`side`, for tall ones). A crop 1,568px on its long edge and 1,568 image tokens (⌈w/28⌉·⌈h/28⌉) and is never scaled below 0.75×; a change too big for that keeps its top rows (or left columns) and is marked `clipped`. Height padding is never cropped. + +## results.json + +Written on every run, errors included, one result per line (so `grep '"url":"/about"'` +pulls a route), scores rounded down to four decimals (so a shot that differs never reads as +`1`). Paths are relative to the out dir; results are in route-then-width order. Its types +(`Results` and friends) are exported from the package. + +```jsonc +{ + "meta": { + "tool": "renderdiff", "version": "0.3.2", "generatedAt": "…", + "left": "http://localhost:3000", "right": "https://example.com", + "widths": [1440, 375], "threshold": null, + "clock": "…", // the instant both sides' clocks start at + "blockUrlPatterns": ["…"], "hideSelectors": ["…"], + "masks": [{ "urlPath": "/pricing", "reason": "live star count" }], // no urlPath: every route + "browser": { "name": "chromium", "version": "…" }, // "chrome" when it fell back + "storageState": { "left": "auth.json", "right": null }, // file names only + "config": "…", // hash of what decides a shot; --rerun-failed needs it unchanged + "rightReplayedFrom": null // --cache-right: when the replayed recording was made + }, + "results": [ + { + "url": "/about", "left": "/about", "right": "/about", // a pair: "/a::/b", "/a", "/b" + "selector": null, "hook": false, // hook: a before hook ran + "width": 1440, "status": "compared", + "score": 0.9714, // share of measured pixels that match + "alignedScore": 1, // score over the aligned rows; null unless there are bands + "diffPixels": 33120, "totalPixels": 1158000, "unstablePixels": 0, + "heightDelta": -24, "widthDelta": 0, // left − right + "regions": [], // left-page px; with bands, from the realigned rows + "bands": [{ "side": "right", "y": 196, "h": 24, // null: too different to align + "elements": [{ // regions have them too; absent: not looked at + "selector": "nav > a[href=\"/pricing\"]", "side": "right", // or "left", "both" + "left": null, "right": { "x": 256, "y": 192, "w": 928, "h": 24 }, + "changed": {}, // "margin-left": ["24px", "16px"], left first; "text" too + "text": "Pricing" // "rightSelector" when the right one differs + }] + }], + "text": { "added": [], "removed": ["Pricing"] }, // added: left only; removed: right only + "accepted": false, // every band and region matched renderdiff.accepted.json + "failed": { "left": [], "right": [] }, // stylesheets and font faces that didn't load: "font Inter 700", "stylesheet https://…" + "computed": { "dom": 1, "changes": [], "truncated": 0, "unmatched": { "left": [], "right": ["body > nav > a[href=\"/pricing\"]"] } }, // --computed only; null: snapshot failed, "computedError" says why + "images": { "left": "about.1440.left.png", "right": "about.1440.right.png", "diff": "about.1440.diff.png" }, + "crops": [{ + "path": "about.1440.c1.png", "kind": "band", // or "region" + "left": { "x": 256, "y": 196, "w": 68, "h": 0 }, // h 0: where the rows would go + "right": { "x": 256, "y": 196, "w": 68, "h": 24 }, + "layout": "stacked", "scale": 1, "clipped": false // left on top, or on the left ("side") + }] + }, + { "url": "/blank", "left": "/blank", "right": "/blank", "width": 1440, "status": "error", "error": "page did not render …" } + ], + "summary": { + "compared": 1, "errors": 1, "mean": 0.9714, + "worst": { "url": "/about", "width": 1440, "score": 0.9714 }, + "belowThreshold": 0, // accepted shots aside + "differing": 1, // shots with any differing pixel, accepted ones aside + "accepted": 0, // shots whose every difference was accepted + "stale": [], // accepted entries the run measured but didn't see + "computed": [] // --computed: { key, prop, values: [left, right], at: [{ url, widths }] } + } +} +``` diff --git a/package.json b/package.json index 225383d..0a45d29 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "renderdiff", "version": "0.3.2", - "description": "Visual-parity checker for website migrations: screenshot-diffs your branch against production across viewport widths, and names the DOM element and CSS property behind each change. Built for coding agents (Claude Code, Codex, Cursor).", + "description": "Visual-parity checker for website migrations: screenshot-diffs your change against a local build of the base (or production) across viewport widths, and names the DOM element and CSS property behind each change. Built for coding agents (Claude Code, Codex, Cursor).", "type": "module", "license": "MIT", "author": "Timur Mashara", diff --git a/renderdiff.config.example.ts b/renderdiff.config.example.ts index f70d7f2..206eb6c 100644 --- a/renderdiff.config.example.ts +++ b/renderdiff.config.example.ts @@ -6,11 +6,11 @@ import type { RenderdiffConfig } from "renderdiff"; export default { - // left: the build you changed (usually localhost). right: the reference you must match - // (usually production). The +/- signs in the output and text.added/removed in - // results.json are written from left's point of view. - left: "http://localhost:3000", - right: "https://example.com", + // left: the build you changed. right: the reference you must match, best a local build + // of the base commit (production adds deploy drift). The +/- signs in the output and + // text.added/removed in results.json are written from left's point of view. + left: "http://localhost:3001", + right: "http://localhost:3002", // Diffed when you run bare `renderdiff` with no positional routes. `/a::/b` (or // `{ left: "/a", right: "/b" }`) loads /a on the left and /b on the right — for a page @@ -53,7 +53,8 @@ export default { // Replaces the default set (1440, 1152, 896, 704, 375). widths: [1440, 896, 375], - // Non-zero exit if any comparison scores below this. + // Exit 1 only when a comparison scores below this, instead of on any difference. + // 0 never fails on one. threshold: 0.97, // Relative to the directory you run in. Wiped at the start of each run. @@ -77,7 +78,14 @@ export default { // Raw CSS injected after the built-in rules. An escape hatch for the odd case that // a selector list cannot express. - extraCss: `.hero video { visibility: hidden !important }`, + extraCss: `.chat-launcher { visibility: hidden !important }`, + + // Videos are kept from playing (each shows its poster) and video.js captions and + // control bars are hidden. false, or --no-freeze-video, lets them play. + freezeVideo: true, + + // Mask every iframe on every route (embeds that differ per load). Same as --mask-media. + maskMedia: false, // Also diff every element's computed style, and say whether the markup is identical // apart from asset hashes. Same as --computed. Pixels still decide the score. @@ -96,7 +104,7 @@ export default { // // Each needs exactly one of `selector` (a Playwright selector) or `locate`. Without // `urlPath` it applies to every route; on a pair it matches either side's path. - // `maskMedia: true` (or --mask-media) adds one for iframes. + // `--mask ` adds one for every route. masks: [ { // Baked in at build time from a nightly job, so a local tree and a production diff --git a/skills/renderdiff/SKILL.md b/skills/renderdiff/SKILL.md index ab6b8a3..6f170e1 100644 --- a/skills/renderdiff/SKILL.md +++ b/skills/renderdiff/SKILL.md @@ -7,64 +7,69 @@ allowed-tools: Bash(npx renderdiff:*), Bash(npx renderdiff@latest:*), Bash(rende # renderdiff ```bash -npx renderdiff@latest http://localhost:3000 https://example.com /about --width 1440 +npx renderdiff@latest http://localhost:3001 http://localhost:3002 / /about /pricing ``` -Left (first origin) = your change; right (second) = the reference. `+` means only/more in -your change, `-` only/more in the reference. First run: `npx playwright install chromium`. -Flags: `--help`. Moved page: `/old::/new`. One component: `--selector`. Click-gated state: -a config `before` hook. Signed in: `--storage-state auth.json`. Per-load noise: `--mask `, `--mask-media`. When each is -legitimate: [reference.md](reference.md). +First origin = left = your change; second = right = the reference. `+` is only/more in your +change, `-` only/more in the reference. Default widths 1440, 1152, 896, 704, 375. First run: +`npx playwright install chromium`. Flags: `--help`. Details: [reference.md](reference.md), +the § named at each step. + +## Pick the mode + +| Change | Run | +| --- | --- | +| CSS only, markup untouched (refactor, dead-CSS removal, token swap) | pixels + `--computed`. 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, focus and open menus aren't shot without a `before` hook, and dead-CSS removal breaks exactly those. | +| Markup changes (framework, template or component migration) | pixels. `--computed` findings would only be hints. | +| Dependency or build upgrade | pixels, plus `--computed` if the markup should be identical. | +| One component | pixels with `--selector `. | + +Pixels decide the score and the exit code in every mode. ## Loop -1. **Reference: the base, built locally.** When the base can be built, it is the default - reference: the base commit in a `git worktree`, a production build of it on another - port as right, your change as left, both up with the same content. Same data, fonts and CDN, so every diff is yours. - Production as right is a secondary check afterwards: it adds deploy drift, one-sided - third-party content and CSP errors. Serve production builds on both sides: dev overlays - exist only on one side (Next's and Astro's are hidden; others go in `hideSelectors`). - Routes: one per template or layout, from the sitemap or router; skip search results, - pagination and admin. `--dry-run` shows the URL pairs. -2. **Baseline first.** Before changing code, run the base against the reference. Against - the base build that is base vs base, so whatever differs varies per load: mask it - (`--mask-media` for iframes; video is frozen by default; `--mask ` or a config - mask with a `reason` for the rest), then rerun until the baseline is clean. Against - production, `--accept "differs before the change"` what is stable drift. Mask or accept - only what you looked at, never to get green. -3. One route, one width. A row: score, `h±N`/`w±N` height/width delta, - `band`, `aligned`, `N reg`, `unstable Npx` (moving pixels, unmeasured), `text`. -4. `failed` first: a stylesheet or font one side didn't load explains the whole row; fix - that and rerun. Then `text`: `-"x"` is missing from your change, `+"x"` only in yours. -5. `band -24@y196`: 24 rows only the reference has. `aligned 100.00%`: the band is the - whole difference. `unaligned`: see reference.md. -6. `dom` before crops. `sel prop l→r`: computed value, left first; find the *rule*. - `+sel`/`-sel`: only left/right. `sel x+8`: moved; the cause is listed after it. - Bare `sel`: its own pixels changed (image, canvas). - CSS refactor or dead-CSS removal: add `--computed`. Each `computed:` finding is - `key prop left→right`, collapsed across routes and widths. `dom identical` means the - cause is CSS or JS, not markup. -7. `Read` the crops under each row (next to results.json) for what `dom` doesn't explain. - Left is on top or left; red box = change, red seam = missing rows. -8. Fix or justify every band, region and text line. After each migration step, - `--rerun-failed` (same arguments) reruns only what isn't clean or accepted; add - `--cache-right` to replay the reference's traffic from the last such run (an hour at most) - instead of fetching it again. Finish with all routes at default widths, without - `--cache-right`. For a multi-width row, open the widest and narrowest crop. - `accepted:` routes are known; a row saying `1 accepted` still has something new. +1. **Serve both sides as production builds**: the base commit in a `git worktree` on one + port (right), your change on another (left), same data (static build: + `npx serve -l 3002 dist`). Production as the reference is a later second pass. Routes: + every page the change can reach, from the sitemap; `--dry-run` prints the pairs. + § Reference and routes; moved page, component, sign-in, click state: § Scoping. +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 (`--mask-media` for iframes, `--mask ` 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. 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` → + `failed` (a missing stylesheet or font explains the whole row: fix, rerun) → `text` → + `h`/`w`, `band`, `aligned`, `line` → `dom` (`sel prop l→r` is a computed value: find the + *rule*) → `computed:` → `Read` the `crops` for what `dom` doesn't explain (multi-width row: + widest and narrowest). Every token: § Output. +4. **Decide every band, region, line and text line:** + + | It is | Do | + | --- | --- | + | Caused by your change, not intended | Fix it. | + | In the baseline too, or intended, and you opened it | `--accept ""` on the OS that checks (Mac entries go stale on Linux CI). | + | Varying per load (base vs base shows it) | Mask it, with a `reason`. | + | `unstable`, a width change, or `unaligned` with a height change | Can't be accepted (§ Masks, accepts and thresholds): fix or report. | -Exit: 0 no differing pixels, or all accepted (unstable pixels or a failed asset alone still -exit 0: read their rows) · 1 a difference (with `--threshold`: below it), even on `--accept` for one it can't accept (unstable pixels, width change, unaligned height change) · 2 bad args/config/origin down · 3 a route errored (unmeasured) or crash. 1 wins over 3. -All clean? Confirm both sides actually rendered. + 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. + All clean? Confirm both sides actually rendered. -**Before you mask, lower the threshold, drop a route or skip widths,** read -reference.md's Rationalizations. +Exit 0 is not verified: unstable pixels or a failed asset alone exit 0, so report them. 1: an +unaccepted difference. § Exit codes. ## Verdict (all four, in order) 1. **Numbers**: the `renderdiff:` line and each differing row. -2. **What you saw**: per route and width, element and property ("/pricing @1440: `.cta` margin-left 24px→16px"). -3. **Not verified**: errors, skipped widths, masks, unopened regions, unlisted routes, baseline drift and its reference (base build or production). +2. **What you saw**: per route and width, element and property ("/pricing @1440: `.cta` + margin-left 24px→16px"). +3. **Not verified**: errors, unstable or failed-asset rows, skipped widths, masks, accepts, + hooks, unshot states (hover, open menus), unopened regions, unlisted pages, and the + reference (base build or production). 4. **Call**: parity, regression, or expected change, and why. A score without looking is not a verdict: 99.6% can be a missing nav link. diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md index 0cf8619..b6f42cd 100644 --- a/skills/renderdiff/reference.md +++ b/skills/renderdiff/reference.md @@ -1,168 +1,309 @@ # renderdiff reference -Left is your change, right is the reference: `+` is only/more on the left, `-` only/more on the right. +Left is your change, right is the reference: `+` is only/more on the left, `-` only/more on +the right. Sections: Reference and routes · Output · Errors · `--computed` · Masks, accepts +and thresholds · Rationalizations · Exit codes · Iterating · Scoping · Config file · +results.json · Gotchas. -## Triage +## Reference and routes -| What you see | What it means | +- **Base build vs change build, both local, is the default.** The base commit in a + `git worktree`, a production build of each on its own port, same content, data, fonts and + CDN, so every difference is yours. Production as the reference mixes in deploy drift, + one-sided embeds (job boards, ads) and CSP blocks: a second pass only, and say which you used. +- **Production builds on both sides.** Dev overlays exist on one side only; Next's and + Astro's are hidden by default, others go in `hideSelectors`. +- **Static builds:** `npx serve -l 3002 dist` (or any static server). Match the real host's + clean URLs and trailing slashes, or a route 404s or redirects on one side only. +- **Routes** are literal (no globs, no discovery): every template or page the change can + reach, from the sitemap or router; skip search results, pagination and admin. For removed + CSS, every page where its selectors could match. Pages you don't list go under Not verified. + Routes normalize to no trailing slash (`/` stays `/`). `--dry-run` shows how each was read. +- **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. +- **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. + +## Output + +Piped (what an agent sees), stdout is one compact summary; `--progress` prints a line per shot +instead, `--no-progress` forces the summary on a terminal. + +``` +Routes: 3 +clean: / +accepted: /blog +/about clean @1152,896,704 + @1440 97.41% h-24 band -24@y196 aligned 100.00% text -"Pricing" + failed right: font Inter 700 + dom -nav > a[href="/pricing"] "Pricing" + crops about.1440.c1.png + @375 ERROR HTTP 404 at http://localhost:3001/about +computed: … (with --computed, see below) +renderdiff: 1 of 3 routes differ (1 of 15 shots), 1 error, worst 97.41% /about@1440 — …/results.json +``` + +Before the summary, when they apply: `Config: `, `accepted N difference(s), pruned M +stale — ` and `not accepted: N differing shot(s) can't be (2 unstable, 1 width change)` (`--accept`), `rerun: …` (`--rerun-failed`), `right: replayed from …` or +`right: loaded live and recorded …` (`--cache-right`), `stale accepted: /a@1440 …`. After it, +on stderr: `✗ 2 routes differ (10 shots).` (`below 97.00%` with `--threshold`). + +**Lines** + +| Line | Meaning | +| --- | --- | +| `clean: /a /b` | Not one pixel differs, none unstable, no asset failed. Suspect it until you confirm both sides rendered: two identical error pages diff as clean. | +| `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 ` | 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 `) 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. | +| ` 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`. | +| ` @w ERROR …` | Unmeasured. Grouped across widths sharing a message. See Errors. | +| `renderdiff: D of R routes differ (S of T shots), E errors, worst …` | `S` counts unaccepted shots with any differing pixel; `worst` leaves accepted shots out. With `--threshold`: `, K below 97.00%`. | + +**Row tokens**, in order + +| Token | Meaning | +| --- | --- | +| `97.41%` / `99.12%–99.87%` | Share of measured pixels that match, floored to 2 decimals (a differing shot never reads 100.00%). Triage, not a verdict. | +| `h-24` / `w+8` | Height / width delta, left − right. The smaller shot is padded magenta; padding counts against the score on purpose. `w±` is usually horizontal overflow. | +| `unaligned` | Heights differ but too few identical rows to align: very different pages, edits over 2,000 rows, or sub-threshold noise on every row. No bands; use the delta and regions. | +| `band -24@y196` | 24 rows only the right has, at y=196 (`+`: only the left). `@y~196`: widths put it at different y; the first width's. Repeated identical rows can slide a band's y. | +| `aligned 100.00%` | Score with the bands cut out; 100% = the bands are the whole difference. Only with bands. | +| `line -1px@y812` | A 1–2px line across at least half the page that only the right draws (`+`: only the left; no sign: both, differently). Barely moves the score, large visually: a lost border or divider. Look for a `::before`/`::after` in `dom`. Past three: `(+N more)`. Not counted in `reg`. | +| `3 reg` / `2–3 reg` | Regions: connected patches of differing pixels on a 16px grid. With bands, from the realigned rows, so content a band merely pushed isn't one. | +| `unstable 1,204px` | Pixels that kept changing between shots of the same load on one origin (ticker, carousel, video with `--no-freeze-video`). Painted out on both sides, excluded from the score; the route is never clean. Large: a big area went unmeasured, look at the magenta in the full shots. | +| `1 accepted` | That many of the shot's bands and regions are accepted; the rest are new. `dom` names only the new. | +| `text +"x" -"y"` | Lines of visible text only on the left (`+`) / right (`-`), added first. Up to three, then `(+N more)`. Masked elements are left out. | + +**`dom` entries** (left first, `;`-separated) + +| Entry | Meaning | +| --- | --- | +| `sel margin-left 24px→16px` | On both sides; those computed values differ. A symptom: find the rule that sets it, check it changed on purpose. | +| `sel "old"→"new"` | Its text differs. | +| `+sel "x"` / `-sel "x"` | Only on the left / only on the right. | +| `+sel::before` / `-sel::after` | A pseudo-element only the left / right generates. `sel::before height 1px→2px`: on both, differing in `content`, size, background, top/bottom border or `box-shadow`. A lost divider often shows only here. | +| `sel x+8 y-4` | It moved or resized, no style of its own changed: the neighbour or parent listed after it is the cause; none listed, look above it. | +| `sel` (nothing after) | On both, unchanged and unmoved: its own pixels changed (image source, canvas, SVG). Open the crop. | +| `… (re-parented)` | Paired across a structure change (grandparent/parent tags differ); its properties may not be the cause. Open the crop. | +| no `dom` line | Nothing named: a band holds nothing only one side has, past the first five bands and regions, fixed chrome covering it, shadow DOM or iframe, or the 5s probe timed out. Open the crop. | + +Each selector is unique on its side, so `--selector` takes it. + +**Crops**: left on top (`stacked`) or on the left (`side`); 1px red box round the change; on +the side lacking a band's rows, a 2px red seam where they would be. Within 1,568px and 1,568 +image tokens, never below 0.75×; too big keeps the top rows and is `clipped` in results.json. +Height padding is never cropped: for a height delta, open `{slug}.{width}.diff.png`. + +Report (`--open`, for a human): green from 99.5%, amber to 97%, red below. + +## Errors + +`ERROR` rows are unmeasured, neither pass nor fail, and exit 3. Report them as unverified. + +| Error | Cause and fix | | --- | --- | -| `h±N` | One side is taller (`+`: left). The shorter shot is padded with magenta, and the padding counts against the score on purpose. | -| `w±N` | One side is wider (`+`: left), usually horizontal overflow. The narrower shot is padded with magenta. | -| Everything on the `clean:` line | Suspect before you celebrate. Confirm both sides actually rendered: two identical error pages diff as clean. | -| `ERROR HTTP 404 at …` (or any status ≥ 400) | That side answered with an error status. Usually a route that doesn't exist on one origin, or a dev server not ready. | -| `ERROR page did not render on either side (…)` | Both sides had under 200 chars of text and no visible images, SVG, canvas, video, iframes or form controls, so renderdiff refused to score two blanks as a match. Usually a failed asset or an app that never mounted. One blank side isn't refused; it shows up as a low score. | -| `ERROR` rows | Unmeasured, not failed. They exit 3 because an unmeasured route isn't a verified one. Report them as unverified. | -| `failed left: font Inter 700` / `stylesheet …` | That side didn't get the asset (404, CORS, a font CDN that refuses localhost). Fix it before reading anything else on the row: a fallback font reflows every line. | -| Uniform low score, whole page shifted | Almost always a height or font-loading difference near the top pushing everything down. A `band` names where; compare left and right at that `y`. No band means the shift is horizontal or the content itself changed. | -| `text -"x" +"y"` | Content differs: `-` lines are on the reference only, `+` on your change only. `(+N more)` means more lines; the report card or results.json lists them all. | -| `unaligned` | The pages differ in height but share too few identical rows to align, so no bands. Either they are very different, the edits total more than 2,000 rows, or sub-threshold noise touches every row. Use the height delta and regions. | -| `dom sel margin-left 24px→16px` | That element is on both sides and those computed values differ, left first. The value is a symptom: find the rule that sets it, and check it changed on purpose. | -| `dom +sel "x"` / `dom -sel "x"` | That element exists only on the left (your change) / only on the right. | -| `dom -sel::before` / `+sel::before` | That pseudo-element is generated only on the right / only on the left; `sel::before height 1px→2px` is one on both that differs. A lost divider often shows only here. | -| `dom … (re-parented)` | Paired across a structure change (ancestor tags differ), so the listed properties may not be the cause. Open the crop. | -| `line -1px@yN` | A 1–2px line across the page that only the right draws (`+`: only the left, no sign: both, differently). Small in pixels, large visually: a lost border or divider. Check `dom` for a `::before`/`::after`. | -| `dom sel x+8` | It moved but no style of its own changed: the neighbour or parent listed after it is the cause; with none listed, look above it. | -| `dom sel` (nothing after it) | On both sides, and no compared style changed and it didn't move: its own pixels did (an image's source, a canvas, an SVG). Open the crop. | -| No `dom` line | Nothing was found under the change, a band whose rows hold nothing only one side has, past the first five bands and regions, or the probe timed out. Open the crop. | -| `band …@y~N` | Widths collapsed into one row put the band at different `y`; `N` is the first width's. | -| `unstable Npx` | Pixels that kept changing between shots of the same load on one origin (a ticker, a carousel, a video with `--no-freeze-video`). Painted out on both sides and excluded from the score. A large number means a big area went unmeasured: look at the magenta on the full shots. Such a route is never on the `clean:` line. | -| `ERROR selector "…" matched N elements on left (/a), expected 1` | A selector must match exactly one element per side. Make it more specific (`>> nth=0`, an id, `data-test`), or list the route once per element. | -| `ERROR selector "…" has no box on …` | It matched an element that isn't rendered (`display: none`, zero size). | -| `accepted: /a /b` | Every difference on those routes matches `renderdiff.accepted.json`. Known, not verified again: say so in the verdict. | -| `N accepted` on a row | Some of that shot's changes are accepted; the rest are new. `dom` names only the new ones. | -| `stale accepted: /a@1440` | An accepted difference wasn't seen. It was fixed, or the page changed under it; `--accept` over that route and width prunes it. | -| `ERROR page did not settle: Npx unstable at …` | More than 25% of the page kept changing between shots, so too little was measured to score. Mask or stop the moving part. | - -Report colouring (`--open`, for a human): green above 99.5%, amber to 97%, red below. +| `HTTP 404 at …` (any ≥ 400) | That side answered an error: a route missing on one origin, or a server not ready. | +| `page did not render on either side (…)` | Both sides under 200 chars of text and no visible image, SVG, canvas, video, iframe or form control. Usually a failed asset or an app that never mounted. One blank side isn't refused; it scores low. | +| `page did not settle: Npx unstable at …` | Over 25% of the page kept changing. Mask or stop the moving part. | +| `page is Npx tall at Wpx wide, past the …px sanity ceiling …` | Taller than 57,600,000px ÷ width (never under 40,000px): a runaway layout, not a page. | +| `selector "…" matched N elements on left (/a), expected 1` | Make it unique (an id, `data-test`, `>> nth=0`), or list the route once per element. | +| `selector "…" has no box on …` / `is off the page on …` | Matched an element not rendered (`display: none`, zero size) or outside the page. | +| `before hook failed on left: …` | The hook threw. Never retried. | + +A failed `--computed` snapshot (`snapshot failed on /a@1440 (…)` on the `computed:` line) is +not a route error: the pixel result stands. + +## `--computed` + +After each shot, reads the computed style (the `dom` properties plus `content`) of every +rendered element and its `::before`/`::after`, on both sides, and compares the markup. One +block after the rows: + +``` +computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so findings there are hints + body > div.page > nav > a[href="#blog"] margin-left 24px→16px /about@1440,375 /@1440,375 +4 routes + body > footer > a.cta::after content "→"→none /about@1440 + (+N more in results.json) + truncated: only the first 500 changes kept on /a@1440 (+12) + unmatched /pricing@1440 -body > main > section.plans:nth-of-type(3) +``` + +- A finding is `key prop left→right`, then up to three `route@widths` (`+N routes`). One per + distinct change across the run, most widespread first, accepted shots included; 20 shown. + `--progress` rows say `computed dom identical, N change(s)` or `dom differs (N)`. +- `dom identical on X of Y`: every walked element's tag, attributes and own text match, + bundler hashes in `src`/`href`/`srcset`/`poster` and generated class names (`css-1q2w3e`, + `Button_root__a1b2c`) aside. Then a pixel difference comes from CSS or script, and findings + are exact causes. +- `differs /a (N)`: N elements differ or are one-sided; findings there are hints. A class + renamed on a wrapper re-keys its whole subtree, so a style change under it shows only as + `dom differs` and `unmatched`. +- `unmatched`: outermost elements only one side has, `+` left, `-` right. +- Keys are selector paths from `body` (`:scope` with `--selector`), usable with + `querySelector`. Elements match by key, so an injected node doesn't misalign the rest; an + inserted same-tag sibling still shifts `:nth-of-type` after it. +- Collapsed to the cause: an inherited property the parent has the same change for is + dropped, and so is a width inside a parent whose width changed, or a height around a child + whose height changed (unless set in px). Shown on one side and `display: none` on the other + is one `display` finding. A pseudo-element one side no longer generates is `content` against + `none`. +- A finding on a clean route is a change you can't see in this state: a hidden element + (closed menu), another breakpoint, `:hover`/`:focus` (not snapshotted). Decide it; a + `before` hook can open the state. +- Fails per shot (reported, pixels stand) past 15s or 50,000 elements. Not walked: SVG + internals, shadow DOM, iframes, masked and `display: none` subtrees. + +## Masks, accepts and thresholds + +| Tool | Legitimate for | Never for | +| --- | --- | --- | +| Mask (`--mask `, config `masks` with `reason`, `--mask-media`) | Content *proven* to vary per load: a base-vs-base baseline differs there (clocks, star counts, rotating quotes, embeds). | Anything that differs only after your change. | +| `--accept ""` | A difference you opened that exists before your change (baseline vs production) or is intended, with a reason saying which. | Getting green. | +| `--threshold <0..1>` | A CI gate on the exit code. | Reaching green; the difference is still there. | + +- Every mask is coverage surrendered and listed in the report with its reason. `--mask-media` + gives up every iframe. Video is not masked: it is frozen by default (no `video` plays, each + shows its poster, video.js captions and control bars hidden), so its box is still compared. + `--no-freeze-video` lets it play: expect `unstable` or `did not settle`. +- Masks hide text too, so masked text leaves the text diff. +- Accepted entries go to `renderdiff.accepted.json` next to the config (or cwd), one per band + or region, scoped by the run's routes and widths. A match ignores `y` and needs the same + kind, side, box, pixel hash (4 bits a channel) and named elements, so anything else drawn + there still surfaces. Never accepted: a shot with unstable pixels, a width delta, or a height + delta without bands; `--accept` exits 1 on those. A new change can make an accepted one + re-read as different (repeated rows aligning differently): look, then accept again. +- **Accept where you check.** The pixel hash isn't portable: entries accepted on macOS mostly + come back stale on a Linux CI runner. For CI, accept in CI. +- `stale accepted: /a@1440`: an accepted difference wasn't seen (fixed, or the page changed + under it). `--accept` over that route and width prunes it. +- Analytics, consent and A/B tooling are already blocked on both sides. Something + that still flickers between runs is a candidate for `blockUrlPatterns` before a mask. ## Rationalizations | Thought | Reality | | --- | --- | | "Worst is 99.1%, no regressions." | You reported a number, not a check. Open the worst route's crops. | -| "99.6%, it's noise." | Check `text` and the region count first. A missing nav link is 99.6% and one `-` line. | +| "99.6%, it's noise." | Check `text`, `line` and the region count first. A missing nav link is 99.6% and one `-` line. | | "It's probably just fonts / antialiasing." | "Probably" is exactly what the crop resolves. Look. | | "`dom` says margin, done." | It's a computed value. Confirm the source rule changed on purpose, and still open the crop when the region is large or `dom` names nothing. | -| "The crops looked fine, done." | There are at most three: bands, then the largest regions. Check the region count, any `clipped` crop in results.json, and open the diff PNG for the rest and for any height delta: padding is never cropped. | -| "Masking the header gets this to 100%." | Every mask is coverage surrendered. Mask only content *proven* to vary per load (clocks, star counts, rotating quotes), with a `reason`, which the report prints verbatim. Differing base vs base is that proof; `--mask-media` still gives up every iframe. | -| "I'll `--accept` it so the run is green." | Accept only differences you opened and that exist before your change (or are intended), with a reason that says which. | -| "I'll lower `--threshold` until it passes." | `--threshold` relaxes the exit code; the difference is still there. It's a CI gate, not a dial for reaching green. | -| "That route errors, I'll drop it from the list." | Shrinking the route list shrinks what you verified. Fix it, or say it's unverified. | +| "The crops looked fine, done." | There are at most three. Check the region count, any `clipped` crop, and the diff PNG for the rest and for any height delta. | +| "`--computed` found nothing, so pixels don't matter." | Pixels decide. A finding list is only complete where `dom identical`. | +| "Masking the header gets this to 100%." | Mask only what a base-vs-base baseline shows varying, with a `reason`. | +| "I'll `--accept` it so the run is green." | Accept only differences you opened that predate your change or are intended. | +| "I'll lower `--threshold` until it passes." | It relaxes the exit code; the difference is still there. | +| "That route errors, I'll drop it." | Shrinking the route list shrinks what you verified. Fix it, or say it's unverified. | | "One width is enough." | Migrations break at one width and not others. That's why there are five defaults. | -| "A `before` hook that hides that element on the left gets this clean." | That hook is a mask with no `reason` in the report. A hook brings both sides to the same *state* (opens the menu, dismisses a modal both show, logs in); it never edits one side to match the other. | +| "A `before` hook that hides that element on the left gets this clean." | That hook is a mask with no `reason`. A hook brings both sides to the same *state*; it never edits one side to match the other. | -## results.json +## Exit codes + +| Code | When | +| --- | --- | +| 0 | No unaccepted shot differs (with `--threshold`: none scores below it) and no route errored. Unstable pixels or a failed asset alone exit 0: read their rows. | +| 1 | An unaccepted shot differs (with `--threshold`: scores below it; `--threshold 0` never fails). Also on an `--accept` run for what can't be accepted. Wins over 3. | +| 2 | Bad arguments or config; an origin not responding; a bad storage state or `renderdiff.accepted.json`; an out dir holding files renderdiff didn't write; `--rerun-failed` that doesn't repeat the last run. | +| 3 | A route errored (unmeasured), or the run crashed (e.g. no browser). | + +## 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 + origins, routes, widths, config (masks, hooks, hidden selectors, CSS, storage state, + `--computed`) and version as the run it continues, or it exits 2. +- **`--cache-right`** replays the right side's recorded traffic (`/.cache/`, kept by the + wipe) for up to an hour, if the recording covers every shot; otherwise loads live and records. + The page still renders live, so `dom` and the refusals hold, but a deploy to the reference + goes unseen: never verdict from a replayed run. `failed right: N request(s) not in the + recording, loaded live`: part replay, part live; drop the flag rather than trust or accept it. +- **The out dir is wiped** at the start of every run except `--rerun-failed`. Keep evidence + with `--out renderdiff-before` / `--out renderdiff-after`. +- Lower `--concurrency` (default half the cores, 2–8) when the right side is someone's live site. + +## Scoping -Scripts, and drilling into one route: every score, region (`x,y,w,h,pixels`, left-page -px, `line` `{ y, h, side }` when it is a thin line), band, their `elements` (`selector`, `side`, each side's box, `changed`, `text`, and -`rightSelector` when the right was found under another selector, `reparented` when paired -across a structure change; absent when not looked -at, `[]` when nothing was named), full text diff, image path and crop (`kind`, each side's box with `h` 0 at an -insertion point, `layout` `stacked` = left on top or `side` = left on the left, `scale`, -`clipped`), `selector` (`{ left, right }` or null), with `--computed` a `computed` per result -(`dom`, the count of elements whose markup differs, with 0 meaning identical; `changes` -`{ key, prop, values }`, the first 500, `truncated` counting the rest; `unmatched` keys per side; null if the snapshot failed, with `computedError`), one result per line, so `grep '"url":"/about"'` pulls a route. -Paths are relative to the out dir. `summary` has `compared`, `errors`, `mean`, `worst`, -`belowThreshold` and `differing` (unaccepted shots with any differing pixel: without -`--threshold`, any exits 1), plus `computed` with `--computed`: every change once, with the routes and widths it was seen at. `meta` records origins, widths, threshold, the pinned clock, block -patterns, hidden selectors, mask reasons, the browser (`chromium`, or `chrome` when it fell -back to the system Chrome), each side's storage state file name, and `rightReplayedFrom` -(with `--cache-right`, when the replayed recording was made; also on each replayed result). `hook: true` marks a -route a `before` hook ran on. The normal loop doesn't need it. +- **Moved pages:** `/pricing::/plans` loads `/pricing` left, `/plans` right. Splits on the + first `::` followed by `/`, so `/q?x=std::vector` and `pricing::plans` are single routes. Named + `/a::/b` in stdout and `url`; files `{a}~{b}.{width}.*.png`. +- **One component:** `--selector ` (or `--left-selector` + `--right-selector`, or a route + object's `selector: ".x" | { left, right }`) compares the one element it matches, exactly one + per side, in its own pixels. A CLI selector applies to every route and replaces the config's. + Named `/a [.x]`; files `{slug}@{sel}.{width}.*.png`. The whole page still loads; it's shot at + scroll 0, so fixed or sticky overlays over it are included (`hideSelectors` them); a + transformed element is shot at its axis-aligned box. `xpath=` and `>>` work; pseudo-elements + are rejected; iframes can't be reached. +- **`before` hooks** (config only: `before: async (page, { side, route, width }) => …` on a + route object, or top level for every route without its own) run after load and the HTTP + check, before settle, masks and the shot. Legitimate: open a menu or tab, dismiss a modal or + banner *both* sides show, sign in, set a carousel to slide 1 on both. Not: branching on + `side` to make the sides look alike, hiding or removing an element on one side. `side` is for + markup that legitimately differs. Say in the verdict that a hook ran (`hook: true`). +- **Signed-in pages:** `npx playwright codegen --save-storage=auth.json `, then + `--storage-state auth.json` (or `--left-`/`--right-storage-state`, or config `storageState`, + relative to the config file). The file holds live session tokens: never commit or paste it, + add it to `.gitignore`. The out dir then holds signed-in screenshots and text: keep it out of + git too. ## Config file -Flags cover a one-off run. A `renderdiff.config.{ts,mts,js,mjs}` in the working directory -covers a repo you diff repeatedly, and expresses what flags can't: masks, extra selectors -to hide, extra URLs to block. **CLI flag > config file > default.** +`renderdiff.config.{ts,mts,js,mjs}` in cwd (or `--config`) holds what flags can't. **CLI flag > +config file > default.** A plain `export default {}` needs no import. ```js -// renderdiff.config.mjs export default { - left: "http://localhost:4000", - right: "https://example.com", - routes: ["/", "/about", "/pricing::/plans", { left: "/blog", right: "/posts" }, - { left: "/pricing", selector: "[data-test=plans]" }], + left: "http://localhost:3001", + right: "http://localhost:3002", + routes: ["/", "/about", "/pricing::/plans", { left: "/pricing", selector: "[data-test=plans]" }], widths: [1440, 896, 375], - threshold: 0.97, hideSelectors: [".site-cookie-banner"], + blockUrlPatterns: ["**://*.my-tracker.example/**"], masks: [{ selector: "[data-star-count]", reason: "live star count", urlPath: "/pricing" }], + maskMedia: false, // --mask-media + freezeVideo: true, // --no-freeze-video sets false + computed: false, // --computed }; ``` A mask takes exactly one of `selector` or `locate: (page) => Locator`; without `urlPath` it -applies to every route, and on a pair it matches either side's path and paints both. A plain -`export default {}` needs no import; a type import from "renderdiff" is for editor types only. Without a config, `--mask ` (repeatable) adds a mask on every -route, after the config's; `--mask-media` (config `maskMedia: true`) adds one for -`iframe`; videos are already kept from playing, with video.js overlays hidden, unless `--no-freeze-video`. Both are listed in the report like any mask. [`renderdiff.config.example.ts`](https://github.com/tmashara/renderdiff/blob/main/renderdiff.config.example.ts) -annotates every field. +applies to every route, and on a pair it matches either side's path. `--mask ` adds to the +config's masks. Also: `threshold`, `outDir`, `concurrency`, `extraCss`, `before`, +`storageState`. `hideSelectors`: match the element **exactly** (consent scripts stamp classes on +``; a loose selector blanks the whole document and blank matches blank), and they hide +rather than remove. + +## results.json + +For scripts and drilling into one route; the loop doesn't need it. One result per line, so +`grep '"url":"/about"'` pulls a route. Paths are relative to the out dir. -Two rules for `hideSelectors`: match the element **exactly** (consent scripts also stamp -classes on ``, and a loose selector blanks the whole document; blank matches -blank, so everything "passes"), and these hide rather than remove (removing after the -cookie script ran wedges the renderer). +- **Each result:** `url`, `left`, `right`, `selector` (`{ left, right }` or null), `hook`, + `width`, `status` (`compared` or `error` with `error`); `score`, `alignedScore`, + `diffPixels`, `totalPixels`, `unstablePixels`, `heightDelta`, `widthDelta`; `regions` + (`x,y,w,h,pixels`, left-page px, `line` `{ y, h, side }`, `accepted` reason); `bands` (`side`, + `y`, `h`, or null when unaligned); each with `elements` (`selector`, `side`, each side's box, + `changed` `{ prop: [left, right] }`, `text`, `rightSelector`, `reparented`; absent when not + looked at, `[]` when nothing was named); `text` `{ added, removed }`; `failed` `{ left, right }`; + `images`; `crops` (`kind`, each side's box with `h` 0 at an insertion point, `layout`, `scale`, + `clipped`); `accepted`; `rightReplayedFrom`; with `--computed`, `computed` (`dom`, 0 = + identical; `changes` `{ key, prop, values }`, first 500; `truncated`; `unmatched`) or null with + `computedError`. +- **`summary`:** `compared`, `errors`, `mean` and `worst` (accepted shots aside), + `belowThreshold`, `differing` (unaccepted shots with any differing pixel; without + `--threshold`, any exits 1), `accepted`, `stale`, and with `--computed` `computed` (each + change once with `at: [{ url, widths }]`). +- **`meta`:** origins, widths, threshold, `clock`, block patterns, hidden selectors, mask + reasons, `browser` (`chromium`, or `chrome` after a fallback), storage state file names, + `config` hash, `rightReplayedFrom`. ## Gotchas -- **Reference choice:** base build vs change build, both local, is the default. Production as - the reference mixes in deploy drift, one-sided embeds (job boards, ads) and CSP blocks: use - it as a second pass, and say in the verdict which reference you used. -- **stdout is compact when piped** (what an agent sees). `--progress` prints a line per - shot instead; `--no-progress` forces the summary on a terminal. -- **Accepted differences** (`--accept ""`) go to `renderdiff.accepted.json` next to the - config (or in cwd), one entry per band or region, scoped by the run's routes and widths. A - match ignores `y` and needs the same box, the same pixel hash and the same named elements, so - anything else drawn in that spot still surfaces. A shot whose widths differ, or whose heights - differ without aligning, is never accepted. A new change can make an accepted one re-read - as different (repeated rows aligning differently): look, then accept again. -- **`--rerun-failed`** keeps the out dir and reruns only what wasn't clean or accepted. Give it - the same origins, routes, widths and config (hooks included) as the run it continues, or it - exits 2. -- **`--cache-right`** replays the right side's recorded network traffic (`/.cache/`, kept by the wipe) - for up to an hour, and only if the recording covers every shot in the run. The page still - renders live, so `dom` and the refusals still hold, but a deploy to the reference goes unseen - until the recording expires. A `right: replayed from …` line says so. Never give a verdict - from a replayed run alone. A `--rerun-failed --cache-right` re-record covers only the rerun - shots. `failed right: N request(s) not in the recording, loaded live` means the reference was - part replay, part live: drop the flag rather than trust or accept that shot. -- **The out dir is wiped at the start of every run** (except `--rerun-failed`). To keep a previous run's evidence - next to a new one, pass `--out renderdiff-before` / `--out renderdiff-after`. A - directory holding files renderdiff didn't write is refused (exit 2). -- **Routes normalize** to no trailing slash; `/` stays `/`. Globs are rejected. -- **Route pairs** split on the first `::` followed by `/`: `/pricing::/plans` is a pair, - `/q?x=std::vector` and `pricing::plans` are single routes. `--dry-run` shows how each was - read. A pair is `/a::/b` in stdout and `url`; results.json also has `left` and `right`, - and its files are `{slug(a)}~{slug(b)}.{width}.*.png`. -- **Component scope** (`--selector`, `--left-selector`, `--right-selector`, or a route - object's `selector: ".x" | { left, right }`): use it when the question is one component - (a migrated widget, a design-system swap), so page noise elsewhere can't hide or fake a - change. Exactly one match per side, or the route errors. A CLI selector applies to every - route and replaces the config's. A route is `/a [.x]` in the summary (`/a @1440` with a - `selector` line under it in `--progress`), files are `{slug}@{sel}.{width}.*.png` (`@{l}~{r}` when the sides' selectors differ), and - regions are in the element's own pixels. The whole page still loads and settles. It's - shot at scroll 0, so fixed or sticky overlays over it are included (`hideSelectors`); inside - a shorter scroll container, whatever paints below the container is too; a transformed - element is shot at its axis-aligned box. `xpath=` and `>>` work and `::` is never split; - pseudo-elements are rejected by Playwright; iframes can't be reached. -- **`before` hooks** (config only: `before: async (page, { side, route, width }) => …` on a - route object, or top level for every route without its own) run after load and the HTTP - check, before settle, masks and the shot. Legitimate: opening a menu or tab, dismissing a - modal or banner *both* sides show, signing in, scrolling a carousel to slide 1 on both. - Masking a real difference: branching on `side` to make the sides look alike, hiding or - removing an element on one side, waiting out a bug on one side only. `side` is for markup - that legitimately differs (the same button, a different selector). A throw is - `ERROR before hook failed on left: …`, never retried. Say in the verdict that a hook ran; - the report badges those cards and results.json has `hook: true`. -- **Signed-in pages:** `npx playwright codegen --save-storage=auth.json `, then - `--storage-state auth.json` (or `--left-storage-state` / `--right-storage-state`, or - config `storageState`, relative to the config file). Missing, non-JSON or not a storage state: exit 2. - The file holds live session tokens: never commit it, add it to `.gitignore`, and don't - paste it into a chat. renderdiff records only its file name. The out dir then holds - signed-in screenshots and their text in results.json: don't publish or commit it either - (add it to `.gitignore`). -- **Browser:** if the bundled Chromium won't launch, renderdiff uses the system Chrome on - both sides and says so; else it prints the `npx playwright install chromium` hint. -- **Analytics, consent and A/B tooling are blocked at the network layer** on both sides, - and animations are stilled. If something still flickers between runs, it's a candidate - for `blockUrlPatterns`, not for a mask. -- Lower `--concurrency` (default half the cores, 2–8) when the right side is someone's live site. +- **Browser:** if the bundled Chromium won't launch, the system Chrome is used on both sides + and the run says so; otherwise it prints the `npx playwright install chromium` hint. +- **Pinned on both sides:** clock (one instant per run, floored to the minute), seeded + `Math.random`, UTC, en-US, light scheme, reduced motion; animations and transitions stilled. + A clock showing seconds can still tick between sides. +- **Pixel sensitivity:** pixelmatch threshold 0.05, anti-aliasing ignored. A half-pixel shift + (`translate(-50%)` landing on `.5`) shows as a thin region. diff --git a/src/accept.ts b/src/accept.ts index edce758..6f4b75b 100644 --- a/src/accept.ts +++ b/src/accept.ts @@ -63,8 +63,17 @@ const same = (a: Fingerprint, b: Fingerprint) => * Padding no band or region covers: columns past the narrower page, or rows past the shorter * one when they didn't align. A shot with any, or with unstable pixels, is never accepted. */ -const acceptable = (r: ComparedResult) => - r.unstablePixels === 0 && r.widthDelta === 0 && (r.bands !== null || r.heightDelta === 0); +const acceptable = (r: ComparedResult) => !unacceptable(r); + +/** Why a shot can never be accepted, or null when it can. */ +export const unacceptable = (r: ComparedResult) => + r.unstablePixels + ? "unstable" + : r.widthDelta + ? "width change" + : r.bands === null && r.heightDelta + ? "unaligned height" + : null; export function readAccepted(file: string): Accepted[] { if (!fs.existsSync(file)) return []; diff --git a/src/cli.ts b/src/cli.ts index 4aa4909..29b1124 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -188,9 +188,10 @@ const HELP = ` --rerun-failed reruns only what the previous run in --out didn't find clean or accepted. Writes report.html, results.json and crops of each change to --out. Exits 1 if any - shot differs (with --threshold, only if one scores below it; --threshold 0 never fails - on a diff), 3 if a route errored (unmeasured) or the run crashed, 2 on bad arguments, - bad config or an origin that is down. + shot differs and isn't accepted (with --threshold, only if one scores below it; + --threshold 0 never fails on a diff), 3 if a route errored (unmeasured) or the run + crashed, 2 on bad arguments or config, an origin that is down, or an out dir it won't + wipe. Options --left Left origin, instead of the first positional one. diff --git a/src/run.ts b/src/run.ts index 7e1082c..b08a13b 100644 --- a/src/run.ts +++ b/src/run.ts @@ -4,7 +4,7 @@ import fs from "node:fs"; import path from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { chromium, errors, type Browser, type Page } from "playwright"; -import { applyAccepted, readAccepted, updateAccepted } from "./accept.ts"; +import { applyAccepted, readAccepted, unacceptable, updateAccepted } from "./accept.ts"; import { CACHE_DIR, cacheFile, replayable, REPLAY_TTL, saveRecording, shotId } from "./cache.ts"; import { cancelUnstable, capture, HookError, prepare, type Shot } from "./capture.ts"; import { compare, crops, type Band, type Region } from "./compare.ts"; @@ -486,6 +486,19 @@ export async function run({ ({ stale } = applyAccepted(results, readAccepted(acceptedFile))); } console.log(`accepted ${added.length} difference(s), pruned ${pruned} stale — ${acceptedFile}`); + const why = new Map(); + for (const r of results) { + const w = r.status === "compared" && r.diffPixels > 0 && !r.accepted && unacceptable(r); + if (w) why.set(w, (why.get(w) ?? 0) + 1); + } + const skipped = [...why.values()].reduce((a, b) => a + b, 0); + if (skipped) { + console.log( + `not accepted: ${skipped} differing shot(s) can't be (` + + [...why].map(([w, n]) => `${n} ${w}`).join(", ") + + `) — reference.md § Masks, accepts and thresholds`, + ); + } } const { left, right, widths, ...rest } = setup; @@ -544,8 +557,11 @@ export async function run({ (cfg.threshold === null ? r.diffPixels > 0 : r.score < cfg.threshold), ); if (below.length) { - const what = cfg.threshold === null ? "differ" : `below ${pct(cfg.threshold)}`; - console.error(`\n✗ ${below.length} route(s) ${what}.`); + const n = new Set(below.map(name)).size; + const what = + cfg.threshold === null ? (n === 1 ? "differs" : "differ") : `below ${pct(cfg.threshold)}`; + const shots = `${below.length} shot${below.length === 1 ? "" : "s"}`; + console.error(`\n✗ ${n} route${n === 1 ? "" : "s"} ${what} (${shots}).`); } return below.length ? 1 : results.some((r) => r.status === "error") ? 3 : 0; } diff --git a/tests/visual/accepted.test.ts b/tests/visual/accepted.test.ts index 873fdc2..eab8c36 100644 --- a/tests/visual/accepted.test.ts +++ b/tests/visual/accepted.test.ts @@ -178,6 +178,19 @@ describe("accepted differences", () => { }); }); +test("--accept says which differing shots it can't accept, and why", async () => { + const dir = tempDir(); + const hook = leftCss(dir, "body { min-width: 2000px }"); + const run = await runCli(args(["/color"], [...hook, "--accept", "wider"]), { cwd: dir }); + assert.equal(run.code, 1, context(run)); + assert.match(run.stdout, /^accepted 0 difference\(s\), pruned 0 stale/m, context(run)); + assert.match( + run.stdout, + /^not accepted: 1 differing shot\(s\) can't be \(1 width change\) — reference\.md § Masks, accepts and thresholds$/m, + context(run), + ); +}); + describe("--rerun-failed", () => { test("reruns only what wasn't clean or accepted, and leaves the rest untouched", async () => { const dir = tempDir(); diff --git a/tests/visual/controls.test.ts b/tests/visual/controls.test.ts index 0ce1b54..e6a20b3 100644 --- a/tests/visual/controls.test.ts +++ b/tests/visual/controls.test.ts @@ -482,22 +482,22 @@ test("--threshold turns a low score into a failure", async () => { }), ); assert.equal(r.code, 1, `expected exit 1 below threshold${context(r)}`); - assert.match(r.stderr, /1 route\(s\) below 99\.90%/); + assert.match(r.stderr, /✗ 1 route below 99\.90% \(1 shot\)\./); // The report is still written — a failing run is the one you most want to look at. assert.ok(r.report(), "no report on a threshold failure"); }); -test("any difference fails when no threshold is set", async () => { +test("any difference fails when no threshold is set, counted in routes and shots", async () => { const r = await runCli( renderdiffArgs({ left: site.left, right: site.right, - routes: ["/shifted"], - widths: [1440], + routes: ["/shifted", "/margin"], + widths: [1440, 896], }), ); assert.equal(r.code, 1, context(r)); - assert.match(r.stderr, /1 route\(s\) differ/); + assert.match(r.stderr, /✗ 2 routes differ \(4 shots\)\./, context(r)); }); test("--threshold 0 never fails on a difference", async () => { diff --git a/tests/visual/guardrails.test.ts b/tests/visual/guardrails.test.ts index ece0e10..6104fcd 100644 --- a/tests/visual/guardrails.test.ts +++ b/tests/visual/guardrails.test.ts @@ -1028,7 +1028,7 @@ describe("the run summary", () => { { count: 1, threshold: 0.99 }, context(run), ); - assert.match(run.stderr, /1 route\(s\) below 99\.00%/); + assert.match(run.stderr, /1 route below 99\.00% \(1 shot\)/); }); });