From 5a68983fb504bbf7cd3a185cd6a5e4bde41c9d64 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:19:10 +1300 Subject: [PATCH 1/7] WIP: snapshot detail, change sizes, review order, flaky --- app/Cargo.toml | 1 + app/src/domain/detail.rs | 436 +++++++++++++++++++++++++++++++++++++++ app/src/domain/mod.rs | 1 + 3 files changed, 438 insertions(+) create mode 100644 app/src/domain/detail.rs diff --git a/app/Cargo.toml b/app/Cargo.toml index ed319bfd..2e19d5ab 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -38,6 +38,7 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg", reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } rusty-s3 = "0.12" globset = "0.4" +schemars = "1" tracing = "0.1" # VisualCI's own crates, shared with the CLI. visualci-core = { path = "../crates/visualci-core" } diff --git a/app/src/domain/detail.rs b/app/src/domain/detail.rs new file mode 100644 index 00000000..01495cae --- /dev/null +++ b/app/src/domain/detail.rs @@ -0,0 +1,436 @@ +//! What a reviewer sees of a snapshot (the web app and the MCP server): its pages with image URLs and text diffs, the +//! lines that moved to another page, a text snapshot's format and JSON changes, the comparison with an earlier build, +//! and the review order of a build's snapshots. + +use std::collections::HashMap; + +use laravel::db; +use visualci_core::align::{PageOp, align_pages}; +use visualci_core::snapshot_text::{self, Format}; + +use super::pages::{self, Page}; +use super::snapshots::text_format; +use crate::models::{Blob, Build, Diff, Snapshot}; +use crate::storage::BlobStore; + +/// One page of a snapshot's comparison, for reviewers. +#[derive(Clone, Debug, serde::Serialize)] +pub struct PageDetail { + pub position: i32, + pub op: String, + pub state: String, + pub head_index: Option, + pub base_index: Option, + pub head_image: Option, + pub base_image: Option, + pub overlay_image: Option, + pub head_url: Option, + pub base_url: Option, + pub overlay_url: Option, + /// Retention deleted this page's images: the URLs are empty and the diff numbers remain. + pub expired: bool, + /// Each side's image size, `[width, height]`, when known: they differ when the page or screenshot was resized, and + /// the diff then covers the larger canvas, both images aligned top-left. + pub base_size: Option<[i32; 2]>, + pub head_size: Option<[i32; 2]>, + pub diff: Option, + pub text_diff: Vec, +} + +/// What a reviewer sees of a text snapshot beyond its line diff. +#[derive(Clone, Debug, serde::Serialize)] +pub struct TextDetail { + /// `text`, `json` or `html`: how it was normalized and compared. + pub format: String, + pub base_lines: usize, + pub head_lines: usize, + /// JSON: the changes by path (`items[3].price: 10 → 12`), at most [`JSON_CHANGE_LIMIT`]. + pub json_changes: Vec, + pub json_changes_truncated: bool, + /// Why it was compared differently from its format (JSON that didn't parse). + pub note: Option, + /// The unified diff (`@@` hunks), for agents. Left out of the web app's JSON, which has the lines. + #[serde(skip)] + pub unified: String, + /// Each side's whole normalized text: `None` for a side the snapshot doesn't have. + pub base: Option, + pub head: Option, +} + +pub const JSON_CHANGE_LIMIT: usize = 200; + +/// Everything a reviewer sees of a snapshot. +pub struct ReviewDetail { + pub pages: Vec, + pub moved: Vec, + pub text: Option, +} + +/// Unchanged lines shown around each change, unless the reviewer asks for the whole text. +pub const DEFAULT_CONTEXT: usize = 3; + +/// Every page of the comparison with presigned image URLs, text diffs (with `context` unchanged lines around each +/// change), the lines that moved to another page, and for text snapshots their format and JSON changes by path. +/// +/// # Errors +/// On a database error. +pub async fn review_detail(snapshot: &Snapshot, store: &BlobStore, context: usize) -> laravel::Result { + let rows = pages::of(store, snapshot).await?; + detail_of(snapshot, store, context, &rows).await +} + +/// This snapshot in an earlier build of the same project and branch: build `number`, or the newest earlier one where +/// it wasn't failed, removed or pending. Read through `effective_snapshots`, so a build that holds it as a sourced +/// group counts. +/// +/// # Errors +/// On a database error. +pub async fn earlier(snapshot: &Snapshot, build: &Build, number: Option) -> laravel::Result> { + let (project_id, branch, before) = (build.project_id, build.branch.as_str(), build.number); + let (name, platform) = (snapshot.name.as_str(), snapshot.platform.as_str()); + let found: Option = db::query!( + "SELECT s.* FROM effective_snapshots s JOIN builds b ON b.id = s.build_id \ + WHERE b.project_id = {project_id} AND b.branch = {branch} AND b.number < {before} \ + AND ({number}::INT IS NULL OR b.number = {number}) \ + AND s.name = {name} AND s.platform = {platform} AND s.state NOT IN ('failed', 'removed', 'pending') \ + ORDER BY b.number DESC LIMIT 1" + ) + .select_one_as() + .await?; + let Some(found) = found else { return Ok(None) }; + let Some(earlier_build) = Build::find(found.build_id).await? else { return Ok(None) }; + Ok(Some((earlier_build, found))) +} + +/// The comparison of this snapshot's new side with an earlier build's new side (the previous build of the branch, +/// say): "did the fix answer the comment?". A view only: it changes no state, review or credits. Diffs are computed on +/// first use and cached like any other. +/// +/// # Errors +/// When an image is missing or can't be diffed. +pub async fn review_detail_against( + snapshot: &Snapshot, + store: &BlobStore, + earlier: &Snapshot, + options: visualci_core::diff::DiffOptions, + context: usize, +) -> laravel::Result { + let heads = async |s: &Snapshot| -> laravel::Result> { + let mut rows: Vec = pages::of(store, s).await?.into_iter().filter(|r| r.head_index.is_some()).collect(); + rows.sort_by_key(|r| r.head_index); + Ok(rows) + }; + let (old, new) = (heads(earlier).await?, heads(snapshot).await?); + let key = |r: &Page| r.head_image.clone().or_else(|| r.head_text.clone()).unwrap_or_default(); + let text = |rows: &[Page]| -> Vec { rows.iter().map(|r| r.head_text.clone().unwrap_or_default()).collect() }; + let (old_text, new_text) = (text(&old), text(&new)); + let has_text = old_text.iter().chain(&new_text).any(|t| !t.is_empty()); + let ops = align_pages( + &old.iter().map(key).collect::>(), + &new.iter().map(key).collect::>(), + has_text.then_some(old_text.as_slice()), + has_text.then_some(new_text.as_slice()), + ); + let row = |position: usize, op: &str, state: &str, b: Option<&Page>, h: Option<&Page>, diff_id: Option| Page { + position: i32::try_from(position).unwrap_or(i32::MAX), + op: op.into(), + state: state.into(), + head_index: h.and_then(|h| h.head_index), + base_index: b.and_then(|b| b.head_index), + head_image: h.and_then(|h| h.head_image.clone()), + base_image: b.and_then(|b| b.head_image.clone()), + head_text: h.and_then(|h| h.head_text.clone()), + base_text: b.and_then(|b| b.head_text.clone()), + diff_id, + }; + let mut rows = Vec::new(); + for (position, op) in ops.iter().enumerate() { + rows.push(match *op { + PageOp::Unchanged { base: b, head: h } => row(position, "unchanged", "unchanged", Some(&old[b]), Some(&new[h]), None), + PageOp::Inserted { head: h } => row(position, "inserted", "changed", None, Some(&new[h]), None), + PageOp::Removed { base: b } => row(position, "removed", "changed", Some(&old[b]), None, None), + PageOp::Changed { base: b, head: h } => { + 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" }; + row(position, "changed", state, Some(bp), Some(hp), Some(diff.id)) + } + _ => { + let state = if bp.head_text == hp.head_text { "unchanged" } else { "changed" }; + row(position, "changed", state, Some(bp), Some(hp), None) + } + } + } + }); + } + detail_of(snapshot, store, context, &rows).await +} + +async fn detail_of(snapshot: &Snapshot, store: &BlobStore, context: usize, rows: &[Page]) -> laravel::Result { + let mut pages = Vec::new(); + let (mut base_texts, mut head_texts) = (Vec::new(), Vec::new()); + // The images that still exist (retention deletes some), with their sizes where known. + let named: Vec = rows.iter().flat_map(|r| [r.head_image.clone(), r.base_image.clone()]).flatten().collect(); + let mut stored: HashMap> = HashMap::new(); + for chunk in named.chunks(10_000) { + for b in Blob::query().filter(Blob::sha256.is_in(chunk.to_vec())).get().await? { + stored.insert(b.sha256, b.width.zip(b.height).map(|(w, h)| [w, h])); + } + } + let size = |sha: &Option| sha.as_ref().and_then(|s| stored.get(s).copied().flatten()); + for row in rows { + if let (Some(i), Some(t)) = (row.base_index, &row.base_text) { + base_texts.push((i, t.clone())); + } + if let (Some(i), Some(t)) = (row.head_index, &row.head_text) { + head_texts.push((i, t.clone())); + } + let diff = match row.diff_id { + Some(id) => Diff::find(id).await?, + None => None, + }; + let text_diff = if row.state == "unchanged" { + Vec::new() + } else { + visualci_core::text::page_diff(row.base_text.as_deref().unwrap_or(""), row.head_text.as_deref().unwrap_or(""), context) + }; + let expired = [&row.head_image, &row.base_image].into_iter().flatten().any(|s| !stored.contains_key(s)); + let overlay = diff.as_ref().and_then(|d| d.overlay_blob.clone()).filter(|_| !expired); + let url = |s: &Option| s.as_ref().filter(|_| !expired).and_then(|s| store.download_url(s).ok()); + pages.push(PageDetail { + position: row.position, + op: row.op.clone(), + state: row.state.clone(), + head_index: row.head_index, + base_index: row.base_index, + head_url: url(&row.head_image), + base_url: url(&row.base_image), + overlay_url: overlay.as_ref().and_then(|s| store.download_url(s).ok()), + expired, + base_size: size(&row.base_image), + head_size: size(&row.head_image), + head_image: row.head_image.clone(), + base_image: row.base_image.clone(), + overlay_image: overlay, + diff: diff.as_ref().and_then(super::diffs::result), + text_diff, + }); + } + let ordered = |mut v: Vec<(i32, String)>| { + v.sort_by_key(|(i, _)| *i); + v.into_iter().map(|(_, t)| t).collect::>() + }; + let text = text_format(snapshot).map(|format| { + let row = rows.first(); + let base = row.and_then(|r| r.base_text.as_deref()).unwrap_or(""); + let head = row.and_then(|r| r.head_text.as_deref()).unwrap_or(""); + let mut detail = text_detail(format, base, head, row.is_some_and(|r| r.base_text.is_some())); + detail.base = row.and_then(|r| r.base_text.clone()); + detail.head = row.and_then(|r| r.head_text.clone()).filter(|_| snapshot.state != "removed"); + detail + }); + let moved = + if text.is_some() { Vec::new() } else { visualci_core::text::moved_lines(&ordered(base_texts), &ordered(head_texts)) }; + Ok(ReviewDetail { pages, moved, text }) +} + +/// The format a text was compared in, its JSON changes by path, and its unified diff. The stored texts are already +/// normalized, so JSON that doesn't parse here was compared as plain text. +#[must_use] +pub fn text_detail(format: Format, base: &str, head: &str, has_base: bool) -> TextDetail { + let parse = |t: &str| serde_json::from_str::(t); + let (format, json_changes, truncated, note) = match format { + Format::Json => match (parse(head), has_base.then(|| parse(base))) { + (Ok(h), Some(Ok(b))) => { + let (changes, more) = snapshot_text::json_changes(&b, &h, JSON_CHANGE_LIMIT); + (Format::Json, changes, more, None) + } + (Ok(_), None) => (Format::Json, Vec::new(), false, None), + (Ok(_), Some(Err(_))) => { + (Format::Json, Vec::new(), false, Some("the base wasn't valid JSON, so there are no changes by path".into())) + } + (Err(e), _) => (Format::Text, Vec::new(), false, Some(format!("not valid JSON ({e}), compared as plain text"))), + }, + other => (other, Vec::new(), false, None), + }; + TextDetail { + format: format.as_str().to_string(), + base_lines: base.lines().count(), + head_lines: head.lines().count(), + json_changes, + json_changes_truncated: truncated, + note, + unified: snapshot_text::unified(base, head, DEFAULT_CONTEXT), + base: None, + head: None, + } +} + +/// How big a snapshot's change is, for putting the biggest in front of a reviewer first: the largest share of a page +/// that changed (an inserted or removed page counts whole; for text, the share of lines added or removed) and, to break +/// ties, how many pixels (or lines) changed. +#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize)] +pub struct ChangeSize { + pub fraction: f64, + pub amount: i64, +} + +/// The order snapshots are listed in for review. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum ReviewOrder { + /// Changed snapshots, the largest change first; then added, removed, failed and the rest. The default. + #[default] + Change, + /// By name. + Name, +} + +/// Each changed snapshot's [`ChangeSize`] in a build, by snapshot id. Changes are always the build's own rows. +/// +/// # Errors +/// On a database error. +pub async fn change_sizes(build_id: i64) -> laravel::Result> { + let mut sizes = HashMap::new(); + let pixels = db::query!( + "SELECT p.snapshot_id, \ + MAX(CASE WHEN p.op IN ('inserted', 'removed') THEN 1.0 ELSE COALESCE(d.changed_fraction, 0) END)::FLOAT8 \ + AS fraction, \ + COALESCE(SUM(d.changed_pixels), 0)::BIGINT AS amount \ + FROM snapshot_pages p JOIN snapshots s ON s.id = p.snapshot_id LEFT JOIN diffs d ON d.id = p.diff_id \ + WHERE s.build_id = {build_id} AND s.kind <> 'text' AND p.state = 'changed' GROUP BY p.snapshot_id" + ) + .select() + .await?; + for r in pixels { + sizes.insert(r.try_get::("snapshot_id")?, ChangeSize { fraction: r.try_get("fraction")?, amount: r.try_get("amount")? }); + } + let texts = db::query!( + "SELECT p.snapshot_id, bt.body AS base_text, ht.body AS head_text FROM snapshot_pages p \ + JOIN snapshots s ON s.id = p.snapshot_id \ + LEFT JOIN texts bt ON bt.sha256 = p.base_text_sha LEFT JOIN texts ht ON ht.sha256 = p.head_text_sha \ + WHERE s.build_id = {build_id} AND s.kind = 'text' AND p.state = 'changed'" + ) + .select() + .await?; + for r in texts { + let base: String = r.try_get::>("base_text")?.unwrap_or_default(); + let head: String = r.try_get::>("head_text")?.unwrap_or_default(); + let changed = visualci_core::text::page_diff(&base, &head, 0).iter().filter(|l| l.tag != " ").count(); + let lines = base.lines().count().max(head.lines().count()).max(1); + let size = ChangeSize { + #[allow(clippy::cast_precision_loss)] + fraction: (changed as f64 / lines as f64).min(1.0), + amount: i64::try_from(changed).unwrap_or(i64::MAX), + }; + let entry = sizes.entry(r.try_get::("snapshot_id")?).or_default(); + if size.fraction > entry.fraction { + *entry = size; + } + } + Ok(sizes) +} + +/// The review order of a state: what needs a decision first. +fn state_rank(state: &str) -> u8 { + match state { + "changed" => 0, + "added" => 1, + "removed" => 2, + "failed" => 3, + "pending" => 4, + "ignored" => 5, + _ => 6, + } +} + +/// Sort a build's snapshots for review. Ties go by name and platform, so the order is the same every time. +pub fn sort_for_review(list: &mut [Snapshot], sizes: &HashMap, order: ReviewOrder) { + let by_name = |a: &Snapshot, b: &Snapshot| a.name.cmp(&b.name).then_with(|| a.platform.cmp(&b.platform)); + match order { + ReviewOrder::Name => list.sort_by(by_name), + ReviewOrder::Change => list.sort_by(|a, b| { + let (sa, sb) = (sizes.get(&a.id).copied().unwrap_or_default(), sizes.get(&b.id).copied().unwrap_or_default()); + state_rank(&a.state) + .cmp(&state_rank(&b.state)) + .then_with(|| sb.fraction.total_cmp(&sa.fraction)) + .then_with(|| sb.amount.cmp(&sa.amount)) + .then_with(|| by_name(a, b)) + }), + } +} + +/// How many of a branch's newest builds the flaky hint looks at. +pub const FLAKY_WINDOW: i64 = 8; + +/// Whether a run of versions, oldest first, changed at least three times and came back to an earlier version. +#[must_use] +pub fn flips(versions: &[String]) -> bool { + let changes = versions.windows(2).filter(|w| w[0] != w[1]).count(); + let returned = versions.iter().enumerate().skip(1).any(|(i, v)| versions[i - 1] != *v && versions[..i - 1].contains(v)); + changes >= 3 && returned +} + +/// The snapshots of this build that look flaky, by name and platform: over the newest builds of its suite on its +/// branch, up to this one ([`FLAKY_WINDOW`]), the content changed at least three times and came back to a version it +/// had before (A, B, A, B). Only a hint for whoever reviews. +/// +/// # Errors +/// On a database error. +pub async fn flaky_in(build: &Build) -> laravel::Result> { + let (project_id, name, branch, id) = (build.project_id, build.name.as_str(), build.branch.as_str(), build.id); + let recent: Vec = db::query!( + "SELECT id FROM builds WHERE project_id = {project_id} AND name = {name} AND branch = {branch} AND id <= {id} \ + ORDER BY id DESC LIMIT {FLAKY_WINDOW}" + ) + .select() + .await? + .iter() + .filter_map(|r| r.try_get("id").ok()) + .collect(); + // Three changes need at least four builds. + if recent.len() < 4 { + return Ok(std::collections::HashSet::new()); + } + let rows = db::query!( + "SELECT build_id, name, platform, source_fingerprint FROM effective_snapshots \ + WHERE build_id IN ({...recent}) AND source_fingerprint <> '' ORDER BY build_id" + ) + .select() + .await?; + let mut history: HashMap<(String, String), Vec> = HashMap::new(); + for r in rows { + history.entry((r.try_get("name")?, r.try_get("platform")?)).or_default().push(r.try_get("source_fingerprint")?); + } + Ok(history.into_iter().filter(|(_, versions)| flips(versions)).map(|(key, _)| key).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn flipping_back_and_forth_is_flaky() { + let run = |s: &str| s.chars().map(String::from).collect::>(); + assert!(flips(&run("ABAB"))); + assert!(flips(&run("AABBAAB"))); + assert!(flips(&run("ABCA"))); + assert!(!flips(&run("AAAA"))); + assert!(!flips(&run("ABCD"))); + assert!(!flips(&run("ABA"))); + assert!(!flips(&run("AABBA"))); + } + + #[test] + fn json_detail_lists_changes_by_path() { + let d = text_detail(Format::Json, "{\"price\": 10, \"x\": 1}", "{\"price\": 12, \"x\": 1}", true); + assert_eq!(d.format, "json"); + assert_eq!(d.json_changes.iter().map(snapshot_text::PathChange::line).collect::>(), vec!["price: 10 → 12"]); + assert!(d.unified.contains("@@")); + let bad = text_detail(Format::Json, "", "{oops", false); + assert_eq!(bad.format, "text"); + assert!(bad.note.unwrap().contains("not valid JSON")); + } +} diff --git a/app/src/domain/mod.rs b/app/src/domain/mod.rs index bd6d2660..a694de84 100644 --- a/app/src/domain/mod.rs +++ b/app/src/domain/mod.rs @@ -17,3 +17,4 @@ pub mod processing; pub mod projects; pub mod renders; pub mod snapshots; +pub mod detail; From e9c7a5948043f7dc9df7ef196ff3d9264f5edb56 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:21:24 +1300 Subject: [PATCH 2/7] WIP: comments, reviews --- app/src/domain/comments.rs | 366 +++++++++++++++++++++++++++++++++++++ app/src/domain/mod.rs | 2 + app/src/domain/reviews.rs | 237 ++++++++++++++++++++++++ 3 files changed, 605 insertions(+) create mode 100644 app/src/domain/comments.rs create mode 100644 app/src/domain/reviews.rs diff --git a/app/src/domain/comments.rs b/app/src/domain/comments.rs new file mode 100644 index 00000000..cea0b099 --- /dev/null +++ b/app/src/domain/comments.rs @@ -0,0 +1,366 @@ +//! Comment threads pinned to pixels. A thread is on one snapshot (name and platform) of a project's branch, so it +//! follows the branch: it shows on every newer build of that snapshot there. It's pinned to a point, a box or the whole +//! image, on a page's base or head side (coordinates in that image's pixels). An open thread blocks approving its +//! snapshot ([`open_on`]), so a person's question stops an agent's approval until someone answers and resolves it. + +use std::collections::HashMap; + +use laravel::db; +use laravel::model::{create, update}; +use laravel::str::Uuid; +use serde::Deserialize; + +use crate::models::{Build, Comment, CommentThread, Snapshot, User}; + +/// Where a thread is pinned, in pixels of the pinned side's own image (base or head), from its top left. +#[derive(Debug, Clone, PartialEq, Deserialize, schemars::JsonSchema)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum Anchor { + /// The whole image. + Image, + /// A point. + Point { x: f64, y: f64 }, + /// A box: its top left corner, width and height. + Box { x: f64, y: f64, w: f64, h: f64 }, +} + +impl Anchor { + /// # Errors + /// A message when it isn't inside the image (`size` is the image's width and height, when known). + pub fn validate(&self, size: Option<(f64, f64)>) -> Result<(), String> { + let (w_max, h_max) = size.unwrap_or((f64::MAX, f64::MAX)); + let within = |x: f64, y: f64| x >= 0.0 && y >= 0.0 && x <= w_max && y <= h_max; + let ok = match self { + Self::Image => true, + Self::Point { x, y } => within(*x, *y), + Self::Box { x, y, w, h } => *w > 0.0 && *h > 0.0 && within(*x, *y) && within(x + w, y + h), + }; + if ok { + return Ok(()); + } + Err(match size { + Some((w, h)) => format!("the anchor is outside the image: it's {w}×{h} pixels, from the top left"), + None => "anchor coordinates are pixels from the image's top left, so they can't be negative".into(), + }) + } + + fn json(&self) -> serde_json::Value { + match self { + Self::Image => serde_json::json!({ "kind": "image" }), + Self::Point { x, y } => serde_json::json!({ "kind": "point", "x": x, "y": y }), + Self::Box { x, y, w, h } => serde_json::json!({ "kind": "box", "x": x, "y": y, "w": w, "h": h }), + } + } +} + +/// The pixel size of one side of a snapshot's page, when it has an image there. +async fn image_size(snapshot: &Snapshot, page: i32, side: &str) -> laravel::Result> { + let pages = super::pages::of_many(None, &[snapshot]).await?; + let row = pages.get(&snapshot.id).and_then(|p| p.iter().find(|r| r.position == page)).cloned(); + let sha = row.and_then(|r| if side == "base" { r.base_image } else { r.head_image }); + let Some(sha) = sha else { return Ok(None) }; + let blob = crate::models::Blob::find(sha).await?; + Ok(blob.and_then(|b| Some((f64::from(b.width?), f64::from(b.height?))))) +} + +/// Who wrote a comment: a person in the web app, or an agent (MCP or the API) acting for one or for a project token. +#[derive(Debug, Clone)] +pub struct Author { + pub user_id: Option, + pub agent: Option, +} + +impl Author { + const fn kind(&self) -> &'static str { + if self.agent.is_some() { "agent" } else { "person" } + } +} + +/// Where a new thread goes. +#[derive(Debug, Clone)] +pub struct Place { + pub page: Option, + pub side: String, + pub anchor: Anchor, +} + +const MAX_BODY: usize = 10_000; + +fn clean_body(body: &str) -> Result { + let body = body.trim(); + if body.is_empty() || body.len() > MAX_BODY { + return Err(format!("a comment is 1 to {MAX_BODY} characters of Markdown")); + } + Ok(body.to_string()) +} + +async fn add_comment(thread_id: i64, author: &Author, body: String) -> laravel::Result { + create!(Comment { + pid: laravel::str::uuid7(), + thread_id: thread_id, + user_id: author.user_id, + author_kind: author.kind(), + agent: author.agent.clone(), + body: body, + }) + .await +} + +/// Start a thread on a build's snapshot. +/// +/// # Errors +/// `Ok(Err(message))` for a bad anchor, side or body; `Err` on a database error. +pub async fn start( + build: &Build, + snapshot: &Snapshot, + place: &Place, + author: &Author, + body: &str, +) -> laravel::Result> { + if !matches!(place.side.as_str(), "base" | "head") { + return Ok(Err("side is base or head".into())); + } + // A pin is on one page: a single image's, unless the caller names another. + let page = match (&place.anchor, place.page) { + (Anchor::Image, p) => p, + (_, Some(p)) => Some(p), + (_, None) => Some(0), + }; + let size = match page { + Some(p) => image_size(snapshot, p, &place.side).await?, + None => None, + }; + if let Err(m) = place.anchor.validate(size) { + return Ok(Err(m)); + } + let body = match clean_body(body) { + Ok(b) => b, + Err(m) => return Ok(Err(m)), + }; + let thread = db::transaction(async |_| { + let thread = create!(CommentThread { + pid: laravel::str::uuid7(), + project_id: build.project_id, + branch: build.branch.as_str(), + snapshot_name: snapshot.name.as_str(), + platform: snapshot.platform.as_str(), + page: page, + side: place.side.as_str(), + anchor: place.anchor.json(), + build_id: Some(build.id), + resolved_at: None, + resolved_by: None, + }) + .await?; + add_comment(thread.id, author, body.clone()).await?; + Ok(thread) + }) + .await?; + Ok(Ok(thread)) +} + +/// The thread with this id in a project. +/// +/// # Errors +/// On a database error. +pub async fn thread(project_id: i64, pid: Uuid) -> laravel::Result> { + CommentThread::query().filter(CommentThread::pid.eq(pid) & CommentThread::project_id.eq(project_id)).first().await +} + +/// Reply in a thread (and reopen it, if it was resolved: a new question needs an answer). +/// +/// # Errors +/// `Ok(Err(message))` for a bad body; `Err` on a database error. +pub async fn reply(mut thread: CommentThread, author: &Author, body: &str) -> laravel::Result> { + let body = match clean_body(body) { + Ok(b) => b, + Err(m) => return Ok(Err(m)), + }; + let comment = add_comment(thread.id, author, body).await?; + update!(thread { resolved_at: None, resolved_by: None }).await?; + Ok(Ok(comment)) +} + +/// A comment in a project, with its thread. +/// +/// # Errors +/// On a database error. +pub async fn comment(project_id: i64, pid: Uuid) -> laravel::Result> { + let Some(c) = Comment::query().filter(Comment::pid.eq(pid)).first().await? else { return Ok(None) }; + let t = CommentThread::find(c.thread_id).await?.filter(|t| t.project_id == project_id); + Ok(t.map(|t| (c, t))) +} + +/// Whether `author` wrote the comment: the same person, or, for an agent's comment made with a project token (no +/// person), the project's tokens. Never a person's comment whose account is gone: that stays theirs, for an admin to +/// delete. +#[must_use] +pub fn wrote(c: &Comment, author: &Author) -> bool { + match c.user_id { + Some(id) => author.user_id == Some(id), + None => author.user_id.is_none() && c.author_kind == "agent", + } +} + +/// Edit a comment (its author only). +/// +/// # Errors +/// `Ok(Err(message))` when it's someone else's or the body is bad; `Err` on a database error. +pub async fn edit(mut c: Comment, author: &Author, body: &str) -> laravel::Result> { + if !wrote(&c, author) { + return Ok(Err("only its author can edit a comment".into())); + } + let body = match clean_body(body) { + Ok(b) => b, + Err(m) => return Ok(Err(m)), + }; + update!(c { body }).await?; + Ok(Ok(c)) +} + +/// Delete a comment (its author, or an admin). A thread left with no comments goes too. Returns whether the thread +/// went. +/// +/// # Errors +/// `Ok(Err(message))` when it's someone else's and the caller isn't an admin; `Err` on a database error. +pub async fn delete(c: Comment, author: &Author, admin: bool) -> laravel::Result> { + if !wrote(&c, author) && !admin { + return Ok(Err("only its author or an admin can delete a comment".into())); + } + let (id, thread_id) = (c.id, c.thread_id); + db::query!("DELETE FROM comments WHERE id = {id}").delete().await?; + let left = Comment::query().filter(Comment::thread_id.eq(thread_id)).count().await?; + if left == 0 { + db::query!("DELETE FROM comment_threads WHERE id = {thread_id}").delete().await?; + return Ok(Ok(true)); + } + Ok(Ok(false)) +} + +/// Resolve a thread, or reopen it. +/// +/// # Errors +/// On a database error. +pub async fn resolve(mut thread: CommentThread, resolved: bool, user_id: Option) -> laravel::Result { + let resolved_at = resolved.then(|| laravel::now().timestamp()); + let resolved_by = if resolved { user_id } else { None }; + update!(thread { resolved_at, resolved_by }).await?; + Ok(thread) +} + +/// The open threads on these snapshots (name, platform) of a project's branch. +/// +/// # Errors +/// On a database error. +pub async fn open_on(project_id: i64, branch: &str, snapshots: &[(String, String)]) -> laravel::Result> { + if snapshots.is_empty() { + return Ok(vec![]); + } + let names: Vec = snapshots.iter().map(|(n, _)| n.clone()).collect(); + let rows: Vec = db::query!( + "SELECT * FROM comment_threads WHERE project_id = {project_id} AND branch = {branch} AND resolved_at IS NULL \ + AND snapshot_name IN ({...names}) ORDER BY id" + ) + .select_as() + .await?; + Ok(rows.into_iter().filter(|t| snapshots.iter().any(|(n, p)| &t.snapshot_name == n && &t.platform == p)).collect()) +} + +/// A thread's first comment's first line, to name it in a refusal. +/// +/// # Errors +/// On a database error. +pub async fn first_line(thread_id: i64) -> laravel::Result { + let c = Comment::query().filter(Comment::thread_id.eq(thread_id)).order_by(Comment::id.asc()).first().await?; + Ok(c.map(|c| c.body.lines().next().unwrap_or_default().chars().take(120).collect()).unwrap_or_default()) +} + +/// Threads (with their comments) for a project's branch, on one snapshot or all of them, open only unless +/// `include_resolved`. +/// +/// # Errors +/// On a database error. +pub async fn list( + project_id: i64, + branch: &str, + snapshot: Option<(&str, &str)>, + include_resolved: bool, +) -> laravel::Result> { + let mut q = CommentThread::query().filter(CommentThread::project_id.eq(project_id) & CommentThread::branch.eq(branch)); + if let Some((name, platform)) = snapshot { + q = q.filter(CommentThread::snapshot_name.eq(name) & CommentThread::platform.eq(platform)); + } + if !include_resolved { + q = q.filter(CommentThread::resolved_at.is_null()); + } + let threads = q.order_by(CommentThread::id.asc()).get().await?; + let ids: Vec = threads.iter().map(|t| t.id).collect(); + let all = if ids.is_empty() { + Vec::new() + } else { + Comment::query().filter(Comment::thread_id.is_in(ids)).order_by(Comment::id.asc()).get().await? + }; + let user_ids: Vec = all.iter().filter_map(|c| c.user_id).collect(); + let people: HashMap = if user_ids.is_empty() { + HashMap::new() + } else { + User::query().filter(User::id.is_in(user_ids)).get().await?.into_iter().map(|u| (u.id, u.name)).collect() + }; + let build_ids: Vec = threads.iter().filter_map(|t| t.build_id).collect(); + let mut build_numbers: HashMap = HashMap::new(); + let mut drawn_on: HashMap<(i64, String, String), Uuid> = HashMap::new(); + if !build_ids.is_empty() { + for b in Build::query().filter(Build::id.is_in(build_ids.clone())).get().await? { + build_numbers.insert(b.id, b.number); + } + // Each thread's snapshot in the build it was drawn on (its own row, or one it reads from an earlier build), so + // the web app can link there. + let names: Vec = threads.iter().map(|t| t.snapshot_name.clone()).collect(); + let rows = db::query!( + "SELECT build_id, name, platform, pid FROM effective_snapshots \ + WHERE build_id IN ({...build_ids}) AND name IN ({...names})" + ) + .select() + .await?; + for r in rows { + drawn_on.insert((r.try_get("build_id")?, r.try_get("name")?, r.try_get("platform")?), r.try_get("pid")?); + } + } + Ok(threads + .iter() + .map(|t| { + let list: Vec = all + .iter() + .filter(|c| c.thread_id == t.id) + .map(|c| { + let person = c.user_id.and_then(|id| people.get(&id)).cloned(); + serde_json::json!({ + "id": c.pid, "author": { "kind": c.author_kind, "name": person, "agent": c.agent }, + "body": c.body, "created_at": c.created_at.to_string(), "updated_at": c.updated_at.to_string(), + }) + }) + .collect(); + serde_json::json!({ + "id": t.pid, "snapshot": t.snapshot_name, "platform": t.platform, "page": t.page, "side": t.side, + "anchor": t.anchor, "started_in_build": t.build_id.and_then(|id| build_numbers.get(&id)), + "started_in_snapshot": t.build_id.and_then(|id| drawn_on.get(&(id, t.snapshot_name.clone(), t.platform.clone()))), + "resolved": t.resolved_at.is_some(), "resolved_at": t.resolved_at.map(|d| d.to_string()), + "comments": list, + }) + }) + .collect()) +} + +/// The project's branches with open threads, and how many each: for `whoami` and `get_build`. +/// +/// # Errors +/// On a database error. +pub async fn open_by_branch(project_id: i64) -> laravel::Result> { + let rows = db::query!( + "SELECT branch, COUNT(*)::BIGINT AS open FROM comment_threads WHERE project_id = {project_id} \ + AND resolved_at IS NULL GROUP BY branch ORDER BY branch" + ) + .select() + .await?; + Ok(rows.iter().filter_map(|r| Some((r.try_get::("branch").ok()?, r.try_get::("open").ok()?))).collect()) +} diff --git a/app/src/domain/mod.rs b/app/src/domain/mod.rs index a694de84..7b105431 100644 --- a/app/src/domain/mod.rs +++ b/app/src/domain/mod.rs @@ -18,3 +18,5 @@ pub mod projects; pub mod renders; pub mod snapshots; pub mod detail; +pub mod comments; +pub mod reviews; diff --git a/app/src/domain/reviews.rs b/app/src/domain/reviews.rs new file mode 100644 index 00000000..9a0b70ea --- /dev/null +++ b/app/src/domain/reviews.rs @@ -0,0 +1,237 @@ +//! Reviews: approving or rejecting a build's changes, who did it, and what follows (baselines, superseded builds). + +use laravel::db::{self, Json}; +use laravel::model::{create, update}; + +use super::snapshots::is_change; +use crate::models::{Build, Review, Snapshot, User}; + +/// How a review was made besides its person, for "Approved by Claude Code for Ada": where it came from (`web`, `oauth`, +/// `personal_token` or `project_token`), the OAuth app, the agent that sent it and the token's name. A review in the web +/// app is `Via::default()`: a person, nothing else. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Via { + pub source: &'static str, + /// The OAuth app's name. + pub client: Option, + /// The agent: an `X-Agent` header, or the MCP client's name and version. + pub agent: Option, + /// The personal or project token's name. + pub token: Option, +} + +impl Default for Via { + fn default() -> Self { + Self { source: "web", client: None, agent: None, token: None } + } +} + +/// Who made a review, as people read it after "Approved by": the person in the web app ("Ada Lovelace"), the agent for +/// its person ("Claude Code for Ada Lovelace"), or a project token ("a project token (GitHub Actions)"). VisualCI is +/// mostly used by agents, so an agent's review never reads as the person's own. +#[must_use] +pub fn by(source: &str, client: Option<&str>, agent: Option<&str>, token: Option<&str>, person: Option<&str>) -> String { + let person = person.unwrap_or("someone"); + let agent_name = client.or(agent).map(str::trim).filter(|a| !a.is_empty()); + match source { + "web" => person.to_string(), + "oauth" => format!("{} for {person}", agent_name.unwrap_or("an agent")), + // A token's name is what its person called it ("Claude Code on the laptop"): it says more than the MCP + // client's library name ("rmcp 3.12.0"), so it comes first. + "personal_token" => format!("{} for {person}", token.or(agent_name).unwrap_or("an agent")), + _ => match token { + Some(t) => format!("a project token ({t})"), + None => "a project token".to_string(), + }, + } +} + +/// One review as it's shown: what, by whom ([`by`]), the reviewer's note, how many snapshots and when. +#[derive(Clone, Debug, serde::Serialize)] +pub struct Shown { + pub action: String, + pub by: String, + pub note: Option, + pub snapshots: usize, + pub created_at: String, +} + +impl Shown { + /// "approved by Claude Code for Ada Lovelace", for a status line. + #[must_use] + pub fn line(&self) -> String { + let done = if self.action == "reject" { "rejected" } else { "approved" }; + format!("{done} by {}", self.by) + } +} + +/// A build's reviews, newest first, at most `limit`. +/// +/// # Errors +/// On a database error. +pub async fn shown(build_id: i64, limit: i64) -> laravel::Result> { + let reviews: Vec = + db::query!("SELECT * FROM reviews WHERE build_id = {build_id} ORDER BY id DESC LIMIT {limit}").select_as().await?; + let user_ids: Vec = reviews.iter().filter_map(|r| r.user_id).collect(); + let people: std::collections::HashMap = if user_ids.is_empty() { + std::collections::HashMap::new() + } else { + User::query().filter(User::id.is_in(user_ids)).get().await?.into_iter().map(|u| (u.id, u.name)).collect() + }; + Ok(reviews + .into_iter() + .map(|r| { + let person = r.user_id.and_then(|id| people.get(&id)).map(String::as_str); + Shown { + by: by(&r.source, r.client_name.as_deref(), r.agent.as_deref(), r.token_name.as_deref(), person), + action: r.action, + note: r.note, + snapshots: r.snapshot_ids.len(), + created_at: r.created_at.to_string(), + } + }) + .collect()) +} + +/// The note on a build approved with uncommitted changes. +pub const DIRTY_APPROVAL: &str = "This build ran with uncommitted changes, so approving it set baselines for its own \ +environment's screenshots only: approved documents and text weren't made baselines. Commit, run again and approve that \ +build."; + +/// Approve or reject the build, or some of its changed snapshots (by id). Approving every change approves the build. +/// Only the build's own rows are ever written: a snapshot it reads from an earlier build is unchanged, so it's never a +/// target. +/// +/// # Errors +/// `Ok(Err(message))` when the build can't be reviewed (not completed, a bad action, an open comment thread on an +/// approval); `Err` on a database error. +pub async fn review( + mut build: Build, + user_id: Option, + via: &Via, + action: &str, + snapshot_ids: Option>, + note: Option<&str>, +) -> laravel::Result> { + if build.state != "completed" { + return Ok(Err("only completed builds can be reviewed".into())); + } + let verdict = match action { + "approve" => "approved", + "reject" => "rejected", + _ => return Ok(Err("action must be approve or reject".into())), + }; + let snapshots = super::snapshots::of_build(build.id).await?; + let targets: Vec<&Snapshot> = snapshots + .iter() + .filter(|s| is_change(s) && !s.sourced) + .filter(|s| snapshot_ids.as_ref().is_none_or(|ids| ids.contains(&s.id))) + .collect(); + // An open comment thread blocks approving its snapshot: someone asked something, and it needs an answer first. + // Rejecting still works. + if verdict == "approved" { + let keys: Vec<(String, String)> = targets.iter().map(|s| (s.name.clone(), s.platform.clone())).collect(); + let open = super::comments::open_on(build.project_id, &build.branch, &keys).await?; + if let Some(t) = open.first() { + let line = super::comments::first_line(t.id).await?; + let more = if open.len() > 1 { format!(" (and {} more open threads)", open.len() - 1) } else { String::new() }; + let on = match t.build_id { + Some(id) if id != build.id => { + format!(" on build #{}", Build::find(id).await?.map(|b| b.number).unwrap_or_default()) + } + _ => String::new(), + }; + return Ok(Err(format!( + "{} has an open comment thread{on} ({}): \"{line}\"{more}. Answer it and resolve it (resolve_comment) \ + before approving, or reject.", + t.snapshot_name, t.pid + ))); + } + } + let ids: Vec = targets.iter().map(|s| s.id).collect(); + if !ids.is_empty() { + db::query!("UPDATE snapshots SET review = {verdict}, updated_at = now() WHERE id IN ({...ids})").update().await?; + } + let note = note.map(str::trim).filter(|n| !n.is_empty()).map(|n| n.chars().take(2000).collect::()); + let review = create!(Review { + build_id: build.id, + user_id: user_id, + action: action, + snapshot_ids: Json(ids.clone()), + client_name: via.client.clone(), + agent: via.agent.clone(), + source: via.source, + token_name: via.token.clone(), + note: note, + }) + .await?; + let mut skipped = 0; + if verdict == "approved" { + // Each approved snapshot is a baseline for this branch (and environment, for screenshots) from now on. + let fresh: Vec<&Snapshot> = targets.iter().filter(|s| s.review.as_deref() != Some("approved")).copied().collect(); + skipped = super::baselines::record(&build, &fresh, user_id, Some(review.id), "review").await?; + } else { + // Rejecting what was approved withdraws the baselines that approval made. + let was_approved: Vec<&Snapshot> = + targets.iter().filter(|s| s.review.as_deref() == Some("approved")).copied().collect(); + super::baselines::withdraw(&build, &was_approved).await?; + } + + let snapshots = super::snapshots::of_build(build.id).await?; + let changes: Vec<&Snapshot> = snapshots.iter().filter(|s| is_change(s)).collect(); + let review_state = if changes.iter().any(|s| s.review.as_deref() == Some("rejected")) { + "rejected" + } else if changes.iter().all(|s| s.review.as_deref() == Some("approved")) { + "approved" + } else { + "pending" + }; + let mut warnings: Vec = serde_json::from_value(build.warnings.clone()).unwrap_or_default(); + if skipped > 0 && !warnings.iter().any(|w| w == DIRTY_APPROVAL) { + warnings.push(DIRTY_APPROVAL.to_string()); + } + let warnings = serde_json::json!(warnings); + let review_state = review_state.to_string(); + update!(build { review_state, warnings }).await?; + Ok(Ok(build)) +} + +/// Once this build is approved or rejected, the older pending builds it covers are superseded: the same project, build +/// name and environment, finished, and on this build's history (their commit is among its ancestors). Returns their ids, +/// for their checks. +/// +/// # Errors +/// On a database error. +pub async fn supersede_older(build: &Build) -> laravel::Result> { + if !matches!(build.review_state.as_str(), "approved" | "rejected") || build.parent_commits.is_empty() { + return Ok(Vec::new()); + } + let (id, project_id, name, environment) = (build.id, build.project_id, build.name.as_str(), build.environment.as_str()); + let parents: Vec = build.parent_commits.to_vec(); + let rows = db::query!( + "UPDATE builds SET review_state = 'superseded', superseded_by_build_id = {id}, updated_at = now() \ + WHERE project_id = {project_id} AND name = {name} AND environment = {environment} AND id < {id} \ + AND state = 'completed' AND review_state = 'pending' AND commit_sha IN ({...parents}) \ + RETURNING id" + ) + .select() + .await?; + Ok(rows.iter().filter_map(|r| r.try_get::("id").ok()).collect()) +} + +#[cfg(test)] +mod tests { + use super::by; + + #[test] + fn says_who_and_through_what() { + assert_eq!(by("web", None, None, None, Some("Ada")), "Ada"); + assert_eq!(by("oauth", Some("Claude Code"), Some("claude-code 2.1"), None, Some("Ada")), "Claude Code for Ada"); + let named = by("personal_token", None, Some("rmcp 3.12.0"), Some("Claude Code on the laptop"), Some("Ada")); + assert_eq!(named, "Claude Code on the laptop for Ada"); + assert_eq!(by("personal_token", None, Some("codex 1.0"), None, Some("Ada")), "codex 1.0 for Ada"); + assert_eq!(by("personal_token", None, None, None, Some("Ada")), "an agent for Ada"); + assert_eq!(by("project_token", None, None, Some("GitHub Actions"), None), "a project token (GitHub Actions)"); + assert_eq!(by("project_token", None, Some("claude-code 2.1"), Some("CI"), None), "a project token (CI)"); + } +} From 7164bfeeceaec9bcf0617a02bf4426697a2645c9 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:23:29 +1300 Subject: [PATCH 3/7] WIP: inherited, summary line, changeset, page actions --- app/src/domain/changeset.rs | 160 ++++++++++++++++++++++++++++++++++++ app/src/domain/inherited.rs | 94 +++++++++++++++++++++ app/src/domain/mod.rs | 3 + app/src/domain/reviews.rs | 73 ++++++++++++++++ app/src/domain/summary.rs | 151 ++++++++++++++++++++++++++++++++++ 5 files changed, 481 insertions(+) create mode 100644 app/src/domain/changeset.rs create mode 100644 app/src/domain/inherited.rs create mode 100644 app/src/domain/summary.rs diff --git a/app/src/domain/changeset.rs b/app/src/domain/changeset.rs new file mode 100644 index 00000000..a5844f2c --- /dev/null +++ b/app/src/domain/changeset.rs @@ -0,0 +1,160 @@ +//! "This PR vs base": everything a pull request (or branch) changes, across all of its builds, against the baseline +//! it forked from. A per-build diff loses things: a snapshot removed and approved in build 2 looks unchanged by build 5, +//! because build 5 compares with build 2's approvals. Here the base is fixed (what the PR's first build of each suite +//! compared with) and the head is the newest build, so in-PR approvals don't hide anything, and the answer stays the +//! same after the merge. + +use std::collections::{BTreeMap, HashMap}; + +use laravel::db; + +use super::baselines; +use super::snapshots::CONFIG_PLATFORM; +use crate::models::{Build, Project, Snapshot}; + +/// One snapshot the pull request adds, changes or removes. +#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)] +pub struct Entry { + pub name: String, + pub platform: String, + /// `added`, `changed` or `removed`. + pub change: &'static str, + /// Where review stands for it in the newest build: `approved` (there or in an earlier build of the PR), `pending`, + /// `rejected`, or `failed`. + pub review: &'static str, +} + +/// One suite's changeset. +#[derive(Debug, Clone, serde::Serialize)] +pub struct Suite { + pub name: String, + /// The default branch's build the PR forked from, if it had one. + pub base_build: Option, + /// The PR's first and newest builds of the suite. + pub first_build: i32, + pub head_build: i32, + pub builds: usize, + pub entries: Vec, +} + +impl Suite { + #[must_use] + pub fn count(&self, change: &str) -> usize { + self.entries.iter().filter(|e| e.change == change).count() + } +} + +/// What a pull request is: its number, or a branch. +#[derive(Debug, Clone)] +pub enum Target { + Pr(i32), + Branch(String), +} + +/// The changeset of a pull request or branch, one entry per suite (build name), suites by name. Empty when it has +/// no CI builds. +/// +/// # Errors +/// On a database error. +pub async fn changeset(project: &Project, target: &Target) -> laravel::Result> { + let project_id = project.id; + let all: Vec = match target { + Target::Pr(n) => { + db::query!("SELECT * FROM builds WHERE project_id = {project_id} AND mode = 'ci' AND pr_number = {n} ORDER BY id") + .select_as() + .await? + } + Target::Branch(b) => { + db::query!("SELECT * FROM builds WHERE project_id = {project_id} AND mode = 'ci' AND branch = {b} ORDER BY id") + .select_as() + .await? + } + }; + let mut by_suite: BTreeMap> = BTreeMap::new(); + for b in all { + by_suite.entry(b.name.clone()).or_default().push(b); + } + let mut out = Vec::new(); + for (name, list) in by_suite { + let (Some(first), Some(head)) = (list.first(), list.last()) else { continue }; + // The base: what the first build compared each snapshot with, at the fork point. + let (base, anchor) = baselines::resolve(first, project).await?; + let base: HashMap<(String, String), Snapshot> = base + .into_iter() + .filter(|(_, r)| r.snapshot.platform != CONFIG_PLATFORM) + .map(|(k, r)| (k, r.snapshot)) + .collect(); + let all_head = super::snapshots::of_build(head.id).await?; + let head_snaps: HashMap<(String, String), Snapshot> = all_head + .iter() + .filter(|&s| s.platform != CONFIG_PLATFORM && s.state != "removed") + .cloned() + .map(|s| ((s.name.clone(), s.platform.clone()), s)) + .collect(); + // Review state: the newest build's verdict, or "approved" when an earlier build of the PR approved it (the + // newest then shows it unchanged against that approval). + let review_of = |s: Option<&Snapshot>, head_removed: Option<&Snapshot>| -> &'static str { + let s = s.or(head_removed); + match s { + Some(s) if s.state == "failed" => "failed", + Some(s) if s.review.as_deref() == Some("rejected") || head.review_state == "rejected" => "rejected", + Some(s) if s.state == "unchanged" => "approved", + Some(s) + if s.review.as_deref() == Some("approved") + || matches!(head.review_state.as_str(), "approved" | "auto_approved") => + { + "approved" + } + Some(_) => "pending", + // Gone from the newest build without being reported removed there: removed and approved earlier. + None => "approved", + } + }; + let head_removed: HashMap<(String, String), Snapshot> = all_head + .into_iter() + .filter(|s| s.state == "removed") + .map(|s| ((s.name.clone(), s.platform.clone()), s)) + .collect(); + let mut keys: Vec<(String, String)> = base.keys().chain(head_snaps.keys()).cloned().collect(); + keys.sort(); + keys.dedup(); + let mut entries = Vec::new(); + for key in keys { + let change = match (base.get(&key), head_snaps.get(&key)) { + (None, Some(_)) => "added", + (Some(_), None) => "removed", + (Some(b), Some(h)) if b.source_fingerprint != h.source_fingerprint => "changed", + _ => continue, + }; + entries.push(Entry { + name: key.0.clone(), + platform: key.1.clone(), + change, + review: review_of(head_snaps.get(&key), head_removed.get(&key)), + }); + } + out.push(Suite { + name, + base_build: anchor.map(|a| a.number), + first_build: first.number, + head_build: head.number, + builds: list.len(), + entries, + }); + } + Ok(out) +} + +/// The changeset as JSON, for the web app and MCP. +#[must_use] +pub fn json(suites: &[Suite]) -> serde_json::Value { + serde_json::json!({ + "suites": suites.iter().map(|s| serde_json::json!({ + "name": s.name, "base_build": s.base_build, "first_build": s.first_build, "head_build": s.head_build, + "builds": s.builds, + "counts": { "added": s.count("added"), "changed": s.count("changed"), "removed": s.count("removed") }, + "pending": s.entries.iter().filter(|e| e.review == "pending").count(), + "entries": s.entries, + })).collect::>(), + }) +} diff --git a/app/src/domain/inherited.rs b/app/src/domain/inherited.rs new file mode 100644 index 00000000..7be92c55 --- /dev/null +++ b/app/src/domain/inherited.rs @@ -0,0 +1,94 @@ +//! Changes a pull request build only inherited from its base branch. When the default branch's newest build (the one a +//! PR build is compared on top of) is still waiting for review, its changes aren't baselines yet, so every PR build +//! made after it shows them again: a reviewer can't tell the PR's own changes from main's backlog (2 Dec 2026, PR 3: +//! 98 changes, none of them the PR's). A PR build's change that's exactly the base build's unreviewed change (the same +//! snapshot, the same new content) is marked inherited, and the build says "N changes are already on main and +//! unreviewed (build #X)". Approval and the check still go by approved baselines: this only says where a change came +//! from. + +use std::collections::{HashMap, HashSet}; + +use super::snapshots::{is_change, is_config_item}; +use crate::models::{Build, Project, Snapshot}; + +/// A PR build's inherited changes: the base build they're unreviewed in, and which of this build's snapshots they are. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Inherited { + pub build: i32, + pub branch: String, + pub snapshot_ids: HashSet, +} + +impl Inherited { + /// "3 changes are already on main and unreviewed (build #77)". + #[must_use] + pub fn note(&self) -> String { + let n = self.snapshot_ids.len(); + let changes = if n == 1 { "change is" } else { "changes are" }; + format!("{n} {changes} already on {} and unreviewed (build #{})", self.branch, self.build) + } + + /// For an API answer: the base build, how many, and the sentence. + #[must_use] + pub fn json(&self) -> serde_json::Value { + serde_json::json!({ "build": self.build, "branch": self.branch, "count": self.snapshot_ids.len(), "note": self.note() }) + } +} + +/// The build's changes that are its base build's unreviewed changes, when its base is an unreviewed build of the +/// default branch and this build isn't on that branch. `None` when there are none. +/// +/// # Errors +/// On a database error. +pub async fn of_build(build: &Build, project: &Project) -> laravel::Result> { + if build.branch == project.default_branch { + return Ok(None); + } + let Some(base_id) = build.base_build_id else { return Ok(None) }; + let Some(base) = Build::find(base_id).await? else { return Ok(None) }; + if base.branch != project.default_branch || base.review_state != "pending" { + return Ok(None); + } + // The base build's changes that nobody has approved, by snapshot. + let pending: HashMap<(String, String), Snapshot> = super::snapshots::of_build(base.id) + .await? + .into_iter() + .filter(|s| is_change(s) && !is_config_item(s) && s.review.as_deref() != Some("approved")) + .map(|s| ((s.name.clone(), s.platform.clone()), s)) + .collect(); + if pending.is_empty() { + return Ok(None); + } + let snapshot_ids: HashSet = super::snapshots::of_build(build.id) + .await? + .into_iter() + .filter(|s| is_change(s) && !is_config_item(s)) + .filter(|s| { + pending.get(&(s.name.clone(), s.platform.clone())).is_some_and(|p| { + if s.state == "removed" { + p.state == "removed" + } else { + p.state != "removed" && p.source_fingerprint == s.source_fingerprint + } + }) + }) + .map(|s| s.id) + .collect(); + if snapshot_ids.is_empty() { + return Ok(None); + } + Ok(Some(Inherited { build: base.number, branch: base.branch, snapshot_ids })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn says_how_many_and_where() { + let one = Inherited { build: 77, branch: "main".into(), snapshot_ids: [1].into_iter().collect() }; + assert_eq!(one.note(), "1 change is already on main and unreviewed (build #77)"); + let three = Inherited { build: 77, branch: "main".into(), snapshot_ids: [1, 2, 3].into_iter().collect() }; + assert_eq!(three.note(), "3 changes are already on main and unreviewed (build #77)"); + } +} diff --git a/app/src/domain/mod.rs b/app/src/domain/mod.rs index 7b105431..6578d4eb 100644 --- a/app/src/domain/mod.rs +++ b/app/src/domain/mod.rs @@ -20,3 +20,6 @@ pub mod snapshots; pub mod detail; pub mod comments; pub mod reviews; +pub mod inherited; +pub mod summary; +pub mod changeset; diff --git a/app/src/domain/reviews.rs b/app/src/domain/reviews.rs index 9a0b70ea..71ff7704 100644 --- a/app/src/domain/reviews.rs +++ b/app/src/domain/reviews.rs @@ -219,6 +219,79 @@ pub async fn supersede_older(build: &Build) -> laravel::Result> { Ok(rows.iter().filter_map(|r| r.try_get::("id").ok()).collect()) } +/// Accept a changed page as a variant (an alternative baseline image for that page: both versions are fine), or ignore +/// its change (this exact diff, by fingerprint, in every later build). The snapshot stops being changed when none of +/// its pages are. Returns the build, recounted. A snapshot the build reads from an earlier build is unchanged there, +/// and its rows are that build's: it's refused. +/// +/// # Errors +/// `Ok(Err(message))` when the page isn't a changed page or the action is unknown; `Err` on a database error. +pub async fn page_action( + snapshot: Snapshot, + build: Build, + project_id: i64, + position: i32, + action: &str, + user_id: Option, +) -> laravel::Result> { + use crate::models::{IgnoredChange, SnapshotPage, Variant}; + let refused = || Ok(Err("only a changed page can be accepted as a variant or ignored".to_string())); + if snapshot.sourced { + return refused(); + } + let Some(mut page) = SnapshotPage::query() + .filter(SnapshotPage::snapshot_id.eq(snapshot.id) & SnapshotPage::position.eq(position)) + .first() + .await? + else { + return refused(); + }; + if page.state != "changed" || page.op != "changed" { + return refused(); + } + let new_state = match action { + "variant" => { + let Some(image) = page.head_image.clone() else { return Ok(Err("the page has no image".into())) }; + create!(Variant { + project_id: project_id, + name: snapshot.name.as_str(), + platform: snapshot.platform.as_str(), + page_index: page.head_index.unwrap_or(0), + image: image, + created_by: user_id, + }) + .await?; + "variant" + } + "ignore" => { + let Some(diff_id) = page.diff_id else { return Ok(Err("the page has no diff to ignore".into())) }; + let Some(fingerprint) = crate::models::Diff::find_or_fail(diff_id).await?.fingerprint else { + return Ok(Err("the diff has no fingerprint".into())); + }; + create!(IgnoredChange { + project_id: project_id, + name: snapshot.name.as_str(), + platform: snapshot.platform.as_str(), + fingerprint: fingerprint, + created_by: user_id, + }) + .await?; + "ignored" + } + _ => return Ok(Err("action must be variant or ignore".into())), + }; + update!(page { state: new_state }).await?; + let id = snapshot.id; + let remaining = SnapshotPage::query().filter(SnapshotPage::snapshot_id.eq(id) & SnapshotPage::state.eq("changed")).count().await?; + if remaining == 0 && snapshot.state == "changed" { + let ignored = + SnapshotPage::query().filter(SnapshotPage::snapshot_id.eq(id) & SnapshotPage::state.eq("ignored")).count().await?; + let state = if ignored > 0 { "ignored" } else { "unchanged" }; + db::query!("UPDATE snapshots SET state = {state}, updated_at = now() WHERE id = {id}").update().await?; + } + Ok(Ok(super::processing::recount(build).await?)) +} + #[cfg(test)] mod tests { use super::by; diff --git a/app/src/domain/summary.rs b/app/src/domain/summary.rs new file mode 100644 index 00000000..18e1c2a0 --- /dev/null +++ b/app/src/domain/summary.rs @@ -0,0 +1,151 @@ +//! A build's summary line, computed from its comparison: what changed and by how much, with no model call. +//! "invoice_typical: page 1 changed (2 regions); api/invoice.json: 3 JSON fields changed; 1 added". VisualCI never +//! runs a model: the customer's own agent reads the evidence over MCP. + +use visualci_core::snapshot_text; + +use super::snapshots::{CONFIG_PLATFORM, is_change, text_format}; +use crate::models::{Build, Diff, Snapshot}; + +/// At most this many changed snapshots are described one by one; the rest are counted. +const DESCRIBED: usize = 5; + +/// The build's summary line, or `None` while it's still comparing or when nothing needs a look. +/// +/// # Errors +/// On a database error. +pub async fn summary_line(build: &Build) -> laravel::Result> { + if build.state != "completed" { + return Ok(None); + } + let all = super::snapshots::of_build(build.id).await?; + let mut parts = Vec::new(); + // Finished with nothing of its own on purpose (a CI run that skipped the suite's jobs): say so, and where its + // baseline came from, rather than leave "0 unchanged" to read like something broke + // What it sent: its own rows, or (once its unchanged groups were read from an earlier build and its own rows of + // them deleted) the snapshot checks it was charged for. + let charged: super::processing::Usage = serde_json::from_value(build.charged.clone()).unwrap_or_default(); + let sent = charged.snapshot_checks > 0 + || all.iter().any(|s| !s.carried_forward && s.state != "removed" && s.platform != CONFIG_PLATFORM); + if build.allow_empty && !sent && build.conclusion.as_deref() != Some("failed") { + parts.push(nothing_sent(build).await?); + } + if all.iter().any(|s| s.platform == CONFIG_PLATFORM && is_change(s)) { + parts.push("visualci.yml could hide changes".to_string()); + } + let changed: Vec<&Snapshot> = + all.iter().filter(|s| s.state == "changed" && s.platform != CONFIG_PLATFORM).collect(); + for s in changed.iter().take(DESCRIBED) { + parts.push(format!("{}: {}", display_name(s), describe(s).await?)); + } + if changed.len() > DESCRIBED { + parts.push(format!("{} more changed", changed.len() - DESCRIBED)); + } + let count = |state: &str| all.iter().filter(|s| s.state == state && s.platform != CONFIG_PLATFORM).count(); + for (state, n) in [("added", count("added")), ("removed", count("removed")), ("failed", count("failed"))] { + if n > 0 { + parts.push(format!("{n} {state}")); + } + } + Ok((!parts.is_empty()).then(|| parts.join("; "))) +} + +/// "No snapshots this run (inputs unchanged): baseline from #12" +async fn nothing_sent(build: &Build) -> laravel::Result { + let reason = build.empty_reason.as_deref().map(|r| format!(" ({r})")).unwrap_or_default(); + let base = match build.base_build_id { + Some(id) => Build::find(id).await?.map(|b| b.number), + None => None, + }; + let baseline = base.map_or_else(|| "no baseline yet".to_string(), |n| format!("baseline from #{n}")); + Ok(format!("No snapshots this run{reason}: {baseline}")) +} + +fn display_name(s: &Snapshot) -> String { + if s.platform.is_empty() { s.name.clone() } else { format!("{} ({})", s.name, s.platform) } +} + +/// What changed in one snapshot: its pages and regions, its JSON fields, or its lines. +async fn describe(s: &Snapshot) -> laravel::Result { + let pages = super::pages::of_many(None, &[s]).await?.remove(&s.id).unwrap_or_default(); + if s.kind == "text" { + let page = pages.first(); + let base = page.and_then(|p| p.base_text.as_deref()).unwrap_or(""); + let head = page.and_then(|p| p.head_text.as_deref()).unwrap_or(""); + if text_format(s) == Some(snapshot_text::Format::Json) + && let (Ok(b), Ok(h)) = (serde_json::from_str(base), serde_json::from_str(head)) + { + let (changes, more) = snapshot_text::json_changes(&b, &h, 1000); + let n = changes.len(); + return Ok(format!("{n}{} JSON {} changed", if more { "+" } else { "" }, plural(n, "field", "fields"))); + } + let lines = visualci_core::text::page_diff(base, head, 0); + let added = lines.iter().filter(|l| l.tag == "+").count(); + let removed = lines.iter().filter(|l| l.tag == "-").count(); + return Ok(format!("+{added} −{removed} lines")); + } + let mut changed_pages = Vec::new(); + let mut regions = 0usize; + let (mut inserted, mut deleted) = (0usize, 0usize); + for p in &pages { + match (p.op.as_str(), p.state.as_str()) { + ("inserted", _) => inserted += 1, + ("removed", _) => deleted += 1, + (_, "changed") => { + changed_pages.push(p.head_index.or(p.base_index).map_or(0, |i| i + 1)); + if let Some(id) = p.diff_id + && let Some(d) = Diff::find(id).await? + { + regions += super::diffs::result(&d).map_or(0, |r| r.regions.len()); + } + } + _ => {} + } + } + let mut out = Vec::new(); + if !changed_pages.is_empty() { + let which = if s.kind == "image" { + "changed".to_string() + } else { + let list = changed_pages.iter().map(ToString::to_string).collect::>(); + format!("{} {} changed", plural(changed_pages.len(), "page", "pages"), join_and(&list)) + }; + out.push(if regions > 0 { + format!("{which} ({regions} {})", plural(regions, "region", "regions")) + } else { + which + }); + } + if inserted > 0 { + out.push(format!("{inserted} {} added", plural(inserted, "page", "pages"))); + } + if deleted > 0 { + out.push(format!("{deleted} {} removed", plural(deleted, "page", "pages"))); + } + Ok(if out.is_empty() { "changed".to_string() } else { out.join(", ") }) +} + +const fn plural<'a>(n: usize, one: &'a str, many: &'a str) -> &'a str { + if n == 1 { one } else { many } +} + +/// "1", "1 and 3", "1, 3 and 5". +fn join_and(items: &[String]) -> String { + match items { + [] => String::new(), + [one] => one.clone(), + [rest @ .., last] => format!("{} and {last}", rest.join(", ")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lists_read_naturally() { + assert_eq!(join_and(&["1".into()]), "1"); + assert_eq!(join_and(&["1".into(), "3".into()]), "1 and 3"); + assert_eq!(join_and(&["1".into(), "3".into(), "5".into()]), "1, 3 and 5"); + } +} From 45db26359a4096e1e66da2e23c486eb1f4e4e5a7 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:24:21 +1300 Subject: [PATCH 4/7] WIP: skills, MCP image and schema helpers copied --- app/Cargo.toml | 4 + app/src/mcp/images.rs | 173 ++++++++++++++++++++++++++++ app/src/mcp/schema.rs | 260 ++++++++++++++++++++++++++++++++++++++++++ app/src/skills.rs | 58 ++++++++++ 4 files changed, 495 insertions(+) create mode 100644 app/src/mcp/images.rs create mode 100644 app/src/mcp/schema.rs create mode 100644 app/src/skills.rs diff --git a/app/Cargo.toml b/app/Cargo.toml index 2e19d5ab..76846805 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -40,6 +40,10 @@ rusty-s3 = "0.12" globset = "0.4" schemars = "1" tracing = "0.1" +include_dir = "0.7" +rmcp = { version = "3.12", features = ["server", "transport-streamable-http-server", "macros"] } +base64 = "0.22" +tower = { version = "0.5", features = ["util"] } # VisualCI's own crates, shared with the CLI. visualci-core = { path = "../crates/visualci-core" } snapshot-diff = { path = "../crates/snapshot-diff" } diff --git a/app/src/mcp/images.rs b/app/src/mcp/images.rs new file mode 100644 index 00000000..13936f56 --- /dev/null +++ b/app/src/mcp/images.rs @@ -0,0 +1,173 @@ +//! Images for MCP answers, sized for an agent to read: scaled to a width, optionally cropped to what changed, and +//! re-encoded as JPEG when a PNG would be large. And contact sheets: many snapshots' thumbnails in one image. + +use image::{DynamicImage, GenericImageView, ImageFormat, Rgba, RgbaImage, imageops::FilterType}; +use visualci_core::diff::Region; + +/// The default width of images in answers. +pub const DEFAULT_MAX_WIDTH: u32 = 1200; +/// Margin around the changed regions when cropping. +const CROP_MARGIN: u32 = 32; +/// A PNG bigger than this goes out as JPEG instead. +const PNG_LIMIT: usize = 300_000; + +/// The smallest rectangle around all the regions, with a margin, inside `width` × `height`. +pub fn crop_box(regions: &[Region], width: u32, height: u32) -> Option { + let first = regions.first()?; + let (mut x0, mut y0, mut x1, mut y1) = (first.x, first.y, first.x + first.width, first.y + first.height); + for r in ®ions[1..] { + x0 = x0.min(r.x); + y0 = y0.min(r.y); + x1 = x1.max(r.x + r.width); + y1 = y1.max(r.y + r.height); + } + let x0 = x0.saturating_sub(CROP_MARGIN).min(width.saturating_sub(1)); + let y0 = y0.saturating_sub(CROP_MARGIN).min(height.saturating_sub(1)); + let x1 = (x1 + CROP_MARGIN).min(width).max(x0 + 1); + let y1 = (y1 + CROP_MARGIN).min(height).max(y0 + 1); + Some(Region { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }) +} + +/// An image ready for an answer: cropped (when a box is given), scaled down to `max_width`, and encoded as PNG, or as +/// JPEG when the PNG would be large. Returns the bytes and their media type. Bytes that don't decode go out as they +/// are. +pub fn prepare(bytes: &[u8], crop: Option<&[Region]>, max_width: u32) -> (Vec, &'static str) { + let Ok(mut img) = visualci_core::image_hash::decode(bytes) else { return (bytes.to_vec(), "image/png") }; + if let Some(regions) = crop + && let Some(b) = crop_box(regions, img.width(), img.height()) + { + img = img.crop_imm(b.x, b.y, b.width, b.height); + } + if img.width() > max_width { + let height = (u64::from(img.height()) * u64::from(max_width) / u64::from(img.width())).max(1); + img = img.resize_exact(max_width, u32::try_from(height).unwrap_or(u32::MAX), FilterType::Triangle); + } + encode(&img) +} + +/// The image cropped to its changed regions (with a margin) at full size, as PNG: a bulk download's `regions` file. +/// `None` when the bytes don't decode or there are no regions. +pub fn crop_png(bytes: &[u8], regions: &[Region]) -> Option> { + let img = visualci_core::image_hash::decode(bytes).ok()?; + let b = crop_box(regions, img.width(), img.height())?; + let mut png = std::io::Cursor::new(Vec::new()); + img.crop_imm(b.x, b.y, b.width, b.height).write_to(&mut png, ImageFormat::Png).ok()?; + Some(png.into_inner()) +} + +fn encode(img: &DynamicImage) -> (Vec, &'static str) { + let mut png = std::io::Cursor::new(Vec::new()); + if img.write_to(&mut png, ImageFormat::Png).is_ok() && png.get_ref().len() <= PNG_LIMIT { + return (png.into_inner(), "image/png"); + } + let mut jpeg = std::io::Cursor::new(Vec::new()); + let rgb = DynamicImage::ImageRgb8(img.to_rgb8()); + let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 80); + if rgb.write_with_encoder(encoder).is_ok() { + return (jpeg.into_inner(), "image/jpeg"); + } + (png.into_inner(), "image/png") +} + +/// Thumbnails laid out in a grid, left to right and top to bottom, `columns` wide, in a `width`-pixel image. Each +/// cell has a thin border so neighbouring white pages stay apart. Missing images leave their cell grey. +pub fn contact_sheet(images: &[Option>], columns: u32, width: u32) -> (Vec, &'static str) { + let columns = columns.clamp(1, 8); + let gap = 8u32; + let cell_w = (width.saturating_sub(gap * (columns + 1)) / columns).max(32); + // Cells are as tall as the tallest thumbnail in their row, capped at twice their width. + let thumbs: Vec> = images + .iter() + .map(|b| { + b.as_ref().and_then(|b| visualci_core::image_hash::decode(b).ok()).map(|img| { + let h = (u64::from(img.height()) * u64::from(cell_w) / u64::from(img.width().max(1))).max(1); + let h = u32::try_from(h).unwrap_or(u32::MAX).min(cell_w * 2); + img.resize(cell_w, h, FilterType::Triangle) + }) + }) + .collect(); + let rows = (u32::try_from(thumbs.len()).unwrap_or(0)).div_ceil(columns).max(1); + let row_heights: Vec = (0..rows) + .map(|r| { + (0..columns) + .filter_map(|c| thumbs.get((r * columns + c) as usize)) + .map(|t| t.as_ref().map_or(cell_w / 2, |t| t.height())) + .max() + .unwrap_or(cell_w / 2) + }) + .collect(); + let height = row_heights.iter().sum::() + gap * (rows + 1); + let mut sheet = RgbaImage::from_pixel(width, height, Rgba([246, 247, 249, 255])); + let mut y = gap; + for (r, row_h) in row_heights.iter().enumerate() { + for c in 0..columns { + let i = r * columns as usize + c as usize; + if i >= thumbs.len() { + break; + } + let x = gap + c * (cell_w + gap); + let (w, h) = thumbs[i].as_ref().map_or((cell_w, cell_w / 2), |t| t.dimensions()); + // Border, then the thumbnail (or grey when there's none). + for bx in x.saturating_sub(1)..(x + w + 1).min(width) { + for by in y.saturating_sub(1)..(y + h + 1).min(height) { + sheet.put_pixel(bx, by, Rgba([200, 204, 212, 255])); + } + } + match &thumbs[i] { + Some(t) => image::imageops::overlay(&mut sheet, &t.to_rgba8(), i64::from(x), i64::from(y)), + None => { + for bx in x..(x + w).min(width) { + for by in y..(y + h).min(height) { + sheet.put_pixel(bx, by, Rgba([225, 228, 233, 255])); + } + } + } + } + } + y += row_h + gap; + } + encode(&DynamicImage::ImageRgba8(sheet)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn png(w: u32, h: u32) -> Vec { + let img = RgbaImage::from_pixel(w, h, Rgba([10, 20, 30, 255])); + let mut out = std::io::Cursor::new(Vec::new()); + DynamicImage::ImageRgba8(img).write_to(&mut out, ImageFormat::Png).unwrap(); + out.into_inner() + } + + #[test] + fn scales_down_to_the_width() { + let (bytes, _) = prepare(&png(2400, 1000), None, 1200); + let img = image::load_from_memory(&bytes).unwrap(); + assert_eq!((img.width(), img.height()), (1200, 500)); + let (bytes, _) = prepare(&png(400, 100), None, 1200); + assert_eq!(image::load_from_memory(&bytes).unwrap().width(), 400, "small images aren't scaled up"); + } + + #[test] + fn crops_to_the_changed_regions_with_a_margin() { + let regions = + [Region { x: 100, y: 100, width: 10, height: 10 }, Region { x: 300, y: 150, width: 20, height: 5 }]; + assert_eq!(crop_box(®ions, 1000, 1000), Some(Region { x: 68, y: 68, width: 284, height: 119 })); + // Clamped to the image. + let edge = [Region { x: 0, y: 990, width: 10, height: 10 }]; + assert_eq!(crop_box(&edge, 1000, 1000), Some(Region { x: 0, y: 958, width: 42, height: 42 })); + let (bytes, _) = prepare(&png(1000, 1000), Some(®ions), 1200); + let img = image::load_from_memory(&bytes).unwrap(); + assert_eq!((img.width(), img.height()), (284, 119)); + } + + #[test] + fn a_contact_sheet_fits_its_width() { + let images = vec![Some(png(800, 600)), None, Some(png(400, 1600)), Some(png(1440, 900)), Some(png(10, 10))]; + let (bytes, _) = contact_sheet(&images, 4, 1200); + let img = image::load_from_memory(&bytes).unwrap(); + assert_eq!(img.width(), 1200); + assert!(img.height() > 200 && img.height() < 2000, "{}", img.height()); + } +} diff --git a/app/src/mcp/schema.rs b/app/src/mcp/schema.rs new file mode 100644 index 00000000..e9104ad7 --- /dev/null +++ b/app/src/mcp/schema.rs @@ -0,0 +1,260 @@ +//! Tool schemas as every MCP client and directory can read them. schemars writes `$ref`s into `$defs`, enums as +//! `oneOf` of `const`s, optional enums as `anyOf` with `null`, and nothing at all for a free-form value. Some clients +//! refuse those, and directories flag them ("Add a type to this parameter"). Each tool's input and output schema is +//! rewritten once, when the router is built: references inlined, `$defs` dropped, enums as `type` + `enum` (their +//! descriptions folded into the property's), optional values as a type list with `null`, and a `type` on every +//! property. + +use std::sync::Arc; + +use serde_json::{Map, Value, json}; + +/// Rewrite every tool's schemas in a router. +pub fn normalize_router(router: &mut rmcp::handler::server::router::tool::ToolRouter) { + for route in router.map.values_mut() { + let mut input = normalize_object(&route.attr.input_schema); + // Unknown arguments are refused (`mcp::unknown_arguments`); the schema says so up front. + input.insert("additionalProperties".into(), json!(false)); + route.attr.input_schema = Arc::new(input); + if let Some(out) = &route.attr.output_schema { + route.attr.output_schema = Some(Arc::new(normalize_object(out))); + } + } +} + +fn normalize_object(schema: &Map) -> Map { + let root = Value::Object(schema.clone()); + let defs = root.get("$defs").or_else(|| root.get("definitions")).cloned().unwrap_or(Value::Null); + let mut out = normalize(&root, &defs, 0); + if let Value::Object(m) = &mut out { + m.remove("$defs"); + m.remove("definitions"); + m.entry("type").or_insert_with(|| json!("object")); + return m.clone(); + } + schema.clone() +} + +/// The definition a `$ref` names (`#/$defs/Name`). +fn lookup<'a>(defs: &'a Value, reference: &str) -> Option<&'a Value> { + let name = reference.rsplit('/').next()?; + defs.get(name) +} + +/// The JSON type of a constant. +fn type_of(v: &Value) -> &'static str { + match v { + Value::Null => "null", + Value::Bool(_) => "boolean", + Value::Number(n) if n.is_i64() || n.is_u64() => "integer", + Value::Number(_) => "number", + Value::String(_) => "string", + Value::Array(_) => "array", + Value::Object(_) => "object", + } +} + +/// A list of types, as one string when there's one. +fn types(mut list: Vec) -> Value { + list.sort_by_key(|t| t == "null"); + list.dedup(); + if list.len() == 1 { json!(list[0]) } else { json!(list) } +} + +fn merge_description(target: &mut Map, extra: &str) { + if extra.is_empty() { + return; + } + let joined = match target.get("description").and_then(Value::as_str) { + Some(d) if !d.is_empty() => format!("{d} {extra}"), + _ => extra.to_string(), + }; + target.insert("description".into(), json!(joined)); +} + +fn normalize(node: &Value, defs: &Value, depth: usize) -> Value { + if depth > 32 { + return node.clone(); + } + let Value::Object(map) = node else { return node.clone() }; + // A reference: the definition, with the referring schema's own keys (its description) on top. + if let Some(reference) = map.get("$ref").and_then(Value::as_str) { + let mut resolved = match lookup(defs, reference).map(|d| normalize(d, defs, depth + 1)) { + Some(Value::Object(m)) => m, + _ => Map::new(), + }; + // The definition's own description (an enum's notes on each value) follows the referring one. + let inner = resolved.remove("description").and_then(|d| d.as_str().map(str::to_string)); + for (k, v) in map { + if k != "$ref" { + resolved.insert(k.clone(), normalize(v, defs, depth + 1)); + } + } + if let Some(d) = inner { + merge_description(&mut resolved, &d); + } + return Value::Object(resolved); + } + let mut out = Map::new(); + for (k, v) in map { + match k.as_str() { + "properties" => { + let props: Map = v + .as_object() + .map(|p| p.iter().map(|(n, s)| (n.clone(), typed(normalize(s, defs, depth + 1)))).collect()) + .unwrap_or_default(); + out.insert(k.clone(), Value::Object(props)); + } + "items" | "additionalProperties" if v.is_object() => { + out.insert(k.clone(), typed(normalize(v, defs, depth + 1))); + } + "oneOf" | "anyOf" => {} + _ => { + out.insert(k.clone(), v.clone()); + } + } + } + let variants = map.get("oneOf").or_else(|| map.get("anyOf")).and_then(Value::as_array); + if let Some(variants) = variants { + let variants: Vec = variants.iter().map(|v| normalize(v, defs, depth + 1)).collect(); + fold_variants(&mut out, &variants); + } + Value::Object(out) +} + +/// `oneOf`/`anyOf` folded into one schema: constants (and `null`) into `type` + `enum`, one real schema plus `null` +/// into that schema with `null` added to its type. Anything else keeps the first variant's shape, so a client still +/// sees a typed property. +fn fold_variants(out: &mut Map, variants: &[Value]) { + let is_null = |v: &Value| v.get("type") == Some(&json!("null")); + let constants: Option)>> = variants + .iter() + .map(|v| { + if let Some(c) = v.get("const") { + Some((c.clone(), v.get("description").and_then(Value::as_str).map(str::to_string))) + } else if is_null(v) { + Some((Value::Null, None)) + } else { + None + } + }) + .collect(); + let constants = constants.or_else(|| { + // Also plain enums (`{"type": "string", "enum": [...]}`) and null. + let mut all = Vec::new(); + for v in variants { + if is_null(v) { + all.push((Value::Null, None)); + } else { + for e in v.get("enum")?.as_array()? { + all.push((e.clone(), None)); + } + } + } + Some(all).filter(|a| !a.is_empty()) + }); + if let Some(constants) = constants { + let kinds: Vec = constants.iter().map(|(c, _)| type_of(c).to_string()).collect(); + out.insert("type".into(), types(kinds)); + out.insert("enum".into(), Value::Array(constants.iter().map(|(c, _)| c.clone()).collect())); + let notes: Vec = constants + .iter() + .filter_map(|(c, d)| { + d.as_ref().map(|d| format!("`{}`: {}", c.as_str().unwrap_or_default(), d.trim_end_matches('.'))) + }) + .collect(); + if !notes.is_empty() { + merge_description(out, &format!("{}.", notes.join("; "))); + } + return; + } + let real: Vec<&Value> = variants.iter().filter(|v| !is_null(v)).collect(); + let nullable = real.len() < variants.len(); + if let Some(Value::Object(first)) = real.first() { + for (k, v) in first { + if k == "description" { + if let Some(d) = v.as_str() { + merge_description(out, d); + } + } else { + out.entry(k.clone()).or_insert_with(|| v.clone()); + } + } + } + if nullable { + let mut list: Vec = match out.get("type") { + Some(Value::String(t)) => vec![t.clone()], + Some(Value::Array(ts)) => ts.iter().filter_map(|t| t.as_str().map(str::to_string)).collect(), + _ => vec!["object".to_string()], + }; + list.push("null".to_string()); + if let Some(Value::Array(e)) = out.get_mut("enum") + && !e.contains(&Value::Null) + { + e.push(Value::Null); + } + out.insert("type".into(), types(list)); + } +} + +/// A property schema with a `type`: from its constants or enum when it has them, `object` for a free-form value +/// (an object of anything is what those carry). +fn typed(schema: Value) -> Value { + let Value::Object(mut m) = schema else { + // `true` (anything): an object of anything. + return json!({ "type": "object" }); + }; + if !m.contains_key("type") { + let t = if let Some(c) = m.get("const") { + json!(type_of(c)) + } else if let Some(Value::Array(e)) = m.get("enum") { + types(e.iter().map(|v| type_of(v).to_string()).collect()) + } else if m.contains_key("properties") { + json!("object") + } else if m.contains_key("items") { + json!("array") + } else { + json!("object") + }; + m.insert("type".into(), t); + } + Value::Object(m) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn inlines_refs_and_folds_enums() { + let schema = json!({ + "type": "object", + "properties": { + "role": { "$ref": "#/$defs/Role", "description": "The role." }, + "kind": { "anyOf": [{ "$ref": "#/$defs/Kind" }, { "type": "null" }] }, + "config": { "description": "visualci.yml as JSON." }, + "build": { "type": ["integer", "string"] }, + "tags": { "type": "array", "items": { "$ref": "#/$defs/Kind" } } + }, + "$defs": { + "Role": { "oneOf": [ + { "const": "read", "description": "Looks only." }, + { "const": "admin", "description": "Everything." } + ] }, + "Kind": { "type": "string", "enum": ["bug", "idea"] } + } + }); + let out = normalize_object(schema.as_object().unwrap()); + let p = &out["properties"]; + assert!(out.get("$defs").is_none()); + assert_eq!(p["role"]["type"], "string"); + assert_eq!(p["role"]["enum"], json!(["read", "admin"])); + assert_eq!(p["role"]["description"], "The role. `read`: Looks only; `admin`: Everything."); + assert_eq!(p["kind"]["type"], json!(["string", "null"])); + assert_eq!(p["kind"]["enum"], json!(["bug", "idea", null])); + assert_eq!(p["config"]["type"], "object"); + assert_eq!(p["build"]["type"], json!(["integer", "string"])); + assert_eq!(p["tags"]["items"]["enum"], json!(["bug", "idea"])); + assert!(!serde_json::to_string(&out).unwrap().contains("$ref")); + } +} diff --git a/app/src/skills.rs b/app/src/skills.rs new file mode 100644 index 00000000..b349227f --- /dev/null +++ b/app/src/skills.rs @@ -0,0 +1,58 @@ +//! VisualCI's agent skills (skills/ at the repository's root, generated from the docs pages by +//! server/frontend/scripts/skills.mjs), embedded at build time for the MCP server's `get_skill`. + +use include_dir::{Dir, include_dir}; + +static SKILLS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/../skills"); + +/// One skill: its name, description and SKILL.md. +pub struct Skill { + pub name: &'static str, + pub description: String, + pub text: &'static str, +} + +/// Every skill, by name. +#[must_use] +pub fn all() -> Vec { + let mut skills: Vec = SKILLS + .dirs() + .filter_map(|dir| { + let name = dir.path().file_name()?.to_str()?; + let text = dir.get_file(dir.path().join("SKILL.md"))?.contents_utf8()?; + Some(Skill { name, description: description(text), text }) + }) + .collect(); + skills.sort_by_key(|s| s.name); + skills +} + +/// The SKILL.md of the skill called `name`. +#[must_use] +pub fn get(name: &str) -> Option { + all().into_iter().find(|s| s.name == name) +} + +/// The front matter's `description:`, a JSON string. +fn description(text: &str) -> String { + text.lines() + .find_map(|line| line.strip_prefix("description: ")) + .and_then(|raw| serde_json::from_str::(raw).ok()) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + #[test] + fn every_skill_has_a_description_and_the_main_one_lists_the_others() { + let skills = super::all(); + assert!(skills.len() > 10, "{}", skills.len()); + for s in &skills { + assert!(s.description.contains("Use when"), "{}", s.name); + } + let main = super::get("visualci").unwrap(); + for s in skills.iter().filter(|s| s.name != "visualci") { + assert!(main.text.contains(&format!("`{}`", s.name)), "{} isn't listed", s.name); + } + } +} From b5a71b35d87f6b16f5b1833445722c160ddaad9d Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:27:26 +1300 Subject: [PATCH 5/7] WIP: environment_info_for, blocked notice on build responses, approved_elsewhere, MCP args --- app/src/domain/baselines.rs | 66 ++++++ app/src/domain/builds.rs | 17 ++ app/src/http/api/builds.rs | 31 ++- app/src/mcp/args.rs | 438 ++++++++++++++++++++++++++++++++++++ 4 files changed, 549 insertions(+), 3 deletions(-) create mode 100644 app/src/mcp/args.rs diff --git a/app/src/domain/baselines.rs b/app/src/domain/baselines.rs index f74fcf0f..6adda98d 100644 --- a/app/src/domain/baselines.rs +++ b/app/src/domain/baselines.rs @@ -476,3 +476,69 @@ pub async fn local_notes(ids: &[i64]) -> laravel::Result> { } Ok(out) } + +/// Where a snapshot's new version was already approved: the same name and platform, the same content (its +/// fingerprint), approved in a review on another branch. A hint for the reviewer: it approves nothing. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub struct ApprovedElsewhere { + pub branch: String, + pub pr_number: Option, + /// The build it was approved in, and the snapshot there. + pub build: i32, + pub snapshot_id: laravel::str::Uuid, + /// Who approved it ("Claude Code for Ada Lovelace"). + pub approved_by: Option, + pub approved_at: String, +} + +/// For a build's changed and added snapshots, and those that passed by matching an approval elsewhere, the newest +/// matching approval on another branch, by snapshot id. Changes are always the build's own rows. +/// +/// # Errors +/// On a database error. +pub async fn approved_elsewhere(build_id: i64) -> laravel::Result> { + let rows = db::query!( + "SELECT DISTINCT ON (s.id) s.id AS snapshot_id, bl.branch, b2.pr_number, b2.number, s2.pid AS other, \ + u.name AS approver, r.source, r.client_name, r.agent, r.token_name, bl.created_at \ + FROM snapshots s \ + JOIN builds b ON b.id = s.build_id \ + JOIN baselines bl ON bl.project_id = b.project_id AND bl.name = s.name AND bl.platform = s.platform \ + AND bl.approval = 'review' AND bl.branch <> b.branch AND bl.snapshot_id IS NOT NULL \ + JOIN snapshots s2 ON s2.id = bl.snapshot_id AND s2.source_fingerprint = s.source_fingerprint \ + JOIN builds b2 ON b2.id = bl.build_id \ + LEFT JOIN users u ON u.id = bl.approved_by \ + LEFT JOIN reviews r ON r.id = bl.review_id \ + WHERE s.build_id = {build_id} AND (s.state IN ('changed', 'added') \ + OR EXISTS (SELECT 1 FROM snapshot_pages p WHERE p.snapshot_id = s.id AND p.state = 'variant')) \ + ORDER BY s.id, bl.created_at DESC" + ) + .select() + .await?; + let mut out = HashMap::new(); + for r in rows { + let at: laravel::time::Timestamp = r.try_get("created_at")?; + let person: Option = r.try_get("approver")?; + let approved_by = match r.try_get::>("source")? { + Some(source) => Some(super::reviews::by( + &source, + r.try_get::>("client_name")?.as_deref(), + r.try_get::>("agent")?.as_deref(), + r.try_get::>("token_name")?.as_deref(), + person.as_deref(), + )), + None => person, + }; + out.insert( + r.try_get::("snapshot_id")?, + ApprovedElsewhere { + branch: r.try_get("branch")?, + pr_number: r.try_get("pr_number")?, + build: r.try_get("number")?, + snapshot_id: r.try_get("other")?, + approved_by, + approved_at: at.to_string(), + }, + ); + } + Ok(out) +} diff --git a/app/src/domain/builds.rs b/app/src/domain/builds.rs index f6eeb81e..f5b7f3b3 100644 --- a/app/src/domain/builds.rs +++ b/app/src/domain/builds.rs @@ -363,3 +363,20 @@ pub async fn finalize_shard(build: Build, shard: Option, allow_empty: bool) .await; result.or_else(server) } + +/// Where the build ran, as someone outside the organization may see it on a public project: the CI provider and the +/// links to the job and the repository, never a local run's user name or machine. +#[must_use] +pub fn environment_info_for(build: &Build, member: bool) -> serde_json::Value { + let info = build.environment_info.clone(); + if member { + return info; + } + let keep = ["provider", "job_url", "repository_url"]; + match info { + serde_json::Value::Object(map) => { + serde_json::Value::Object(map.into_iter().filter(|(k, _)| keep.contains(&k.as_str())).collect()) + } + _ => serde_json::Value::Null, + } +} diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index e1d2b80a..e275a697 100644 --- a/app/src/http/api/builds.rs +++ b/app/src/http/api/builds.rs @@ -83,6 +83,31 @@ impl BuildResponse { } } +impl BuildResponse { + /// The response with `blocked` filled in: for a build stopped for credits, and for one still receiving files while + /// its organization has none. A stopped build whose organization has credits again says so. + /// + /// # Errors + /// On a database error. + pub async fn with_blocked(mut self, build: &Build, project: &Project, organization: &Organization) -> laravel::Result { + use crate::domain::{credits, processing::OUT_OF_CREDITS}; + let stopped = build.error_code.as_deref() == Some(OUT_OF_CREDITS); + if !stopped && build.state != "receiving" { + return Ok(self); + } + self.blocked = match credits::blocked(organization, &app_url(), Some(credits::Spender::of(project))).await? { + Some(b) => Some(b), + None if stopped => Some(serde_json::json!({ + "reason": OUT_OF_CREDITS, + "resolved": true, + "message": format!("{} has VisualCI credits again. Run CI again to compare this commit.", organization.name), + })), + None => None, + }; + Ok(self) + } +} + fn respond(result: Result) -> Response { match result { Ok(body) => axum::response::IntoResponse::into_response(axum::Json(body)), @@ -113,7 +138,7 @@ pub async fn create(auth: Result, Body(params): Body, Params(pid): Params) async { let ApiProject { project, organization, .. } = auth?; let build = own_build(&project, pid).await?; - Ok(BuildResponse::new(&build, &project, &organization)) + Ok(BuildResponse::new(&build, &project, &organization).with_blocked(&build, &project, &organization).await?) } .await, ) @@ -239,7 +264,7 @@ pub async fn finalize( } // The job may have run already (a synchronous queue): answer with the build as it is now. let build = Build::find(build.id).await?.unwrap_or(build); - Ok(BuildResponse::new(&build, &project, &organization)) + Ok(BuildResponse::new(&build, &project, &organization).with_blocked(&build, &project, &organization).await?) } .await, ) diff --git a/app/src/mcp/args.rs b/app/src/mcp/args.rs new file mode 100644 index 00000000..6dfc5065 --- /dev/null +++ b/app/src/mcp/args.rs @@ -0,0 +1,438 @@ +//! The MCP tools' arguments, as their JSON schemas describe them to agents. + +#![allow(clippy::doc_markdown)] + +use schemars::JsonSchema; +use serde::Deserialize; + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct NoArgs {} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct SkillArgs { + /// A skill's name, such as `visualci-circleci`. Leave it out to list the skills. + #[serde(default)] + pub name: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct OrgArgs { + /// The organization's slug. + pub org: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct CreateOrgArgs { + /// Lowercase letters, digits and dashes; used in URLs. + pub slug: String, + pub name: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct CreateProjectArgs { + pub org: String, + /// Lowercase letters, digits and dashes; used in URLs. + pub slug: String, + pub name: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ProjectArgs { + /// `org/project`. Optional with a project token. + pub project: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct CreateTokenArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// What the token is for, e.g. `CircleCI`. + pub name: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct DeleteTokenArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The token's id, from `get_project`. + pub token_id: i64, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ListBuildsArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// Only builds of this branch. + pub branch: Option, + /// How many, newest first (default 20, at most 100). + pub limit: Option, + /// Only builds whose changes wait for a review (a local build only for the person whose run it was). + pub waiting_for_review: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct BuildArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The build number (as in the build's URL) or its id. + pub build: BuildRef, + /// Also list unchanged snapshots (by default they're only counted). + #[serde(default)] + pub include_unchanged: bool, + /// Skip this many listed snapshots (for the next page). Default 0. + pub offset: Option, + /// List at most this many snapshots, 1 to 200. Default 30. Longer lists also come grouped by state and name + /// prefix, so a build with hundreds of new snapshots reads in one answer. + pub limit: Option, + /// `change` (the default): changed snapshots with the largest change first, then added, removed, failed and the + /// rest. `name`: by name. + #[serde(default)] + pub order: crate::domain::detail::ReviewOrder, +} + +/// A build, by number (`12`, `"12"` or `"#12"`) or id: agents send either a number or a string. +#[derive(Debug, Clone)] +pub struct BuildRef(String); + +impl<'de> Deserialize<'de> for BuildRef { + fn deserialize>(d: D) -> Result { + match serde_json::Value::deserialize(d)? { + serde_json::Value::String(s) => Ok(Self(s)), + serde_json::Value::Number(n) => Ok(Self(n.to_string())), + other => Err(serde::de::Error::custom(format!("build must be a number or a string, not {other}"))), + } + } +} + +impl JsonSchema for BuildRef { + fn schema_name() -> std::borrow::Cow<'static, str> { + "BuildRef".into() + } + + fn inline_schema() -> bool { + true + } + + fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({ "type": ["integer", "string"] }) + } +} + +impl std::ops::Deref for BuildRef { + type Target = str; + + fn deref(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for BuildRef { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct SnapshotArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The build number or id. + pub build: BuildRef, + /// The snapshot's name, as `get_build` lists it, or its `id` from `get_build`. + #[serde(default)] + pub name: String, + /// The snapshot's id, as `get_build` lists it: instead of `name` and `platform`. + pub id: Option, + /// The snapshot's platform. Optional when the name is on one platform only. + #[serde(default)] + pub platform: String, + /// Positions of the pages to include images for (from a previous answer). Default: the first three changed pages. + pub pages: Option>, + /// Which images to include: `all` (base, head, diff; the default), `diff`, `head`, `base`, or `none`. + /// For text, JSON and HTML: `head`, `base` or `all` adds that whole version's text. + pub images: Option, + /// Scale images down to this width in pixels (default 1200). Large ones come back as JPEG. + pub max_width: Option, + /// `changed` crops each image to the changed regions with a margin, for a close look at a small change on a tall + /// page. + pub crop: Option, + /// What the new side is compared with: `baseline` (the default, what review uses), `previous` (the newest earlier + /// build of this snapshot on the branch: did a fix answer a comment there?), or an earlier build's number on the + /// branch. Only `baseline` decides the review; the others are a view. + pub against: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ContactSheetArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The build number or id. + pub build: BuildRef, + /// Which snapshots, by state: comma-separated, from `changed`, `added`, `removed`, `unchanged`, `ignored` + /// (default `changed,added`). + pub states: Option, + /// Skip this many (for the next sheet). Default 0. + pub offset: Option, + /// How many per sheet, at most 48. Default 24. + pub limit: Option, + /// Thumbnails per row, 1 to 8. Default 4. + pub columns: Option, + /// `change` (the default): the largest change first, then added and removed. `name`: by name. + #[serde(default)] + pub order: crate::domain::detail::ReviewOrder, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ChangesetArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The pull request's number. + pub pr: Option, + /// A branch, instead of a pull request number. + pub branch: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct HistoryArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub name: String, + #[serde(default)] + pub platform: String, + /// Only builds of this branch. + pub branch: Option, + /// How many builds to look back (default 20, at most 200). + pub limit: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ReviewArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub build: BuildRef, + /// `approve` or `reject`. + pub action: String, + /// Snapshot names to review; all changed snapshots when left out. + pub snapshots: Option>, + /// 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. + pub comment: Option, + /// Why you approved or rejected, in a sentence. It's shown wherever the review appears (the build's + /// reviews, the pull request comment). A note, not a thread: it never blocks anything. + pub note: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ListCommentsArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// A build: its branch's threads are listed (threads follow the branch). + pub build: BuildRef, + /// Only this snapshot's threads (its name, or its id from `get_build`). + pub snapshot: Option, + #[serde(default)] + pub platform: String, + /// Also resolved threads. Default: open ones only. + #[serde(default)] + pub include_resolved: bool, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct PostCommentArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The build being looked at. + pub build: BuildRef, + /// To reply: the thread's id. Leave out to start a thread. + pub thread: Option, + /// To start a thread: the snapshot's name (or its id from `get_build`). + pub snapshot: Option, + #[serde(default)] + pub platform: String, + /// The page's position (from `get_snapshot`); leave out for the whole snapshot. + pub page: Option, + /// `head` (the new image, the default) or `base`. + pub side: Option, + /// Where on the image: `{"kind": "image"}` (the default), `{"kind": "point", "x": 410, "y": 96}` or + /// `{"kind": "box", "x": 120, "y": 80, "w": 300, "h": 140}`, in pixels of that side's image from its top left: + /// the same units as `regions` in `get_snapshot`, so a region can be pinned as it is. + pub anchor: Option, + /// Markdown. + pub body: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct CommentIdArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The comment's id. + pub comment: String, + /// The new text (Markdown), for `update_comment`. + pub body: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ResolveArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The thread's id. + pub thread: String, + /// `false` reopens it. Default `true`. + pub resolved: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ReviewPageArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub build: BuildRef, + pub name: String, + #[serde(default)] + pub platform: String, + /// The page's position, from `get_snapshot`. + pub position: i32, + /// `variant` (both the old and the new page are fine: keep both as baselines) or `ignore` (ignore this exact + /// change in later builds too). + pub action: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct CreateBuildArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The commit SHA the files come from. + pub commit: String, + pub branch: String, + pub pr_number: Option, + /// Ancestor commits, nearest first, for finding the baseline. + #[serde(default)] + pub parent_commits: Vec, + /// `ci` (the default) or `local` (a check from a laptop that never becomes a baseline). + pub mode: Option, + /// Builds with different names (e.g. `pdfs`, `browser`) keep separate baselines. Default `default`. + pub name: Option, + /// The build has only some of the project's snapshots; missing ones are carried forward, not removed. + #[serde(default)] + pub subset: bool, + /// Calls with the same nonce get the same build back (for parallel shards). + pub nonce: Option, + /// Where the build runs: `ci` (the default), `local-mac`, `local-linux`. Screenshots keep a baseline set per + /// environment; documents and text share one. + pub environment: Option, + /// The repository's visualci.yml as JSON (the CLI sends it). Its fields override the project's settings for this + /// build; ignore rules must each name their snapshots. + pub config: Option, + /// How many shards will finalize the build (default 1). + pub shard_total: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct UploadFile { + /// The snapshot's name, unique in the build (e.g. the test's name). + pub name: String, + /// For screenshots: the browser or device, so each platform keeps its own baseline. + #[serde(default)] + pub platform: String, + /// The file's bytes, base64. PDFs, PNG, JPEG or WebP images, or text (plain text, JSON, HTML, a serialized + /// component tree). + pub content_base64: String, + /// The file's name or extension (e.g. `invoice.pdf`, `.png`, `response.json`), to tell images from text and JSON + /// or HTML from plain text. + pub filename: Option, + /// Text: `text`, `json` or `html`, overriding the file name. JSON is compared with keys sorted, HTML with + /// attributes sorted and whitespace collapsed. + pub format: Option, + /// The diff threshold (0 to 1), overriding the project's: 0 is exact, above 0 a perceptual colour threshold. + pub threshold: Option, + /// Documents: `pdfbox` or `mutool`, overriding the project's renderer. + pub engine: Option, + /// Anything to keep with the snapshot (test file, URL, viewport). + pub meta: Option, + /// Text: values to ignore in this snapshot only, `{json_paths, text_patterns}`, on top of the visualci.yml's or + /// project's rules. + pub ignore: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct UploadArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub build: BuildRef, + pub files: Vec, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct FinalizeArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub build: BuildRef, + /// The shard that finished, when the build has several. + pub shard: Option, + /// True when the build may have no snapshots on purpose. Otherwise a build that was sent none fails. + pub allow_empty: Option, + /// Why it has none, like "inputs unchanged" (the CI run skipped the tests): implies allow_empty, and shows in the + /// build's summary with the build its baseline came from. + pub empty_reason: Option, +} + +// Standard Support level 1 (standardsupport.dev): the schema names every field and its choices, with no field +// descriptions (so these structs have plain comments, not doc comments, which would become descriptions). +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum SendAction { + Feedback, +} + +#[derive(Debug, serde::Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum FeedbackKind { + Bug, + Crash, + WrongResult, + Confusing, + MissingFeature, + Docs, + Question, + Other, +} + +#[derive(Debug, serde::Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Impact { + Blocked, + WorkedAround, + Friction, +} + +#[derive(Debug, serde::Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Source { + User, + Agent, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct SupportSendArgs { + pub action: SendAction, + pub title: Option, + pub kind: Option, + pub description: Option, + pub impact: Option, + pub task: Option, + pub request_ids: Option>, + pub tool: Option, + pub error: Option, + pub suggestion: Option, + pub source: Option, + pub session: Option, + /// The agent sending it, as an object such as `{name, version, model}`. + // An object schema, not a bare `true`: MCP clients built on the TypeScript SDK refuse the whole tool list when + // a property's schema isn't an object. + #[schemars(with = "Option>")] + pub agent: Option, + pub idempotency_key: Option, +} + From 889e2de908fb93e2ea4bc11edccf02ce5e95223a Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:47:40 +1300 Subject: [PATCH 6/7] app/: the public MCP server's build tools (sc-8900): get_skill, list_builds, get_build, contact_sheet, get_snapshot, get_pr_changeset, snapshot_history, review, review_page, the comment tools, create_build, upload_snapshots, finalize_build and support_send, against today's answers; POST /api/v1/support/feedback; tools run in the request's Laravel context (until laravel/rust-framework#520); answers keep today's sorted keys --- app/Cargo.lock | 159 ++++ app/Cargo.toml | 5 +- app/src/domain/builds.rs | 53 ++ app/src/domain/changeset.rs | 23 +- app/src/domain/comments.rs | 20 +- app/src/domain/detail.rs | 60 +- app/src/domain/feedback.rs | 227 +++++ app/src/domain/mod.rs | 11 +- app/src/domain/reviews.rs | 36 +- app/src/domain/snapshots.rs | 28 + app/src/events.rs | 7 + app/src/http/api/builds.rs | 19 +- app/src/http/api/mod.rs | 2 + app/src/http/api/support.rs | 47 + app/src/lib.rs | 5 + app/src/mcp/args.rs | 1 - app/src/mcp/context.rs | 25 + app/src/mcp/mod.rs | 1654 +++++++++++++++++++++++++++++++++++ app/tests/mcp.rs | 446 ++++++++++ 19 files changed, 2779 insertions(+), 49 deletions(-) create mode 100644 app/src/domain/feedback.rs create mode 100644 app/src/http/api/support.rs create mode 100644 app/src/mcp/context.rs create mode 100644 app/src/mcp/mod.rs create mode 100644 app/tests/mcp.rs diff --git a/app/Cargo.lock b/app/Cargo.lock index d877b816..8ade652e 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -797,6 +797,40 @@ dependencies = [ "cmov", ] +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.10", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.10", +] + [[package]] name = "deranged" version = "0.5.9" @@ -1040,6 +1074,21 @@ dependencies = [ "windows-sys 0.101.0", ] +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.34" @@ -1113,6 +1162,7 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ + "futures-channel", "futures-core", "futures-io", "futures-macro", @@ -1538,6 +1588,12 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -1585,6 +1641,25 @@ dependencies = [ "quick-error", ] +[[package]] +name = "include_dir" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd" +dependencies = [ + "include_dir_macros", +] + +[[package]] +name = "include_dir_macros" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75" +dependencies = [ + "proc-macro2", + "quote", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -2940,6 +3015,12 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -3342,6 +3423,57 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rmcp" +version = "3.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc4fa9a7558c480e1817c0f02e9a73782001ac1f47fb9d26cc073915963282ea" +dependencies = [ + "async-trait", + "base64 0.23.1", + "bytes", + "chrono", + "futures", + "http", + "http-body", + "http-body-util", + "indexmap", + "jiff 1.1.0", + "libc", + "pastey", + "percent-encoding", + "pin-project-lite", + "rand 0.10.4", + "rmcp-macros", + "schemars", + "serde", + "serde_json", + "sha2 0.11.3", + "sse-stream", + "thiserror", + "tokio", + "tokio-stream", + "tokio-util", + "tower-service", + "tracing", + "unicode-general-category", + "unicode-normalization", + "uuid", +] + +[[package]] +name = "rmcp-macros" +version = "3.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43c1bf063ba32333267a8bc282ec33ae0edf56bf74890118cb0c7bf910a7a1c0" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "serde_json", + "syn 3.0.10", +] + [[package]] name = "rustc-demangle" version = "0.1.28" @@ -3515,6 +3647,7 @@ version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ + "chrono", "dyn-clone", "ref-cast", "schemars_derive", @@ -3979,6 +4112,19 @@ dependencies = [ "uuid", ] +[[package]] +name = "sse-stream" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4" +dependencies = [ + "bytes", + "futures-util", + "http-body", + "http-body-util", + "pin-project-lite", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -4223,6 +4369,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "libc", "pin-project-lite", "tokio", ] @@ -4421,6 +4568,12 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -4544,22 +4697,28 @@ name = "visualci-app" version = "0.0.0" dependencies = [ "axum", + "base64 0.22.1", "globset", "hex", "hmac 0.12.1", "image", + "include_dir", "laravel-rust", "oauth-provider", "oauth-provider-laravel", "regex", "reqwest 0.12.28", + "rmcp", "rusty-s3", + "schemars", "serde", "serde_json", "sha2 0.10.9", "snapshot-diff", "tokio", + "tower", "tracing", + "url", "visualci-core", ] diff --git a/app/Cargo.toml b/app/Cargo.toml index 76846805..805dbec1 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -33,7 +33,7 @@ hmac = "0.12" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" -tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } rusty-s3 = "0.12" @@ -44,12 +44,13 @@ include_dir = "0.7" rmcp = { version = "3.12", features = ["server", "transport-streamable-http-server", "macros"] } base64 = "0.22" tower = { version = "0.5", features = ["util"] } +url = "2" +regex = "1" # VisualCI's own crates, shared with the CLI. visualci-core = { path = "../crates/visualci-core" } snapshot-diff = { path = "../crates/snapshot-diff" } [dev-dependencies] -regex = "1" [profile.dev] debug = "line-tables-only" diff --git a/app/src/domain/builds.rs b/app/src/domain/builds.rs index f5b7f3b3..907a46bb 100644 --- a/app/src/domain/builds.rs +++ b/app/src/domain/builds.rs @@ -380,3 +380,56 @@ pub fn environment_info_for(build: &Build, member: bool) -> serde_json::Value { _ => serde_json::Value::Null, } } + +/// A project's build by number (`8` or `#8`) or id. +/// +/// # Errors +/// On a database error. +pub async fn find_by_ref(project_id: i64, reference: &str) -> laravel::Result> { + if let Ok(number) = reference.trim_start_matches('#').parse::() { + return Build::query().filter(Build::project_id.eq(project_id) & Build::number.eq(number)).first().await; + } + let Ok(pid) = laravel::str::Uuid::parse_str(reference) else { return Ok(None) }; + Build::query().filter(Build::project_id.eq(project_id) & Build::pid.eq(pid)).first().await +} + +/// A project's newest builds, newest first. +/// +/// # Errors +/// On a database error. +pub async fn recent(project_id: i64, limit: u64) -> laravel::Result> { + Build::query().filter(Build::project_id.eq(project_id)).order_by(Build::id.desc()).limit(limit).get().await +} + +/// The build once it can be reviewed: straight after a run it may still be comparing, so it's waited for up to +/// `timeout`. +/// +/// # Errors +/// `Ok(Err(message))` for a build that isn't finalized, failed, or is still comparing at the deadline; `Err` on a +/// database error. +pub async fn wait_until_reviewable( + build: Build, + timeout: std::time::Duration, +) -> laravel::Result> { + let deadline = std::time::Instant::now() + timeout; + let mut build = build; + loop { + match build.state.as_str() { + "completed" => return Ok(Ok(build)), + "receiving" => { + return Ok(Err(format!( + "build {} isn't finalized yet: run `visualci build finalize` first", + build.number + ))); + } + "failed" => return Ok(Err(format!("build {} failed, so it can't be reviewed", build.number))), + _ if std::time::Instant::now() >= deadline => { + return Ok(Err(format!("build {} is still comparing; try again in a moment", build.number))); + } + _ => { + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + build = Build::find_or_fail(build.id).await?; + } + } + } +} diff --git a/app/src/domain/changeset.rs b/app/src/domain/changeset.rs index a5844f2c..ae32ba41 100644 --- a/app/src/domain/changeset.rs +++ b/app/src/domain/changeset.rs @@ -58,18 +58,21 @@ pub enum Target { /// On a database error. pub async fn changeset(project: &Project, target: &Target) -> laravel::Result> { let project_id = project.id; - let all: Vec = match target { - Target::Pr(n) => { - db::query!("SELECT * FROM builds WHERE project_id = {project_id} AND mode = 'ci' AND pr_number = {n} ORDER BY id") + let all: Vec = + match target { + Target::Pr(n) => db::query!( + "SELECT * FROM builds WHERE project_id = {project_id} AND mode = 'ci' AND pr_number = {n} ORDER BY id" + ) + .select_as() + .await?, + Target::Branch(b) => { + db::query!( + "SELECT * FROM builds WHERE project_id = {project_id} AND mode = 'ci' AND branch = {b} ORDER BY id" + ) .select_as() .await? - } - Target::Branch(b) => { - db::query!("SELECT * FROM builds WHERE project_id = {project_id} AND mode = 'ci' AND branch = {b} ORDER BY id") - .select_as() - .await? - } - }; + } + }; let mut by_suite: BTreeMap> = BTreeMap::new(); for b in all { by_suite.entry(b.name.clone()).or_default().push(b); diff --git a/app/src/domain/comments.rs b/app/src/domain/comments.rs index cea0b099..65523701 100644 --- a/app/src/domain/comments.rs +++ b/app/src/domain/comments.rs @@ -241,7 +241,11 @@ pub async fn delete(c: Comment, author: &Author, admin: bool) -> laravel::Result /// /// # Errors /// On a database error. -pub async fn resolve(mut thread: CommentThread, resolved: bool, user_id: Option) -> laravel::Result { +pub async fn resolve( + mut thread: CommentThread, + resolved: bool, + user_id: Option, +) -> laravel::Result { let resolved_at = resolved.then(|| laravel::now().timestamp()); let resolved_by = if resolved { user_id } else { None }; update!(thread { resolved_at, resolved_by }).await?; @@ -252,7 +256,11 @@ pub async fn resolve(mut thread: CommentThread, resolved: bool, user_id: Option< /// /// # Errors /// On a database error. -pub async fn open_on(project_id: i64, branch: &str, snapshots: &[(String, String)]) -> laravel::Result> { +pub async fn open_on( + project_id: i64, + branch: &str, + snapshots: &[(String, String)], +) -> laravel::Result> { if snapshots.is_empty() { return Ok(vec![]); } @@ -286,7 +294,8 @@ pub async fn list( snapshot: Option<(&str, &str)>, include_resolved: bool, ) -> laravel::Result> { - let mut q = CommentThread::query().filter(CommentThread::project_id.eq(project_id) & CommentThread::branch.eq(branch)); + let mut q = + CommentThread::query().filter(CommentThread::project_id.eq(project_id) & CommentThread::branch.eq(branch)); if let Some((name, platform)) = snapshot { q = q.filter(CommentThread::snapshot_name.eq(name) & CommentThread::platform.eq(platform)); } @@ -362,5 +371,8 @@ pub async fn open_by_branch(project_id: i64) -> laravel::Result("branch").ok()?, r.try_get::("open").ok()?))).collect()) + Ok(rows + .iter() + .filter_map(|r| Some((r.try_get::("branch").ok()?, r.try_get::("open").ok()?))) + .collect()) } diff --git a/app/src/domain/detail.rs b/app/src/domain/detail.rs index 01495cae..23eef338 100644 --- a/app/src/domain/detail.rs +++ b/app/src/domain/detail.rs @@ -85,7 +85,11 @@ pub async fn review_detail(snapshot: &Snapshot, store: &BlobStore, context: usiz /// /// # Errors /// On a database error. -pub async fn earlier(snapshot: &Snapshot, build: &Build, number: Option) -> laravel::Result> { +pub async fn earlier( + snapshot: &Snapshot, + build: &Build, + number: Option, +) -> laravel::Result> { let (project_id, branch, before) = (build.project_id, build.branch.as_str(), build.number); let (name, platform) = (snapshot.name.as_str(), snapshot.platform.as_str()); let found: Option = db::query!( @@ -122,7 +126,8 @@ pub async fn review_detail_against( }; let (old, new) = (heads(earlier).await?, heads(snapshot).await?); let key = |r: &Page| r.head_image.clone().or_else(|| r.head_text.clone()).unwrap_or_default(); - let text = |rows: &[Page]| -> Vec { rows.iter().map(|r| r.head_text.clone().unwrap_or_default()).collect() }; + let text = + |rows: &[Page]| -> Vec { rows.iter().map(|r| r.head_text.clone().unwrap_or_default()).collect() }; let (old_text, new_text) = (text(&old), text(&new)); let has_text = old_text.iter().chain(&new_text).any(|t| !t.is_empty()); let ops = align_pages( @@ -146,7 +151,9 @@ pub async fn review_detail_against( let mut rows = Vec::new(); for (position, op) in ops.iter().enumerate() { rows.push(match *op { - PageOp::Unchanged { base: b, head: h } => row(position, "unchanged", "unchanged", Some(&old[b]), Some(&new[h]), None), + PageOp::Unchanged { base: b, head: h } => { + row(position, "unchanged", "unchanged", Some(&old[b]), Some(&new[h]), None) + } PageOp::Inserted { head: h } => row(position, "inserted", "changed", None, Some(&new[h]), None), PageOp::Removed { base: b } => row(position, "removed", "changed", Some(&old[b]), None, None), PageOp::Changed { base: b, head: h } => { @@ -168,7 +175,12 @@ pub async fn review_detail_against( detail_of(snapshot, store, context, &rows).await } -async fn detail_of(snapshot: &Snapshot, store: &BlobStore, context: usize, rows: &[Page]) -> laravel::Result { +async fn detail_of( + snapshot: &Snapshot, + store: &BlobStore, + context: usize, + rows: &[Page], +) -> laravel::Result { let mut pages = Vec::new(); let (mut base_texts, mut head_texts) = (Vec::new(), Vec::new()); // The images that still exist (retention deletes some), with their sizes where known. @@ -194,7 +206,11 @@ async fn detail_of(snapshot: &Snapshot, store: &BlobStore, context: usize, rows: let text_diff = if row.state == "unchanged" { Vec::new() } else { - visualci_core::text::page_diff(row.base_text.as_deref().unwrap_or(""), row.head_text.as_deref().unwrap_or(""), context) + visualci_core::text::page_diff( + row.base_text.as_deref().unwrap_or(""), + row.head_text.as_deref().unwrap_or(""), + context, + ) }; let expired = [&row.head_image, &row.base_image].into_iter().flatten().any(|s| !stored.contains_key(s)); let overlay = diff.as_ref().and_then(|d| d.overlay_blob.clone()).filter(|_| !expired); @@ -231,8 +247,11 @@ async fn detail_of(snapshot: &Snapshot, store: &BlobStore, context: usize, rows: detail.head = row.and_then(|r| r.head_text.clone()).filter(|_| snapshot.state != "removed"); detail }); - let moved = - if text.is_some() { Vec::new() } else { visualci_core::text::moved_lines(&ordered(base_texts), &ordered(head_texts)) }; + let moved = if text.is_some() { + Vec::new() + } else { + visualci_core::text::moved_lines(&ordered(base_texts), &ordered(head_texts)) + }; Ok(ReviewDetail { pages, moved, text }) } @@ -248,10 +267,15 @@ pub fn text_detail(format: Format, base: &str, head: &str, has_base: bool) -> Te (Format::Json, changes, more, None) } (Ok(_), None) => (Format::Json, Vec::new(), false, None), - (Ok(_), Some(Err(_))) => { - (Format::Json, Vec::new(), false, Some("the base wasn't valid JSON, so there are no changes by path".into())) + (Ok(_), Some(Err(_))) => ( + Format::Json, + Vec::new(), + false, + Some("the base wasn't valid JSON, so there are no changes by path".into()), + ), + (Err(e), _) => { + (Format::Text, Vec::new(), false, Some(format!("not valid JSON ({e}), compared as plain text"))) } - (Err(e), _) => (Format::Text, Vec::new(), false, Some(format!("not valid JSON ({e}), compared as plain text"))), }, other => (other, Vec::new(), false, None), }; @@ -305,7 +329,10 @@ pub async fn change_sizes(build_id: i64) -> laravel::Result("snapshot_id")?, ChangeSize { fraction: r.try_get("fraction")?, amount: r.try_get("amount")? }); + sizes.insert( + r.try_get::("snapshot_id")?, + ChangeSize { fraction: r.try_get("fraction")?, amount: r.try_get("amount")? }, + ); } let texts = db::query!( "SELECT p.snapshot_id, bt.body AS base_text, ht.body AS head_text FROM snapshot_pages p \ @@ -352,7 +379,8 @@ pub fn sort_for_review(list: &mut [Snapshot], sizes: &HashMap, match order { ReviewOrder::Name => list.sort_by(by_name), ReviewOrder::Change => list.sort_by(|a, b| { - let (sa, sb) = (sizes.get(&a.id).copied().unwrap_or_default(), sizes.get(&b.id).copied().unwrap_or_default()); + let (sa, sb) = + (sizes.get(&a.id).copied().unwrap_or_default(), sizes.get(&b.id).copied().unwrap_or_default()); state_rank(&a.state) .cmp(&state_rank(&b.state)) .then_with(|| sb.fraction.total_cmp(&sa.fraction)) @@ -369,7 +397,8 @@ pub const FLAKY_WINDOW: i64 = 8; #[must_use] pub fn flips(versions: &[String]) -> bool { let changes = versions.windows(2).filter(|w| w[0] != w[1]).count(); - let returned = versions.iter().enumerate().skip(1).any(|(i, v)| versions[i - 1] != *v && versions[..i - 1].contains(v)); + let returned = + versions.iter().enumerate().skip(1).any(|(i, v)| versions[i - 1] != *v && versions[..i - 1].contains(v)); changes >= 3 && returned } @@ -427,7 +456,10 @@ mod tests { fn json_detail_lists_changes_by_path() { let d = text_detail(Format::Json, "{\"price\": 10, \"x\": 1}", "{\"price\": 12, \"x\": 1}", true); assert_eq!(d.format, "json"); - assert_eq!(d.json_changes.iter().map(snapshot_text::PathChange::line).collect::>(), vec!["price: 10 → 12"]); + assert_eq!( + d.json_changes.iter().map(snapshot_text::PathChange::line).collect::>(), + vec!["price: 10 → 12"] + ); assert!(d.unified.contains("@@")); let bad = text_detail(Format::Json, "", "{oops", false); assert_eq!(bad.format, "text"); diff --git a/app/src/domain/feedback.rs b/app/src/domain/feedback.rs new file mode 100644 index 00000000..6a7d6386 --- /dev/null +++ b/app/src/domain/feedback.rs @@ -0,0 +1,227 @@ +//! Feedback from agents about VisualCI itself: Standard Support level 1 (standardsupport.dev, draft 0.5). One-way: +//! nobody replies, and there's no status for an agent to read back. The team reads it, as data. + +use std::sync::OnceLock; + +use laravel::db; +use laravel::model::create; +use regex::Regex; +use serde::Deserialize; + +use crate::models::Feedback; + +/// `request` comes from people, through the setup page's "What do you need from VisualCI?" and "Ask for something". +pub const KINDS: &[&str] = + &["bug", "crash", "wrong_result", "confusing", "missing_feature", "docs", "question", "request", "other"]; +pub const IMPACTS: &[&str] = &["blocked", "worked_around", "friction"]; +/// Pieces of feedback per account per day. +pub const DAILY_LIMIT: i64 = 50; +/// What `support_send` with action `feedback` needs, for error messages. +pub const NEEDS: &str = "title (3 to 200 characters), kind (bug, crash, wrong_result, confusing, missing_feature, docs, question, other) and description (1 to 4000 characters)"; +/// The fixed line every result carries. +pub const FOLLOW_UP: &str = "Nobody replies to feedback. The VisualCI team may email the user if it acts on this."; + +/// The fields of a report, as the spec names them. Everything is optional here so that a missing field gets a +/// message that says what to send, not a parse error. +#[derive(Debug, Default, Deserialize)] +pub struct Report { + pub title: Option, + pub kind: Option, + pub description: Option, + pub impact: Option, + pub task: Option, + pub request_ids: Option>, + pub tool: Option, + pub error: Option, + pub suggestion: Option, + pub category: Option, + pub source: Option, + pub session: Option, + pub agent: Option, + pub idempotency_key: Option, +} + +/// Who sent a report, filled in by the server: never taken from the call. +pub struct Sender { + pub user_id: Option, + pub project_id: Option, + /// `user:` or `project:`. + pub account: String, + /// `mcp` or `api`. + pub channel: &'static str, + pub client: Option, +} + +#[derive(Debug)] +pub enum FeedbackError { + /// The report is missing something or has a bad value: the message says what to send. + Invalid(String), + RateLimited(String), + Server(laravel::Error), +} + +impl std::fmt::Display for FeedbackError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Invalid(m) | Self::RateLimited(m) => f.write_str(m), + Self::Server(e) => write!(f, "{e}"), + } + } +} + +impl From for FeedbackError { + fn from(e: laravel::Error) -> Self { + Self::Server(e) + } +} + +fn len_ok(v: Option<&String>, max: usize) -> bool { + v.is_none_or(|s| s.chars().count() <= max) +} + +impl Report { + /// Every problem with the report, or none. + #[must_use] + pub fn problems(&self) -> Vec { + let mut out = Vec::new(); + match self.title.as_deref().map(str::trim) { + None | Some("") => out.push("title is missing".to_string()), + Some(t) if !(3..=200).contains(&t.chars().count()) => out.push("title must be 3 to 200 characters".into()), + _ => {} + } + match self.kind.as_deref() { + None => out.push("kind is missing".into()), + Some(k) if !KINDS.contains(&k) => out.push(format!("kind must be one of {}", KINDS.join(", "))), + _ => {} + } + match self.description.as_deref().map(str::trim) { + None | Some("") => out.push("description is missing".into()), + Some(d) if d.chars().count() > 4000 => out.push("description must be at most 4000 characters".into()), + _ => {} + } + if let Some(i) = self.impact.as_deref() + && !IMPACTS.contains(&i) + { + out.push(format!("impact must be one of {}", IMPACTS.join(", "))); + } + if let Some(s) = self.source.as_deref() + && !["user", "agent"].contains(&s) + { + out.push("source must be user or agent".into()); + } + for (name, value, max) in [ + ("task", &self.task, 200), + ("tool", &self.tool, 100), + ("error", &self.error, 4000), + ("suggestion", &self.suggestion, 2000), + ("category", &self.category, 50), + ("session", &self.session, 100), + ("idempotency_key", &self.idempotency_key, 64), + ] { + if !len_ok(value.as_ref(), max) { + out.push(format!("{name} must be at most {max} characters")); + } + } + if let Some(ids) = &self.request_ids + && (ids.len() > 10 || ids.iter().any(|i| i.len() > 200)) + { + out.push("request_ids takes at most 10 IDs".into()); + } + if self.agent.as_ref().is_some_and(|a| !a.is_object() || a.to_string().len() > 1000) { + out.push("agent must be an object such as {name, version, model}".into()); + } + out + } +} + +/// Tokens and keys we recognise, replaced before anything is stored. +fn scrub(text: &str) -> String { + static RE: OnceLock = OnceLock::new(); + let re = RE.get_or_init(|| { + Regex::new( + r"(?x) + \bvc[iu]_[A-Za-z0-9]{12,} + | \b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,} + | \bgithub_pat_[A-Za-z0-9_]{20,} + | \bsk-[A-Za-z0-9_-]{20,} + | \bxox[abprs]-[A-Za-z0-9-]{10,} + | \bAKIA[0-9A-Z]{16}\b + | (?i:bearer)\s+[A-Za-z0-9._~+/=-]{12,} + | -----BEGIN[A-Z\ ]*PRIVATE\ KEY-----[\s\S]*?-----END[A-Z\ ]*PRIVATE\ KEY-----", + ) + .expect("valid regex") + }); + re.replace_all(text, "[redacted]").into_owned() +} + +fn clean(v: Option) -> Option { + v.map(|s| scrub(s.trim())).filter(|s| !s.is_empty()) +} + +/// Store a report. A retry with the same idempotency key returns the first record, with `duplicate` true. +/// +/// # Errors +/// `Invalid` with what to send, `RateLimited` past the daily limit, or a database error. +pub async fn record(sender: Sender, report: Report) -> Result<(Feedback, bool), FeedbackError> { + let problems = report.problems(); + if !problems.is_empty() { + return Err(FeedbackError::Invalid(format!( + "support_send with action feedback needs {NEEDS}. Problem: {}.", + problems.join("; ") + ))); + } + let account = sender.account.as_str(); + if let Some(key) = &report.idempotency_key + && let Some(first) = + Feedback::query().filter(Feedback::account.eq(account) & Feedback::idempotency_key.eq(key)).first().await? + { + return Ok((first, true)); + } + let today: i64 = + db::query!("SELECT COUNT(*) FROM feedback WHERE account = {account} AND created_at > now() - interval '1 day'") + .scalar() + .await? + .unwrap_or(0); + if today >= DAILY_LIMIT { + return Err(FeedbackError::RateLimited(format!( + "This account has sent {DAILY_LIMIT} pieces of feedback in the last 24 hours, the limit. Try again \ + tomorrow, and carry on with the task." + ))); + } + let row = create!(Feedback { + pid: laravel::str::uuid7(), + user_id: sender.user_id, + project_id: sender.project_id, + account: sender.account.clone(), + title: clean(report.title).unwrap_or_default(), + kind: report.kind.unwrap_or_default(), + description: clean(report.description).unwrap_or_default(), + impact: report.impact, + task: clean(report.task), + request_ids: serde_json::json!(report.request_ids.unwrap_or_default()), + tool: clean(report.tool), + error: clean(report.error), + suggestion: clean(report.suggestion), + category: clean(report.category), + source: report.source.unwrap_or_else(|| "agent".into()), + session: clean(report.session), + agent: report.agent, + idempotency_key: report.idempotency_key, + channel: sender.channel, + client: sender.client, + }) + .await?; + tracing::info!(feedback = %row.pid, kind = %row.kind, title = %row.title, account = %row.account, "feedback received"); + crate::events::FeedbackReceived { feedback_id: row.id }.dispatch().await?; + Ok((row, false)) +} + +/// The result both the MCP tool and the endpoint return. +#[must_use] +pub fn result(row: &Feedback, duplicate: bool) -> serde_json::Value { + serde_json::json!({ + "feedback": { "id": format!("fb_{}", row.pid.simple()), "received_at": row.created_at.to_string() }, + "follow_up": FOLLOW_UP, + "duplicate": duplicate, + }) +} diff --git a/app/src/domain/mod.rs b/app/src/domain/mod.rs index 6578d4eb..fc869178 100644 --- a/app/src/domain/mod.rs +++ b/app/src/domain/mod.rs @@ -5,21 +5,22 @@ pub mod baselines; pub mod blobs; pub mod build_settings; pub mod builds; +pub mod changeset; +pub mod comments; pub mod compare; pub mod credits; +pub mod detail; pub mod diffs; pub mod environments; +pub mod feedback; pub mod groups; +pub mod inherited; pub mod lenient; pub mod matching; pub mod pages; pub mod processing; pub mod projects; pub mod renders; -pub mod snapshots; -pub mod detail; -pub mod comments; pub mod reviews; -pub mod inherited; +pub mod snapshots; pub mod summary; -pub mod changeset; diff --git a/app/src/domain/reviews.rs b/app/src/domain/reviews.rs index 71ff7704..71391576 100644 --- a/app/src/domain/reviews.rs +++ b/app/src/domain/reviews.rs @@ -30,7 +30,13 @@ impl Default for Via { /// its person ("Claude Code for Ada Lovelace"), or a project token ("a project token (GitHub Actions)"). VisualCI is /// mostly used by agents, so an agent's review never reads as the person's own. #[must_use] -pub fn by(source: &str, client: Option<&str>, agent: Option<&str>, token: Option<&str>, person: Option<&str>) -> String { +pub fn by( + source: &str, + client: Option<&str>, + agent: Option<&str>, + token: Option<&str>, + person: Option<&str>, +) -> String { let person = person.unwrap_or("someone"); let agent_name = client.or(agent).map(str::trim).filter(|a| !a.is_empty()); match source { @@ -71,7 +77,9 @@ impl Shown { /// On a database error. pub async fn shown(build_id: i64, limit: i64) -> laravel::Result> { let reviews: Vec = - db::query!("SELECT * FROM reviews WHERE build_id = {build_id} ORDER BY id DESC LIMIT {limit}").select_as().await?; + db::query!("SELECT * FROM reviews WHERE build_id = {build_id} ORDER BY id DESC LIMIT {limit}") + .select_as() + .await?; let user_ids: Vec = reviews.iter().filter_map(|r| r.user_id).collect(); let people: std::collections::HashMap = if user_ids.is_empty() { std::collections::HashMap::new() @@ -134,7 +142,8 @@ pub async fn review( let open = super::comments::open_on(build.project_id, &build.branch, &keys).await?; if let Some(t) = open.first() { let line = super::comments::first_line(t.id).await?; - let more = if open.len() > 1 { format!(" (and {} more open threads)", open.len() - 1) } else { String::new() }; + let more = + if open.len() > 1 { format!(" (and {} more open threads)", open.len() - 1) } else { String::new() }; let on = match t.build_id { Some(id) if id != build.id => { format!(" on build #{}", Build::find(id).await?.map(|b| b.number).unwrap_or_default()) @@ -150,7 +159,9 @@ pub async fn review( } let ids: Vec = targets.iter().map(|s| s.id).collect(); if !ids.is_empty() { - db::query!("UPDATE snapshots SET review = {verdict}, updated_at = now() WHERE id IN ({...ids})").update().await?; + db::query!("UPDATE snapshots SET review = {verdict}, updated_at = now() WHERE id IN ({...ids})") + .update() + .await?; } let note = note.map(str::trim).filter(|n| !n.is_empty()).map(|n| n.chars().take(2000).collect::()); let review = create!(Review { @@ -168,7 +179,8 @@ pub async fn review( let mut skipped = 0; if verdict == "approved" { // Each approved snapshot is a baseline for this branch (and environment, for screenshots) from now on. - let fresh: Vec<&Snapshot> = targets.iter().filter(|s| s.review.as_deref() != Some("approved")).copied().collect(); + let fresh: Vec<&Snapshot> = + targets.iter().filter(|s| s.review.as_deref() != Some("approved")).copied().collect(); skipped = super::baselines::record(&build, &fresh, user_id, Some(review.id), "review").await?; } else { // Rejecting what was approved withdraws the baselines that approval made. @@ -206,7 +218,8 @@ pub async fn supersede_older(build: &Build) -> laravel::Result> { if !matches!(build.review_state.as_str(), "approved" | "rejected") || build.parent_commits.is_empty() { return Ok(Vec::new()); } - let (id, project_id, name, environment) = (build.id, build.project_id, build.name.as_str(), build.environment.as_str()); + let (id, project_id, name, environment) = + (build.id, build.project_id, build.name.as_str(), build.environment.as_str()); let parents: Vec = build.parent_commits.to_vec(); let rows = db::query!( "UPDATE builds SET review_state = 'superseded', superseded_by_build_id = {id}, updated_at = now() \ @@ -282,10 +295,15 @@ pub async fn page_action( }; update!(page { state: new_state }).await?; let id = snapshot.id; - let remaining = SnapshotPage::query().filter(SnapshotPage::snapshot_id.eq(id) & SnapshotPage::state.eq("changed")).count().await?; + let remaining = SnapshotPage::query() + .filter(SnapshotPage::snapshot_id.eq(id) & SnapshotPage::state.eq("changed")) + .count() + .await?; if remaining == 0 && snapshot.state == "changed" { - let ignored = - SnapshotPage::query().filter(SnapshotPage::snapshot_id.eq(id) & SnapshotPage::state.eq("ignored")).count().await?; + let ignored = SnapshotPage::query() + .filter(SnapshotPage::snapshot_id.eq(id) & SnapshotPage::state.eq("ignored")) + .count() + .await?; let state = if ignored > 0 { "ignored" } else { "unchanged" }; db::query!("UPDATE snapshots SET state = {state}, updated_at = now() WHERE id = {id}").update().await?; } diff --git a/app/src/domain/snapshots.rs b/app/src/domain/snapshots.rs index bbcedef4..2eb97043 100644 --- a/app/src/domain/snapshots.rs +++ b/app/src/domain/snapshots.rs @@ -252,3 +252,31 @@ pub fn is_change(snapshot: &Snapshot) -> bool { pub fn own_ignore_rules(snapshot: &Snapshot) -> IgnoreRules { serde_json::from_value(snapshot.ignore_rules.clone()).unwrap_or_default() } + +/// The build's snapshots that `review`'s `only` picks: its `added` or `changed` ones, or the `matching` changes (made +/// only of changes a merged pull request approved). The visualci.yml item is never picked. +/// +/// # Errors +/// `Ok(Err(message))` for another `only`, or when nothing is picked; `Err` on a database error. +pub async fn picked_by(build_id: i64, only: &str) -> laravel::Result, String>> { + if !matches!(only, "added" | "changed" | "matching") { + return Ok(Err(format!("only must be added, changed or matching, not {only:?}"))); + } + let ids: Vec = of_build(build_id) + .await? + .into_iter() + .filter(|s| !is_config_item(s) && !s.sourced) + .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 Ok(Err(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(Ok(ids)) +} diff --git a/app/src/events.rs b/app/src/events.rs index 240df212..13a42c96 100644 --- a/app/src/events.rs +++ b/app/src/events.rs @@ -26,3 +26,10 @@ pub struct BuildStoppedForCredits { pub build_id: i64, pub organization_id: i64, } + +/// An agent or a person sent feedback about VisualCI (`support_send`, the API's feedback endpoint): the team hears +/// about it by email, once. +#[derive(laravel::event::Event, Clone, Debug)] +pub struct FeedbackReceived { + pub feedback_id: i64, +} diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index e275a697..6967c417 100644 --- a/app/src/http/api/builds.rs +++ b/app/src/http/api/builds.rs @@ -89,7 +89,12 @@ impl BuildResponse { /// /// # Errors /// On a database error. - pub async fn with_blocked(mut self, build: &Build, project: &Project, organization: &Organization) -> laravel::Result { + pub async fn with_blocked( + mut self, + build: &Build, + project: &Project, + organization: &Organization, + ) -> laravel::Result { use crate::domain::{credits, processing::OUT_OF_CREDITS}; let stopped = build.error_code.as_deref() == Some(OUT_OF_CREDITS); if !stopped && build.state != "receiving" { @@ -138,7 +143,9 @@ pub async fn create(auth: Result, Body(params): Body, Params(pid): Params) async { let ApiProject { project, organization, .. } = auth?; let build = own_build(&project, pid).await?; - Ok(BuildResponse::new(&build, &project, &organization).with_blocked(&build, &project, &organization).await?) + Ok(BuildResponse::new(&build, &project, &organization) + .with_blocked(&build, &project, &organization) + .await?) } .await, ) @@ -264,7 +273,9 @@ pub async fn finalize( } // The job may have run already (a synchronous queue): answer with the build as it is now. let build = Build::find(build.id).await?.unwrap_or(build); - Ok(BuildResponse::new(&build, &project, &organization).with_blocked(&build, &project, &organization).await?) + Ok(BuildResponse::new(&build, &project, &organization) + .with_blocked(&build, &project, &organization) + .await?) } .await, ) diff --git a/app/src/http/api/mod.rs b/app/src/http/api/mod.rs index 90889b8c..766117f8 100644 --- a/app/src/http/api/mod.rs +++ b/app/src/http/api/mod.rs @@ -3,6 +3,7 @@ //! is a 422 `{"error": "invalid body: …"}`. pub mod builds; +pub mod support; use axum::extract::FromRequestParts; use axum::http::StatusCode; @@ -19,6 +20,7 @@ pub fn routes(route: &mut Router) { }); route.get("/v1/whoami", crate::auth::whoami); builds::routes(route); + route.post("/v1/support/feedback", support::feedback); route.fallback(async || laravel::abort(404)); } diff --git a/app/src/http/api/support.rs b/app/src/http/api/support.rs new file mode 100644 index 00000000..a528ca65 --- /dev/null +++ b/app/src/http/api/support.rs @@ -0,0 +1,47 @@ +//! `POST /api/v1/support/feedback`: the same feedback as MCP's `support_send`, for agents that use the API. + +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use serde_json::json; + +use super::ApiError; +use crate::auth::Principal; +use crate::domain::feedback::{self, FeedbackError}; + +pub async fn feedback( + principal: Result, + headers: axum::http::HeaderMap, + axum::Json(report): axum::Json, +) -> Response { + let Ok(principal) = principal else { + let token = headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(str::trim) + .unwrap_or_default(); + return ApiError::unauthorized(if token.starts_with("vcu_") { + "invalid token" + } else { + "a personal access token or a project token is required" + }) + .into_response(); + }; + let (user_id, project_id, account) = match &principal { + Principal::User { user, .. } => (Some(user.id), None, format!("user:{}", user.id)), + Principal::Project { project_id, .. } => (None, Some(*project_id), format!("project:{project_id}")), + }; + let client = headers + .get(axum::http::header::USER_AGENT) + .and_then(|v| v.to_str().ok()) + .map(|s| s.chars().take(200).collect()); + let sender = feedback::Sender { user_id, project_id, account, channel: "api", client }; + match feedback::record(sender, report).await { + Ok((row, duplicate)) => axum::Json(feedback::result(&row, duplicate)).into_response(), + Err(FeedbackError::Invalid(m)) => ApiError::bad_request(m).into_response(), + Err(FeedbackError::RateLimited(m)) => { + (StatusCode::TOO_MANY_REQUESTS, axum::Json(json!({ "error": m }))).into_response() + } + Err(FeedbackError::Server(e)) => ApiError::server(&e).into_response(), + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 9cc13675..f68e2118 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -11,10 +11,12 @@ pub mod heartbeat; pub mod http; pub mod jobs; pub mod listeners; +pub mod mcp; pub mod models; pub mod notify; #[path = "../database/seeders/mod.rs"] pub mod seeders; +pub mod skills; pub mod storage; pub mod testing; @@ -62,6 +64,9 @@ pub fn configure() -> ApplicationBuilder { .routes(|route| { route.post("/webhooks/stripe", billing::webhook::handle); route.get("/status", http::status::status); + // MCP clients: a person's OAuth token (the guard joins with the OAuth server, #57) or a personal + // or project token. + route.any("/mcp", mcp::handle); }) .health("/up"); }) diff --git a/app/src/mcp/args.rs b/app/src/mcp/args.rs index 6dfc5065..85bf9c2d 100644 --- a/app/src/mcp/args.rs +++ b/app/src/mcp/args.rs @@ -435,4 +435,3 @@ pub struct SupportSendArgs { pub agent: Option, pub idempotency_key: Option, } - diff --git a/app/src/mcp/context.rs b/app/src/mcp/context.rs new file mode 100644 index 00000000..6ce257bb --- /dev/null +++ b/app/src/mcp/context.rs @@ -0,0 +1,25 @@ +//! Running MCP tools inside Laravel's request context. +//! +//! rmcp's Streamable HTTP service runs each tool call on a task of its own, where Laravel's task-local context (the +//! database connection, the container, the config) is gone. The `/mcp` handler puts the request's context into the +//! HTTP request's extensions ([`carry`]), and `call_tool` runs the tool inside it ([`of`]). +//! +//! A workaround until a framework release mounts a tower service on a route with the context in place +//! (laravel/rust-framework#520, `routing::service`). Once that's released, this module goes and `/mcp` mounts rmcp's +//! service directly. + +use laravel::context::Context; +use rmcp::service::{RequestContext, RoleServer}; + +/// Put the current Laravel context into the request, for the tool calls rmcp makes from it. +pub fn carry(request: &mut axum::extract::Request) { + if let Some(context) = Context::current() { + request.extensions_mut().insert(context); + } +} + +/// The Laravel context of the HTTP request an MCP call came in on. +#[must_use] +pub fn of(rc: &RequestContext) -> Option { + rc.extensions.get::().and_then(|p| p.extensions.get::().cloned()) +} diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs new file mode 100644 index 00000000..99484ef6 --- /dev/null +++ b/app/src/mcp/mod.rs @@ -0,0 +1,1654 @@ +//! The MCP server at `/mcp` (Streamable HTTP, stateless), for coding agents. It can do everything the web app and +//! the CI API can, except buy credits (a person adds a card and decides what to spend): organizations, projects and +//! their settings, project tokens, builds (create, upload, finalize), the comparison of each snapshot page by page +//! (base, head and diff images, regions, text diffs), snapshot history, and reviews, down to single pages. +//! +//! Who a request acts for is an [`auth::Principal`](crate::auth::Principal): a person (an MCP client's OAuth token, or +//! a personal access token `vcu_...`) or a project token (`vci_...`, that one project). + +pub mod args; +pub mod context; +pub mod images; +pub mod schema; + +use std::sync::OnceLock; + +use axum::response::{IntoResponse, Response}; +use base64::Engine; +use rmcp::{ + ErrorData, ServerHandler, + handler::server::{router::tool::ToolRouter, wrapper::Parameters}, + model::{CallToolResult, ContentBlock as Content, Implementation, ServerCapabilities, ServerConfig}, + service::{RequestContext, RoleServer}, + tool, tool_handler, tool_router, + transport::streamable_http_server::{ + StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager, + }, +}; +use serde_json::json; +use tower::ServiceExt; + +use self::args::*; +use crate::auth::{Principal, Role}; +use crate::domain::{self, build_settings::BuildSettings, builds::Invalid, comments, detail, snapshots as snaps}; +use crate::http::api::builds::{BuildResponse, app_url, renderer_version}; +use crate::models::{Build, Organization, Project, Snapshot}; +use crate::storage::BlobStore; + +const INSTRUCTIONS: &str = "VisualCI compares the PDFs, screenshots and images a test suite produces with approved \ +baselines, page by page. After a CI run: `list_builds`, then `get_build` for the changed snapshots, then \ +`get_snapshot` to look at a changed snapshot's pages (base, head and diff images, the changed regions, and the page's \ +text diff). Fix the code when a change is a regression. Approve with `review` (or `review_page` for one page) only \ +when the person you work for asked for the change. You can also run a comparison yourself (`create_build`, \ +`upload_snapshots`, `finalize_build`), manage organizations, projects, settings and tokens, and read each organization's plan and usage. \ +To set VisualCI up in a CI provider or test tool, or write visualci.yml, read the matching skill with `get_skill` first. Choosing a plan and paying are left to a person. Projects are named `org/project`; with a project token you can leave `project` out. \ +`whoami` lists the newest builds waiting for a review (`list_builds` with `waiting_for_review` lists a project's): \ +on a repository that pushes straight to main, review your push's build there. \ +When something about VisualCI got in your way (a confusing error, a missing feature, a bug you worked around), send it \ +with support_send, action feedback."; + +/// At most this many pages' images go into one `get_snapshot` answer, unless pages are named. +const DEFAULT_IMAGE_PAGES: usize = 3; +/// At most this many bytes of files in one `upload_snapshots` call (after base64 decoding). +const MAX_UPLOAD_BYTES: usize = 64 * 1024 * 1024; + +#[derive(Clone)] +pub struct VisualCi { + tool_router: ToolRouter, +} + +impl Default for VisualCi { + fn default() -> Self { + Self::new() + } +} + +/// An enum's snake_case name, as the spec spells the choices. +fn choice(v: Option<&T>) -> Option { + v.and_then(|v| serde_json::to_value(v).ok()).and_then(|v| v.as_str().map(str::to_string)) +} + +fn tool_error(message: impl Into) -> CallToolResult { + CallToolResult::error(vec![Content::text(message.into())]) +} + +fn internal(e: impl std::fmt::Display) -> ErrorData { + ErrorData::internal_error(e.to_string(), None) +} + +/// A JSON value with every object's keys in order. This app's JSON maps keep insertion order, and agents (and the +/// golden files) read the answers as they've always been: keys sorted. +fn sorted(value: serde_json::Value) -> serde_json::Value { + match value { + serde_json::Value::Object(map) => { + let mut entries: Vec<(String, serde_json::Value)> = map.into_iter().collect(); + entries.sort_by(|a, b| a.0.cmp(&b.0)); + serde_json::Value::Object(entries.into_iter().map(|(k, v)| (k, sorted(v))).collect()) + } + serde_json::Value::Array(items) => serde_json::Value::Array(items.into_iter().map(sorted).collect()), + other => other, + } +} + +/// A tool's structured answer, keys sorted ([`sorted`]). +fn structured(value: serde_json::Value) -> CallToolResult { + CallToolResult::structured(sorted(value)) +} + +/// A domain call's client mistake as a tool error, the server's as an internal error. +fn outcome(r: domain::builds::Outcome) -> Result, ErrorData> { + match r { + Ok(v) => Ok(Ok(v)), + Err(Ok(Invalid::Message(m) | Invalid::Conflict(m))) => Ok(Err(tool_error(m))), + Err(Err(e)) => Err(internal(e)), + } +} + +/// Who sent the request (the handler put it in the HTTP request's extensions). +fn principal_of(rc: &RequestContext) -> Option { + rc.extensions.get::().and_then(|p| p.extensions.get::().cloned()) +} + +fn user_id(rc: &RequestContext) -> Option { + principal_of(rc).and_then(|p| p.user().map(|u| u.id)) +} + +/// Kind, fingerprint and content type of an uploaded file, as the CLI works them out. +fn classify(filename: Option<&str>, bytes: &[u8]) -> Result<(&'static str, String, &'static str), String> { + if bytes.starts_with(b"%PDF") { + return Ok(("document", visualci_core::pdf::fingerprint_bytes(bytes).document, "application/pdf")); + } + let ext = filename.and_then(|f| f.rsplit('.').next()).unwrap_or("").to_ascii_lowercase(); + let image_type = match ext.as_str() { + "png" => Some("image/png"), + "jpg" | "jpeg" => Some("image/jpeg"), + "webp" => Some("image/webp"), + _ if bytes.starts_with(b"\x89PNG") => Some("image/png"), + _ if bytes.starts_with(b"\xff\xd8\xff") => Some("image/jpeg"), + _ => None, + }; + if let Some(content_type) = image_type { + let fp = visualci_core::image_hash::fingerprint_bytes(bytes).map_err(|e| format!("decoding the image: {e}"))?; + return Ok(("image", fp, content_type)); + } + let format = visualci_core::snapshot_text::Format::detect(None, None, filename); + Ok(("text", visualci_core::sha256_hex(bytes), format.content_type())) +} + +/// `let Some(x) = ... else return tool_error` for the `Result, ErrorData>` helpers. +macro_rules! need { + ($e:expr) => { + match $e.await? { + Ok(v) => v, + Err(message) => return Ok(tool_error(message)), + } + }; +} + +/// `?` for a domain call that answers `Ok(Err(message))` for the caller's mistake. +macro_rules! refuse { + ($e:expr) => { + match $e.await.map_err(internal)? { + Ok(v) => v, + Err(message) => return Ok(tool_error(message)), + } + }; +} + +impl VisualCi { + #[must_use] + pub fn new() -> Self { + let mut tool_router = Self::tool_router(); + schema::normalize_router(&mut tool_router); + Self { tool_router } + } + + async fn organization_of(project: &Project) -> Result { + Organization::find_or_fail(project.organization_id).await.map_err(internal) + } + + /// The caller's role in a project's organization: a person's membership; a project token acts for its own project + /// as a member would (sends builds, reviews, comments), never as an admin (no tokens, settings or members: a CI + /// secret that leaks must not mint itself new tokens or loosen the project's checks). + async fn role_in(rc: &RequestContext, project: &Project) -> Result, ErrorData> { + match principal_of(rc) { + Some(p) => p.role_in(project).await.map_err(internal), + None => Ok(None), + } + } + + /// `Err(message)` unless the caller's role is at least `needed`. + async fn need_role( + rc: &RequestContext, + project: &Project, + needed: Role, + what: &str, + ) -> Result, ErrorData> { + let role = Self::role_in(rc, project).await?; + if role.is_some_and(|r| r >= needed) { + return Ok(Ok(())); + } + let who = match needed { + Role::Admin => "an admin", + Role::Member => "a member (not read-only)", + Role::Read => "a member", + }; + Ok(Err(format!( + "only {who} of the organization can {what}; you're {}", + role.map_or("not a member", Role::as_str) + ))) + } + + /// Why a project token can't approve in this project (its `tokens_can_approve` is off), else `None`. + fn tokens_may_not_approve(rc: &RequestContext, project: &Project) -> Option { + (matches!(principal_of(rc), Some(Principal::Project { .. })) && !project.tokens_can_approve).then(|| { + "this project keeps approving with people: a project token can't approve, accept a variant or ignore a \ + change (rejecting and commenting still work); a person approves in the web app, or with their own \ + token" + .to_string() + }) + } + + /// The project a tool works on: `org/project`, or the project token's own project. + async fn project(rc: &RequestContext, arg: Option<&str>) -> Result, ErrorData> { + let Some(principal) = principal_of(rc) else { return Ok(Err("missing token".into())) }; + match principal { + Principal::Project { project_id, .. } => { + let p = Project::find_or_fail(project_id).await.map_err(internal)?; + if let Some(arg) = arg { + let own = format!("{}/{}", Self::organization_of(&p).await?.slug, p.slug); + if arg != own && arg != p.slug { + return Ok(Err(format!("this project token is for {own}, not {arg}"))); + } + } + Ok(Ok(p)) + } + Principal::User { .. } => { + let Some(arg) = arg else { + return Ok(Err("name the project as `org/project` (list_organizations lists them)".into())); + }; + let Some((org_slug, project_slug)) = arg.split_once('/') else { + return Ok(Err(format!("name the project as `org/project`, not {arg:?}"))); + }; + let not_found = || Err(format!("no project {arg} that you can see")); + let Some(p) = crate::http::api::project_by_slugs(org_slug, project_slug).await.map_err(internal)? + else { + return Ok(not_found()); + }; + // A public project (the demo) can be read by anyone; writes still need a role (`need_role`). + if !p.public && principal.role_in(&p).await.map_err(internal)?.is_none() { + return Ok(not_found()); + } + Ok(Ok(p)) + } + } + } + + /// How a review was made besides its person, for "Approved by Claude Code for Ada". + fn via(rc: &RequestContext) -> domain::reviews::Via { + let parts = rc.extensions.get::(); + let header = parts + .and_then(|p| p.headers.get("x-agent")) + .and_then(|v| v.to_str().ok()) + .map(|v| v.trim().chars().take(100).collect::()) + .filter(|v| !v.is_empty()); + let peer = rc.peer.peer_info().map(|i| { + let c = &i.client_info; + format!("{} {}", c.name, c.version).trim().chars().take(100).collect::() + }); + let agent = header.or(peer).filter(|a| !a.is_empty()); + match principal_of(rc) { + Some(Principal::User { via: crate::auth::Via::OAuth { client_id }, .. }) => { + let client = parts.and_then(|p| p.extensions.get::()).map(|c| c.0.clone()); + domain::reviews::Via { source: "oauth", client: client.or(Some(client_id)), agent, token: None } + } + Some(Principal::User { via: crate::auth::Via::Token { name, .. }, .. }) => { + domain::reviews::Via { source: "personal_token", client: None, agent, token: Some(name) } + } + Some(Principal::Project { token_name, .. }) => { + domain::reviews::Via { source: "project_token", client: None, agent, token: Some(token_name) } + } + _ => domain::reviews::Via { source: "personal_token", client: None, agent, token: None }, + } + } + + /// Who's commenting: an agent (an MCP call), acting for its person or project token. + fn author(rc: &RequestContext) -> comments::Author { + let via = Self::via(rc); + comments::Author { + user_id: user_id(rc), + agent: Some(via.agent.or(via.client).unwrap_or_else(|| "an agent".to_string())), + } + } + + #[expect(dead_code, reason = "whoami, once the organization tools land (subdomains' #70)")] + /// Each project's branches with open comment threads: `[{project, branch, open}]`. + async fn open_threads(projects: &[Project]) -> Result, ErrorData> { + let mut out = Vec::new(); + for p in projects { + let org = Self::organization_of(p).await?.slug; + for (branch, open) in comments::open_by_branch(p.id).await.map_err(internal)? { + out.push(json!({ "project": format!("{org}/{}", p.slug), "branch": branch, "open": open })); + } + } + Ok(out) + } + + async fn find_build(project: &Project, build: &str) -> Result, ErrorData> { + domain::builds::find_by_ref(project.id, build).await.map_err(internal) + } + + /// The build's snapshot with this name: on the given platform, or on its only platform when none is given. The + /// error says which platforms the name has when it's ambiguous or the platform is wrong. Snapshots the build reads + /// from an earlier build count. + async fn find_snapshot(build: &Build, name: &str, platform: &str) -> Result, ErrorData> { + // An id from `get_build` names one snapshot of the build. + if let Ok(pid) = laravel::str::Uuid::parse_str(name) { + return Ok(snaps::in_build(build.id, pid) + .await + .map_err(internal)? + .ok_or_else(|| format!("no snapshot {name} in build {}", build.number))); + } + let all: Vec = + snaps::of_build(build.id).await.map_err(internal)?.into_iter().filter(|s| s.name == name).collect(); + if let Some(s) = all.iter().find(|s| s.platform == platform) { + return Ok(Ok(s.clone())); + } + let platforms: Vec<&str> = all.iter().map(|s| s.platform.as_str()).collect(); + Ok(match (platform.is_empty(), platforms.as_slice()) { + (_, []) => Err(format!("no snapshot {name:?} in build {}", build.number)), + (true, [_]) => Ok(all[0].clone()), + (true, many) => Err(format!( + "{name:?} is in build {} on several platforms ({}): pass platform", + build.number, + many.join(", ") + )), + (false, found) => Err(format!( + "{name:?} isn't in build {} on platform {platform:?}; it is on {}", + build.number, + found + .iter() + .map(|p| if p.is_empty() { "no platform".to_string() } else { format!("{p:?}") }) + .collect::>() + .join(", ") + )), + }) + } + + /// A build as the tools show it. `member` is false for someone outside the organization reading a public + /// project, who doesn't see where a local build ran. + async fn build_json(project: &Project, build: &Build, member: bool) -> Result { + let organization = Self::organization_of(project).await?; + let response = BuildResponse::new(build, project, &organization) + .with_blocked(build, project, &organization) + .await + .map_err(internal)?; + let mut v = serde_json::to_value(response).map_err(internal)?; + v["name"] = json!(build.name); + v["branch"] = json!(build.branch); + v["commit"] = json!(build.commit_sha); + v["pr_number"] = json!(build.pr_number); + v["mode"] = json!(build.mode); + // Whether `review` can act on it now (it has finished comparing; review also waits up to a minute). + v["reviewable"] = json!(domain::builds::reviewable(build)); + v["environment"] = json!(build.environment); + v["environment_info"] = domain::builds::environment_info_for(build, member); + v["created_at"] = json!(build.created_at.to_string()); + // Who reviewed it and how: a person in the web app, or an agent for its person, or a project token. + v["reviews"] = json!(domain::reviews::shown(build.id, 10).await.map_err(internal)?); + // A large suite's groups (sc-8868): which matched their baselines and were carried forward unchanged. + if let Some(groups) = domain::groups::summary(build).await.map_err(internal)? { + v["groups"] = groups; + } + Ok(v) + } + + #[expect(dead_code, reason = "whoami, once the organization tools land (subdomains' #70)")] + /// The newest builds of these projects whose changes wait for a review, at most 10: on a repository that pushes + /// straight to the default branch, nothing else would remind the agent that pushed. + /// A local build waits only for the person whose run it was (`user`; a project token sees none). + async fn waiting_for_review(reachable: &[Project], user: Option) -> Result, ErrorData> { + let ids: Vec = reachable.iter().map(|p| p.id).collect(); + if ids.is_empty() { + return Ok(Vec::new()); + } + let pending: Vec = Build::query() + .filter(Build::project_id.is_in(ids) & Build::review_state.eq("pending")) + .order_by(Build::id.desc()) + .limit(100) + .get() + .await + .map_err(internal)? + .into_iter() + .filter(|b| domain::builds::waits_for(b, user)) + .take(10) + .collect(); + let mut out = Vec::new(); + for b in pending { + let Some(project) = reachable.iter().find(|p| p.id == b.project_id) else { continue }; + let org = Self::organization_of(project).await?.slug; + out.push(json!({ + "project": format!("{org}/{}", project.slug), "build": b.number, "branch": b.branch, + "commit": b.commit_sha, + "url": format!("{}/{org}/{}/builds/{}", app_url(), project.slug, b.number), + })); + } + Ok(out) + } + + /// The build changed: its forge check, PR comment and live updates follow; and the older builds a review + /// superseded. + async fn changed(build: &Build) -> Result, ErrorData> { + crate::events::BuildChanged { build_id: build.id }.dispatch().await.map_err(internal)?; + let superseded = domain::reviews::supersede_older(build).await.map_err(internal)?; + for id in &superseded { + crate::events::BuildChanged { build_id: *id }.dispatch().await.map_err(internal)?; + } + Ok(superseded) + } +} + +/// The OAuth client's display name, when the request came through one (for "Approved by Claude Code for Ada"). +#[derive(Clone, Debug)] +pub struct ClientName(pub String); + +#[tool_router] +impl VisualCi { + #[tool( + description = "VisualCI's agent skills: setting VisualCI up in each CI provider and test tool, reviewing builds, local runs and visualci.yml. Without `name`, lists them; with it, returns that skill's SKILL.md.", + annotations(title = "Get a skill", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn get_skill(&self, Parameters(args): Parameters) -> Result { + let Some(name) = args.name else { + let list: Vec<_> = crate::skills::all() + .into_iter() + .map(|s| json!({ "name": s.name, "description": s.description })) + .collect(); + return Ok(structured(json!({ "skills": list }))); + }; + match crate::skills::get(&name) { + Some(skill) => Ok(CallToolResult::success(vec![Content::text(skill.text)])), + None => Ok(tool_error(format!("no skill {name}; call get_skill without a name to list them"))), + } + } + + #[tool( + description = "List a project's builds, newest first: number, name, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, counts and URL. waiting_for_review: only builds whose changes wait for a review.", + annotations(title = "List builds", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn list_builds( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let member = Self::role_in(&rc, &project).await?.is_some(); + let limit = usize::try_from(args.limit.unwrap_or(20).clamp(1, 100)).unwrap_or(20); + let mut list = Vec::new(); + for b in domain::builds::recent(project.id, 1000).await.map_err(internal)? { + if args.branch.as_ref().is_some_and(|br| *br != b.branch) { + continue; + } + if args.waiting_for_review == Some(true) && !domain::builds::waits_for(&b, user_id(&rc)) { + continue; + } + list.push(Self::build_json(&project, &b, member).await?); + if list.len() >= limit { + break; + } + } + Ok(structured(json!({ "builds": list }))) + } + + #[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. On a pull request's build, `on_main_unreviewed: true` marks a change that's the default branch's own unreviewed change (its newest build, still waiting for review, has it too), and `inherited` counts them: review those on main's build. `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( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let store = BlobStore::current().await.map_err(internal)?; + let org = Self::organization_of(&project).await?.slug; + let project_url = format!("{}/{org}/{}", app_url(), project.slug); + let build_url = format!("{project_url}/builds/{}", build.number); + let mut listed: Vec = snaps::of_build(build.id) + .await + .map_err(internal)? + .into_iter() + .filter(|s| args.include_unchanged || snaps::is_change(s) || s.state == "failed") + .collect(); + let sizes = detail::change_sizes(build.id).await.map_err(internal)?; + detail::sort_for_review(&mut listed, &sizes, args.order); + let elsewhere = domain::baselines::approved_elsewhere(build.id).await.map_err(internal)?; + let matching = domain::matching::of_build(build.id).await.map_err(internal)?; + let inherited = domain::inherited::of_build(&build, &project).await.map_err(internal)?; + let snapshot_url = |e: &domain::baselines::ApprovedElsewhere| { + format!("{project_url}/builds/{}/snapshots/{}", e.build, e.snapshot_id) + }; + // Long lists: a page of them (details only for those), with every listed snapshot grouped by state and the + // start of its name ("added: screenshots/landing/ ×110"). + let total = listed.len(); + let offset = args.offset.unwrap_or(0) as usize; + let limit = args.limit.unwrap_or(30).clamp(1, 200) as usize; + let paged = total > limit || offset > 0; + let mut groups: std::collections::BTreeMap<(String, String), usize> = std::collections::BTreeMap::new(); + if paged { + for s in &listed { + let prefix = s.name.rfind('/').map_or_else(String::new, |i| s.name[..=i].to_string()); + *groups.entry((s.state.clone(), prefix)).or_default() += 1; + } + } + let flaky = detail::flaky_in(&build).await.map_err(internal)?; + let mut items = Vec::new(); + for s in listed.into_iter().skip(offset).take(limit) { + let attention = snaps::is_change(&s) || s.state == "failed"; + let review_detail = if attention { + Some(detail::review_detail(&s, &store, detail::DEFAULT_CONTEXT).await.map_err(internal)?) + } else { + None + }; + let pages = review_detail.as_ref().map(|d| &d.pages); + let mut item = json!({ + "id": s.pid, "url": format!("{build_url}/snapshots/{}", s.pid), + "name": s.name, "platform": s.platform, "kind": s.kind, "state": s.state, "review": s.review, + "environment": s.environment, "matched_environment": s.matched_environment, + "error": s.error, + // How big the change is: the largest share of a page (or of the lines) that changed, and how many + // pixels (or lines). The list puts the biggest first. + "change": sizes.get(&s.id), + // The same new version was already approved on another branch: a hint, it approves nothing here. + "approved_elsewhere": elsewhere.get(&s.id).map(|e| { + let mut v = json!(e); + v["url"] = json!(snapshot_url(e)); + v + }), + "pages": pages.map(Vec::len), + "changed_pages": pages.map(|p| p.iter().filter(|p| p.state == "changed").count()), + "moved_lines": review_detail.as_ref().map_or(0, |d| d.moved.len()), + }); + if inherited.as_ref().is_some_and(|i| i.snapshot_ids.contains(&s.id)) { + // Not this pull request's change: the base build on the default branch has it too, unreviewed. + item["on_main_unreviewed"] = json!(true); + } + 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 snaps::is_change(&s) && 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); + } + if let Some(format) = snaps::text_format(&s) { + item["format"] = json!(format.as_str()); + if let Some(text) = review_detail.as_ref().and_then(|d| d.text.as_ref()) { + let lines = pages.and_then(|p| p.first()).map(|p| &p.text_diff); + item["lines_added"] = json!(lines.map_or(0, |l| l.iter().filter(|l| l.tag == "+").count())); + item["lines_removed"] = json!(lines.map_or(0, |l| l.iter().filter(|l| l.tag == "-").count())); + if text.format == "json" { + item["json_changes"] = json!(text.json_changes.len()); + } + } + } + items.push(item); + } + let mut out = Self::build_json(&project, &build, Self::role_in(&rc, &project).await?.is_some()).await?; + if let Some(base) = build.base_build_id { + out["base_build"] = json!(Build::find(base).await.map_err(internal)?.map(|b| b.number)); + } + // The visualci.yml the build was sent (null without one), and the CI mode it ran under. + out["config"] = json!(build.config); + // What changed, computed from the comparison ("invoice: page 1 changed (2 regions); 3 added"). + out["summary"] = json!(domain::summary::summary_line(&build).await.map_err(internal)?); + out["warnings"] = build.warnings.clone(); + out["ci_mode"] = json!(BuildSettings::new(&project, &build).ci_mode()); + if paged { + out["groups"] = json!( + groups + .into_iter() + .map(|((state, prefix), count)| json!({ "state": state, "prefix": prefix, "count": count })) + .collect::>() + ); + out["listed"] = json!(format!("{} to {} of {total}", (offset + 1).min(total), (offset + limit).min(total))); + out["next_offset"] = json!((offset + limit < total).then_some(offset + limit)); + } + out["snapshots"] = json!(items); + if let Some(i) = &inherited { + // "3 changes are already on main and unreviewed (build #77)": they're main's, not this pull request's. + out["inherited"] = i.json(); + } + // Open comment threads on this build's branch: each blocks approving its snapshot until it's resolved. + let threads = comments::list(project.id, &build.branch, None, false).await.map_err(internal)?; + if !threads.is_empty() { + out["open_comment_threads"] = json!(threads); + } + Ok(structured(out)) + } + + #[tool( + description = "Many snapshots of a build at a glance: one image with a grid of thumbnails (each snapshot's first page, the new version, or the old one for a removed snapshot), and the list of what's in it in the same order, left to right and top to bottom, with each one's name, state and link. For checking a build with many added or changed snapshots in a few calls; page through with offset. Text snapshots have no thumbnail: look at them with get_snapshot.", + annotations(title = "Contact sheet", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn contact_sheet( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let states: Vec = args + .states + .as_deref() + .unwrap_or("changed,added") + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(); + let mut all: Vec = snaps::of_build(build.id) + .await + .map_err(internal)? + .into_iter() + .filter(|s| s.kind != "text" && !snaps::is_config_item(s) && states.contains(&s.state)) + .collect(); + let sizes = detail::change_sizes(build.id).await.map_err(internal)?; + detail::sort_for_review(&mut all, &sizes, args.order); + let offset = args.offset.unwrap_or(0) as usize; + let limit = args.limit.unwrap_or(24).clamp(1, 48) as usize; + let page: Vec<&Snapshot> = all.iter().skip(offset).take(limit).collect(); + let store = BlobStore::current().await.map_err(internal)?; + let org = Self::organization_of(&project).await?.slug; + let build_url = format!("{}/{org}/{}/builds/{}", app_url(), project.slug, build.number); + let pages = domain::pages::of_many(None, &page).await.map_err(internal)?; + let mut images = Vec::with_capacity(page.len()); + let mut list = Vec::with_capacity(page.len()); + for (i, s) in page.iter().enumerate() { + let first = pages.get(&s.id).and_then(|p| p.iter().min_by_key(|p| p.position)); + let sha = first.and_then(|p| p.head_image.clone().or_else(|| p.base_image.clone())); + let bytes = match sha { + Some(sha) => store.get(&sha).await.ok(), + None => None, + }; + images.push(bytes); + list.push(json!({ + "n": offset + i + 1, "name": s.name, "platform": s.platform, "state": s.state, "review": s.review, + "change": sizes.get(&s.id), + "url": format!("{build_url}/snapshots/{}", s.pid), + })); + } + let columns = args.columns.unwrap_or(4).clamp(1, 8); + let header = json!({ + "build": build.number, + "total": all.len(), + "showing": format!("{} to {} of {}", if page.is_empty() { 0 } else { offset + 1 }, offset + page.len(), all.len()), + "columns": columns, + "next_offset": (offset + page.len() < all.len()).then_some(offset + page.len()), + "snapshots": list, + }); + let mut content = vec![Content::text(serde_json::to_string_pretty(&sorted(header)).map_err(internal)?)]; + if !images.is_empty() { + let (bytes, media_type) = images::contact_sheet(&images, columns, 1200); + content.push(Content::image(base64::engine::general_purpose::STANDARD.encode(bytes), media_type)); + } + Ok(CallToolResult::success(content)) + } + + #[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.", + annotations(title = "Get snapshot", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn get_snapshot( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let key = args.id.as_deref().unwrap_or(&args.name); + if key.is_empty() { + return Ok(tool_error("pass the snapshot's name (or its id from get_build)")); + } + let snapshot = need!(Self::find_snapshot(&build, key, &args.platform)); + let store = BlobStore::current().await.map_err(internal)?; + let settings = BuildSettings::new(&project, &build); + let earlier = match args.against.as_deref().map(str::trim) { + None | Some("" | "baseline") => None, + Some(other) => { + let number = match other { + "previous" => None, + n => match n.trim_start_matches('#').parse::() { + Ok(n) => Some(n), + Err(_) => return Ok(tool_error("against is baseline, previous, or an earlier build's number")), + }, + }; + match detail::earlier(&snapshot, &build, number).await.map_err(internal)? { + Some(found) => Some(found), + None => { + return Ok(tool_error(format!( + "{} has no {} on branch {} to compare with", + snapshot.name, + number.map_or("earlier build".to_string(), |n| format!("build #{n} before this one")), + build.branch + ))); + } + } + } + }; + 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 + } + None => detail::review_detail(&snapshot, &store, detail::DEFAULT_CONTEXT).await, + } + .map_err(internal)?; + let compared_with = match &earlier { + Some((b, _)) => json!({ "build": b.number, "note": "a view: review still compares with the baseline" }), + None => json!("baseline"), + }; + // Open threads on this snapshot of the branch, with the build each was drawn on. + let open_threads = comments::list(project.id, &build.branch, Some((&snapshot.name, &snapshot.platform)), false) + .await + .map_err(internal)?; + let org = Self::organization_of(&project).await?.slug; + let url = format!("{}/{org}/{}/builds/{}/snapshots/{}", app_url(), project.slug, build.number, snapshot.pid); + // Text, JSON and HTML: the unified diff and the JSON changes by path, with no images. + if let Some(text) = &review_detail.text { + let header = json!({ + "name": snapshot.name, "platform": snapshot.platform, "kind": snapshot.kind, "format": text.format, + "state": snapshot.state, "review": snapshot.review, "error": snapshot.error, "build": build.number, + "meta": snapshot.meta, "url": url, "note": text.note, "compared_with": compared_with, + "open_comment_threads": open_threads, + "base_lines": text.base_lines, "head_lines": text.head_lines, + "json_changes": (text.format == "json").then(|| text.json_changes.iter().map(visualci_core::snapshot_text::PathChange::line).collect::>()), + "json_changes_truncated": text.json_changes_truncated, + // The ignore rules applied to both sides, each with where it came from (file, test or project). + "ignore_rules": settings.applied_rules(&snapshot), + }); + let mut content = vec![Content::text(serde_json::to_string_pretty(&sorted(header)).map_err(internal)?)]; + let added = snapshot.state == "added"; + if !text.unified.is_empty() && !added { + content.push(Content::text(text.unified.clone())); + } else if added { + let head = review_detail + .pages + .first() + .map(|p| p.text_diff.iter().map(|l| l.text.as_str()).collect::>().join("\n")); + content.push(Content::text(format!( + "New snapshot, no baseline. Its content:\n{}", + head.unwrap_or_default() + ))); + } + // Either version as it was, on request: `images: head`, `base` or `all` (any snapshot, unchanged too). + let asked = args.images.as_deref(); + let side = |name: &str| asked == Some(name) || asked == Some("all"); + if side("head") + && !added + && let Some(head) = &text.head + { + content.push(Content::text(format!("This build's version:\n{head}"))); + } + if side("base") + && let Some(base) = &text.base + { + content.push(Content::text(format!("The baseline's version:\n{base}"))); + } + return Ok(CallToolResult::success(content)); + } + let (pages, moved) = (review_detail.pages, review_detail.moved); + + // Changed pages first; with none (an unchanged snapshot), the first pages, so any snapshot can be looked at. + let wanted: Vec = match &args.pages { + Some(p) => p.clone(), + None => { + let changed: Vec = pages + .iter() + .filter(|p| p.state == "changed") + .take(DEFAULT_IMAGE_PAGES) + .map(|p| p.position) + .collect(); + if changed.is_empty() { + pages.iter().take(DEFAULT_IMAGE_PAGES).map(|p| p.position).collect() + } else { + changed + } + } + }; + let which = args.images.as_deref().unwrap_or("all"); + let embed = |sha: &Option| sha.as_ref().and_then(|s| store.embed_url(s).ok()); + let summary: Vec = pages + .iter() + .map(|p| { + json!({ + "position": p.position, + "page": if snapshot.kind == "image" { None } else { p.head_index.or(p.base_index).map(|i| i + 1) }, + "op": p.op, "state": p.state, + "changed_pixels": p.diff.as_ref().map(|d| d.changed_pixels), + "changed_fraction": p.diff.as_ref().map(|d| d.changed_fraction), + // A resized page or screenshot: the diff covers the larger canvas, both aligned top-left, and the + // extra rows or columns count as changed. + "size_changed": p.diff.as_ref().map(|d| d.size_changed), + "base_size": p.base_size, + "head_size": p.head_size, + "regions": p.diff.as_ref().map(|d| &d.regions), + "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, + // Week-long links to the page's images, for putting them in a pull request comment or a report. + "embed_url": (!p.expired).then(|| { + json!({ "base": embed(&p.base_image), "head": embed(&p.head_image), "diff": embed(&p.overlay_image) }) + }), + }) + }) + .collect(); + let header = json!({ + "name": snapshot.name, "platform": snapshot.platform, "kind": snapshot.kind, "state": snapshot.state, + "review": snapshot.review, "error": snapshot.error, "build": build.number, "meta": snapshot.meta, + "url": url, + "compared_with": compared_with, + "open_comment_threads": open_threads, + "pages": summary, + "moved_lines": moved.iter().map(|m| json!({ "text": m.text, "from_page": m.from_page + 1, "to_page": m.to_page + 1 })).collect::>(), + }); + + let mut content = vec![Content::text(serde_json::to_string_pretty(&sorted(header)).map_err(internal)?)]; + if which != "none" { + let b64 = base64::engine::general_purpose::STANDARD; + for p in pages.iter().filter(|p| wanted.contains(&p.position) && !p.expired) { + // A screenshot or image is one picture: "page" is a PDF's word. + let label = if snapshot.kind == "image" { + "image".to_string() + } else { + p.head_index.or(p.base_index).map_or(String::new(), |i| format!("page {}", i + 1)) + }; + let sides: Vec<(&str, &Option)> = match which { + "diff" => vec![("diff", &p.overlay_image)], + "head" => vec![("head", &p.head_image)], + "base" => vec![("base", &p.base_image)], + _ => vec![("base", &p.base_image), ("head", &p.head_image), ("diff", &p.overlay_image)], + }; + let regions = (args.crop.as_deref() == Some("changed")) + .then(|| p.diff.as_ref().map(|d| d.regions.clone()).filter(|r| !r.is_empty())) + .flatten(); + for (kind, sha) in sides { + let Some(sha) = sha else { continue }; + let bytes = store.get(sha).await.map_err(internal)?; + let (bytes, media_type) = images::prepare( + &bytes, + regions.as_deref(), + args.max_width.unwrap_or(images::DEFAULT_MAX_WIDTH).clamp(100, 4000), + ); + let cropped = if regions.is_some() { ", cropped to the changes" } else { "" }; + content.push(Content::text(format!("{label} ({}), {kind}{cropped}:", p.op))); + content.push(Content::image(b64.encode(bytes), media_type)); + } + } + } + Ok(CallToolResult::success(content)) + } + + #[tool( + description = "Everything a pull request (or branch) changes, across all of its builds, against the baseline it forked from: each suite's added, changed and removed snapshots, with where review stands for each (approved, here or in an earlier build of the PR; pending; rejected; failed). A per-build diff can hide a change approved in an earlier build; this doesn't. Use it as the final self-check before asking for a merge: nothing should be pending or unexpected.", + annotations( + title = "Get PR changeset", + read_only_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn get_pr_changeset( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + use domain::changeset::{Target, changeset, json as changeset_json}; + let project = need!(Self::project(&rc, args.project.as_deref())); + let target = match (args.pr, args.branch) { + (Some(n), _) => Target::Pr(n), + (None, Some(b)) => Target::Branch(b), + (None, None) => return Ok(tool_error("name the pull request (`pr`) or a `branch`")), + }; + let suites = changeset(&project, &target).await.map_err(internal)?; + if suites.is_empty() { + return Ok(tool_error("no CI builds for that pull request or branch in this project")); + } + Ok(structured(changeset_json(&suites))) + } + + #[tool( + description = "One snapshot across recent builds, newest first: in each build its state (unchanged, changed, added, removed, failed) and review. Use it to find when a page started changing.", + annotations( + title = "Snapshot history", + read_only_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn snapshot_history( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let limit = usize::try_from(args.limit.unwrap_or(20).clamp(1, 200)).unwrap_or(20); + let recent: Vec = domain::builds::recent(project.id, 2000) + .await + .map_err(internal)? + .into_iter() + .filter(|b| args.branch.as_ref().is_none_or(|br| *br == b.branch)) + .take(limit) + .collect(); + let ids: Vec = recent.iter().map(|b| b.id).collect(); + let (name, platform) = (args.name.as_str(), args.platform.as_str()); + let found: Vec = if ids.is_empty() { + Vec::new() + } else { + laravel::db::query!( + "SELECT * FROM effective_snapshots WHERE build_id IN ({...ids}) AND name = {name} \ + AND platform = {platform}" + ) + .select_as() + .await + .map_err(internal)? + }; + let history: Vec = recent + .iter() + .map(|b| { + let s = found.iter().find(|s| s.build_id == b.id); + json!({ + "build": b.number, "branch": b.branch, "commit": b.commit_sha, "created_at": b.created_at.to_string(), + "state": s.map(|s| s.state.clone()), "review": s.and_then(|s| s.review.clone()), + }) + }) + .collect(); + Ok(structured(json!({ "name": args.name, "platform": args.platform, "history": history }))) + } + + #[tool( + description = "Approve or reject a build's changes, some snapshots' changes (`snapshots`), or only its new or only its changed snapshots (`only`). Approved snapshots become the baseline, and the pull request's VisualCI check updates. Approve only changes the person you work for asked for. A build that's still comparing (straight after a run) is waited for, up to a minute.", + annotations(title = "Review build", read_only_hint = false, destructive_hint = true, open_world_hint = false) + )] + async fn review( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Member, "review builds")); + if args.action == "approve" + && let Some(refused) = Self::tokens_may_not_approve(&rc, &project) + { + return Ok(tool_error(refused)); + } + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + // Straight after a run the build may still be comparing: wait for it rather than refusing. + let build = refuse!(domain::builds::wait_until_reviewable(build, std::time::Duration::from_secs(60))); + let ids = match (&args.snapshots, args.only.as_deref()) { + (Some(_), Some(_)) => return Ok(tool_error("pass `snapshots` or `only`, not both")), + (Some(names), None) => Some( + snaps::of_build(build.id) + .await + .map_err(internal)? + .into_iter() + .filter(|s| names.contains(&s.name)) + .map(|s| s.id) + .collect(), + ), + (None, Some(only)) => Some(refuse!(snaps::picked_by(build.id, only))), + (None, None) => None, + }; + if args.comment.is_some() && args.action != "reject" { + return Ok(tool_error("a comment goes with `reject`; to comment otherwise, use post_comment")); + } + // A review with a project token is recorded without a user. + let via = Self::via(&rc); + let rejected_ids = ids.clone(); + let build = refuse!(domain::reviews::review( + build.clone(), + user_id(&rc), + &via, + &args.action, + ids, + args.note.as_deref() + )); + if let Some(body) = &args.comment { + let author = Self::author(&rc); + let place = comments::Place { page: None, side: "head".into(), anchor: comments::Anchor::Image }; + for s in snaps::of_build(build.id).await.map_err(internal)? { + let named = rejected_ids.as_ref().is_none_or(|ids| ids.contains(&s.id)); + if named && snaps::is_change(&s) && !s.sourced { + refuse!(comments::start(&build, &s, &place, &author, body)); + } + } + } + let superseded = Self::changed(&build).await?; + let mut out = Self::build_json(&project, &build, true).await?; + if !superseded.is_empty() { + // The older pending builds this review covered. + out["superseded_builds"] = json!(superseded.len()); + } + Ok(structured(out)) + } + + #[tool( + description = "Comment threads on a build's branch: each with the build it was drawn on (`started_in_build`; its pin is on that build's image, and an open one still blocks approving the snapshot in newer builds), its snapshot, page, side (base or head), anchor (point, box or the whole image, in that image's pixels), whether it's resolved, and its comments with their authors (a person, or an agent and its name). Open threads only unless `include_resolved`. An open thread blocks approving its snapshot.", + annotations(title = "List comments", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn list_comments( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let snapshot = match &args.snapshot { + Some(key) => Some(need!(Self::find_snapshot(&build, key, &args.platform))), + None => None, + }; + let threads = comments::list( + project.id, + &build.branch, + snapshot.as_ref().map(|s| (s.name.as_str(), s.platform.as_str())), + args.include_resolved, + ) + .await + .map_err(internal)?; + Ok(structured(json!({ "branch": build.branch, "threads": threads }))) + } + + #[tool( + description = "Comment on a snapshot: start a thread pinned to a point or a box (in that image's pixels, like get_snapshot's regions) or the whole image of a page's head (new) or base (old) side, or reply in a thread (`thread`). Markdown. Use it to ask about a change you can't judge, or to say why you rejected one; a person's open thread on a snapshot stops `review` from approving it until someone resolves the thread. Replying reopens a resolved thread.", + annotations(title = "Post comment", read_only_hint = false, destructive_hint = false, open_world_hint = false) + )] + async fn post_comment( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + // Members only, as in the web app: an open thread blocks approving its snapshot, and its text reaches the + // members' agents, so nobody outside (a public project's visitors) or read-only may start or reopen one. + need!(Self::need_role(&rc, &project, Role::Member, "comment")); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let author = Self::author(&rc); + if let Some(thread) = &args.thread { + let Ok(pid) = laravel::str::Uuid::parse_str(thread) else { + return Ok(tool_error("thread is the thread's id")); + }; + let Some(t) = comments::thread(project.id, pid).await.map_err(internal)? else { + return Ok(tool_error(format!("no thread {thread} in this project"))); + }; + let c = refuse!(comments::reply(t, &author, &args.body)); + return Ok(structured(json!({ "comment": c.pid, "thread": pid }))); + } + let Some(key) = &args.snapshot else { + return Ok(tool_error("name the snapshot to start a thread on, or the `thread` to reply in")); + }; + let snapshot = need!(Self::find_snapshot(&build, key, &args.platform)); + let place = comments::Place { + page: args.page, + side: args.side.unwrap_or_else(|| "head".into()), + anchor: args.anchor.unwrap_or(comments::Anchor::Image), + }; + let t = refuse!(comments::start(&build, &snapshot, &place, &author, &args.body)); + Ok(structured(json!({ "thread": t.pid, "snapshot": t.snapshot_name, "branch": t.branch }))) + } + + #[tool( + description = "Edit one of your own comments (`body`, Markdown).", + annotations( + title = "Update comment", + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn update_comment( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Read, "change comments")); + let Some(body) = &args.body else { return Ok(tool_error("give the new `body`")) }; + let Ok(pid) = laravel::str::Uuid::parse_str(&args.comment) else { + return Ok(tool_error("comment is the comment's id")); + }; + let Some((c, _)) = comments::comment(project.id, pid).await.map_err(internal)? else { + return Ok(tool_error(format!("no comment {} in this project", args.comment))); + }; + let c = refuse!(comments::edit(c, &Self::author(&rc), body)); + Ok(structured(json!({ "comment": c.pid, "body": c.body }))) + } + + #[tool( + description = "Resolve a comment thread once its question is answered (or reopen it with `resolved: false`). Resolving the open threads on a snapshot lets `review` approve it.", + annotations( + title = "Resolve comment", + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn resolve_comment( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Member, "resolve comment threads")); + let Ok(pid) = laravel::str::Uuid::parse_str(&args.thread) else { + return Ok(tool_error("thread is the thread's id")); + }; + let Some(t) = comments::thread(project.id, pid).await.map_err(internal)? else { + return Ok(tool_error(format!("no thread {} in this project", args.thread))); + }; + let resolved = args.resolved.unwrap_or(true); + let t = comments::resolve(t, resolved, user_id(&rc)).await.map_err(internal)?; + Ok(structured(json!({ "thread": t.pid, "resolved": t.resolved_at.is_some() }))) + } + + #[tool( + description = "Delete a comment (your own; an organization admin can delete anyone's). A thread left with no comments goes too.", + annotations( + title = "Delete comment", + read_only_hint = false, + destructive_hint = true, + open_world_hint = false + ) + )] + async fn delete_comment( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Read, "change comments")); + let Ok(pid) = laravel::str::Uuid::parse_str(&args.comment) else { + return Ok(tool_error("comment is the comment's id")); + }; + let Some((c, _)) = comments::comment(project.id, pid).await.map_err(internal)? else { + return Ok(tool_error(format!("no comment {} in this project", args.comment))); + }; + let admin = Self::role_in(&rc, &project).await? == Some(Role::Admin); + let thread_gone = refuse!(comments::delete(c, &Self::author(&rc), admin)); + Ok(structured(json!({ "deleted": pid, "thread_deleted": thread_gone }))) + } + + #[tool( + description = "Review one changed page: `variant` keeps the new page as another accepted baseline next to the old one (both are fine, e.g. a page that legitimately renders two ways); `ignore` ignores this exact change, in this build and later ones.", + annotations(title = "Review page", read_only_hint = false, destructive_hint = true, open_world_hint = false) + )] + async fn review_page( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Member, "review builds")); + if let Some(refused) = Self::tokens_may_not_approve(&rc, &project) { + return Ok(tool_error(refused)); + } + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let snapshot = need!(Self::find_snapshot(&build, &args.name, &args.platform)); + let build = refuse!(domain::reviews::page_action( + snapshot, + build, + project.id, + args.position, + &args.action, + user_id(&rc) + )); + let superseded = Self::changed(&build).await?; + let mut out = Self::build_json(&project, &build, true).await?; + if !superseded.is_empty() { + // The older pending builds this review covered. + out["superseded_builds"] = json!(superseded.len()); + } + Ok(structured(out)) + } + + #[tool( + description = "Start a build, as CI does: then `upload_snapshots` and `finalize_build`. VisualCI compares it with the baseline from the branch's ancestors (or the default branch).", + annotations(title = "Create build", read_only_hint = false, destructive_hint = false, open_world_hint = false) + )] + async fn create_build( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Member, "send builds")); + let params = domain::builds::CreateParams { + commit: args.commit, + branch: args.branch, + pr_number: args.pr_number, + parent_commits: args.parent_commits, + mode: args.mode.unwrap_or_else(|| "ci".into()), + name: args.name.unwrap_or_else(|| "default".into()), + shard_total: args.shard_total.unwrap_or(1), + subset: args.subset, + nonce: args.nonce, + config: args.config, + environment: args.environment, + environment_info: None, + }; + domain::processing::expire_abandoned(Some(project.id)).await.map_err(internal)?; + let build = match outcome(domain::builds::create(&project, ¶ms, user_id(&rc)).await)? { + Ok(b) => b, + Err(refused) => return Ok(refused), + }; + Ok(structured(Self::build_json(&project, &build, true).await?)) + } + + #[tool( + description = "Add files to a build that's still receiving: PDFs, PNG/JPEG/WebP images, or text snapshots (plain text, JSON, HTML, serialized component trees; `format` or the file name's extension decides), base64. Files VisualCI has seen before aren't stored again. Up to 64 MB per call; call it as often as needed.", + annotations( + title = "Upload snapshots", + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn upload_snapshots( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Member, "send builds")); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + if args.files.is_empty() || args.files.len() > 1000 { + return Ok(tool_error("send 1 to 1000 files per call")); + } + let b64 = base64::engine::general_purpose::STANDARD; + let mut decoded = Vec::with_capacity(args.files.len()); + let mut total = 0usize; + for f in &args.files { + let bytes = match b64.decode(f.content_base64.trim()) { + Ok(b) => b, + Err(e) => return Ok(tool_error(format!("{}: content_base64 isn't base64: {e}", f.name))), + }; + total += bytes.len(); + if total > MAX_UPLOAD_BYTES { + return Ok(tool_error("more than 64 MB of files in one call: split them over several calls")); + } + let (kind, fingerprint, content_type) = match classify(f.filename.as_deref(), &bytes) { + Ok(c) => c, + Err(e) => return Ok(tool_error(format!("{}: {e}", f.name))), + }; + decoded.push((bytes, kind, fingerprint, content_type)); + } + let params: Vec = args + .files + .iter() + .zip(&decoded) + .map(|(f, (bytes, kind, fingerprint, content_type))| snaps::SnapshotParams { + name: f.name.clone(), + platform: f.platform.clone(), + kind: (*kind).to_string(), + fingerprint: fingerprint.clone(), + sha256: visualci_core::sha256_hex(bytes), + size: i64::try_from(bytes.len()).unwrap_or(i64::MAX), + content_type: (*content_type).to_string(), + threshold: f.threshold, + ignore_anti_aliasing: None, + engine: f.engine.clone(), + format: f.format.clone(), + meta: f.meta.clone().unwrap_or(serde_json::Value::Null), + ignore: f.ignore.clone(), + }) + .collect(); + if build.state != "receiving" { + return Ok(tool_error(format!("build {} is {}, not receiving snapshots", build.number, build.state))); + } + // Every file is checked before any is written. + for p in ¶ms { + if let Err(e) = p.validate() { + return Ok(tool_error(e)); + } + } + let settings = BuildSettings::new(&project, &build); + let version = renderer_version(); + let store = BlobStore::current().await.map_err(internal)?; + let mut out = Vec::new(); + for (p, (bytes, _, _, content_type)) in params.iter().zip(decoded) { + let r = refuse!(snaps::register(&build, &settings, &version, p)); + if r.needs_upload { + domain::blobs::put(&store, bytes, content_type).await.map_err(internal)?; + } + out.push(json!({ "name": r.snapshot.name, "platform": r.snapshot.platform, "stored": r.needs_upload })); + } + Ok(structured(json!({ "build": build.number, "snapshots": out }))) + } + + #[tool( + description = "Finish a build (or one shard of it): VisualCI renders and compares what was uploaded. Then poll `get_build` until its state is completed. A build that was sent no snapshots fails, unless allow_empty is true or empty_reason says why it has none (\"inputs unchanged\").", + annotations( + title = "Finalize build", + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn finalize_build( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Member, "send builds")); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let was_receiving = build.state == "receiving"; + let build = match args.empty_reason.as_deref() { + Some(reason) => match outcome(domain::builds::allow_empty_because(build, reason).await)? { + Ok(b) => b, + Err(refused) => return Ok(refused), + }, + None => build, + }; + let allow_empty = args.allow_empty.unwrap_or(false) || args.empty_reason.is_some(); + let build = match outcome(domain::builds::finalize_shard(build, args.shard, allow_empty).await)? { + Ok(b) => b, + Err(refused) => return Ok(refused), + }; + let build = if was_receiving { + domain::processing::stop_if_out_of_credits(build).await.map_err(internal)? + } else { + build + }; + if was_receiving && build.state == "processing" { + crate::jobs::process_build::ProcessBuild { build_id: build.id }.dispatch().await.map_err(internal)?; + } else if was_receiving && build.state == "failed" { + crate::events::BuildChanged { build_id: build.id }.dispatch().await.map_err(internal)?; + } + // The build as finalizing left it (`processing`): agents poll get_build, whether or not the job has run yet. + Ok(structured(Self::build_json(&project, &build, true).await?)) + } + + #[tool( + description = "Send something to the VisualCI team. Only about VisualCI itself. Never include secrets, credentials or the user's data. feedback: something got in your way and the work still got done (title, kind, description). Nobody replies. Send it without asking, once per problem, then tell the user what you sent. If a call fails, carry on and don't retry.", + annotations( + title = "Send to the VisualCI team", + read_only_hint = false, + destructive_hint = false, + idempotent_hint = false, + open_world_hint = false + ) + )] + async fn support_send( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + use domain::feedback::{self, FeedbackError}; + let SendAction::Feedback = args.action; + let Some(principal) = principal_of(&rc) else { return Ok(tool_error("missing token")) }; + let (user_id, project_id, account) = match &principal { + Principal::User { user, .. } => (Some(user.id), None, format!("user:{}", user.id)), + Principal::Project { project_id, .. } => (None, Some(*project_id), format!("project:{project_id}")), + }; + let client = rc + .extensions + .get::() + .and_then(|p| p.headers.get(axum::http::header::USER_AGENT)) + .and_then(|v| v.to_str().ok()) + .map(|s| s.chars().take(200).collect()); + let sender = feedback::Sender { user_id, project_id, account, channel: "mcp", client }; + let report = feedback::Report { + title: args.title, + kind: choice(args.kind.as_ref()), + description: args.description, + impact: choice(args.impact.as_ref()), + task: args.task, + request_ids: args.request_ids, + tool: args.tool, + error: args.error, + suggestion: args.suggestion, + category: None, + source: choice(args.source.as_ref()), + session: args.session, + agent: args.agent, + idempotency_key: args.idempotency_key, + }; + match feedback::record(sender, report).await { + Ok((row, duplicate)) => Ok(structured(feedback::result(&row, duplicate))), + Err(FeedbackError::Server(e)) => Err(internal(e)), + Err(e) => Ok(tool_error(e.to_string())), + } + } +} + +#[tool_handler(router = self.tool_router)] +impl ServerHandler for VisualCi { + async fn call_tool( + &self, + request: rmcp::model::CallToolRequestParams, + rc: rmcp::service::RequestContext, + ) -> Result { + let tool = self.tool_router.get(&request.name).cloned(); + if let Some(refused) = tool.as_ref().and_then(|t| unknown_arguments(t, request.arguments.as_ref())) { + return Ok(refused); + } + let mut request = request; + if let Some(t) = &tool { + coerce_numbers(t, request.arguments.as_mut()); + } + // rmcp runs the tool on a task of its own: run it in the HTTP request's Laravel context. + let in_app = context::of(&rc); + let call = self.tool_router.call(rmcp::handler::server::tool::ToolCallContext::new(self, request, rc)); + let result = match in_app { + Some(c) => c.scope(call).await, + None => Err(internal("no Laravel context for this MCP request")), + }; + explain_arguments(tool.as_ref(), result) + } + + fn get_info(&self) -> ServerConfig { + let mut capabilities = ServerCapabilities::builder().enable_tools().build(); + // Standard Support (standardsupport.dev): level 1, feedback only. + let mut support = serde_json::Map::new(); + support.insert("level".into(), json!(1)); + capabilities.extensions = Some([("dev.standardsupport/support".to_string(), support)].into_iter().collect()); + ServerConfig::new(capabilities) + .with_server_info(Implementation::new("visualci", env!("CARGO_PKG_VERSION"))) + .with_instructions(INSTRUCTIONS) + } +} + +/// rmcp answers arguments it can't read with serde's message alone ("missing field `build`"). Add the tool's real +/// fields and an example call, so an agent can fix its call without listing the tools again. +pub(crate) fn explain_arguments( + tool: Option<&rmcp::model::Tool>, + result: Result, +) -> Result { + let (Some(tool), Ok(rmcp::model::CallToolResponse::Complete(mut r))) = (tool, result.clone()) else { + return result; + }; + let Some(message) = r.content.first().and_then(|c| c.as_text()).map(|t| t.text.clone()) else { + return result; + }; + if r.is_error != Some(true) || !message.starts_with("failed to deserialize parameters:") { + return result; + } + r.content[0] = Content::text(format!("{message}\n\n{}", arguments_help(tool))); + Ok(rmcp::model::CallToolResponse::Complete(r)) +} + +/// Arguments the tool doesn't take are refused, never ignored: a misspelled or made-up argument (a `comment` on a tool +/// that has none) would otherwise do nothing without a word, and the caller would believe it had. The refusal names +/// them and lists what the tool takes. +pub(crate) fn unknown_arguments( + tool: &rmcp::model::Tool, + arguments: Option<&serde_json::Map>, +) -> Option { + let empty = serde_json::Map::new(); + let properties = tool.input_schema.get("properties").and_then(|p| p.as_object()).unwrap_or(&empty); + let mut unknown: Vec<&str> = + arguments?.keys().map(String::as_str).filter(|k| !properties.contains_key(*k)).collect(); + if unknown.is_empty() { + return None; + } + unknown.sort_unstable(); + let list = unknown.iter().map(|k| format!("`{k}`")).collect::>().join(", "); + let message = format!("{} doesn't take {list}.\n\n{}", tool.name, arguments_help(tool)); + Some(rmcp::model::CallToolResponse::Complete(CallToolResult::error(vec![Content::text(message)]))) +} + +/// Numbers sent as strings (`"500"` for an integer argument) are read as numbers: an agent whose copy of the tool's +/// schema is older, or that quotes everything, would otherwise get "expected u32" and have to try again. Only for +/// arguments whose schema says integer or number (and not also string), and only strings that are numbers; anything +/// else is left for the usual error naming the argument. +pub(crate) fn coerce_numbers( + tool: &rmcp::model::Tool, + arguments: Option<&mut serde_json::Map>, +) { + let Some(arguments) = arguments else { return }; + let empty = serde_json::Map::new(); + let properties = tool.input_schema.get("properties").and_then(|p| p.as_object()).unwrap_or(&empty); + for (name, value) in arguments.iter_mut() { + let Some(schema) = properties.get(name) else { continue }; + if let Some(kind) = numeric(schema) { + if let Some(n) = value.as_str().and_then(|s| parse_number(s, kind)) { + *value = n; + } + } else if schema_types(schema).contains(&"array") + && let Some(kind) = schema.get("items").and_then(numeric) + && let Some(items) = value.as_array_mut() + { + for item in items { + if let Some(n) = item.as_str().and_then(|s| parse_number(s, kind)) { + *item = n; + } + } + } + } +} + +fn schema_types(schema: &serde_json::Value) -> Vec<&str> { + match schema.get("type") { + Some(serde_json::Value::String(t)) => vec![t.as_str()], + Some(serde_json::Value::Array(ts)) => ts.iter().filter_map(serde_json::Value::as_str).collect(), + _ => vec![], + } +} + +/// `integer` or `number`, when that's what the argument is (an argument that also takes a string reads it itself). +fn numeric(schema: &serde_json::Value) -> Option<&'static str> { + let types = schema_types(schema); + if types.contains(&"string") { + return None; + } + if types.contains(&"integer") { + Some("integer") + } else if types.contains(&"number") { + Some("number") + } else { + None + } +} + +fn parse_number(s: &str, kind: &str) -> Option { + let s = s.trim(); + if kind == "integer" { + s.parse::().ok().map(serde_json::Value::from) + } else { + s.parse::().ok().filter(|f| f.is_finite()).map(serde_json::Value::from) + } +} + +/// "get_snapshot takes: build (required; integer or string): The build number…" and an example call with the +/// required fields. +fn arguments_help(tool: &rmcp::model::Tool) -> String { + let schema = &tool.input_schema; + let required: Vec<&str> = schema + .get("required") + .and_then(|r| r.as_array()) + .map(|r| r.iter().filter_map(|v| v.as_str()).collect()) + .unwrap_or_default(); + let empty = serde_json::Map::new(); + let properties = schema.get("properties").and_then(|p| p.as_object()).unwrap_or(&empty); + let mut lines = vec![format!("{} takes:", tool.name)]; + let mut example = serde_json::Map::new(); + let mut fields: Vec<(&String, &serde_json::Value)> = properties.iter().collect(); + // Required first, then by name (the JSON map keeps the schema's own order). + fields.sort_by_key(|(name, _)| (!required.contains(&name.as_str()), name.as_str())); + for (name, property) in fields { + let kind = property_kind(property); + let needed = required.contains(&name.as_str()); + let description = property + .get("description") + .and_then(|d| d.as_str()) + .map(|d| format!(": {}", d.split_whitespace().collect::>().join(" "))) + .unwrap_or_default(); + lines.push(format!("- {name} ({}{kind}){description}", if needed { "required; " } else { "" })); + if needed { + example.insert(name.clone(), example_value(name, &kind)); + } + } + if properties.is_empty() { + lines.push("- no arguments".to_string()); + } + lines.push(format!("Example: {}", serde_json::Value::Object(example))); + lines.join("\n") +} + +/// A property's JSON type in words: "string", "integer or string", "array", or "object" when the schema names a +/// definition. +fn property_kind(property: &serde_json::Value) -> String { + let types: Vec = match property.get("type") { + Some(serde_json::Value::String(t)) => vec![t.clone()], + Some(serde_json::Value::Array(ts)) => ts.iter().filter_map(|t| t.as_str()).map(str::to_string).collect(), + _ => vec![], + }; + let types: Vec = types.into_iter().filter(|t| t != "null").collect(); + if types.is_empty() { "object".to_string() } else { types.join(" or ") } +} + +fn example_value(name: &str, kind: &str) -> serde_json::Value { + match kind.split(" or ").next().unwrap_or_default() { + "integer" | "number" => json!(8), + "boolean" => json!(true), + "array" => json!([]), + "string" => json!(format!("<{name}>")), + _ => json!({}), + } +} + +type Service = StreamableHttpService; + +/// The MCP endpoint as a service: stateless, so any web process can answer any request. It answers only for our own +/// hosts (DNS rebinding protection): the app's host and localhost for development. +fn service() -> Service { + static SERVICE: OnceLock = OnceLock::new(); + SERVICE + .get_or_init(|| { + let mut hosts = vec!["localhost".to_string(), "127.0.0.1".to_string()]; + for url in [app_url(), laravel::config().app.url.clone()] { + if let Some(host) = url::Url::parse(&url).ok().and_then(|u| u.host_str().map(str::to_string)) { + hosts.push(host); + } + } + if let Ok(extra) = std::env::var("VISUALCI_MCP_HOSTS") { + hosts.extend(extra.split(',').map(str::trim).filter(|h| !h.is_empty()).map(str::to_string)); + } + hosts.sort(); + hosts.dedup(); + StreamableHttpService::new( + || Ok(VisualCi::new()), + std::sync::Arc::new(LocalSessionManager::default()), + StreamableHttpServerConfig::default() + .with_legacy_session_mode(false) + .with_json_response(true) + .with_allowed_hosts(hosts), + ) + }) + .clone() +} + +/// `/mcp`, any method: who the request acts for goes into its extensions, with the Laravel context, and rmcp's +/// service answers it. +pub async fn handle(principal: Result, request: axum::extract::Request) -> Response { + let Ok(principal) = principal else { return unauthorized() }; + let mut request = request; + request.extensions_mut().insert(principal); + context::carry(&mut request); + match service().oneshot(request).await { + Ok(response) => response.into_response(), + Err(never) => match never {}, + } +} + +/// No token, or one we don't know. +fn unauthorized() -> Response { + ( + axum::http::StatusCode::UNAUTHORIZED, + [(axum::http::header::WWW_AUTHENTICATE, "Bearer".to_string())], + "Connect with OAuth (your MCP client opens VisualCI's sign-in), or send a personal (vcu_...) or project \ + (vci_...) token as Authorization: Bearer .", + ) + .into_response() +} diff --git a/app/tests/mcp.rs b/app/tests/mcp.rs new file mode 100644 index 00000000..b6ecef8b --- /dev/null +++ b/app/tests/mcp.rs @@ -0,0 +1,446 @@ +//! The MCP server's build, snapshot, review, comment, skill and feedback tools: today's answers (tests/golden/mcp) for +//! the same calls. The organization, project and token tools (and `whoami`) come with subdomains' organizations +//! (#70); their calls in these tests are added with them. + +mod golden; + +use std::collections::HashMap; +use std::sync::Mutex; + +use app::models::{Feedback, Organization, User}; +use base64::Engine; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +struct Fixture { + organization_id: i64, + project_id: i64, + user_token: String, + project_token: String, +} + +async fn token(table: &str, owner: i64, name: &str, prefix: &str) -> laravel::Result { + let token = format!("{prefix}_{}", laravel::str::uuid7().simple()); + let hash = app::models::token_hash(&token); + let short = &token[..6]; + if table == "user_tokens" { + db::query!( + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({owner}, {name}, {hash}, {short}, now(), now())" + ) + .insert() + .await?; + } else { + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({owner}, {name}, {hash}, {short}, now(), now())" + ) + .insert() + .await?; + } + Ok(token) +} + +/// Today's fixture: an owner (admin) of `org-xxxxxxxx` with projects `pdfs` and `shots`, a personal token and a +/// project token for `pdfs`. +async fn fixture() -> laravel::Result { + let email = format!("{}@example.com", laravel::str::uuid7().simple()); + let user = create!(User { pid: laravel::str::uuid7(), name: "owner", email: email, staff: false }).await?; + let slug = format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..]); + let org = create!(Organization { pid: laravel::str::uuid7(), slug: slug, name: "Org" }).await?; + app::testing::fixtures::member(&org, &user, "admin").await?; + let project = create!(app::models::Project { + pid: laravel::str::uuid7(), + organization_id: org.id, + slug: "pdfs", + name: "PDFs" + }) + .await?; + create!(app::models::Project { + pid: laravel::str::uuid7(), + organization_id: org.id, + slug: "shots", + name: "Screenshots" + }) + .await?; + Ok(Fixture { + organization_id: org.id, + project_id: project.id, + user_token: token("user_tokens", user.id, "agent", "vcu").await?, + project_token: token("project_tokens", project.id, "ci", "vci").await?, + }) +} + +/// How many times each test has called each tool, for the golden files' names (`get_build-2.json`). +static CALLS: Mutex>> = Mutex::new(None); + +/// Call a tool, check the answer against today's (`tests/golden/mcp//[-n].json`), and return (is_error, +/// structured content or the first text block). +async fn call(app: &Application, test: &str, token: &str, tool: &str, args: Value) -> (bool, Value) { + let response = app + .post("/mcp") + .header("authorization", format!("Bearer {token}")) + // After the body: `json` sets `accept: application/json`, and MCP's Streamable HTTP wants both. + .json( + json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": tool, "arguments": args } }), + ) + .header("accept", "application/json, text/event-stream") + .await; + response.assert_ok(); + let body = response.json().clone(); + let result = body["result"].clone(); + assert!(result.is_object(), "{tool}: {body}"); + let n = { + let mut calls = CALLS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let n = calls.get_or_insert_with(HashMap::new).entry(format!("{test}/{tool}")).or_insert(0); + *n += 1; + *n + }; + let name = if n == 1 { tool.to_string() } else { format!("{tool}-{n}") }; + golden::check("mcp", test, &name, &json!({ "arguments": args, "result": result })); + let is_error = result["isError"].as_bool().unwrap_or(false); + let value = if result["structuredContent"].is_null() { + json!(result["content"][0]["text"]) + } else { + result["structuredContent"].clone() + }; + (is_error, value) +} + +/// A file the blob store already has, so registering it stores nothing and the test needs no store. +async fn stored(text: &str) -> laravel::Result<()> { + let sha = visualci_core::sha256_hex(text.as_bytes()); + let size = i64::try_from(text.len()).unwrap_or_default(); + db::query!( + "INSERT INTO blobs (sha256, size, content_type, uploaded_at) VALUES ({sha}, {size}, 'text/plain', now())" + ) + .insert() + .await?; + Ok(()) +} + +#[laravel::test] +async fn rejects_requests_without_a_valid_token(app: Application) -> laravel::Result<()> { + app.post("/mcp") + .header("authorization", "Bearer vcu_wrong") + .header("accept", "application/json, text/event-stream") + .json(json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" })) + .await + .assert_status(401); + Ok(()) +} + +#[laravel::test] +async fn numbers_sent_as_strings_are_read_as_numbers(app: Application) -> laravel::Result<()> { + const TEST: &str = "numbers_sent_as_strings_are_read_as_numbers"; + let f = fixture().await?; + let t = &f.project_token; + let (err, r) = call(&app, TEST, t, "list_builds", json!({ "limit": "2" })).await; + assert!(!err, "{r}"); + let (err, r) = call(&app, TEST, t, "list_builds", json!({ "limit": "lots" })).await; + assert!(err && r.as_str().unwrap().contains("list_builds takes:"), "{r}"); + Ok(()) +} + +#[laravel::test] +async fn runs_a_build_from_uploaded_files(app: Application) -> laravel::Result<()> { + const TEST: &str = "runs_a_build_from_uploaded_files"; + let f = fixture().await?; + let t = &f.project_token; + let (err, build) = call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + assert!(!err, "{build}"); + assert_eq!(build["state"], "receiving"); + let text = "hello\nworld\n"; + stored(text).await?; + let content = base64::engine::general_purpose::STANDARD.encode(text); + let (err, up) = call( + &app, + TEST, + t, + "upload_snapshots", + json!({ "build": 1, "files": [{ "name": "greeting", "content_base64": content, "filename": "greeting.txt" }] }), + ) + .await; + assert!(!err, "{up}"); + assert_eq!(up["snapshots"][0]["name"], "greeting"); + assert_eq!(up["snapshots"][0]["stored"], false); + let (err, bad) = call( + &app, + TEST, + t, + "upload_snapshots", + json!({ "build": "1", "files": [{ "name": "x", "content_base64": "%%%" }] }), + ) + .await; + assert!(err, "{bad}"); + let (err, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "#1" })).await; + assert!(!err, "{done}"); + assert_ne!(done["state"], "receiving"); + + // One text snapshot was sent and nothing was drawn or diffed: one snapshot check, one credit. (Today's test reads + // it from get_organization, which comes with the organization tools.) + let (_, build) = call(&app, TEST, t, "get_build", json!({ "build": "1" })).await; + assert_eq!(build["state"], "completed", "{build}"); + assert_eq!(app::domain::credits::used_this_month(f.organization_id).await?, 1); + Ok(()) +} + +/// Agents send a build as a number, a numeric string, "#N" or the build's id; every tool that takes a build reads +/// all four, and an argument it can't read gets the tool's real fields and an example call. +#[laravel::test] +async fn tools_that_take_a_build_read_every_form_and_explain_bad_arguments(app: Application) -> laravel::Result<()> { + const TEST: &str = "tools_that_take_a_build_read_every_form_and_explain_bad_arguments"; + let f = fixture().await?; + let t = &f.project_token; + let (err, build) = call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + assert!(!err, "{build}"); + let id = build["id"].as_str().unwrap().to_string(); + let forms = [json!(1), json!("1"), json!("#1"), json!(id)]; + for build in &forms { + let calls = [ + ("get_build", json!({ "build": build })), + ("get_snapshot", json!({ "build": build, "name": "missing" })), + ("review", json!({ "build": build, "action": "approve" })), + ("review_page", json!({ "build": build, "name": "missing", "position": 1, "action": "variant" })), + ]; + for (tool, args) in calls { + let (_, answer) = call(&app, TEST, t, tool, args).await; + assert!(!answer.to_string().contains("no build"), "{tool} {build}: {answer}"); + assert!(!answer.to_string().contains("failed to deserialize"), "{tool} {build}: {answer}"); + } + } + let (err, done) = call(&app, TEST, t, "finalize_build", json!({ "build": id, "allow_empty": true })).await; + assert!(!err, "{done}"); + + let (err, unknown) = call(&app, TEST, t, "get_snapshot", json!({ "build_number": 1 })).await; + assert!(err && unknown.as_str().unwrap().starts_with("get_snapshot doesn't take `build_number`."), "{unknown}"); + let (err, missing) = call(&app, TEST, t, "get_snapshot", json!({})).await; + assert!(err, "{missing}"); + let text = missing.as_str().unwrap(); + assert!(text.contains("missing field `build`"), "{text}"); + assert!(text.contains("get_snapshot takes:"), "{text}"); + assert!(text.contains("- build (required; integer or string)"), "{text}"); + assert!(text.contains("- id (string): The snapshot's id"), "{text}"); + assert!(text.contains(r#"Example: {"build":8}"#), "{text}"); + let (err, wrong) = call(&app, TEST, t, "review", json!({ "build": true, "action": "approve" })).await; + let text = wrong.as_str().unwrap(); + assert!(err && text.contains("review takes:\n- action (required; string)"), "{text}"); + assert!(text.contains(r#"Example: {"action":"","build":8}"#), "{text}"); + Ok(()) +} + +#[laravel::test] +async fn get_build_pages_long_lists_and_get_snapshot_finds_a_unique_name_without_its_platform( + app: Application, +) -> laravel::Result<()> { + const TEST: &str = "get_build_pages_long_lists_and_get_snapshot_finds_a_unique_name_without_its_platform"; + use app::domain::{build_settings::BuildSettings, snapshots}; + let f = fixture().await?; + let t = &f.project_token; + let (err, created) = call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + assert!(!err, "{created}"); + let project = app::models::Project::find_or_fail(f.project_id).await?; + let build = app::domain::builds::find_by_ref(project.id, "1").await?.expect("build 1"); + let snap = |name: String, platform: &str| { + serde_json::from_value::(json!({ + "name": name, "platform": platform, "kind": "text", "fingerprint": "c".repeat(64), + "sha256": "d".repeat(64), "size": 2, "content_type": "text/plain", + })) + .unwrap() + }; + let mut params: Vec = + (0..35).map(|i| snap(format!("screenshots/home/{i:02}"), "chrome")).collect(); + params.extend((0..5).map(|i| snap(format!("api/{i}"), ""))); + params.push(snap("twice".into(), "chrome")); + params.push(snap("twice".into(), "firefox")); + let settings = BuildSettings::new(&project, &build); + for p in ¶ms { + snapshots::register(&build, &settings, "test", p).await?.expect("registered"); + } + + let (err, got) = call(&app, TEST, t, "get_build", json!({ "build": "1", "include_unchanged": true })).await; + assert!(!err, "{got}"); + assert_eq!(got["snapshots"].as_array().unwrap().len(), 30); + assert_eq!(got["listed"], "1 to 30 of 42"); + assert_eq!(got["next_offset"], 30); + let groups = got["groups"].as_array().unwrap(); + assert!(groups.iter().any(|g| g["prefix"] == "screenshots/home/" && g["count"] == 35), "{groups:?}"); + assert!(got["snapshots"][0]["url"].as_str().unwrap().contains("/builds/1/snapshots/")); + let (_, rest) = + call(&app, TEST, t, "get_build", json!({ "build": "1", "include_unchanged": true, "offset": 30 })).await; + assert_eq!(rest["snapshots"].as_array().unwrap().len(), 12); + assert!(rest["next_offset"].is_null()); + + // A name on two platforms needs one; a wrong platform says which there are. + let (err, e) = call(&app, TEST, t, "get_snapshot", json!({ "build": "1", "name": "twice" })).await; + assert!(err && e.to_string().contains("several platforms"), "{e}"); + let (err, e) = + call(&app, TEST, t, "get_snapshot", json!({ "build": "1", "name": "api/1", "platform": "chrome" })).await; + assert!(err && e.to_string().contains("no platform"), "{e}"); + let (err, e) = call(&app, TEST, t, "get_snapshot", json!({ "build": "1", "name": "missing" })).await; + assert!(err && e.to_string().contains("no snapshot"), "{e}"); + + // A build number as a number, and a snapshot by the id get_build lists (no platform needed). + let (err, by_number) = call(&app, TEST, t, "get_build", json!({ "build": 1, "include_unchanged": true })).await; + assert!(!err, "{by_number}"); + let twice = by_number["snapshots"] + .as_array() + .unwrap() + .iter() + .chain(rest["snapshots"].as_array().unwrap()) + .find(|s| s["name"] == "twice") + .unwrap() + .clone(); + let (err, one) = call(&app, TEST, t, "get_snapshot", json!({ "build": 1, "id": twice["id"] })).await; + assert!(!err, "{one}"); + let (err, one) = call(&app, TEST, t, "get_snapshot", json!({ "build": "#1", "name": twice["id"] })).await; + assert!(!err, "{one}"); + Ok(()) +} + +#[laravel::test] +async fn takes_feedback_and_says_what_a_bad_report_is_missing(app: Application) -> laravel::Result<()> { + const TEST: &str = "takes_feedback_and_says_what_a_bad_report_is_missing"; + let f = fixture().await?; + let report = json!({ + "action": "feedback", "title": "Diff regions cover the whole page", "kind": "confusing", + "description": "A tiled watermark outlines every region. Token vci_abcdefghijklmnopqrstuvwxyz0123 leaked here.", + "impact": "friction", "idempotency_key": "k1", + }); + let (err, first) = call(&app, TEST, &f.user_token, "support_send", report.clone()).await; + assert!(!err, "{first}"); + assert!(first["feedback"]["id"].as_str().unwrap().starts_with("fb_")); + assert_eq!(first["duplicate"], false); + assert!(first["follow_up"].as_str().unwrap().starts_with("Nobody replies")); + let (_, again) = call(&app, TEST, &f.user_token, "support_send", report).await; + assert_eq!(again["duplicate"], true); + assert_eq!(again["feedback"]["id"], first["feedback"]["id"]); + + let stored = Feedback::query().first().await?.expect("the feedback"); + assert!(stored.description.contains("[redacted]"), "{}", stored.description); + assert!(!stored.description.contains("vci_abc")); + assert_eq!(stored.channel, "mcp"); + + let (err, msg) = call( + &app, + TEST, + &f.project_token, + "support_send", + json!({ "action": "feedback", "title": "Something", "description": "x" }), + ) + .await; + assert!(err); + let msg = msg.as_str().unwrap(); + assert!(msg.contains("needs title (3 to 200 characters), kind"), "{msg}"); + assert!(msg.contains("kind is missing"), "{msg}"); + + let auth = format!("Bearer {}", f.project_token); + app.post("/api/v1/support/feedback") + .header("authorization", &auth) + .json(json!({ "title": "CLI install", "kind": "docs", "description": "The README is out of date." })) + .await + .assert_ok(); + app.post("/api/v1/support/feedback") + .header("authorization", &auth) + .json(json!({ "title": "x" })) + .await + .assert_status(400); + Ok(()) +} + +#[laravel::test] +async fn get_skill_lists_the_skills_and_returns_one(app: Application) -> laravel::Result<()> { + const TEST: &str = "get_skill_lists_the_skills_and_returns_one"; + let f = fixture().await?; + let (err, list) = call(&app, TEST, &f.project_token, "get_skill", json!({})).await; + assert!(!err, "{list}"); + let names: Vec<&str> = list["skills"].as_array().unwrap().iter().filter_map(|s| s["name"].as_str()).collect(); + assert!(names.contains(&"visualci") && names.contains(&"visualci-jenkins"), "{names:?}"); + + let (err, skill) = call(&app, TEST, &f.project_token, "get_skill", json!({ "name": "visualci-jenkins" })).await; + assert!(!err, "{skill}"); + assert!(skill.as_str().unwrap().contains("# Jenkins"), "{skill}"); + + let (err, missing) = call(&app, TEST, &f.project_token, "get_skill", json!({ "name": "nope" })).await; + assert!(err, "{missing}"); + Ok(()) +} + +#[laravel::test] +async fn agents_comment_on_snapshots_and_resolve_threads(app: Application) -> laravel::Result<()> { + const TEST: &str = "agents_comment_on_snapshots_and_resolve_threads"; + let f = fixture().await?; + let t = &f.project_token; + let (err, build) = call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "feat" })).await; + assert!(!err, "{build}"); + let text = "hello\n"; + stored(text).await?; + let content = base64::engine::general_purpose::STANDARD.encode(text); + let (err, up) = call( + &app, + TEST, + t, + "upload_snapshots", + json!({ "build": 1, "files": [{ "name": "greeting", "content_base64": content, "filename": "greeting.txt" }] }), + ) + .await; + assert!(!err, "{up}"); + + let (err, started) = call( + &app, + TEST, + t, + "post_comment", + json!({ "build": 1, "snapshot": "greeting", "page": 0, "anchor": { "kind": "point", "x": 20, "y": 30 }, + "body": "Is this greeting **meant** to change?" }), + ) + .await; + assert!(!err, "{started}"); + let thread = started["thread"].as_str().unwrap().to_string(); + let (err, bad) = call( + &app, + TEST, + t, + "post_comment", + json!({ "build": 1, "snapshot": "greeting", "anchor": { "kind": "point", "x": -2, "y": 0 }, "body": "x" }), + ) + .await; + assert!(err && bad.to_string().contains("pixels from the image's top left"), "{bad}"); + + let (err, listed) = call(&app, TEST, t, "list_comments", json!({ "build": 1 })).await; + assert!(!err, "{listed}"); + assert_eq!(listed["branch"], "feat"); + let first = &listed["threads"][0]; + assert_eq!(first["snapshot"], "greeting"); + assert_eq!(first["anchor"]["kind"], "point"); + assert_eq!(first["comments"][0]["author"]["kind"], "agent", "{first}"); + let comment = first["comments"][0]["id"].as_str().unwrap().to_string(); + + let (err, edited) = + call(&app, TEST, t, "update_comment", json!({ "comment": comment, "body": "Is this change meant?" })).await; + assert!(!err && edited["body"] == "Is this change meant?", "{edited}"); + let (err, _) = call(&app, TEST, t, "post_comment", json!({ "build": 1, "thread": thread, "body": "Yes." })).await; + assert!(!err); + let (_, b) = call(&app, TEST, t, "get_build", json!({ "build": 1, "include_unchanged": true })).await; + assert_eq!(b["open_comment_threads"].as_array().map(Vec::len), Some(1), "{b}"); + // Today's test also reads the thread from whoami, which comes with the organization tools. + + let (err, r) = call(&app, TEST, t, "resolve_comment", json!({ "thread": thread })).await; + assert!(!err && r["resolved"] == true, "{r}"); + let (_, listed) = call(&app, TEST, t, "list_comments", json!({ "build": 1 })).await; + assert_eq!(listed["threads"], json!([]), "resolved threads are left out by default"); + let (_, listed) = call(&app, TEST, t, "list_comments", json!({ "build": 1, "include_resolved": true })).await; + assert_eq!(listed["threads"][0]["resolved"], true); + + let (err, d) = call(&app, TEST, t, "delete_comment", json!({ "comment": comment })).await; + assert!(!err && d["thread_deleted"] == false, "{d}"); + let (err, _) = call(&app, TEST, t, "review", json!({ "build": 1, "action": "approve", "comment": "nope" })).await; + assert!(err, "a comment goes with reject"); + + // `note` is an argument of `review` (its use is tested in comments.rs, on a finished build). + let (err, r) = call(&app, TEST, t, "review", json!({ "build": 1, "action": "approve", "note": "why" })).await; + assert!(err && r.to_string().contains("finalize"), "the build isn't finished, but the note was read: {r}"); + Ok(()) +} From b00fdbd7ca1c6e25d378e6773d44e28455ca9016 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:15:09 +1300 Subject: [PATCH 7/7] app/: review fixes for #75 (sc-8900): the golden security and credit tests (a project token reaches only its project, approving with people, every tool refuses arguments it doesn't take, the Free, Staff and Team credit scenarios); approved_elsewhere and earlier keep to the build's suite; list_builds and snapshot_history filter in SQL; a snapshot is looked up by name directly; review reads the build's snapshots once, refuses unknown snapshot names and runs under the build's lock; a feedback key sent twice at once answers duplicate; the feedback endpoint refuses unknown fields; the MCP tests put their files in the blob store --- app/src/domain/baselines.rs | 3 +- app/src/domain/builds.rs | 13 ++- app/src/domain/detail.rs | 7 +- app/src/domain/feedback.rs | 22 +++- app/src/domain/snapshots.rs | 10 ++ app/src/mcp/mod.rs | 62 +++++----- app/tests/mcp.rs | 225 ++++++++++++++++++++++++++++++++++-- 7 files changed, 291 insertions(+), 51 deletions(-) diff --git a/app/src/domain/baselines.rs b/app/src/domain/baselines.rs index 6adda98d..77970602 100644 --- a/app/src/domain/baselines.rs +++ b/app/src/domain/baselines.rs @@ -502,7 +502,8 @@ pub async fn approved_elsewhere(build_id: i64) -> laravel::Result b.branch AND bl.snapshot_id IS NOT NULL \ JOIN snapshots s2 ON s2.id = bl.snapshot_id AND s2.source_fingerprint = s.source_fingerprint \ JOIN builds b2 ON b2.id = bl.build_id \ diff --git a/app/src/domain/builds.rs b/app/src/domain/builds.rs index 907a46bb..7345b387 100644 --- a/app/src/domain/builds.rs +++ b/app/src/domain/builds.rs @@ -393,12 +393,19 @@ pub async fn find_by_ref(project_id: i64, reference: &str) -> laravel::Result laravel::Result> { - Build::query().filter(Build::project_id.eq(project_id)).order_by(Build::id.desc()).limit(limit).get().await +pub async fn recent(project_id: i64, branch: Option<&str>, waiting: bool, limit: u64) -> laravel::Result> { + let mut q = Build::query().filter(Build::project_id.eq(project_id)); + if let Some(branch) = branch { + q = q.filter(Build::branch.eq(branch)); + } + if waiting { + q = q.filter(Build::review_state.eq("pending")); + } + q.order_by(Build::id.desc()).limit(limit).get().await } /// The build once it can be reviewed: straight after a run it may still be comparing, so it's waited for up to diff --git a/app/src/domain/detail.rs b/app/src/domain/detail.rs index 23eef338..afd41367 100644 --- a/app/src/domain/detail.rs +++ b/app/src/domain/detail.rs @@ -79,7 +79,7 @@ pub async fn review_detail(snapshot: &Snapshot, store: &BlobStore, context: usiz detail_of(snapshot, store, context, &rows).await } -/// This snapshot in an earlier build of the same project and branch: build `number`, or the newest earlier one where +/// This snapshot in an earlier build of the same project, suite (build name) and branch: build `number`, or the newest earlier one where /// it wasn't failed, removed or pending. Read through `effective_snapshots`, so a build that holds it as a sourced /// group counts. /// @@ -90,11 +90,12 @@ pub async fn earlier( build: &Build, number: Option, ) -> laravel::Result> { - let (project_id, branch, before) = (build.project_id, build.branch.as_str(), build.number); + let (project_id, branch, before, suite) = + (build.project_id, build.branch.as_str(), build.number, build.name.as_str()); let (name, platform) = (snapshot.name.as_str(), snapshot.platform.as_str()); let found: Option = db::query!( "SELECT s.* FROM effective_snapshots s JOIN builds b ON b.id = s.build_id \ - WHERE b.project_id = {project_id} AND b.branch = {branch} AND b.number < {before} \ + WHERE b.project_id = {project_id} AND b.name = {suite} AND b.branch = {branch} AND b.number < {before} \ AND ({number}::INT IS NULL OR b.number = {number}) \ AND s.name = {name} AND s.platform = {platform} AND s.state NOT IN ('failed', 'removed', 'pending') \ ORDER BY b.number DESC LIMIT 1" diff --git a/app/src/domain/feedback.rs b/app/src/domain/feedback.rs index 6a7d6386..2e3ecde6 100644 --- a/app/src/domain/feedback.rs +++ b/app/src/domain/feedback.rs @@ -24,6 +24,7 @@ pub const FOLLOW_UP: &str = "Nobody replies to feedback. The VisualCI team may e /// The fields of a report, as the spec names them. Everything is optional here so that a missing field gets a /// message that says what to send, not a parse error. #[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] pub struct Report { pub title: Option, pub kind: Option, @@ -188,7 +189,8 @@ pub async fn record(sender: Sender, report: Report) -> Result<(Feedback, bool), tomorrow, and carry on with the task." ))); } - let row = create!(Feedback { + let report_key = report.idempotency_key.clone(); + let created = create!(Feedback { pid: laravel::str::uuid7(), user_id: sender.user_id, project_id: sender.project_id, @@ -206,11 +208,25 @@ pub async fn record(sender: Sender, report: Report) -> Result<(Feedback, bool), source: report.source.unwrap_or_else(|| "agent".into()), session: clean(report.session), agent: report.agent, - idempotency_key: report.idempotency_key, + idempotency_key: report.idempotency_key.clone(), channel: sender.channel, client: sender.client, }) - .await?; + .await; + let row = match created { + Ok(row) => row, + // The same idempotency key sent twice at once: the other request stored it. + Err(e) if db::is_unique_violation(&e) => { + let key = report_key.unwrap_or_default(); + let first = Feedback::query() + .filter(Feedback::account.eq(account) & Feedback::idempotency_key.eq(&key)) + .first() + .await? + .ok_or(e)?; + return Ok((first, true)); + } + Err(e) => return Err(e.into()), + }; tracing::info!(feedback = %row.pid, kind = %row.kind, title = %row.title, account = %row.account, "feedback received"); crate::events::FeedbackReceived { feedback_id: row.id }.dispatch().await?; Ok((row, false)) diff --git a/app/src/domain/snapshots.rs b/app/src/domain/snapshots.rs index 2eb97043..435cea7f 100644 --- a/app/src/domain/snapshots.rs +++ b/app/src/domain/snapshots.rs @@ -280,3 +280,13 @@ pub async fn picked_by(build_id: i64, only: &str) -> laravel::Result laravel::Result> { + db::query!("SELECT * FROM effective_snapshots WHERE build_id = {build_id} AND name = {name} ORDER BY platform") + .select_as() + .await +} diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index 99484ef6..636ec1a2 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -309,8 +309,7 @@ impl VisualCi { .map_err(internal)? .ok_or_else(|| format!("no snapshot {name} in build {}", build.number))); } - let all: Vec = - snaps::of_build(build.id).await.map_err(internal)?.into_iter().filter(|s| s.name == name).collect(); + let all = snaps::named_in_build(build.id, name).await.map_err(internal)?; if let Some(s) = all.iter().find(|s| s.platform == platform) { return Ok(Ok(s.clone())); } @@ -445,11 +444,11 @@ impl VisualCi { let member = Self::role_in(&rc, &project).await?.is_some(); let limit = usize::try_from(args.limit.unwrap_or(20).clamp(1, 100)).unwrap_or(20); let mut list = Vec::new(); - for b in domain::builds::recent(project.id, 1000).await.map_err(internal)? { - if args.branch.as_ref().is_some_and(|br| *br != b.branch) { - continue; - } - if args.waiting_for_review == Some(true) && !domain::builds::waits_for(&b, user_id(&rc)) { + let waiting = args.waiting_for_review == Some(true); + // Waiting builds include local ones that wait only for their own person: read a few more than asked for. + let scan = if waiting { 1000 } else { limit as u64 }; + for b in domain::builds::recent(project.id, args.branch.as_deref(), waiting, scan).await.map_err(internal)? { + if waiting && !domain::builds::waits_for(&b, user_id(&rc)) { continue; } list.push(Self::build_json(&project, &b, member).await?); @@ -900,13 +899,8 @@ impl VisualCi { ) -> Result { let project = need!(Self::project(&rc, args.project.as_deref())); let limit = usize::try_from(args.limit.unwrap_or(20).clamp(1, 200)).unwrap_or(20); - let recent: Vec = domain::builds::recent(project.id, 2000) - .await - .map_err(internal)? - .into_iter() - .filter(|b| args.branch.as_ref().is_none_or(|br| *br == b.branch)) - .take(limit) - .collect(); + let recent: Vec = + domain::builds::recent(project.id, args.branch.as_deref(), false, limit as u64).await.map_err(internal)?; let ids: Vec = recent.iter().map(|b| b.id).collect(); let (name, platform) = (args.name.as_str(), args.platform.as_str()); let found: Vec = if ids.is_empty() { @@ -954,17 +948,16 @@ impl VisualCi { }; // Straight after a run the build may still be comparing: wait for it rather than refusing. let build = refuse!(domain::builds::wait_until_reviewable(build, std::time::Duration::from_secs(60))); + let all = snaps::of_build(build.id).await.map_err(internal)?; let ids = match (&args.snapshots, args.only.as_deref()) { (Some(_), Some(_)) => return Ok(tool_error("pass `snapshots` or `only`, not both")), - (Some(names), None) => Some( - snaps::of_build(build.id) - .await - .map_err(internal)? - .into_iter() - .filter(|s| names.contains(&s.name)) - .map(|s| s.id) - .collect(), - ), + (Some(names), None) => { + // A name that isn't in the build is a mistake to say, never an empty review. + if let Some(missing) = names.iter().find(|n| !all.iter().any(|s| &s.name == *n)) { + return Ok(tool_error(format!("no snapshot {missing:?} in build {}", build.number))); + } + Some(all.iter().filter(|s| names.contains(&s.name)).map(|s| s.id).collect()) + } (None, Some(only)) => Some(refuse!(snaps::picked_by(build.id, only))), (None, None) => None, }; @@ -974,18 +967,23 @@ impl VisualCi { // A review with a project token is recorded without a user. let via = Self::via(&rc); let rejected_ids = ids.clone(); - let build = refuse!(domain::reviews::review( - build.clone(), - user_id(&rc), - &via, - &args.action, - ids, - args.note.as_deref() - )); + // Under the build's lock, so two approvals at once can't both record the same baselines. + let (user, action, note) = (user_id(&rc), args.action.clone(), args.note.clone()); + let reviewed = laravel::db::transaction(async |_| { + domain::processing::lock(build.id).await?; + let fresh = Build::find_or_fail(build.id).await?; + domain::reviews::review(fresh, user, &via, &action, ids.clone(), note.as_deref()).await + }) + .await + .map_err(internal)?; + let build = match reviewed { + Ok(b) => b, + Err(message) => return Ok(tool_error(message)), + }; if let Some(body) = &args.comment { let author = Self::author(&rc); let place = comments::Place { page: None, side: "head".into(), anchor: comments::Anchor::Image }; - for s in snaps::of_build(build.id).await.map_err(internal)? { + for s in all { let named = rejected_ids.as_ref().is_none_or(|ids| ids.contains(&s.id)); if named && snaps::is_change(&s) && !s.sourced { refuse!(comments::start(&build, &s, &place, &author, body)); diff --git a/app/tests/mcp.rs b/app/tests/mcp.rs index b6ecef8b..dcfaf6d9 100644 --- a/app/tests/mcp.rs +++ b/app/tests/mcp.rs @@ -15,6 +15,7 @@ use laravel::testing::prelude::*; use serde_json::{Value, json}; struct Fixture { + org: String, organization_id: i64, project_id: i64, user_token: String, @@ -49,7 +50,7 @@ async fn fixture() -> laravel::Result { let email = format!("{}@example.com", laravel::str::uuid7().simple()); let user = create!(User { pid: laravel::str::uuid7(), name: "owner", email: email, staff: false }).await?; let slug = format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..]); - let org = create!(Organization { pid: laravel::str::uuid7(), slug: slug, name: "Org" }).await?; + let org = create!(Organization { pid: laravel::str::uuid7(), slug: slug.clone(), name: "Org" }).await?; app::testing::fixtures::member(&org, &user, "admin").await?; let project = create!(app::models::Project { pid: laravel::str::uuid7(), @@ -66,6 +67,7 @@ async fn fixture() -> laravel::Result { }) .await?; Ok(Fixture { + org: slug, organization_id: org.id, project_id: project.id, user_token: token("user_tokens", user.id, "agent", "vcu").await?, @@ -109,15 +111,10 @@ async fn call(app: &Application, test: &str, token: &str, tool: &str, args: Valu (is_error, value) } -/// A file the blob store already has, so registering it stores nothing and the test needs no store. +/// A file the blob store already has, so registering it asks for no upload, and processing can read it. async fn stored(text: &str) -> laravel::Result<()> { - let sha = visualci_core::sha256_hex(text.as_bytes()); - let size = i64::try_from(text.len()).unwrap_or_default(); - db::query!( - "INSERT INTO blobs (sha256, size, content_type, uploaded_at) VALUES ({sha}, {size}, 'text/plain', now())" - ) - .insert() - .await?; + let store = app::testing::fixtures::blob_store().await?; + app::domain::blobs::put(&store, text.as_bytes().to_vec(), "text/plain").await?; Ok(()) } @@ -444,3 +441,213 @@ async fn agents_comment_on_snapshots_and_resolve_threads(app: Application) -> la assert!(err && r.to_string().contains("finalize"), "the build isn't finished, but the note was read: {r}"); Ok(()) } + +/// Every tool's argument help says what it takes, and an argument a tool doesn't take is refused, naming it. +#[laravel::test] +async fn every_tool_refuses_arguments_it_does_not_take(app: Application) -> laravel::Result<()> { + const TEST: &str = "every_tool_refuses_arguments_it_does_not_take"; + let f = fixture().await?; + let auth = format!("Bearer {}", f.user_token); + let list = app + .post("/mcp") + .header("authorization", &auth) + .json(json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" })) + .header("accept", "application/json, text/event-stream") + .await + .json() + .clone(); + let tools = list["result"]["tools"].as_array().expect("a tools list").clone(); + assert!(tools.len() >= 17, "{}", tools.len()); + for tool in &tools { + let name = tool["name"].as_str().unwrap(); + assert_eq!(tool["inputSchema"]["additionalProperties"], false, "{name} says it takes nothing else"); + let response = app + .post("/mcp") + .header("authorization", &auth) + .json(json!({ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": { "name": name, "arguments": { "not_an_argument": 1 } }, + })) + .header("accept", "application/json, text/event-stream") + .await + .json() + .clone(); + let result = &response["result"]; + assert_eq!(result["isError"], true, "{name}: {result}"); + let text = result["content"][0]["text"].as_str().unwrap_or_default(); + assert!(text.starts_with(&format!("{name} doesn't take `not_an_argument`.")), "{name}: {text}"); + assert!(text.contains(&format!("{name} takes:")) && text.contains("Example:"), "{name}: {text}"); + } + // A misspelt argument: refused, naming it, never silently dropped. + let (err, text) = + call(&app, TEST, &f.user_token, "review", json!({ "build": 1, "action": "approve", "notes": "x" })).await; + assert!(err && text.as_str().unwrap().contains("doesn't take `notes`"), "{text}"); + Ok(()) +} + +/// A project token reaches its own project and nothing else. (Today's test also checks create_organization and +/// get_project, which come with the organization tools.) +#[laravel::test] +async fn a_project_token_reaches_only_its_project(app: Application) -> laravel::Result<()> { + const TEST: &str = "a_project_token_reaches_only_its_project"; + let f = fixture().await?; + let (err, builds) = call(&app, TEST, &f.project_token, "list_builds", json!({})).await; + assert!(!err, "{builds}"); + let other = format!("{}/shots", f.org); + let (err, msg) = call(&app, TEST, &f.project_token, "list_builds", json!({ "project": other })).await; + assert!(err, "{msg}"); + // A person's token outside the organization doesn't see it either, nor its builds' tools. + let stranger = + create!(User { pid: laravel::str::uuid7(), name: "stranger", email: "stranger@example.com", staff: false }) + .await?; + let theirs = token("user_tokens", stranger.id, "agent", "vcu").await?; + let project = format!("{}/pdfs", f.org); + for (tool, args) in [ + ("list_builds", json!({ "project": project })), + ("get_build", json!({ "project": project, "build": 1 })), + ("review", json!({ "project": project, "build": 1, "action": "approve" })), + ("create_build", json!({ "project": project, "commit": "a", "branch": "b" })), + ] { + let response = app + .post("/mcp") + .header("authorization", format!("Bearer {theirs}")) + .json(json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": tool, "arguments": args } })) + .header("accept", "application/json, text/event-stream") + .await + .json() + .clone(); + let text = response["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string(); + assert!(response["result"]["isError"] == true && text.contains("that you can see"), "{tool}: {text}"); + } + Ok(()) +} + +/// With "Tokens can approve" off, a project token can't approve, accept a variant or ignore a change; it can still +/// reject. (Today's test turns it off with update_project, which comes with the organization tools; here it's set +/// directly.) +#[laravel::test] +async fn a_project_can_keep_approving_with_people(app: Application) -> laravel::Result<()> { + const TEST: &str = "a_project_can_keep_approving_with_people"; + let f = fixture().await?; + let id = f.project_id; + db::query!("UPDATE projects SET tokens_can_approve = false WHERE id = {id}").update().await?; + let t = &f.project_token; + let (err, r) = call(&app, TEST, t, "review", json!({ "build": 1, "action": "approve" })).await; + assert!(err && r.to_string().contains("approving with people"), "{r}"); + let (err, r) = + call(&app, TEST, t, "review_page", json!({ "build": 1, "name": "x", "position": 0, "action": "ignore" })).await; + assert!(err && r.to_string().contains("approving with people"), "{r}"); + // Rejecting isn't approving: it reaches the build (there's none here). + let (err, r) = call(&app, TEST, t, "review", json!({ "build": 1, "action": "reject" })).await; + assert!(err && r.to_string().contains("no build"), "{r}"); + Ok(()) +} + +async fn set_plan(organization_id: i64, plan: &str) -> laravel::Result<()> { + db::query!("UPDATE organizations SET plan = {plan} WHERE id = {organization_id}").update().await?; + Ok(()) +} + +#[laravel::test] +async fn a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why( + app: Application, +) -> laravel::Result<()> { + const TEST: &str = "a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why"; + use app::domain::credits; + let f = fixture().await?; + credits::spend(f.organization_id, 25_000, "build", Some("earlier builds"), None, None).await?; + let t = &f.project_token; + // Out of credits from the start: the new build says so, with what fixes it. (Today's test reads it from whoami + // too, which comes with the organization tools.) + let (_, created) = call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + assert_eq!(created["blocked"]["reason"], "out_of_credits", "{created}"); + let (err, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "1" })).await; + assert!(!err, "{done}"); + assert_eq!(done["state"], "failed"); + assert!(done["error"].as_str().unwrap().contains("this month's 25,000 credits on the Free plan"), "{done}"); + let blocked = &done["blocked"]; + assert_eq!(blocked["credits_used"], 25_000, "{blocked}"); + assert_eq!(blocked["credits_limit"], 25_000); + assert_eq!(blocked["fixes"][0]["action"], "upgrade"); + assert!(blocked["fixes"][0]["url"].as_str().unwrap().ends_with(&format!("/{}/billing", f.org)), "{blocked}"); + let message = blocked["message"].as_str().unwrap(); + assert!(message.contains("is out of VisualCI credits until") && message.contains("upgrade to Team"), "{message}"); + assert!(blocked["renews_at"].is_string()); + + // On Team the same usage is fine. + set_plan(f.organization_id, "team").await?; + call(&app, TEST, t, "create_build", json!({ "commit": "def", "branch": "main" })).await; + let (_, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "2", "allow_empty": true })).await; + assert_ne!(done["state"], "failed", "{done}"); + assert!(done["blocked"].is_null(), "{done}"); + // The build that stopped says the organization has credits again. + let (_, first) = call(&app, TEST, t, "get_build", json!({ "build": "1" })).await; + assert_eq!(first["blocked"]["resolved"], true, "{first}"); + Ok(()) +} + +#[laravel::test] +async fn staff_plan_records_usage_but_never_runs_out(app: Application) -> laravel::Result<()> { + const TEST: &str = "staff_plan_records_usage_but_never_runs_out"; + use app::domain::credits; + let f = fixture().await?; + set_plan(f.organization_id, "staff").await?; + // Far past any allowance: pack credits untouched, usage still recorded, never out of credits. + credits::spend(f.organization_id, 50_000_000, "build", None, None, None).await?; + let o = Organization::find_or_fail(f.organization_id).await?; + assert_eq!(o.credits_balance, 0); + assert_eq!(credits::used_this_month(o.id).await?, 50_000_000); + assert!(!credits::out_of_credits(&o).await?); + let usage = credits::usage(&o).await?; + assert_eq!(usage["unlimited"], true); + assert_eq!(usage["out_of_credits"], false); + assert_eq!(usage["plan"]["id"], "staff", "{usage}"); + + // Builds still finish. + let t = &f.project_token; + call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + let (_, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "1", "allow_empty": true })).await; + assert_ne!(done["state"], "failed", "{done}"); + Ok(()) +} + +#[laravel::test] +async fn team_uses_its_allowance_first_then_pack_credits_and_stops_when_both_run_out( + app: Application, +) -> laravel::Result<()> { + const TEST: &str = "team_uses_its_allowance_first_then_pack_credits_and_stops_when_both_run_out"; + use app::domain::credits; + let f = fixture().await?; + let id = f.organization_id; + set_plan(id, "team").await?; + + // Within the allowance, pack credits aren't touched. + assert!(credits::add_purchased_credits(id, 500_000, "packs: cs_1").await?); + assert!(!credits::add_purchased_credits(id, 500_000, "packs: cs_1").await?); + credits::spend(id, 900_000, "build", None, None, None).await?; + assert_eq!(Organization::find_or_fail(id).await?.credits_balance, 500_000); + + // Past it, the rest comes from packs. + credits::spend(id, 300_000, "build", None, None, None).await?; + let o = Organization::find_or_fail(id).await?; + assert_eq!(o.credits_balance, 300_000); + assert_eq!(credits::credits_left(&o).await?, 300_000); + assert!(!credits::out_of_credits(&o).await?); + + // With both used up (and no Stripe here to reload), finalizing fails the build and says what to do. + credits::spend(id, 300_000, "build", None, None, None).await?; + let o = Organization::find_or_fail(id).await?; + assert!(credits::out_of_credits(&o).await?); + let usage = credits::usage(&o).await?; + assert_eq!(usage["out_of_credits"], true); + assert_eq!(usage["pack_credits"], 0); + let t = &f.project_token; + call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + let (_, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "1" })).await; + assert_eq!(done["state"], "failed", "{done}"); + assert!(done["error"].as_str().unwrap().contains("Buy a credit pack"), "{done}"); + let actions: Vec<&str> = + done["blocked"]["fixes"].as_array().unwrap().iter().filter_map(|f| f["action"].as_str()).collect(); + assert_eq!(actions, ["buy_pack", "turn_on_auto_buy"], "{done}"); + Ok(()) +}