From b69393bf614f30dbf3ea2f304a0f557c5175b024 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:09:35 +1300 Subject: [PATCH 1/6] app/: project settings in domain::projects (sc-8900): Settings, SettingsChange, change_settings (a gallery turned off is purged first), create, valid_slug and repository_seen_in_ci, for the MCP tools and subdomains' web UI alike --- app/src/domain/projects.rs | 272 ++++++++++++++++++++++++++++++++++++- 1 file changed, 271 insertions(+), 1 deletion(-) diff --git a/app/src/domain/projects.rs b/app/src/domain/projects.rs index 51397382..a461b8d5 100644 --- a/app/src/domain/projects.rs +++ b/app/src/domain/projects.rs @@ -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; @@ -39,3 +40,272 @@ 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//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, + pub repository_url: Option, + /// 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, + /// 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 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, + /// 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, + 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, +} + +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, + 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, + /// The project's display name. + pub name: Option, + /// 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, + /// 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, + /// 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, + /// `false`: project tokens can't approve changes (people do); `true` lets CI's agents approve again. + pub tokens_can_approve: Option, + /// `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, + /// `true` dismisses the project's notice. + pub dismiss_notice: Option, + /// The branch whose builds become the baseline automatically. + pub default_branch: Option, + /// `review` (CI passes, the check waits for review), `strict` (CI fails on unreviewed changes) or `wait`. + pub ci_mode: Option, + /// The PDF renderer: `pdfbox` or `mutool`. + pub renderer: Option, + /// Render resolution for documents, 36 to 600. + pub dpi: Option, + /// 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, + /// Ignore anti-aliasing differences in images. + pub ignore_anti_aliasing: Option, + /// 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>, +} + +/// 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> { + 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> { + let project_id = project.id; + let info: Option = 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> { + 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| -> Vec { + v.into_iter().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect() + }; + let rules: Vec = 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 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, + gallery_enabled, + public, + notice, + default_branch, + ci_mode, + renderer, + dpi, + threshold, + ignore_anti_aliasing, + ignore_rules, + }) + .await?; + Ok(Ok(project)) +} From 5f24fabacc9f4f3044e02acdf46aeb10ab26bde9 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:09:35 +1300 Subject: [PATCH 2/6] app/: the rest of the public MCP server (sc-8900): whoami (with via), list_organizations, get_organization, create_project, get_project, update_project and download_build; list_builds as one short line per build (sc-8891, part 1); create_project_token, delete_project_token, invite_member and create_organization registered, waiting for #70; the comment anchor's schema text as today's; golden files can be rewritten on purpose (VISUALCI_GOLDEN_UPDATE) --- app/src/domain/comments.rs | 4 +- app/src/mcp/args.rs | 56 ++ app/src/mcp/mod.rs | 603 +++++++++++++++++- .../whoami-2.json | 6 +- .../whoami.json | 6 +- .../whoami.json | 6 +- .../whoami.json | 6 +- .../create_build-2.json | 52 ++ .../create_build.json | 50 ++ .../finalize_build.json | 50 ++ .../list_builds.json | 43 ++ .../tools-list-project-token.json | 70 +- .../tools-list-user-token.json | 70 +- app/tests/golden/mod.rs | 10 +- app/tests/mcp.rs | 424 +++++++++++- 15 files changed, 1419 insertions(+), 37 deletions(-) create mode 100644 app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build-2.json create mode 100644 app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build.json create mode 100644 app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/finalize_build.json create mode 100644 app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/list_builds.json diff --git a/app/src/domain/comments.rs b/app/src/domain/comments.rs index 65523701..d87326ab 100644 --- a/app/src/domain/comments.rs +++ b/app/src/domain/comments.rs @@ -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 { diff --git a/app/src/mcp/args.rs b/app/src/mcp/args.rs index 85bf9c2d..eaf8239f 100644 --- a/app/src/mcp/args.rs +++ b/app/src/mcp/args.rs @@ -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 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. @@ -42,6 +74,14 @@ pub struct ProjectArgs { pub project: Option, } +#[derive(Debug, Deserialize, JsonSchema)] +pub struct UpdateProjectArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + #[serde(flatten)] + pub change: crate::domain::projects::SettingsChange, +} + #[derive(Debug, Deserialize, JsonSchema)] pub struct CreateTokenArgs { /// `org/project`. Optional with a project token. @@ -435,3 +475,19 @@ pub struct SupportSendArgs { pub agent: Option, pub idempotency_key: Option, } + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct DownloadArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub build: BuildRef, + /// Which snapshots: `changed` (the default), `added`, `removed`, `unchanged`, or `all`. + pub state: Option, + /// Which images of each page: `base`, `head`, `diff`, `regions` (the head cropped to the changes). Default: base, + /// head and diff. + pub sides: Option>, + /// Only snapshots whose name matches this glob, like `v2/pdfjs/**`. + pub glob: Option, + /// Seconds to wait for the archive (default 50, at most 60). Not ready by then: call again with the same arguments. + pub wait: Option, +} diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index 636ec1a2..0ef8ed90 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -15,6 +15,7 @@ use std::sync::OnceLock; use axum::response::{IntoResponse, Response}; use base64::Engine; +use laravel::db; use rmcp::{ ErrorData, ServerHandler, handler::server::{router::tool::ToolRouter, wrapper::Parameters}, @@ -281,7 +282,6 @@ impl VisualCi { } } - #[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(); @@ -294,6 +294,142 @@ impl VisualCi { Ok(out) } + /// An organization the caller may see, with the caller's role as text: `admin`, `member` or `read`, or `project` + /// for a project token's own organization. + async fn org( + rc: &RequestContext, + slug: &str, + ) -> Result, ErrorData> { + let Some(principal) = principal_of(rc) else { return Ok(Err("missing token".into())) }; + let not_found = || Err(format!("no organization {slug} that this token can see")); + let Some(org) = Organization::query().filter(Organization::slug.eq(slug)).first().await.map_err(internal)? + else { + return Ok(not_found()); + }; + match principal { + Principal::User { user, .. } => match Self::role_of(org.id, user.id).await? { + Some(role) => Ok(Ok((org, role.as_str().to_string()))), + None => Ok(not_found()), + }, + Principal::Project { project_id, .. } => { + let project = Project::find_or_fail(project_id).await.map_err(internal)?; + if project.organization_id == org.id { Ok(Ok((org, "project".into()))) } else { Ok(not_found()) } + } + } + } + + /// A person's role in an organization. + async fn role_of(organization_id: i64, user_id: i64) -> Result, ErrorData> { + let role: Option = db::query!( + "SELECT role FROM memberships WHERE organization_id = {organization_id} AND user_id = {user_id}" + ) + .scalar() + .await + .map_err(internal)?; + Ok(role.as_deref().and_then(Role::parse)) + } + + /// A person's organizations, by slug. + async fn organizations_of(user_id: i64) -> Result, ErrorData> { + db::query!( + "SELECT o.* FROM organizations o JOIN memberships m ON m.organization_id = o.id \ + WHERE m.user_id = {user_id} ORDER BY o.slug" + ) + .select_as() + .await + .map_err(internal) + } + + /// An organization's projects, by slug. + async fn projects_of(organization_id: i64) -> Result, ErrorData> { + Project::query() + .filter(Project::organization_id.eq(organization_id)) + .order_by(Project::slug.asc()) + .get() + .await + .map_err(internal) + } + + /// What the caller runs as, for whoami: the token's name, or the MCP client's. + fn via_json(rc: &RequestContext) -> serde_json::Value { + let Some(principal) = principal_of(rc) else { return serde_json::Value::Null }; + let client = principal.client(); + match client.token_name { + Some(name) => json!({ "source": client.source, "token_name": name }), + None => { + let parts = rc.extensions.get::(); + let name = parts.and_then(|p| p.extensions.get::()).map(|c| c.0.clone()); + json!({ "source": client.source, "client_name": name.or(client.client_id) }) + } + } + } + + /// For someone whose projects have no builds yet: the public demo project and its newest build, to look at with + /// `get_build` and `get_snapshot` before sending anything. + async fn demo_if_new(reachable: &[Project]) -> Result, ErrorData> { + let ids: Vec = reachable.iter().map(|p| p.id).collect(); + if !ids.is_empty() && Build::query().filter(Build::project_id.is_in(ids)).exists().await.map_err(internal)? { + return Ok(None); + } + let (org, slug) = (domain::demo::ORG, domain::demo::PROJECT); + let Some(demo) = crate::http::api::project_by_slugs(org, slug).await.map_err(internal)? else { + return Ok(None); + }; + if !demo.public { + return Ok(None); + } + let newest = domain::builds::recent(demo.id, None, false, 20) + .await + .map_err(internal)? + .into_iter() + .find(|b| b.conclusion.as_deref() == Some("changes")); + Ok(Some(json!({ + "project": format!("{org}/{slug}"), + "build": newest.as_ref().map(|b| b.number), + "url": format!("{}/{org}/{slug}", app_url()), + "note": "Your projects have no builds yet. This public demo shows what a review looks like: try get_build and get_snapshot on it (read-only).", + }))) + } + + /// A build in a list (sc-8891): only what tells builds apart, with its counts as words. get_build has the rest. + fn build_line(org: &str, project: &Project, b: &Build, waits: bool) -> serde_json::Value { + let stats = domain::builds::stats(b); + let counts = [ + (stats.changed, "changed"), + (stats.added, "added"), + (stats.removed, "removed"), + (stats.failed, "failed"), + (stats.pending, "pending"), + ]; + let parts: Vec = counts.iter().filter(|(n, _)| *n > 0).map(|(n, what)| format!("{n} {what}")).collect(); + // "unchanged" only for a build that finished comparing: one still receiving (or failed) compared nothing yet. + let changes = match (parts.is_empty(), b.state.as_str()) { + (false, _) => parts.join(", "), + (true, "completed") => "unchanged".to_string(), + (true, _) => "not compared".to_string(), + }; + let mut v = json!({ + "number": b.number, + "branch": b.branch, + "commit": b.commit_sha.chars().take(12).collect::(), + "pr_number": b.pr_number, + "state": b.state, + "conclusion": b.conclusion, + "review_state": b.review_state, + "waiting_for_review": waits, + "changes": changes, + "url": format!("{}/{org}/{}/builds/{}", app_url(), project.slug, b.number), + "created_at": b.created_at.to_string(), + }); + if b.name != "default" { + v["name"] = json!(b.name); + } + if b.mode != "ci" { + v["mode"] = json!(b.mode); + } + v + } + async fn find_build(project: &Project, build: &str) -> Result, ErrorData> { domain::builds::find_by_ref(project.id, build).await.map_err(internal) } @@ -362,7 +498,6 @@ impl VisualCi { 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). @@ -407,6 +542,13 @@ impl VisualCi { } } +/// A subdomains function a tool needs that isn't on main yet: the tool's error until it lands. +fn not_on_main_yet(function: &str) -> CallToolResult { + tool_error(format!( + "this tool isn't available yet: it needs {function} (subdomains' organization functions, sc-8900)" + )) +} + /// 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); @@ -432,7 +574,452 @@ impl VisualCi { } #[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.", + description = "Who this token belongs to (a person or a project), how it reached VisualCI (`via`: the token's name, or the MCP client's), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", + annotations(title = "Who am I", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn whoami( + &self, + Parameters(_): Parameters, + rc: RequestContext, + ) -> Result { + let via = Self::via_json(&rc); + match principal_of(&rc) { + Some(Principal::User { user, .. }) => { + let mut orgs = Vec::new(); + let mut reachable = Vec::new(); + for org in Self::organizations_of(user.id).await? { + let role = Self::role_of(org.id, user.id).await?.map(Role::as_str); + let projects = Self::projects_of(org.id).await?; + let names: Vec = projects.iter().map(|p| format!("{}/{}", org.slug, p.slug)).collect(); + let setup = crate::auth::setup::state(org.id, Some(user.pid)).await.map_err(internal)?; + // Out of credits: why builds aren't compared, and what fixes it. + let blocked = domain::credits::blocked(&org, &app_url(), None).await.map_err(internal)?; + orgs.push(json!({ + "slug": org.slug, "name": org.name, "role": role, "projects": names, "setup": setup, + "blocked": blocked, + })); + reachable.extend(projects); + } + let waiting = Self::waiting_for_review(&reachable, Some(user.id)).await?; + let user_id = user.id; + let identities: Vec = + db::query!("SELECT forge, login FROM identities WHERE user_id = {user_id} ORDER BY id") + .select() + .await + .map_err(internal)? + .iter() + .map(|r| { + json!({ "forge": r.try_get::("forge").ok(), "login": r.try_get::("login").ok() }) + }) + .collect(); + let mut out = json!({ + "kind": "user", "name": user.name, "email": user.email, "identities": identities, + "organizations": orgs, "waiting_for_review": waiting, "via": via, + }); + let threads = Self::open_threads(&reachable).await?; + if !threads.is_empty() { + // Branches where someone asked something: an open thread blocks approving its snapshot. + out["open_comment_threads"] = json!(threads); + } + // Nothing sent yet: point at the public demo, so the first look is a real review. + if let Some(demo) = Self::demo_if_new(&reachable).await? { + out["demo"] = demo; + } + Ok(structured(out)) + } + Some(Principal::Project { project_id, .. }) => { + let p = Project::find_or_fail(project_id).await.map_err(internal)?; + let org = Self::organization_of(&p).await?; + let waiting = Self::waiting_for_review(std::slice::from_ref(&p), None).await?; + let threads = Self::open_threads(std::slice::from_ref(&p)).await?; + let blocked = domain::credits::blocked(&org, &app_url(), Some(domain::credits::Spender::of(&p))) + .await + .map_err(internal)?; + Ok(structured(json!({ + "kind": "project", "project": format!("{}/{}", org.slug, p.slug), "waiting_for_review": waiting, + "open_comment_threads": threads, "blocked": blocked, "via": via, + }))) + } + None => Ok(tool_error("missing token")), + } + } + + #[tool( + description = "The organizations this token can reach, with each one's projects, the caller's role, and its plan and credits used this month.", + annotations( + title = "List organizations", + read_only_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn list_organizations( + &self, + Parameters(_): Parameters, + rc: RequestContext, + ) -> Result { + let (orgs, only, user) = match principal_of(&rc) { + Some(Principal::User { user, .. }) => (Self::organizations_of(user.id).await?, None, Some(user.id)), + // A project token sees its own project, not the rest of the organization. + Some(Principal::Project { project_id, .. }) => { + let p = Project::find_or_fail(project_id).await.map_err(internal)?; + (vec![Self::organization_of(&p).await?], Some(p.id), None) + } + None => return Ok(tool_error("missing token")), + }; + let mut list = Vec::new(); + for org in orgs { + let projects: Vec = Self::projects_of(org.id) + .await? + .into_iter() + .filter(|p| only.is_none_or(|id| id == p.id)) + .map(|p| p.slug) + .collect(); + let role = match user { + Some(id) => Self::role_of(org.id, id).await?.map(|r| r.as_str().to_string()), + None => Some("project".to_string()), + }; + let usage = domain::credits::usage(&org).await.map_err(internal)?; + list.push( + json!({ "slug": org.slug, "name": org.name, "role": role, "usage": usage, "projects": projects }), + ); + } + Ok(structured(json!({ "organizations": list }))) + } + + #[tool( + description = "An organization: its members (role admin, member or read, and where each one's access came from: `github` when it follows their permission on the linked repositories, `invite`, `staff` or `created`), its projects (with each one's latest build), its plan, the credits used this month with what each thing costs (a snapshot check, a text diff, an image diff, a PDF page drawn) and its last 50 builds' usage. Choosing a plan and paying are left to a person in the web app.", + annotations( + title = "Get organization", + read_only_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn get_organization( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let (org, role) = need!(Self::org(&rc, &args.org)); + // A project token sees its own project and the organization's plan and usage: not the members (their emails) + // or the other projects. + let only = match principal_of(&rc) { + Some(Principal::Project { project_id, .. }) => Some(project_id), + _ => None, + }; + let mut list = Vec::new(); + for p in Self::projects_of(org.id).await? { + if only.is_some_and(|id| id != p.id) { + continue; + } + let last = match domain::builds::recent(p.id, None, false, 1).await.map_err(internal)?.first() { + Some(b) => Some(Self::build_json(&p, b, true).await?), + None => None, + }; + list.push(json!({ "project": format!("{}/{}", org.slug, p.slug), "name": p.name, "last_build": last })); + } + let usage = domain::credits::usage(&org).await.map_err(internal)?; + // The usage history names other projects' builds. + let history: Vec = if only.is_some() { + Vec::new() + } else { + let org_id = org.id; + db::query!( + "SELECT amount, kind, reference, \ + to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"+00:00\"') AS created_at \ + FROM credit_transactions \ + WHERE organization_id = {org_id} AND kind IN ('build', 'render', 'gallery') ORDER BY id DESC LIMIT 50" + ) + .select() + .await + .map_err(internal)? + .iter() + .map(|t| { + json!({ + "credits": -t.try_get::("amount").unwrap_or_default(), + "kind": t.try_get::("kind").ok(), + "reference": t.try_get::>("reference").ok().flatten(), + "created_at": t.try_get::("created_at").ok(), + }) + }) + .collect() + }; + let user_pid = principal_of(&rc).and_then(|p| p.user().map(|u| u.pid)); + let setup = crate::auth::setup::state(org.id, user_pid).await.map_err(internal)?; + let admin = role == "admin"; + let members = if only.is_some() { + Vec::new() + } else { + crate::auth::invitations::members_json(org.id, admin).await.map_err(internal)? + }; + let pending = + if admin { crate::auth::invitations::pending(org.id).await.map_err(internal)? } else { Vec::new() }; + Ok(structured(json!({ + "slug": org.slug, "name": org.name, "role": role, "usage": usage, "members": members, + "invitations": pending, "billing_url": format!("{}/{}/billing", app_url(), org.slug), "projects": list, + "usage_history": history, "setup": setup, + }))) + } + + #[tool( + description = "Invite someone to an organization by email address or GitHub login (admins, with a personal access token). They're emailed, and join with `role` (admin, member or read) once they accept it in the web app, whether or not they already have an account. People with access to a linked repository on GitHub don't need an invitation: their access follows their permission there.", + annotations( + title = "Invite member", + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn invite_member( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let (_org, role) = need!(Self::org(&rc, &args.org)); + let Some(Principal::User { .. }) = principal_of(&rc) else { + return Ok(tool_error("invitations need a personal access token")); + }; + if role != "admin" { + return Ok(tool_error(format!("only an organization's admins can invite people; you're {role}"))); + } + let _ = (&args.invitee, crate::auth::Role::from(args.role)); + // TODO(#70): app::auth::invitations::invite_to(org.id, &user, invitee, role) once it's on main. + Ok(not_on_main_yet("app::auth::invitations::invite_to")) + } + + #[tool( + description = "Create an organization with you as its admin (personal access tokens only), on the Free plan.", + annotations( + title = "Create organization", + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn create_organization( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let Some(Principal::User { .. }) = principal_of(&rc) else { + return Ok(tool_error("creating an organization needs a personal access token")); + }; + let _ = (&args.slug, &args.name); + // TODO(#70): orgs::create_org(&user, slug, name) once it's on main. + Ok(not_on_main_yet("orgs::create_org")) + } + + #[tool( + description = "Create a project in an organization (owners and admins). Then `create_project_token` for CI, and `update_project` to link its GitHub repository.", + annotations( + title = "Create project", + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn create_project( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let (org, role) = need!(Self::org(&rc, &args.org)); + if role != "admin" { + return Ok(tool_error("only an organization's admins can create projects (with a personal access token)")); + } + match domain::projects::create(org.id, &args.slug, &args.name).await.map_err(internal)? { + Ok(p) => Ok(structured(json!({ + "project": format!("{}/{}", org.slug, p.slug), "settings": domain::projects::Settings::from(&p), + }))), + Err(m) => Ok(tool_error(m)), + } + } + + #[tool( + description = "A project's settings (renderer, dpi, threshold, CI mode, default branch, linked repository) and its tokens (names and prefixes; a token itself is shown only when it's created).", + annotations(title = "Get project", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn get_project( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let org = Self::organization_of(&project).await?.slug; + // A public project's tokens are its members' business. + let member = Self::role_in(&rc, &project).await?.is_some(); + let tokens: Vec = if member { + crate::models::ProjectToken::query() + .filter(crate::models::ProjectToken::project_id.eq(project.id)) + .order_by(crate::models::ProjectToken::id.asc()) + .get() + .await + .map_err(internal)? + .into_iter() + .map(|t| { + json!({ + "id": t.id, "name": t.name, "prefix": t.token_prefix, + "last_used_at": t.last_used_at.map(|d| d.to_string()), "created_at": t.created_at.to_string(), + }) + }) + .collect() + } else { + Vec::new() + }; + Ok(structured(json!({ + "project": format!("{org}/{}", project.slug), + "url": format!("{}/{org}/{}", app_url(), project.slug), + "settings": domain::projects::Settings::from(&project), + // The repository its CI builds come from, when the project isn't linked yet: link it with + // `update_project` (`repository_url`). + "repository_seen_in_ci": domain::projects::repository_seen_in_ci(&project).await.map_err(internal)?, + // What's public: the gallery's manifest and each published screenshot's URL (visualci.yml's `gallery`). + "gallery": domain::gallery::public_list(&app_url(), &org, &project).await.map_err(internal)?, + "tokens": tokens, + }))) + } + + #[tool( + description = "Change a project's settings. Fields left out stay as they are. These are defaults: a build's visualci.yml overrides them field by field. `ignore_rules` replaces the project's rules for values in text snapshots that change on every run, as a list of `{snapshots, json_paths, text_patterns}`: `snapshots` is a required glob over snapshot names (`api/invoices/**`, `**` for all), `json_paths` like `$.generated_at`, `$.items[*].id`, `$..request_id`, and `text_patterns` regular expressions.", + annotations( + title = "Update project", + read_only_hint = false, + destructive_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn update_project( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + if let Err(e) = Self::need_role(&rc, &project, Role::Admin, "change a project's settings").await? { + return Ok(tool_error(e)); + } + let mut change = args.change; + if let Some(url) = change.repository_url.take() + && Some(url.trim()) != project.repository_url.as_deref() + { + if !matches!(principal_of(&rc), Some(Principal::User { .. })) { + return Ok(tool_error( + "linking a repository needs a person (signed in with the repository's forge, as an admin or \ + maintainer of it), not a project token", + )); + } + // TODO(subdomains): crate::forge::link::link_repository(project, &user, &url, change.forge_token, + // change.move_link) goes here once it's ported. Until then a link is refused as today's server refuses a + // forge it isn't set up for. + return Ok(tool_error(match crate::forge::Repository::parse(&url) { + Some(repository) => format!("{} isn't set up on this server", repository.forge.label()), + None => format!( + "{url:?} isn't a repository URL VisualCI knows: https://github.com/owner/name, \ + https://gitlab.com/group/project, or a project on a GitLab instance this organization added" + ), + })); + } + match domain::projects::change_settings(project, change).await.map_err(internal)? { + Ok(p) => Ok(structured(json!({ "settings": domain::projects::Settings::from(&p) }))), + Err(m) => Ok(tool_error(m)), + } + } + + #[tool( + description = "Create a project token (`vci_...`) for CI or the CLI. The token is in this answer only: store it where it's needed (e.g. as VISUALCI_TOKEN).", + annotations( + title = "Create project token", + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn create_project_token( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + if let Err(e) = Self::need_role(&rc, &project, Role::Admin, "create project tokens").await? { + return Ok(tool_error(e)); + } + if args.name.trim().is_empty() { + return Ok(tool_error("give the token a name")); + } + // TODO(#70): app::auth::tokens::make_project_token(&user, project.id, name) once it's on main. + Ok(not_on_main_yet("app::auth::tokens::make_project_token")) + } + + #[tool( + description = "Delete a project token. Anything still using it (a CI variable) stops working.", + annotations( + title = "Delete project token", + read_only_hint = false, + destructive_hint = true, + open_world_hint = false + ) + )] + async fn delete_project_token( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + if let Err(e) = Self::need_role(&rc, &project, Role::Admin, "delete project tokens").await? { + return Ok(tool_error(e)); + } + let _ = args.token_id; + // TODO(#70): app::auth::tokens::remove_project_token(project.id, id) once it's on main. + Ok(not_on_main_yet("app::auth::tokens::remove_project_token")) + } + + #[tool( + description = "Download a build's images as one tar.zst, for a close look at a big build or for checks of your own: a URL (it lasts an hour) and a summary, never the images themselves. Filter by `state` (changed by default, added, removed, unchanged, all), `sides` (base, head, diff, regions: the head cropped to the changes) and a `glob` on snapshot names. The archive has `[@platform][/page-N]/{base,head,diff,regions}.png` and `manifest.json` (each snapshot's state, pages, changed fraction, regions and files). It's built in the background: when `state` is `building`, call again with the same arguments. Free.", + annotations( + title = "Download a build's images", + read_only_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn download_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 filter = domain::downloads::Filter { state: args.state, sides: args.sides, glob: args.glob }; + let (mut download, new) = match domain::downloads::request(&build, &filter).await.map_err(internal)? { + Ok(d) => d, + Err(domain::downloads::Refused::Invalid(m) | domain::downloads::Refused::Busy(m)) => { + return Ok(tool_error(m)); + } + }; + if new { + crate::jobs::build_download::BuildDownload { download_id: download.id } + .dispatch() + .await + .map_err(internal)?; + } + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(args.wait.unwrap_or(50).min(60)); + loop { + download = crate::models::Download::find_or_fail(download.id).await.map_err(internal)?; + if !matches!(download.state.as_str(), "pending" | "building") || std::time::Instant::now() >= deadline { + break; + } + tokio::time::sleep(std::time::Duration::from_secs(2)).await; + } + let store = BlobStore::current().await.map_err(internal)?; + Ok(structured(domain::downloads::to_json(&download, &store))) + } + + #[tool( + description = "List a project's builds, newest first, one short line each: number, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, whether it waits for your review, its changes in a few words (`2 changed, 1 added`) and URL. get_build has the details (its snapshots, environment, reviews, groups, CI mode and warnings). 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( @@ -441,17 +1028,19 @@ impl VisualCi { rc: RequestContext, ) -> Result { let project = need!(Self::project(&rc, args.project.as_deref())); - let member = Self::role_in(&rc, &project).await?.is_some(); + let org = Self::organization_of(&project).await?.slug; let limit = usize::try_from(args.limit.unwrap_or(20).clamp(1, 100)).unwrap_or(20); - let mut list = Vec::new(); + let user = 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 }; + let mut list = Vec::new(); 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)) { + let waits = domain::builds::waits_for(&b, user); + if waiting && !waits { continue; } - list.push(Self::build_json(&project, &b, member).await?); + list.push(Self::build_line(&org, &project, &b, waits)); if list.len() >= limit { break; } diff --git a/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami-2.json b/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami-2.json index c7600d59..d21f6ed3 100644 --- a/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami-2.json +++ b/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami-2.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"blocked\":null,\"kind\":\"project\",\"open_comment_threads\":[],\"project\":\"/pdfs\",\"waiting_for_review\":[]}", + "text": "{\"blocked\":null,\"kind\":\"project\",\"open_comment_threads\":[],\"project\":\"/pdfs\",\"via\":{\"source\":\"project_token\",\"token_name\":\"ci\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -13,6 +13,10 @@ "kind": "project", "open_comment_threads": [], "project": "/pdfs", + "via": { + "source": "project_token", + "token_name": "ci" + }, "waiting_for_review": [] } } diff --git a/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami.json b/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami.json index 0340a7ff..9062b2d1 100644 --- a/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami.json +++ b/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"blocked\":{\"billing_url\":\"https://app.visualci.test//billing\",\"credits_limit\":25000,\"credits_used\":25000,\"fixes\":[{\"action\":\"upgrade\",\"label\":\"Upgrade to Team\",\"url\":\"https://app.visualci.test//billing\"}],\"message\":\"Org is out of VisualCI credits until 1 January 2027: it has used all 25,000 credits on the Free plan, so builds aren't compared. An admin can upgrade to Team at https://app.visualci.test//billing\",\"pack_credits\":0,\"plan\":\"Free\",\"reason\":\"out_of_credits\",\"renews_at\":\"\"},\"kind\":\"project\",\"open_comment_threads\":[],\"project\":\"/pdfs\",\"waiting_for_review\":[]}", + "text": "{\"blocked\":{\"billing_url\":\"https://app.visualci.test//billing\",\"credits_limit\":25000,\"credits_used\":25000,\"fixes\":[{\"action\":\"upgrade\",\"label\":\"Upgrade to Team\",\"url\":\"https://app.visualci.test//billing\"}],\"message\":\"Org is out of VisualCI credits until 1 January 2027: it has used all 25,000 credits on the Free plan, so builds aren't compared. An admin can upgrade to Team at https://app.visualci.test//billing\",\"pack_credits\":0,\"plan\":\"Free\",\"reason\":\"out_of_credits\",\"renews_at\":\"\"},\"kind\":\"project\",\"open_comment_threads\":[],\"project\":\"/pdfs\",\"via\":{\"source\":\"project_token\",\"token_name\":\"ci\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -29,6 +29,10 @@ "kind": "project", "open_comment_threads": [], "project": "/pdfs", + "via": { + "source": "project_token", + "token_name": "ci" + }, "waiting_for_review": [] } } diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json index 1896d6a6..992d0771 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"install_github_app\",\"steps\":[{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"waiting_for_review\":[]}", + "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"install_github_app\",\"steps\":[{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"via\":{\"source\":\"token\",\"token_name\":\"agent\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -52,6 +52,10 @@ "slug": "" } ], + "via": { + "source": "token", + "token_name": "agent" + }, "waiting_for_review": [] } } diff --git a/app/tests/golden/mcp/agents_comment_on_snapshots_and_resolve_threads/whoami.json b/app/tests/golden/mcp/agents_comment_on_snapshots_and_resolve_threads/whoami.json index c873c983..d5508555 100644 --- a/app/tests/golden/mcp/agents_comment_on_snapshots_and_resolve_threads/whoami.json +++ b/app/tests/golden/mcp/agents_comment_on_snapshots_and_resolve_threads/whoami.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"blocked\":null,\"kind\":\"project\",\"open_comment_threads\":[{\"branch\":\"feat\",\"open\":1,\"project\":\"/pdfs\"}],\"project\":\"/pdfs\",\"waiting_for_review\":[]}", + "text": "{\"blocked\":null,\"kind\":\"project\",\"open_comment_threads\":[{\"branch\":\"feat\",\"open\":1,\"project\":\"/pdfs\"}],\"project\":\"/pdfs\",\"via\":{\"source\":\"project_token\",\"token_name\":\"ci\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -19,6 +19,10 @@ } ], "project": "/pdfs", + "via": { + "source": "project_token", + "token_name": "ci" + }, "waiting_for_review": [] } } diff --git a/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build-2.json b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build-2.json new file mode 100644 index 00000000..b6ae254d --- /dev/null +++ b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build-2.json @@ -0,0 +1,52 @@ +{ + "arguments": { + "branch": "feat", + "commit": "b2c3d4e5f6", + "name": "docs", + "pr_number": 7 + }, + "result": { + "content": [ + { + "text": "{\"blocked\":null,\"branch\":\"feat\",\"ci_mode\":\"review\",\"commit\":\"b2c3d4e5f6\",\"conclusion\":null,\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"docs\",\"number\":2,\"passed\":null,\"pr_number\":7,\"project\":\"/pdfs\",\"review_state\":\"none\",\"reviewable\":false,\"reviews\":[],\"state\":\"receiving\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/2\",\"warnings\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "blocked": null, + "branch": "feat", + "ci_mode": "review", + "commit": "b2c3d4e5f6", + "conclusion": null, + "created_at": "", + "environment": "ci", + "environment_info": {}, + "error": null, + "id": "", + "mode": "ci", + "name": "docs", + "number": 2, + "passed": null, + "pr_number": 7, + "project": "/pdfs", + "review_state": "none", + "reviewable": false, + "reviews": [], + "state": "receiving", + "stats": { + "added": 0, + "changed": 0, + "config": 0, + "failed": 0, + "ignored": 0, + "pending": 0, + "removed": 0, + "total": 0, + "unchanged": 0 + }, + "url": "https://app.visualci.test//pdfs/builds/2", + "warnings": [] + } + } +} diff --git a/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build.json b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build.json new file mode 100644 index 00000000..65fc0877 --- /dev/null +++ b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build.json @@ -0,0 +1,50 @@ +{ + "arguments": { + "branch": "main", + "commit": "a1b2c3d4e5f60718293a" + }, + "result": { + "content": [ + { + "text": "{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"a1b2c3d4e5f60718293a\",\"conclusion\":null,\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":null,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"none\",\"reviewable\":false,\"reviews\":[],\"state\":\"receiving\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "blocked": null, + "branch": "main", + "ci_mode": "review", + "commit": "a1b2c3d4e5f60718293a", + "conclusion": null, + "created_at": "", + "environment": "ci", + "environment_info": {}, + "error": null, + "id": "", + "mode": "ci", + "name": "default", + "number": 1, + "passed": null, + "pr_number": null, + "project": "/pdfs", + "review_state": "none", + "reviewable": false, + "reviews": [], + "state": "receiving", + "stats": { + "added": 0, + "changed": 0, + "config": 0, + "failed": 0, + "ignored": 0, + "pending": 0, + "removed": 0, + "total": 0, + "unchanged": 0 + }, + "url": "https://app.visualci.test//pdfs/builds/1", + "warnings": [] + } + } +} diff --git a/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/finalize_build.json b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/finalize_build.json new file mode 100644 index 00000000..75843c41 --- /dev/null +++ b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/finalize_build.json @@ -0,0 +1,50 @@ +{ + "arguments": { + "allow_empty": true, + "build": "1" + }, + "result": { + "content": [ + { + "text": "{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"a1b2c3d4e5f60718293a\",\"conclusion\":null,\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":null,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"none\",\"reviewable\":false,\"reviews\":[],\"state\":\"processing\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "blocked": null, + "branch": "main", + "ci_mode": "review", + "commit": "a1b2c3d4e5f60718293a", + "conclusion": null, + "created_at": "", + "environment": "ci", + "environment_info": {}, + "error": null, + "id": "", + "mode": "ci", + "name": "default", + "number": 1, + "passed": null, + "pr_number": null, + "project": "/pdfs", + "review_state": "none", + "reviewable": false, + "reviews": [], + "state": "processing", + "stats": { + "added": 0, + "changed": 0, + "config": 0, + "failed": 0, + "ignored": 0, + "pending": 0, + "removed": 0, + "total": 0, + "unchanged": 0 + }, + "url": "https://app.visualci.test//pdfs/builds/1", + "warnings": [] + } + } +} diff --git a/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/list_builds.json b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/list_builds.json new file mode 100644 index 00000000..150d0f86 --- /dev/null +++ b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/list_builds.json @@ -0,0 +1,43 @@ +{ + "arguments": {}, + "result": { + "content": [ + { + "text": "{\"builds\":[{\"branch\":\"feat\",\"changes\":\"not compared\",\"commit\":\"b2c3d4e5f6\",\"conclusion\":null,\"created_at\":\"\",\"name\":\"docs\",\"number\":2,\"pr_number\":7,\"review_state\":\"none\",\"state\":\"receiving\",\"url\":\"https://app.visualci.test//pdfs/builds/2\",\"waiting_for_review\":false},{\"branch\":\"main\",\"changes\":\"unchanged\",\"commit\":\"a1b2c3d4e5f6\",\"conclusion\":\"unchanged\",\"created_at\":\"\",\"number\":1,\"pr_number\":null,\"review_state\":\"auto_approved\",\"state\":\"completed\",\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"waiting_for_review\":false}]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "builds": [ + { + "branch": "feat", + "changes": "not compared", + "commit": "b2c3d4e5f6", + "conclusion": null, + "created_at": "", + "name": "docs", + "number": 2, + "pr_number": 7, + "review_state": "none", + "state": "receiving", + "url": "https://app.visualci.test//pdfs/builds/2", + "waiting_for_review": false + }, + { + "branch": "main", + "changes": "unchanged", + "commit": "a1b2c3d4e5f6", + "conclusion": "unchanged", + "created_at": "", + "number": 1, + "pr_number": null, + "review_state": "auto_approved", + "state": "completed", + "url": "https://app.visualci.test//pdfs/builds/1", + "waiting_for_review": false + } + ] + } + } +} diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json index ac56be47..9c376f10 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json @@ -332,6 +332,72 @@ }, "name": "delete_project_token" }, + { + "annotations": { + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": true, + "title": "Download a build's images" + }, + "description": "Download a build's images as one tar.zst, for a close look at a big build or for checks of your own: a URL (it lasts an hour) and a summary, never the images themselves. Filter by `state` (changed by default, added, removed, unchanged, all), `sides` (base, head, diff, regions: the head cropped to the changes) and a `glob` on snapshot names. The archive has `[@platform][/page-N]/{base,head,diff,regions}.png` and `manifest.json` (each snapshot's state, pages, changed fraction, regions and files). It's built in the background: when `state` is `building`, call again with the same arguments. Free.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "build": { + "type": [ + "integer", + "string" + ] + }, + "glob": { + "description": "Only snapshots whose name matches this glob, like `v2/pdfjs/**`.", + "type": [ + "string", + "null" + ] + }, + "project": { + "description": "`org/project`. Optional with a project token.", + "type": [ + "string", + "null" + ] + }, + "sides": { + "description": "Which images of each page: `base`, `head`, `diff`, `regions` (the head cropped to the changes). Default: base,\nhead and diff.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "state": { + "description": "Which snapshots: `changed` (the default), `added`, `removed`, `unchanged`, or `all`.", + "type": [ + "string", + "null" + ] + }, + "wait": { + "description": "Seconds to wait for the archive (default 50, at most 60). Not ready by then: call again with the same arguments.", + "format": "uint64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "build" + ], + "type": "object" + }, + "name": "download_build" + }, { "annotations": { "destructiveHint": false, @@ -703,7 +769,7 @@ "readOnlyHint": true, "title": "List builds" }, - "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.", + "description": "List a project's builds, newest first, one short line each: number, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, whether it waits for your review, its changes in a few words (`2 changed, 1 added`) and URL. get_build has the details (its snapshots, environment, reviews, groups, CI mode and warnings). waiting_for_review: only builds whose changes wait for a review.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, @@ -1567,7 +1633,7 @@ "readOnlyHint": true, "title": "Who am I" }, - "description": "Who this token belongs to (a person or a project), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", + "description": "Who this token belongs to (a person or a project), how it reached VisualCI (`via`: the token's name, or the MCP client's), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json index ac56be47..9c376f10 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json @@ -332,6 +332,72 @@ }, "name": "delete_project_token" }, + { + "annotations": { + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": true, + "title": "Download a build's images" + }, + "description": "Download a build's images as one tar.zst, for a close look at a big build or for checks of your own: a URL (it lasts an hour) and a summary, never the images themselves. Filter by `state` (changed by default, added, removed, unchanged, all), `sides` (base, head, diff, regions: the head cropped to the changes) and a `glob` on snapshot names. The archive has `[@platform][/page-N]/{base,head,diff,regions}.png` and `manifest.json` (each snapshot's state, pages, changed fraction, regions and files). It's built in the background: when `state` is `building`, call again with the same arguments. Free.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "build": { + "type": [ + "integer", + "string" + ] + }, + "glob": { + "description": "Only snapshots whose name matches this glob, like `v2/pdfjs/**`.", + "type": [ + "string", + "null" + ] + }, + "project": { + "description": "`org/project`. Optional with a project token.", + "type": [ + "string", + "null" + ] + }, + "sides": { + "description": "Which images of each page: `base`, `head`, `diff`, `regions` (the head cropped to the changes). Default: base,\nhead and diff.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "state": { + "description": "Which snapshots: `changed` (the default), `added`, `removed`, `unchanged`, or `all`.", + "type": [ + "string", + "null" + ] + }, + "wait": { + "description": "Seconds to wait for the archive (default 50, at most 60). Not ready by then: call again with the same arguments.", + "format": "uint64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "build" + ], + "type": "object" + }, + "name": "download_build" + }, { "annotations": { "destructiveHint": false, @@ -703,7 +769,7 @@ "readOnlyHint": true, "title": "List builds" }, - "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.", + "description": "List a project's builds, newest first, one short line each: number, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, whether it waits for your review, its changes in a few words (`2 changed, 1 added`) and URL. get_build has the details (its snapshots, environment, reviews, groups, CI mode and warnings). waiting_for_review: only builds whose changes wait for a review.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, @@ -1567,7 +1633,7 @@ "readOnlyHint": true, "title": "Who am I" }, - "description": "Who this token belongs to (a person or a project), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", + "description": "Who this token belongs to (a person or a project), how it reached VisualCI (`via`: the token's name, or the MCP client's), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, diff --git a/app/tests/golden/mod.rs b/app/tests/golden/mod.rs index faa68750..2dafa973 100644 --- a/app/tests/golden/mod.rs +++ b/app/tests/golden/mod.rs @@ -7,7 +7,8 @@ use std::sync::LazyLock; use regex::Regex; -/// Assert that `value` matches the golden file `tests/golden///.json`. +/// Assert that `value` matches the golden file `tests/golden///.json`. With +/// `VISUALCI_GOLDEN_UPDATE=1`, write it instead (an answer changed on purpose; review the diff). /// /// # Panics /// When it doesn't, showing both. @@ -17,6 +18,13 @@ pub fn check(kind: &str, test: &str, name: &str, value: &serde_json::Value) { .join(kind) .join(test) .join(format!("{name}.json")); + // A deliberate change to an answer: `VISUALCI_GOLDEN_UPDATE=1` writes the new answer, to review in the diff. + if std::env::var("VISUALCI_GOLDEN_UPDATE").is_ok_and(|v| v == "1") { + std::fs::create_dir_all(path.parent().expect("a golden file's directory")).expect("making the directory"); + let text = serde_json::to_string_pretty(&normalize(value)).expect("JSON") + "\n"; + std::fs::write(&path, text).unwrap_or_else(|e| panic!("writing {}: {e}", path.display())); + return; + } let golden: serde_json::Value = serde_json::from_str( &std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display())), ) diff --git a/app/tests/mcp.rs b/app/tests/mcp.rs index dcfaf6d9..d749b5a9 100644 --- a/app/tests/mcp.rs +++ b/app/tests/mcp.rs @@ -1,6 +1,5 @@ -//! 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. +//! The public MCP server's tools: today's answers (tests/golden/mcp) for the same calls. `whoami`'s `via` and +//! `list_builds`' compact lines are deliberate changes from today's answers. mod golden; @@ -47,7 +46,8 @@ async fn token(table: &str, owner: i64, name: &str, prefix: &str) -> laravel::Re /// 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()); + // A hyphenated UUID, as today's fixture had: the golden files' normalizer replaces it. + let email = format!("{}@example.com", laravel::str::uuid7()); 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.clone(), name: "Org" }).await?; @@ -66,13 +66,15 @@ async fn fixture() -> laravel::Result { name: "Screenshots" }) .await?; - Ok(Fixture { - org: slug, - 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?, - }) + // Token ids show in the answers. The test databases are reused with their rows rolled back, but sequences don't roll + // back, so they start again here: the project token is 1, and the next one 3, as with today's fixture (a fresh + // database, with a second project's token as 2). + db::query!("ALTER SEQUENCE project_tokens_id_seq RESTART WITH 1").statement().await?; + db::query!("ALTER SEQUENCE user_tokens_id_seq RESTART WITH 1").statement().await?; + let user_token = token("user_tokens", user.id, "agent", "vcu").await?; + let project_token = token("project_tokens", project.id, "ci", "vci").await?; + db::query!("SELECT setval('project_tokens_id_seq', 2)").statement().await?; + Ok(Fixture { org: slug, organization_id: org.id, project_id: project.id, user_token, project_token }) } /// How many times each test has called each tool, for the golden files' names (`get_build-2.json`). @@ -176,11 +178,14 @@ async fn runs_a_build_from_uploaded_files(app: Application) -> laravel::Result<( 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.) + // One text snapshot was sent and nothing was drawn or diffed: one snapshot check, one credit. 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); + // The usage history is the organization's people's to see (it names every project's builds). + let (_, org) = call(&app, TEST, &f.user_token, "get_organization", json!({ "org": f.org })).await; + assert_eq!(org["usage"]["credits_this_month"], 1, "{org}"); + assert_eq!(org["usage_history"][0]["credits"], 1, "{org}"); Ok(()) } @@ -422,7 +427,8 @@ async fn agents_comment_on_snapshots_and_resolve_threads(app: Application) -> la 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 (_, me) = call(&app, TEST, t, "whoami", json!({})).await; + assert_eq!(me["open_comment_threads"][0]["branch"], "feat", "{me}"); let (err, r) = call(&app, TEST, t, "resolve_comment", json!({ "thread": thread })).await; assert!(!err && r["resolved"] == true, "{r}"); @@ -523,14 +529,16 @@ async fn a_project_token_reaches_only_its_project(app: Application) -> laravel:: } /// 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.) +/// reject. A person's token can turn it off and on. #[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 project = format!("{}/pdfs", f.org); + let (err, s) = + call(&app, TEST, &f.user_token, "update_project", json!({ "project": project, "tokens_can_approve": false })) + .await; + assert!(!err && s["settings"]["tokens_can_approve"] == false, "{s}"); 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}"); @@ -557,8 +565,9 @@ async fn a_free_organization_over_its_allowance_gets_a_failed_build_that_says_wh 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.) + // Out of credits from the start: whoami and the new build say so, with what fixes it. + let (_, me) = call(&app, TEST, t, "whoami", json!({})).await; + assert_eq!(me["blocked"]["reason"], "out_of_credits", "{me}"); 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; @@ -583,6 +592,8 @@ async fn a_free_organization_over_its_allowance_gets_a_failed_build_that_says_wh // 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}"); + let (_, me) = call(&app, TEST, t, "whoami", json!({})).await; + assert!(me["blocked"].is_null(), "{me}"); Ok(()) } @@ -651,3 +662,376 @@ async fn team_uses_its_allowance_first_then_pack_credits_and_stops_when_both_run assert_eq!(actions, ["buy_pack", "turn_on_auto_buy"], "{done}"); Ok(()) } + +/// What the MCP TypeScript SDK checks (Executor and other clients built on it refuse the whole list otherwise): each +/// schema is an object, every property's schema is an object with a type, and arrays name their items' type. +fn check_schema(path: &str, schema: &Value) { + assert!(schema.is_object(), "{path} isn't an object: {schema}"); + if let Some(props) = schema.get("properties").and_then(Value::as_object) { + for (name, prop) in props { + assert!(prop.is_object(), "{path}.{name} isn't an object: {prop}"); + assert!(prop.get("type").is_some() || prop.get("anyOf").is_some(), "{path}.{name} has no type: {prop}"); + check_schema(&format!("{path}.{name}"), prop); + } + } + if let Some(items) = schema.get("items") { + assert!(items.get("type").is_some(), "{path}[] has no type: {items}"); + check_schema(&format!("{path}[]"), items); + } +} + +#[laravel::test] +async fn lists_the_tools_each_kind_of_token_can_use(app: Application) -> laravel::Result<()> { + const TEST: &str = "lists_the_tools_each_kind_of_token_can_use"; + let f = fixture().await?; + for (kind, token) in [("user", &f.user_token), ("project", &f.project_token)] { + let response = app + .post("/mcp") + .header("authorization", format!("Bearer {token}")) + .json(json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" })) + .header("accept", "application/json, text/event-stream") + .await; + response.assert_ok(); + let result = response.json()["result"].clone(); + let tools = result["tools"].as_array().expect("a tools list"); + assert!(!tools.is_empty()); + for tool in tools { + for key in ["inputSchema", "outputSchema"] { + let Some(schema) = tool.get(key) else { continue }; + assert_eq!(schema["type"], "object", "{} {key}", tool["name"]); + check_schema(&format!("{} {key}", tool["name"]), schema); + } + } + golden::check("mcp", TEST, &format!("tools-list-{kind}-token"), &result); + } + Ok(()) +} + +#[laravel::test] +async fn a_personal_token_manages_organizations_projects_and_tokens(app: Application) -> laravel::Result<()> { + Box::pin(personal_token_manages(app)).await +} + +async fn personal_token_manages(app: Application) -> laravel::Result<()> { + const TEST: &str = "a_personal_token_manages_organizations_projects_and_tokens"; + let f = fixture().await?; + let t = &f.user_token; + + let (err, me) = call(&app, TEST, t, "whoami", json!({})).await; + assert!(!err); + assert_eq!(me["kind"], "user"); + assert_eq!(me["organizations"][0]["projects"].as_array().unwrap().len(), 2); + assert_eq!(me["via"], json!({ "source": "token", "token_name": "agent" }), "{me}"); + + let (err, org) = call(&app, TEST, t, "get_organization", json!({ "org": f.org })).await; + assert!(!err, "{org}"); + assert_eq!(org["usage"]["plan"]["id"], "free"); + assert_eq!(org["usage"]["included_credits"], 25000); + assert_eq!(org["usage"]["credits_this_month"], 0); + + let new_org = format!("{}-b", f.org); + let (err, _) = call(&app, TEST, t, "create_organization", json!({ "slug": new_org, "name": "B" })).await; + assert!(!err); + let (err, p) = + call(&app, TEST, t, "create_project", json!({ "org": new_org, "slug": "docs", "name": "Docs" })).await; + assert!(!err, "{p}"); + let project = format!("{new_org}/docs"); + + let (err, s) = call(&app, TEST, t, "update_project", json!({ "project": project, "dpi": 150 })).await; + assert!(!err, "{s}"); + assert_eq!(s["settings"]["dpi"], 150); + assert_eq!(s["settings"]["repository_url"], Value::Null); + // Linking a repository needs the forge to agree; a URL VisualCI doesn't know is refused. + let (err, s) = call( + &app, + TEST, + t, + "update_project", + json!({ "project": project, "repository_url": "https://example.com/a/b" }), + ) + .await; + assert!(err && s.to_string().contains("isn't a repository URL"), "{s}"); + let (err, s) = call(&app, TEST, t, "update_project", json!({ "project": project, "dpi": 9000 })).await; + assert!(err, "{s}"); + + // Ignore rules for text snapshots: each scoped to a snapshot glob, checked when saved, blank lines dropped. + let (err, s) = call( + &app, + TEST, + t, + "update_project", + json!({ "project": project, "ignore_rules": [{ "snapshots": "api/**", "json_paths": ["$.generated_at", " "], + "text_patterns": ["\\d{4}-\\d{2}-\\d{2}"] }] }), + ) + .await; + assert!(!err, "{s}"); + assert_eq!(s["settings"]["ignore_rules"][0]["snapshots"], "api/**"); + assert_eq!(s["settings"]["ignore_rules"][0]["json_paths"], json!(["$.generated_at"])); + assert_eq!(s["settings"]["ignore_rules"][0]["text_patterns"], json!(["\\d{4}-\\d{2}-\\d{2}"])); + for (rules, needle) in [ + (json!([{ "snapshots": "**", "json_paths": ["$.items["] }]), "JSON path"), + (json!([{ "snapshots": "**", "text_patterns": ["("] }]), "pattern"), + (json!([{ "snapshots": "", "json_paths": ["$.a"] }]), "names the snapshots"), + (json!([{ "json_paths": ["$.a"] }]), "snapshots"), + ] { + let (err, s) = + call(&app, TEST, t, "update_project", json!({ "project": project, "ignore_rules": rules })).await; + assert!(err, "{s}"); + assert!(s.to_string().contains(needle), "{needle}: {s}"); + } + + let (err, token) = + call(&app, TEST, t, "create_project_token", json!({ "project": project, "name": "CircleCI" })).await; + assert!(!err, "{token}"); + assert!(token["token"].as_str().unwrap().starts_with("vci_")); + let (_, got) = call(&app, TEST, t, "get_project", json!({ "project": project })).await; + assert_eq!(got["tokens"].as_array().unwrap().len(), 1); + let (err, _) = + call(&app, TEST, t, "delete_project_token", json!({ "project": project, "token_id": token["id"] })).await; + assert!(!err); + + // Someone else's organization stays invisible. + let (err, _) = call(&app, TEST, t, "get_organization", json!({ "org": "nobody-else" })).await; + assert!(err); + Ok(()) +} + +#[laravel::test] +async fn projects_can_be_renamed(app: Application) -> laravel::Result<()> { + const TEST: &str = "projects_can_be_renamed"; + let f = fixture().await?; + let old = format!("{}/pdfs", f.org); + let (err, s) = + call(&app, TEST, &f.user_token, "update_project", json!({ "project": old, "slug": "monorepo" })).await; + assert!(!err, "{s}"); + assert_eq!(s["settings"]["slug"], "monorepo"); + // The old reference is gone; the new one works. + let (err, _) = call(&app, TEST, &f.user_token, "get_project", json!({ "project": old })).await; + assert!(err, "the old slug no longer finds the project"); + // Taken or invalid slugs are refused. + let renamed = format!("{}/monorepo", f.org); + let (err, got) = call(&app, TEST, &f.user_token, "get_project", json!({ "project": renamed })).await; + assert!(!err, "{got}"); + for (slug, needle) in [("shots", "already has"), ("Not OK", "lowercase")] { + let (err, e) = + call(&app, TEST, &f.user_token, "update_project", json!({ "project": renamed, "slug": slug })).await; + assert!(err, "{e}"); + assert!(e.to_string().contains(needle), "{needle}: {e}"); + } + Ok(()) +} + +/// A project token is CI's: it sends builds, reviews and comments, but can't mint tokens, change the project's settings +/// or see the organization's members, so a leaked CI secret can't keep itself alive or loosen the checks. +#[laravel::test] +async fn a_project_token_acts_as_a_member_not_an_admin(app: Application) -> laravel::Result<()> { + const TEST: &str = "a_project_token_acts_as_a_member_not_an_admin"; + let f = fixture().await?; + let t = &f.project_token; + let (err, r) = call(&app, TEST, t, "create_project_token", json!({ "name": "spare" })).await; + assert!(err, "no new tokens: {r}"); + let (err, r) = call(&app, TEST, t, "update_project", json!({ "ci_mode": "review" })).await; + assert!(err, "no settings: {r}"); + let (err, org) = call(&app, TEST, t, "get_organization", json!({ "org": f.org })).await; + assert!(!err, "{org}"); + assert_eq!(org["members"], json!([]), "no members' emails"); + assert_eq!(org["projects"].as_array().map(Vec::len), Some(1), "only its own project: {org}"); + let (_, orgs) = call(&app, TEST, t, "list_organizations", json!({})).await; + assert_eq!(orgs["organizations"][0]["projects"], json!(["pdfs"])); + // A person's token still can. + let (err, r) = call( + &app, + TEST, + &f.user_token, + "create_project_token", + json!({ "project": format!("{}/pdfs", f.org), "name": "spare" }), + ) + .await; + assert!(!err, "{r}"); + Ok(()) +} + +#[laravel::test] +async fn a_builds_visualci_yml_overrides_the_project_settings(app: Application) -> laravel::Result<()> { + Box::pin(visualci_yml_overrides(app)).await +} + +async fn visualci_yml_overrides(app: Application) -> laravel::Result<()> { + use app::domain::build_settings::BuildSettings; + use app::domain::snapshots::SnapshotParams; + use app::models::{Build, Project}; + const TEST: &str = "a_builds_visualci_yml_overrides_the_project_settings"; + let f = fixture().await?; + let t = &f.project_token; + let pdfs = format!("{}/pdfs", f.org); + // The project's own rules apply only to builds without `ignore` in their file. + let (err, s) = call( + &app, + TEST, + &f.user_token, + "update_project", + json!({ "project": pdfs, "ci_mode": "review", "ignore_rules": [{ "snapshots": "**", "json_paths": ["$.project_rule"] }] }), + ) + .await; + assert!(!err, "{s}"); + + // A rule without a scope is refused, and so is the build. + let (err, e) = call( + &app, + TEST, + t, + "create_build", + json!({ "commit": "abc", "branch": "main", "config": { "ignore": [{ "json_paths": ["$.generated_at"] }] } }), + ) + .await; + assert!(err, "{e}"); + assert!(e.to_string().contains("visualci.yml"), "{e}"); + + let config = json!({ + "ignore": [{ "snapshots": "api/**", "json_paths": ["$.generated_at"] }], + "threshold": { "screenshots/**": 0.2 }, + "pdf": { "engine": "mutool", "dpi": 200 }, + "ci_mode": "strict", + }); + let (err, build) = + call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main", "config": config })).await; + assert!(!err, "{build}"); + let (_, got) = call(&app, TEST, t, "get_build", json!({ "build": "1" })).await; + assert_eq!(got["config"]["ci_mode"], "strict", "{got}"); + assert_eq!(got["ci_mode"], "strict", "{got}"); + + let project = Project::find_or_fail(f.project_id).await?; + let build = Build::query().filter(Build::project_id.eq(project.id) & Build::number.eq(1)).first().await?.unwrap(); + let text = |name: &str, ignore: Option| { + serde_json::from_value::(json!({ + "name": name, "kind": "text", "fingerprint": "c".repeat(64), "sha256": "d".repeat(64), "size": 2, + "content_type": "application/json", "ignore": ignore, + })) + .unwrap() + }; + let settings = BuildSettings::new(&project, &build); + let mut regs = Vec::new(); + for p in [text("api/invoice", Some(json!({ "json_paths": ["$.in_test"] }))), text("other", None)] { + p.validate().unwrap(); + regs.push(app::domain::snapshots::register(&build, &settings, "test", &p).await?.unwrap().snapshot); + } + let applied = |i: usize| serde_json::to_value(settings.applied_rules(®s[i])).unwrap(); + assert_eq!( + applied(0), + json!([ + { "source": "file", "snapshots": "api/**", "json_paths": ["$.generated_at"], "text_patterns": [] }, + { "source": "test", "snapshots": null, "json_paths": ["$.in_test"], "text_patterns": [] }, + ]) + ); + // The file has `ignore`, so the project's rule doesn't apply, and its glob doesn't match `other`. + assert_eq!(applied(1), json!([])); + assert_eq!(settings.ci_mode(), "strict"); + assert_eq!(settings.renderer_key(None, "v1"), "mutool/200dpi/v1"); + assert_eq!(settings.renderer_key(Some("pdfbox"), "v1"), "pdfbox/200dpi/v1"); + let mut shot = regs[1].clone(); + shot.name = "screenshots/home".into(); + assert!((settings.diff_options(&shot).threshold - 0.2).abs() < 1e-9); + assert!((settings.diff_options(®s[1]).threshold - project.threshold).abs() < 1e-9); + + // An invalid rule in the test is refused. + assert!(text("x", Some(json!({ "json_paths": ["$.a["] }))).validate().is_err()); + + // Several rules each within the cap but over it together still all apply (each is parsed on its own). + let many: Vec = (0..150).map(|i| format!("$.k{i}")).collect(); + let (err, s) = call( + &app, + TEST, + &f.user_token, + "update_project", + json!({ "project": pdfs, "ignore_rules": [{ "snapshots": "**", "json_paths": many }] }), + ) + .await; + assert!(!err, "{s}"); + + // The file can tighten the CI mode but not loosen it. + let (err, s) = + call(&app, TEST, &f.user_token, "update_project", json!({ "project": pdfs, "ci_mode": "strict" })).await; + assert!(!err, "{s}"); + let (err, loose) = call( + &app, + TEST, + t, + "create_build", + json!({ "commit": "lmn", "branch": "main", "config": { "ci_mode": "review" } }), + ) + .await; + assert!(!err, "{loose}"); + let project = Project::find_or_fail(f.project_id).await?; + let number = i32::try_from(loose["number"].as_i64().unwrap()).unwrap(); + let loose = + Build::query().filter(Build::project_id.eq(project.id) & Build::number.eq(number)).first().await?.unwrap(); + assert_eq!(BuildSettings::new(&project, &loose).ci_mode(), "strict"); + assert!(loose.warnings.to_string().contains("only make the mode"), "{}", loose.warnings); + + // A file that hides more than its base's needs review; one that hides less doesn't. + let make = |config: Value| { + let mut b = loose.clone(); + b.config = Some(config); + b + }; + let base = make(json!({ "ignore": [{ "snapshots": "api/**", "json_paths": ["$.a"] }], "threshold": 0.1 })); + let wider = make(json!({ "ignore": [{ "snapshots": "**", "json_paths": ["$.a"] }], "threshold": 0.1 })); + let higher = make(json!({ "ignore": [{ "snapshots": "api/**", "json_paths": ["$.a"] }], "threshold": 0.3 })); + let fewer = make(json!({ "ignore": [], "threshold": 0.05 })); + let (b, w, h, l) = ( + BuildSettings::new(&project, &base), + BuildSettings::new(&project, &wider), + BuildSettings::new(&project, &higher), + BuildSettings::new(&project, &fewer), + ); + assert!(w.hides_more_than(&b)); + assert!(h.hides_more_than(&b)); + assert!(!l.hides_more_than(&b)); + assert!(!b.hides_more_than(&b)); + assert_eq!(b.unmatched_rules(["invoices/show"]).len(), 1); + assert!(b.unmatched_rules(["api/invoices/show"]).is_empty()); + + // A build without a file uses the project's settings. + call(&app, TEST, t, "create_build", json!({ "commit": "def", "branch": "main" })).await; + let plain = Build::query().filter(Build::project_id.eq(project.id) & Build::number.eq(3)).first().await?.unwrap(); + let settings = BuildSettings::new(&project, &plain); + let other = + app::domain::snapshots::register(&plain, &settings, "test", &text("other", None)).await?.unwrap().snapshot; + assert_eq!(settings.ci_mode(), "strict"); + assert_eq!(serde_json::to_value(settings.applied_rules(&other)).unwrap()[0]["source"], "project"); + assert_eq!(settings.renderer_key(None, "v1"), format!("{}/{}dpi/v1", project.renderer, project.dpi)); + Ok(()) +} + +/// `list_builds` answers one short line per build (sc-8891): what tells builds apart, and their changes in a few words; +/// get_build has the rest. +#[laravel::test] +async fn list_builds_answers_one_short_line_per_build(app: Application) -> laravel::Result<()> { + const TEST: &str = "list_builds_answers_one_short_line_per_build"; + let f = fixture().await?; + let t = &f.project_token; + call(&app, TEST, t, "create_build", json!({ "commit": "a1b2c3d4e5f60718293a", "branch": "main" })).await; + let (err, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "1", "allow_empty": true })).await; + assert!(!err, "{done}"); + call( + &app, + TEST, + t, + "create_build", + json!({ "commit": "b2c3d4e5f6", "branch": "feat", "pr_number": 7, "name": "docs" }), + ) + .await; + let (err, list) = call(&app, TEST, t, "list_builds", json!({})).await; + assert!(!err, "{list}"); + let builds = list["builds"].as_array().unwrap(); + assert_eq!(builds.len(), 2); + assert_eq!(builds[0]["name"], "docs", "a suite's name shows when it isn't the default: {list}"); + assert!(builds[1].get("name").is_none() && builds[1].get("mode").is_none(), "{list}"); + assert_eq!(builds[1]["commit"], "a1b2c3d4e5f6", "12 characters of the commit"); + assert_eq!(builds[1]["changes"], "unchanged"); + assert_eq!(builds[0]["changes"], "not compared", "still receiving"); + for left_out in ["environment_info", "reviews", "groups", "blocked", "ci_mode", "passed", "warnings"] { + assert!(builds[0].get(left_out).is_none(), "{left_out} is get_build's: {list}"); + } + Ok(()) +} From 529d1a1e7f42f088b6af3369c450f8a0126cc242 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:11:26 +1300 Subject: [PATCH 3/6] app/: comment_when_unchanged (c2da705, #90) as a project setting: a migration, the model, domain::projects' Settings and SettingsChange, get_project and update_project; its test and golden --- ..._000500_projects_comment_when_unchanged.rs | 9 +++ app/src/domain/projects.rs | 9 +++ app/src/models/projects.rs | 3 + .../update_project-2.json | 3 +- .../update_project-3.json | 3 +- .../update_project.json | 3 +- .../update_project.json | 3 +- .../get_project.json | 58 +++++++++++++++++++ .../update_project.json | 42 ++++++++++++++ .../tools-list-project-token.json | 7 +++ .../tools-list-user-token.json | 7 +++ .../get_project-2.json | 3 +- .../update_project.json | 3 +- app/tests/mcp.rs | 15 +++++ 14 files changed, 162 insertions(+), 6 deletions(-) create mode 100644 app/database/migrations/2026_12_03_000500_projects_comment_when_unchanged.rs create mode 100644 app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/get_project.json create mode 100644 app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/update_project.json diff --git a/app/database/migrations/2026_12_03_000500_projects_comment_when_unchanged.rs b/app/database/migrations/2026_12_03_000500_projects_comment_when_unchanged.rs new file mode 100644 index 00000000..495cd1a5 --- /dev/null +++ b/app/database/migrations/2026_12_03_000500_projects_comment_when_unchanged.rs @@ -0,0 +1,9 @@ +//! `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(()) +} diff --git a/app/src/domain/projects.rs b/app/src/domain/projects.rs index a461b8d5..8f24539a 100644 --- a/app/src/domain/projects.rs +++ b/app/src/domain/projects.rs @@ -68,6 +68,9 @@ pub struct Settings { 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, @@ -103,6 +106,7 @@ impl From<&Project> for Settings { 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, @@ -146,6 +150,9 @@ pub struct SettingsChange { pub gallery_enabled: Option, /// `false`: project tokens can't approve changes (people do); `true` lets CI's agents approve again. pub tokens_can_approve: Option, + /// `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, /// `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. @@ -281,6 +288,7 @@ pub async fn change_settings(project: Project, p: SettingsChange) -> laravel::Re 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() }; @@ -295,6 +303,7 @@ pub async fn change_settings(project: Project, p: SettingsChange) -> laravel::Re slug, name, tokens_can_approve, + comment_when_unchanged, gallery_enabled, public, notice, diff --git a/app/src/models/projects.rs b/app/src/models/projects.rs index 2906a66d..2e878064 100644 --- a/app/src/models/projects.rs +++ b/app/src/models/projects.rs @@ -47,6 +47,9 @@ pub struct Project { pub linked_by: Option, #[default] pub tokens_can_approve: bool, + /// Whether VisualCI comments on a pull request whose builds are all unchanged (off by default). + #[default] + pub comment_when_unchanged: bool, pub repository_id: Option, /// The gallery URLs last purged as published (`jobs::purge_gallery`). #[default] diff --git a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-2.json b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-2.json index 892d005b..bf8c264c 100644 --- a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-2.json +++ b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-2.json @@ -162,7 +162,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.k0\",\"$.k1\",\"$.k2\",\"$.k3\",\"$.k4\",\"$.k5\",\"$.k6\",\"$.k7\",\"$.k8\",\"$.k9\",\"$.k10\",\"$.k11\",\"$.k12\",\"$.k13\",\"$.k14\",\"$.k15\",\"$.k16\",\"$.k17\",\"$.k18\",\"$.k19\",\"$.k20\",\"$.k21\",\"$.k22\",\"$.k23\",\"$.k24\",\"$.k25\",\"$.k26\",\"$.k27\",\"$.k28\",\"$.k29\",\"$.k30\",\"$.k31\",\"$.k32\",\"$.k33\",\"$.k34\",\"$.k35\",\"$.k36\",\"$.k37\",\"$.k38\",\"$.k39\",\"$.k40\",\"$.k41\",\"$.k42\",\"$.k43\",\"$.k44\",\"$.k45\",\"$.k46\",\"$.k47\",\"$.k48\",\"$.k49\",\"$.k50\",\"$.k51\",\"$.k52\",\"$.k53\",\"$.k54\",\"$.k55\",\"$.k56\",\"$.k57\",\"$.k58\",\"$.k59\",\"$.k60\",\"$.k61\",\"$.k62\",\"$.k63\",\"$.k64\",\"$.k65\",\"$.k66\",\"$.k67\",\"$.k68\",\"$.k69\",\"$.k70\",\"$.k71\",\"$.k72\",\"$.k73\",\"$.k74\",\"$.k75\",\"$.k76\",\"$.k77\",\"$.k78\",\"$.k79\",\"$.k80\",\"$.k81\",\"$.k82\",\"$.k83\",\"$.k84\",\"$.k85\",\"$.k86\",\"$.k87\",\"$.k88\",\"$.k89\",\"$.k90\",\"$.k91\",\"$.k92\",\"$.k93\",\"$.k94\",\"$.k95\",\"$.k96\",\"$.k97\",\"$.k98\",\"$.k99\",\"$.k100\",\"$.k101\",\"$.k102\",\"$.k103\",\"$.k104\",\"$.k105\",\"$.k106\",\"$.k107\",\"$.k108\",\"$.k109\",\"$.k110\",\"$.k111\",\"$.k112\",\"$.k113\",\"$.k114\",\"$.k115\",\"$.k116\",\"$.k117\",\"$.k118\",\"$.k119\",\"$.k120\",\"$.k121\",\"$.k122\",\"$.k123\",\"$.k124\",\"$.k125\",\"$.k126\",\"$.k127\",\"$.k128\",\"$.k129\",\"$.k130\",\"$.k131\",\"$.k132\",\"$.k133\",\"$.k134\",\"$.k135\",\"$.k136\",\"$.k137\",\"$.k138\",\"$.k139\",\"$.k140\",\"$.k141\",\"$.k142\",\"$.k143\",\"$.k144\",\"$.k145\",\"$.k146\",\"$.k147\",\"$.k148\",\"$.k149\"],\"snapshots\":\"**\"}],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.k0\",\"$.k1\",\"$.k2\",\"$.k3\",\"$.k4\",\"$.k5\",\"$.k6\",\"$.k7\",\"$.k8\",\"$.k9\",\"$.k10\",\"$.k11\",\"$.k12\",\"$.k13\",\"$.k14\",\"$.k15\",\"$.k16\",\"$.k17\",\"$.k18\",\"$.k19\",\"$.k20\",\"$.k21\",\"$.k22\",\"$.k23\",\"$.k24\",\"$.k25\",\"$.k26\",\"$.k27\",\"$.k28\",\"$.k29\",\"$.k30\",\"$.k31\",\"$.k32\",\"$.k33\",\"$.k34\",\"$.k35\",\"$.k36\",\"$.k37\",\"$.k38\",\"$.k39\",\"$.k40\",\"$.k41\",\"$.k42\",\"$.k43\",\"$.k44\",\"$.k45\",\"$.k46\",\"$.k47\",\"$.k48\",\"$.k49\",\"$.k50\",\"$.k51\",\"$.k52\",\"$.k53\",\"$.k54\",\"$.k55\",\"$.k56\",\"$.k57\",\"$.k58\",\"$.k59\",\"$.k60\",\"$.k61\",\"$.k62\",\"$.k63\",\"$.k64\",\"$.k65\",\"$.k66\",\"$.k67\",\"$.k68\",\"$.k69\",\"$.k70\",\"$.k71\",\"$.k72\",\"$.k73\",\"$.k74\",\"$.k75\",\"$.k76\",\"$.k77\",\"$.k78\",\"$.k79\",\"$.k80\",\"$.k81\",\"$.k82\",\"$.k83\",\"$.k84\",\"$.k85\",\"$.k86\",\"$.k87\",\"$.k88\",\"$.k89\",\"$.k90\",\"$.k91\",\"$.k92\",\"$.k93\",\"$.k94\",\"$.k95\",\"$.k96\",\"$.k97\",\"$.k98\",\"$.k99\",\"$.k100\",\"$.k101\",\"$.k102\",\"$.k103\",\"$.k104\",\"$.k105\",\"$.k106\",\"$.k107\",\"$.k108\",\"$.k109\",\"$.k110\",\"$.k111\",\"$.k112\",\"$.k113\",\"$.k114\",\"$.k115\",\"$.k116\",\"$.k117\",\"$.k118\",\"$.k119\",\"$.k120\",\"$.k121\",\"$.k122\",\"$.k123\",\"$.k124\",\"$.k125\",\"$.k126\",\"$.k127\",\"$.k128\",\"$.k129\",\"$.k130\",\"$.k131\",\"$.k132\",\"$.k133\",\"$.k134\",\"$.k135\",\"$.k136\",\"$.k137\",\"$.k138\",\"$.k139\",\"$.k140\",\"$.k141\",\"$.k142\",\"$.k143\",\"$.k144\",\"$.k145\",\"$.k146\",\"$.k147\",\"$.k148\",\"$.k149\"],\"snapshots\":\"**\"}],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -170,6 +170,7 @@ "structuredContent": { "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-3.json b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-3.json index fd1787cf..829eb23d 100644 --- a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-3.json +++ b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-3.json @@ -6,7 +6,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"strict\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.k0\",\"$.k1\",\"$.k2\",\"$.k3\",\"$.k4\",\"$.k5\",\"$.k6\",\"$.k7\",\"$.k8\",\"$.k9\",\"$.k10\",\"$.k11\",\"$.k12\",\"$.k13\",\"$.k14\",\"$.k15\",\"$.k16\",\"$.k17\",\"$.k18\",\"$.k19\",\"$.k20\",\"$.k21\",\"$.k22\",\"$.k23\",\"$.k24\",\"$.k25\",\"$.k26\",\"$.k27\",\"$.k28\",\"$.k29\",\"$.k30\",\"$.k31\",\"$.k32\",\"$.k33\",\"$.k34\",\"$.k35\",\"$.k36\",\"$.k37\",\"$.k38\",\"$.k39\",\"$.k40\",\"$.k41\",\"$.k42\",\"$.k43\",\"$.k44\",\"$.k45\",\"$.k46\",\"$.k47\",\"$.k48\",\"$.k49\",\"$.k50\",\"$.k51\",\"$.k52\",\"$.k53\",\"$.k54\",\"$.k55\",\"$.k56\",\"$.k57\",\"$.k58\",\"$.k59\",\"$.k60\",\"$.k61\",\"$.k62\",\"$.k63\",\"$.k64\",\"$.k65\",\"$.k66\",\"$.k67\",\"$.k68\",\"$.k69\",\"$.k70\",\"$.k71\",\"$.k72\",\"$.k73\",\"$.k74\",\"$.k75\",\"$.k76\",\"$.k77\",\"$.k78\",\"$.k79\",\"$.k80\",\"$.k81\",\"$.k82\",\"$.k83\",\"$.k84\",\"$.k85\",\"$.k86\",\"$.k87\",\"$.k88\",\"$.k89\",\"$.k90\",\"$.k91\",\"$.k92\",\"$.k93\",\"$.k94\",\"$.k95\",\"$.k96\",\"$.k97\",\"$.k98\",\"$.k99\",\"$.k100\",\"$.k101\",\"$.k102\",\"$.k103\",\"$.k104\",\"$.k105\",\"$.k106\",\"$.k107\",\"$.k108\",\"$.k109\",\"$.k110\",\"$.k111\",\"$.k112\",\"$.k113\",\"$.k114\",\"$.k115\",\"$.k116\",\"$.k117\",\"$.k118\",\"$.k119\",\"$.k120\",\"$.k121\",\"$.k122\",\"$.k123\",\"$.k124\",\"$.k125\",\"$.k126\",\"$.k127\",\"$.k128\",\"$.k129\",\"$.k130\",\"$.k131\",\"$.k132\",\"$.k133\",\"$.k134\",\"$.k135\",\"$.k136\",\"$.k137\",\"$.k138\",\"$.k139\",\"$.k140\",\"$.k141\",\"$.k142\",\"$.k143\",\"$.k144\",\"$.k145\",\"$.k146\",\"$.k147\",\"$.k148\",\"$.k149\"],\"snapshots\":\"**\"}],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"settings\":{\"ci_mode\":\"strict\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.k0\",\"$.k1\",\"$.k2\",\"$.k3\",\"$.k4\",\"$.k5\",\"$.k6\",\"$.k7\",\"$.k8\",\"$.k9\",\"$.k10\",\"$.k11\",\"$.k12\",\"$.k13\",\"$.k14\",\"$.k15\",\"$.k16\",\"$.k17\",\"$.k18\",\"$.k19\",\"$.k20\",\"$.k21\",\"$.k22\",\"$.k23\",\"$.k24\",\"$.k25\",\"$.k26\",\"$.k27\",\"$.k28\",\"$.k29\",\"$.k30\",\"$.k31\",\"$.k32\",\"$.k33\",\"$.k34\",\"$.k35\",\"$.k36\",\"$.k37\",\"$.k38\",\"$.k39\",\"$.k40\",\"$.k41\",\"$.k42\",\"$.k43\",\"$.k44\",\"$.k45\",\"$.k46\",\"$.k47\",\"$.k48\",\"$.k49\",\"$.k50\",\"$.k51\",\"$.k52\",\"$.k53\",\"$.k54\",\"$.k55\",\"$.k56\",\"$.k57\",\"$.k58\",\"$.k59\",\"$.k60\",\"$.k61\",\"$.k62\",\"$.k63\",\"$.k64\",\"$.k65\",\"$.k66\",\"$.k67\",\"$.k68\",\"$.k69\",\"$.k70\",\"$.k71\",\"$.k72\",\"$.k73\",\"$.k74\",\"$.k75\",\"$.k76\",\"$.k77\",\"$.k78\",\"$.k79\",\"$.k80\",\"$.k81\",\"$.k82\",\"$.k83\",\"$.k84\",\"$.k85\",\"$.k86\",\"$.k87\",\"$.k88\",\"$.k89\",\"$.k90\",\"$.k91\",\"$.k92\",\"$.k93\",\"$.k94\",\"$.k95\",\"$.k96\",\"$.k97\",\"$.k98\",\"$.k99\",\"$.k100\",\"$.k101\",\"$.k102\",\"$.k103\",\"$.k104\",\"$.k105\",\"$.k106\",\"$.k107\",\"$.k108\",\"$.k109\",\"$.k110\",\"$.k111\",\"$.k112\",\"$.k113\",\"$.k114\",\"$.k115\",\"$.k116\",\"$.k117\",\"$.k118\",\"$.k119\",\"$.k120\",\"$.k121\",\"$.k122\",\"$.k123\",\"$.k124\",\"$.k125\",\"$.k126\",\"$.k127\",\"$.k128\",\"$.k129\",\"$.k130\",\"$.k131\",\"$.k132\",\"$.k133\",\"$.k134\",\"$.k135\",\"$.k136\",\"$.k137\",\"$.k138\",\"$.k139\",\"$.k140\",\"$.k141\",\"$.k142\",\"$.k143\",\"$.k144\",\"$.k145\",\"$.k146\",\"$.k147\",\"$.k148\",\"$.k149\"],\"snapshots\":\"**\"}],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -14,6 +14,7 @@ "structuredContent": { "settings": { "ci_mode": "strict", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project.json b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project.json index 557191ad..72435633 100644 --- a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project.json +++ b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project.json @@ -14,7 +14,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.project_rule\"],\"snapshots\":\"**\"}],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.project_rule\"],\"snapshots\":\"**\"}],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -22,6 +22,7 @@ "structuredContent": { "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mcp/a_project_can_keep_approving_with_people/update_project.json b/app/tests/golden/mcp/a_project_can_keep_approving_with_people/update_project.json index 4cdd3c0b..b8e4c9ee 100644 --- a/app/tests/golden/mcp/a_project_can_keep_approving_with_people/update_project.json +++ b/app/tests/golden/mcp/a_project_can_keep_approving_with_people/update_project.json @@ -6,7 +6,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":false}}", + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":false}}", "type": "text" } ], @@ -14,6 +14,7 @@ "structuredContent": { "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/get_project.json b/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/get_project.json new file mode 100644 index 00000000..fcfc5ff5 --- /dev/null +++ b/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/get_project.json @@ -0,0 +1,58 @@ +{ + "arguments": { + "project": "/pdfs" + }, + "result": { + "content": [ + { + "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"/pdfs\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":1,\"last_used_at\":null,\"name\":\"ci\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test//pdfs\"}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "gallery": { + "enabled": true, + "items": [], + "manifest_url": null + }, + "project": "/pdfs", + "repository_seen_in_ci": null, + "settings": { + "ci_mode": "review", + "comment_when_unchanged": false, + "default_branch": "main", + "dpi": 140, + "forge": null, + "forge_app_installed": false, + "forge_webhook_at": null, + "gallery_enabled": true, + "ignore_anti_aliasing": false, + "ignore_rules": [], + "name": "PDFs", + "notice": null, + "open_source": false, + "open_source_note": null, + "open_source_pool": false, + "open_source_withdrawn": false, + "public": false, + "renderer": "pdfbox", + "repository_public": false, + "repository_url": null, + "slug": "pdfs", + "threshold": 0.0, + "tokens_can_approve": true + }, + "tokens": [ + { + "created_at": "", + "id": 1, + "last_used_at": null, + "name": "ci", + "prefix": "" + } + ], + "url": "https://app.visualci.test//pdfs" + } + } +} diff --git a/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/update_project.json b/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/update_project.json new file mode 100644 index 00000000..989f0b76 --- /dev/null +++ b/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/update_project.json @@ -0,0 +1,42 @@ +{ + "arguments": { + "comment_when_unchanged": true, + "project": "/pdfs" + }, + "result": { + "content": [ + { + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":true,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "settings": { + "ci_mode": "review", + "comment_when_unchanged": true, + "default_branch": "main", + "dpi": 140, + "forge": null, + "forge_app_installed": false, + "forge_webhook_at": null, + "gallery_enabled": true, + "ignore_anti_aliasing": false, + "ignore_rules": [], + "name": "PDFs", + "notice": null, + "open_source": false, + "open_source_note": null, + "open_source_pool": false, + "open_source_withdrawn": false, + "public": false, + "renderer": "pdfbox", + "repository_public": false, + "repository_url": null, + "slug": "pdfs", + "threshold": 0.0, + "tokens_can_approve": true + } + } + } +} diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json index 9c376f10..1bc9020b 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json @@ -1363,6 +1363,13 @@ "null" ] }, + "comment_when_unchanged": { + "description": "`true`: comment on pull requests even when nothing changed. `false` (the default): a pull request whose builds\nare all unchanged gets no comment, only the passing check; a comment already there keeps being updated.", + "type": [ + "boolean", + "null" + ] + }, "default_branch": { "description": "The branch whose builds become the baseline automatically.", "type": [ diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json index 9c376f10..1bc9020b 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json @@ -1363,6 +1363,13 @@ "null" ] }, + "comment_when_unchanged": { + "description": "`true`: comment on pull requests even when nothing changed. `false` (the default): a pull request whose builds\nare all unchanged gets no comment, only the passing check; a comment already there keeps being updated.", + "type": [ + "boolean", + "null" + ] + }, "default_branch": { "description": "The branch whose builds become the baseline automatically.", "type": [ diff --git a/app/tests/golden/mcp/projects_can_be_renamed/get_project-2.json b/app/tests/golden/mcp/projects_can_be_renamed/get_project-2.json index dd8e7baf..3e7bbea9 100644 --- a/app/tests/golden/mcp/projects_can_be_renamed/get_project-2.json +++ b/app/tests/golden/mcp/projects_can_be_renamed/get_project-2.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"/monorepo\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"monorepo\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":1,\"last_used_at\":null,\"name\":\"ci\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test//monorepo\"}", + "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"/monorepo\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"monorepo\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":1,\"last_used_at\":null,\"name\":\"ci\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test//monorepo\"}", "type": "text" } ], @@ -20,6 +20,7 @@ "repository_seen_in_ci": null, "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mcp/projects_can_be_renamed/update_project.json b/app/tests/golden/mcp/projects_can_be_renamed/update_project.json index dc46ee3a..5edb2b80 100644 --- a/app/tests/golden/mcp/projects_can_be_renamed/update_project.json +++ b/app/tests/golden/mcp/projects_can_be_renamed/update_project.json @@ -6,7 +6,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"monorepo\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"monorepo\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -14,6 +14,7 @@ "structuredContent": { "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/mcp.rs b/app/tests/mcp.rs index d749b5a9..2a25c555 100644 --- a/app/tests/mcp.rs +++ b/app/tests/mcp.rs @@ -1035,3 +1035,18 @@ async fn list_builds_answers_one_short_line_per_build(app: Application) -> larav } Ok(()) } + +/// A pull request where nothing changed gets no comment by default; `comment_when_unchanged` turns that on. +#[laravel::test] +async fn comments_when_nothing_changed_are_off_until_turned_on(app: Application) -> laravel::Result<()> { + const TEST: &str = "comments_when_nothing_changed_are_off_until_turned_on"; + let f = fixture().await?; + let project = format!("{}/pdfs", f.org); + let (err, s) = call(&app, TEST, &f.user_token, "get_project", json!({ "project": project })).await; + assert!(!err && s["settings"]["comment_when_unchanged"] == false, "off by default: {s}"); + let (err, s) = + call(&app, TEST, &f.user_token, "update_project", json!({ "project": project, "comment_when_unchanged": true })) + .await; + assert!(!err && s["settings"]["comment_when_unchanged"] == true, "{s}"); + Ok(()) +} From dd846690bbc9a5b2ac77d8d5b72239e03eb6886f Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:11:52 +1300 Subject: [PATCH 4/6] app/: format the comment_when_unchanged migration and test --- ...26_12_03_000500_projects_comment_when_unchanged.rs | 4 +++- app/tests/mcp.rs | 11 ++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/app/database/migrations/2026_12_03_000500_projects_comment_when_unchanged.rs b/app/database/migrations/2026_12_03_000500_projects_comment_when_unchanged.rs index 495cd1a5..c12e663b 100644 --- a/app/database/migrations/2026_12_03_000500_projects_comment_when_unchanged.rs +++ b/app/database/migrations/2026_12_03_000500_projects_comment_when_unchanged.rs @@ -4,6 +4,8 @@ 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?; + tx.query("ALTER TABLE projects ADD COLUMN comment_when_unchanged boolean DEFAULT false NOT NULL") + .unprepared() + .await?; Ok(()) } diff --git a/app/tests/mcp.rs b/app/tests/mcp.rs index 2a25c555..480a8b7f 100644 --- a/app/tests/mcp.rs +++ b/app/tests/mcp.rs @@ -1044,9 +1044,14 @@ async fn comments_when_nothing_changed_are_off_until_turned_on(app: Application) let project = format!("{}/pdfs", f.org); let (err, s) = call(&app, TEST, &f.user_token, "get_project", json!({ "project": project })).await; assert!(!err && s["settings"]["comment_when_unchanged"] == false, "off by default: {s}"); - let (err, s) = - call(&app, TEST, &f.user_token, "update_project", json!({ "project": project, "comment_when_unchanged": true })) - .await; + let (err, s) = call( + &app, + TEST, + &f.user_token, + "update_project", + json!({ "project": project, "comment_when_unchanged": true }), + ) + .await; assert!(!err && s["settings"]["comment_when_unchanged"] == true, "{s}"); Ok(()) } From 75a163ac02892f215151fb94d007a8d854fab10d Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:27:01 +1300 Subject: [PATCH 5/6] app/: create_organization, invite_member, create_project_token and delete_project_token on #70's functions (create_org, invite_to, make_project_token, remove_project_token), with today's role checks and messages; the personal-token test's settings goldens gain comment_when_unchanged --- app/src/mcp/mod.rs | 64 +++++++++++++------ .../create_project.json | 3 +- .../get_project.json | 3 +- .../update_project-4.json | 3 +- .../update_project-8.json | 2 +- .../update_project.json | 3 +- 6 files changed, 53 insertions(+), 25 deletions(-) diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index 0ef8ed90..7a37ed66 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -542,11 +542,10 @@ impl VisualCi { } } -/// A subdomains function a tool needs that isn't on main yet: the tool's error until it lands. -fn not_on_main_yet(function: &str) -> CallToolResult { - tool_error(format!( - "this tool isn't available yet: it needs {function} (subdomains' organization functions, sc-8900)" - )) +/// A subdomains function's refusal (`abort_with(422 | 409 | 429, message)`) as the tool's error, with its message; +/// anything else is an internal error. +fn refusal(e: laravel::Error) -> Result { + if e.status().is_client_error() { Ok(e.to_string()) } else { Err(internal(e)) } } /// The OAuth client's display name, when the request came through one (for "Approved by Claude Code for Ada"). @@ -777,16 +776,22 @@ impl VisualCi { Parameters(args): Parameters, rc: RequestContext, ) -> Result { - let (_org, role) = need!(Self::org(&rc, &args.org)); - let Some(Principal::User { .. }) = principal_of(&rc) else { + let (org, role) = need!(Self::org(&rc, &args.org)); + let Some(Principal::User { user, .. }) = principal_of(&rc) else { return Ok(tool_error("invitations need a personal access token")); }; if role != "admin" { return Ok(tool_error(format!("only an organization's admins can invite people; you're {role}"))); } - let _ = (&args.invitee, crate::auth::Role::from(args.role)); - // TODO(#70): app::auth::invitations::invite_to(org.id, &user, invitee, role) once it's on main. - Ok(not_on_main_yet("app::auth::invitations::invite_to")) + let role = crate::auth::Role::from(args.role).as_str(); + let invitation = match crate::auth::invitations::invite_to(org.id, &user, &args.invitee, role).await { + Ok(v) => v, + Err(e) => return Ok(tool_error(refusal(e)?)), + }; + Ok(structured(json!({ + "invitation": invitation, + "members": crate::auth::invitations::members_json(org.id, true).await.map_err(internal)?, + }))) } #[tool( @@ -803,12 +808,23 @@ impl VisualCi { Parameters(args): Parameters, rc: RequestContext, ) -> Result { - let Some(Principal::User { .. }) = principal_of(&rc) else { + let Some(Principal::User { user, .. }) = principal_of(&rc) else { return Ok(tool_error("creating an organization needs a personal access token")); }; - let _ = (&args.slug, &args.name); - // TODO(#70): orgs::create_org(&user, slug, name) once it's on main. - Ok(not_on_main_yet("orgs::create_org")) + let slug = match crate::auth::orgs::create_org(&user, &args.slug, &args.name).await { + Ok(slug) => slug, + // Today's words for a slug that's taken. + Err(e) if e.status().as_u16() == 409 => return Ok(tool_error(format!("the slug {} is taken", args.slug))), + Err(e) => return Ok(tool_error(refusal(e)?)), + }; + let org = Organization::query() + .filter(Organization::slug.eq(slug.as_str())) + .first() + .await + .map_err(internal)? + .ok_or_else(|| internal("the new organization wasn't saved"))?; + let plan = domain::credits::plan_by_id(&org.plan); + Ok(structured(json!({ "slug": org.slug, "name": org.name, "plan": plan.name }))) } #[tool( @@ -945,11 +961,18 @@ impl VisualCi { if let Err(e) = Self::need_role(&rc, &project, Role::Admin, "create project tokens").await? { return Ok(tool_error(e)); } - if args.name.trim().is_empty() { + let Some(Principal::User { user, .. }) = principal_of(&rc) else { + return Ok(tool_error("creating a project token needs a personal access token")); + }; + let name = args.name.trim(); + if name.is_empty() { return Ok(tool_error("give the token a name")); } - // TODO(#70): app::auth::tokens::make_project_token(&user, project.id, name) once it's on main. - Ok(not_on_main_yet("app::auth::tokens::make_project_token")) + let (token, id) = match crate::auth::tokens::make_project_token(&user, project.id, name).await { + Ok(made) => made, + Err(e) => return Ok(tool_error(refusal(e)?)), + }; + Ok(structured(json!({ "id": id, "name": name, "token": token }))) } #[tool( @@ -970,9 +993,10 @@ impl VisualCi { if let Err(e) = Self::need_role(&rc, &project, Role::Admin, "delete project tokens").await? { return Ok(tool_error(e)); } - let _ = args.token_id; - // TODO(#70): app::auth::tokens::remove_project_token(project.id, id) once it's on main. - Ok(not_on_main_yet("app::auth::tokens::remove_project_token")) + if !crate::auth::tokens::remove_project_token(project.id, args.token_id).await.map_err(internal)? { + return Ok(tool_error(format!("no token {} in this project", args.token_id))); + } + Ok(structured(json!({ "deleted": args.token_id }))) } #[tool( diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/create_project.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/create_project.json index bdd62ca9..df03619f 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/create_project.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/create_project.json @@ -7,7 +7,7 @@ "result": { "content": [ { - "text": "{\"project\":\"-b/docs\",\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"project\":\"-b/docs\",\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -16,6 +16,7 @@ "project": "-b/docs", "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_project.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_project.json index 5652ccc4..55a970ce 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_project.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_project.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"-b/docs\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.generated_at\"],\"snapshots\":\"api/**\",\"text_patterns\":[\"\\\\d{4}-\\\\d{2}-\\\\d{2}\"]}],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":3,\"last_used_at\":null,\"name\":\"CircleCI\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test/-b/docs\"}", + "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"-b/docs\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.generated_at\"],\"snapshots\":\"api/**\",\"text_patterns\":[\"\\\\d{4}-\\\\d{2}-\\\\d{2}\"]}],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":3,\"last_used_at\":null,\"name\":\"CircleCI\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test/-b/docs\"}", "type": "text" } ], @@ -20,6 +20,7 @@ "repository_seen_in_ci": null, "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 150, "forge": null, diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-4.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-4.json index aae6cbfa..63466abf 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-4.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-4.json @@ -17,7 +17,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.generated_at\"],\"snapshots\":\"api/**\",\"text_patterns\":[\"\\\\d{4}-\\\\d{2}-\\\\d{2}\"]}],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.generated_at\"],\"snapshots\":\"api/**\",\"text_patterns\":[\"\\\\d{4}-\\\\d{2}-\\\\d{2}\"]}],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -25,6 +25,7 @@ "structuredContent": { "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 150, "forge": null, diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-8.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-8.json index 9f352fdf..5335eac0 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-8.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-8.json @@ -12,7 +12,7 @@ "result": { "content": [ { - "text": "failed to deserialize parameters: missing field `snapshots`\n\nupdate_project takes:\n- ci_mode (string): `review` (CI passes, the check waits for review), `strict` (CI fails on unreviewed changes) or `wait`.\n- default_branch (string): The branch whose builds become the baseline automatically.\n- dismiss_notice (boolean): `true` dismisses the project's notice.\n- dpi (integer): Render resolution for documents, 36 to 600.\n- forge_token (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.\n- gallery_enabled (boolean): `false` takes the public gallery down (visualci.yml's `gallery` decides what's in it); `true` puts it back.\n- ignore_anti_aliasing (boolean): Ignore anti-aliasing differences in images.\n- ignore_rules (array): 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`.\n- move_link (boolean): 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).\n- name (string): The project's display name.\n- project (string): `org/project`. Optional with a project token.\n- public (boolean): `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.\n- renderer (string): The PDF renderer: `pdfbox` or `mutool`.\n- repository_url (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.\n- slug (string): 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.\n- threshold (number): 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.\n- tokens_can_approve (boolean): `false`: project tokens can't approve changes (people do); `true` lets CI's agents approve again.\nExample: {}", + "text": "failed to deserialize parameters: missing field `snapshots`\n\nupdate_project takes:\n- ci_mode (string): `review` (CI passes, the check waits for review), `strict` (CI fails on unreviewed changes) or `wait`.\n- comment_when_unchanged (boolean): `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.\n- default_branch (string): The branch whose builds become the baseline automatically.\n- dismiss_notice (boolean): `true` dismisses the project's notice.\n- dpi (integer): Render resolution for documents, 36 to 600.\n- forge_token (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.\n- gallery_enabled (boolean): `false` takes the public gallery down (visualci.yml's `gallery` decides what's in it); `true` puts it back.\n- ignore_anti_aliasing (boolean): Ignore anti-aliasing differences in images.\n- ignore_rules (array): 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`.\n- move_link (boolean): 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).\n- name (string): The project's display name.\n- project (string): `org/project`. Optional with a project token.\n- public (boolean): `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.\n- renderer (string): The PDF renderer: `pdfbox` or `mutool`.\n- repository_url (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.\n- slug (string): 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.\n- threshold (number): 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.\n- tokens_can_approve (boolean): `false`: project tokens can't approve changes (people do); `true` lets CI's agents approve again.\nExample: {}", "type": "text" } ], diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project.json index a37d3cef..6f5c94fb 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project.json @@ -6,7 +6,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -14,6 +14,7 @@ "structuredContent": { "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 150, "forge": null, From d57dd61b70378bccb98d16abd84f74162607f6b9 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 11:50:31 +1300 Subject: [PATCH 6/6] app/: #91 review fixes: list_builds keeps the whole commit, adds numeric stats and blocked on each line; whoami's via.source in the words reviews record (personal_token, project_token, oauth, web); new MCP tests for invite_member (who may invite, the daily limit), download_build, list_organizations and create_organization's taken slug --- app/src/mcp/mod.rs | 45 ++++++-- .../whoami.json | 4 +- .../create_organization.json | 15 +++ .../create_build.json | 50 +++++++++ .../download_build-2.json | 15 +++ .../download_build-3.json | 14 +++ .../download_build.json | 38 +++++++ .../finalize_build.json | 50 +++++++++ .../invite_member-2.json | 16 +++ .../invite_member-3.json | 53 +++++++++ .../invite_member-4.json | 53 +++++++++ .../invite_member-5.json | 16 +++ .../invite_member.json | 16 +++ .../list_builds.json | 20 +++- .../list_organizations.json | 61 +++++++++++ .../tools-list-project-token.json | 4 +- .../tools-list-user-token.json | 4 +- app/tests/mcp.rs | 102 +++++++++++++++++- 18 files changed, 554 insertions(+), 22 deletions(-) create mode 100644 app/tests/golden/mcp/create_organization_refuses_a_taken_slug/create_organization.json create mode 100644 app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/create_build.json create mode 100644 app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-2.json create mode 100644 app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-3.json create mode 100644 app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build.json create mode 100644 app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/finalize_build.json create mode 100644 app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-2.json create mode 100644 app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-3.json create mode 100644 app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-4.json create mode 100644 app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-5.json create mode 100644 app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member.json create mode 100644 app/tests/golden/mcp/list_organizations_lists_a_persons_organizations/list_organizations.json diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index 7a37ed66..264185f0 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -353,13 +353,19 @@ impl VisualCi { /// What the caller runs as, for whoami: the token's name, or the MCP client's. fn via_json(rc: &RequestContext) -> serde_json::Value { let Some(principal) = principal_of(rc) else { return serde_json::Value::Null }; + // The words reviews record (`domain::reviews::Via::source`). let client = principal.client(); + let source = match client.source { + "mcp" => "oauth", + "token" => "personal_token", + other => other, + }; match client.token_name { - Some(name) => json!({ "source": client.source, "token_name": name }), + Some(name) => json!({ "source": source, "token_name": name }), None => { let parts = rc.extensions.get::(); let name = parts.and_then(|p| p.extensions.get::()).map(|c| c.0.clone()); - json!({ "source": client.source, "client_name": name.or(client.client_id) }) + json!({ "source": source, "client_name": name.or(client.client_id) }) } } } @@ -391,8 +397,14 @@ impl VisualCi { }))) } - /// A build in a list (sc-8891): only what tells builds apart, with its counts as words. get_build has the rest. - fn build_line(org: &str, project: &Project, b: &Build, waits: bool) -> serde_json::Value { + /// A build in a list (sc-8891): only what tells builds apart, its counts (as words and as numbers) and whether + /// it's blocked. get_build has the rest. + async fn build_line( + organization: &Organization, + project: &Project, + b: &Build, + waits: bool, + ) -> Result { let stats = domain::builds::stats(b); let counts = [ (stats.changed, "changed"), @@ -408,17 +420,28 @@ impl VisualCi { (true, "completed") => "unchanged".to_string(), (true, _) => "not compared".to_string(), }; + // Out of credits: why it wasn't compared, and what fixes it (null when it isn't blocked). + let blocked = BuildResponse::new(b, project, organization) + .with_blocked(b, project, organization) + .await + .map_err(internal)? + .blocked; let mut v = json!({ "number": b.number, "branch": b.branch, - "commit": b.commit_sha.chars().take(12).collect::(), + "commit": b.commit_sha, "pr_number": b.pr_number, "state": b.state, "conclusion": b.conclusion, "review_state": b.review_state, "waiting_for_review": waits, "changes": changes, - "url": format!("{}/{org}/{}/builds/{}", app_url(), project.slug, b.number), + "stats": { + "changed": stats.changed, "added": stats.added, "removed": stats.removed, + "unchanged": stats.unchanged, "failed": stats.failed, + }, + "blocked": blocked, + "url": format!("{}/{}/{}/builds/{}", app_url(), organization.slug, project.slug, b.number), "created_at": b.created_at.to_string(), }); if b.name != "default" { @@ -427,7 +450,7 @@ impl VisualCi { if b.mode != "ci" { v["mode"] = json!(b.mode); } - v + Ok(v) } async fn find_build(project: &Project, build: &str) -> Result, ErrorData> { @@ -573,7 +596,7 @@ impl VisualCi { } #[tool( - description = "Who this token belongs to (a person or a project), how it reached VisualCI (`via`: the token's name, or the MCP client's), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", + description = "Who this token belongs to (a person or a project), how it reached VisualCI (`via`: `source` as reviews record it, `personal_token`, `project_token`, `oauth` or `web`, with the token's or the MCP client's name), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", annotations(title = "Who am I", read_only_hint = true, idempotent_hint = true, open_world_hint = false) )] async fn whoami( @@ -1043,7 +1066,7 @@ impl VisualCi { } #[tool( - description = "List a project's builds, newest first, one short line each: number, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, whether it waits for your review, its changes in a few words (`2 changed, 1 added`) and URL. get_build has the details (its snapshots, environment, reviews, groups, CI mode and warnings). waiting_for_review: only builds whose changes wait for a review.", + description = "List a project's builds, newest first, one short line each: number, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, whether it waits for your review, its changes in a few words (`2 changed, 1 added`) and as numbers (`stats`), `blocked` when it's out of credits, and URL. get_build has the details (its snapshots, environment, reviews, groups, CI mode and warnings). 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( @@ -1052,7 +1075,7 @@ impl VisualCi { rc: RequestContext, ) -> Result { let project = need!(Self::project(&rc, args.project.as_deref())); - let org = Self::organization_of(&project).await?.slug; + let organization = Self::organization_of(&project).await?; let limit = usize::try_from(args.limit.unwrap_or(20).clamp(1, 100)).unwrap_or(20); let user = user_id(&rc); let waiting = args.waiting_for_review == Some(true); @@ -1064,7 +1087,7 @@ impl VisualCi { if waiting && !waits { continue; } - list.push(Self::build_line(&org, &project, &b, waits)); + list.push(Self::build_line(&organization, &project, &b, waits).await?); if list.len() >= limit { break; } diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json index 992d0771..f4429033 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"install_github_app\",\"steps\":[{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"via\":{\"source\":\"token\",\"token_name\":\"agent\"},\"waiting_for_review\":[]}", + "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"install_github_app\",\"steps\":[{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"via\":{\"source\":\"personal_token\",\"token_name\":\"agent\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -53,7 +53,7 @@ } ], "via": { - "source": "token", + "source": "personal_token", "token_name": "agent" }, "waiting_for_review": [] diff --git a/app/tests/golden/mcp/create_organization_refuses_a_taken_slug/create_organization.json b/app/tests/golden/mcp/create_organization_refuses_a_taken_slug/create_organization.json new file mode 100644 index 00000000..7a89b6ef --- /dev/null +++ b/app/tests/golden/mcp/create_organization_refuses_a_taken_slug/create_organization.json @@ -0,0 +1,15 @@ +{ + "arguments": { + "name": "Again", + "slug": "" + }, + "result": { + "content": [ + { + "text": "the slug is taken", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/create_build.json b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/create_build.json new file mode 100644 index 00000000..560b7e67 --- /dev/null +++ b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/create_build.json @@ -0,0 +1,50 @@ +{ + "arguments": { + "branch": "main", + "commit": "abc" + }, + "result": { + "content": [ + { + "text": "{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":null,\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":null,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"none\",\"reviewable\":false,\"reviews\":[],\"state\":\"receiving\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "blocked": null, + "branch": "main", + "ci_mode": "review", + "commit": "abc", + "conclusion": null, + "created_at": "", + "environment": "ci", + "environment_info": {}, + "error": null, + "id": "", + "mode": "ci", + "name": "default", + "number": 1, + "passed": null, + "pr_number": null, + "project": "/pdfs", + "review_state": "none", + "reviewable": false, + "reviews": [], + "state": "receiving", + "stats": { + "added": 0, + "changed": 0, + "config": 0, + "failed": 0, + "ignored": 0, + "pending": 0, + "removed": 0, + "total": 0, + "unchanged": 0 + }, + "url": "https://app.visualci.test//pdfs/builds/1", + "warnings": [] + } + } +} diff --git a/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-2.json b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-2.json new file mode 100644 index 00000000..c7ade30a --- /dev/null +++ b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-2.json @@ -0,0 +1,15 @@ +{ + "arguments": { + "build": "1", + "state": "new" + }, + "result": { + "content": [ + { + "text": "state must be one of changed, added, removed, unchanged, all", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-3.json b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-3.json new file mode 100644 index 00000000..516dc496 --- /dev/null +++ b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-3.json @@ -0,0 +1,14 @@ +{ + "arguments": { + "build": "9" + }, + "result": { + "content": [ + { + "text": "no build 9 in this project", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build.json b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build.json new file mode 100644 index 00000000..9004efdb --- /dev/null +++ b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build.json @@ -0,0 +1,38 @@ +{ + "arguments": { + "build": "1", + "state": "all" + }, + "result": { + "content": [ + { + "text": "{\"bytes\":191,\"error\":null,\"files\":1,\"filter\":{\"glob\":null,\"sides\":[\"base\",\"head\",\"diff\"],\"state\":\"all\"},\"id\":\"\",\"state\":\"ready\",\"summary\":{\"build\":1,\"by_state\":{},\"names\":[],\"snapshots\":0},\"url\":\"http://127.0.0.1:59000/visualci-test/downloads/.tar.zst?\"}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "bytes": 191, + "error": null, + "files": 1, + "filter": { + "glob": null, + "sides": [ + "base", + "head", + "diff" + ], + "state": "all" + }, + "id": "", + "state": "ready", + "summary": { + "build": 1, + "by_state": {}, + "names": [], + "snapshots": 0 + }, + "url": "http://127.0.0.1:59000/visualci-test/downloads/.tar.zst?" + } + } +} diff --git a/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/finalize_build.json b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/finalize_build.json new file mode 100644 index 00000000..0517d2ba --- /dev/null +++ b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/finalize_build.json @@ -0,0 +1,50 @@ +{ + "arguments": { + "allow_empty": true, + "build": "1" + }, + "result": { + "content": [ + { + "text": "{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":null,\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":null,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"none\",\"reviewable\":false,\"reviews\":[],\"state\":\"processing\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "blocked": null, + "branch": "main", + "ci_mode": "review", + "commit": "abc", + "conclusion": null, + "created_at": "", + "environment": "ci", + "environment_info": {}, + "error": null, + "id": "", + "mode": "ci", + "name": "default", + "number": 1, + "passed": null, + "pr_number": null, + "project": "/pdfs", + "review_state": "none", + "reviewable": false, + "reviews": [], + "state": "processing", + "stats": { + "added": 0, + "changed": 0, + "config": 0, + "failed": 0, + "ignored": 0, + "pending": 0, + "removed": 0, + "total": 0, + "unchanged": 0 + }, + "url": "https://app.visualci.test//pdfs/builds/1", + "warnings": [] + } + } +} diff --git a/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-2.json b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-2.json new file mode 100644 index 00000000..cb9b4fb6 --- /dev/null +++ b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-2.json @@ -0,0 +1,16 @@ +{ + "arguments": { + "invitee": "ada@example.com", + "org": "", + "role": "member" + }, + "result": { + "content": [ + { + "text": "only an organization's admins can invite people; you're member", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-3.json b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-3.json new file mode 100644 index 00000000..8821c157 --- /dev/null +++ b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-3.json @@ -0,0 +1,53 @@ +{ + "arguments": { + "invitee": "ada@example.com", + "org": "", + "role": "member" + }, + "result": { + "content": [ + { + "text": "{\"invitation\":{\"created_at\":\"\",\"email\":\"ada@example.com\",\"forge\":null,\"id\":\"\",\"invitee\":\"ada@example.com\",\"login\":null,\"role\":\"member\"},\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null},{\"avatar_url\":null,\"email\":\"member@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"member\",\"role\":\"member\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "invitation": { + "created_at": "", + "email": "ada@example.com", + "forge": null, + "id": "", + "invitee": "ada@example.com", + "login": null, + "role": "member" + }, + "members": [ + { + "avatar_url": null, + "email": "@example.com", + "id": "", + "identities": [], + "login": null, + "name": "owner", + "role": "admin", + "since": "", + "source": "created", + "synced_at": null + }, + { + "avatar_url": null, + "email": "member@example.com", + "id": "", + "identities": [], + "login": null, + "name": "member", + "role": "member", + "since": "", + "source": "created", + "synced_at": null + } + ] + } + } +} diff --git a/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-4.json b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-4.json new file mode 100644 index 00000000..8821c157 --- /dev/null +++ b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-4.json @@ -0,0 +1,53 @@ +{ + "arguments": { + "invitee": "ada@example.com", + "org": "", + "role": "member" + }, + "result": { + "content": [ + { + "text": "{\"invitation\":{\"created_at\":\"\",\"email\":\"ada@example.com\",\"forge\":null,\"id\":\"\",\"invitee\":\"ada@example.com\",\"login\":null,\"role\":\"member\"},\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null},{\"avatar_url\":null,\"email\":\"member@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"member\",\"role\":\"member\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "invitation": { + "created_at": "", + "email": "ada@example.com", + "forge": null, + "id": "", + "invitee": "ada@example.com", + "login": null, + "role": "member" + }, + "members": [ + { + "avatar_url": null, + "email": "@example.com", + "id": "", + "identities": [], + "login": null, + "name": "owner", + "role": "admin", + "since": "", + "source": "created", + "synced_at": null + }, + { + "avatar_url": null, + "email": "member@example.com", + "id": "", + "identities": [], + "login": null, + "name": "member", + "role": "member", + "since": "", + "source": "created", + "synced_at": null + } + ] + } + } +} diff --git a/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-5.json b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-5.json new file mode 100644 index 00000000..95b1e5b7 --- /dev/null +++ b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-5.json @@ -0,0 +1,16 @@ +{ + "arguments": { + "invitee": "bea@example.com", + "org": "", + "role": "read" + }, + "result": { + "content": [ + { + "text": "that person has been invited too often in the last 24 hours; try again tomorrow", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member.json b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member.json new file mode 100644 index 00000000..4175f72c --- /dev/null +++ b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member.json @@ -0,0 +1,16 @@ +{ + "arguments": { + "invitee": "ada@example.com", + "org": "", + "role": "member" + }, + "result": { + "content": [ + { + "text": "invitations need a personal access token", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/list_builds.json b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/list_builds.json index 150d0f86..dab2ae61 100644 --- a/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/list_builds.json +++ b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/list_builds.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"builds\":[{\"branch\":\"feat\",\"changes\":\"not compared\",\"commit\":\"b2c3d4e5f6\",\"conclusion\":null,\"created_at\":\"\",\"name\":\"docs\",\"number\":2,\"pr_number\":7,\"review_state\":\"none\",\"state\":\"receiving\",\"url\":\"https://app.visualci.test//pdfs/builds/2\",\"waiting_for_review\":false},{\"branch\":\"main\",\"changes\":\"unchanged\",\"commit\":\"a1b2c3d4e5f6\",\"conclusion\":\"unchanged\",\"created_at\":\"\",\"number\":1,\"pr_number\":null,\"review_state\":\"auto_approved\",\"state\":\"completed\",\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"waiting_for_review\":false}]}", + "text": "{\"builds\":[{\"blocked\":null,\"branch\":\"feat\",\"changes\":\"not compared\",\"commit\":\"b2c3d4e5f6\",\"conclusion\":null,\"created_at\":\"\",\"name\":\"docs\",\"number\":2,\"pr_number\":7,\"review_state\":\"none\",\"state\":\"receiving\",\"stats\":{\"added\":0,\"changed\":0,\"failed\":0,\"removed\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/2\",\"waiting_for_review\":false},{\"blocked\":null,\"branch\":\"main\",\"changes\":\"unchanged\",\"commit\":\"a1b2c3d4e5f60718293a\",\"conclusion\":\"unchanged\",\"created_at\":\"\",\"number\":1,\"pr_number\":null,\"review_state\":\"auto_approved\",\"state\":\"completed\",\"stats\":{\"added\":0,\"changed\":0,\"failed\":0,\"removed\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"waiting_for_review\":false}]}", "type": "text" } ], @@ -11,6 +11,7 @@ "structuredContent": { "builds": [ { + "blocked": null, "branch": "feat", "changes": "not compared", "commit": "b2c3d4e5f6", @@ -21,19 +22,34 @@ "pr_number": 7, "review_state": "none", "state": "receiving", + "stats": { + "added": 0, + "changed": 0, + "failed": 0, + "removed": 0, + "unchanged": 0 + }, "url": "https://app.visualci.test//pdfs/builds/2", "waiting_for_review": false }, { + "blocked": null, "branch": "main", "changes": "unchanged", - "commit": "a1b2c3d4e5f6", + "commit": "a1b2c3d4e5f60718293a", "conclusion": "unchanged", "created_at": "", "number": 1, "pr_number": null, "review_state": "auto_approved", "state": "completed", + "stats": { + "added": 0, + "changed": 0, + "failed": 0, + "removed": 0, + "unchanged": 0 + }, "url": "https://app.visualci.test//pdfs/builds/1", "waiting_for_review": false } diff --git a/app/tests/golden/mcp/list_organizations_lists_a_persons_organizations/list_organizations.json b/app/tests/golden/mcp/list_organizations_lists_a_persons_organizations/list_organizations.json new file mode 100644 index 00000000..7e9b5af2 --- /dev/null +++ b/app/tests/golden/mcp/list_organizations_lists_a_persons_organizations/list_organizations.json @@ -0,0 +1,61 @@ +{ + "arguments": {}, + "result": { + "content": [ + { + "text": "{\"organizations\":[{\"name\":\"Org\",\"projects\":[\"pdfs\",\"shots\"],\"role\":\"admin\",\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false}}]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "organizations": [ + { + "name": "Org", + "projects": [ + "pdfs", + "shots" + ], + "role": "admin", + "slug": "", + "usage": { + "auto_reload_packs": 4, + "billing_problem": null, + "credit_pack": { + "credits": 500000, + "price_cents": 1500, + "reload_below": 100000 + }, + "credits_this_month": 0, + "included_credits": 25000, + "open_source": { + "pool": 1000000, + "projects": 0, + "used": 0 + }, + "out_of_credits": false, + "pack_credits": 0, + "plan": { + "credit_packs": false, + "id": "free", + "included_credits": 25000, + "name": "Free", + "price_cents": 0, + "unlimited": false + }, + "rates": { + "image_diff": 10, + "rendered_page": 20, + "snapshot_check": 1, + "text_diff": 5 + }, + "reloads_paused": false, + "reloads_this_month": 0, + "renews_at": "", + "unlimited": false + } + } + ] + } + } +} diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json index 1bc9020b..2569b463 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json @@ -769,7 +769,7 @@ "readOnlyHint": true, "title": "List builds" }, - "description": "List a project's builds, newest first, one short line each: number, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, whether it waits for your review, its changes in a few words (`2 changed, 1 added`) and URL. get_build has the details (its snapshots, environment, reviews, groups, CI mode and warnings). waiting_for_review: only builds whose changes wait for a review.", + "description": "List a project's builds, newest first, one short line each: number, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, whether it waits for your review, its changes in a few words (`2 changed, 1 added`) and as numbers (`stats`), `blocked` when it's out of credits, and URL. get_build has the details (its snapshots, environment, reviews, groups, CI mode and warnings). waiting_for_review: only builds whose changes wait for a review.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, @@ -1640,7 +1640,7 @@ "readOnlyHint": true, "title": "Who am I" }, - "description": "Who this token belongs to (a person or a project), how it reached VisualCI (`via`: the token's name, or the MCP client's), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", + "description": "Who this token belongs to (a person or a project), how it reached VisualCI (`via`: `source` as reviews record it, `personal_token`, `project_token`, `oauth` or `web`, with the token's or the MCP client's name), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json index 1bc9020b..2569b463 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json @@ -769,7 +769,7 @@ "readOnlyHint": true, "title": "List builds" }, - "description": "List a project's builds, newest first, one short line each: number, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, whether it waits for your review, its changes in a few words (`2 changed, 1 added`) and URL. get_build has the details (its snapshots, environment, reviews, groups, CI mode and warnings). waiting_for_review: only builds whose changes wait for a review.", + "description": "List a project's builds, newest first, one short line each: number, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, whether it waits for your review, its changes in a few words (`2 changed, 1 added`) and as numbers (`stats`), `blocked` when it's out of credits, and URL. get_build has the details (its snapshots, environment, reviews, groups, CI mode and warnings). waiting_for_review: only builds whose changes wait for a review.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, @@ -1640,7 +1640,7 @@ "readOnlyHint": true, "title": "Who am I" }, - "description": "Who this token belongs to (a person or a project), how it reached VisualCI (`via`: the token's name, or the MCP client's), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", + "description": "Who this token belongs to (a person or a project), how it reached VisualCI (`via`: `source` as reviews record it, `personal_token`, `project_token`, `oauth` or `web`, with the token's or the MCP client's name), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, diff --git a/app/tests/mcp.rs b/app/tests/mcp.rs index 480a8b7f..5ed8fbab 100644 --- a/app/tests/mcp.rs +++ b/app/tests/mcp.rs @@ -721,7 +721,7 @@ async fn personal_token_manages(app: Application) -> laravel::Result<()> { assert!(!err); assert_eq!(me["kind"], "user"); assert_eq!(me["organizations"][0]["projects"].as_array().unwrap().len(), 2); - assert_eq!(me["via"], json!({ "source": "token", "token_name": "agent" }), "{me}"); + assert_eq!(me["via"], json!({ "source": "personal_token", "token_name": "agent" }), "{me}"); let (err, org) = call(&app, TEST, t, "get_organization", json!({ "org": f.org })).await; assert!(!err, "{org}"); @@ -1027,10 +1027,12 @@ async fn list_builds_answers_one_short_line_per_build(app: Application) -> larav assert_eq!(builds.len(), 2); assert_eq!(builds[0]["name"], "docs", "a suite's name shows when it isn't the default: {list}"); assert!(builds[1].get("name").is_none() && builds[1].get("mode").is_none(), "{list}"); - assert_eq!(builds[1]["commit"], "a1b2c3d4e5f6", "12 characters of the commit"); + assert_eq!(builds[1]["commit"], "a1b2c3d4e5f60718293a", "the whole commit, to compare with HEAD"); + assert_eq!(builds[1]["stats"], json!({ "changed": 0, "added": 0, "removed": 0, "unchanged": 0, "failed": 0 })); + assert!(builds[1]["blocked"].is_null(), "{list}"); assert_eq!(builds[1]["changes"], "unchanged"); assert_eq!(builds[0]["changes"], "not compared", "still receiving"); - for left_out in ["environment_info", "reviews", "groups", "blocked", "ci_mode", "passed", "warnings"] { + for left_out in ["environment_info", "reviews", "groups", "ci_mode", "passed", "warnings"] { assert!(builds[0].get(left_out).is_none(), "{left_out} is get_build's: {list}"); } Ok(()) @@ -1055,3 +1057,97 @@ async fn comments_when_nothing_changed_are_off_until_turned_on(app: Application) assert!(!err && s["settings"]["comment_when_unchanged"] == true, "{s}"); Ok(()) } + +/// Only an organization's admins invite people, with a person's token, and a recipient is invited at most three times +/// a day. (New: today's server has no golden for invite_member.) +#[laravel::test] +async fn invite_member_checks_who_may_invite_and_its_limits(app: Application) -> laravel::Result<()> { + Box::pin(invite_member_checks(app)).await +} + +async fn invite_member_checks(app: Application) -> laravel::Result<()> { + const TEST: &str = "invite_member_checks_who_may_invite_and_its_limits"; + let f = fixture().await?; + let org = Organization::find_or_fail(f.organization_id).await?; + let member = + create!(User { pid: laravel::str::uuid7(), name: "member", email: "member@example.com", staff: false }).await?; + app::testing::fixtures::member(&org, &member, "member").await?; + let member_token = token("user_tokens", member.id, "member", "vcu").await?; + let invite = json!({ "org": f.org, "invitee": "ada@example.com", "role": "member" }); + + let (err, r) = call(&app, TEST, &f.project_token, "invite_member", invite.clone()).await; + assert!(err && r.to_string().contains("personal access token"), "a project token can't invite: {r}"); + let (err, r) = call(&app, TEST, &member_token, "invite_member", invite.clone()).await; + assert!(err && r.to_string().contains("only an organization's admins"), "a member can't: {r}"); + + let (err, r) = call(&app, TEST, &f.user_token, "invite_member", invite.clone()).await; + assert!(!err, "{r}"); + assert_eq!(r["invitation"]["invitee"], "ada@example.com", "{r}"); + assert_eq!(r["invitation"]["role"], "member"); + // Inviting the same person again keeps one invitation (and one email). Someone invited three times in a day (here by + // other organizations) isn't invited again until tomorrow. + let (err, r) = call(&app, TEST, &f.user_token, "invite_member", invite.clone()).await; + assert!(!err, "{r}"); + for n in 0..3 { + let key = format!("invited:elsewhere:{n}"); + db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data) VALUES ('invited', {key}, 'bea@example.com', '{{}}')" + ) + .insert() + .await?; + } + let bea = json!({ "org": f.org, "invitee": "bea@example.com", "role": "read" }); + let (err, r) = call(&app, TEST, &f.user_token, "invite_member", bea).await; + assert!(err && r.to_string().contains("invited too often"), "{r}"); + Ok(()) +} + +/// A build's images download as one archive, built in the background (inline in tests): the answer says its state and, +/// when ready, its URL. (New: today's server has no golden for download_build.) +#[laravel::test] +async fn download_build_builds_an_archive_and_says_its_state(app: Application) -> laravel::Result<()> { + const TEST: &str = "download_build_builds_an_archive_and_says_its_state"; + app::testing::fixtures::blob_store().await?; + let f = fixture().await?; + let t = &f.project_token; + call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + let (err, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "1", "allow_empty": true })).await; + assert!(!err, "{done}"); + let (err, d) = call(&app, TEST, t, "download_build", json!({ "build": "1", "state": "all" })).await; + assert!(!err, "{d}"); + assert_eq!(d["state"], "ready", "{d}"); + assert!(d["url"].is_string(), "{d}"); + assert_eq!(d["summary"]["snapshots"], 0, "{d}"); + let (err, r) = call(&app, TEST, t, "download_build", json!({ "build": "1", "state": "new" })).await; + assert!(err && r.to_string().contains("state must be one of"), "{r}"); + let (err, r) = call(&app, TEST, t, "download_build", json!({ "build": "9" })).await; + assert!(err && r.to_string().contains("no build"), "{r}"); + Ok(()) +} + +/// A person's organizations, with their role, usage and projects. (New: today's tests read it with a project token +/// only.) +#[laravel::test] +async fn list_organizations_lists_a_persons_organizations(app: Application) -> laravel::Result<()> { + const TEST: &str = "list_organizations_lists_a_persons_organizations"; + let f = fixture().await?; + let (err, orgs) = call(&app, TEST, &f.user_token, "list_organizations", json!({})).await; + assert!(!err, "{orgs}"); + assert_eq!(orgs["organizations"][0]["slug"], f.org); + assert_eq!(orgs["organizations"][0]["role"], "admin"); + assert_eq!(orgs["organizations"][0]["projects"], json!(["pdfs", "shots"])); + assert_eq!(orgs["organizations"][0]["usage"]["plan"]["id"], "free"); + Ok(()) +} + +/// A slug that's taken is refused in today's words. (New: today's server has no golden for it.) +#[laravel::test] +async fn create_organization_refuses_a_taken_slug(app: Application) -> laravel::Result<()> { + const TEST: &str = "create_organization_refuses_a_taken_slug"; + let f = fixture().await?; + let (err, r) = + call(&app, TEST, &f.user_token, "create_organization", json!({ "slug": f.org, "name": "Again" })).await; + assert!(err, "{r}"); + assert_eq!(r, json!(format!("the slug {} is taken", f.org))); + Ok(()) +}