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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"plugins": [
{
"name": "visualci",
"version": "0.1.38",
"version": "0.1.42",
"description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.",
"author": { "name": "DocSpring", "url": "https://visualci.com" },
"homepage": "https://visualci.com/docs/skills/",
Expand Down
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "visualci",
"version": "0.1.38",
"version": "0.1.42",
"description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.",
"author": { "name": "DocSpring", "url": "https://visualci.com" },
"homepage": "https://visualci.com/docs/skills/",
Expand Down
2 changes: 1 addition & 1 deletion .cursor-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "visualci",
"displayName": "VisualCI",
"version": "0.1.38",
"version": "0.1.42",
"description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.",
"author": {
"name": "DocSpring"
Expand Down
10 changes: 5 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "server", "server/migration"]

[workspace.package]
version = "0.2.13"
version = "0.2.15"
edition = "2024"
license = "Apache-2.0"
repository = "https://github.com/DocSpring/visualci"
Expand Down
126 changes: 98 additions & 28 deletions crates/visualci-cli/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,40 +183,36 @@ impl Client {
}

/// Register snapshots and upload the files the server doesn't have. Returns (registered, uploaded).
/// Large suites (sc-8868): send the run's manifest hash and one hash per group of names, and get back which
/// groups the server needs. Groups that match their baselines are carried forward on the server.
pub fn check_groups(
&self,
build_id: &str,
entries: &[visualci_core::manifest::Entry],
group_depth: Option<u32>,
) -> Result<GroupCheck> {
use visualci_core::manifest;
let grouping = group_depth.map_or(manifest::Grouping::default(), |d| manifest::Grouping::Depth(d as usize));
let groups: Vec<serde_json::Value> = manifest::groups(entries, grouping)
.into_iter()
.map(|g| json!({ "key": g.key, "hash": g.hash, "count": g.count }))
.collect();
let body = json!({
"manifest_hash": manifest::manifest_hash(entries),
"group_depth": group_depth,
"groups": groups,
});
Ok(serde_json::from_value(self.post(&format!("/api/v1/builds/{build_id}/groups"), &body)?)?)
}

pub fn add_snapshots(&self, build_id: &str, snapshots: &[Snapshot]) -> Result<(usize, usize)> {
let mut uploaded = 0;
for chunk in snapshots.chunks(BATCH) {
let mut files = Vec::with_capacity(chunk.len());
let mut params = Vec::with_capacity(chunk.len());
for s in chunk {
let bytes = match &s.content {
Some(c) => c.clone(),
None => std::fs::read(&s.path).with_context(|| format!("reading {}", s.path.display()))?,
};
let (kind, fingerprint, mut content_type) = if s.content.is_some() {
("text", visualci_core::sha256_hex(&bytes), "text/plain")
} else {
classify(&s.path, &bytes)?
};
if kind == "text" {
let name = s.path.file_name().and_then(|n| n.to_str());
content_type =
Format::detect(s.format.as_deref(), None, if s.content.is_some() { None } else { name })
.content_type();
}
params.push(json!({
"name": s.name,
"platform": s.platform,
"kind": kind,
"fingerprint": fingerprint,
"sha256": visualci_core::sha256_hex(&bytes),
"size": bytes.len(),
"content_type": content_type,
"threshold": s.threshold,
"engine": s.engine,
"format": s.format,
"ignore": s.ignore,
}));
let (p, bytes) = registration(s)?;
params.push(p);
files.push(bytes);
}
let response =
Expand Down Expand Up @@ -295,6 +291,80 @@ pub fn mcp_url_for(api_url: &str) -> String {
}
}

/// What the server's answer to `check_groups` says.
#[derive(Debug, Deserialize)]
pub struct GroupCheck {
/// The whole manifest matched this build's: nothing needs sending.
pub same_as_build: Option<i32>,
pub changed: Vec<String>,
pub unchanged: Vec<String>,
}

/// A snapshot's registration (as `POST /builds/:id/snapshots` takes it) and its bytes.
///
/// # Errors
/// When the file can't be read or classified.
pub fn registration(s: &Snapshot) -> Result<(serde_json::Value, Vec<u8>)> {
let bytes = match &s.content {
Some(c) => c.clone(),
None => std::fs::read(&s.path).with_context(|| format!("reading {}", s.path.display()))?,
};
let (kind, fingerprint, mut content_type) = if s.content.is_some() {
("text", visualci_core::sha256_hex(&bytes), "text/plain")
} else {
classify(&s.path, &bytes)?
};
if kind == "text" {
let name = s.path.file_name().and_then(|n| n.to_str());
content_type =
Format::detect(s.format.as_deref(), None, if s.content.is_some() { None } else { name }).content_type();
}
let params = json!({
"name": s.name,
"platform": s.platform,
"kind": kind,
"fingerprint": fingerprint,
"sha256": visualci_core::sha256_hex(&bytes),
"size": bytes.len(),
"content_type": content_type,
"threshold": s.threshold,
"engine": s.engine,
"format": s.format,
"ignore": s.ignore,
});
Ok((params, bytes))
}

/// A registration as a manifest entry, normalized as the server stores the snapshot (`models::build_groups::entry_of`):
/// a text snapshot's format as the server detects it, the ignore rules as their full JSON.
///
/// # Errors
/// When the ignore rules aren't valid.
pub fn entry_of(params: &serde_json::Value) -> Result<visualci_core::manifest::Entry> {
let str_of = |k: &str| params[k].as_str().map(str::to_string);
let kind = str_of("kind").unwrap_or_default();
let name = str_of("name").unwrap_or_default();
let format = (kind == "text").then(|| {
Format::detect(params["format"].as_str(), params["content_type"].as_str(), Some(&name)).as_str().to_string()
});
let ignore: visualci_core::snapshot_text::IgnoreRules = if params["ignore"].is_null() {
visualci_core::snapshot_text::IgnoreRules::default()
} else {
serde_json::from_value(params["ignore"].clone()).context("reading a snapshot's ignore rules")?
};
Ok(visualci_core::manifest::Entry {
name,
platform: str_of("platform").unwrap_or_default(),
kind,
fingerprint: str_of("fingerprint").unwrap_or_default(),
format,
engine: str_of("engine"),
threshold: params["threshold"].as_f64(),
ignore_anti_aliasing: params["ignore_anti_aliasing"].as_bool(),
ignore: serde_json::to_value(ignore)?,
})
}

/// Kind, fingerprint and content type of a file.
pub fn classify(path: &Path, bytes: &[u8]) -> Result<(&'static str, String, &'static str)> {
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
Expand Down
54 changes: 47 additions & 7 deletions crates/visualci-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -613,8 +613,7 @@ fn run() -> Result<()> {
eprintln!("visualci: nothing to upload (--allow-empty)");
return Ok(());
}
let (registered, uploaded) = client.add_snapshots(&build_id(build)?, &snapshots)?;
eprintln!("{registered} snapshots, {uploaded} uploaded");
send_snapshots(&client, &build_id(build)?, &snapshots)?;
}
Command::Compare { names, platform, build, wait, timeout, json, connection } => {
let client = Client::from_env(connection.api_url, connection.token, connection.project)?;
Expand Down Expand Up @@ -693,8 +692,7 @@ fn run() -> Result<()> {
let snapshots = configured_uploads(&snapshot)?;
client::check_unique(&snapshots)?;
if !snapshots.is_empty() {
let (registered, uploaded) = client.add_snapshots(&build.id, &snapshots)?;
eprintln!("{registered} snapshots, {uploaded} uploaded");
send_snapshots(&client, &build.id, &snapshots)?;
}
}
// Finalized whatever happened to the tests: a run that sent nothing (it failed before any snapshot) too.
Expand All @@ -714,8 +712,8 @@ fn run() -> Result<()> {
if snapshots.is_empty() {
bail!("nothing to check: no snapshot files in {}", describe_paths(&paths));
}
let (registered, uploaded) = client.add_snapshots(&build.id, &snapshots)?;
eprintln!("{registered} snapshots, {uploaded} uploaded; waiting for build #{}", build.number);
send_snapshots(&client, &build.id, &snapshots)?;
eprintln!("waiting for build #{}", build.number);
client.finalize(&build.id, None, false)?;
let build = client.wait(&build.id, Duration::from_secs(timeout))?;
print_build(&client, &build)?;
Expand Down Expand Up @@ -814,7 +812,49 @@ impl Drop for IgnoreInterrupts {
}
}

/// The device-code sign-in:/// The device-code sign-in: ask for a code pair, show the link and code, wait for the person to approve it in the
/// From this many snapshots, a run first sends its manifest and group hashes (sc-8868), then only the groups that
/// changed. `VISUALCI_GROUPS=0` turns that off, `VISUALCI_GROUPS=1` turns it on for any size.
const GROUP_MIN: usize = 500;

/// Send snapshots to a build and say what happened. A large suite (`GROUP_MIN`) asks first which groups of names
/// match their baselines, and sends only the others: the server carries the matched ones forward, charged per group.
fn send_snapshots(client: &Client, build_id: &str, snapshots: &[Snapshot]) -> Result<()> {
let grouped = match std::env::var("VISUALCI_GROUPS").as_deref() {
Ok("0" | "false") => false,
Ok("1" | "true") => true,
_ => snapshots.len() >= GROUP_MIN,
};
if !grouped {
let (registered, uploaded) = client.add_snapshots(build_id, snapshots)?;
eprintln!("{registered} snapshots, {uploaded} uploaded");
return Ok(());
}
let group_depth = config_file::discover().ok().flatten().and_then(|f| f.config.group_depth);
let entries = snapshots
.iter()
.map(|s| client::registration(s).and_then(|(params, _)| client::entry_of(&params)))
.collect::<Result<Vec<_>>>()?;
let check = client.check_groups(build_id, &entries, group_depth)?;
if let Some(n) = check.same_as_build {
eprintln!("{} snapshots: nothing changed since build #{n}", snapshots.len());
return Ok(());
}
let grouping = group_depth
.map_or(visualci_core::manifest::Grouping::default(), |d| visualci_core::manifest::Grouping::Depth(d as usize));
let changed: std::collections::HashSet<&str> = check.changed.iter().map(String::as_str).collect();
let send: Vec<Snapshot> =
snapshots.iter().filter(|s| changed.contains(grouping.key(&s.name).as_str())).cloned().collect();
let (registered, uploaded) = if send.is_empty() { (0, 0) } else { client.add_snapshots(build_id, &send)? };
eprintln!(
"{} snapshots: {} of {} groups unchanged; {registered} sent, {uploaded} uploaded",
snapshots.len(),
check.unchanged.len(),
check.unchanged.len() + check.changed.len()
);
Ok(())
}

/// The device-code sign-in:/// The device-code sign-in:/// The device-code sign-in: ask for a code pair, show the link and code, wait for the person to approve it in the
/// browser, then keep the personal access token it gives.
fn login(api: &str, no_browser: bool) -> Result<()> {
let http = reqwest::blocking::Client::builder()
Expand Down
4 changes: 4 additions & 0 deletions crates/visualci-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ pub struct Config {
/// unapproved changes) or `wait` (`finalize --wait` waits for a decision).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ci_mode: Option<CiMode>,
/// Large suites: names are grouped for group hashes by their first this many path segments (by default, all but
/// the last two). A group whose snapshots match their baselines isn't sent again (sc-8868).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub group_depth: Option<u32>,
/// What a bare `visualci upload` sends.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub uploads: Vec<Upload>,
Expand Down
1 change: 1 addition & 0 deletions crates/visualci-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub mod align;
pub mod config;
pub mod diff;
pub mod image_hash;
pub mod manifest;
pub mod pdf;
/// Text snapshots: the `snapshot-diff` crate.
pub mod snapshot_text {
Expand Down
Loading
Loading