From b2a29ae6a14ac3b9cb264e58147370a84dfd3312 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 01:58:43 +1300 Subject: [PATCH 1/2] Image ignore regions: visualci.yml masks for screenshots and pages (sc-9018); CLI 0.2.22 An ignore rule can now carry `region` (bands along the image's edges: top, bottom, left, right, in pixels) and `rects` (x, y, width, height). For the snapshots its glob matches, those pixels are left out of the image diff: never counted as changed, nor in the regions or the fingerprint. A page that differs only inside them gets the new page state `masked` and its snapshot stays unchanged. - visualci-core: `ScopedIgnoreRule.region`/`rects`, validated with clear messages (at most 100 areas in all); `ImageMask` resolves them against a diff's canvas; `diff::diff_masked` skips masked pixels and hatches them in the overlay; `DiffResult` gains `masked` and `masked_pixels`. - app/: `BuildSettings::image_mask` takes the areas from the build's own rules (its file's, else the project's), so past builds are compared and shown with their own settings. The mask's hash is part of the diff cache key. A new mask counts as hiding more, so it brings the visualci.yml review item. Migration allows the `masked` page state. - get_snapshot and the download manifest list each page's masked areas; the PR comment names masked areas next to the images it shows. - Review UI: masked areas hatched over the base, head, diff and slider views; "masked" page pill and pixel count. - Docs: visualci.yml reference (Masking part of an image), the mobile page (Liquid Glass tab bar), design.md; skills regenerated; plugin 0.1.51; visualci.schema.json regenerated. --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- Cargo.lock | 8 +- Cargo.toml | 2 +- .../2026_12_04_000000_masked_page_state.rs | 15 ++ app/src/domain/build_settings.rs | 26 ++- app/src/domain/compare.rs | 12 +- app/src/domain/detail.rs | 9 +- app/src/domain/diffs.rs | 31 ++- app/src/domain/downloads.rs | 5 +- app/src/domain/projects.rs | 2 + app/src/forge/pr_comment.rs | 18 +- app/src/http/ui/builds.rs | 3 +- app/src/mcp/mod.rs | 10 +- app/tests/forge_reports.rs | 1 + .../get_skill.json | 4 +- .../tools-list-project-token.json | 83 ++++++- .../tools-list-user-token.json | 83 ++++++- app/tests/goldens/pr_comment.md | 2 +- app/tests/masks.rs | 187 ++++++++++++++++ crates/visualci-core/src/config.rs | 203 +++++++++++++++++- crates/visualci-core/src/diff.rs | 74 ++++++- docs/design.md | 12 +- frontend/content/docs/reference/config.md | 28 ++- frontend/content/docs/screenshots/mobile.md | 12 ++ frontend/public/visualci.schema.json | 90 ++++++++ frontend/src/__tests__/masked-areas.test.tsx | 40 ++++ frontend/src/api/types.ts | 7 +- frontend/src/components/MaskedAreas.tsx | 26 +++ frontend/src/pages/SnapshotPage.tsx | 26 ++- frontend/src/styles.css | 19 ++ gemini-extension.json | 2 +- skills/visualci-config/SKILL.md | 28 ++- skills/visualci-mobile/SKILL.md | 12 ++ 35 files changed, 1030 insertions(+), 56 deletions(-) create mode 100644 app/database/migrations/2026_12_04_000000_masked_page_state.rs create mode 100644 app/tests/masks.rs create mode 100644 frontend/src/__tests__/masked-areas.test.tsx create mode 100644 frontend/src/components/MaskedAreas.tsx diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 30f0b8c3..9bb7c654 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,7 +5,7 @@ "plugins": [ { "name": "visualci", - "version": "0.1.50", + "version": "0.1.51", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "author": { "name": "DocSpring", "url": "https://visualci.com" }, "homepage": "https://visualci.com/docs/skills/", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index ff42b859..ee25fed7 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.50", + "version": "0.1.51", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "author": { "name": "DocSpring", "url": "https://visualci.com" }, "homepage": "https://visualci.com/docs/skills/", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 4c1c6783..5069e42b 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "visualci", "displayName": "VisualCI", - "version": "0.1.50", + "version": "0.1.51", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "author": { "name": "DocSpring" diff --git a/Cargo.lock b/Cargo.lock index 3ec964b3..795d640f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5005,7 +5005,7 @@ dependencies = [ [[package]] name = "visualci-cli" -version = "0.2.21" +version = "0.2.22" dependencies = [ "anyhow", "base64 0.22.1", @@ -5022,7 +5022,7 @@ dependencies = [ [[package]] name = "visualci-core" -version = "0.2.21" +version = "0.2.22" dependencies = [ "globset", "hex", @@ -5042,7 +5042,7 @@ dependencies = [ [[package]] name = "visualci-renderer" -version = "0.2.21" +version = "0.2.22" dependencies = [ "anyhow", "image", @@ -5057,7 +5057,7 @@ dependencies = [ [[package]] name = "visualci-wasm" -version = "0.2.21" +version = "0.2.22" dependencies = [ "image", "serde", diff --git a/Cargo.toml b/Cargo.toml index e93dce6b..a6edf347 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ resolver = "3" members = ["crates/*", "app"] [workspace.package] -version = "0.2.21" +version = "0.2.22" edition = "2024" license = "Apache-2.0" repository = "https://github.com/DocSpring/visualci" diff --git a/app/database/migrations/2026_12_04_000000_masked_page_state.rs b/app/database/migrations/2026_12_04_000000_masked_page_state.rs new file mode 100644 index 00000000..f553b921 --- /dev/null +++ b/app/database/migrations/2026_12_04_000000_masked_page_state.rs @@ -0,0 +1,15 @@ +//! A page whose images differ only inside an ignore rule's masked areas (`region`, `rects`; sc-9018) has the state +//! `masked`: like `within_threshold`, it doesn't make its snapshot changed. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "ALTER TABLE snapshot_pages DROP CONSTRAINT snapshot_pages_state_check; \ + ALTER TABLE snapshot_pages ADD CONSTRAINT snapshot_pages_state_check CHECK (state = ANY (ARRAY['unchanged', \ + 'changed', 'ignored', 'variant', 'within_threshold', 'masked']))", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/src/domain/build_settings.rs b/app/src/domain/build_settings.rs index 12e85c3d..b25f2f13 100644 --- a/app/src/domain/build_settings.rs +++ b/app/src/domain/build_settings.rs @@ -7,7 +7,7 @@ use globset::GlobMatcher; use serde::Serialize; -use visualci_core::config::{self, Config, ScopedIgnoreRule, Threshold}; +use visualci_core::config::{self, Config, ImageMask, ScopedIgnoreRule, Threshold}; use visualci_core::snapshot_text::{CompiledRules, IgnoreRules}; use crate::models::{Build, Project, Snapshot}; @@ -81,12 +81,15 @@ impl<'a> BuildSettings<'a> { (self.source, self.rules.iter().map(|(_, r)| r.clone()).collect()) } - /// Every ignore rule that applies to a snapshot, with its source. + /// Every text ignore rule that applies to a snapshot, with its source. pub fn applied_rules(&self, snapshot: &Snapshot) -> Vec { let mut out: Vec = self .rules .iter() - .filter(|(m, _)| m.as_ref().is_some_and(|m| m.is_match(&snapshot.name))) + .filter(|(m, r)| { + m.as_ref().is_some_and(|m| m.is_match(&snapshot.name)) + && !(r.json_paths.is_empty() && r.text_patterns.is_empty()) + }) .map(|(_, r)| AppliedRule { source: self.source, snapshots: Some(r.snapshots.clone()), @@ -123,6 +126,17 @@ impl<'a> BuildSettings<'a> { out } + /// The areas of a snapshot's images left out of its diffs: the `region` and `rects` of every rule in force whose + /// glob matches its name. Like text rules, they're the build's own (its file's, else the project's), read when the + /// build is compared or looked at. + pub fn image_mask(&self, snapshot: &Snapshot) -> ImageMask { + let mut out = ImageMask::default(); + for (_, r) in self.rules.iter().filter(|(m, _)| m.as_ref().is_some_and(|m| m.is_match(&snapshot.name))) { + out.add(r); + } + out + } + /// The file's threshold for a snapshot name: the longest matching glob's. fn file_threshold(&self, name: &str) -> Option { self.thresholds.iter().filter(|(m, _, _)| m.is_match(name)).max_by_key(|(_, g, _)| g.len()).map(|(_, _, t)| *t) @@ -200,8 +214,8 @@ impl<'a> BuildSettings<'a> { }) } - /// Whether these settings could hide a change the base build's settings would show: an ignore rule (glob and path - /// or pattern) the base didn't have, or a higher threshold for some glob. + /// Whether these settings could hide a change the base build's settings would show: an ignore rule (glob and path, + /// pattern, region or rectangle) the base didn't have, or a higher threshold for some glob. pub fn hides_more_than(&self, base: &BuildSettings<'_>) -> bool { let pairs = |s: &BuildSettings<'_>| -> std::collections::HashSet<(String, String)> { s.rules @@ -211,6 +225,8 @@ impl<'a> BuildSettings<'a> { .iter() .map(|p| (r.snapshots.clone(), format!("json:{p}"))) .chain(r.text_patterns.iter().map(|p| (r.snapshots.clone(), format!("text:{p}")))) + .chain(r.region.iter().map(|e| (r.snapshots.clone(), format!("region:{e:?}")))) + .chain(r.rects.iter().map(|x| (r.snapshots.clone(), format!("rect:{x:?}")))) .collect::>() }) .collect() diff --git a/app/src/domain/compare.rs b/app/src/domain/compare.rs index 82619b04..9d08c53a 100644 --- a/app/src/domain/compare.rs +++ b/app/src/domain/compare.rs @@ -148,6 +148,7 @@ pub async fn compare( ); let options = settings.diff_options(snapshot); + let mask = settings.image_mask(snapshot); let (mut changed, mut ignored) = (false, false); let mut matched_environment: Option = None; for (position, op) in ops.iter().enumerate() { @@ -165,7 +166,7 @@ pub async fn compare( } PageOp::Changed { base: b, head: h } => { let (bp, hp) = (&base_pages[b], &head_pages[h]); - let (state, diff_id, matched) = page_state(snapshot, store, project, h, bp, hp, options).await?; + let (state, diff_id, matched) = page_state(snapshot, store, project, h, bp, hp, options, &mask).await?; if matched.is_some() { matched_environment = matched; } @@ -200,7 +201,9 @@ pub async fn compare( } /// The state of a page whose fingerprint changed: identical pixels, an accepted variant, an image approved before, -/// within the threshold, an ignored change, or a change. With the diff, and the other environment it matched. +/// within the threshold, different only inside the masked areas, an ignored change, or a change. With the diff, and the +/// other environment it matched. +#[allow(clippy::too_many_arguments)] async fn page_state( snapshot: &Snapshot, store: &BlobStore, @@ -209,6 +212,7 @@ async fn page_state( base: &RenderPage, head: &RenderPage, options: visualci_core::diff::DiffOptions, + mask: &visualci_core::config::ImageMask, ) -> laravel::Result<(&'static str, Option, Option)> { let (project_id, build_id) = (project.id, snapshot.build_id); let (name, platform) = (snapshot.name.as_str(), snapshot.platform.as_str()); @@ -276,9 +280,9 @@ async fn page_state( let other = (env != snapshot.environment).then_some(env); return Ok(("variant", None, other)); } - let diff = super::diffs::find_or_compute(store, &base.image, &head.image, options).await?; + let diff = super::diffs::find_or_compute(store, &base.image, &head.image, options, mask).await?; if !super::diffs::is_change(&diff) { - return Ok(("within_threshold", Some(diff.id), None)); + return Ok((super::diffs::unchanged_state(&diff), Some(diff.id), None)); } if let Some(fingerprint) = &diff.fingerprint { let is_ignored = IgnoredChange::query() diff --git a/app/src/domain/detail.rs b/app/src/domain/detail.rs index afd41367..38c69cf5 100644 --- a/app/src/domain/detail.rs +++ b/app/src/domain/detail.rs @@ -118,6 +118,7 @@ pub async fn review_detail_against( store: &BlobStore, earlier: &Snapshot, options: visualci_core::diff::DiffOptions, + mask: &visualci_core::config::ImageMask, context: usize, ) -> laravel::Result { let heads = async |s: &Snapshot| -> laravel::Result> { @@ -161,8 +162,12 @@ pub async fn review_detail_against( let (bp, hp) = (&old[b], &new[h]); match (&bp.head_image, &hp.head_image) { (Some(bi), Some(hi)) => { - let diff = super::diffs::find_or_compute(store, bi, hi, options).await?; - let state = if super::diffs::is_change(&diff) { "changed" } else { "within_threshold" }; + let diff = super::diffs::find_or_compute(store, bi, hi, options, mask).await?; + let state = if super::diffs::is_change(&diff) { + "changed" + } else { + super::diffs::unchanged_state(&diff) + }; row(position, "changed", state, Some(bp), Some(hp), Some(diff.id)) } _ => { diff --git a/app/src/domain/diffs.rs b/app/src/domain/diffs.rs index 2ab1e0a1..21bed2ff 100644 --- a/app/src/domain/diffs.rs +++ b/app/src/domain/diffs.rs @@ -1,17 +1,28 @@ -//! Image diffs, cached by (base image, head image, options): the same pair is never diffed twice. +//! Image diffs, cached by (base image, head image, options and mask): the same pair is never diffed twice. use std::io::Cursor; use laravel::db; use laravel::model::update; +use visualci_core::config::ImageMask; use visualci_core::diff::{DiffOptions, DiffResult}; use crate::models::Diff; use crate::storage::BlobStore; +/// The cache key: the algorithm, the options, and a hash of the mask when there is one. #[must_use] -pub fn options_key(options: &DiffOptions) -> String { - format!("{}/t{}/aa{}", visualci_core::diff::ALGORITHM, options.threshold, u8::from(options.ignore_anti_aliasing)) +pub fn options_key(options: &DiffOptions, mask: &ImageMask) -> String { + let key = format!( + "{}/t{}/aa{}", + visualci_core::diff::ALGORITHM, + options.threshold, + u8::from(options.ignore_anti_aliasing) + ); + match mask.key() { + Some(m) => format!("{key}/m{m}"), + None => key, + } } #[must_use] @@ -24,6 +35,13 @@ pub fn is_change(diff: &Diff) -> bool { diff.size_changed || diff.changed_pixels > 0 } +/// A page's state when its diff isn't a change: `masked` when it differs only inside the masked areas, else +/// `within_threshold`. +#[must_use] +pub fn unchanged_state(diff: &Diff) -> &'static str { + if result(diff).is_some_and(|r| r.masked_pixels > 0) { "masked" } else { "within_threshold" } +} + async fn find(base_image: &str, head_image: &str, key: &str) -> laravel::Result> { Diff::query() .filter(Diff::base_image.eq(base_image) & Diff::head_image.eq(head_image) & Diff::options_key.eq(key)) @@ -53,8 +71,9 @@ pub async fn find_or_compute( base_image: &str, head_image: &str, options: DiffOptions, + mask: &ImageMask, ) -> laravel::Result { - let key = options_key(&options); + let key = options_key(&options, mask); let stale = match find(base_image, head_image, &key).await? { Some(diff) if diff.overlay_blob.is_some() || result(&diff).is_none_or(|r| r.is_identical()) => { mark_used(diff.id).await?; @@ -63,10 +82,12 @@ pub async fn find_or_compute( other => other, }; let (base_bytes, head_bytes) = (store.get(base_image).await?, store.get(head_image).await?); + let mask = mask.clone(); let (outcome, overlay_png) = laravel::task::spawn_blocking(move || -> Result<_, String> { let base = visualci_core::image_hash::decode(&base_bytes).map_err(|e| e.to_string())?.to_rgba8(); let head = visualci_core::image_hash::decode(&head_bytes).map_err(|e| e.to_string())?.to_rgba8(); - let (outcome, overlay) = visualci_core::diff::diff(&base, &head, options); + let masked = mask.resolve(base.width().max(head.width()), base.height().max(head.height())); + let (outcome, overlay) = visualci_core::diff::diff_masked(&base, &head, options, &masked); let overlay_png = if outcome.is_identical() { None } else { diff --git a/app/src/domain/downloads.rs b/app/src/domain/downloads.rs index b090ce67..0bbce386 100644 --- a/app/src/domain/downloads.rs +++ b/app/src/domain/downloads.rs @@ -5,8 +5,8 @@ //! //! The archive holds `[@][/page-]/{base,head,diff,regions}.` (`regions` is the head cropped to //! the changed regions) and `manifest.json`, which lists every snapshot with its state, pages, changed fraction, -//! regions, files and URL. Snapshots are read through `effective_snapshots`, so a build that reads a group from an -//! earlier build downloads that group's images too. +//! regions, masked areas, files and URL. Snapshots are read through `effective_snapshots`, so a build that reads a +//! group from an earlier build downloads that group's images too. use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -437,6 +437,7 @@ async fn write_archive( "state": p.state, "changed_fraction": result.as_ref().map(|r| r.changed_fraction), "regions": result.as_ref().map(|r| &r.regions), + "masked": result.as_ref().map(|r| &r.masked), "files": written, })); } diff --git a/app/src/domain/projects.rs b/app/src/domain/projects.rs index 5aa542be..cd59413b 100644 --- a/app/src/domain/projects.rs +++ b/app/src/domain/projects.rs @@ -298,6 +298,8 @@ pub async fn change_settings(project: Project, p: SettingsChange) -> laravel::Re snapshots: r.snapshots.trim().to_string(), json_paths: clean(r.json_paths), text_patterns: clean(r.text_patterns), + region: r.region, + rects: r.rects, }) .collect(); if let Err(e) = visualci_core::config::validate_ignore_rules(&rules) { diff --git a/app/src/forge/pr_comment.rs b/app/src/forge/pr_comment.rs index 222cf5be..426c3668 100644 --- a/app/src/forge/pr_comment.rs +++ b/app/src/forge/pr_comment.rs @@ -38,6 +38,9 @@ pub struct Change { pub kind: String, pub before: Option, pub after: Option, + /// How many areas of the shown page an ignore rule masked: left out of its diff, and named in the row, since the + /// images are shown as they are. + pub masked: usize, } /// One suite's newest build for the pull request. @@ -132,7 +135,12 @@ pub fn render(suites: &[Suite], request: &str) -> String { } else { (img(&c.before), img(&c.after)) }; - out.push(format!("| `{}` ({}) | {before} | {after} |", c.name.replace('|', "\\|"), c.state)); + let masked = match c.masked { + 0 => String::new(), + 1 => ", 1 masked area not compared".to_string(), + n => format!(", {n} masked areas not compared"), + }; + out.push(format!("| `{}` ({}{masked}) | {before} | {after} |", c.name.replace('|', "\\|"), c.state)); } if s.more_changes > 0 { out.push(format!("| and {} more in [the build]({}) | | |", s.more_changes, s.url)); @@ -232,12 +240,20 @@ pub async fn suites(project: &Project, org: &Organization, pr_number: i32) -> la .select_as() .await?; let page = pages.iter().find(|p| p.state == "changed").or(pages.first()); + let masked = match page.and_then(|p| p.diff_id) { + Some(id) => crate::models::Diff::find(id) + .await? + .and_then(|d| crate::domain::diffs::result(&d)) + .map_or(0, |r| r.masked.len()), + None => 0, + }; shown.push(Change { name: s.name.clone(), state: s.state.clone(), kind: s.kind.clone(), before: embed(&store, page.and_then(|p| p.base_image.as_ref())).await?, after: embed(&store, page.and_then(|p| p.head_image.as_ref())).await?, + masked, }); } let removed: Vec = list.iter().filter(|s| s.state == "removed").map(|s| s.name.clone()).collect(); diff --git a/app/src/http/ui/builds.rs b/app/src/http/ui/builds.rs index c1ce81c0..1c81d159 100644 --- a/app/src/http/ui/builds.rs +++ b/app/src/http/ui/builds.rs @@ -242,7 +242,8 @@ pub async fn show_snapshot( let shown = match against { Some((_, earlier)) => { let options = settings.diff_options(&snapshot); - detail::review_detail_against(&snapshot, &store, earlier, options, context).await? + let mask = settings.image_mask(&snapshot); + detail::review_detail_against(&snapshot, &store, earlier, options, &mask, context).await? } None => detail::review_detail(&snapshot, &store, context).await?, }; diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index a17de5c5..8b1a1cb9 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -925,7 +925,7 @@ impl VisualCi { } #[tool( - description = "Change a project's settings. Fields left out stay as they are. These are defaults: a build's visualci.yml overrides them field by field. `ignore_rules` replaces the project's rules for values in text snapshots that change on every run, as a list of `{snapshots, json_paths, text_patterns}`: `snapshots` is a required glob over snapshot names (`api/invoices/**`, `**` for all), `json_paths` like `$.generated_at`, `$.items[*].id`, `$..request_id`, and `text_patterns` regular expressions.", + description = "Change a project's settings. Fields left out stay as they are. These are defaults: a build's visualci.yml overrides them field by field. `ignore_rules` replaces the project's rules for what changes on every run, as a list of `{snapshots, json_paths, text_patterns}`: `snapshots` is a required glob over snapshot names (`api/invoices/**`, `**` for all), `json_paths` like `$.generated_at`, `$.items[*].id`, `$..request_id`, and `text_patterns` regular expressions. For screenshots and pages, `region` (`{\"bottom\": 150}`: bands along the image's edges, in pixels) and `rects` (`[{\"x\": 0, \"y\": 0, \"width\": 300, \"height\": 40}]`) are left out of the image diff.", annotations( title = "Update project", read_only_hint = false, @@ -1304,7 +1304,7 @@ impl VisualCi { } #[tool( - description = "Look at one snapshot's comparison. Documents and images: for every page its operation (unchanged, changed, inserted, removed), the diff's changed pixels and regions, and the text diff; lines that moved to another page; and the base, head and diff images of changed pages (the first three, or the pages you name). Each page's `embed_url` has week-long links to its images, for a pull request comment or a report. Text, JSON and HTML snapshots: the format, the changes by JSON path (`items[3].price: 10 → 12`) and a unified diff of the normalized text (sorted JSON keys, one HTML node per line, ignore rules applied); `images: head`, `base` or `all` adds that whole version. An unchanged snapshot's images come too (its first pages), so any build's version can be looked at. Also the snapshot's open comment threads, each with the build it was drawn on. `against: \"previous\"` compares with the branch's previous build instead of the baseline, to check a fix against a comment left there.", + description = "Look at one snapshot's comparison. Documents and images: for every page its operation (unchanged, changed, inserted, removed) and state, the diff's changed pixels and regions, the areas ignore rules masked (`masked`, left out of the diff; a page that differs only there is `masked`), and the text diff; lines that moved to another page; and the base, head and diff images of changed pages (the first three, or the pages you name). Each page's `embed_url` has week-long links to its images, for a pull request comment or a report. Text, JSON and HTML snapshots: the format, the changes by JSON path (`items[3].price: 10 → 12`) and a unified diff of the normalized text (sorted JSON keys, one HTML node per line, ignore rules applied); `images: head`, `base` or `all` adds that whole version. An unchanged snapshot's images come too (its first pages), so any build's version can be looked at. Also the snapshot's open comment threads, each with the build it was drawn on. `against: \"previous\"` compares with the branch's previous build instead of the baseline, to check a fix against a comment left there.", annotations(title = "Get snapshot", read_only_hint = true, idempotent_hint = true, open_world_hint = false) )] async fn get_snapshot( @@ -1349,7 +1349,8 @@ impl VisualCi { let review_detail = match &earlier { Some((_, e)) => { let options = settings.diff_options(&snapshot); - detail::review_detail_against(&snapshot, &store, e, options, detail::DEFAULT_CONTEXT).await + let mask = settings.image_mask(&snapshot); + detail::review_detail_against(&snapshot, &store, e, options, &mask, detail::DEFAULT_CONTEXT).await } None => detail::review_detail(&snapshot, &store, detail::DEFAULT_CONTEXT).await, } @@ -1443,6 +1444,9 @@ impl VisualCi { "base_size": p.base_size, "head_size": p.head_size, "regions": p.diff.as_ref().map(|d| &d.regions), + // Areas an ignore rule's `region` or `rects` left out of the diff, and the differing pixels in them. + "masked": p.diff.as_ref().map(|d| &d.masked), + "masked_pixels": p.diff.as_ref().map(|d| d.masked_pixels), "text_diff": p.text_diff.iter().map(|l| format!("{}{}", l.tag, l.text)).collect::>(), "images_included": wanted.contains(&p.position) && which != "none" && !p.expired, "expired": p.expired, diff --git a/app/tests/forge_reports.rs b/app/tests/forge_reports.rs index 84acfc49..3ee28e72 100644 --- a/app/tests/forge_reports.rs +++ b/app/tests/forge_reports.rs @@ -61,6 +61,7 @@ fn the_comment_shows_counts_images_and_removals() { kind: "image".into(), before: before.map(Into::into), after: after.map(Into::into), + masked: usize::from(name == "home|1440"), }; let web = Suite { project: "acme/web".into(), diff --git a/app/tests/golden/mcp/get_skill_lists_the_skills_and_returns_one/get_skill.json b/app/tests/golden/mcp/get_skill_lists_the_skills_and_returns_one/get_skill.json index d7848664..36e840e0 100644 --- a/app/tests/golden/mcp/get_skill_lists_the_skills_and_returns_one/get_skill.json +++ b/app/tests/golden/mcp/get_skill_lists_the_skills_and_returns_one/get_skill.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"skills\":[{\"description\":\"Sets up VisualCI, visual regression and snapshot review for PDFs, screenshots, images, JSON, HTML and text: installs the GitHub App (which makes a project per repository) and the CLI, creates a CI token, sends the first build, and picks the visualci-* skill for the user's CI provider and test tools. Use when the user mentions VisualCI, wants visual regression testing, screenshot or PDF comparison, or snapshot changes that wait for review instead of failing CI. Not for a specific CI provider or test tool once VisualCI is set up: use that skill.\",\"name\":\"visualci\"},{\"description\":\"Sets up VisualCI in Bitbucket Pipelines (bitbucket-pipelines.yml): the token as a secured variable, installing the CLI, creating the build, uploading snapshots and finalizing, including parallel steps. Use when the user wants visual or snapshot review in Bitbucket Pipelines, or a project has bitbucket-pipelines.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-bitbucket\"},{\"description\":\"Sets up VisualCI in Buildkite pipelines: the token as a secret, installing the CLI, creating the build, uploading snapshots and finalizing, including parallel jobs. Use when the user wants visual or snapshot review in Buildkite, or a project has .buildkite/ and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-buildkite\"},{\"description\":\"Sets up VisualCI in CircleCI (.circleci/config.yml): the token in a context or project variable, installing the CLI, creating the build, uploading snapshots and finalizing, including parallelism. Use when the user wants visual or snapshot review in CircleCI, or a project has .circleci/config.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-circleci\"},{\"description\":\"Writes and edits visualci.yml: ignore rules scoped to snapshot globs (JSON paths and regular expressions), thresholds, PDF rendering, the CI mode and what to upload. Use when the user wants to ignore volatile values such as timestamps or IDs, change thresholds or the CI mode, or keep VisualCI settings in the repository. Not for per-snapshot ignores in a single test.\",\"name\":\"visualci-config\"},{\"description\":\"Sends Cypress screenshots to VisualCI: taking them with cy.screenshot, turning off failure screenshots, uploading cypress/screenshots with a platform per browser and a threshold, and reviewing changes. Use when a project uses Cypress (cypress.config, cy.screenshot) and wants visual review with VisualCI. Not for Playwright or Capybara.\",\"name\":\"visualci-cypress\"},{\"description\":\"Makes browser screenshots deterministic so VisualCI shows only real changes, covering seeded randomness, loaded and self-hosted fonts, reduced motion, frozen animations, GIFs and videos, a pinned clock and timezone, a hermetic network, and a fixed viewport, scrollbar and device pixel ratio. Gives recipes for Playwright, Cypress and Storybook. Use when screenshots differ between runs of the same commit (flaky diffs), or when setting up visual tests. Not for uploading screenshots or setting up the CI provider.\",\"name\":\"visualci-deterministic\"},{\"description\":\"Sets up VisualCI in GitHub Actions, including Blacksmith and Depot runners, with VisualCI's action (DocSpring/visualci/clients/github-action): the token as a secret, what to upload, and matrix and parallel jobs, or with the CLI directly. Use when the user wants visual or snapshot review in GitHub Actions, or a project has .github/workflows and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-github-actions\"},{\"description\":\"Sets up VisualCI in GitLab CI (.gitlab-ci.yml): the token as a masked variable, installing the CLI, creating the build, uploading snapshots and finalizing, and the CI modes for reviewing without a GitHub check. Use when the user wants visual or snapshot review in GitLab CI, or a project has .gitlab-ci.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-gitlab\"},{\"description\":\"Sends insta (Rust) snapshot files to VisualCI, so a changed snapshot waits for review instead of failing cargo test: accepting snapshots in CI and uploading the .snap files. Use when a Rust project uses insta (assert_snapshot!, snapshots/*.snap) with VisualCI. Not for other languages.\",\"name\":\"visualci-insta\"},{\"description\":\"Sets up VisualCI in a Jenkins pipeline (Jenkinsfile): the token as a credential, installing the CLI, creating the build, uploading snapshots and finalizing, including parallel stages. Use when the user wants visual or snapshot review in Jenkins, or a project has a Jenkinsfile and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-jenkins\"},{\"description\":\"Sends Jest snapshot files to VisualCI, so a changed snapshot waits for review instead of failing the build: running Jest with -u in CI and uploading the .snap files, one snapshot per test. Use when a project uses Jest snapshots (toMatchSnapshot, __snapshots__/*.snap) with VisualCI. Not for Vitest or screenshots.\",\"name\":\"visualci-jest\"},{\"description\":\"Sets up VisualCI for a Laravel Rust app's tests with the snapshot-testing-laravel crate: browser screenshots and HTML, JSON and text snapshots of responses, run under `visualci test -- cargo test`, with names, platforms, ignore rules and thresholds as VisualCI sees them. Use when a Laravel Rust project uses snapshot-testing-laravel, or wants screenshot or snapshot tests with VisualCI. Not for other Rust projects (see visualci-insta) or other frameworks.\",\"name\":\"visualci-laravel-rust\"},{\"description\":\"Runs tests on a laptop against VisualCI's baselines: local environments, each test failing once with every snapshot it changed, and approving local changes so the branch's baseline matches. Use when the user runs visual or snapshot tests locally with VisualCI, sees VisualCI failures in a local run, or wants to approve local results. Not for CI setup.\",\"name\":\"visualci-local-runs\"},{\"description\":\"Sends mobile app screenshots to VisualCI from iOS (XCUITest, swift-snapshot-testing), Android (Espresso, Paparazzi, Roborazzi), Maestro, Detox (React Native) and Flutter golden tests, with a platform tag per OS version and device. Use when an iOS, Android, React Native or Flutter project wants visual review with VisualCI. Not for browser screenshots (Playwright, Cypress) or for setting up the CI provider.\",\"name\":\"visualci-mobile\"},{\"description\":\"Compares PDFs a test suite generates (Ruby, Node, Python or anything else) with VisualCI, page by page in one pinned renderer: uploading them, fingerprints, checking fingerprints are stable, and reading page, text and moved-line changes. Use when a project generates PDFs (invoices, reports, statements, labels) and the user wants them checked for visual changes. Not for screenshots.\",\"name\":\"visualci-pdfs\"},{\"description\":\"Sends Playwright screenshots to VisualCI instead of toHaveScreenshot baselines in the repository: saving screenshots in tests, uploading them with a platform per browser project and a threshold, and reviewing changes. Use when a project uses Playwright (playwright.config, @playwright/test) and wants visual review with VisualCI. Not for Cypress or Capybara.\",\"name\":\"visualci-playwright\"},{\"description\":\"Reviews a VisualCI build over the MCP server: finds what changed, reads each snapshot's diff images, text diff or JSON changes, checks them against the code and the task, then approves intended changes or fixes the code and pushes. Use when a VisualCI check is pending or failing on a pull request, the user asks what changed visually, or asks to approve or reject snapshots. Not for setting VisualCI up in CI.\",\"name\":\"visualci-review\"},{\"description\":\"Adds VisualCI to RSpec feature and system specs with the visualci gem: screenshots from Capybara, PDFs, JSON, HTML and text matchers, per-snapshot ignore rules, local runs that fail each example once, and sharded CI builds. Use when a Ruby project wants visual review of Capybara screenshots or generated documents in RSpec. Not for rspec-snapshot files: see visualci-rspec-snapshot.\",\"name\":\"visualci-rspec-screenshots\"},{\"description\":\"Sends rspec-snapshot files to VisualCI, so a changed snapshot waits for review instead of failing RSpec: updating snapshots in CI and uploading the .snap files. Use when a Ruby project uses rspec-snapshot (match_snapshot) with VisualCI. Not for RSpec screenshots or PDFs: see visualci-rspec-screenshots and visualci-pdfs.\",\"name\":\"visualci-rspec-snapshot\"},{\"description\":\"Sets up VisualCI in Semaphore (.semaphore/semaphore.yml): the token as a secret, installing the CLI, creating the build, uploading snapshots and finalizing, including parallelism. Use when the user wants visual or snapshot review in Semaphore, or a project has .semaphore/ and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-semaphore\"},{\"description\":\"Sends syrupy (pytest) snapshot files to VisualCI, so a changed snapshot waits for review instead of failing pytest: updating snapshots in CI and uploading the .ambr files, one snapshot per test. Use when a Python project uses syrupy (snapshot fixture, __snapshots__/*.ambr) with VisualCI. Not for other languages.\",\"name\":\"visualci-syrupy\"},{\"description\":\"Sets up VisualCI in TeamCity: the token as a password parameter, the commit, branch and pull request from TeamCity's parameters, installing the CLI, creating the build, uploading snapshots and finalizing. Use when the user wants visual or snapshot review in TeamCity, or a project has a .teamcity/ directory and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-teamcity\"},{\"description\":\"Sets up VisualCI in Travis CI (.travis.yml): the token as a repository variable, installing the CLI, creating the build, uploading snapshots and finalizing. Use when the user wants visual or snapshot review in Travis CI, or a project has .travis.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-travis\"},{\"description\":\"Sends Vitest snapshot files to VisualCI, so a changed snapshot waits for review instead of failing the build: running Vitest with -u in CI and uploading the .snap files, one snapshot per test. Use when a project uses Vitest snapshots (toMatchSnapshot, __snapshots__/*.snap) with VisualCI. Not for Jest or screenshots.\",\"name\":\"visualci-vitest\"}]}", + "text": "{\"skills\":[{\"description\":\"Sets up VisualCI, visual regression and snapshot review for PDFs, screenshots, images, JSON, HTML and text: installs the GitHub App (which makes a project per repository) and the CLI, creates a CI token, sends the first build, and picks the visualci-* skill for the user's CI provider and test tools. Use when the user mentions VisualCI, wants visual regression testing, screenshot or PDF comparison, or snapshot changes that wait for review instead of failing CI. Not for a specific CI provider or test tool once VisualCI is set up: use that skill.\",\"name\":\"visualci\"},{\"description\":\"Sets up VisualCI in Bitbucket Pipelines (bitbucket-pipelines.yml): the token as a secured variable, installing the CLI, creating the build, uploading snapshots and finalizing, including parallel steps. Use when the user wants visual or snapshot review in Bitbucket Pipelines, or a project has bitbucket-pipelines.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-bitbucket\"},{\"description\":\"Sets up VisualCI in Buildkite pipelines: the token as a secret, installing the CLI, creating the build, uploading snapshots and finalizing, including parallel jobs. Use when the user wants visual or snapshot review in Buildkite, or a project has .buildkite/ and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-buildkite\"},{\"description\":\"Sets up VisualCI in CircleCI (.circleci/config.yml): the token in a context or project variable, installing the CLI, creating the build, uploading snapshots and finalizing, including parallelism. Use when the user wants visual or snapshot review in CircleCI, or a project has .circleci/config.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-circleci\"},{\"description\":\"Writes and edits visualci.yml: ignore rules scoped to snapshot globs (JSON paths and regular expressions for text, masked regions and rectangles for screenshots), thresholds, PDF rendering, the CI mode and what to upload. Use when the user wants to ignore volatile values such as timestamps or IDs, leave a part of a screenshot that differs on every run (a status bar, a tab bar's glass effect) out of the diff, change thresholds or the CI mode, or keep VisualCI settings in the repository. Not for per-snapshot ignores in a single test.\",\"name\":\"visualci-config\"},{\"description\":\"Sends Cypress screenshots to VisualCI: taking them with cy.screenshot, turning off failure screenshots, uploading cypress/screenshots with a platform per browser and a threshold, and reviewing changes. Use when a project uses Cypress (cypress.config, cy.screenshot) and wants visual review with VisualCI. Not for Playwright or Capybara.\",\"name\":\"visualci-cypress\"},{\"description\":\"Makes browser screenshots deterministic so VisualCI shows only real changes, covering seeded randomness, loaded and self-hosted fonts, reduced motion, frozen animations, GIFs and videos, a pinned clock and timezone, a hermetic network, and a fixed viewport, scrollbar and device pixel ratio. Gives recipes for Playwright, Cypress and Storybook. Use when screenshots differ between runs of the same commit (flaky diffs), or when setting up visual tests. Not for uploading screenshots or setting up the CI provider.\",\"name\":\"visualci-deterministic\"},{\"description\":\"Sets up VisualCI in GitHub Actions, including Blacksmith and Depot runners, with VisualCI's action (DocSpring/visualci/clients/github-action): the token as a secret, what to upload, and matrix and parallel jobs, or with the CLI directly. Use when the user wants visual or snapshot review in GitHub Actions, or a project has .github/workflows and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-github-actions\"},{\"description\":\"Sets up VisualCI in GitLab CI (.gitlab-ci.yml): the token as a masked variable, installing the CLI, creating the build, uploading snapshots and finalizing, and the CI modes for reviewing without a GitHub check. Use when the user wants visual or snapshot review in GitLab CI, or a project has .gitlab-ci.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-gitlab\"},{\"description\":\"Sends insta (Rust) snapshot files to VisualCI, so a changed snapshot waits for review instead of failing cargo test: accepting snapshots in CI and uploading the .snap files. Use when a Rust project uses insta (assert_snapshot!, snapshots/*.snap) with VisualCI. Not for other languages.\",\"name\":\"visualci-insta\"},{\"description\":\"Sets up VisualCI in a Jenkins pipeline (Jenkinsfile): the token as a credential, installing the CLI, creating the build, uploading snapshots and finalizing, including parallel stages. Use when the user wants visual or snapshot review in Jenkins, or a project has a Jenkinsfile and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-jenkins\"},{\"description\":\"Sends Jest snapshot files to VisualCI, so a changed snapshot waits for review instead of failing the build: running Jest with -u in CI and uploading the .snap files, one snapshot per test. Use when a project uses Jest snapshots (toMatchSnapshot, __snapshots__/*.snap) with VisualCI. Not for Vitest or screenshots.\",\"name\":\"visualci-jest\"},{\"description\":\"Sets up VisualCI for a Laravel Rust app's tests with the snapshot-testing-laravel crate: browser screenshots and HTML, JSON and text snapshots of responses, run under `visualci test -- cargo test`, with names, platforms, ignore rules and thresholds as VisualCI sees them. Use when a Laravel Rust project uses snapshot-testing-laravel, or wants screenshot or snapshot tests with VisualCI. Not for other Rust projects (see visualci-insta) or other frameworks.\",\"name\":\"visualci-laravel-rust\"},{\"description\":\"Runs tests on a laptop against VisualCI's baselines: local environments, each test failing once with every snapshot it changed, and approving local changes so the branch's baseline matches. Use when the user runs visual or snapshot tests locally with VisualCI, sees VisualCI failures in a local run, or wants to approve local results. Not for CI setup.\",\"name\":\"visualci-local-runs\"},{\"description\":\"Sends mobile app screenshots to VisualCI from iOS (XCUITest, swift-snapshot-testing), Android (Espresso, Paparazzi, Roborazzi), Maestro, Detox (React Native) and Flutter golden tests, with a platform tag per OS version and device. Use when an iOS, Android, React Native or Flutter project wants visual review with VisualCI. Not for browser screenshots (Playwright, Cypress) or for setting up the CI provider.\",\"name\":\"visualci-mobile\"},{\"description\":\"Compares PDFs a test suite generates (Ruby, Node, Python or anything else) with VisualCI, page by page in one pinned renderer: uploading them, fingerprints, checking fingerprints are stable, and reading page, text and moved-line changes. Use when a project generates PDFs (invoices, reports, statements, labels) and the user wants them checked for visual changes. Not for screenshots.\",\"name\":\"visualci-pdfs\"},{\"description\":\"Sends Playwright screenshots to VisualCI instead of toHaveScreenshot baselines in the repository: saving screenshots in tests, uploading them with a platform per browser project and a threshold, and reviewing changes. Use when a project uses Playwright (playwright.config, @playwright/test) and wants visual review with VisualCI. Not for Cypress or Capybara.\",\"name\":\"visualci-playwright\"},{\"description\":\"Reviews a VisualCI build over the MCP server: finds what changed, reads each snapshot's diff images, text diff or JSON changes, checks them against the code and the task, then approves intended changes or fixes the code and pushes. Use when a VisualCI check is pending or failing on a pull request, the user asks what changed visually, or asks to approve or reject snapshots. Not for setting VisualCI up in CI.\",\"name\":\"visualci-review\"},{\"description\":\"Adds VisualCI to RSpec feature and system specs with the visualci gem: screenshots from Capybara, PDFs, JSON, HTML and text matchers, per-snapshot ignore rules, local runs that fail each example once, and sharded CI builds. Use when a Ruby project wants visual review of Capybara screenshots or generated documents in RSpec. Not for rspec-snapshot files: see visualci-rspec-snapshot.\",\"name\":\"visualci-rspec-screenshots\"},{\"description\":\"Sends rspec-snapshot files to VisualCI, so a changed snapshot waits for review instead of failing RSpec: updating snapshots in CI and uploading the .snap files. Use when a Ruby project uses rspec-snapshot (match_snapshot) with VisualCI. Not for RSpec screenshots or PDFs: see visualci-rspec-screenshots and visualci-pdfs.\",\"name\":\"visualci-rspec-snapshot\"},{\"description\":\"Sets up VisualCI in Semaphore (.semaphore/semaphore.yml): the token as a secret, installing the CLI, creating the build, uploading snapshots and finalizing, including parallelism. Use when the user wants visual or snapshot review in Semaphore, or a project has .semaphore/ and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-semaphore\"},{\"description\":\"Sends syrupy (pytest) snapshot files to VisualCI, so a changed snapshot waits for review instead of failing pytest: updating snapshots in CI and uploading the .ambr files, one snapshot per test. Use when a Python project uses syrupy (snapshot fixture, __snapshots__/*.ambr) with VisualCI. Not for other languages.\",\"name\":\"visualci-syrupy\"},{\"description\":\"Sets up VisualCI in TeamCity: the token as a password parameter, the commit, branch and pull request from TeamCity's parameters, installing the CLI, creating the build, uploading snapshots and finalizing. Use when the user wants visual or snapshot review in TeamCity, or a project has a .teamcity/ directory and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-teamcity\"},{\"description\":\"Sets up VisualCI in Travis CI (.travis.yml): the token as a repository variable, installing the CLI, creating the build, uploading snapshots and finalizing. Use when the user wants visual or snapshot review in Travis CI, or a project has .travis.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-travis\"},{\"description\":\"Sends Vitest snapshot files to VisualCI, so a changed snapshot waits for review instead of failing the build: running Vitest with -u in CI and uploading the .snap files, one snapshot per test. Use when a project uses Vitest snapshots (toMatchSnapshot, __snapshots__/*.snap) with VisualCI. Not for Jest or screenshots.\",\"name\":\"visualci-vitest\"}]}", "type": "text" } ], @@ -27,7 +27,7 @@ "name": "visualci-circleci" }, { - "description": "Writes and edits visualci.yml: ignore rules scoped to snapshot globs (JSON paths and regular expressions), thresholds, PDF rendering, the CI mode and what to upload. Use when the user wants to ignore volatile values such as timestamps or IDs, change thresholds or the CI mode, or keep VisualCI settings in the repository. Not for per-snapshot ignores in a single test.", + "description": "Writes and edits visualci.yml: ignore rules scoped to snapshot globs (JSON paths and regular expressions for text, masked regions and rectangles for screenshots), thresholds, PDF rendering, the CI mode and what to upload. Use when the user wants to ignore volatile values such as timestamps or IDs, leave a part of a screenshot that differs on every run (a status bar, a tab bar's glass effect) out of the diff, change thresholds or the CI mode, or keep VisualCI settings in the repository. Not for per-snapshot ignores in a single test.", "name": "visualci-config" }, { diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json index 2569b463..90e4a5de 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json @@ -637,7 +637,7 @@ "readOnlyHint": true, "title": "Get snapshot" }, - "description": "Look at one snapshot's comparison. Documents and images: for every page its operation (unchanged, changed, inserted, removed), the diff's changed pixels and regions, and the text diff; lines that moved to another page; and the base, head and diff images of changed pages (the first three, or the pages you name). Each page's `embed_url` has week-long links to its images, for a pull request comment or a report. Text, JSON and HTML snapshots: the format, the changes by JSON path (`items[3].price: 10 → 12`) and a unified diff of the normalized text (sorted JSON keys, one HTML node per line, ignore rules applied); `images: head`, `base` or `all` adds that whole version. An unchanged snapshot's images come too (its first pages), so any build's version can be looked at. Also the snapshot's open comment threads, each with the build it was drawn on. `against: \"previous\"` compares with the branch's previous build instead of the baseline, to check a fix against a comment left there.", + "description": "Look at one snapshot's comparison. Documents and images: for every page its operation (unchanged, changed, inserted, removed) and state, the diff's changed pixels and regions, the areas ignore rules masked (`masked`, left out of the diff; a page that differs only there is `masked`), and the text diff; lines that moved to another page; and the base, head and diff images of changed pages (the first three, or the pages you name). Each page's `embed_url` has week-long links to its images, for a pull request comment or a report. Text, JSON and HTML snapshots: the format, the changes by JSON path (`items[3].price: 10 → 12`) and a unified diff of the normalized text (sorted JSON keys, one HTML node per line, ignore rules applied); `images: head`, `base` or `all` adds that whole version. An unchanged snapshot's images come too (its first pages), so any build's version can be looked at. Also the snapshot's open comment threads, each with the build it was drawn on. `against: \"previous\"` compares with the branch's previous build instead of the baseline, to check a fix against a comment left there.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, @@ -1351,7 +1351,7 @@ "readOnlyHint": false, "title": "Update project" }, - "description": "Change a project's settings. Fields left out stay as they are. These are defaults: a build's visualci.yml overrides them field by field. `ignore_rules` replaces the project's rules for values in text snapshots that change on every run, as a list of `{snapshots, json_paths, text_patterns}`: `snapshots` is a required glob over snapshot names (`api/invoices/**`, `**` for all), `json_paths` like `$.generated_at`, `$.items[*].id`, `$..request_id`, and `text_patterns` regular expressions.", + "description": "Change a project's settings. Fields left out stay as they are. These are defaults: a build's visualci.yml overrides them field by field. `ignore_rules` replaces the project's rules for what changes on every run, as a list of `{snapshots, json_paths, text_patterns}`: `snapshots` is a required glob over snapshot names (`api/invoices/**`, `**` for all), `json_paths` like `$.generated_at`, `$.items[*].id`, `$..request_id`, and `text_patterns` regular expressions. For screenshots and pages, `region` (`{\"bottom\": 150}`: bands along the image's edges, in pixels) and `rects` (`[{\"x\": 0, \"y\": 0, \"width\": 300, \"height\": 40}]`) are left out of the image diff.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, @@ -1426,6 +1426,85 @@ }, "type": "array" }, + "rects": { + "description": "Images: rectangles whose pixels aren't compared, in pixels of the image from its top-left corner.", + "items": { + "additionalProperties": false, + "description": "A rectangle in an image's pixels, from its top-left corner.", + "properties": { + "height": { + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "width": { + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "x": { + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "y": { + "format": "uint32", + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "x", + "y", + "width", + "height" + ], + "type": "object" + }, + "type": "array" + }, + "region": { + "additionalProperties": false, + "description": "Images: bands along the image's edges whose pixels aren't compared, in pixels of the image: `{ bottom: 150 }`. Bands along an image's edges, each the given number of pixels deep.", + "properties": { + "bottom": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "left": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "right": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "top": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "type": [ + "object", + "null" + ] + }, "snapshots": { "description": "The snapshots this rule applies to, as a glob over snapshot names: `api/invoices/**`, `emails/*.html`.", "type": "string" diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json index 2569b463..90e4a5de 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json @@ -637,7 +637,7 @@ "readOnlyHint": true, "title": "Get snapshot" }, - "description": "Look at one snapshot's comparison. Documents and images: for every page its operation (unchanged, changed, inserted, removed), the diff's changed pixels and regions, and the text diff; lines that moved to another page; and the base, head and diff images of changed pages (the first three, or the pages you name). Each page's `embed_url` has week-long links to its images, for a pull request comment or a report. Text, JSON and HTML snapshots: the format, the changes by JSON path (`items[3].price: 10 → 12`) and a unified diff of the normalized text (sorted JSON keys, one HTML node per line, ignore rules applied); `images: head`, `base` or `all` adds that whole version. An unchanged snapshot's images come too (its first pages), so any build's version can be looked at. Also the snapshot's open comment threads, each with the build it was drawn on. `against: \"previous\"` compares with the branch's previous build instead of the baseline, to check a fix against a comment left there.", + "description": "Look at one snapshot's comparison. Documents and images: for every page its operation (unchanged, changed, inserted, removed) and state, the diff's changed pixels and regions, the areas ignore rules masked (`masked`, left out of the diff; a page that differs only there is `masked`), and the text diff; lines that moved to another page; and the base, head and diff images of changed pages (the first three, or the pages you name). Each page's `embed_url` has week-long links to its images, for a pull request comment or a report. Text, JSON and HTML snapshots: the format, the changes by JSON path (`items[3].price: 10 → 12`) and a unified diff of the normalized text (sorted JSON keys, one HTML node per line, ignore rules applied); `images: head`, `base` or `all` adds that whole version. An unchanged snapshot's images come too (its first pages), so any build's version can be looked at. Also the snapshot's open comment threads, each with the build it was drawn on. `against: \"previous\"` compares with the branch's previous build instead of the baseline, to check a fix against a comment left there.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, @@ -1351,7 +1351,7 @@ "readOnlyHint": false, "title": "Update project" }, - "description": "Change a project's settings. Fields left out stay as they are. These are defaults: a build's visualci.yml overrides them field by field. `ignore_rules` replaces the project's rules for values in text snapshots that change on every run, as a list of `{snapshots, json_paths, text_patterns}`: `snapshots` is a required glob over snapshot names (`api/invoices/**`, `**` for all), `json_paths` like `$.generated_at`, `$.items[*].id`, `$..request_id`, and `text_patterns` regular expressions.", + "description": "Change a project's settings. Fields left out stay as they are. These are defaults: a build's visualci.yml overrides them field by field. `ignore_rules` replaces the project's rules for what changes on every run, as a list of `{snapshots, json_paths, text_patterns}`: `snapshots` is a required glob over snapshot names (`api/invoices/**`, `**` for all), `json_paths` like `$.generated_at`, `$.items[*].id`, `$..request_id`, and `text_patterns` regular expressions. For screenshots and pages, `region` (`{\"bottom\": 150}`: bands along the image's edges, in pixels) and `rects` (`[{\"x\": 0, \"y\": 0, \"width\": 300, \"height\": 40}]`) are left out of the image diff.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, @@ -1426,6 +1426,85 @@ }, "type": "array" }, + "rects": { + "description": "Images: rectangles whose pixels aren't compared, in pixels of the image from its top-left corner.", + "items": { + "additionalProperties": false, + "description": "A rectangle in an image's pixels, from its top-left corner.", + "properties": { + "height": { + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "width": { + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "x": { + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "y": { + "format": "uint32", + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "x", + "y", + "width", + "height" + ], + "type": "object" + }, + "type": "array" + }, + "region": { + "additionalProperties": false, + "description": "Images: bands along the image's edges whose pixels aren't compared, in pixels of the image: `{ bottom: 150 }`. Bands along an image's edges, each the given number of pixels deep.", + "properties": { + "bottom": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "left": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "right": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "top": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "type": [ + "object", + "null" + ] + }, "snapshots": { "description": "The snapshots this rule applies to, as a glob over snapshot names: `api/invoices/**`, `emails/*.html`.", "type": "string" diff --git a/app/tests/goldens/pr_comment.md b/app/tests/goldens/pr_comment.md index 21753d5f..6dee3545 100644 --- a/app/tests/goldens/pr_comment.md +++ b/app/tests/goldens/pr_comment.md @@ -7,7 +7,7 @@ This PR vs base: 3 changed, 1 removed since #10, across 2 builds · 1 not approv | Snapshot | Before | After | | --- | --- | --- | -| `home\|1440` (changed) | | | +| `home\|1440` (changed, 1 masked area not compared) | | | | `cart` (added) | – | | | `api.json` (changed) | text | text, see the build | | and 3 more in [the build](https://app.visualci.com/acme/web/builds/12) | | | diff --git a/app/tests/masks.rs b/app/tests/masks.rs new file mode 100644 index 00000000..b4510aa9 --- /dev/null +++ b/app/tests/masks.rs @@ -0,0 +1,187 @@ +//! Image ignore regions (sc-9018): an ignore rule's `region` and `rects` leave those pixels out of the diff, for the +//! snapshots its glob matches. A change only inside them leaves the snapshot unchanged, a change partly outside is +//! reported by its outside regions alone, and get_snapshot and the review page list the masked areas. + +use app::models::{Build, Snapshot, SnapshotPage, User}; +use app::testing::fixtures; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +const SIZE: u32 = 32; + +/// A white 32 × 32 screenshot with these pixels black. +fn png(black: &[(u32, u32)]) -> Vec { + let mut image = image::RgbaImage::from_pixel(SIZE, SIZE, image::Rgba([255, 255, 255, 255])); + for &(x, y) in black { + image.put_pixel(x, y, image::Rgba([0, 0, 0, 255])); + } + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).expect("a PNG encodes"); + bytes +} + +/// Send and finalize one build of these screenshots on `main`, with this visualci.yml. +async fn run(app: &Application, token: &str, commit: &str, config: &Value, shots: &[(&str, Vec)]) -> Value { + let auth = format!("Bearer {token}"); + let build = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": commit, "branch": "main", "config": config })) + .await; + build.assert_ok(); + let id = build.json()["id"].as_str().unwrap().to_string(); + let snapshots: Vec = shots + .iter() + .map(|(name, bytes)| { + json!({ + "name": name, "kind": "image", "sha256": visualci_core::sha256_hex(bytes), "size": bytes.len(), + "content_type": "image/png", + }) + }) + .collect(); + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": snapshots })) + .await; + registered.assert_ok(); + let client = reqwest::Client::new(); + for (answer, (_, bytes)) in registered.json()["snapshots"].as_array().unwrap().iter().zip(shots) { + if let Some(url) = answer["upload_url"].as_str() { + let put = + client.put(url).header("content-type", "image/png").body(bytes.clone()).send().await.expect("upload"); + assert!(put.status().is_success(), "uploading: {}", put.status()); + } + } + let done = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await; + done.assert_ok(); + done.json().clone() +} + +async fn snapshot(number: i32, name: &str) -> laravel::Result { + let build = Build::query().filter(Build::number.eq(number)).first().await?.expect("the build"); + let all = app::domain::snapshots::of_build(build.id).await?; + let found = all.into_iter().find(|s| s.name == name).expect("the snapshot"); + Snapshot::find_or_fail(found.id).await +} + +async fn page_states(snapshot: &Snapshot) -> laravel::Result> { + let pages = SnapshotPage::query().filter(SnapshotPage::snapshot_id.eq(snapshot.id)).get().await?; + Ok(pages.into_iter().map(|p| p.state).collect()) +} + +async fn get_snapshot(app: &Application, token: &str, build: i32, name: &str) -> Value { + let response = app + .post("/mcp") + .header("authorization", format!("Bearer {token}")) + .json(json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": { "name": "get_snapshot", "arguments": { "build": build, "name": name, "images": "none" } } })) + .header("accept", "application/json, text/event-stream") + .await; + response.assert_ok(); + let body = response.json().clone(); + let text = body["result"]["content"][0]["text"].as_str().unwrap_or_else(|| panic!("{body}")); + serde_json::from_str(text).unwrap_or_else(|e| panic!("{e}: {text}")) +} + +#[laravel::test] +async fn masked_areas_are_left_out_of_image_diffs(app: Application) -> laravel::Result<()> { + Box::pin(masked_areas(app)).await +} + +async fn masked_areas(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + // The bottom 8 px of the iOS screenshots, and a rectangle at the top left of the web ones. + let config = json!({ "ignore": [ + { "snapshots": "ios/**", "region": { "bottom": 8 } }, + { "snapshots": "web/**", "rects": [{ "x": 0, "y": 0, "width": 8, "height": 4 }] }, + ] }); + let white = png(&[]); + let bottom = png(&[(3, 30), (20, 27)]); + + // #1 adds them. + let first = run( + &app, + &token, + "c1", + &config, + &[("ios/home", white.clone()), ("android/home", white.clone()), ("web/home", white.clone())], + ) + .await; + assert_eq!(first["review_state"], "auto_approved", "{first}"); + + // #2: the same change at the bottom of each. Only inside the iOS mask: unchanged, its page `masked`. Android's + // glob doesn't match, so it's a change; the web rectangle is elsewhere, so that's a change too. + let second = run( + &app, + &token, + "c2", + &config, + &[("ios/home", bottom.clone()), ("android/home", bottom.clone()), ("web/home", bottom.clone())], + ) + .await; + assert_eq!(second["stats"]["changed"], 2, "{second}"); + let ios = snapshot(2, "ios/home").await?; + assert_eq!(ios.state, "unchanged"); + assert_eq!(page_states(&ios).await?, vec!["masked"]); + assert_eq!(snapshot(2, "android/home").await?.state, "changed"); + assert_eq!(snapshot(2, "web/home").await?.state, "changed"); + let mcp = get_snapshot(&app, &token, 2, "ios/home").await; + assert_eq!(mcp["pages"][0]["state"], "masked", "{mcp}"); + assert_eq!(mcp["pages"][0]["masked"], json!([{ "x": 0, "y": 24, "width": 32, "height": 8 }]), "{mcp}"); + assert_eq!(mcp["pages"][0]["masked_pixels"], 2, "{mcp}"); + assert_eq!(mcp["pages"][0]["regions"], json!([]), "{mcp}"); + let mcp = get_snapshot(&app, &token, 2, "android/home").await; + assert_eq!(mcp["pages"][0]["masked"], json!([]), "{mcp}"); + assert_eq!(mcp["pages"][0]["regions"], json!([{ "x": 0, "y": 16, "width": 32, "height": 16 }]), "{mcp}"); + assert_eq!(mcp["pages"][0]["changed_pixels"], 2, "{mcp}"); + + // #3: a change at the top as well as the bottom: changed, with the top's region only. + let both = png(&[(3, 30), (20, 27), (2, 2)]); + let third = run(&app, &token, "c3", &config, &[("ios/home", both)]).await; + assert_eq!(third["stats"]["changed"], 1, "{third}"); + let ios = snapshot(3, "ios/home").await?; + assert_eq!(ios.state, "changed"); + let mcp = get_snapshot(&app, &token, 3, "ios/home").await; + let page = &mcp["pages"][0]; + assert_eq!(page["regions"], json!([{ "x": 0, "y": 0, "width": 16, "height": 16 }]), "{mcp}"); + assert_eq!((page["changed_pixels"].as_u64(), page["masked_pixels"].as_u64()), (Some(1), Some(2)), "{mcp}"); + + // The review page's API has the same areas, for the hatching. + let email = format!("{}@example.com", laravel::str::uuid7()); + let owner = create!(User { pid: laravel::str::uuid7(), name: "owner", email: email, staff: false }).await?; + fixtures::member(&org, &owner, "admin").await?; + let ui = app + .get(format!("/api/ui/orgs/{}/projects/web/builds/3/snapshots/{}", org.slug, ios.pid)) + .acting_as(&owner) + .await; + ui.assert_ok(); + let ui = ui.json().clone(); + assert_eq!(ui["pages"][0]["diff"]["masked"], json!([{ "x": 0, "y": 24, "width": 32, "height": 8 }]), "{ui}"); + + // A file that adds a mask hides more than one without it: the build shows a visualci.yml change to review. + let plain = Build::query().filter(Build::number.eq(1)).first().await?.unwrap(); + let mut without = plain.clone(); + without.config = + Some(json!({ "ignore": [{ "snapshots": "web/**", "rects": [{ "x": 0, "y": 0, "width": 8, "height": 4 }] }] })); + let project = app::models::Project::find_or_fail(project_id).await?; + let (with, without) = ( + app::domain::build_settings::BuildSettings::new(&project, &plain), + app::domain::build_settings::BuildSettings::new(&project, &without), + ); + assert!(with.hides_more_than(&without)); + assert!(!without.hides_more_than(&with)); + Ok(()) +} diff --git a/crates/visualci-core/src/config.rs b/crates/visualci-core/src/config.rs index b85075aa..87c963a9 100644 --- a/crates/visualci-core/src/config.rs +++ b/crates/visualci-core/src/config.rs @@ -135,6 +135,107 @@ pub struct ScopedIgnoreRule { /// Regular expressions; matching text is ignored in every text format. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub text_patterns: Vec, + /// Images: bands along the image's edges whose pixels aren't compared, in pixels of the image: `{ bottom: 150 }`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub region: Option, + /// Images: rectangles whose pixels aren't compared, in pixels of the image from its top-left corner. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub rects: Vec, +} + +/// At most this many masked areas (edge bands and rectangles) across all ignore rules. +pub const MAX_MASKED_AREAS: usize = 100; +/// The largest coordinate or size a mask may name, in pixels. +pub const MAX_MASK_PIXELS: u32 = 100_000; + +/// Bands along an image's edges, each the given number of pixels deep. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Edges { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub top: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bottom: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub left: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub right: Option, +} + +/// A rectangle in an image's pixels, from its top-left corner. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Rect { + pub x: u32, + pub y: u32, + pub width: u32, + pub height: u32, +} + +/// The parts of an image left out of its diff: every edge band and rectangle of the ignore rules that apply to a +/// snapshot. Resolved to pixels against each diff's canvas, since an edge band depends on the image's size. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ImageMask { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub edges: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub rects: Vec, +} + +impl ImageMask { + pub fn is_empty(&self) -> bool { + self.edges.is_empty() && self.rects.is_empty() + } + + /// Add a rule's areas. + pub fn add(&mut self, rule: &ScopedIgnoreRule) { + self.edges.extend(rule.region); + self.rects.extend(rule.rects.iter().copied()); + } + + /// A short hash of the mask, for diff cache keys; `None` when it's empty. + pub fn key(&self) -> Option { + (!self.is_empty()).then(|| { + let json = serde_json::to_string(self).unwrap_or_default(); + crate::sha256_hex(json.as_bytes())[..16].to_string() + }) + } + + /// The masked areas as rectangles inside a `width` × `height` canvas: an edge band is the band along that edge, + /// and a rectangle is clipped to the canvas. Areas that fall outside it are left out. + pub fn resolve(&self, width: u32, height: u32) -> Vec { + use crate::diff::Region; + let mut out = Vec::new(); + let mut push = |x: u32, y: u32, w: u32, h: u32| { + if x >= width || y >= height { + return; + } + let (w, h) = (w.min(width - x), h.min(height - y)); + if w > 0 && h > 0 { + out.push(Region { x, y, width: w, height: h }); + } + }; + for e in &self.edges { + if let Some(d) = e.top { + push(0, 0, width, d); + } + if let Some(d) = e.bottom { + let d = d.min(height); + push(0, height - d, width, d); + } + if let Some(d) = e.left { + push(0, 0, d, height); + } + if let Some(d) = e.right { + let d = d.min(width); + push(width - d, 0, d, height); + } + } + for r in &self.rects { + push(r.x, r.y, r.width, r.height); + } + out + } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] @@ -237,8 +338,32 @@ impl ScopedIgnoreRule { .into()); } glob(&self.snapshots)?; - if self.json_paths.is_empty() && self.text_patterns.is_empty() { - return Err(format!("the ignore rule for {:?} has no json_paths or text_patterns", self.snapshots)); + if self.json_paths.is_empty() && self.text_patterns.is_empty() && self.region.is_none() && self.rects.is_empty() + { + return Err(format!( + "the ignore rule for {:?} ignores nothing: give json_paths or text_patterns (text snapshots), or region \ + or rects (images)", + self.snapshots + )); + } + let rule = |e: String| format!("the ignore rule for {:?}: {e}", self.snapshots); + let in_range = |v: u32| (1..=MAX_MASK_PIXELS).contains(&v); + if let Some(e) = &self.region { + let sides = [e.top, e.bottom, e.left, e.right]; + if sides.iter().all(Option::is_none) { + return Err(rule("region names no edge: give top, bottom, left or right, in pixels".into())); + } + if sides.into_iter().flatten().any(|v| !in_range(v)) { + return Err(rule(format!("region's top, bottom, left and right are 1 to {MAX_MASK_PIXELS} pixels"))); + } + } + for (i, r) in self.rects.iter().enumerate() { + if !in_range(r.width) || !in_range(r.height) || r.x > MAX_MASK_PIXELS || r.y > MAX_MASK_PIXELS { + return Err(rule(format!( + "rects[{i}]: width and height are 1 to {MAX_MASK_PIXELS} pixels, and x and y at most \ + {MAX_MASK_PIXELS}" + ))); + } } IgnoreRules { json_paths: self.json_paths.clone(), text_patterns: self.text_patterns.clone() } .compile() @@ -284,12 +409,25 @@ pub fn validate_ignore_rules(rules: &[ScopedIgnoreRule]) -> Result<(), String> { if total > MAX_IGNORE_RULES { return Err(format!("at most {MAX_IGNORE_RULES} JSON paths and patterns in all")); } + let areas: usize = rules.iter().map(|r| usize::from(r.region.is_some()) + r.rects.len()).sum(); + if areas > MAX_MASKED_AREAS { + return Err(format!("at most {MAX_MASKED_AREAS} regions and rects in all")); + } for (i, rule) in rules.iter().enumerate() { rule.validate().map_err(|e| format!("ignore rule {}: {e}", i + 1))?; } Ok(()) } +/// The masked areas of every rule that applies to the named snapshot, merged. +pub fn mask_for(rules: &[ScopedIgnoreRule], name: &str) -> ImageMask { + let mut out = ImageMask::default(); + for rule in rules.iter().filter(|r| r.applies_to(name)) { + out.add(rule); + } + out +} + /// The JSON paths and patterns of every rule that applies to the named snapshot, merged. pub fn rules_for(rules: &[ScopedIgnoreRule], name: &str) -> IgnoreRules { let mut out = IgnoreRules::default(); @@ -428,7 +566,7 @@ mod tests { } fn rule(glob: &str, path: &str) -> ScopedIgnoreRule { - ScopedIgnoreRule { snapshots: glob.into(), json_paths: vec![path.into()], text_patterns: vec![] } + ScopedIgnoreRule { snapshots: glob.into(), json_paths: vec![path.into()], ..Default::default() } } #[test] @@ -457,7 +595,7 @@ mod tests { let e = Config::from_json(&json!({"ignore": [{"snapshots": " ", "json_paths": ["$.a"]}]})).unwrap_err(); assert!(e.contains("names the snapshots"), "{e}"); let e = Config::from_json(&json!({"ignore": [{"snapshots": "a/**"}]})).unwrap_err(); - assert!(e.contains("no json_paths"), "{e}"); + assert!(e.contains("ignores nothing"), "{e}"); } #[test] @@ -495,6 +633,63 @@ mod tests { assert_eq!(Config::default().ignore_rules_for("x"), None); } + #[test] + fn image_masks_parse_and_apply_by_glob() { + let c = Config::from_json(&json!({"ignore": [ + {"snapshots": "ios/**", "region": {"bottom": 150}}, + {"snapshots": "screenshots/app/**", "rects": [{"x": 0, "y": 0, "width": 300, "height": 40}]}, + {"snapshots": "api/**", "json_paths": ["$.id"]}, + ]})) + .unwrap(); + let rules = c.ignore.unwrap(); + let ios = mask_for(&rules, "ios/usage-dark"); + assert_eq!(ios.edges, vec![Edges { bottom: Some(150), ..Default::default() }]); + assert!(ios.rects.is_empty()); + assert_eq!(mask_for(&rules, "screenshots/app/home").rects, vec![Rect { x: 0, y: 0, width: 300, height: 40 }]); + assert!(mask_for(&rules, "android/usage-dark").is_empty()); + assert!(mask_for(&rules, "api/x").is_empty()); + assert_eq!(mask_for(&rules, "android/x").key(), None); + assert!(ios.key().is_some_and(|k| k.len() == 16)); + // A rule's text parts don't apply to images, nor its mask to text. + assert!(rules_for(&rules, "ios/usage-dark").is_empty()); + } + + #[test] + fn image_masks_resolve_against_the_canvas() { + use crate::diff::Region; + let mask = ImageMask { + edges: vec![Edges { bottom: Some(150), right: Some(500), ..Default::default() }], + rects: vec![Rect { x: 90, y: 90, width: 50, height: 50 }, Rect { x: 200, y: 0, width: 5, height: 5 }], + }; + assert_eq!( + mask.resolve(100, 400), + vec![ + Region { x: 0, y: 250, width: 100, height: 150 }, + Region { x: 0, y: 0, width: 100, height: 400 }, + Region { x: 90, y: 90, width: 10, height: 50 }, + ] + ); + } + + #[test] + fn rejects_bad_masks() { + for (rule, needle) in [ + (json!({"snapshots": "a/**", "region": {}}), "names no edge"), + (json!({"snapshots": "a/**", "region": {"bottom": 0}}), "1 to 100000"), + (json!({"snapshots": "a/**", "region": {"middle": 4}}), "unknown field"), + (json!({"snapshots": "a/**", "region": {"bottom": -4}}), "invalid value"), + (json!({"snapshots": "a/**", "rects": [{"x": 0, "y": 0, "width": 0, "height": 4}]}), "rects[0]"), + (json!({"snapshots": "a/**", "rects": [{"x": 0, "y": 0, "width": 4}]}), "missing field `height`"), + (json!({"region": {"bottom": 4}}), "snapshots"), + ] { + let e = Config::from_json(&json!({ "ignore": [rule] })).unwrap_err(); + assert!(e.contains(needle), "{needle}: {e}"); + } + let many: Vec<_> = (0..101).map(|i| json!({"snapshots": format!("a{i}"), "region": {"top": 1}})).collect(); + let e = Config::from_json(&json!({ "ignore": many })).unwrap_err(); + assert!(e.contains("at most 100 regions"), "{e}"); + } + #[test] fn the_longest_matching_threshold_glob_wins() { let c = diff --git a/crates/visualci-core/src/diff.rs b/crates/visualci-core/src/diff.rs index 346d23e8..a90ea14a 100644 --- a/crates/visualci-core/src/diff.rs +++ b/crates/visualci-core/src/diff.rs @@ -11,6 +11,10 @@ //! The result lists changed regions (bounding boxes of 16 px tiles with changes, joined when they touch) and a diff //! fingerprint (a hash of the changed-tile map) that ignore rules match on, so the same flaky change is recognised //! from run to run. +//! +//! Masked areas (an ignore rule's `region` and `rects`) are left out: a pixel there is never counted as changed, nor +//! part of a region or the fingerprint. The overlay hatches them, and the result lists them with the changed pixels +//! they hid. use image::{Rgba, RgbaImage}; use serde::{Deserialize, Serialize}; @@ -60,6 +64,12 @@ pub struct DiffResult { pub regions: Vec, /// Hash of the changed-tile map; `None` when nothing changed. pub fingerprint: Option, + /// The masked areas, in canvas pixels: left out of the counts, regions and fingerprint. + #[serde(default)] + pub masked: Vec, + /// Pixels inside the masked areas that differ: changes the mask hid. + #[serde(default)] + pub masked_pixels: u64, } impl DiffResult { @@ -76,8 +86,27 @@ impl DiffResult { /// Compare two images. Returns the result and an overlay image: the head image faded, changed pixels red, /// anti-aliased pixels yellow. pub fn diff(base: &RgbaImage, head: &RgbaImage, options: DiffOptions) -> (DiffResult, RgbaImage) { + diff_masked(base, head, options, &[]) +} + +/// [`diff`], leaving out the masked areas (in canvas pixels): their pixels never count as changed, and the overlay +/// hatches them. +pub fn diff_masked( + base: &RgbaImage, + head: &RgbaImage, + options: DiffOptions, + masked: &[Region], +) -> (DiffResult, RgbaImage) { let width = base.width().max(head.width()); let height = base.height().max(head.height()); + let mut mask = vec![false; (width as usize) * (height as usize)]; + for r in masked { + for y in r.y..(r.y.saturating_add(r.height)).min(height) { + for x in r.x..(r.x.saturating_add(r.width)).min(width) { + mask[(y * width + x) as usize] = true; + } + } + } let size_changed = base.dimensions() != head.dimensions(); let max_delta = 35215.0 * options.threshold * options.threshold; let exact = options.threshold <= 0.0; @@ -86,6 +115,7 @@ pub fn diff(base: &RgbaImage, head: &RgbaImage, options: DiffOptions) -> (DiffRe let mut changed = vec![false; (width as usize) * (height as usize)]; let mut changed_pixels = 0u64; let mut anti_aliased_pixels = 0u64; + let mut masked_pixels = 0u64; for y in 0..height { for x in 0..width { @@ -113,7 +143,12 @@ pub fn diff(base: &RgbaImage, head: &RgbaImage, options: DiffOptions) -> (DiffRe // Outside one of the images: the canvas grew or shrank there. _ => (true, false), }; - let out = if is_changed { + let out = if mask[(y * width + x) as usize] { + if is_changed || is_aa { + masked_pixels += 1; + } + hatched(shown, x, y) + } else if is_changed { changed[(y * width + x) as usize] = true; changed_pixels += 1; Rgba([255, 0, 0, 255]) @@ -145,10 +180,17 @@ pub fn diff(base: &RgbaImage, head: &RgbaImage, options: DiffOptions) -> (DiffRe anti_aliased_pixels, regions, fingerprint, + masked: masked.to_vec(), + masked_pixels, }; (result, overlay) } +/// A masked pixel in the overlay: diagonal grey stripes over the faded image. +fn hatched(p: Rgba, x: u32, y: u32) -> Rgba { + if (x + y) % 12 < 3 { Rgba([112, 120, 136, 255]) } else { faded(p) } +} + fn pixel(img: &RgbaImage, x: u32, y: u32) -> Option> { (x < img.width() && y < img.height()).then(|| *img.get_pixel(x, y)) } @@ -372,6 +414,36 @@ mod tests { assert_eq!(*overlay.get_pixel(500, 700), Rgba([255, 0, 0, 255])); } + #[test] + fn changes_inside_the_mask_are_left_out() { + let base = RgbaImage::from_pixel(64, 64, Rgba([255, 255, 255, 255])); + let mut head = base.clone(); + // A change at the bottom only: inside a 16 px bottom band. + head.put_pixel(10, 60, Rgba([0, 0, 0, 255])); + head.put_pixel(40, 50, Rgba([0, 0, 0, 255])); + let band = [Region { x: 0, y: 48, width: 64, height: 16 }]; + let (r, overlay) = diff_masked(&base, &head, DiffOptions::EXACT, &band); + assert!(r.is_identical(), "{r:?}"); + assert_eq!((r.changed_pixels, r.masked_pixels, r.fingerprint.clone()), (0, 2, None)); + assert!(r.regions.is_empty()); + assert_eq!(r.masked, band); + assert_eq!(*overlay.get_pixel(0, 48), Rgba([112, 120, 136, 255]), "masked pixels are hatched"); + + // Another change outside it: only that one is a region, and the fingerprint is the same as the change alone. + head.put_pixel(5, 5, Rgba([0, 0, 0, 255])); + let (r, _) = diff_masked(&base, &head, DiffOptions::EXACT, &band); + assert_eq!((r.changed_pixels, r.masked_pixels), (1, 2)); + assert_eq!(r.regions, vec![Region { x: 0, y: 0, width: 16, height: 16 }]); + let mut alone = base.clone(); + alone.put_pixel(5, 5, Rgba([0, 0, 0, 255])); + let (a, _) = diff(&base, &alone, DiffOptions::EXACT); + assert_eq!(r.fingerprint, a.fingerprint); + + // Without the mask, all three count. + let (r, _) = diff(&base, &head, DiffOptions::EXACT); + assert_eq!((r.changed_pixels, r.masked_pixels, r.regions.len()), (3, 0, 3)); + } + #[test] fn perceptual_mode_ignores_faint_changes() { let base = white(100, 100); diff --git a/docs/design.md b/docs/design.md index e3fdb247..939c5fef 100644 --- a/docs/design.md +++ b/docs/design.md @@ -56,7 +56,7 @@ self-hostable version. | Baseline | The approved snapshot for a name on a lineage (see Baselines) | | Variant | An extra accepted image for a name (a flaky render). Matching any variant counts as a match | | Diff | `(base image key, head image key, diff settings) → score, changed-pixel count, mask, bounding boxes, fingerprint`. Cached, so the same pair is never diffed twice | -| Ignore rule | A diff fingerprint accepted as noise for one snapshot name (Argos's model), with an optional "after N occurrences". For text snapshots, a project's JSON paths and regular expressions whose matches are ignored | +| Ignore rule | A diff fingerprint accepted as noise for one snapshot name (Argos's model), with an optional "after N occurrences". For text snapshots, a project's JSON paths and regular expressions whose matches are ignored; for images, masked areas (`region`, `rects`) left out of the diff | | Config | `visualci.yml` in the repository, validated by the CLI and the server and stored on the build (`builds.config`). Each build uses its own commit's file; fields it sets (ignore rules, thresholds by glob, PDF engine and DPI, CI mode) override the project's settings for that build (`domain::build_settings`) | | Review | Approve or reject a build, or individual snapshots. Approval moves the baseline | @@ -191,6 +191,16 @@ the same way as a screenshot: a change keeps the GitHub check pending instead of `visualci.yml` when it has `ignore`, else the project's (`projects.ignore_rules`), plus rules set in the test for one snapshot (`snapshots.ignore_rules`). The head's rules apply to both sides, so a new rule hides a value without re-approving the baseline. Matches become `[ignored]` before comparing. They're checked when saved. +- Image masks (sc-9018): the same scoped rules can carry `region` (edge bands: `top`, `bottom`, `left`, `right`, in + pixels) and `rects` (`x`, `y`, `width`, `height`). For images and rendered pages, `BuildSettings::image_mask` + collects the areas of every rule in force that matches the snapshot (the build's file, else the project's: the same + model as text rules, read from `builds.config` when the build is compared or viewed, never from a later file). + `diffs::find_or_compute` resolves them against the diff's canvas (`ImageMask::resolve`) and diffs with + `visualci_core::diff::diff_masked`: masked pixels are never changed, so they stay out of the counts, the regions + and the fingerprint, and the overlay hatches them. The mask's hash is part of the diff cache key. The result keeps + `masked` (the areas) and `masked_pixels` (the differing pixels they hid); a page that differs only there is + `masked`, and counts as unchanged. A new mask is a "hides more" change, so it brings the `visualci.yml` item. Not + done: a ±1 px shift tolerance. - The page row keeps the normalized texts, so the review shows what was compared: a unified diff with line numbers (3 lines of context, folded in the web app, `?context=all` for every line) and, for JSON, the changes by path (`items[3].price: 10 → 12`), arrays aligned by element so an insertion is one change. diff --git a/frontend/content/docs/reference/config.md b/frontend/content/docs/reference/config.md index 90252567..3610a170 100644 --- a/frontend/content/docs/reference/config.md +++ b/frontend/content/docs/reference/config.md @@ -2,7 +2,7 @@ title: visualci.yml description: Keep VisualCI's settings in your repository. Ignore rules scoped to snapshot globs, thresholds, PDF rendering, the CI mode and what to upload, sent with every build. skill: visualci-config -skill_description: Writes and edits visualci.yml: ignore rules scoped to snapshot globs (JSON paths and regular expressions), thresholds, PDF rendering, the CI mode and what to upload. Use when the user wants to ignore volatile values such as timestamps or IDs, change thresholds or the CI mode, or keep VisualCI settings in the repository. Not for per-snapshot ignores in a single test. +skill_description: Writes and edits visualci.yml: ignore rules scoped to snapshot globs (JSON paths and regular expressions for text, masked regions and rectangles for screenshots), thresholds, PDF rendering, the CI mode and what to upload. Use when the user wants to ignore volatile values such as timestamps or IDs, leave a part of a screenshot that differs on every run (a status bar, a tab bar's glass effect) out of the diff, change thresholds or the CI mode, or keep VisualCI settings in the repository. Not for per-snapshot ignores in a single test. --- `visualci.yml` at the root of your repository holds the project's settings in code. `visualci build create` finds it, checks it and sends it with the build. Each build uses its own commit's file, so a change to it in a pull request applies to that pull request's builds, and reaches the default branch when the pull request merges. @@ -17,6 +17,8 @@ ignore: json_paths: ["$..request_id"] - snapshots: "emails/*.html" text_patterns: ['Sent \d{4}-\d{2}-\d{2}'] + - snapshots: "ios/**" + region: { bottom: 150 } threshold: "screenshots/**": 0.1 "pdfs/**": 0 @@ -45,7 +47,7 @@ The build's page shows the file it was sent, and `get_build` returns it as `conf | Field | What it does | | --- | --- | | `project` | `organization/project`. The token decides the project; the CLI warns when this names a different one. | -| `ignore` | Values in text snapshots that change on every run. A list of rules; see below. When the file has `ignore`, the project's own rules aren't used. | +| `ignore` | What changes on every run: values in text snapshots, and areas of screenshots and pages. A list of rules; see below. When the file has `ignore`, the project's own rules aren't used. | | `threshold` | 0 compares exactly; above 0 it's a colour threshold. One number for every snapshot, or a map of snapshot globs to thresholds. When several globs match, the longest glob (by its length in characters) wins. | | `pdf.engine` | `pdfbox` or `mutool`. | | `pdf.dpi` | Render resolution, 36 to 600. | @@ -66,11 +68,31 @@ Each rule names the snapshots it applies to with `snapshots`, a glob over snapsh Matching values become `[ignored]` on both sides before comparing. A new rule takes effect on the next build, without approving the baseline again. +### Masking part of an image + +For screenshots and PDF pages, a rule can leave areas of the image out of the diff instead: + +```yaml +ignore: + - snapshots: "ios/**" + region: { bottom: 150 } # the bottom 150 px: a tab bar that renders a little differently each run + - snapshots: "screenshots/app/**" + rects: [{ x: 0, y: 0, width: 300, height: 40 }] +``` + +- `region` masks bands along the image's edges, each this many pixels deep: `top`, `bottom`, `left` and `right`, one or more of them. `{ bottom: 150 }` stays at the bottom of a screenshot of any height. +- `rects` masks rectangles, from the image's top-left corner: `x`, `y`, `width` and `height`. +- Sizes are in pixels of the image as uploaded (for a PDF, the rendered page at its DPI): a 3x screenshot's 150 px is 50 points. + +Pixels inside a masked area aren't compared. A page that differs only inside them is `masked` and its snapshot unchanged; a change partly outside is reported by the regions outside alone. The review page hatches the masked areas over the images and the diff, `get_snapshot` lists them per page as `masked` (with `masked_pixels`, the differing pixels they hid), and the pull request comment says how many areas of each image it shows were masked. Masks are applied when VisualCI compares, so a new mask takes effect on the next build without approving the baseline again. A rule can combine a mask with `json_paths` or `text_patterns`; each part applies to the snapshots it fits. At most 100 regions and rectangles in all. + +Mask only what really varies from run to run. A masked area hides every change in it, real ones too. + Rules can also be set next to the assertion, for one snapshot only. The [Ruby helpers](/docs/screenshots/rspec/) take `ignore:`, and an upload manifest entry takes `"ignore": {"json_paths": [...], "text_patterns": [...]}`. ## Changes to the file are reviewed -The file can change what counts as a change, so a pull request can't use it to let changes through unseen. When a build's ignore rules or thresholds could hide something its base build's would show (a new or wider rule, a higher threshold), the build gets a `visualci.yml` item next to its snapshots. It shows the rules and thresholds before and after, and it has to be approved like any other change. Removing rules or lowering a threshold needs no review. +The file can change what counts as a change, so a pull request can't use it to let changes through unseen. When a build's ignore rules or thresholds could hide something its base build's would show (a new or wider rule, a new masked area, a higher threshold), the build gets a `visualci.yml` item next to its snapshots. It shows the rules and thresholds before and after, and it has to be approved like any other change. Removing rules or lowering a threshold needs no review. ## Checking the file diff --git a/frontend/content/docs/screenshots/mobile.md b/frontend/content/docs/screenshots/mobile.md index 10e9e9f6..cd7fcace 100644 --- a/frontend/content/docs/screenshots/mobile.md +++ b/frontend/content/docs/screenshots/mobile.md @@ -168,6 +168,18 @@ visualci upload --platform flutter-linux test/goldens Golden images depend on the fonts and the operating system that render them, so run them on the same CI image every time and tag them with it. Stop committing the golden files once VisualCI holds the baselines. +## Parts that differ on every run + +Some system chrome isn't stable between simulator or emulator runs: iOS 26's Liquid Glass tab bar refracts what's +behind it a pixel or so differently on each run. When the app can't hide it, mask that band in +[`visualci.yml`](/docs/reference/config/#masking-part-of-an-image) so the rest of the screen is still compared: + +```yaml +ignore: + - snapshots: "ios/**" + region: { bottom: 150 } # pixels of the screenshot: about 50 pt on a 3x device +``` + ## Then Send the build from your CI provider's guide ([GitHub Actions](/docs/ci/github-actions/), diff --git a/frontend/public/visualci.schema.json b/frontend/public/visualci.schema.json index 6acea188..12241ac8 100644 --- a/frontend/public/visualci.schema.json +++ b/frontend/public/visualci.schema.json @@ -8,6 +8,45 @@ ], "type": "string" }, + "Edges": { + "additionalProperties": false, + "description": "Bands along an image's edges, each the given number of pixels deep.", + "properties": { + "bottom": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "left": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "right": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "top": { + "format": "uint32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + }, "Gallery": { "additionalProperties": false, "description": "The public gallery: named groups of screenshots.", @@ -86,6 +125,39 @@ ], "type": "string" }, + "Rect": { + "additionalProperties": false, + "description": "A rectangle in an image's pixels, from its top-left corner.", + "properties": { + "height": { + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "width": { + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "x": { + "format": "uint32", + "minimum": 0, + "type": "integer" + }, + "y": { + "format": "uint32", + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "x", + "y", + "width", + "height" + ], + "type": "object" + }, "ScopedIgnoreRule": { "additionalProperties": false, "description": "An ignore rule for the snapshots whose names match a glob.", @@ -97,6 +169,24 @@ }, "type": "array" }, + "rects": { + "description": "Images: rectangles whose pixels aren't compared, in pixels of the image from its top-left corner.", + "items": { + "$ref": "#/$defs/Rect" + }, + "type": "array" + }, + "region": { + "anyOf": [ + { + "$ref": "#/$defs/Edges" + }, + { + "type": "null" + } + ], + "description": "Images: bands along the image's edges whose pixels aren't compared, in pixels of the image: `{ bottom: 150 }`." + }, "snapshots": { "description": "The snapshots this rule applies to, as a glob over snapshot names: `api/invoices/**`, `emails/*.html`.", "type": "string" diff --git a/frontend/src/__tests__/masked-areas.test.tsx b/frontend/src/__tests__/masked-areas.test.tsx new file mode 100644 index 00000000..b183e8c0 --- /dev/null +++ b/frontend/src/__tests__/masked-areas.test.tsx @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { render } from '@testing-library/react' +import { MaskedAreas } from '../components/MaskedAreas' +import type { DiffResult } from '../api/types' + +const diff = (masked: DiffResult['masked']): DiffResult => ({ + width: 400, + height: 800, + size_changed: false, + changed_pixels: 0, + changed_fraction: 0, + anti_aliased_pixels: 0, + regions: [], + fingerprint: '', + masked, + masked_pixels: 12, +}) + +describe('masked areas', () => { + it('hatches each masked area where it is on the image', () => { + const { container } = render( + , + ) + const areas = [...container.querySelectorAll('.masked-areas .masked-area')] + expect(areas).toHaveLength(2) + expect(areas[0].style.cssText).toBe('left: 0%; top: 81.25%; width: 100%; height: 18.75%;') + expect(areas[1].style.cssText).toBe('left: 0%; top: 0%; width: 25%; height: 5%;') + expect(container.firstElementChild?.getAttribute('aria-hidden')).toBe('true') + }) + + it('draws nothing without masked areas or a diff', () => { + expect(render().container.innerHTML).toBe('') + expect(render().container.innerHTML).toBe('') + }) +}) diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index e71004e6..982fe28f 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -414,10 +414,15 @@ export type DiffResult = { anti_aliased_pixels: number regions: Region[] fingerprint: string + /** Areas an ignore rule's `region` or `rects` left out of the diff, in canvas pixels. */ + masked: Region[] + /** Pixels inside the masked areas that differ: changes the mask hid. */ + masked_pixels: number } export type PageOp = 'unchanged' | 'changed' | 'inserted' | 'removed' -export type PageState = 'unchanged' | 'changed' | 'ignored' | 'variant' | 'within_threshold' +/** `masked`: the images differ only inside masked areas, so the page counts as unchanged. */ +export type PageState = 'unchanged' | 'changed' | 'ignored' | 'variant' | 'within_threshold' | 'masked' /** A line of a text diff, with its 1-based line numbers in the base and head (an added line has no base line). */ export type TextLine = { tag: '+' | '-' | ' '; text: string; base_line?: number; head_line?: number } diff --git a/frontend/src/components/MaskedAreas.tsx b/frontend/src/components/MaskedAreas.tsx new file mode 100644 index 00000000..686c952e --- /dev/null +++ b/frontend/src/components/MaskedAreas.tsx @@ -0,0 +1,26 @@ +import type { DiffResult } from '../api/types' + +/** + * The areas an ignore rule's `region` or `rects` left out of the diff, hatched over a page's image (in the diff's canvas + * pixels, as percentages, so they follow the image at any zoom). Changes inside them weren't compared. + */ +export function MaskedAreas({ diff }: { diff: DiffResult | null }) { + const areas = diff?.masked ?? [] + if (!diff || !areas.length || !diff.width || !diff.height) return null + return ( + + {areas.map((r, i) => ( + + ))} + + ) +} diff --git a/frontend/src/pages/SnapshotPage.tsx b/frontend/src/pages/SnapshotPage.tsx index dd65f412..557061dc 100644 --- a/frontend/src/pages/SnapshotPage.tsx +++ b/frontend/src/pages/SnapshotPage.tsx @@ -22,6 +22,7 @@ import { usePersistentState } from '../lib/theme' import { approvedElsewhereLabel, compareForReview, reviewable, useReviewOrder, type ReviewOrder } from './BuildPage' import { TextSnapshot, textHunks } from '../components/TextSnapshot' import { SliderStage } from '../components/SliderStage' +import { MaskedAreas } from '../components/MaskedAreas' import { SNAPSHOT_MODES, type SnapshotMode } from '../lib/snapshotModes' import { ZOOMS, ZoomContext, captureScale, shotWidth, useZoomClick, zoomLabel, type Zoom } from '../lib/zoom' @@ -645,6 +646,7 @@ function opLabel(p: PageRow) { if (p.state === 'variant') return 'variant' if (p.state === 'ignored') return 'ignored' if (p.state === 'within_threshold') return 'in threshold' + if (p.state === 'masked') return 'masked' return 'changed' } return p.op @@ -708,6 +710,11 @@ function PageView({ index, page: p, mode, highlight, active, collapsedByDefault, {d.regions.length > 0 && {plural(d.regions.length, 'region')}} {d.anti_aliased_pixels > 0 && {n(d.anti_aliased_pixels)} anti-aliased} + {d.masked.length > 0 && ( + + {d.masked_pixels > 0 ? `${n(d.masked_pixels)} px masked` : plural(d.masked.length, 'masked area')} + + )} )} @@ -756,6 +763,17 @@ function hintFor(mode: Mode, p: PageRow): string | undefined { return undefined } +/** What's drawn over a page's images: the hatched masked areas, and the changed regions in the chosen style. */ +function Overlays({ page, style }: { page: PageRow; style: Highlight }) { + if (style === 'off') return null + return ( + <> + + + + ) +} + function Regions({ page, style }: { page: PageRow; style: Highlight }) { const maskId = `dim${useId().replace(/[^A-Za-z0-9_-]/g, '')}` const d = page.diff @@ -931,7 +949,7 @@ export function PageImages({ const base = p.base_url ? ( - + ) : ( @@ -940,7 +958,7 @@ export function PageImages({ const head = p.head_url ? ( - + ) : ( @@ -978,7 +996,7 @@ export function PageImages({ {p.overlay_url ? ( - + {/* The diff is drawn in this build's coordinates: new comments go on this build's image. */} @@ -1080,7 +1098,7 @@ function Slider({ > {(pos) => ( <> - + {/* Each side's pins show, and take presses, on its own side of the divider: a comment goes on the image where the press starts, and on the line counts as this build. In Fade, comments go on this build. */} Date: Fri, 4 Dec 2026 04:10:37 +1300 Subject: [PATCH 2/2] visualci-core: a negative mask size's message differs with arbitrary_precision --- crates/visualci-core/src/config.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/visualci-core/src/config.rs b/crates/visualci-core/src/config.rs index 87c963a9..212eb464 100644 --- a/crates/visualci-core/src/config.rs +++ b/crates/visualci-core/src/config.rs @@ -677,7 +677,9 @@ mod tests { (json!({"snapshots": "a/**", "region": {}}), "names no edge"), (json!({"snapshots": "a/**", "region": {"bottom": 0}}), "1 to 100000"), (json!({"snapshots": "a/**", "region": {"middle": 4}}), "unknown field"), - (json!({"snapshots": "a/**", "region": {"bottom": -4}}), "invalid value"), + // "invalid value", or "invalid number" with serde_json's arbitrary_precision, + // which the app's dependencies turn on. + (json!({"snapshots": "a/**", "region": {"bottom": -4}}), "invalid"), (json!({"snapshots": "a/**", "rects": [{"x": 0, "y": 0, "width": 0, "height": 4}]}), "rects[0]"), (json!({"snapshots": "a/**", "rects": [{"x": 0, "y": 0, "width": 4}]}), "missing field `height`"), (json!({"region": {"bottom": 4}}), "snapshots"),