Skip to content

Commit a9cedbc

Browse files
authored
app/: the rest of the public MCP server (sc-8900) (#91)
* 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/: 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/: 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 * app/: format the comment_when_unchanged migration and test * 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/: #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
1 parent 7b1cb02 commit a9cedbc

43 files changed

Lines changed: 2424 additions & 49 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
//! `projects.comment_when_unchanged` (c2da705, #90): whether VisualCI comments on a pull request whose builds are all
2+
//! unchanged. Off by default, for every project: such a pull request gets only the passing check.
3+
4+
use laravel::db::AnyTransaction;
5+
6+
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
7+
tx.query("ALTER TABLE projects ADD COLUMN comment_when_unchanged boolean DEFAULT false NOT NULL")
8+
.unprepared()
9+
.await?;
10+
Ok(())
11+
}

‎app/src/domain/comments.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ use serde::Deserialize;
1212

1313
use crate::models::{Build, Comment, CommentThread, Snapshot, User};
1414

15-
/// Where a thread is pinned, in pixels of the pinned side's own image (base or head), from its top left.
15+
/// Where a thread is pinned, in pixels of the pinned side's own image (base or head), from its top left. Pixels, not
16+
/// fractions: when a full-page screenshot grows at the bottom in a later build of the branch, a pin stays on the same
17+
/// content. They're also the units of the regions `get_snapshot` gives.
1618
#[derive(Debug, Clone, PartialEq, Deserialize, schemars::JsonSchema)]
1719
#[serde(tag = "kind", rename_all = "lowercase")]
1820
pub enum Anchor {

‎app/src/domain/projects.rs‎

Lines changed: 280 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
//! Project settings the domain reads.
1+
//! Projects: making one, its settings (as the MCP tools and the web app read and change them), and what the domain
2+
//! reads from them.
23
34
use visualci_core::config::ScopedIgnoreRule;
45

@@ -39,3 +40,281 @@ pub fn diff_options(
3940
pub fn renderer_key(engine: &str, dpi: i32, renderer_version: &str) -> String {
4041
format!("{engine}/{dpi}dpi/{renderer_version}")
4142
}
43+
44+
/// Lowercase letters, digits and dashes, at most 60, and not `billing` (the organization's billing page is
45+
/// `app.visualci.com/<org>/billing`).
46+
#[must_use]
47+
pub fn valid_slug(s: &str) -> bool {
48+
!s.is_empty()
49+
&& s.len() <= 60
50+
&& s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
51+
&& s != "billing"
52+
}
53+
54+
/// A project's settings, as the web app shows them and the MCP server returns them.
55+
#[derive(Debug, Clone, serde::Serialize)]
56+
pub struct Settings {
57+
pub slug: String,
58+
pub name: String,
59+
/// The forge the repository is on (`github`), and the repository's URL.
60+
pub forge: Option<String>,
61+
pub repository_url: Option<String>,
62+
/// Whether the forge's app is installed on the repository, so pull requests get VisualCI's check and people's
63+
/// access follows their permission on it.
64+
pub forge_app_installed: bool,
65+
/// When the forge's webhook last delivered a verified event, or VisualCI added it (GitLab).
66+
pub forge_webhook_at: Option<String>,
67+
/// Whether the screenshots visualci.yml's `gallery` names are public.
68+
pub gallery_enabled: bool,
69+
/// Whether project tokens may approve changes over MCP; off keeps approving with people.
70+
pub tokens_can_approve: bool,
71+
/// Whether VisualCI comments on a pull request whose builds are all unchanged. Off by default: the VisualCI check
72+
/// still passes, and a comment already there (an earlier build had changes) keeps being updated.
73+
pub comment_when_unchanged: bool,
74+
/// Whether anyone, signed in or not, can read the project's builds and diffs (open source). Settings, tokens and
75+
/// reviewing stay with its members.
76+
pub public: bool,
77+
/// The forge says the linked repository is public (checked on linking and once a day). Only then can the project
78+
/// be public.
79+
pub repository_public: bool,
80+
/// The forge verified the repository as public with an OSI-approved licence (checked on linking and once a day).
81+
pub open_source: bool,
82+
/// Why it isn't open source, or its licence when it is.
83+
pub open_source_note: Option<String>,
84+
/// Whether its builds draw from the open source pool now: open source, public, and not withdrawn by staff.
85+
pub open_source_pool: bool,
86+
pub open_source_withdrawn: bool,
87+
/// A change VisualCI made on its own (made private when its repository went private), until it's dismissed.
88+
pub notice: Option<String>,
89+
pub default_branch: String,
90+
pub ci_mode: String,
91+
pub renderer: String,
92+
pub dpi: i32,
93+
pub threshold: f64,
94+
pub ignore_anti_aliasing: bool,
95+
pub ignore_rules: Vec<ScopedIgnoreRule>,
96+
}
97+
98+
impl From<&Project> for Settings {
99+
fn from(p: &Project) -> Self {
100+
Self {
101+
slug: p.slug.clone(),
102+
name: p.name.clone(),
103+
forge: p.forge.clone(),
104+
repository_url: p.repository_url.clone(),
105+
forge_app_installed: p.forge_installation.is_some(),
106+
forge_webhook_at: p.forge_webhook_at.map(|d| d.to_string()),
107+
gallery_enabled: p.gallery_enabled,
108+
tokens_can_approve: p.tokens_can_approve,
109+
comment_when_unchanged: p.comment_when_unchanged,
110+
public: p.public,
111+
repository_public: p.repository_public,
112+
open_source: p.open_source,
113+
open_source_note: p.open_source_note.clone(),
114+
open_source_pool: super::credits::counts_as_open_source(p),
115+
open_source_withdrawn: p.open_source_withdrawn,
116+
notice: p.notice.clone(),
117+
default_branch: p.default_branch.clone(),
118+
ci_mode: p.ci_mode.clone(),
119+
renderer: p.renderer.clone(),
120+
dpi: p.dpi,
121+
threshold: p.threshold,
122+
ignore_anti_aliasing: p.ignore_anti_aliasing,
123+
ignore_rules: ignore_rules(p),
124+
}
125+
}
126+
}
127+
128+
/// Changes to a project's settings; fields left out stay as they are.
129+
#[derive(Debug, Default, serde::Deserialize, schemars::JsonSchema)]
130+
pub struct SettingsChange {
131+
/// A new slug, renaming the project (`acme/old` → `acme/new`): lowercase letters, digits and dashes. Its builds,
132+
/// baselines and tokens stay. The old address and `acme/old` stop working.
133+
pub slug: Option<String>,
134+
/// The project's display name.
135+
pub name: Option<String>,
136+
/// The repository this project tests, by URL (`https://github.com/acme/web`); an empty string unlinks it.
137+
/// Linking needs the forge's VisualCI app installed on the repository and you to be an admin or maintainer of
138+
/// it there. Its pull requests then get VisualCI's check, and people's access to this organization follows their
139+
/// permission on it.
140+
pub repository_url: Option<String>,
141+
/// A project on your organization's own GitLab instance: an access token for it (a project or group access token
142+
/// with the `api` scope and the Developer role, or Maintainer to let VisualCI add its webhook), sent with
143+
/// `repository_url`. Stored encrypted; never shown again.
144+
pub forge_token: Option<String>,
145+
/// With `repository_url`: a repository belongs to one organization, so when another organization has it linked,
146+
/// `true` moves the link here (you must maintain the repository; that organization's admins get an email).
147+
#[serde(default)]
148+
pub move_link: bool,
149+
/// `false` takes the public gallery down (visualci.yml's `gallery` decides what's in it); `true` puts it back.
150+
pub gallery_enabled: Option<bool>,
151+
/// `false`: project tokens can't approve changes (people do); `true` lets CI's agents approve again.
152+
pub tokens_can_approve: Option<bool>,
153+
/// `true`: comment on pull requests even when nothing changed. `false` (the default): a pull request whose builds
154+
/// are all unchanged gets no comment, only the passing check; a comment already there keeps being updated.
155+
pub comment_when_unchanged: Option<bool>,
156+
/// `true` lets anyone, signed in or not, read the project's builds and diffs (for open source projects);
157+
/// settings, tokens and reviewing stay with its members. Only a project linked to a public repository can be
158+
/// public. `false` makes it private again.
159+
pub public: Option<bool>,
160+
/// `true` dismisses the project's notice.
161+
pub dismiss_notice: Option<bool>,
162+
/// The branch whose builds become the baseline automatically.
163+
pub default_branch: Option<String>,
164+
/// `review` (CI passes, the check waits for review), `strict` (CI fails on unreviewed changes) or `wait`.
165+
pub ci_mode: Option<String>,
166+
/// The PDF renderer: `pdfbox` or `mutool`.
167+
pub renderer: Option<String>,
168+
/// Render resolution for documents, 36 to 600.
169+
pub dpi: Option<i32>,
170+
/// The diff threshold, 0 to 1: 0 compares exactly; above 0 it's pixelmatch's colour threshold (how different a
171+
/// pixel's colour must be to count), and anti-aliased pixels are ignored.
172+
pub threshold: Option<f64>,
173+
/// Ignore anti-aliasing differences in images.
174+
pub ignore_anti_aliasing: Option<bool>,
175+
/// Values in text snapshots that change on every run, ignored when comparing. Replaces the project's rules. Each
176+
/// rule names the snapshots it applies to with a glob (`api/invoices/**`; `**` for every snapshot). A build's
177+
/// `visualci.yml` replaces these rules when it has `ignore`.
178+
pub ignore_rules: Option<Vec<ScopedIgnoreRule>>,
179+
}
180+
181+
/// Make a project in an organization, with the default settings.
182+
///
183+
/// # Errors
184+
/// `Ok(Err(message))` for a slug that isn't valid or is taken; `Err` on a database error.
185+
pub async fn create(organization_id: i64, slug: &str, name: &str) -> laravel::Result<Result<Project, String>> {
186+
if !valid_slug(slug) {
187+
return Ok(Err("project slugs use lowercase letters, digits and dashes, and can't be billing".into()));
188+
}
189+
let taken =
190+
Project::query().filter(Project::organization_id.eq(organization_id) & Project::slug.eq(slug)).exists().await?;
191+
if taken {
192+
return Ok(Err(format!("the organization already has a project called {slug}")));
193+
}
194+
let name = name.trim();
195+
Ok(Ok(laravel::model::create!(Project {
196+
pid: laravel::str::uuid7(),
197+
organization_id: organization_id,
198+
slug: slug,
199+
name: name,
200+
})
201+
.await?))
202+
}
203+
204+
/// The repository its newest CI build named (`environment_info.repository_url`), for suggesting a link.
205+
///
206+
/// # Errors
207+
/// On a database error.
208+
pub async fn repository_seen_in_ci(project: &Project) -> laravel::Result<Option<String>> {
209+
let project_id = project.id;
210+
let info: Option<serde_json::Value> = laravel::db::query!(
211+
"SELECT environment_info FROM builds WHERE project_id = {project_id} AND mode = 'ci' ORDER BY id DESC LIMIT 1"
212+
)
213+
.scalar()
214+
.await?;
215+
Ok(info
216+
.as_ref()
217+
.and_then(|i| i.get("repository_url"))
218+
.and_then(|v| v.as_str())
219+
.and_then(crate::forge::Repository::parse)
220+
.map(|r| r.url))
221+
}
222+
223+
/// Apply a settings change, checking every field first. The repository link isn't set here: it needs the forge to agree
224+
/// (subdomains' `forge::link::link_repository`), which callers do first. Turning the gallery off purges what it
225+
/// published first.
226+
///
227+
/// # Errors
228+
/// `Ok(Err(message))` for a value that isn't valid; `Err` on a database error.
229+
pub async fn change_settings(project: Project, p: SettingsChange) -> laravel::Result<Result<Project, String>> {
230+
let new_slug = p.slug.as_deref().map(str::trim).filter(|s| *s != project.slug).map(str::to_string);
231+
if let Some(slug) = &new_slug {
232+
if !valid_slug(slug) {
233+
return Ok(Err("slug must be lowercase letters, digits and dashes, at most 60 characters".into()));
234+
}
235+
let taken = Project::query()
236+
.filter(Project::organization_id.eq(project.organization_id) & Project::slug.eq(slug.as_str()))
237+
.exists()
238+
.await?;
239+
if taken {
240+
return Ok(Err(format!("the organization already has a project called {slug}")));
241+
}
242+
}
243+
// A private repository's screenshots stay private: only a project whose repository the forge says is public can
244+
// be made public.
245+
if p.public == Some(true) && !project.public && !project.repository_public {
246+
return Ok(Err("only a project linked to a public repository can be public".into()));
247+
}
248+
if let Some(m) = &p.ci_mode
249+
&& !["review", "strict", "wait"].contains(&m.as_str())
250+
{
251+
return Ok(Err("ci_mode must be review, strict or wait".into()));
252+
}
253+
if let Some(r) = &p.renderer
254+
&& !["pdfbox", "mutool"].contains(&r.as_str())
255+
{
256+
return Ok(Err("renderer must be pdfbox or mutool".into()));
257+
}
258+
if p.dpi.is_some_and(|d| !(36..=600).contains(&d)) {
259+
return Ok(Err("dpi must be 36 to 600".into()));
260+
}
261+
if p.threshold.is_some_and(|t| !(0.0..=1.0).contains(&t)) {
262+
return Ok(Err("threshold must be between 0 and 1".into()));
263+
}
264+
let ignore_rules = match p.ignore_rules {
265+
Some(rules) => {
266+
let clean = |v: Vec<String>| -> Vec<String> {
267+
v.into_iter().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
268+
};
269+
let rules: Vec<ScopedIgnoreRule> = rules
270+
.into_iter()
271+
.map(|r| ScopedIgnoreRule {
272+
snapshots: r.snapshots.trim().to_string(),
273+
json_paths: clean(r.json_paths),
274+
text_patterns: clean(r.text_patterns),
275+
})
276+
.collect();
277+
if let Err(e) = visualci_core::config::validate_ignore_rules(&rules) {
278+
return Ok(Err(e));
279+
}
280+
Some(serde_json::to_value(rules).unwrap_or_default())
281+
}
282+
None => None,
283+
};
284+
if p.gallery_enabled == Some(false) && project.gallery_enabled {
285+
super::gallery::purge_project(project.id).await?;
286+
}
287+
let mut project = project;
288+
let slug = new_slug.unwrap_or_else(|| project.slug.clone());
289+
let name = p.name.unwrap_or_else(|| project.name.clone());
290+
let tokens_can_approve = p.tokens_can_approve.unwrap_or(project.tokens_can_approve);
291+
let comment_when_unchanged = p.comment_when_unchanged.unwrap_or(project.comment_when_unchanged);
292+
let gallery_enabled = p.gallery_enabled.unwrap_or(project.gallery_enabled);
293+
let public = p.public.unwrap_or(project.public);
294+
let notice = if p.dismiss_notice == Some(true) { None } else { project.notice.clone() };
295+
let default_branch = p.default_branch.unwrap_or_else(|| project.default_branch.clone());
296+
let ci_mode = p.ci_mode.unwrap_or_else(|| project.ci_mode.clone());
297+
let renderer = p.renderer.unwrap_or_else(|| project.renderer.clone());
298+
let dpi = p.dpi.unwrap_or(project.dpi);
299+
let threshold = p.threshold.unwrap_or(project.threshold);
300+
let ignore_anti_aliasing = p.ignore_anti_aliasing.unwrap_or(project.ignore_anti_aliasing);
301+
let ignore_rules = ignore_rules.unwrap_or_else(|| project.ignore_rules.clone());
302+
laravel::model::update!(project {
303+
slug,
304+
name,
305+
tokens_can_approve,
306+
comment_when_unchanged,
307+
gallery_enabled,
308+
public,
309+
notice,
310+
default_branch,
311+
ci_mode,
312+
renderer,
313+
dpi,
314+
threshold,
315+
ignore_anti_aliasing,
316+
ignore_rules,
317+
})
318+
.await?;
319+
Ok(Ok(project))
320+
}

‎app/src/mcp/args.rs‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,38 @@ pub struct OrgArgs {
2121
pub org: String,
2222
}
2323

24+
#[derive(Debug, Deserialize, JsonSchema)]
25+
pub struct InviteArgs {
26+
/// The organization's slug.
27+
pub org: String,
28+
/// An email address, or a GitHub login (`octocat` or `@octocat`).
29+
pub invitee: String,
30+
/// `admin` (settings, projects, tokens, billing, members), `member` (send builds, review and approve) or `read`.
31+
pub role: InviteRole,
32+
}
33+
34+
/// A member's role, lowest first.
35+
#[derive(Clone, Copy, Debug, Deserialize, JsonSchema, PartialEq, Eq)]
36+
#[serde(rename_all = "snake_case")]
37+
pub enum InviteRole {
38+
/// Sees builds and snapshots; changes nothing.
39+
Read,
40+
/// Everything a build needs: uploads, review and approval.
41+
Member,
42+
/// Also settings, projects, tokens, billing and members.
43+
Admin,
44+
}
45+
46+
impl From<InviteRole> for crate::auth::Role {
47+
fn from(r: InviteRole) -> Self {
48+
match r {
49+
InviteRole::Read => Self::Read,
50+
InviteRole::Member => Self::Member,
51+
InviteRole::Admin => Self::Admin,
52+
}
53+
}
54+
}
55+
2456
#[derive(Debug, Deserialize, JsonSchema)]
2557
pub struct CreateOrgArgs {
2658
/// Lowercase letters, digits and dashes; used in URLs.
@@ -42,6 +74,14 @@ pub struct ProjectArgs {
4274
pub project: Option<String>,
4375
}
4476

77+
#[derive(Debug, Deserialize, JsonSchema)]
78+
pub struct UpdateProjectArgs {
79+
/// `org/project`. Optional with a project token.
80+
pub project: Option<String>,
81+
#[serde(flatten)]
82+
pub change: crate::domain::projects::SettingsChange,
83+
}
84+
4585
#[derive(Debug, Deserialize, JsonSchema)]
4686
pub struct CreateTokenArgs {
4787
/// `org/project`. Optional with a project token.
@@ -435,3 +475,19 @@ pub struct SupportSendArgs {
435475
pub agent: Option<serde_json::Value>,
436476
pub idempotency_key: Option<String>,
437477
}
478+
479+
#[derive(Debug, Deserialize, JsonSchema)]
480+
pub struct DownloadArgs {
481+
/// `org/project`. Optional with a project token.
482+
pub project: Option<String>,
483+
pub build: BuildRef,
484+
/// Which snapshots: `changed` (the default), `added`, `removed`, `unchanged`, or `all`.
485+
pub state: Option<String>,
486+
/// Which images of each page: `base`, `head`, `diff`, `regions` (the head cropped to the changes). Default: base,
487+
/// head and diff.
488+
pub sides: Option<Vec<String>>,
489+
/// Only snapshots whose name matches this glob, like `v2/pdfjs/**`.
490+
pub glob: Option<String>,
491+
/// Seconds to wait for the archive (default 50, at most 60). Not ready by then: call again with the same arguments.
492+
pub wait: Option<u64>,
493+
}

0 commit comments

Comments
 (0)