From 2e17b494e68398378f892b115c2136fc19412f7e Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Wed, 2 Dec 2026 17:48:10 +1300 Subject: [PATCH] A change made of other PRs' approved changes says so (sc-8785): two pull requests that change the same screen and merge separately leave an image neither showed. While processing, a changed snapshot whose every changed region is exactly a region a merged PR's build changed and approved (the same box, the same old and new pixels) points at that build (snapshots.matches_build_id, migration 000038, models::matching): get_build's matches and the build page say 'matches PR #8's approved change'; a hint that approves nothing, and review with only: "matching" (MCP and the web app's 'Approve all matching') approves those. Between merged approvals in a build's history the nearer merge wins, whatever order the webhooks came in. Docs: Agents, design; plugin 0.1.30 --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- docs/design.md | 5 + gemini-extension.json | 2 +- server/frontend/content/docs/agents.md | 2 +- server/frontend/src/api/hooks.ts | 2 +- server/frontend/src/api/types.ts | 2 + server/frontend/src/pages/BuildPage.tsx | 16 ++ server/migration/src/lib.rs | 2 + .../src/m20261202_000038_matches_approved.rs | 29 +++ server/src/controllers/ui.rs | 4 + server/src/mcp.rs | 11 +- server/src/models/_entities/snapshots.rs | 2 + server/src/models/baselines.rs | 13 +- server/src/models/builds.rs | 6 + server/src/models/matching.rs | 245 ++++++++++++++++++ server/src/models/mod.rs | 1 + server/src/models/snapshots.rs | 15 +- server/tests/requests/comments.rs | 59 ++++- skills/visualci-review/SKILL.md | 2 +- 21 files changed, 409 insertions(+), 15 deletions(-) create mode 100644 server/migration/src/m20261202_000038_matches_approved.rs create mode 100644 server/src/models/matching.rs diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index e28b7eed..1ed1c602 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,7 +5,7 @@ "plugins": [ { "name": "visualci", - "version": "0.1.29", + "version": "0.1.30", "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 ca59bb27..0718a07f 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.29", + "version": "0.1.30", "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 e533cbdc..e55229b9 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "visualci", "displayName": "VisualCI", - "version": "0.1.29", + "version": "0.1.30", "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/docs/design.md b/docs/design.md index 2fdf97a9..46c1a70c 100644 --- a/docs/design.md +++ b/docs/design.md @@ -200,6 +200,11 @@ the same way as a screenshot: a change keeps the GitHub check pending instead of `get_build`, the PR comment, the check summary) it reads "Claude Code for Ada Lovelace", "Ada Lovelace" (the web app) or "a project token (CI)" (`models::reviews::by`): VisualCI is mostly used by agents, so an agent's approval never reads as the person's own (Nathan, 2 Dec 2026). +- Two pull requests that change the same snapshot and merge separately leave an image neither showed. Between merged + approvals in a build's history the nearer merge wins, and a change whose every region is exactly a region a merged + PR's build changed and approved (the same box, the same old and new pixels) points at that build + (`snapshots.matches_build_id`, `models::matching`, found while processing): "matches PR #8's approved change", a hint + that approves nothing; `review` with `only: "matching"` approves those (sc-8785). - Partial approval per snapshot. "Accept as variant" adds the image to the name's variants without replacing the baseline. "Ignore this change" stores the diff fingerprint. - GitHub App: check run per project and build name, named `VisualCI` (default build name) or `VisualCI: `, so a diff --git a/gemini-extension.json b/gemini-extension.json index 84fdfad8..c6d3f549 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.29", + "version": "0.1.30", "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.", "mcpServers": { "visualci": { diff --git a/server/frontend/content/docs/agents.md b/server/frontend/content/docs/agents.md index d68602da..16abd241 100644 --- a/server/frontend/content/docs/agents.md +++ b/server/frontend/content/docs/agents.md @@ -119,7 +119,7 @@ failing in the repository instead of sending them. **Reviews** -- `review`: approve or reject a build's changes, some snapshots' changes (`snapshots`), or only its new or only its changed snapshots (`only: "added"` or `"changed"`). Add a `note` saying why ("The new header, as the issue asked"): it's kept with the review and shown in the build's reviews, `get_build` and the pull request comment. Every review says who made it and how: "Claude Code for Ada Lovelace" for an agent signed in as its person, "Ada Lovelace" in the web app, or "a project token (CI)", so an agent's approval never reads as the person's own. +- `review`: approve or reject a build's changes, some snapshots' changes (`snapshots`), or only its new or only its changed snapshots (`only: "added"` or `"changed"`). Add a `note` saying why ("The new header, as the issue asked"): it's kept with the review and shown in the build's reviews, `get_build` and the pull request comment. Every review says who made it and how: "Claude Code for Ada Lovelace" for an agent signed in as its person, "Ada Lovelace" in the web app, or "a project token (CI)", so an agent's approval never reads as the person's own. When two pull requests change the same screen and merge separately, the screen after both is one neither showed, so it shows as changed until someone reviews it. If the change is exactly another pull request's approved change (the same regions, from the same old pixels to the same new ones), `get_build` marks it `matches` ("matches PR #8's approved change"), and `only: "matching"` approves those in one call. - `review_page`: accept one page as a variant, or ignore one exact change in later builds too. **Running a comparison** diff --git a/server/frontend/src/api/hooks.ts b/server/frontend/src/api/hooks.ts index a266b37f..2a0f0503 100644 --- a/server/frontend/src/api/hooks.ts +++ b/server/frontend/src/api/hooks.ts @@ -278,7 +278,7 @@ function useBuildAction(org: string, project: string, n: number, fn: (v: V) = } export function useReview(org: string, project: string, n: number) { - return useBuildAction(org, project, n, (v: { action: 'approve' | 'reject'; snapshot_ids?: string[]; only?: 'added' | 'changed' }) => + return useBuildAction(org, project, n, (v: { action: 'approve' | 'reject'; snapshot_ids?: string[]; only?: 'added' | 'changed' | 'matching' }) => post(`${buildPath(org, project, n)}/review`, v), ) } diff --git a/server/frontend/src/api/types.ts b/server/frontend/src/api/types.ts index 215a032d..3b2d8151 100644 --- a/server/frontend/src/api/types.ts +++ b/server/frontend/src/api/types.ts @@ -310,6 +310,8 @@ export type SnapshotRow = { change: { fraction: number; amount: number } | null /** The same new version was already approved on another branch. A hint: it approves nothing here. */ approved_elsewhere: ApprovedElsewhere | null + /** Every changed region is exactly a change a merged pull request approved: "matches PR #8's approved change". */ + matches?: { build: number; branch: string; pr_number: number | null; label: string } | null thumbnail_url: string | null /** Its content flipped back and forth over the branch's recent builds: a hint only. */ flaky: boolean diff --git a/server/frontend/src/pages/BuildPage.tsx b/server/frontend/src/pages/BuildPage.tsx index 1ac241b8..1607f0af 100644 --- a/server/frontend/src/pages/BuildPage.tsx +++ b/server/frontend/src/pages/BuildPage.tsx @@ -218,6 +218,17 @@ export function BuildPage() { Approve all {g.state} )} + {canReviewBuild && g.state === 'changed' && list.filter((s) => s.matches && !s.review).length > 1 && ( + + )}
    {list.map((s) => ( @@ -439,6 +450,11 @@ function SnapshotItem({ matched {environmentLabel(s.matched_environment)} )} {s.baseline_note && Baseline {s.baseline_note}} + {s.matches && ( + + {s.matches.label[0].toUpperCase() + s.matches.label.slice(1)} + + )} {s.approved_elsewhere && ( {approvedElsewhereLabel(s.approved_elsewhere)} diff --git a/server/migration/src/lib.rs b/server/migration/src/lib.rs index abdc6c9e..a316ce1e 100644 --- a/server/migration/src/lib.rs +++ b/server/migration/src/lib.rs @@ -41,6 +41,7 @@ mod m20261202_000034_render_job_token; mod m20261202_000035_invitation_for_user; mod m20261202_000036_tokens_can_approve; mod m20261202_000037_review_source; +mod m20261202_000038_matches_approved; pub struct Migrator; @@ -88,6 +89,7 @@ impl MigratorTrait for Migrator { Box::new(m20261202_000035_invitation_for_user::Migration), Box::new(m20261202_000036_tokens_can_approve::Migration), Box::new(m20261202_000037_review_source::Migration), + Box::new(m20261202_000038_matches_approved::Migration), // inject-above (do not remove this comment) ] } diff --git a/server/migration/src/m20261202_000038_matches_approved.rs b/server/migration/src/m20261202_000038_matches_approved.rs new file mode 100644 index 00000000..5e3f4c77 --- /dev/null +++ b/server/migration/src/m20261202_000038_matches_approved.rs @@ -0,0 +1,29 @@ +//! A changed snapshot whose every changed region is exactly a change another pull request had approved (merged into +//! this build's history) points at that PR's build: "matches PR #8's approved change". A hint, and what +//! `review only: "matching"` approves; it approves nothing by itself. +use sea_orm_migration::prelude::*; + +pub struct Migration; + +impl MigrationName for Migration { + fn name(&self) -> &str { + "m20261202_000038_matches_approved" + } +} + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection() + .execute_unprepared( + "ALTER TABLE snapshots ADD COLUMN matches_build_id BIGINT REFERENCES builds(id) ON DELETE SET NULL;", + ) + .await?; + Ok(()) + } + + async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection().execute_unprepared("ALTER TABLE snapshots DROP COLUMN matches_build_id;").await?; + Ok(()) + } +} diff --git a/server/src/controllers/ui.rs b/server/src/controllers/ui.rs index de017ed9..bdbf9740 100644 --- a/server/src/controllers/ui.rs +++ b/server/src/controllers/ui.rs @@ -768,6 +768,8 @@ struct SnapshotRow { thumbnail_url: Option, /// A change whose content flipped back and forth over the branch's recent builds (`flaky_in`): a hint only. flaky: bool, + /// A change made only of changes a merged pull request approved (`models::matching`): a hint only. + matches: Option, } #[debug_handler] @@ -793,6 +795,7 @@ async fn show_build( let ids: Vec = list.iter().filter_map(|s| s.baseline_id).collect(); let notes = crate::models::baselines::local_notes(&ctx.db, &ids).await?; let flaky = snapshots::Model::flaky_in(&ctx.db, &build).await?; + let mut matching = crate::models::matching::of_build(&ctx.db, build.id).await?; for s in list { let pages = snapshot_pages::Entity::find() .filter(snapshot_pages::Column::SnapshotId.eq(s.id)) @@ -842,6 +845,7 @@ async fn show_build( approved_elsewhere: elsewhere.remove(&s.id), thumbnail_url: thumb, flaky: is_flaky, + matches: matching.remove(&s.id), }); } let mut summary = serde_json::to_value(BuildSummary::for_viewer(&build, member)).unwrap_or_default(); diff --git a/server/src/mcp.rs b/server/src/mcp.rs index 6a1667b6..ffb64f31 100644 --- a/server/src/mcp.rs +++ b/server/src/mcp.rs @@ -311,7 +311,8 @@ pub struct ReviewArgs { pub action: String, /// Snapshot names to review; all changed snapshots when left out. pub snapshots: Option>, - /// Only the build's `added` (new) snapshots, or only its `changed` ones, in one call. Not with `snapshots`. + /// Only the build's `added` (new) snapshots, only its `changed` ones, or only its `matching` ones (changes made + /// only of changes merged pull requests approved: `get_build`'s `matches`), in one call. Not with `snapshots`. pub only: Option, /// With `reject`: why, as a comment thread on each rejected snapshot (Markdown), so the next person or agent sees /// what's wrong. Approving a snapshot with an open thread is refused until the thread is resolved. @@ -1461,7 +1462,7 @@ impl VisualCi { } #[tool( - description = "A build's status and its snapshots that need attention, 30 at a time (offset and limit page through; longer lists also come grouped by state and name prefix) (changed, added, removed, failed), with how many pages changed in each, the largest change first (order: name to sort by name), and approved_elsewhere when the same new version was already approved on another branch (a hint: it approves nothing). Unchanged snapshots are only counted unless include_unchanged is set. `config` is the visualci.yml the build was sent (null when it had none: the project's settings applied). `flaky: true` marks a change whose content flipped back and forth over the branch's recent builds: often something that differs between runs (the time, an animation, a late font) rather than a real change, so check it before approving, and make the test deterministic.", + description = "A build's status and its snapshots that need attention, 30 at a time (offset and limit page through; longer lists also come grouped by state and name prefix) (changed, added, removed, failed), with how many pages changed in each, the largest change first (order: name to sort by name), and approved_elsewhere when the same new version was already approved on another branch (a hint: it approves nothing). Unchanged snapshots are only counted unless include_unchanged is set. `config` is the visualci.yml the build was sent (null when it had none: the project's settings applied). `flaky: true` marks a change whose content flipped back and forth over the branch's recent builds: often something that differs between runs (the time, an animation, a late font) rather than a real change, so check it before approving, and make the test deterministic. `matches` marks a change made only of changes a merged pull request approved (two PRs that changed the same screen and merged separately): approve those with `review` and `only: \"matching\"`.", annotations(title = "Get build", read_only_hint = true, idempotent_hint = true, open_world_hint = false) )] async fn get_build( @@ -1485,6 +1486,7 @@ impl VisualCi { let sizes = snapshots::change_sizes(&self.ctx.db, build.id).await.map_err(internal)?; snapshots::sort_for_review(&mut listed, &sizes, args.order); let elsewhere = crate::models::baselines::approved_elsewhere(&self.ctx.db, build.id).await.map_err(internal)?; + let matching = crate::models::matching::of_build(&self.ctx.db, build.id).await.map_err(internal)?; let project_url = format!("{}/{org}/{}", self.settings()?.app_url(), project.slug); let snapshot_url = |e: &crate::models::baselines::ApprovedElsewhere| { format!("{project_url}/builds/{}/snapshots/{}", e.build, e.snapshot_id) @@ -1530,6 +1532,11 @@ impl VisualCi { "changed_pages": pages.map(|p| p.iter().filter(|p| p.state == "changed").count()), "moved_lines": detail.as_ref().map_or(0, |d| d.moved.len()), }); + if let Some(m) = matching.get(&s.id) { + // Every changed region is exactly a change a merged pull request approved: `review` with + // `only: "matching"` approves these. A hint: it approves nothing by itself. + item["matches"] = json!(m); + } if s.is_change() && flaky.contains(&(s.name.clone(), s.platform.clone())) { // Its content flipped back and forth over the branch's recent builds: a hint, not a verdict. item["flaky"] = json!(true); diff --git a/server/src/models/_entities/snapshots.rs b/server/src/models/_entities/snapshots.rs index b7909c54..9739a37f 100644 --- a/server/src/models/_entities/snapshots.rs +++ b/server/src/models/_entities/snapshots.rs @@ -42,6 +42,8 @@ pub struct Model { #[sea_orm(column_type = "Text")] pub state: String, pub base_snapshot_id: Option, + /// The pull request build whose approved change this change exactly matches (`models::matching`). + pub matches_build_id: Option, #[sea_orm(column_type = "Text", nullable)] pub review: Option, #[sea_orm(column_type = "Text", nullable)] diff --git a/server/src/models/baselines.rs b/server/src/models/baselines.rs index e8489b33..5f8936a1 100644 --- a/server/src/models/baselines.rs +++ b/server/src/models/baselines.rs @@ -271,9 +271,20 @@ pub async fn resolve( // default-branch ones. let mut latest: HashMap<(String, String, String), Model> = HashMap::new(); let rank = |r: &Model| (r.build_id > after || r.branch == build.branch || merged_and_new(r), r.id); + // Between two merged pull requests' approvals, the nearer merge in this build's history wins (it was merged + // later on this line), whatever order the webhooks arrived in. + let history = ancestry(build); + let nearness = |r: &Model| history.iter().position(|c| c == &r.commit_sha).unwrap_or(usize::MAX); + let better = |new: &Model, old: &Model| { + if new.approval == "merged" && old.approval == "merged" && nearness(new) != nearness(old) { + nearness(new) < nearness(old) + } else { + rank(old) < rank(new) + } + }; for row in rows { let key = (row.name.clone(), row.platform.clone(), row.environment.clone()); - if latest.get(&key).is_none_or(|existing| rank(existing) < rank(&row)) { + if latest.get(&key).is_none_or(|existing| better(&row, existing)) { latest.insert(key, row); } } diff --git a/server/src/models/builds.rs b/server/src/models/builds.rs index d5924e25..d9d3f00f 100644 --- a/server/src/models/builds.rs +++ b/server/src/models/builds.rs @@ -685,6 +685,12 @@ impl Model { } } + // Changes made only of changes merged pull requests approved say so (a hint; `models::matching`). A failure + // here costs the hint, never the build. + if let Err(e) = super::matching::mark(db, store, &self).await { + tracing::warn!(build = self.id, error = %e, "matching approved changes"); + } + let has_base = !base_snapshots.is_empty(); let mut active = self.into_active_model(); active.warnings = Set(serde_json::json!(warnings)); diff --git a/server/src/models/matching.rs b/server/src/models/matching.rs new file mode 100644 index 00000000..b1161e40 --- /dev/null +++ b/server/src/models/matching.rs @@ -0,0 +1,245 @@ +//! Changes made of other pull requests' approved changes. Two pull requests that change the same screenshot and merge +//! separately leave an image neither of them showed: PR A approved its change without B's, B approved its change +//! without A's. The next build compares with one of those approvals and shows the other's change again, although it +//! was reviewed (main build #93 on 2 Dec 2026: PR #8's settings checkbox over PR #6's approved page). +//! +//! When every changed region of a snapshot's changed pages is exactly a region a merged pull request's build had +//! changed and that PR approved (the same box, the same old pixels and the same new pixels), the snapshot points at +//! that build (`snapshots.matches_build_id`): "matches PR #8's approved change". It's a hint and approves nothing; +//! `review` with `only: "matching"` approves those snapshots in one call. + +use std::collections::HashMap; + +use image::RgbaImage; +use loco_rs::prelude::*; +use sea_orm::{ConnectionTrait, DbBackend, QueryOrder, Statement}; +use visualci_core::diff::{DiffResult, Region}; + +use super::{ + _entities::{diffs, snapshot_pages, snapshots as snapshot_entity}, + builds, snapshots, +}; +use crate::blobstore::BlobStore; + +/// A page's change: the diff's canvas and regions, and its two images. +struct PageChange { + position: i32, + width: u32, + height: u32, + regions: Vec, + base_image: String, + head_image: String, +} + +async fn page_changes(db: &impl ConnectionTrait, snapshot_id: i64) -> Result> { + let pages = snapshot_pages::Entity::find() + .filter(snapshot_pages::Column::SnapshotId.eq(snapshot_id)) + .order_by_asc(snapshot_pages::Column::Position) + .all(db) + .await?; + let mut out = Vec::new(); + for p in pages.into_iter().filter(|p| p.state == "changed") { + let (Some(diff_id), Some(base_image), Some(head_image)) = (p.diff_id, p.base_image, p.head_image) else { + continue; + }; + let Some(diff) = diffs::Entity::find_by_id(diff_id).one(db).await? else { continue }; + let Ok(result) = serde_json::from_value::(diff.result) else { continue }; + out.push(PageChange { + position: p.position, + width: result.width, + height: result.height, + regions: result.regions, + base_image, + head_image, + }); + } + Ok(out) +} + +/// A merged approval's pull request snapshot: how near its merge is in the build's history, its build, the snapshot. +type Candidate = (usize, i64, i64); + +/// Decoded images, by blob, so a page shared by several candidates is read once. +struct Images<'a> { + store: &'a BlobStore, + cache: HashMap>, +} + +impl Images<'_> { + async fn get(&mut self, sha: &str) -> Option<&RgbaImage> { + if !self.cache.contains_key(sha) { + let decoded = match self.store.get(sha).await { + Ok(bytes) => image::load_from_memory(&bytes).ok().map(|i| i.to_rgba8()), + Err(_) => None, + }; + self.cache.insert(sha.to_string(), decoded); + } + self.cache.get(sha).and_then(Option::as_ref) + } +} + +/// Whether two images have the same pixels inside a region (a pixel one has and the other doesn't is a difference). +#[must_use] +pub fn same_in(a: &RgbaImage, b: &RgbaImage, r: &Region) -> bool { + for y in r.y..r.y.saturating_add(r.height) { + for x in r.x..r.x.saturating_add(r.width) { + let pa = (x < a.width() && y < a.height()).then(|| a.get_pixel(x, y)); + let pb = (x < b.width() && y < b.height()).then(|| b.get_pixel(x, y)); + if pa != pb { + return false; + } + } + } + true +} + +/// Whether every region of `ours` is a region `theirs` changed, from the same old pixels to the same new ones. +async fn covered(images: &mut Images<'_>, ours: &PageChange, theirs: &PageChange) -> bool { + if (ours.width, ours.height) != (theirs.width, theirs.height) || ours.regions.is_empty() { + return false; + } + if !ours.regions.iter().all(|r| theirs.regions.contains(r)) { + return false; + } + for (a, b) in [(&ours.base_image, &theirs.base_image), (&ours.head_image, &theirs.head_image)] { + let Some(a) = images.get(a).await.cloned() else { return false }; + let Some(b) = images.get(b).await else { return false }; + if !ours.regions.iter().all(|r| same_in(&a, b, r)) { + return false; + } + } + true +} + +/// Mark the build's changed snapshots that are made only of changes merged pull requests approved. Returns how many. +/// +/// # Errors +/// On a database or blob store error. +pub async fn mark(db: &DatabaseConnection, store: &BlobStore, build: &builds::Model) -> Result { + if build.mode != "ci" { + return Ok(0); + } + let changed: Vec = snapshots::Model::for_build(db, build.id) + .await? + .into_iter() + .filter(|s| s.state == "changed" && s.kind != "text") + .collect(); + if changed.is_empty() { + return Ok(0); + } + let names: Vec = changed.iter().map(|s| s.name.clone()).collect(); + let mut ancestry = vec![build.commit_sha.clone()]; + ancestry.extend(build.parent_commits.iter().cloned()); + // The pull requests' own snapshots behind each merged approval in this build's history, nearest merge first. + let rows = db + .query_all_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "SELECT bl.name, bl.platform, bl.commit_sha, bl.build_id, s.id AS snapshot_id \ + FROM baselines bl JOIN snapshots s ON s.id = bl.snapshot_id \ + WHERE bl.project_id = $1 AND bl.build_name = $2 AND bl.approval = 'merged' AND bl.commit_sha = ANY($3) \ + AND bl.name = ANY($4) AND s.state = 'changed'", + [build.project_id.into(), build.name.clone().into(), ancestry.clone().into(), names.into()], + )) + .await?; + let mut candidates: HashMap<(String, String), Vec> = HashMap::new(); + for r in rows { + let commit: String = r.try_get("", "commit_sha")?; + let near = ancestry.iter().position(|c| c == &commit).unwrap_or(usize::MAX); + candidates.entry((r.try_get("", "name")?, r.try_get("", "platform")?)).or_default().push(( + near, + r.try_get("", "build_id")?, + r.try_get("", "snapshot_id")?, + )); + } + let mut images = Images { store, cache: HashMap::new() }; + let mut marked = 0; + for s in changed { + let Some(mut theirs) = candidates.remove(&(s.name.clone(), s.platform.clone())) else { continue }; + theirs.sort_unstable(); + let ours = page_changes(db, s.id).await?; + if ours.is_empty() { + continue; + } + let mut matched = None; + for (_, their_build, their_snapshot) in theirs { + let their_pages = page_changes(db, their_snapshot).await?; + let mut all = true; + for page in &ours { + let Some(other) = their_pages.iter().find(|p| p.position == page.position) else { + all = false; + break; + }; + if !covered(&mut images, page, other).await { + all = false; + break; + } + } + if all { + matched = Some(their_build); + break; + } + } + if let Some(id) = matched { + let mut active = snapshot_entity::ActiveModel { id: Set(s.id), ..Default::default() }; + active.matches_build_id = Set(Some(id)); + active.update(db).await?; + marked += 1; + } + } + Ok(marked) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compares_pixels_inside_a_region_only() { + let mut a = RgbaImage::from_pixel(8, 8, image::Rgba([255, 255, 255, 255])); + let b = a.clone(); + a.put_pixel(6, 6, image::Rgba([0, 0, 0, 255])); + let inside = Region { x: 0, y: 0, width: 4, height: 4 }; + let around = Region { x: 4, y: 4, width: 4, height: 4 }; + assert!(same_in(&a, &b, &inside)); + assert!(!same_in(&a, &b, &around)); + // A pixel only one image has (a taller page) is a difference. + let tall = RgbaImage::from_pixel(8, 12, image::Rgba([255, 255, 255, 255])); + assert!(!same_in(&b, &tall, &Region { x: 0, y: 6, width: 8, height: 6 })); + } +} + +/// Where a matching change was approved: the pull request's build, for "matches PR #8's approved change". +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +pub struct Matches { + pub build: i32, + pub branch: String, + pub pr_number: Option, + /// "matches PR #8's approved change" (or "the change approved on sc-8740" with no pull request). + pub label: String, +} + +/// The build's matching changes, by snapshot id. +/// +/// # Errors +/// On a database error. +pub async fn of_build(db: &impl ConnectionTrait, build_id: i64) -> Result> { + let rows = db + .query_all_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "SELECT s.id, b.number, b.branch, b.pr_number FROM snapshots s JOIN builds b ON b.id = s.matches_build_id \ + WHERE s.build_id = $1 AND s.state = 'changed'", + [build_id.into()], + )) + .await?; + let mut out = HashMap::new(); + for r in rows { + let pr_number: Option = r.try_get("", "pr_number")?; + let branch: String = r.try_get("", "branch")?; + let label = match pr_number { + Some(n) => format!("matches PR #{n}'s approved change"), + None => format!("matches the change approved on {branch}"), + }; + out.insert(r.try_get("", "id")?, Matches { build: r.try_get("", "number")?, branch, pr_number, label }); + } + Ok(out) +} diff --git a/server/src/models/mod.rs b/server/src/models/mod.rs index 80c53327..059c1724 100644 --- a/server/src/models/mod.rs +++ b/server/src/models/mod.rs @@ -15,6 +15,7 @@ pub mod heard_about; pub mod identities; pub mod ignored_changes; pub mod invitations; +pub mod matching; pub mod memberships; pub mod organizations; pub mod project_tokens; diff --git a/server/src/models/snapshots.rs b/server/src/models/snapshots.rs index e22857fe..c6c62e35 100644 --- a/server/src/models/snapshots.rs +++ b/server/src/models/snapshots.rs @@ -516,17 +516,24 @@ impl Model { /// # Errors /// When `only` is something else, when the build has no such snapshots, or on a database error. pub async fn picked_by(db: &DatabaseConnection, build_id: i64, only: &str) -> ModelResult> { - if !matches!(only, "added" | "changed") { - return Err(ModelError::Message(format!("only must be added or changed, not {only:?}"))); + if !matches!(only, "added" | "changed" | "matching") { + return Err(ModelError::Message(format!("only must be added, changed or matching, not {only:?}"))); } let ids: Vec = Self::for_build(db, build_id) .await? .into_iter() - .filter(|s| s.state == only && !s.is_config_item()) + .filter(|s| !s.is_config_item()) + .filter(|s| { + if only == "matching" { s.state == "changed" && s.matches_build_id.is_some() } else { s.state == only } + }) .map(|s| s.id) .collect(); if ids.is_empty() { - return Err(ModelError::Message(format!("this build has no {only} snapshots"))); + return Err(ModelError::Message(if only == "matching" { + "this build has no changes that match another pull request's approved change".to_string() + } else { + format!("this build has no {only} snapshots") + })); } Ok(ids) } diff --git a/server/tests/requests/comments.rs b/server/tests/requests/comments.rs index e3b66547..ce98d53d 100644 --- a/server/tests/requests/comments.rs +++ b/server/tests/requests/comments.rs @@ -437,7 +437,7 @@ async fn a_review_can_take_only_the_added_or_only_the_changed_snapshots() { let changed = snapshots::Model::picked_by(w.db, b.id, "changed").await.unwrap(); assert_eq!(name_of(changed).await, vec!["x"]); let e = snapshots::Model::picked_by(w.db, b.id, "removed").await.unwrap_err(); - assert!(e.to_string().contains("added or changed"), "{e}"); + assert!(e.to_string().contains("added, changed or matching"), "{e}"); b.clone().review(w.db, None, &builds::Via::default(), "approve", Some(added), None).await.unwrap(); let review_of = |name: &'static str| async move { @@ -492,6 +492,63 @@ async fn a_review_says_who_made_it_and_keeps_its_note() { .await; } +/// A white page with coloured boxes painted on it: (x, y, width, height, colour). +fn page_with(boxes: &[(u32, u32, u32, u32, [u8; 3])]) -> Vec { + let mut img = image::RgbImage::from_pixel(256, 128, image::Rgb([255, 255, 255])); + for &(x, y, w, h, c) in boxes { + for yy in y..y + h { + for xx in x..x + w { + img.put_pixel(xx, yy, image::Rgb(c)); + } + } + } + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() +} + +/// Two pull requests change different parts of one screen and merge separately. After both, the screen is one +/// neither showed, so main's next build shows a change; but that change is exactly PR 1's approved one, and it says +/// so ("matches PR #1's approved change"), and `only: "matching"` approves it (sc-8785). +#[tokio::test] +#[serial] +async fn a_change_made_of_another_prs_approved_change_says_so() { + request::(|_request, ctx| async move { + let Some(w) = world(&ctx).await else { return }; + let left = (16, 16, 32, 32, RED); + let right = (192, 64, 32, 32, BLUE); + let a = w.build("A", "main", None, &[], &[("x", page_with(&[]))]).await; + a.review(w.db, None, &builds::Via::default(), "approve", None, None).await.unwrap(); + // PR 1 paints the left box, PR 2 the right one; each is approved and merged. + let p1 = w.build("P1", "one", Some(1), &["A"], &[("x", page_with(&[left]))]).await; + p1.clone().review(w.db, None, &builds::Via::default(), "approve", None, None).await.unwrap(); + let p2 = w.build("P2", "two", Some(2), &["A"], &[("x", page_with(&[right]))]).await; + p2.review(w.db, None, &builds::Via::default(), "approve", None, None).await.unwrap(); + visualci_server::models::baselines::record_merge(w.db, w.project.id, "one", "main", "M1").await.unwrap(); + visualci_server::models::baselines::record_merge(w.db, w.project.id, "two", "main", "M2").await.unwrap(); + + // Main after both merges (M2 is the nearer merge): compared with PR 2's approval, it shows PR 1's box. + let m = w.build("M3", "main", None, &["M2", "M1", "A"], &[("x", page_with(&[left, right]))]).await; + let x = snapshots::Model::for_build(w.db, m.id).await.unwrap().into_iter().find(|s| s.name == "x").unwrap(); + assert_eq!(x.state, "changed"); + assert_eq!(x.matches_build_id, Some(p1.id), "the change is PR 1's approved one"); + let labels = visualci_server::models::matching::of_build(w.db, m.id).await.unwrap(); + assert_eq!(labels[&x.id].label, "matches PR #1's approved change"); + let picked = snapshots::Model::picked_by(w.db, m.id, "matching").await.unwrap(); + assert_eq!(picked, vec![x.id]); + + // A change that's only partly someone else's doesn't match. + let other = (100, 40, 32, 32, GREEN); + let n = w.build("M4", "main", None, &["M2", "M1", "A"], &[("x", page_with(&[left, right, other]))]).await; + let x = snapshots::Model::for_build(w.db, n.id).await.unwrap().into_iter().find(|s| s.name == "x").unwrap(); + assert_eq!(x.state, "changed"); + assert_eq!(x.matches_build_id, None); + let e = snapshots::Model::picked_by(w.db, n.id, "matching").await.unwrap_err(); + assert!(e.to_string().contains("no changes that match"), "{e}"); + }) + .await; +} + fn png_color(v: u8) -> [u8; 3] { [v, v, v] } diff --git a/skills/visualci-review/SKILL.md b/skills/visualci-review/SKILL.md index 208a62d0..52fa9fa8 100644 --- a/skills/visualci-review/SKILL.md +++ b/skills/visualci-review/SKILL.md @@ -124,7 +124,7 @@ failing in the repository instead of sending them. **Reviews** -- `review`: approve or reject a build's changes, some snapshots' changes (`snapshots`), or only its new or only its changed snapshots (`only: "added"` or `"changed"`). Add a `note` saying why ("The new header, as the issue asked"): it's kept with the review and shown in the build's reviews, `get_build` and the pull request comment. Every review says who made it and how: "Claude Code for Ada Lovelace" for an agent signed in as its person, "Ada Lovelace" in the web app, or "a project token (CI)", so an agent's approval never reads as the person's own. +- `review`: approve or reject a build's changes, some snapshots' changes (`snapshots`), or only its new or only its changed snapshots (`only: "added"` or `"changed"`). Add a `note` saying why ("The new header, as the issue asked"): it's kept with the review and shown in the build's reviews, `get_build` and the pull request comment. Every review says who made it and how: "Claude Code for Ada Lovelace" for an agent signed in as its person, "Ada Lovelace" in the web app, or "a project token (CI)", so an agent's approval never reads as the person's own. When two pull requests change the same screen and merge separately, the screen after both is one neither showed, so it shows as changed until someone reviews it. If the change is exactly another pull request's approved change (the same regions, from the same old pixels to the same new ones), `get_build` marks it `matches` ("matches PR #8's approved change"), and `only: "matching"` approves those in one call. - `review_page`: accept one page as a variant, or ignore one exact change in later builds too. **Running a comparison**