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
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
//! `projects.comment_when_unchanged` (c2da705, #90): whether VisualCI comments on a pull request whose builds are all
//! unchanged. Off by default, for every project: such a pull request gets only the passing check.

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.query("ALTER TABLE projects ADD COLUMN comment_when_unchanged boolean DEFAULT false NOT NULL")
.unprepared()
.await?;
Ok(())
}
4 changes: 3 additions & 1 deletion app/src/domain/comments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ 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.
/// Where a thread is pinned, in pixels of the pinned side's own image (base or head), from its top left. Pixels, not
/// fractions: when a full-page screenshot grows at the bottom in a later build of the branch, a pin stays on the same
/// content. They're also the units of the regions `get_snapshot` gives.
#[derive(Debug, Clone, PartialEq, Deserialize, schemars::JsonSchema)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Anchor {
Expand Down
281 changes: 280 additions & 1 deletion app/src/domain/projects.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! Project settings the domain reads.
//! Projects: making one, its settings (as the MCP tools and the web app read and change them), and what the domain
//! reads from them.

use visualci_core::config::ScopedIgnoreRule;

Expand Down Expand Up @@ -39,3 +40,281 @@ pub fn diff_options(
pub fn renderer_key(engine: &str, dpi: i32, renderer_version: &str) -> String {
format!("{engine}/{dpi}dpi/{renderer_version}")
}

/// Lowercase letters, digits and dashes, at most 60, and not `billing` (the organization's billing page is
/// `app.visualci.com/<org>/billing`).
#[must_use]
pub fn valid_slug(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 60
&& s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
&& s != "billing"
}

/// A project's settings, as the web app shows them and the MCP server returns them.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Settings {
pub slug: String,
pub name: String,
/// The forge the repository is on (`github`), and the repository's URL.
pub forge: Option<String>,
pub repository_url: Option<String>,
/// Whether the forge's app is installed on the repository, so pull requests get VisualCI's check and people's
/// access follows their permission on it.
pub forge_app_installed: bool,
/// When the forge's webhook last delivered a verified event, or VisualCI added it (GitLab).
pub forge_webhook_at: Option<String>,
/// Whether the screenshots visualci.yml's `gallery` names are public.
pub gallery_enabled: bool,
/// Whether project tokens may approve changes over MCP; off keeps approving with people.
pub tokens_can_approve: bool,
/// Whether VisualCI comments on a pull request whose builds are all unchanged. Off by default: the VisualCI check
/// still passes, and a comment already there (an earlier build had changes) keeps being updated.
pub comment_when_unchanged: bool,
/// Whether anyone, signed in or not, can read the project's builds and diffs (open source). Settings, tokens and
/// reviewing stay with its members.
pub public: bool,
/// The forge says the linked repository is public (checked on linking and once a day). Only then can the project
/// be public.
pub repository_public: bool,
/// The forge verified the repository as public with an OSI-approved licence (checked on linking and once a day).
pub open_source: bool,
/// Why it isn't open source, or its licence when it is.
pub open_source_note: Option<String>,
/// Whether its builds draw from the open source pool now: open source, public, and not withdrawn by staff.
pub open_source_pool: bool,
pub open_source_withdrawn: bool,
/// A change VisualCI made on its own (made private when its repository went private), until it's dismissed.
pub notice: Option<String>,
pub default_branch: String,
pub ci_mode: String,
pub renderer: String,
pub dpi: i32,
pub threshold: f64,
pub ignore_anti_aliasing: bool,
pub ignore_rules: Vec<ScopedIgnoreRule>,
}

impl From<&Project> for Settings {
fn from(p: &Project) -> Self {
Self {
slug: p.slug.clone(),
name: p.name.clone(),
forge: p.forge.clone(),
repository_url: p.repository_url.clone(),
forge_app_installed: p.forge_installation.is_some(),
forge_webhook_at: p.forge_webhook_at.map(|d| d.to_string()),
gallery_enabled: p.gallery_enabled,
tokens_can_approve: p.tokens_can_approve,
comment_when_unchanged: p.comment_when_unchanged,
public: p.public,
repository_public: p.repository_public,
open_source: p.open_source,
open_source_note: p.open_source_note.clone(),
open_source_pool: super::credits::counts_as_open_source(p),
open_source_withdrawn: p.open_source_withdrawn,
notice: p.notice.clone(),
default_branch: p.default_branch.clone(),
ci_mode: p.ci_mode.clone(),
renderer: p.renderer.clone(),
dpi: p.dpi,
threshold: p.threshold,
ignore_anti_aliasing: p.ignore_anti_aliasing,
ignore_rules: ignore_rules(p),
}
}
}

/// Changes to a project's settings; fields left out stay as they are.
#[derive(Debug, Default, serde::Deserialize, schemars::JsonSchema)]
pub struct SettingsChange {
/// A new slug, renaming the project (`acme/old` → `acme/new`): lowercase letters, digits and dashes. Its builds,
/// baselines and tokens stay. The old address and `acme/old` stop working.
pub slug: Option<String>,
/// The project's display name.
pub name: Option<String>,
/// The repository this project tests, by URL (`https://github.com/acme/web`); an empty string unlinks it.
/// Linking needs the forge's VisualCI app installed on the repository and you to be an admin or maintainer of
/// it there. Its pull requests then get VisualCI's check, and people's access to this organization follows their
/// permission on it.
pub repository_url: Option<String>,
/// A project on your organization's own GitLab instance: an access token for it (a project or group access token
/// with the `api` scope and the Developer role, or Maintainer to let VisualCI add its webhook), sent with
/// `repository_url`. Stored encrypted; never shown again.
pub forge_token: Option<String>,
/// With `repository_url`: a repository belongs to one organization, so when another organization has it linked,
/// `true` moves the link here (you must maintain the repository; that organization's admins get an email).
#[serde(default)]
pub move_link: bool,
/// `false` takes the public gallery down (visualci.yml's `gallery` decides what's in it); `true` puts it back.
pub gallery_enabled: Option<bool>,
/// `false`: project tokens can't approve changes (people do); `true` lets CI's agents approve again.
pub tokens_can_approve: Option<bool>,
/// `true`: comment on pull requests even when nothing changed. `false` (the default): a pull request whose builds
/// are all unchanged gets no comment, only the passing check; a comment already there keeps being updated.
pub comment_when_unchanged: Option<bool>,
/// `true` lets anyone, signed in or not, read the project's builds and diffs (for open source projects);
/// settings, tokens and reviewing stay with its members. Only a project linked to a public repository can be
/// public. `false` makes it private again.
pub public: Option<bool>,
/// `true` dismisses the project's notice.
pub dismiss_notice: Option<bool>,
/// The branch whose builds become the baseline automatically.
pub default_branch: Option<String>,
/// `review` (CI passes, the check waits for review), `strict` (CI fails on unreviewed changes) or `wait`.
pub ci_mode: Option<String>,
/// The PDF renderer: `pdfbox` or `mutool`.
pub renderer: Option<String>,
/// Render resolution for documents, 36 to 600.
pub dpi: Option<i32>,
/// The diff threshold, 0 to 1: 0 compares exactly; above 0 it's pixelmatch's colour threshold (how different a
/// pixel's colour must be to count), and anti-aliased pixels are ignored.
pub threshold: Option<f64>,
/// Ignore anti-aliasing differences in images.
pub ignore_anti_aliasing: Option<bool>,
/// Values in text snapshots that change on every run, ignored when comparing. Replaces the project's rules. Each
/// rule names the snapshots it applies to with a glob (`api/invoices/**`; `**` for every snapshot). A build's
/// `visualci.yml` replaces these rules when it has `ignore`.
pub ignore_rules: Option<Vec<ScopedIgnoreRule>>,
}

/// Make a project in an organization, with the default settings.
///
/// # Errors
/// `Ok(Err(message))` for a slug that isn't valid or is taken; `Err` on a database error.
pub async fn create(organization_id: i64, slug: &str, name: &str) -> laravel::Result<Result<Project, String>> {
if !valid_slug(slug) {
return Ok(Err("project slugs use lowercase letters, digits and dashes, and can't be billing".into()));
}
let taken =
Project::query().filter(Project::organization_id.eq(organization_id) & Project::slug.eq(slug)).exists().await?;
if taken {
return Ok(Err(format!("the organization already has a project called {slug}")));
}
let name = name.trim();
Ok(Ok(laravel::model::create!(Project {
pid: laravel::str::uuid7(),
organization_id: organization_id,
slug: slug,
name: name,
})
.await?))
}

/// The repository its newest CI build named (`environment_info.repository_url`), for suggesting a link.
///
/// # Errors
/// On a database error.
pub async fn repository_seen_in_ci(project: &Project) -> laravel::Result<Option<String>> {
let project_id = project.id;
let info: Option<serde_json::Value> = laravel::db::query!(
"SELECT environment_info FROM builds WHERE project_id = {project_id} AND mode = 'ci' ORDER BY id DESC LIMIT 1"
)
.scalar()
.await?;
Ok(info
.as_ref()
.and_then(|i| i.get("repository_url"))
.and_then(|v| v.as_str())
.and_then(crate::forge::Repository::parse)
.map(|r| r.url))
}

/// Apply a settings change, checking every field first. The repository link isn't set here: it needs the forge to agree
/// (subdomains' `forge::link::link_repository`), which callers do first. Turning the gallery off purges what it
/// published first.
///
/// # Errors
/// `Ok(Err(message))` for a value that isn't valid; `Err` on a database error.
pub async fn change_settings(project: Project, p: SettingsChange) -> laravel::Result<Result<Project, String>> {
let new_slug = p.slug.as_deref().map(str::trim).filter(|s| *s != project.slug).map(str::to_string);
if let Some(slug) = &new_slug {
if !valid_slug(slug) {
return Ok(Err("slug must be lowercase letters, digits and dashes, at most 60 characters".into()));
}
let taken = Project::query()
.filter(Project::organization_id.eq(project.organization_id) & Project::slug.eq(slug.as_str()))
.exists()
.await?;
if taken {
return Ok(Err(format!("the organization already has a project called {slug}")));
}
}
// A private repository's screenshots stay private: only a project whose repository the forge says is public can
// be made public.
if p.public == Some(true) && !project.public && !project.repository_public {
return Ok(Err("only a project linked to a public repository can be public".into()));
}
if let Some(m) = &p.ci_mode
&& !["review", "strict", "wait"].contains(&m.as_str())
{
return Ok(Err("ci_mode must be review, strict or wait".into()));
}
if let Some(r) = &p.renderer
&& !["pdfbox", "mutool"].contains(&r.as_str())
{
return Ok(Err("renderer must be pdfbox or mutool".into()));
}
if p.dpi.is_some_and(|d| !(36..=600).contains(&d)) {
return Ok(Err("dpi must be 36 to 600".into()));
}
if p.threshold.is_some_and(|t| !(0.0..=1.0).contains(&t)) {
return Ok(Err("threshold must be between 0 and 1".into()));
}
let ignore_rules = match p.ignore_rules {
Some(rules) => {
let clean = |v: Vec<String>| -> Vec<String> {
v.into_iter().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
};
let rules: Vec<ScopedIgnoreRule> = rules
.into_iter()
.map(|r| ScopedIgnoreRule {
snapshots: r.snapshots.trim().to_string(),
json_paths: clean(r.json_paths),
text_patterns: clean(r.text_patterns),
})
.collect();
if let Err(e) = visualci_core::config::validate_ignore_rules(&rules) {
return Ok(Err(e));
}
Some(serde_json::to_value(rules).unwrap_or_default())
}
None => None,
};
if p.gallery_enabled == Some(false) && project.gallery_enabled {
super::gallery::purge_project(project.id).await?;
}
let mut project = project;
let slug = new_slug.unwrap_or_else(|| project.slug.clone());
let name = p.name.unwrap_or_else(|| project.name.clone());
let tokens_can_approve = p.tokens_can_approve.unwrap_or(project.tokens_can_approve);
let comment_when_unchanged = p.comment_when_unchanged.unwrap_or(project.comment_when_unchanged);
let gallery_enabled = p.gallery_enabled.unwrap_or(project.gallery_enabled);
let public = p.public.unwrap_or(project.public);
let notice = if p.dismiss_notice == Some(true) { None } else { project.notice.clone() };
let default_branch = p.default_branch.unwrap_or_else(|| project.default_branch.clone());
let ci_mode = p.ci_mode.unwrap_or_else(|| project.ci_mode.clone());
let renderer = p.renderer.unwrap_or_else(|| project.renderer.clone());
let dpi = p.dpi.unwrap_or(project.dpi);
let threshold = p.threshold.unwrap_or(project.threshold);
let ignore_anti_aliasing = p.ignore_anti_aliasing.unwrap_or(project.ignore_anti_aliasing);
let ignore_rules = ignore_rules.unwrap_or_else(|| project.ignore_rules.clone());
laravel::model::update!(project {
slug,
name,
tokens_can_approve,
comment_when_unchanged,
gallery_enabled,
public,
notice,
default_branch,
ci_mode,
renderer,
dpi,
threshold,
ignore_anti_aliasing,
ignore_rules,
})
.await?;
Ok(Ok(project))
}
56 changes: 56 additions & 0 deletions app/src/mcp/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,38 @@ pub struct OrgArgs {
pub org: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct InviteArgs {
/// The organization's slug.
pub org: String,
/// An email address, or a GitHub login (`octocat` or `@octocat`).
pub invitee: String,
/// `admin` (settings, projects, tokens, billing, members), `member` (send builds, review and approve) or `read`.
pub role: InviteRole,
}

/// A member's role, lowest first.
#[derive(Clone, Copy, Debug, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum InviteRole {
/// Sees builds and snapshots; changes nothing.
Read,
/// Everything a build needs: uploads, review and approval.
Member,
/// Also settings, projects, tokens, billing and members.
Admin,
}

impl From<InviteRole> for crate::auth::Role {
fn from(r: InviteRole) -> Self {
match r {
InviteRole::Read => Self::Read,
InviteRole::Member => Self::Member,
InviteRole::Admin => Self::Admin,
}
}
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct CreateOrgArgs {
/// Lowercase letters, digits and dashes; used in URLs.
Expand All @@ -42,6 +74,14 @@ pub struct ProjectArgs {
pub project: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct UpdateProjectArgs {
/// `org/project`. Optional with a project token.
pub project: Option<String>,
#[serde(flatten)]
pub change: crate::domain::projects::SettingsChange,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct CreateTokenArgs {
/// `org/project`. Optional with a project token.
Expand Down Expand Up @@ -435,3 +475,19 @@ pub struct SupportSendArgs {
pub agent: Option<serde_json::Value>,
pub idempotency_key: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct DownloadArgs {
/// `org/project`. Optional with a project token.
pub project: Option<String>,
pub build: BuildRef,
/// Which snapshots: `changed` (the default), `added`, `removed`, `unchanged`, or `all`.
pub state: Option<String>,
/// Which images of each page: `base`, `head`, `diff`, `regions` (the head cropped to the changes). Default: base,
/// head and diff.
pub sides: Option<Vec<String>>,
/// Only snapshots whose name matches this glob, like `v2/pdfjs/**`.
pub glob: Option<String>,
/// Seconds to wait for the archive (default 50, at most 60). Not ready by then: call again with the same arguments.
pub wait: Option<u64>,
}
Loading
Loading