diff --git a/app/database/migrations/2026_12_05_000000_repository_picker.rs b/app/database/migrations/2026_12_05_000000_repository_picker.rs new file mode 100644 index 00000000..fcca24c7 --- /dev/null +++ b/app/database/migrations/2026_12_05_000000_repository_picker.rs @@ -0,0 +1,51 @@ +//! The repository picker (sc-9027): setting the GitHub App up maps the installation and makes no projects; people pick +//! the repositories they want, and a queued job makes them into projects. +//! +//! `user_repositories` is every repository each person can reach through each installation, with their permission on +//! it, as of their last GitHub sign-in (which lists them anyway): the picker reads it with no GitHub call, so it pages +//! and searches hundreds of repositories at once. +//! +//! `repository_imports` is one choice of repositories to make into projects, and how far the job has got: the picker +//! shows its progress, and `/status` how long the oldest unfinished one has waited. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r#" +CREATE TABLE user_repositories ( + user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + installation_id TEXT NOT NULL REFERENCES github_installations(installation_id) ON DELETE CASCADE, + -- GitHub's ID for the repository, and its `owner/name`. + repository_id TEXT NOT NULL, + full_name TEXT NOT NULL, + -- read, triage, write, maintain or admin. + permission TEXT NOT NULL, + private BOOLEAN NOT NULL DEFAULT false, + archived BOOLEAN NOT NULL DEFAULT false, + seen_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, installation_id, repository_id) +); +CREATE INDEX user_repositories_name ON user_repositories (user_id, lower(full_name)); + +CREATE TABLE repository_imports ( + id BIGSERIAL PRIMARY KEY, + organization_id BIGINT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE, + user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, + -- [{installation_id, repository_id, full_name}], in the order they're made. + requested JSONB NOT NULL, + -- [{project, repository}] made, and [{repository, reason}] not made, so far. + linked JSONB NOT NULL DEFAULT '[]'::jsonb, + skipped JSONB NOT NULL DEFAULT '[]'::jsonb, + -- Set when the job has gone through every repository, or stopped on an error (`error`). + finished_at TIMESTAMPTZ, + error TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX repository_imports_organization ON repository_imports (organization_id, created_at DESC); +CREATE INDEX repository_imports_unfinished ON repository_imports (created_at) WHERE finished_at IS NULL; +"#; diff --git a/app/src/auth/installations.rs b/app/src/auth/installations.rs index e24ee498..010bd296 100644 --- a/app/src/auth/installations.rs +++ b/app/src/auth/installations.rs @@ -4,12 +4,16 @@ //! - `GET /github/setup?installation_id=…&state=…` is the App's Setup URL: GitHub sends people there after they //! install it, with that `state`. Someone signed out signs in first and comes back; an installation their account //! can't reach yet sends them through GitHub's sign-in once more, which refreshes the list. With the session's -//! `state`, [`set_up`](installations::set_up) gives it an organization and projects, and they land on the -//! organization's page with the next step (adding VisualCI to CI) open. Without it (a link from another site), it +//! `state`, [`set_up`](installations::set_up) gives it an organization (no projects), and they land on the +//! repository picker, where they choose which repositories become projects. Without it (a link from another site), it //! changes nothing: they land on their own organization's page, where the checklist offers the installation and a //! click sets it up. //! - `POST /api/ui/installations/{id}/setup` is that click: it sets up an installation the checklist offers ("already //! installed on X: set it up"), and answers what it did as JSON. +//! - `GET /api/ui/orgs/{org}/repositories?q=…&page=…` is the picker (admins): the repositories the person can reach +//! through the organization's installations, from their last GitHub sign-in, with no GitHub call. `POST` with +//! `repository_ids` makes the chosen ones into projects through a queued job; `GET +//! /api/ui/orgs/{org}/repository-imports/{id}` is its progress. use laravel::auth::{Auth, Authenticated}; use laravel::prelude::*; @@ -24,6 +28,9 @@ pub fn routes(route: &mut Router) { route.get("/github/install", install); route.get("/github/setup", setup_page); route.post("/api/ui/installations/{id}/setup", setup); + route.get("/api/ui/orgs/{org}/repositories", picker); + route.post("/api/ui/orgs/{org}/repositories", import); + route.get("/api/ui/orgs/{org}/repository-imports/{id}", import_progress); } /// The session key holding the `state` sent to GitHub with an install. @@ -38,10 +45,10 @@ pub struct SetupQuery { refreshed: Option, } -/// Where the organization's page opens after a set-up: the next step, adding VisualCI to CI. +/// Where a set-up lands: the organization's repository picker. #[must_use] pub fn landing(outcome: &SetUp) -> String { - format!("/{}?setup=add_to_ci&installation={}", outcome.organization, outcome.installation_id) + format!("/{}/repositories?installation={}", outcome.organization, outcome.installation_id) } /// `GET /github/install`: off to GitHub to install the App, with a `state` that brings the set-up back to this @@ -83,7 +90,12 @@ pub async fn setup_page( let Some(user) = auth.user().await? else { return Ok(laravel::http::Response::new(through_sign_in(&id, q.state.as_deref()))); }; - if !installations::reachable(user.id, &id).await? { + let known = installations::reachable(user.id, &id).await?; + // Reachable only through the `installation` webhook (they installed it): sign in once more for its repositories + if known && q.refreshed.is_none() && !installations::knows_repositories(user.id, &id).await? { + return Ok(laravel::http::Response::new(through_sign_in(&id, q.state.as_deref()))); + } + if !known { if q.refreshed.is_none() { return Ok(laravel::http::Response::new(through_sign_in(&id, q.state.as_deref()))); } @@ -143,3 +155,70 @@ fn page(title: &str, message: &str) -> laravel::http::Response { ); laravel::http::Response::new(laravel::view::Html::raw(html)) } + +/// The organization's ID, for an admin of it (404 for anyone else, so it doesn't say the organization exists). +async fn admin_of(user: &User, org: &str) -> laravel::Result { + let user_id = user.id; + let row = laravel::db::query!( + "SELECT o.id, m.role FROM organizations o \ + LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} WHERE o.slug = {org}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + match row.try_get::>("role")?.as_deref().and_then(crate::auth::Role::parse) { + Some(crate::auth::Role::Admin) => Ok(row.try_get("id")?), + Some(_) => Err(laravel::abort_with(403, "only the organization's admins add repositories")), + None => Err(laravel::abort(404)), + } +} + +#[derive(serde::Deserialize)] +pub struct PickerQuery { + /// Only this installation's repositories. + installation: Option, + q: Option, + page: Option, +} + +/// `GET /api/ui/orgs/{org}/repositories` (admins): a page of the repository picker. +pub async fn picker( + Authenticated(user): Authenticated, + Params(org): Params, + axum::extract::Query(q): axum::extract::Query, +) -> laravel::Result> { + let org_id = admin_of(&user, &org).await?; + let query: String = q.q.unwrap_or_default().chars().take(100).collect(); + Ok(Json(installations::picker(user.id, org_id, q.installation.as_deref(), &query, q.page.unwrap_or(1)).await?)) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct ImportInput { + repository_ids: Vec, +} + +/// `POST /api/ui/orgs/{org}/repositories` (admins): make the chosen repositories into projects, in the background. +/// Answers the pick's progress. +pub async fn import( + Authenticated(user): Authenticated, + Params(org): Params, + Valid(p): Valid, +) -> laravel::Result> { + let org_id = admin_of(&user, &org).await?; + let id = installations::import(&user, org_id, &p.repository_ids).await?; + Ok(Json(installations::import_state(org_id, id).await?)) +} + +/// `GET /api/ui/orgs/{org}/repository-imports/{id}` (admins): a pick's progress. +pub async fn import_progress( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, i64)>, +) -> laravel::Result> { + let org_id = admin_of(&user, &org).await?; + let state = installations::import_state(org_id, id).await?; + if state.is_null() { + return Err(laravel::abort(404)); + } + Ok(Json(state)) +} diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index ba38b291..52d263c9 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -187,7 +187,7 @@ pub async fn callback( } // The GitHub App's installations they can reach, for the setup page and the checklist's offers if sign_in.identity.forge == ForgeKind::Github { - forge::installations::remember(user.id, &sign_in.installations).await?; + forge::installations::remember(user.id, &sign_in.installations, &sign_in.reachable).await?; } SignedIn { user_id: user.id, diff --git a/app/src/domain/demo.rs b/app/src/domain/demo.rs index 1ff5ecb2..a897b856 100644 --- a/app/src/domain/demo.rs +++ b/app/src/domain/demo.rs @@ -146,6 +146,7 @@ pub async fn screenshots_seed(store: &BlobStore, renderer_version: &str) -> lara .insert() .await?; let blog = seed_project(&side, "blog", "Blog").await?; + seed_repository_picker(ada.id, acme_id, side_id).await?; let seeder = Seeder { store, renderer_version }; Box::pin(seeder.web_builds(&web, ada.id)).await?; @@ -626,3 +627,110 @@ fn feed(items: usize) -> String { text.push_str("\n\n"); text } + +/// The repository picker's data: the GitHub App installed on Acme (set up for acme, 60 repositories Ada can reach, web +/// already a project, some she can only write to, two archived) and on her own account (set up for side-project, with a +/// pick of five repositories half made, for the progress page). +async fn seed_repository_picker(ada: i64, acme: i64, side: i64) -> laravel::Result<()> { + for (installation, account_id, login, kind, org) in + [("1", "5005", "acme", "Organization", acme), ("2", "1001", "ada", "User", side)] + { + let result = serde_json::json!({ "installation_id": installation, "account_login": login, "organization": "", + "organization_created": false, "note": null }) + .to_string(); + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type, \ + organization_id, set_up_by, installed_by, setup_result) \ + VALUES ({installation}, {account_id}, {login}, {kind}, {org}, {ada}, '1001', {result}::jsonb)" + ) + .insert() + .await?; + db::query!("INSERT INTO user_installations (user_id, installation_id) VALUES ({ada}, {installation})") + .insert() + .await?; + } + db::query!( + "UPDATE github_installations SET setup_result = jsonb_set(setup_result, '{{organization}}', \ + to_jsonb(CASE installation_id WHEN '1' THEN 'acme' ELSE 'side-project' END))" + ) + .update() + .await?; + const NAMES: &[&str] = &[ + "web", + "api", + "billing", + "checkout", + "design-system", + "docs", + "emails", + "invoices-pdf", + "mobile", + "marketing-site", + "pdf-templates", + "reports", + "search", + "admin", + "analytics", + "auth", + "cli", + "data-pipeline", + "edge", + "forms", + ]; + let mut n = 0; + for round in ["", "-v2", "-legacy"] { + for name in NAMES { + n += 1; + let (full, id) = (format!("acme/{name}{round}"), (100 + n).to_string()); + let permission = match n % 9 { + 0 => "write", + 4 => "read", + _ => "admin", + }; + let archived = round == "-legacy" && n % 7 == 0; + let private = n % 3 != 0; + db::query!( + "INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission, private, \ + archived) VALUES ({ada}, '1', {id}, {full}, {permission}, {private}, {archived})" + ) + .insert() + .await?; + } + } + db::query!("UPDATE projects SET repository_id = '101' WHERE organization_id = {acme} AND slug = 'web'") + .update() + .await?; + for (i, name) in ["blog", "notes", "dotfiles", "recipes", "talks"].iter().enumerate() { + let (full, id) = (format!("ada/{name}"), (900 + i).to_string()); + db::query!( + "INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission, private) \ + VALUES ({ada}, '2', {id}, {full}, 'admin', false)" + ) + .insert() + .await?; + } + let requested = serde_json::json!([ + { "installation_id": "2", "repository_id": "901", "full_name": "ada/notes" }, + { "installation_id": "2", "repository_id": "902", "full_name": "ada/dotfiles" }, + { "installation_id": "2", "repository_id": "903", "full_name": "ada/recipes" }, + { "installation_id": "2", "repository_id": "904", "full_name": "ada/talks" }, + { "installation_id": "2", "repository_id": "900", "full_name": "ada/blog" }, + ]) + .to_string(); + let linked = serde_json::json!([ + { "project": "notes", "repository": "ada/notes" }, + { "project": "dotfiles", "repository": "ada/dotfiles" }, + ]) + .to_string(); + let skipped = serde_json::json!([ + { "repository": "ada/recipes", "reason": "it's archived on GitHub" }, + ]) + .to_string(); + db::query!( + "INSERT INTO repository_imports (organization_id, user_id, requested, linked, skipped) \ + VALUES ({side}, {ada}, {requested}::jsonb, {linked}::jsonb, {skipped}::jsonb)" + ) + .insert() + .await?; + Ok(()) +} diff --git a/app/src/forge/github.rs b/app/src/forge/github.rs index 0c0ef04c..7deea7c8 100644 --- a/app/src/forge/github.rs +++ b/app/src/forge/github.rs @@ -21,7 +21,7 @@ pub async fn sign_in(profile: &laravel::auth::social::User) -> laravel::Result laravel::Result laravel::Result> { Ok(emails.into_iter().map(|e| e.email.to_lowercase()).collect()) } -/// The App's installations the person can reach, and every repository the App can see through them that the person -/// has a permission on. -async fn installations(token: &str) -> laravel::Result<(Vec, Vec<(Repository, Permission)>)> { +/// The App's installations the person can reach, every repository the App can see through them that the person has a +/// permission on, and the same repositories by installation (with whether each is private or archived). +async fn installations( + token: &str, +) -> laravel::Result<(Vec, Vec<(Repository, Permission)>, Vec)> { let mut found = Vec::new(); let mut out = Vec::new(); + let mut reachable = Vec::new(); for item in all_pages(token, "/user/installations", "installations").await? { let Some(installation) = item["id"].as_i64() else { continue }; if let Some(account) = installation_account(installation.to_string(), &item["account"]) { @@ -73,10 +77,20 @@ async fn installations(token: &str) -> laravel::Result<(Vec, Vec<( else { continue; }; - out.push((repository.with_id(repo["id"].as_i64().map(|i| i.to_string())), permission)); + let repository = repository.with_id(repo["id"].as_i64().map(|i| i.to_string())); + if repository.id.is_some() { + reachable.push(super::Reachable { + installation_id: installation.to_string(), + repository: repository.clone(), + permission, + private: repo["private"].as_bool().unwrap_or(false), + archived: repo["archived"].as_bool().unwrap_or(false), + }); + } + out.push((repository, permission)); } } - Ok((found, out)) + Ok((found, out, reachable)) } /// An installation from GitHub's `account` object (on `/user/installations` and the `installation` webhook). diff --git a/app/src/forge/gitlab.rs b/app/src/forge/gitlab.rs index 8ac41c19..9ed60992 100644 --- a/app/src/forge/gitlab.rs +++ b/app/src/forge/gitlab.rs @@ -95,6 +95,7 @@ pub async fn sign_in(base: &str, profile: &social::User) -> laravel::Result, - /// Projects made now. - pub linked: Vec, - /// Repositories already linked to a project of this organization. - pub already: Vec, - pub skipped: Vec, - /// More repositories were granted than one set-up looks at ([`REPOSITORY_LIMIT`]). - pub truncated: bool, } fn refused(status: u16, message: impl Into) -> laravel::Error { laravel::abort_with(status, message.into()) } -/// Record the installations a person's GitHub sign-in listed: each installation, and that they can reach exactly -/// these now. +/// Record the installations a person's GitHub sign-in listed, and the repositories they can reach through each (for +/// the repository picker): each installation, and that they can reach exactly these now. /// /// # Errors /// On a database error. -pub async fn remember(user_id: i64, found: &[Installation]) -> laravel::Result<()> { +pub async fn remember(user_id: i64, found: &[Installation], reachable: &[Reachable]) -> laravel::Result<()> { let found = found.to_vec(); + let reachable = reachable.to_vec(); db::transaction(async |_| { for i in &found { upsert(i).await?; } db::query!("DELETE FROM user_installations WHERE user_id = {user_id}").delete().await?; + db::query!("DELETE FROM user_repositories WHERE user_id = {user_id}").delete().await?; for i in &found { let id = i.id.clone(); db::query!( @@ -86,6 +85,26 @@ pub async fn remember(user_id: i64, found: &[Installation]) -> laravel::Result<( .insert() .await?; } + for r in reachable.iter().filter(|r| found.iter().any(|i| i.id == r.installation_id)) { + let (installation, repository_id, name, permission, private, archived) = ( + r.installation_id.clone(), + r.repository.id.clone(), + r.repository.path.clone(), + r.permission.as_str(), + r.private, + r.archived, + ); + db::query!( + "INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission, \ + private, archived) \ + VALUES ({user_id}, {installation}, {repository_id}, {name}, {permission}, {private}, {archived}) \ + ON CONFLICT (user_id, installation_id, repository_id) DO UPDATE SET full_name = EXCLUDED.full_name, \ + permission = EXCLUDED.permission, private = EXCLUDED.private, archived = EXCLUDED.archived, \ + seen_at = now()" + ) + .insert() + .await?; + } Ok(()) }) .await @@ -131,13 +150,12 @@ async fn role_in(organization_id: i64, user_id: i64) -> laravel::Result laravel::Result { +/// On a database error. +pub async fn from_webhook(kind: &str, event: &Value) -> laravel::Result { let action = event["action"].as_str().unwrap_or_default(); let Some(id) = event["installation"]["id"].as_i64().map(|i| i.to_string()) else { return Ok(Value::Null) }; match (kind, action) { @@ -189,48 +207,7 @@ pub async fn from_webhook(app: &GithubApp, kind: &str, event: &Value) -> laravel db::query!("DELETE FROM user_installations WHERE installation_id = {id}").delete().await?; Ok(json!({ "installation": "removed" })) } - ("installation_repositories", "added") => { - let row = db::query!( - "SELECT organization_id, set_up_by FROM github_installations \ - WHERE installation_id = {id} AND organization_id IS NOT NULL AND deleted_at IS NULL \ - AND suspended_at IS NULL" - ) - .select_one() - .await?; - let Some(row) = row else { return Ok(json!({ "projects": "not set up" })) }; - let organization_id: i64 = row.try_get("organization_id")?; - // The person who added them, if they're an admin there; else whoever set the installation up - let mut by = None; - if let Some(sender) = event["sender"]["id"].as_i64().map(|i| i.to_string()) - && let Some(user) = user_for_github(&sender).await? - && role_in(organization_id, user.id).await? == Some(Role::Admin) - { - by = Some(user); - } - if by.is_none() - && let Some(set_up_by) = row.try_get::>("set_up_by")? - && role_in(organization_id, set_up_by).await? == Some(Role::Admin) - { - by = User::find(set_up_by).await?; - } - let Some(by) = by else { return Ok(json!({ "projects": "no admin to link them" })) }; - let granted = event["repositories_added"] - .as_array() - .map(|l| { - l.iter() - .filter_map(|r| { - Some(github_app::Granted { - full_name: r["full_name"].as_str()?.to_string(), - id: r["id"].as_i64().map(|i| i.to_string()), - archived: false, - }) - }) - .collect::>() - }) - .unwrap_or_default(); - let made = add_repositories(app, organization_id, &by, &id, granted).await?; - Ok(json!({ "projects": made.linked.len(), "skipped": made.skipped.len() })) - } + // Repositories added on GitHub aren't made into projects: people pick the ones they want _ => Ok(Value::Null), } } @@ -278,8 +255,22 @@ pub async fn reachable(user_id: i64, installation_id: &str) -> laravel::Result laravel::Result { + let id = installation_id.to_string(); + let found: Option = db::query!( + "SELECT EXISTS (SELECT 1 FROM user_repositories WHERE user_id = {user_id} AND installation_id = {id})" + ) + .scalar() + .await?; + Ok(found.unwrap_or(false)) +} + +/// Set an installation up for `user`: find or make its organization and map the installation to it, with no projects +/// (people pick repositories next: [`picker`]). Quick, a few GitHub calls at most, and safe to run again. /// /// # Errors /// 404 when the person can't reach the installation, 409 when it's suspended, 403 when it's set up for an @@ -366,23 +357,12 @@ pub async fn set_up(app: &GithubApp, user: &User, installation_id: &str) -> lara } return Err(refused(409, format!("someone else has just set VisualCI up for {login}: reload the page"))); } - let granted = { - let token = github_app::installation_token(app, installation_id).await?; - github_app::installation_repositories(&token, REPOSITORY_LIMIT + 1).await? - }; - let truncated = granted.len() > REPOSITORY_LIMIT; - let granted = granted.into_iter().take(REPOSITORY_LIMIT).collect(); - let made = add_repositories(app, organization.id, user, installation_id, granted).await?; let outcome = SetUp { installation_id: id.clone(), account_login: login, organization: organization.slug, organization_created: created, note, - linked: made.linked, - already: made.already, - skipped: made.skipped, - truncated, }; let result = serde_json::to_string(&outcome).map_err(|e| laravel::Error::msg(e.to_string()))?; db::query!("UPDATE github_installations SET setup_result = {result}::jsonb WHERE installation_id = {id}") @@ -493,71 +473,290 @@ async fn create_for_account(user: &User, login: &str, name: &str) -> laravel::Re Err(laravel::Error::msg("no free organization slug")) } -/// What [`add_repositories`] did. -struct Added { - linked: Vec, - already: Vec, - skipped: Vec, +/// A page of the repository picker: the repositories `user_id` can reach through the organization's installations +/// (as of their last GitHub sign-in), matching `query`, with their permission and the organization's project already +/// linked to each (only `installation`'s, when given). Read from the database, with no GitHub call, so it pages hundreds at once. `can_add` is a +/// repository they maintain or administer, not archived and not linked yet. Also the organization's installations +/// they reach, and its newest pick still being made (for its progress). +/// +/// # Errors +/// On a database error. +pub async fn picker( + user_id: i64, + organization_id: i64, + installation: Option<&str>, + query: &str, + page: i64, +) -> laravel::Result { + let q = query.trim().to_lowercase(); + let only = installation.map(str::to_string); + let page = page.max(1); + let (limit, offset) = (PAGE_SIZE, (page - 1) * PAGE_SIZE); + let rows = db::query!( + "SELECT ur.installation_id, ur.repository_id, ur.full_name, ur.permission, ur.private, ur.archived, \ + (SELECT p.slug FROM projects p WHERE p.organization_id = {organization_id} AND p.forge = 'github' \ + AND (p.repository_id = ur.repository_id OR lower(p.repository_url) LIKE '%/' || lower(ur.full_name)) \ + ORDER BY p.id LIMIT 1) AS project \ + FROM user_repositories ur JOIN github_installations g ON g.installation_id = ur.installation_id \ + WHERE ur.user_id = {user_id} AND g.organization_id = {organization_id} AND g.deleted_at IS NULL \ + AND g.suspended_at IS NULL AND strpos(lower(ur.full_name), {q}) > 0 \ + AND ({only}::text IS NULL OR ur.installation_id = {only}) \ + ORDER BY lower(ur.full_name) LIMIT {limit} OFFSET {offset}" + ) + .select() + .await?; + let total: Option = db::query!( + "SELECT COUNT(*) FROM user_repositories ur JOIN github_installations g ON g.installation_id = ur.installation_id \ + WHERE ur.user_id = {user_id} AND g.organization_id = {organization_id} AND g.deleted_at IS NULL \ + AND g.suspended_at IS NULL AND strpos(lower(ur.full_name), {q}) > 0 \ + AND ({only}::text IS NULL OR ur.installation_id = {only})" + ) + .scalar() + .await?; + let repositories = rows + .iter() + .map(|r| { + let permission: String = r.try_get("permission")?; + let archived: bool = r.try_get("archived")?; + let project: Option = r.try_get("project")?; + let maintains = Permission::parse(&permission).is_some_and(|p| p >= Permission::Maintain); + Ok(json!({ + "installation_id": r.try_get::("installation_id")?, + "repository_id": r.try_get::("repository_id")?, + "full_name": r.try_get::("full_name")?, + "permission": permission, + "private": r.try_get::("private")?, + "archived": archived, + "can_add": maintains && !archived && project.is_none(), + "project": project, + })) + }) + .collect::>>()?; + let installations = db::query!( + "SELECT g.installation_id, g.account_login FROM github_installations g \ + JOIN user_installations ui ON ui.installation_id = g.installation_id AND ui.user_id = {user_id} \ + WHERE g.organization_id = {organization_id} AND g.deleted_at IS NULL ORDER BY lower(g.account_login)" + ) + .select() + .await? + .iter() + .map(|r| { + Ok(json!({ + "installation_id": r.try_get::("installation_id")?, + "account_login": r.try_get::("account_login")?, + })) + }) + .collect::>>()?; + let running: Option = db::query!( + "SELECT id FROM repository_imports WHERE organization_id = {organization_id} AND user_id = {user_id} \ + AND finished_at IS NULL ORDER BY id DESC LIMIT 1" + ) + .scalar() + .await?; + let running = match running { + Some(id) => import_state(organization_id, id).await?, + None => Value::Null, + }; + Ok(json!({ + "repositories": repositories, + "total": total.unwrap_or(0), + "page": page, + "per_page": PAGE_SIZE, + "query": query, + "installations": installations, + "running": running, + })) } -/// Make a project for each repository `by` can maintain, linked through `link_repository`'s checks; list the rest. -async fn add_repositories( - app: &GithubApp, - organization_id: i64, - by: &User, - installation_id: &str, - granted: Vec, -) -> laravel::Result { - let mut added = Added { linked: Vec::new(), already: Vec::new(), skipped: Vec::new() }; - let forge_user = github_id(by.id).await?; - for repo in granted { - let Some(repository) = Repository::parse(&repo.full_name).map(|r| r.with_id(repo.id.clone())) else { - continue; - }; - let path = repository.path.clone(); - if let Some(project) = linked_here(&repository, organization_id).await? { - added.already.push(Linked { project, repository: path }); +/// Make the chosen repositories (GitHub's IDs) into projects of the organization: checked against what the person +/// can reach through its installations and maintain, then made by a queued job ([`ImportRepositories`]), a few +/// GitHub calls each. Repositories already linked are left out. Returns the pick's ID, for its progress +/// ([`import_state`]). +/// +/// # Errors +/// 422 for none, more than [`IMPORT_LIMIT`], or one they can't add; database and queue errors. +pub async fn import(user: &User, organization_id: i64, repository_ids: &[String]) -> laravel::Result { + if repository_ids.is_empty() { + return Err(refused(422, "pick at least one repository")); + } + if repository_ids.len() > IMPORT_LIMIT { + return Err(refused(422, format!("pick at most {IMPORT_LIMIT} repositories at a time"))); + } + let user_id = user.id; + let mut requested = Vec::new(); + for repository_id in repository_ids { + let rid = repository_id.clone(); + let row = db::query!( + "SELECT ur.installation_id, ur.full_name, ur.permission, ur.archived, \ + EXISTS (SELECT 1 FROM projects p WHERE p.organization_id = {organization_id} AND p.forge = 'github' \ + AND (p.repository_id = ur.repository_id OR lower(p.repository_url) LIKE '%/' || lower(ur.full_name))) \ + AS linked \ + FROM user_repositories ur JOIN github_installations g ON g.installation_id = ur.installation_id \ + WHERE ur.user_id = {user_id} AND ur.repository_id = {rid} AND g.organization_id = {organization_id} \ + AND g.deleted_at IS NULL AND g.suspended_at IS NULL LIMIT 1" + ) + .select_one() + .await? + .ok_or_else(|| refused(422, format!("repository {repository_id} isn't one you can add here")))?; + let name: String = row.try_get("full_name")?; + if row.try_get::("linked")? { continue; } - if repo.archived { - added.skipped.push(Skipped { repository: path, reason: "it's archived".into() }); - continue; + let permission: String = row.try_get("permission")?; + if row.try_get::("archived")? + || !Permission::parse(&permission).is_some_and(|p| p >= Permission::Maintain) + { + return Err(refused( + 422, + format!("{name}: only an admin or maintainer can add it (you have {permission} access)"), + )); } - let Some(forge_user) = forge_user.as_deref() else { - added.skipped.push(Skipped { repository: path, reason: "sign in with GitHub first".into() }); - continue; + requested.push(json!({ + "installation_id": row.try_get::("installation_id")?, + "repository_id": repository_id, + "full_name": name, + })); + } + if requested.is_empty() { + return Err(refused(422, "those repositories are already projects here")); + } + let requested = Value::Array(requested).to_string(); + let id: Option = db::query!( + "INSERT INTO repository_imports (organization_id, user_id, requested) \ + VALUES ({organization_id}, {user_id}, {requested}::jsonb) RETURNING id" + ) + .scalar() + .await?; + let id = id.ok_or_else(|| laravel::Error::msg("no import row"))?; + ImportRepositories { import_id: id }.dispatch().await?; + Ok(id) +} + +/// A pick's progress: how many repositories it asked for, the projects made and the repositories not made (with +/// why) so far, and whether it's finished (or stopped on an error). `Value::Null` for another organization's. +/// +/// # Errors +/// On a database error. +pub async fn import_state(organization_id: i64, id: i64) -> laravel::Result { + let row = db::query!( + "SELECT id, jsonb_array_length(requested) AS total, linked::text AS linked, skipped::text AS skipped, \ + finished_at IS NOT NULL AS finished, error FROM repository_imports \ + WHERE id = {id} AND organization_id = {organization_id}" + ) + .select_one() + .await?; + let Some(row) = row else { return Ok(Value::Null) }; + let parse = |t: String| serde_json::from_str::(&t).unwrap_or_else(|_| json!([])); + Ok(json!({ + "id": row.try_get::("id")?, + "total": row.try_get::("total")?, + "linked": parse(row.try_get("linked")?), + "skipped": parse(row.try_get("skipped")?), + "finished": row.try_get::("finished")?, + "error": row.try_get::>("error")?, + })) +} + +/// Make a pick's repositories into projects ([`import`]), one by one, saving its progress after each. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct ImportRepositories { + pub import_id: i64, +} + +#[job] +impl ImportRepositories { + async fn handle(self) -> laravel::Result<()> { + let id = self.import_id; + let Some(row) = db::query!( + "SELECT organization_id, user_id, requested::text AS requested, finished_at IS NOT NULL AS finished \ + FROM repository_imports WHERE id = {id}" + ) + .select_one() + .await? + else { + return Ok(()); }; - let permission = github_app::permission(app, &path, installation_id, forge_user).await?; - if !permission.is_some_and(|p| p >= Permission::Maintain) { - let you = permission.map_or("not a collaborator".to_string(), |p| format!("{p:?}").to_lowercase()); - let owner = path.split('/').next().unwrap_or_default(); - added.skipped.push(Skipped { - repository: path.clone(), - reason: format!( - "only an admin or maintainer can add it (you're {you}): ask an admin of {owner} to set it up" - ), - }); - continue; + if row.try_get::("finished")? { + return Ok(()); } - let name = path.rsplit('/').next().unwrap_or(&path).to_string(); - let Some(project) = new_project(organization_id, &name).await? else { - added.skipped.push(Skipped { repository: path, reason: "no free project slug".into() }); - continue; + let organization_id: i64 = row.try_get("organization_id")?; + let requested: Vec = serde_json::from_str(&row.try_get::("requested")?) + .map_err(|e| laravel::Error::msg(e.to_string()))?; + let user = match row.try_get::>("user_id")? { + Some(u) => User::find(u).await?, + None => None, }; - let (project_id, slug) = (project.id, project.slug.clone()); - match super::link::link_repository(project, by, &repository.url, None, false).await { - Ok(_) => added.linked.push(Linked { project: slug, repository: path }), - Err(e) if e.status().is_client_error() => { - db::query!("DELETE FROM projects WHERE id = {project_id}").delete().await?; - added.skipped.push(Skipped { repository: path, reason: e.to_string() }); - } - Err(e) => { - db::query!("DELETE FROM projects WHERE id = {project_id}").delete().await?; - return Err(e); + let Some(user) = user else { + return finish(id, Some("the person who picked these repositories is gone")).await; + }; + let (mut linked, mut skipped) = (Vec::::new(), Vec::::new()); + for r in &requested { + let Some(name) = r["full_name"].as_str() else { continue }; + let Some(repository) = + Repository::parse(name).map(|repo| repo.with_id(r["repository_id"].as_str().map(str::to_string))) + else { + continue; + }; + match add_one(organization_id, &user, &repository).await { + Ok(Ok(l)) => linked.push(l), + Ok(Err(s)) => skipped.push(s), + Err(e) => { + save_progress(id, &linked, &skipped).await?; + tracing::warn!(import = id, error = %e, "repository import stopped"); + return finish(id, Some(&format!("{name}: {e}"))).await; + } } + save_progress(id, &linked, &skipped).await?; + } + finish(id, None).await + } +} + +async fn save_progress(id: i64, linked: &[Linked], skipped: &[Skipped]) -> laravel::Result<()> { + let linked = serde_json::to_string(linked).map_err(|e| laravel::Error::msg(e.to_string()))?; + let skipped = serde_json::to_string(skipped).map_err(|e| laravel::Error::msg(e.to_string()))?; + db::query!( + "UPDATE repository_imports SET linked = {linked}::jsonb, skipped = {skipped}::jsonb, updated_at = now() \ + WHERE id = {id}" + ) + .update() + .await?; + Ok(()) +} + +async fn finish(id: i64, error: Option<&str>) -> laravel::Result<()> { + let error = error.map(str::to_string); + db::query!( + "UPDATE repository_imports SET finished_at = now(), error = {error}, updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + Ok(()) +} + +/// Make one repository into a project of the organization, linked through `link_repository`'s checks (the person's +/// permission, the installation): `Ok(Ok)` with the project (or the one already linked), `Ok(Err)` with why not. +async fn add_one(organization_id: i64, by: &User, repository: &Repository) -> laravel::Result> { + let path = repository.path.clone(); + if let Some(project) = linked_here(repository, organization_id).await? { + return Ok(Ok(Linked { project, repository: path })); + } + let name = path.rsplit('/').next().unwrap_or(&path).to_string(); + let Some(project) = new_project(organization_id, &name).await? else { + return Ok(Err(Skipped { repository: path, reason: "no free project slug".into() })); + }; + let (project_id, slug) = (project.id, project.slug.clone()); + match super::link::link_repository(project, by, &repository.url, None, false).await { + Ok(_) => Ok(Ok(Linked { project: slug, repository: path })), + Err(e) if e.status().is_client_error() => { + db::query!("DELETE FROM projects WHERE id = {project_id}").delete().await?; + Ok(Err(Skipped { repository: path, reason: e.to_string() })) + } + Err(e) => { + db::query!("DELETE FROM projects WHERE id = {project_id}").delete().await?; + Err(e) } } - Ok(added) } /// The slug of a project of this organization already linked to the repository. diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index 71be8925..03034716 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -62,6 +62,24 @@ pub enum Permission { } impl Permission { + /// GitHub's name for it. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Read => "read", + Self::Triage => "triage", + Self::Write => "write", + Self::Maintain => "maintain", + Self::Admin => "admin", + } + } + + /// From GitHub's name for it ([`Permission::as_str`]). + #[must_use] + pub fn parse(name: &str) -> Option { + [Self::Read, Self::Triage, Self::Write, Self::Maintain, Self::Admin].into_iter().find(|p| p.as_str() == name) + } + /// The VisualCI role it gives: admin or maintain → admin, write → member (review and approve), triage or read → /// read. #[must_use] @@ -287,6 +305,19 @@ pub struct SignIn { pub repositories: Vec<(Repository, Permission)>, /// The GitHub App's installations this person can reach (none on GitLab). pub installations: Vec, + /// Each repository they can reach through each of those installations, for the repository picker. + pub reachable: Vec, +} + +/// A repository someone can reach through an installation of the GitHub App, and their permission on it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Reachable { + pub installation_id: String, + /// With GitHub's ID for it. + pub repository: Repository, + pub permission: Permission, + pub private: bool, + pub archived: bool, } /// An installation of the VisualCI GitHub App, and the account it's installed on. diff --git a/app/src/forge/webhooks.rs b/app/src/forge/webhooks.rs index a5fd3184..e0b0771b 100644 --- a/app/src/forge/webhooks.rs +++ b/app/src/forge/webhooks.rs @@ -277,9 +277,8 @@ pub async fn github( let (kind, delivery) = (header("x-github-event"), header("x-github-delivery")); let read = read_event(&kind, &event).map_err(|e| laravel::abort_with(400, e))?; let mut outcome = handle(&app, read).await?; - // Installations recorded, and repositories added to a set-up installation made into projects (after `handle` - // has attached the ones already linked) - let installations = super::installations::from_webhook(&app, &kind, &event).await?; + // Installations recorded (after `handle` has attached the projects already linked) + let installations = super::installations::from_webhook(&kind, &event).await?; if !installations.is_null() && let Some(map) = outcome.as_object_mut() { diff --git a/app/src/http/status.rs b/app/src/http/status.rs index f743e667..4344614e 100644 --- a/app/src/http/status.rs +++ b/app/src/http/status.rs @@ -54,7 +54,9 @@ async fn numbers() -> laravel::Result> { (SELECT COUNT(*) FROM jobs WHERE attempts >= 3 \ AND (payload LIKE '%forge.check%' OR payload LIKE '%forge.pr_comment%'))::BIGINT AS forge_posts_retrying, \ COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(synced_at)) FROM memberships \ - WHERE source = 'github' AND synced_at IS NOT NULL), 0)::BIGINT AS oldest_forge_sync_seconds" + WHERE source = 'github' AND synced_at IS NOT NULL), 0)::BIGINT AS oldest_forge_sync_seconds, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(updated_at)) FROM repository_imports \ + WHERE finished_at IS NULL), 0)::BIGINT AS stalled_repository_import_seconds" ) .select_one() .await? @@ -90,5 +92,8 @@ async fn numbers() -> laravel::Result> { // on a reconnection). `idle` until the first stream starts it. "live_streams_open": super::live::STREAMS.open(), "live_listener": crate::live::listener_state(), + // The longest an unfinished pick of repositories has gone without progress: its job saves after each repository + // (a few seconds), so past a few minutes the queue has stopped or the job died. + "stalled_repository_import_seconds": get("stalled_repository_import_seconds")?, }))) } diff --git a/app/src/models/organizations.rs b/app/src/models/organizations.rs index 9101b351..cf0cb8f3 100644 --- a/app/src/models/organizations.rs +++ b/app/src/models/organizations.rs @@ -29,8 +29,24 @@ pub struct Organization { /// Paths an organization's slug can't take. pub const RESERVED_SLUGS: &[&str] = &[ - "account", "api", "assets", "auth", "billing", "cli", "device", "docs", "g", "github", "mcp", "new", "settings", - "staff", "status", "visualci", "webhooks", + "account", + "api", + "assets", + "auth", + "billing", + "cli", + "device", + "docs", + "g", + "github", + "mcp", + "new", + "settings", + "repositories", + "staff", + "status", + "visualci", + "webhooks", ]; /// Lowercase letters, digits and dashes, at most 60, and not a reserved path. diff --git a/app/tests/golden/mcp/get_skill_lists_the_skills_and_returns_one/get_skill.json b/app/tests/golden/mcp/get_skill_lists_the_skills_and_returns_one/get_skill.json index 36e840e0..6047f174 100644 --- a/app/tests/golden/mcp/get_skill_lists_the_skills_and_returns_one/get_skill.json +++ b/app/tests/golden/mcp/get_skill_lists_the_skills_and_returns_one/get_skill.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"skills\":[{\"description\":\"Sets up VisualCI, visual regression and snapshot review for PDFs, screenshots, images, JSON, HTML and text: installs the GitHub App (which makes a project per repository) and the CLI, creates a CI token, sends the first build, and picks the visualci-* skill for the user's CI provider and test tools. Use when the user mentions VisualCI, wants visual regression testing, screenshot or PDF comparison, or snapshot changes that wait for review instead of failing CI. Not for a specific CI provider or test tool once VisualCI is set up: use that skill.\",\"name\":\"visualci\"},{\"description\":\"Sets up VisualCI in Bitbucket Pipelines (bitbucket-pipelines.yml): the token as a secured variable, installing the CLI, creating the build, uploading snapshots and finalizing, including parallel steps. Use when the user wants visual or snapshot review in Bitbucket Pipelines, or a project has bitbucket-pipelines.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-bitbucket\"},{\"description\":\"Sets up VisualCI in Buildkite pipelines: the token as a secret, installing the CLI, creating the build, uploading snapshots and finalizing, including parallel jobs. Use when the user wants visual or snapshot review in Buildkite, or a project has .buildkite/ and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-buildkite\"},{\"description\":\"Sets up VisualCI in CircleCI (.circleci/config.yml): the token in a context or project variable, installing the CLI, creating the build, uploading snapshots and finalizing, including parallelism. Use when the user wants visual or snapshot review in CircleCI, or a project has .circleci/config.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-circleci\"},{\"description\":\"Writes and edits visualci.yml: ignore rules scoped to snapshot globs (JSON paths and regular expressions for text, masked regions and rectangles for screenshots), thresholds, PDF rendering, the CI mode and what to upload. Use when the user wants to ignore volatile values such as timestamps or IDs, leave a part of a screenshot that differs on every run (a status bar, a tab bar's glass effect) out of the diff, change thresholds or the CI mode, or keep VisualCI settings in the repository. Not for per-snapshot ignores in a single test.\",\"name\":\"visualci-config\"},{\"description\":\"Sends Cypress screenshots to VisualCI: taking them with cy.screenshot, turning off failure screenshots, uploading cypress/screenshots with a platform per browser and a threshold, and reviewing changes. Use when a project uses Cypress (cypress.config, cy.screenshot) and wants visual review with VisualCI. Not for Playwright or Capybara.\",\"name\":\"visualci-cypress\"},{\"description\":\"Makes browser screenshots deterministic so VisualCI shows only real changes, covering seeded randomness, loaded and self-hosted fonts, reduced motion, frozen animations, GIFs and videos, a pinned clock and timezone, a hermetic network, and a fixed viewport, scrollbar and device pixel ratio. Gives recipes for Playwright, Cypress and Storybook. Use when screenshots differ between runs of the same commit (flaky diffs), or when setting up visual tests. Not for uploading screenshots or setting up the CI provider.\",\"name\":\"visualci-deterministic\"},{\"description\":\"Sets up VisualCI in GitHub Actions, including Blacksmith and Depot runners, with VisualCI's action (DocSpring/visualci/clients/github-action): the token as a secret, what to upload, and matrix and parallel jobs, or with the CLI directly. Use when the user wants visual or snapshot review in GitHub Actions, or a project has .github/workflows and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-github-actions\"},{\"description\":\"Sets up VisualCI in GitLab CI (.gitlab-ci.yml): the token as a masked variable, installing the CLI, creating the build, uploading snapshots and finalizing, and the CI modes for reviewing without a GitHub check. Use when the user wants visual or snapshot review in GitLab CI, or a project has .gitlab-ci.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-gitlab\"},{\"description\":\"Sends insta (Rust) snapshot files to VisualCI, so a changed snapshot waits for review instead of failing cargo test: accepting snapshots in CI and uploading the .snap files. Use when a Rust project uses insta (assert_snapshot!, snapshots/*.snap) with VisualCI. Not for other languages.\",\"name\":\"visualci-insta\"},{\"description\":\"Sets up VisualCI in a Jenkins pipeline (Jenkinsfile): the token as a credential, installing the CLI, creating the build, uploading snapshots and finalizing, including parallel stages. Use when the user wants visual or snapshot review in Jenkins, or a project has a Jenkinsfile and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-jenkins\"},{\"description\":\"Sends Jest snapshot files to VisualCI, so a changed snapshot waits for review instead of failing the build: running Jest with -u in CI and uploading the .snap files, one snapshot per test. Use when a project uses Jest snapshots (toMatchSnapshot, __snapshots__/*.snap) with VisualCI. Not for Vitest or screenshots.\",\"name\":\"visualci-jest\"},{\"description\":\"Sets up VisualCI for a Laravel Rust app's tests with the snapshot-testing-laravel crate: browser screenshots and HTML, JSON and text snapshots of responses, run under `visualci test -- cargo test`, with names, platforms, ignore rules and thresholds as VisualCI sees them. Use when a Laravel Rust project uses snapshot-testing-laravel, or wants screenshot or snapshot tests with VisualCI. Not for other Rust projects (see visualci-insta) or other frameworks.\",\"name\":\"visualci-laravel-rust\"},{\"description\":\"Runs tests on a laptop against VisualCI's baselines: local environments, each test failing once with every snapshot it changed, and approving local changes so the branch's baseline matches. Use when the user runs visual or snapshot tests locally with VisualCI, sees VisualCI failures in a local run, or wants to approve local results. Not for CI setup.\",\"name\":\"visualci-local-runs\"},{\"description\":\"Sends mobile app screenshots to VisualCI from iOS (XCUITest, swift-snapshot-testing), Android (Espresso, Paparazzi, Roborazzi), Maestro, Detox (React Native) and Flutter golden tests, with a platform tag per OS version and device. Use when an iOS, Android, React Native or Flutter project wants visual review with VisualCI. Not for browser screenshots (Playwright, Cypress) or for setting up the CI provider.\",\"name\":\"visualci-mobile\"},{\"description\":\"Compares PDFs a test suite generates (Ruby, Node, Python or anything else) with VisualCI, page by page in one pinned renderer: uploading them, fingerprints, checking fingerprints are stable, and reading page, text and moved-line changes. Use when a project generates PDFs (invoices, reports, statements, labels) and the user wants them checked for visual changes. Not for screenshots.\",\"name\":\"visualci-pdfs\"},{\"description\":\"Sends Playwright screenshots to VisualCI instead of toHaveScreenshot baselines in the repository: saving screenshots in tests, uploading them with a platform per browser project and a threshold, and reviewing changes. Use when a project uses Playwright (playwright.config, @playwright/test) and wants visual review with VisualCI. Not for Cypress or Capybara.\",\"name\":\"visualci-playwright\"},{\"description\":\"Reviews a VisualCI build over the MCP server: finds what changed, reads each snapshot's diff images, text diff or JSON changes, checks them against the code and the task, then approves intended changes or fixes the code and pushes. Use when a VisualCI check is pending or failing on a pull request, the user asks what changed visually, or asks to approve or reject snapshots. Not for setting VisualCI up in CI.\",\"name\":\"visualci-review\"},{\"description\":\"Adds VisualCI to RSpec feature and system specs with the visualci gem: screenshots from Capybara, PDFs, JSON, HTML and text matchers, per-snapshot ignore rules, local runs that fail each example once, and sharded CI builds. Use when a Ruby project wants visual review of Capybara screenshots or generated documents in RSpec. Not for rspec-snapshot files: see visualci-rspec-snapshot.\",\"name\":\"visualci-rspec-screenshots\"},{\"description\":\"Sends rspec-snapshot files to VisualCI, so a changed snapshot waits for review instead of failing RSpec: updating snapshots in CI and uploading the .snap files. Use when a Ruby project uses rspec-snapshot (match_snapshot) with VisualCI. Not for RSpec screenshots or PDFs: see visualci-rspec-screenshots and visualci-pdfs.\",\"name\":\"visualci-rspec-snapshot\"},{\"description\":\"Sets up VisualCI in Semaphore (.semaphore/semaphore.yml): the token as a secret, installing the CLI, creating the build, uploading snapshots and finalizing, including parallelism. Use when the user wants visual or snapshot review in Semaphore, or a project has .semaphore/ and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-semaphore\"},{\"description\":\"Sends syrupy (pytest) snapshot files to VisualCI, so a changed snapshot waits for review instead of failing pytest: updating snapshots in CI and uploading the .ambr files, one snapshot per test. Use when a Python project uses syrupy (snapshot fixture, __snapshots__/*.ambr) with VisualCI. Not for other languages.\",\"name\":\"visualci-syrupy\"},{\"description\":\"Sets up VisualCI in TeamCity: the token as a password parameter, the commit, branch and pull request from TeamCity's parameters, installing the CLI, creating the build, uploading snapshots and finalizing. Use when the user wants visual or snapshot review in TeamCity, or a project has a .teamcity/ directory and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-teamcity\"},{\"description\":\"Sets up VisualCI in Travis CI (.travis.yml): the token as a repository variable, installing the CLI, creating the build, uploading snapshots and finalizing. Use when the user wants visual or snapshot review in Travis CI, or a project has .travis.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-travis\"},{\"description\":\"Sends Vitest snapshot files to VisualCI, so a changed snapshot waits for review instead of failing the build: running Vitest with -u in CI and uploading the .snap files, one snapshot per test. Use when a project uses Vitest snapshots (toMatchSnapshot, __snapshots__/*.snap) with VisualCI. Not for Jest or screenshots.\",\"name\":\"visualci-vitest\"}]}", + "text": "{\"skills\":[{\"description\":\"Sets up VisualCI, visual regression and snapshot review for PDFs, screenshots, images, JSON, HTML and text: installs the GitHub App (the person picks which repositories become projects) and the CLI, creates a CI token, sends the first build, and picks the visualci-* skill for the user's CI provider and test tools. Use when the user mentions VisualCI, wants visual regression testing, screenshot or PDF comparison, or snapshot changes that wait for review instead of failing CI. Not for a specific CI provider or test tool once VisualCI is set up: use that skill.\",\"name\":\"visualci\"},{\"description\":\"Sets up VisualCI in Bitbucket Pipelines (bitbucket-pipelines.yml): the token as a secured variable, installing the CLI, creating the build, uploading snapshots and finalizing, including parallel steps. Use when the user wants visual or snapshot review in Bitbucket Pipelines, or a project has bitbucket-pipelines.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-bitbucket\"},{\"description\":\"Sets up VisualCI in Buildkite pipelines: the token as a secret, installing the CLI, creating the build, uploading snapshots and finalizing, including parallel jobs. Use when the user wants visual or snapshot review in Buildkite, or a project has .buildkite/ and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-buildkite\"},{\"description\":\"Sets up VisualCI in CircleCI (.circleci/config.yml): the token in a context or project variable, installing the CLI, creating the build, uploading snapshots and finalizing, including parallelism. Use when the user wants visual or snapshot review in CircleCI, or a project has .circleci/config.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-circleci\"},{\"description\":\"Writes and edits visualci.yml: ignore rules scoped to snapshot globs (JSON paths and regular expressions for text, masked regions and rectangles for screenshots), thresholds, PDF rendering, the CI mode and what to upload. Use when the user wants to ignore volatile values such as timestamps or IDs, leave a part of a screenshot that differs on every run (a status bar, a tab bar's glass effect) out of the diff, change thresholds or the CI mode, or keep VisualCI settings in the repository. Not for per-snapshot ignores in a single test.\",\"name\":\"visualci-config\"},{\"description\":\"Sends Cypress screenshots to VisualCI: taking them with cy.screenshot, turning off failure screenshots, uploading cypress/screenshots with a platform per browser and a threshold, and reviewing changes. Use when a project uses Cypress (cypress.config, cy.screenshot) and wants visual review with VisualCI. Not for Playwright or Capybara.\",\"name\":\"visualci-cypress\"},{\"description\":\"Makes browser screenshots deterministic so VisualCI shows only real changes, covering seeded randomness, loaded and self-hosted fonts, reduced motion, frozen animations, GIFs and videos, a pinned clock and timezone, a hermetic network, and a fixed viewport, scrollbar and device pixel ratio. Gives recipes for Playwright, Cypress and Storybook. Use when screenshots differ between runs of the same commit (flaky diffs), or when setting up visual tests. Not for uploading screenshots or setting up the CI provider.\",\"name\":\"visualci-deterministic\"},{\"description\":\"Sets up VisualCI in GitHub Actions, including Blacksmith and Depot runners, with VisualCI's action (DocSpring/visualci/clients/github-action): the token as a secret, what to upload, and matrix and parallel jobs, or with the CLI directly. Use when the user wants visual or snapshot review in GitHub Actions, or a project has .github/workflows and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-github-actions\"},{\"description\":\"Sets up VisualCI in GitLab CI (.gitlab-ci.yml): the token as a masked variable, installing the CLI, creating the build, uploading snapshots and finalizing, and the CI modes for reviewing without a GitHub check. Use when the user wants visual or snapshot review in GitLab CI, or a project has .gitlab-ci.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-gitlab\"},{\"description\":\"Sends insta (Rust) snapshot files to VisualCI, so a changed snapshot waits for review instead of failing cargo test: accepting snapshots in CI and uploading the .snap files. Use when a Rust project uses insta (assert_snapshot!, snapshots/*.snap) with VisualCI. Not for other languages.\",\"name\":\"visualci-insta\"},{\"description\":\"Sets up VisualCI in a Jenkins pipeline (Jenkinsfile): the token as a credential, installing the CLI, creating the build, uploading snapshots and finalizing, including parallel stages. Use when the user wants visual or snapshot review in Jenkins, or a project has a Jenkinsfile and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-jenkins\"},{\"description\":\"Sends Jest snapshot files to VisualCI, so a changed snapshot waits for review instead of failing the build: running Jest with -u in CI and uploading the .snap files, one snapshot per test. Use when a project uses Jest snapshots (toMatchSnapshot, __snapshots__/*.snap) with VisualCI. Not for Vitest or screenshots.\",\"name\":\"visualci-jest\"},{\"description\":\"Sets up VisualCI for a Laravel Rust app's tests with the snapshot-testing-laravel crate: browser screenshots and HTML, JSON and text snapshots of responses, run under `visualci test -- cargo test`, with names, platforms, ignore rules and thresholds as VisualCI sees them. Use when a Laravel Rust project uses snapshot-testing-laravel, or wants screenshot or snapshot tests with VisualCI. Not for other Rust projects (see visualci-insta) or other frameworks.\",\"name\":\"visualci-laravel-rust\"},{\"description\":\"Runs tests on a laptop against VisualCI's baselines: local environments, each test failing once with every snapshot it changed, and approving local changes so the branch's baseline matches. Use when the user runs visual or snapshot tests locally with VisualCI, sees VisualCI failures in a local run, or wants to approve local results. Not for CI setup.\",\"name\":\"visualci-local-runs\"},{\"description\":\"Sends mobile app screenshots to VisualCI from iOS (XCUITest, swift-snapshot-testing), Android (Espresso, Paparazzi, Roborazzi), Maestro, Detox (React Native) and Flutter golden tests, with a platform tag per OS version and device. Use when an iOS, Android, React Native or Flutter project wants visual review with VisualCI. Not for browser screenshots (Playwright, Cypress) or for setting up the CI provider.\",\"name\":\"visualci-mobile\"},{\"description\":\"Compares PDFs a test suite generates (Ruby, Node, Python or anything else) with VisualCI, page by page in one pinned renderer: uploading them, fingerprints, checking fingerprints are stable, and reading page, text and moved-line changes. Use when a project generates PDFs (invoices, reports, statements, labels) and the user wants them checked for visual changes. Not for screenshots.\",\"name\":\"visualci-pdfs\"},{\"description\":\"Sends Playwright screenshots to VisualCI instead of toHaveScreenshot baselines in the repository: saving screenshots in tests, uploading them with a platform per browser project and a threshold, and reviewing changes. Use when a project uses Playwright (playwright.config, @playwright/test) and wants visual review with VisualCI. Not for Cypress or Capybara.\",\"name\":\"visualci-playwright\"},{\"description\":\"Reviews a VisualCI build over the MCP server: finds what changed, reads each snapshot's diff images, text diff or JSON changes, checks them against the code and the task, then approves intended changes or fixes the code and pushes. Use when a VisualCI check is pending or failing on a pull request, the user asks what changed visually, or asks to approve or reject snapshots. Not for setting VisualCI up in CI.\",\"name\":\"visualci-review\"},{\"description\":\"Adds VisualCI to RSpec feature and system specs with the visualci gem: screenshots from Capybara, PDFs, JSON, HTML and text matchers, per-snapshot ignore rules, local runs that fail each example once, and sharded CI builds. Use when a Ruby project wants visual review of Capybara screenshots or generated documents in RSpec. Not for rspec-snapshot files: see visualci-rspec-snapshot.\",\"name\":\"visualci-rspec-screenshots\"},{\"description\":\"Sends rspec-snapshot files to VisualCI, so a changed snapshot waits for review instead of failing RSpec: updating snapshots in CI and uploading the .snap files. Use when a Ruby project uses rspec-snapshot (match_snapshot) with VisualCI. Not for RSpec screenshots or PDFs: see visualci-rspec-screenshots and visualci-pdfs.\",\"name\":\"visualci-rspec-snapshot\"},{\"description\":\"Sets up VisualCI in Semaphore (.semaphore/semaphore.yml): the token as a secret, installing the CLI, creating the build, uploading snapshots and finalizing, including parallelism. Use when the user wants visual or snapshot review in Semaphore, or a project has .semaphore/ and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-semaphore\"},{\"description\":\"Sends syrupy (pytest) snapshot files to VisualCI, so a changed snapshot waits for review instead of failing pytest: updating snapshots in CI and uploading the .ambr files, one snapshot per test. Use when a Python project uses syrupy (snapshot fixture, __snapshots__/*.ambr) with VisualCI. Not for other languages.\",\"name\":\"visualci-syrupy\"},{\"description\":\"Sets up VisualCI in TeamCity: the token as a password parameter, the commit, branch and pull request from TeamCity's parameters, installing the CLI, creating the build, uploading snapshots and finalizing. Use when the user wants visual or snapshot review in TeamCity, or a project has a .teamcity/ directory and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-teamcity\"},{\"description\":\"Sets up VisualCI in Travis CI (.travis.yml): the token as a repository variable, installing the CLI, creating the build, uploading snapshots and finalizing. Use when the user wants visual or snapshot review in Travis CI, or a project has .travis.yml and VisualCI. Not for other CI providers, or for writing the tests themselves.\",\"name\":\"visualci-travis\"},{\"description\":\"Sends Vitest snapshot files to VisualCI, so a changed snapshot waits for review instead of failing the build: running Vitest with -u in CI and uploading the .snap files, one snapshot per test. Use when a project uses Vitest snapshots (toMatchSnapshot, __snapshots__/*.snap) with VisualCI. Not for Jest or screenshots.\",\"name\":\"visualci-vitest\"}]}", "type": "text" } ], @@ -11,7 +11,7 @@ "structuredContent": { "skills": [ { - "description": "Sets up VisualCI, visual regression and snapshot review for PDFs, screenshots, images, JSON, HTML and text: installs the GitHub App (which makes a project per repository) and the CLI, creates a CI token, sends the first build, and picks the visualci-* skill for the user's CI provider and test tools. Use when the user mentions VisualCI, wants visual regression testing, screenshot or PDF comparison, or snapshot changes that wait for review instead of failing CI. Not for a specific CI provider or test tool once VisualCI is set up: use that skill.", + "description": "Sets up VisualCI, visual regression and snapshot review for PDFs, screenshots, images, JSON, HTML and text: installs the GitHub App (the person picks which repositories become projects) and the CLI, creates a CI token, sends the first build, and picks the visualci-* skill for the user's CI provider and test tools. Use when the user mentions VisualCI, wants visual regression testing, screenshot or PDF comparison, or snapshot changes that wait for review instead of failing CI. Not for a specific CI provider or test tool once VisualCI is set up: use that skill.", "name": "visualci" }, { diff --git a/app/tests/installations.rs b/app/tests/installations.rs index d911de4d..20d74c43 100644 --- a/app/tests/installations.rs +++ b/app/tests/installations.rs @@ -1,8 +1,9 @@ -//! Setting up the GitHub App (sc-9027): installations recorded from sign-ins and webhooks, the Setup URL, and an -//! installation mapped to an organization with a project for each repository the person can maintain. +//! Setting up the GitHub App (sc-9027): installations recorded from sign-ins and webhooks, the Setup URL, an +//! installation mapped to an organization with no projects, and the repository picker, whose queued job makes the +//! repositories people choose into projects. An organization with 300 repositories sets up in a few GitHub calls. -use app::forge::Installation; use app::forge::installations::{self, remember}; +use app::forge::{Installation, Permission, Reachable, Repository}; use app::models::{Organization, User}; use hmac::{Hmac, Mac}; use laravel::db; @@ -112,6 +113,35 @@ fn granted(owner: &str) -> client::HttpFake { .with(&format!("api.github.com/repos/{owner}/web"), json!({ "id": 42, "private": true, "license": null })) } +/// What a sign-in lists: `repositories` (`owner/name`, GitHub ID, permission) reachable through installation 7. +fn reach(repositories: &[(&str, &str, Permission)]) -> Vec { + repositories + .iter() + .map(|(name, id, permission)| Reachable { + installation_id: "7".into(), + repository: Repository::parse(name).expect("a repository").with_id(Some((*id).to_string())), + permission: *permission, + private: true, + archived: false, + }) + .collect() +} + +fn ui( + app: &Application, + user: &User, + method: &str, + path: &str, + body: Option, +) -> laravel::testing::TestRequest { + let r = if method == "POST" { app.post(path) } else { app.get(path) }; + let r = r.acting_as(user).header("sec-fetch-site", "same-origin").header("accept", "application/json"); + match body { + Some(b) => r.json(b), + None => r, + } +} + async fn projects(org_id: i64) -> laravel::Result, Option)>> { let rows = db::query!( "SELECT slug, repository_url, forge_installation FROM projects WHERE organization_id = {org_id} ORDER BY slug" @@ -124,41 +154,61 @@ async fn projects(org_id: i64) -> laravel::Result, O } #[laravel::test(app = github)] -async fn installed_on_her_own_account_it_fills_her_organization(_app: Application) -> laravel::Result<()> { +async fn installed_on_her_own_account_it_maps_to_her_organization_and_she_picks( + app: Application, +) -> laravel::Result<()> { let (ada, org) = ada().await?; assert!(projects(org.id).await?.is_empty(), "signing up makes no Default project"); - remember(ada.id, &[installation("7", "1001", "ada", "User")]).await?; + let listed = reach(&[("ada/web", "42", Permission::Maintain), ("ada/docs", "43", Permission::Write)]); + remember(ada.id, &[installation("7", "1001", "ada", "User")], &listed).await?; let _github = granted("ada"); let done = installations::set_up(&github_app(), &ada, "7").await?; assert_eq!(done.organization, org.slug); assert!(!done.organization_created); - assert_eq!(done.linked.len(), 1, "{done:?}"); - assert_eq!((done.linked[0].project.as_str(), done.linked[0].repository.as_str()), ("web", "ada/web")); - assert_eq!(done.skipped.len(), 1); - assert_eq!(done.skipped[0].repository, "ada/docs"); - assert!(done.skipped[0].reason.contains("you're write"), "{}", done.skipped[0].reason); - assert_eq!( - projects(org.id).await?, - vec![("web".into(), Some("https://github.com/ada/web".into()), Some("7".into()))] - ); + assert!(projects(org.id).await?.is_empty(), "setting up makes no projects: she picks them"); let state = app::auth::setup::state(org.id, Some(ada.pid)).await?; assert_eq!(state["next"], "add_to_ci", "{state}"); assert_eq!(state["installations"][0]["organization"], org.slug.as_str()); - assert_eq!(state["github"][0]["result"]["skipped"][0]["repository"], "ada/docs"); - // Again: nothing new, the project already there - let again = installations::set_up(&github_app(), &ada, "7").await?; - assert!(again.linked.is_empty()); - assert_eq!(again.already.len(), 1); - assert_eq!(projects(org.id).await?.len(), 1); + // The picker: both repositories, only the one she maintains can be added + let path = format!("/api/ui/orgs/{}/repositories", org.slug); + let page = ui(&app, &ada, "GET", &path, None).await; + page.assert_ok().assert_json_path("total", 2); + let page = page.json().clone(); + assert_eq!(page["repositories"][0]["full_name"], "ada/docs"); + assert_eq!(page["repositories"][0]["can_add"], false); + assert_eq!(page["repositories"][1]["full_name"], "ada/web"); + assert_eq!(page["repositories"][1]["can_add"], true); + ui(&app, &ada, "POST", &path, Some(json!({ "repository_ids": ["43"] }))) + .await + .assert_status(422) + .assert_see("you have write access"); + + // Picking web: the job (run at once in tests) makes it a project + let pick = ui(&app, &ada, "POST", &path, Some(json!({ "repository_ids": ["42"] }))).await; + pick.assert_ok(); + let id = pick.json()["id"].as_i64().expect("the pick's id"); + let progress = ui(&app, &ada, "GET", &format!("/api/ui/orgs/{}/repository-imports/{id}", org.slug), None).await; + progress.assert_ok().assert_json_path("finished", true).assert_json_path("linked.0.project", "web"); + assert_eq!( + projects(org.id).await?, + vec![("web".into(), Some("https://github.com/ada/web".into()), Some("7".into()))] + ); + let page = ui(&app, &ada, "GET", &path, None).await.json().clone(); + assert_eq!(page["repositories"][1]["project"], "web", "marked as already a project"); + assert_eq!(page["repositories"][1]["can_add"], false); + ui(&app, &ada, "POST", &path, Some(json!({ "repository_ids": ["42"] }))) + .await + .assert_status(422) + .assert_see("already projects"); Ok(()) } #[laravel::test(app = github)] async fn installed_on_a_github_organization_it_makes_one_named_after_it(_app: Application) -> laravel::Result<()> { let (ada, _) = ada().await?; - remember(ada.id, &[installation("7", "5005", "Acme", "Organization")]).await?; + remember(ada.id, &[installation("7", "5005", "Acme", "Organization")], &[]).await?; let _github = granted("Acme"); let done = installations::set_up(&github_app(), &ada, "7").await?; @@ -173,7 +223,7 @@ async fn installed_on_a_github_organization_it_makes_one_named_after_it(_app: Ap .scalar() .await?; assert_eq!(role.as_deref(), Some("admin")); - assert_eq!(projects(org.id).await?.len(), 1); + assert!(projects(org.id).await?.is_empty(), "no projects until she picks them"); Ok(()) } @@ -181,7 +231,7 @@ async fn installed_on_a_github_organization_it_makes_one_named_after_it(_app: Ap async fn a_taken_slug_becomes_login_github_with_a_note(_app: Application) -> laravel::Result<()> { app::testing::fixtures::organization("acme").await?; let (ada, _) = ada().await?; - remember(ada.id, &[installation("7", "5005", "acme", "Organization")]).await?; + remember(ada.id, &[installation("7", "5005", "acme", "Organization")], &[]).await?; let _github = granted("acme"); let done = installations::set_up(&github_app(), &ada, "7").await?; assert_eq!(done.organization, "acme-github"); @@ -192,7 +242,7 @@ async fn a_taken_slug_becomes_login_github_with_a_note(_app: Application) -> lar #[laravel::test(app = github)] async fn a_member_who_is_not_an_owner_cannot_claim_a_github_organization(_app: Application) -> laravel::Result<()> { let (ada, _) = ada().await?; - remember(ada.id, &[installation("7", "5005", "acme", "Organization")]).await?; + remember(ada.id, &[installation("7", "5005", "acme", "Organization")], &[]).await?; let _github = client::fake() .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) .with("api.github.com/user/1001", json!({ "id": 1001, "login": "ada" })) @@ -215,7 +265,7 @@ async fn a_member_who_is_not_an_owner_cannot_claim_a_github_organization(_app: A #[laravel::test(app = github)] async fn nobody_claims_another_persons_account(_app: Application) -> laravel::Result<()> { let (ada, _) = ada().await?; - remember(ada.id, &[installation("7", "9009", "torvalds", "User")]).await?; + remember(ada.id, &[installation("7", "9009", "torvalds", "User")], &[]).await?; let err = installations::set_up(&github_app(), &ada, "7").await.expect_err("his account"); assert_eq!(err.status().as_u16(), 403); assert!(Organization::query().filter(Organization::slug.eq("torvalds")).first().await?.is_none()); @@ -225,7 +275,7 @@ async fn nobody_claims_another_persons_account(_app: Application) -> laravel::Re #[laravel::test(app = github)] async fn someone_else_cannot_set_up_an_installation_they_cannot_reach(_app: Application) -> laravel::Result<()> { let (ada, _) = ada().await?; - remember(ada.id, &[installation("7", "5005", "acme", "Organization")]).await?; + remember(ada.id, &[installation("7", "5005", "acme", "Organization")], &[]).await?; let bob = create!(User { pid: laravel::str::uuid7(), name: "Bob", email: "bob@example.com", staff: false }).await?; let err = installations::set_up(&github_app(), &bob, "7").await.expect_err("not his"); assert_eq!(err.status().as_u16(), 404); @@ -247,7 +297,15 @@ async fn the_setup_url_signs_in_refreshes_once_and_lands_on_the_organization(app let r = app.get("/github/setup?installation_id=7&refreshed=1").acting_as(&ada).await; r.assert_ok().assert_see("isn't yours"); - remember(ada.id, &[installation("7", "1001", "ada", "User")]).await?; + // Reachable but with no repositories listed (only the `installation` webhook said so): one more sign-in + remember(ada.id, &[installation("7", "1001", "ada", "User")], &[]).await?; + let r = app.get("/github/setup?installation_id=7&state=abc123").acting_as(&ada).await; + r.assert_status(302).assert_header( + "location", + "/auth/github?return_to=%2Fgithub%2Fsetup%3Finstallation_id%3D7%26state%3Dabc123%26refreshed%3D1", + ); + remember(ada.id, &[installation("7", "1001", "ada", "User")], &reach(&[("ada/web", "42", Permission::Admin)])) + .await?; let _github = granted("ada"); // Without the state this browser's install sent (a link from another site): nothing set up, the offer instead let r = app.get("/github/setup?installation_id=7&state=forged").acting_as(&ada).await; @@ -265,7 +323,8 @@ async fn the_setup_url_signs_in_refreshes_once_and_lands_on_the_organization(app .acting_as(&ada) .with_cookies_from(&install) .await; - r.assert_status(302).assert_header("location", &format!("/{}?setup=add_to_ci&installation=7", org.slug)); + r.assert_status(302).assert_header("location", &format!("/{}/repositories?installation=7", org.slug)); + assert!(projects(org.id).await?.is_empty(), "the picker comes next: no projects made"); // No installation ID: an owner still has to approve it app.get("/github/setup?setup_action=request").acting_as(&ada).await.assert_ok().assert_see("Waiting for GitHub"); Ok(()) @@ -274,7 +333,7 @@ async fn the_setup_url_signs_in_refreshes_once_and_lands_on_the_organization(app #[laravel::test(app = github)] async fn the_checklist_offer_sets_it_up_over_the_api(app: Application) -> laravel::Result<()> { let (ada, org) = ada().await?; - remember(ada.id, &[installation("7", "1001", "ada", "User")]).await?; + remember(ada.id, &[installation("7", "1001", "ada", "User")], &[]).await?; let state = app::auth::setup::state(org.id, Some(ada.pid)).await?; assert_eq!(state["installations"][0]["installation_id"], "7"); assert_eq!(state["installations"][0]["organization"], serde_json::Value::Null, "an offer: not set up yet"); @@ -287,12 +346,12 @@ async fn the_checklist_offer_sets_it_up_over_the_api(app: Application) -> larave .await .assert_ok() .assert_json_path("organization", org.slug.as_str()) - .assert_json_path("landing", format!("/{}?setup=add_to_ci&installation=7", org.slug).as_str()); + .assert_json_path("landing", format!("/{}/repositories?installation=7", org.slug).as_str()); Ok(()) } #[laravel::test(app = github)] -async fn webhooks_record_installations_and_add_repositories(app: Application) -> laravel::Result<()> { +async fn webhooks_record_installations_and_never_make_projects(app: Application) -> laravel::Result<()> { let (ada, org) = ada().await?; let _github = granted("ada"); let account = json!({ "id": 1001, "login": "ada", "type": "User" }); @@ -315,7 +374,7 @@ async fn webhooks_record_installations_and_add_repositories(app: Application) -> let id = org.id; db::query!("UPDATE github_installations SET organization_id = {id} WHERE installation_id = '7'").update().await?; deliver(&app, "installation_repositories", added).await.assert_ok(); - assert_eq!(projects(org.id).await?.len(), 1, "added to a set-up installation: a project"); + assert!(projects(org.id).await?.is_empty(), "added to a set-up installation: still people pick"); deliver(&app, "installation", json!({ "action": "suspend", "installation": { "id": 7, "account": account } })) .await @@ -340,3 +399,230 @@ fn project_slugs_come_from_repository_names() { assert_eq!(installations::project_slug("My.Repo_2"), "my-repo-2"); assert_eq!(installations::project_slug("billing"), "billing-project"); } + +/// GitHub for installation `id` on Acme ("all repositories"), where Ada maintains `acme/web` (42) and `acme/app` (44). +fn acme_all(id: &str) -> client::HttpFake { + let number: i64 = id.parse().expect("a numeric installation ID"); + let mut fake = client::fake() + .with(&format!("api.github.com/app/installations/{id}/access_tokens"), json!({ "token": "t" })) + .with(&format!("api.github.com/app/installations/{id}"), json!({ "id": number, "repository_selection": "all" })) + .with("api.github.com/orgs/acme", json!({ "login": "acme", "name": "Acme Inc" })) + .with("api.github.com/orgs/acme/memberships/ada", json!({ "state": "active", "role": "admin" })) + .with("api.github.com/user/1001", json!({ "id": 1001, "login": "ada" })); + for (name, repo_id) in [("web", 42), ("app", 44)] { + fake = fake + .with(&format!("api.github.com/repos/acme/{name}/installation"), json!({ "id": number })) + .with(&format!("api.github.com/repos/acme/{name}/collaborators/ada"), client::response().status(204)) + .with( + &format!("api.github.com/repos/acme/{name}/collaborators/ada/permission"), + json!({ "role_name": "admin" }), + ) + .with(&format!("api.github.com/repositories/{repo_id}"), json!({ "full_name": format!("acme/{name}") })) + .with( + &format!("api.github.com/repos/acme/{name}"), + json!({ "id": repo_id, "private": true, "license": null }), + ); + } + fake +} + +/// Acme's 300 repositories as Ada's sign-in lists them through installation 7: `acme/repo-001`… plus web and app. +fn three_hundred() -> Vec { + let mut names: Vec<(String, String)> = + (1..=298).map(|n| (format!("acme/repo-{n:03}"), (1000 + n).to_string())).collect(); + names.push(("acme/web".into(), "42".into())); + names.push(("acme/app".into(), "44".into())); + names + .into_iter() + .map(|(name, id)| Reachable { + installation_id: "7".into(), + repository: Repository::parse(&name).expect("a repository").with_id(Some(id)), + permission: Permission::Admin, + private: true, + archived: false, + }) + .collect() +} + +/// Nathan's case, at scale: an organization with 300 repositories, installed on all of them. Setting it up takes a few +/// GitHub calls and makes no projects; the picker pages and searches them with none; picking two makes exactly two. +#[laravel::test(app = github)] +async fn three_hundred_repositories_set_up_in_a_few_calls_and_two_picked_make_two( + app: Application, +) -> laravel::Result<()> { + let (ada, _) = ada().await?; + remember(ada.id, &[installation("7", "5005", "acme", "Organization")], &three_hundred()).await?; + let github = acme_all("7"); + + let started = std::time::Instant::now(); + let done = installations::set_up(&github_app(), &ada, "7").await?; + assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + assert_eq!(done.organization, "acme"); + let org = Organization::query().filter(Organization::slug.eq("acme")).first().await?.expect("acme"); + assert!(projects(org.id).await?.is_empty(), "no projects made by setting it up"); + let calls = github.sent().len(); + assert!(calls <= 5, "setting up made {calls} GitHub calls"); + + // Paged and searched from the database: no GitHub call + let path = "/api/ui/orgs/acme/repositories"; + let first = ui(&app, &ada, "GET", path, None).await; + first.assert_ok().assert_json_path("total", 300).assert_json_path("per_page", 50); + assert_eq!(first.json()["repositories"].as_array().map(Vec::len), Some(50)); + let last = ui(&app, &ada, "GET", &format!("{path}?page=6"), None).await.json().clone(); + assert_eq!(last["repositories"].as_array().map(Vec::len), Some(50)); + let beyond = ui(&app, &ada, "GET", &format!("{path}?page=7"), None).await.json().clone(); + assert_eq!(beyond["repositories"].as_array().map(Vec::len), Some(0)); + let found = ui(&app, &ada, "GET", &format!("{path}?q=REPO-29"), None).await.json().clone(); + assert_eq!(found["total"], 9, "repo-290 to repo-298: {found}"); + assert_eq!(github.sent().len(), calls, "the picker made GitHub calls"); + + let too_many: Vec = (1..=51).map(|n| (1000 + n).to_string()).collect(); + ui(&app, &ada, "POST", path, Some(json!({ "repository_ids": too_many }))).await.assert_status(422); + let pick = ui(&app, &ada, "POST", path, Some(json!({ "repository_ids": ["42", "44"] }))).await; + pick.assert_ok().assert_json_path("total", 2); + let id = pick.json()["id"].as_i64().unwrap(); + let progress = ui(&app, &ada, "GET", &format!("/api/ui/orgs/acme/repository-imports/{id}"), None).await; + progress.assert_ok().assert_json_path("finished", true).assert_json_path("error", serde_json::Value::Null); + assert_eq!(progress.json()["linked"].as_array().map(Vec::len), Some(2), "{}", progress.json()); + let made: Vec = projects(org.id).await?.into_iter().map(|(slug, _, _)| slug).collect(); + assert_eq!(made, vec!["app".to_string(), "web".to_string()], "exactly the two picked"); + let status = app.get("/status").await.json().clone(); + assert_eq!(status["stalled_repository_import_seconds"], 0, "{status}"); + Ok(()) +} + +/// Uninstalled and installed again (a new installation ID): the projects move to the new one, setting it up finds the +/// same organization, and nothing new is made. +#[laravel::test(app = github)] +async fn a_reinstall_moves_projects_to_the_new_installation_with_no_new_organization( + app: Application, +) -> laravel::Result<()> { + let (ada, _) = ada().await?; + remember(ada.id, &[installation("7", "5005", "acme", "Organization")], &three_hundred()).await?; + let _github = acme_all("7"); + installations::set_up(&github_app(), &ada, "7").await?; + let path = "/api/ui/orgs/acme/repositories"; + ui(&app, &ada, "POST", path, Some(json!({ "repository_ids": ["42"] }))).await.assert_ok(); + let org = Organization::query().filter(Organization::slug.eq("acme")).first().await?.expect("acme"); + let orgs_before: Option = db::query!("SELECT COUNT(*) FROM organizations").scalar().await?; + + let account = json!({ "id": 5005, "login": "acme", "type": "Organization" }); + let web = json!([{ "full_name": "acme/web", "id": 42 }]); + let _github = acme_all("8").with("api.github.com/repos/acme/web/collaborators*", json!([])); + deliver( + &app, + "installation", + json!({ "action": "deleted", "installation": { "id": 7, "account": account }, + "sender": { "id": 1001 }, "repositories": web }), + ) + .await + .assert_ok(); + deliver( + &app, + "installation", + json!({ "action": "created", "installation": { "id": 8, "account": account }, + "sender": { "id": 1001 }, "repositories": web }), + ) + .await + .assert_ok() + .assert_json_path("linked", 1); + assert_eq!( + projects(org.id).await?, + vec![("web".into(), Some("https://github.com/acme/web".into()), Some("8".into()))] + ); + + let done = installations::set_up(&github_app(), &ada, "8").await?; + assert_eq!(done.organization, "acme", "found again by the account"); + assert!(!done.organization_created); + let orgs_after: Option = db::query!("SELECT COUNT(*) FROM organizations").scalar().await?; + assert_eq!(orgs_after, orgs_before, "no new organization"); + assert_eq!(projects(org.id).await?.len(), 1, "no new projects"); + let old: Option = + db::query!("SELECT deleted_at IS NOT NULL FROM github_installations WHERE installation_id = '7'") + .scalar() + .await?; + assert_eq!(old, Some(true)); + Ok(()) +} + +/// The App is public: a stranger's installation (no VisualCI user) is recorded and left unclaimed, and its deliveries +/// answer 200 without queueing anything that retries. +#[laravel::test(app = github)] +async fn a_strangers_installation_stays_unclaimed_without_errors(app: Application) -> laravel::Result<()> { + let account = json!({ "id": 7777, "login": "stranger", "type": "User" }); + let repo = json!({ "id": 9001, "full_name": "stranger/site" }); + let _github = client::fake().with("api.github.com/app/installations/77", json!({ "id": 77 })); + deliver( + &app, + "installation", + json!({ "action": "created", "installation": { "id": 77, "account": account }, + "sender": { "id": 7777 }, "repositories": [repo] }), + ) + .await + .assert_ok() + .assert_json_path("installations.installation", "recorded"); + for (kind, event) in [ + ( + "push", + json!({ "ref": "refs/heads/main", "deleted": true, "repository": repo, "installation": { "id": 77 } }), + ), + ( + "workflow_run", + json!({ "action": "completed", "repository": repo, "installation": { "id": 77 }, + "workflow_run": { "head_sha": "abc", "conclusion": "failure", "html_url": "https://github.com/stranger/site/actions/runs/1" } }), + ), + ( + "installation_repositories", + json!({ "action": "added", "installation": { "id": 77, "account": account }, + "sender": { "id": 7777 }, "repositories_added": [repo] }), + ), + ] { + deliver(&app, kind, event).await.assert_ok(); + } + let row = db::query!("SELECT organization_id, installed_by FROM github_installations WHERE installation_id = '77'") + .select_one() + .await? + .expect("recorded"); + assert_eq!(row.try_get::>("organization_id")?, None, "unclaimed"); + assert_eq!(row.try_get::>("installed_by")?.as_deref(), Some("7777")); + let queued: Option = db::query!("SELECT COUNT(*) FROM failed_jobs").scalar().await?; + assert_eq!(queued, Some(0)); + let projects: Option = db::query!("SELECT COUNT(*) FROM projects").scalar().await?; + assert_eq!(projects, Some(0)); + Ok(()) +} + +/// One person, two installations (her own account and Acme): each maps to its organization, and each picker lists +/// only its installation's repositories. +#[laravel::test(app = github)] +async fn two_installations_each_get_their_own_picker(app: Application) -> laravel::Result<()> { + let (ada, own) = ada().await?; + let mut listed = three_hundred(); + listed.push(Reachable { + installation_id: "9".into(), + repository: Repository::parse("ada/notes").expect("a repository").with_id(Some("77".into())), + permission: Permission::Admin, + private: false, + archived: false, + }); + remember( + ada.id, + &[installation("7", "5005", "acme", "Organization"), installation("9", "1001", "ada", "User")], + &listed, + ) + .await?; + let _github = acme_all("7") + .with("api.github.com/app/installations/9", json!({ "id": 9, "repository_selection": "selected" })) + .with("api.github.com/app/installations/9/access_tokens", json!({ "token": "t" })); + assert_eq!(installations::set_up(&github_app(), &ada, "9").await?.organization, own.slug, "hers: her organization"); + assert_eq!(installations::set_up(&github_app(), &ada, "7").await?.organization, "acme"); + + let mine = ui(&app, &ada, "GET", &format!("/api/ui/orgs/{}/repositories", own.slug), None).await.json().clone(); + assert_eq!(mine["total"], 1, "{mine}"); + assert_eq!(mine["repositories"][0]["full_name"], "ada/notes"); + let acme = ui(&app, &ada, "GET", "/api/ui/orgs/acme/repositories?installation=7", None).await.json().clone(); + assert_eq!(acme["total"], 300); + let none = ui(&app, &ada, "GET", "/api/ui/orgs/acme/repositories?installation=9", None).await.json().clone(); + assert_eq!(none["total"], 0, "her own installation's repositories aren't Acme's"); + Ok(()) +} diff --git a/docs/design.md b/docs/design.md index a0abfa83..60c0d840 100644 --- a/docs/design.md +++ b/docs/design.md @@ -380,7 +380,7 @@ notice on the project), so nobody keeps posting VisualCI's checks to a repositor looked up by the person's permanent forge user ID, never a stored login, which can be renamed and taken. **Onboarding through the GitHub App (sc-9027).** Signing up makes an empty personal organization; installing the GitHub -App makes the projects. `github_installations` records every installation VisualCI hears of (from a sign-in, which +App maps the installation to an organization, and people pick which repositories become projects. `github_installations` records every installation VisualCI hears of (from a sign-in, which lists the ones the person can reach into `user_installations`, and from the `installation` webhook: created, suspended, removed, with removed rows kept so a reinstall finds its organization again). The App's Setup URL, `GET /github/setup?installation_id=…&state=…` on the app host, maps the installation to an organization: the person's @@ -392,9 +392,15 @@ person's own account, or for a GitHub organization its owner (`GET /orgs/{org}/m App's Members: read permission) or whoever installed the App there (the `installation` webhook's sender, `installed_by`); another person's account is refused. The mapping is written only where none exists, so two people setting it up at once can't both win. The GET sets up only the install this browser started (`/github/install` puts a -`state` in the session and sends it to GitHub); anything else lands on the checklist, where a click sets it up. Each granted repository the installer can Maintain becomes a project linked through the usual -link checks; the rest are listed with the reason. Repositories added to a set-up installation later become projects -in its organization. The checklist (`install_github_app`, `add_to_ci`, `connect_agent`, `review_changes`) offers +`state` in the session and sends it to GitHub); anything else lands on the checklist, where a click sets it up. Setting up makes no projects and takes a few GitHub +calls at most, so it answers at once even for an organization with hundreds of repositories (3 Dec 2026: making a +project per repository inside the request ran past the 30 s limit on DocSpring's 255). It lands on the repository +picker (`/{org}/repositories`), which reads `user_repositories`: every repository each person can reach through each +installation, with their permission, as of their last GitHub sign-in (which lists them anyway), so it pages and +searches with no GitHub call. The repositories they pick (Maintain or Admin, not archived, at most 50 at a time) become +a `repository_imports` row and a queued job (`ImportRepositories`) links them one by one through the usual link checks, +saving progress after each; the picker shows it, and `/status` reports `stalled_repository_import_seconds`. Nothing +becomes a project on its own: repositories added to an installation later wait in the picker too. The checklist (`install_github_app`, `add_to_ci`, `connect_agent`, `review_changes`) offers installations the person can reach that aren't set up yet (`POST /api/ui/installations/{id}/setup`). **GitLab.** GitLab is parked in app/ (sign-in and the bot's token are read, the rest of this is the design to finish). diff --git a/frontend/content/docs/index.md b/frontend/content/docs/index.md index c87a479e..310cd5b0 100644 --- a/frontend/content/docs/index.md +++ b/frontend/content/docs/index.md @@ -9,7 +9,7 @@ A change doesn't fail the build. The pull request's GitHub check waits while you ## Start here -- [Quick start](/docs/quick-start/): install the GitHub App, which makes your projects, then the CLI, and run your first build. +- [Quick start](/docs/quick-start/): install the GitHub App and pick your repositories, then the CLI, and run your first build. - [Coding agents](/docs/agents/): connect an agent to the MCP server and let it review builds. - [CI providers](/docs/ci/github-actions/): GitHub Actions, CircleCI, Buildkite, GitLab and the rest. diff --git a/frontend/content/docs/quick-start.md b/frontend/content/docs/quick-start.md index b01434a4..1f6394b2 100644 --- a/frontend/content/docs/quick-start.md +++ b/frontend/content/docs/quick-start.md @@ -1,17 +1,17 @@ --- title: Quick start -description: Install the GitHub App, which makes your projects, then the visualci CLI, and send your first build from CI. +description: Install the GitHub App and pick the repositories to test, then install the visualci CLI and send your first build from CI. skill: visualci -skill_description: Sets up VisualCI, visual regression and snapshot review for PDFs, screenshots, images, JSON, HTML and text: installs the GitHub App (which makes a project per repository) and the CLI, creates a CI token, sends the first build, and picks the visualci-* skill for the user's CI provider and test tools. Use when the user mentions VisualCI, wants visual regression testing, screenshot or PDF comparison, or snapshot changes that wait for review instead of failing CI. Not for a specific CI provider or test tool once VisualCI is set up: use that skill. +skill_description: Sets up VisualCI, visual regression and snapshot review for PDFs, screenshots, images, JSON, HTML and text: installs the GitHub App (the person picks which repositories become projects) and the CLI, creates a CI token, sends the first build, and picks the visualci-* skill for the user's CI provider and test tools. Use when the user mentions VisualCI, wants visual regression testing, screenshot or PDF comparison, or snapshot changes that wait for review instead of failing CI. Not for a specific CI provider or test tool once VisualCI is set up: use that skill. --- To see what a review looks like first, open the [demo build](https://app.visualci.com/visualci/demo): no sign-in needed. ## 1. Install the GitHub App -Sign in at [app.visualci.com](https://app.visualci.com) with GitHub, then choose **Install on GitHub** in the setup steps and pick the repositories to test. VisualCI makes a project for each repository you can maintain (an admin or maintainer on GitHub), linked to it, so its pull requests get a VisualCI check. Installed on your own account, the projects go into your personal organization; installed on a GitHub organization, into a VisualCI organization named after it, which your teammates join from their permission on the repositories when they sign in. See [Members and access](/docs/reference/access/). +Sign in at [app.visualci.com](https://app.visualci.com) with GitHub, then choose **Install on GitHub** in the setup steps and install it on your account or a GitHub organization. Installed on your own account, it's set up for your personal organization; installed on a GitHub organization, for a VisualCI organization named after it, which your teammates join from their permission on the repositories when they sign in. See [Members and access](/docs/reference/access/). -Repositories you can't maintain are listed with the reason: ask an admin of the repository to set it up. Already installed the App? The setup steps offer that installation: choose **Set it up**. +Back in VisualCI, pick the repositories to test: search and page through everything the App can reach, even an organization with hundreds of repositories. Each one you pick becomes a project, linked to the repository, so its pull requests get a VisualCI check. You can pick repositories you maintain or administer on GitHub; the others say why not. **Add repositories** on the organization's page picks more later. Already installed the App? The setup steps offer that installation: choose **Set it up**. Then create a project token on the project's **Tokens** tab (the **Add VisualCI to CI** step does it for you). Project tokens start with `vci_`. diff --git a/frontend/src/__tests__/search.test.ts b/frontend/src/__tests__/search.test.ts new file mode 100644 index 00000000..bacb08e1 --- /dev/null +++ b/frontend/src/__tests__/search.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { parseSearch, stringifySearch } from '../search' + +describe('search params', () => { + it('writes a numeric-looking string without quotes', () => { + expect(stringifySearch({ installation: '5002', page: 2 })).toBe('?installation=5002&page=2') + }) + + it('reads plain values as the decoder makes them, for validateSearch to convert', () => { + expect(parseSearch('?installation=5002&page=2&q=pdf')).toEqual({ installation: 5002, page: 2, q: 'pdf' }) + }) + + it('round-trips text', () => { + const search = { q: 'invoices', thread: '01a23e1d-6aa7-7913-8368-8c9c6f5a61cc', mode: 'side-by-side' } + expect(parseSearch(stringifySearch(search))).toEqual(search) + }) + + it('keeps objects and arrays structured', () => { + const search = { filter: { state: ['changed', 'added'] } } + expect(parseSearch(stringifySearch(search))).toEqual(search) + }) +}) diff --git a/frontend/src/api/hooks.ts b/frontend/src/api/hooks.ts index 83d2a457..5fdee348 100644 --- a/frontend/src/api/hooks.ts +++ b/frontend/src/api/hooks.ts @@ -21,6 +21,8 @@ import type { ProjectSettings, Providers, InstallationSetUp, + RepositoryImport, + RepositoryPicker, Setup, Signup, SnapshotData, @@ -468,6 +470,45 @@ export function useSetUpInstallation() { }) } +/** A page of the repository picker: what the person can reach through the organization's installations. */ +export function useRepositoryPicker(org: string, search: { installation?: string; q?: string; page?: number }) { + const params = new URLSearchParams() + if (search.installation) params.set('installation', search.installation) + if (search.q) params.set('q', search.q) + if (search.page && search.page > 1) params.set('page', String(search.page)) + const qs = params.toString() + return useQuery({ + queryKey: ['repositories', org, search.installation ?? '', search.q ?? '', search.page ?? 1], + queryFn: () => get(`/api/ui/orgs/${org}/repositories${qs ? `?${qs}` : ''}`), + placeholderData: (previous) => previous, + }) +} + +/** Make the chosen repositories into projects, in the background: answers the pick's progress. */ +export function useImportRepositories(org: string) { + return useMutation({ + mutationFn: (repositoryIds: string[]) => post(`/api/ui/orgs/${org}/repositories`, { repository_ids: repositoryIds }), + }) +} + +/** A pick's progress, asked again every second and a half until it's finished. */ +export function useRepositoryImport(org: string, id: number | null) { + const qc = useQueryClient() + return useQuery({ + queryKey: ['repository-import', org, id], + enabled: id != null, + queryFn: async () => { + const r = await get(`/api/ui/orgs/${org}/repository-imports/${id}`) + if (r.finished) { + qc.invalidateQueries({ queryKey: keys.org(org) }) + qc.invalidateQueries({ queryKey: ['repositories', org] }) + } + return r + }, + refetchInterval: (q) => (q.state.data?.finished ? false : 1500), + }) +} + /** "How did you hear about VisualCI?": an answer, or Skip. */ export function useHeardAbout() { const qc = useQueryClient() diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index eb9e721b..a12fdb05 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -124,19 +124,50 @@ export type InstallationOffer = { organization: string | null } -/** What setting an installation up did. */ +/** What setting an installation up did: the organization it's set up for. It makes no projects: people pick them. */ export type InstallationSetUp = { installation_id: string account_login: string organization: string organization_created: boolean note: string | null + /** Where to go next (the repository picker). Only in the API's answer. */ + landing?: string +} + +/** A repository in the picker: what the person can reach through one of the organization's installations. */ +export type PickerRepository = { + installation_id: string + repository_id: string + full_name: string + permission: 'read' | 'triage' | 'write' | 'maintain' | 'admin' + private: boolean + archived: boolean + /** Maintained (or administered), not archived and not a project here yet. */ + can_add: boolean + /** The project already linked to it here. */ + project: string | null +} + +/** A pick of repositories being made into projects in the background, and how far it's got. */ +export type RepositoryImport = { + id: number + total: number linked: { project: string; repository: string }[] - already: { project: string; repository: string }[] skipped: { repository: string; reason: string }[] - truncated: boolean - /** Where to go next (the organization's page with the next step open). Only in the API's answer. */ - landing?: string + finished: boolean + error: string | null +} + +/** A page of the repository picker. */ +export type RepositoryPicker = { + repositories: PickerRepository[] + total: number + page: number + per_page: number + query: string + installations: { installation_id: string; account_login: string }[] + running: RepositoryImport | null } /** The "Set up VisualCI" checklist: each step ticks itself from what happened. */ diff --git a/frontend/src/components/SetupChecklist.tsx b/frontend/src/components/SetupChecklist.tsx index db77e60a..edd0c950 100644 --- a/frontend/src/components/SetupChecklist.tsx +++ b/frontend/src/components/SetupChecklist.tsx @@ -20,34 +20,16 @@ const TITLES: Record = { } /** "Set up for acme: 3 projects." */ -function projectCount(r: InstallationSetUp): string { - const n = r.linked.length + r.already.length - return n === 1 ? '1 project' : `${n} projects` -} - -/** What setting an installation up did: its projects, and the repositories it couldn't add, with why. */ -function SetUpResult({ result }: { result: InstallationSetUp }) { +/** An installation set up for this organization: its repositories are picked in the repository picker. */ +function SetUpResult({ org, result }: { org: string; result: InstallationSetUp }) { return (

- Set up for {result.account_login}: {projectCount(result)}. - {result.note && {result.note}.} + Set up for {result.account_login}.{result.note && {result.note}.}{' '} + + Pick its repositories +

- {result.skipped.length > 0 && ( -
- - {result.skipped.length === 1 ? '1 repository' : `${result.skipped.length} repositories`} not added - -
    - {result.skipped.map((s) => ( -
  • - {s.repository} {s.reason} -
  • - ))} -
-
- )} - {result.truncated &&

Only the first 100 repositories were looked at. Add the rest by hand.

}
) } @@ -63,16 +45,15 @@ function InstallGithubApp({ org, data, onCreateProject }: { org: string; data: O const go = (id: string) => { setPending(id) setUp.mutate(id, { - onSuccess: (r) => { - if (r.organization !== org) navigate({ to: '/$org', params: { org: r.organization }, search: { setup: 'add_to_ci', installation: r.installation_id } }) - }, + // Set up: on to its repository picker (in whichever organization it's set up for) + onSuccess: (r) => navigate({ to: '/$org/repositories', params: { org: r.organization }, search: { installation: r.installation_id } }), onSettled: () => setPending(null), }) } return ( <> {results.map((r) => ( - + ))} {offers.length > 0 && (
    @@ -110,8 +91,9 @@ function InstallGithubApp({ org, data, onCreateProject }: { org: string; data: O {offers.length || results.length ? 'Install on another account' : 'Install on GitHub'} - Pick the repositories to test. Each one you maintain becomes a project here, with checks on its pull requests - and access that follows people’s permission on it. It can’t read your code. + Install it on your GitHub account or organization, then pick the repositories to test. Each one you pick becomes + a project here, with checks on its pull requests and access that follows people’s permission on it. It can’t read + your code. {onCreateProject && ( @@ -309,7 +291,7 @@ export function SetupChecklist({ {just && (

    - VisualCI is set up for {just.account_login}: {projectCount(just)}. Next, add it to CI. + VisualCI is set up for {just.account_login}. Next, add it to CI.

    )}
      diff --git a/frontend/src/pages/OrgPage.tsx b/frontend/src/pages/OrgPage.tsx index c3bb63d2..88629f33 100644 --- a/frontend/src/pages/OrgPage.tsx +++ b/frontend/src/pages/OrgPage.tsx @@ -73,8 +73,13 @@ export function OrgPage() { Show setup steps )} + {canCreate && o.setup.github.length > 0 && ( + + Add repositories + + )} {canCreate && !creating && o.projects.length > 0 && ( - )} @@ -105,10 +110,24 @@ export function OrgPage() { // The GitHub App makes the projects: the empty state points at the same step as the checklist, and the // hand-made path stays a small link (in the checklist's first step, or here when the checklist is hidden) -

      Install the GitHub App to add your repositories: each one you maintain becomes a project.

      - - Install on GitHub - + {o.setup.github.length > 0 ? ( + <> +

      The GitHub App is installed. Pick the repositories to test: each one becomes a project.

      + + Pick repositories + + + ) : showSetup ? ( + // The checklist's first step already offers the install: one action on the page +

      Pick repositories after installing the GitHub App.

      + ) : ( + <> +

      Install the GitHub App, then pick the repositories to test: each one becomes a project.

      + + Install on GitHub + + + )} {canCreate && !showSetup && (

      Not on GitHub?{' '} diff --git a/frontend/src/pages/RepositoriesPage.tsx b/frontend/src/pages/RepositoriesPage.tsx new file mode 100644 index 00000000..525364a1 --- /dev/null +++ b/frontend/src/pages/RepositoriesPage.tsx @@ -0,0 +1,311 @@ +import { useEffect, useRef, useState } from 'react' +import { Link, getRouteApi, useNavigate } from '@tanstack/react-router' +import { ArrowRightIcon, CaretLeftIcon, CaretRightIcon, LockSimpleIcon, MagnifyingGlassIcon } from '@phosphor-icons/react' +import { useImportRepositories, useOrg, useRepositoryImport, useRepositoryPicker } from '../api/hooks' +import type { PickerRepository, RepositoryImport } from '../api/types' +import { QueryState } from '../components/QueryState' +import { Button, Empty, Help } from '../components/ui' + +const route = getRouteApi('/_app/$org/repositories') + +/** The most repositories one pick makes into projects (the server's IMPORT_LIMIT). */ +const PICK_LIMIT = 50 + +/** + * The repository picker: the repositories the person can reach through the organization's GitHub App installations + * (from their last GitHub sign-in), searched and paged on the server. The ones they pick become projects in the + * background, with progress here, then the checklist's next step. + */ +export function RepositoriesPage() { + const { org } = route.useParams() + const search = route.useSearch() + const navigate = useNavigate({ from: '/$org/repositories' }) + const orgQ = useOrg(org) + const picker = useRepositoryPicker(org, search) + const start = useImportRepositories(org) + const [picked, setPicked] = useState>(new Map()) + const [importId, setImportId] = useState(null) + const [query, setQuery] = useState(search.q ?? '') + const running = picker.data?.running ?? null + const progress = useRepositoryImport(org, importId ?? running?.id ?? null) + + // The search box updates the URL a moment after typing stops, back to the first page + useEffect(() => { + const t = setTimeout(() => { + if ((search.q ?? '') !== query) navigate({ search: (s) => ({ ...s, q: query || undefined, page: undefined }), replace: true }) + }, 250) + return () => clearTimeout(t) + }, [query, search.q, navigate]) + + if (!orgQ.data || !picker.data) return + const o = orgQ.data + const p = picker.data + const shown = progress.data ?? (importId == null ? running : null) + if (shown) return setImportId(null)} /> + + const pages = Math.max(1, Math.ceil(p.total / p.per_page)) + const from = p.total === 0 ? 0 : (p.page - 1) * p.per_page + 1 + const to = Math.min(p.total, p.page * p.per_page) + const toggle = (r: PickerRepository) => + setPicked((m) => { + const next = new Map(m) + if (next.has(r.repository_id)) next.delete(r.repository_id) + else if (next.size < PICK_LIMIT) next.set(r.repository_id, r.full_name) + return next + }) + const pickable = p.repositories.filter((r) => r.can_add) + const pickedHere = pickable.filter((r) => picked.has(r.repository_id)).length + const allHere = pickable.length > 0 && pickedHere === pickable.length + const toggleAll = () => + setPicked((m) => { + const next = new Map(m) + if (allHere) for (const r of pickable) next.delete(r.repository_id) + else for (const r of pickable) if (next.size < PICK_LIMIT) next.set(r.repository_id, r.full_name) + return next + }) + const account = p.installations.find((i) => i.installation_id === search.installation) + const refresh = `/auth/github?return_to=${encodeURIComponent(`/${org}/repositories${search.installation ? `?installation=${search.installation}` : ''}`)}` + + return ( +

      +
      +
      +

      + + {o.name} + +

      +

      Add repositories

      +

      + Pick the repositories to test{account ? ` from ${account.account_login}` : ''}. Each one becomes a project in {o.name}, with + checks on its pull requests. +

      +
      +
      + + {p.installations.length > 1 && ( +
      + + All accounts + + {p.installations.map((i) => ( + + {i.account_login} + + ))} +
      + )} + +
      + + + {p.total === 0 ? 'No repositories' : `${from}–${to} of ${p.total}`} + + + + + {p.page}/{pages} + + + +
      + + {p.total === 0 ? ( + + {!p.query && ( +

      + Your last GitHub sign-in didn’t list any repositories for {o.name}. If you’ve just installed the App or given it + more repositories, refresh the list. +

      + )} + {!p.query && ( + + Refresh from GitHub + + )} +
      + ) : ( +
        + {pickable.length > 0 && ( +
      • + +
      • + )} + {p.repositories.map((r) => ( +
      • + + {!r.can_add && {rowState(org, r)}} +
      • + ))} +
      + )} + +

      + Missing one? Refresh the list from GitHub, or{' '} + install the App on another account. +

      + +
      + + {picked.size === 0 ? 'Nothing picked yet' : `${picked.size} picked`} + {picked.size >= PICK_LIMIT && (at most {PICK_LIMIT} at a time)} + + {start.error && ( + + {start.error.message} + + )} + +
      +
      + ) +} + +/** Why a row can't be picked: a short label, with the explanation in a tooltip. */ +function rowState(org: string, r: PickerRepository) { + if (r.project) + return ( + + Already a project + + ) + if (r.archived) return Archived + return ( + + Needs admin + + Only an admin or maintainer of the repository can add it. You have {r.permission} access. + + + ) +} + +/** The list's select-all box: ticked when every pickable row on the page is, half-ticked when some are. */ +function PageCheckbox({ checked, mixed, disabled, onChange }: { checked: boolean; mixed: boolean; disabled: boolean; onChange: () => void }) { + const box = useRef(null) + useEffect(() => { + if (box.current) box.current.indeterminate = mixed + }, [mixed]) + return +} + +/** A pick being made into projects: how far it's got, then the next step. */ +function Progress({ org, orgName, state, onMore }: { org: string; orgName: string; state: RepositoryImport; onMore: () => void }) { + const navigate = useNavigate() + const done = state.linked.length + state.skipped.length + const first = state.linked[0]?.project + return ( +
      +
      +
      +

      + + {orgName} + +

      +

      {state.finished ? (state.linked.length === 1 ? 'Added 1 project' : `Added ${state.linked.length} projects`) : 'Adding repositories'}

      +
      +
      +
      +

      + {state.finished ? `${done} of ${state.total} done.` : `${done} of ${state.total} done. Each takes a few seconds.`} +

      + +
        + {state.linked.map((l) => ( +
      • + {l.repository}{' '} + {' '} + + {l.project} + +
      • + ))} + {state.skipped.map((s) => ( +
      • + {s.repository} not added: {s.reason} +
      • + ))} +
      + {state.error && ( +

      + Stopped: {state.error} +

      + )} + {state.finished && ( +
      + {first && ( + + )} + +
      + )} +
      +
      + ) +} diff --git a/frontend/src/router.tsx b/frontend/src/router.tsx index 01b0a348..d7e811c6 100644 --- a/frontend/src/router.tsx +++ b/frontend/src/router.tsx @@ -1,9 +1,11 @@ import { Outlet, createRootRouteWithContext, createRoute, createRouter } from '@tanstack/react-router' +import { parseSearch, stringifySearch } from './search' import type { QueryClient } from '@tanstack/react-query' import type { SetupStepKey } from './api/types' import { AppGate, NotFound } from './components/AppShell' import { Home } from './pages/Home' import { OrgPage } from './pages/OrgPage' +import { RepositoriesPage } from './pages/RepositoriesPage' import { BillingPage } from './pages/BillingPage' import { ProjectPage, type ProjectTab } from './pages/ProjectPage' import { BuildPage } from './pages/BuildPage' @@ -61,6 +63,18 @@ const orgRoute = createRoute({ }), }) +// The repository picker: the GitHub App's set-up lands here, and "Add repositories" opens it later +const repositoriesRoute = createRoute({ + getParentRoute: () => appRoute, + path: '$org/repositories', + component: RepositoriesPage, + validateSearch: (search: Record): { installation?: string; q?: string; page?: number } => ({ + ...(search.installation != null && /^\d{1,20}$/.test(String(search.installation)) ? { installation: String(search.installation) } : {}), + ...(typeof search.q === 'string' && search.q !== '' ? { q: search.q.slice(0, 100) } : {}), + ...(Number(search.page) > 1 ? { page: Math.floor(Number(search.page)) } : {}), + }), +}) + const billingRoute = createRoute({ getParentRoute: () => appRoute, path: '$org/billing', component: () => }) const billingUsageRoute = createRoute({ getParentRoute: () => appRoute, path: '$org/billing/usage', component: () => }) const billingMethodsRoute = createRoute({ @@ -119,7 +133,7 @@ const snapshotRoute = createRoute({ ? { mode: search.mode as SnapshotMode } : {}), ...(search.against === 'previous' ? { against: 'previous' as const } : {}), - ...(typeof search.thread === 'string' ? { thread: search.thread } : {}), + ...(typeof search.thread === 'string' || typeof search.thread === 'number' ? { thread: String(search.thread) } : {}), }), component: SnapshotPage, }) @@ -127,7 +141,7 @@ const snapshotRoute = createRoute({ const routeTree = rootRoute.addChildren([ homeRoute, authorizeRoute, - appRoute.addChildren([accountRoute, askRoute, deviceRoute, staffRoute, staffFeedbackRoute, staffEmailsRoute, orgRoute, billingRoute, billingUsageRoute, billingMethodsRoute, billingInvoicesRoute, projectRoute, buildRoute, pullRoute, snapshotRoute]), + appRoute.addChildren([accountRoute, askRoute, deviceRoute, staffRoute, staffFeedbackRoute, staffEmailsRoute, orgRoute, repositoriesRoute, billingRoute, billingUsageRoute, billingMethodsRoute, billingInvoicesRoute, projectRoute, buildRoute, pullRoute, snapshotRoute]), ]) export function makeRouter(queryClient: QueryClient) { @@ -137,6 +151,8 @@ export function makeRouter(queryClient: QueryClient) { scrollRestoration: true, defaultPreload: 'intent', defaultPreloadStaleTime: 0, + parseSearch, + stringifySearch, }) } diff --git a/frontend/src/search.ts b/frontend/src/search.ts new file mode 100644 index 00000000..079883e8 --- /dev/null +++ b/frontend/src/search.ts @@ -0,0 +1,17 @@ +import { parseSearchWith, stringifySearchWith } from '@tanstack/react-router' + +/** + * The app's addresses keep plain values plain: `?installation=5002&page=2`, not the router's default + * `?installation=%225002%22`, which JSON-quotes a string that looks like a number so it reads back as a string. + * A plain value reads back as the router's decoder makes it (`5002` a number, `true` a flag, the rest strings), so each + * route's `validateSearch` converts what it needs, such as `String(search.installation)`. Only objects and arrays go + * through JSON. + */ +function parseStructured(value: string): unknown { + const parsed: unknown = JSON.parse(value) + if (typeof parsed !== 'object' || parsed === null) throw new Error('a plain value stays a string') + return parsed +} + +export const parseSearch = parseSearchWith(parseStructured) +export const stringifySearch = stringifySearchWith(JSON.stringify, parseStructured) diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 79bb664d..961cf1d5 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -5423,3 +5423,181 @@ html.vci-signed-in .site-auth-out { max-width: 100%; height: auto; } + +/* The repository picker (RepositoriesPage) */ +.picker-page { + padding-bottom: calc(var(--space-8) * 2); +} + +.picker-back { + font-size: var(--text-sm); + margin: 0 0 var(--space-1); +} + +.picker-accounts { + margin-bottom: var(--space-3); +} + +.picker-tools { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-3); + margin-bottom: var(--space-3); +} + +.picker-search { + position: relative; + flex: 1 1 260px; + min-width: 0; + display: flex; + align-items: center; +} + +.picker-search svg { + position: absolute; + left: var(--space-3); + color: var(--color-muted); + pointer-events: none; +} + +.picker-search .input { + width: 100%; + padding-left: calc(var(--space-3) + 22px); +} + +.picker-count { + font-size: var(--text-sm); + white-space: nowrap; +} + +.picker-list { + list-style: none; + margin: 0; + padding: 0; + border: 1px solid var(--color-rule); + border-radius: var(--radius-lg); + background: var(--color-surface); +} + +.picker-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + padding: var(--space-2) var(--space-4); + min-height: 44px; +} + +.picker-row + .picker-row { + border-top: 1px solid var(--color-rule); +} + +.picker-row:hover { + background: var(--color-hover); +} + +.picker-row label { + display: flex; + align-items: center; + gap: var(--space-3); + min-width: 0; + flex: 1 1 auto; + cursor: pointer; +} + +.picker-row-off label { + cursor: default; +} + +.picker-row input[type='checkbox'] { + width: 16px; + height: 16px; + flex: none; + accent-color: var(--color-accent); +} + +.picker-name { + font-size: var(--text-sm); + overflow-wrap: anywhere; + min-width: 0; +} + +.picker-row-off .picker-name { + color: var(--color-muted); +} + +.picker-private { + display: inline-flex; + flex: none; +} + +.picker-state { + flex: none; + font-size: var(--text-xs); + text-align: right; + max-width: 45%; +} + +.picker-foot { + font-size: var(--text-sm); + margin-top: var(--space-3); +} + +.picker-bar { + position: sticky; + bottom: var(--space-4); + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + gap: var(--space-3); + margin-top: var(--space-4); + padding: var(--space-3) var(--space-4); + border: 1px solid var(--color-rule-strong); + border-radius: var(--radius-lg); + background: var(--color-surface); + font-size: var(--text-sm); +} + +.picker-bar > span:first-child { + margin-right: auto; +} + +.picker-progress progress { + width: 100%; + height: 8px; + accent-color: var(--color-accent); + margin: var(--space-2) 0 var(--space-3); +} + +.picker-done { + list-style: none; + margin: 0 0 var(--space-3); + padding: 0; + font-size: var(--text-sm); + display: grid; + gap: var(--space-1); +} + +.picker-head { + font-size: var(--text-sm); +} + +.picker-head:hover { + background: none; +} + +.picker-needs { + display: inline-flex; + align-items: center; + gap: var(--space-1); + white-space: nowrap; +} + +@media (max-width: 480px) { + /* A long name wraps beside its label */ + .picker-row label { + flex: 1 1 0; + } +} diff --git a/scripts/journeys/github-stub.mjs b/scripts/journeys/github-stub.mjs index c716d6eb..0495dfb3 100644 --- a/scripts/journeys/github-stub.mjs +++ b/scripts/journeys/github-stub.mjs @@ -2,44 +2,132 @@ // framework's social login and the app's own GitHub calls (at /api/v3, as for a GitHub Enterprise // Server) reach it instead of github.com. Production refuses any GITHUB_URL but github.com (forge::check_github). // -// It plays one person, journey-ada, who approves every sign-in at once: /login/oauth/authorize sends the browser -// straight back to the app's callback with a code, as GitHub does for an app the person already authorized. +// It plays one person at a time, journey-ada at first, who approves every sign-in at once: /login/oauth/authorize sends +// the browser straight back to the app's callback with a code, as GitHub does for an app the person already authorized. +// +// It also plays the GitHub App's side. "Install on GitHub" (/apps/visualci-com/installations/new) installs the App on +// the account POST /_stub/target named (by default the person's own account, with three repositories), sends the app +// the signed `installation` webhook, and redirects to the app's Setup URL with GitHub's state, as GitHub does. The +// installation's repositories answer the app's API calls (installation tokens, repositories, permissions: the person +// who installed it administers every repository). // // node github-stub.mjs [port] (default 5198) +// STUB_APP_URL (where the app listens, for webhooks) and STUB_WEBHOOK_SECRET (the App's webhook secret) // -// GET /_stub/requests lists the requests it has answered, for a journey to check what the app asked; POST /_stub/person -// with a JSON body ({ id, login, name, email }) makes it someone else from the next sign-in on (someone new). +// GET /_stub/requests lists the requests it has answered, for a journey to check what the app asked (POST +// /_stub/requests/clear empties it); POST /_stub/person with a JSON body ({ id, login, name, email }) makes it someone +// else from the next sign-in on; POST /_stub/target ({ account: { id, login, type }, selection, count | repos }) +// says what the next install installs; POST /_stub/uninstall ({ id }) removes an installation, with its webhook; +// POST /_stub/webhook ({ kind, event }) sends the app any signed delivery. +import { createHmac } from 'node:crypto' import { createServer } from 'node:http' const port = Number(process.argv[2] ?? 5198) -let person = { - id: 424242, - login: 'journey-ada', - name: 'Ada Journey', - email: 'ada@journeys.test', - avatar_url: null, -} +const appUrl = process.env.STUB_APP_URL ?? 'http://127.0.0.1:5251' +const appPublic = process.env.STUB_APP_PUBLIC_URL ?? 'https://app.visualci.test' +const secret = process.env.STUB_WEBHOOK_SECRET ?? 'journeys-webhook' + +let person = { id: 424242, login: 'journey-ada', name: 'Ada Journey', email: 'ada@journeys.test', avatar_url: null } +const people = new Map([[person.id, person]]) const requests = [] +/** id -> { id, account, selection, repos: [{ id, full_name, private, archived }], members: [login], deleted } */ +const installations = new Map() +let target = null +let nextInstallation = 5000 +let nextRepository = 70000 function json(res, status, body) { res.writeHead(status, { 'content-type': 'application/json' }) res.end(JSON.stringify(body)) } +/** `count` repositories `owner/repo-001`…, or the named ones. */ +function repositories(owner, spec) { + if (spec.repos) return spec.repos.map((r) => ({ id: r.id ?? nextRepository++, full_name: `${owner}/${r.name}`, private: r.private ?? true, archived: r.archived ?? false })) + return Array.from({ length: spec.count ?? 3 }, (_, i) => ({ + id: nextRepository++, + full_name: `${owner}/repo-${String(i + 1).padStart(3, '0')}`, + private: true, + archived: false, + })) +} + +/** A page of a list, as GitHub pages them (`per_page`, `page`). */ +function page(list, url) { + const per = Math.min(100, Number(url.searchParams.get('per_page') ?? 30)) + const n = Math.max(1, Number(url.searchParams.get('page') ?? 1)) + return list.slice((n - 1) * per, n * per) +} + +const publicRepo = (r) => ({ id: r.id, full_name: r.full_name, name: r.full_name.split('/')[1], private: r.private, archived: r.archived }) +const live = () => [...installations.values()].filter((i) => !i.deleted) +const byToken = (req) => installations.get(Number(String(req.headers.authorization ?? '').replace(/^(Bearer|token) inst-/, ''))) +const repoNamed = (full) => { + for (const i of live()) { + const r = i.repos.find((x) => x.full_name.toLowerCase() === full.toLowerCase()) + if (r) return { installation: i, repo: r } + } + return null +} + +/** Sends the app a signed webhook delivery, as GitHub does. */ +async function deliver(kind, event) { + const body = JSON.stringify(event) + const signature = `sha256=${createHmac('sha256', secret).update(body).digest('hex')}` + const r = await fetch(`${appUrl}/webhooks/github`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-github-event': kind, 'x-github-delivery': `stub-${Date.now()}`, 'x-hub-signature-256': signature }, + body, + }) + const text = await r.text() + console.log(`webhook ${kind} ${event.action ?? ''} -> ${r.status} ${text}`) + return { status: r.status, body: text } +} + createServer(async (req, res) => { const url = new URL(req.url, `http://${req.headers.host}`) const path = url.pathname.replace(/^\/api\/v3/, '') - if (url.pathname !== '/_stub/requests') requests.push(`${req.method} ${url.pathname}`) - // Read the body (the token exchange's form, or a new person) + if (!url.pathname.startsWith('/_stub/')) requests.push(`${req.method} ${url.pathname}`) let body = '' for await (const chunk of req) body += chunk + const input = () => (body ? JSON.parse(body) : {}) + let m + // The journeys' controls if (url.pathname === '/_stub/person' && req.method === 'POST') { - person = { avatar_url: null, ...JSON.parse(body) } + person = { avatar_url: null, ...input() } + people.set(person.id, person) return json(res, 200, person) } - if (url.pathname === '/_stub/requests') return json(res, 200, requests) + if (url.pathname === '/_stub/requests/clear') { + requests.length = 0 + return json(res, 200, {}) + } + if (url.pathname === '/_stub/target' && req.method === 'POST') { + target = input() + return json(res, 200, target) + } + if (url.pathname === '/_stub/installations') return json(res, 200, [...installations.values()].map((i) => ({ ...i, repos: i.repos.length }))) + if (url.pathname === '/_stub/uninstall' && req.method === 'POST') { + const i = installations.get(Number(input().id)) + if (!i) return json(res, 404, {}) + i.deleted = true + const sender = people.get([...people.values()].find((p) => i.members.includes(p.login))?.id) ?? person + const r = await deliver('installation', { + action: 'deleted', + installation: { id: i.id, account: i.account, repository_selection: i.selection }, + repositories: i.repos.map(publicRepo), + sender: { id: sender.id, login: sender.login }, + }) + return json(res, 200, r) + } + if (url.pathname === '/_stub/webhook' && req.method === 'POST') { + const { kind, event } = input() + return json(res, 200, await deliver(kind, event)) + } + + // Signing in if (url.pathname === '/login/oauth/authorize') { const back = new URL(url.searchParams.get('redirect_uri')) back.searchParams.set('code', 'journey-code') @@ -50,8 +138,98 @@ createServer(async (req, res) => { if (url.pathname === '/login/oauth/access_token') { return json(res, 200, { access_token: 'journey-token', token_type: 'bearer', scope: 'read:user,user:email' }) } + + // Installing the App: on the target account (or the person's own), then back to the app's Setup URL + if (url.pathname === '/apps/visualci-com/installations/new') { + const spec = target ?? { account: { id: person.id, login: person.login, type: 'User' }, selection: 'all', count: 3 } + target = null + const id = nextInstallation++ + // `reuse`: installed again on the same account, with the same repositories (GitHub's IDs stay) + const again = spec.reuse != null ? installations.get(Number(spec.reuse)) : null + const installation = again + ? { id, account: again.account, selection: again.selection, repos: again.repos, members: [person.login], deleted: false } + : { id, account: spec.account, selection: spec.selection ?? 'all', repos: repositories(spec.account.login, spec), members: [person.login], deleted: false } + installations.set(id, installation) + await deliver('installation', { + action: 'created', + installation: { id, account: installation.account, repository_selection: installation.selection }, + repositories: installation.repos.map(publicRepo), + sender: { id: person.id, login: person.login }, + }) + const back = new URL('/github/setup', appPublic) + back.searchParams.set('installation_id', String(id)) + back.searchParams.set('setup_action', 'install') + if (url.searchParams.get('state')) back.searchParams.set('state', url.searchParams.get('state')) + res.writeHead(302, { location: back.toString() }) + return res.end() + } + + // The person if (path === '/user') return json(res, 200, person) if (path === '/user/emails') return json(res, 200, [{ email: person.email, primary: true, verified: true }]) - if (path === '/user/installations') return json(res, 200, { total_count: 0, installations: [] }) + if (path === '/user/installations') { + const mine = live().filter((i) => i.members.includes(person.login)) + return json(res, 200, { total_count: mine.length, installations: page(mine, url).map((i) => ({ id: i.id, account: i.account })) }) + } + if ((m = path.match(/^\/user\/installations\/(\d+)\/repositories$/))) { + const i = installations.get(Number(m[1])) + if (!i || i.deleted || !i.members.includes(person.login)) return json(res, 404, { message: 'Not Found' }) + const perms = { admin: true, maintain: true, push: true, triage: true, pull: true } + return json(res, 200, { total_count: i.repos.length, repositories: page(i.repos, url).map((r) => ({ ...publicRepo(r), permissions: perms })) }) + } + if ((m = path.match(/^\/user\/(\d+)$/))) { + const p = people.get(Number(m[1])) + return p ? json(res, 200, { id: p.id, login: p.login }) : json(res, 404, { message: 'Not Found' }) + } + + // The App + if ((m = path.match(/^\/app\/installations\/(\d+)\/access_tokens$/))) { + const i = installations.get(Number(m[1])) + return i && !i.deleted ? json(res, 201, { token: `inst-${i.id}` }) : json(res, 404, { message: 'Not Found' }) + } + if ((m = path.match(/^\/app\/installations\/(\d+)$/))) { + const i = installations.get(Number(m[1])) + return i && !i.deleted ? json(res, 200, { id: i.id, account: i.account, repository_selection: i.selection }) : json(res, 404, { message: 'Not Found' }) + } + if (path === '/installation/repositories') { + const i = byToken(req) + if (!i) return json(res, 401, { message: 'Bad credentials' }) + return json(res, 200, { total_count: i.repos.length, repositories: page(i.repos, url).map(publicRepo) }) + } + if ((m = path.match(/^\/orgs\/([^/]+)\/memberships\/([^/]+)$/))) { + const i = live().find((x) => x.account.login.toLowerCase() === m[1].toLowerCase()) + if (!i || !i.members.includes(m[2])) return json(res, 404, { message: 'Not Found' }) + return json(res, 200, { state: 'active', role: 'admin' }) + } + if ((m = path.match(/^\/orgs\/([^/]+)$/))) return json(res, 200, { login: m[1], name: m[1] }) + if ((m = path.match(/^\/users\/([^/]+)$/))) return json(res, 200, { login: m[1], name: m[1] }) + if ((m = path.match(/^\/repositories\/(\d+)$/))) { + const r = live().flatMap((i) => i.repos).find((x) => x.id === Number(m[1])) + return r ? json(res, 200, publicRepo(r)) : json(res, 404, { message: 'Not Found' }) + } + if ((m = path.match(/^\/repos\/([^/]+\/[^/]+)\/installation$/))) { + const found = repoNamed(m[1]) + return found ? json(res, 200, { id: found.installation.id }) : json(res, 404, { message: 'Not Found' }) + } + if ((m = path.match(/^\/repos\/([^/]+\/[^/]+)\/collaborators\/([^/]+)\/permission$/))) { + const found = repoNamed(m[1]) + if (!found || !found.installation.members.includes(m[2])) return json(res, 200, { permission: 'none', role_name: 'none' }) + return json(res, 200, { permission: 'admin', role_name: 'admin' }) + } + if ((m = path.match(/^\/repos\/([^/]+\/[^/]+)\/collaborators\/([^/]+)$/))) { + const found = repoNamed(m[1]) + res.writeHead(found && found.installation.members.includes(m[2]) ? 204 : 404) + return res.end() + } + if ((m = path.match(/^\/repos\/([^/]+\/[^/]+)\/collaborators$/))) { + const found = repoNamed(m[1]) + if (!found) return json(res, 404, { message: 'Not Found' }) + const members = [...people.values()].filter((p) => found.installation.members.includes(p.login)) + return json(res, 200, page(members.map((p) => ({ id: p.id, login: p.login, permissions: { admin: true, maintain: true, push: true, triage: true, pull: true }, role_name: 'admin' })), url)) + } + if ((m = path.match(/^\/repos\/([^/]+\/[^/]+)$/))) { + const found = repoNamed(m[1]) + return found ? json(res, 200, { ...publicRepo(found.repo), license: null }) : json(res, 404, { message: 'Not Found' }) + } json(res, 404, { message: 'Not Found (journeys GitHub stub)', path: url.pathname }) }).listen(port, '127.0.0.1', () => console.log(`GitHub stub on http://127.0.0.1:${port}`)) diff --git a/scripts/journeys/run.sh b/scripts/journeys/run.sh index 4ba133e8..6e902c7c 100755 --- a/scripts/journeys/run.sh +++ b/scripts/journeys/run.sh @@ -95,6 +95,9 @@ VISUALCI_RENDERER_VERSION=$(cat "$root/docker/renderer.version") GITHUB_URL=http://github.test:$stub_port GITHUB_CLIENT_ID=journeys GITHUB_CLIENT_SECRET=journeys-secret +VISUALCI_GITHUB_APP_ID=1 +VISUALCI_GITHUB_APP_PRIVATE_KEY_BASE64=$(openssl genrsa -traditional 2048 2>/dev/null | base64 -w0) +VISUALCI_GITHUB_WEBHOOK_SECRET=journeys-webhook EOF set -a . "$run/env" @@ -116,7 +119,9 @@ trap cleanup EXIT pids+=($!) (cd "$run" && exec "$app" queue:work >"$out/worker.log" 2>&1) & pids+=($!) -node "$root/scripts/journeys/github-stub.mjs" "$stub_port" >"$out/github-stub.log" 2>&1 & +# The stub sends the App's webhooks straight to the app, signed with its secret +STUB_APP_URL="http://127.0.0.1:$port" STUB_WEBHOOK_SECRET=journeys-webhook \ + node "$root/scripts/journeys/github-stub.mjs" "$stub_port" >"$out/github-stub.log" 2>&1 & pids+=($!) cat >"$run/Caddyfile" < { } }) +// The GitHub App's set-up (sc-9027), from the bugs of 3 Dec 2026: setting up an organization with hundreds of +// repositories ran past the 30 s request limit while it made a project for each one. + +/** The stub's controls. */ +async function stub(page, path, data) { + const r = await page.request.post(`${GITHUB}${path}`, { data: data ?? {} }) + expect(r.ok(), `the GitHub stub refused ${path}: ${r.status()}`) + return r.json() +} + +/** Signs `who` in from the site (someone new gets their own organization). */ +async function signInAs(page, shot, who) { + await stub(page, '/_stub/person', who) + await signInFromSite(page, shot) +} + +/** "Install on GitHub" from the app: the stub installs the App and sends the browser back to the Setup URL, which + * sets it up and lands on the repository picker. Returns the picker's organization and installation. */ +async function install(page) { + const started = Date.now() + await page.goto(`${APP}/github/install`) + await page.waitForURL((url) => url.host === 'app.visualci.test' && /^\/[^/]+\/repositories$/.test(url.pathname), { timeout: 20000 }) + await page.getByRole('heading', { name: 'Add repositories' }).waitFor() + const url = new URL(page.url()) + const installation = url.searchParams.get('installation') ?? '' + expect(/^\d+$/.test(installation), `the picker's address names installation ${JSON.stringify(installation)}`) + return { org: url.pathname.split('/')[1], installation, seconds: (Date.now() - started) / 1000 } +} + +const api = (page, path) => page.evaluate((p) => fetch(p, { headers: { accept: 'application/json' } }).then((r) => r.json()), path) +const bigOwner = { id: 600001, login: 'journey-owner', name: 'Owen Journey', email: 'owner@journeys.test' } + +// 8. An organization with 300 repositories, installed on all of them: set up in seconds with no projects, on the +// picker, which pages and searches; picking two makes exactly two, with their progress, then the next step. +await journey('setup-picks-from-300-repositories', async ({ page, shot }) => { + await signInAs(page, shot, bigOwner) + await stub(page, '/_stub/target', { account: { id: 880001, login: 'journey-big', type: 'Organization' }, selection: 'all', count: 300 }) + const { org, seconds } = await install(page) + expect(org === 'journey-big', `set up for ${org}`) + expect(seconds < 10, `setting it up took ${seconds} s`) + const before = await api(page, `/api/ui/orgs/${org}`) + expect(before.projects.length === 0, `setting it up made ${before.projects.length} projects`) + await page.getByText('1–50 of 300').waitFor() + await shot('picker') + await page.getByRole('button', { name: 'Next page' }).click() + await page.getByText('51–100 of 300').waitFor() + // Pick all on the page: the count holds through a search, and the box clears the page again + const pageBox = page.getByRole('checkbox', { name: 'Pick every repository on this page' }) + await pageBox.check() + await page.getByText('50 picked').waitFor() + await shot('page-2') + await page.getByRole('searchbox', { name: 'Search repositories' }).fill('repo-29') + await page.getByText('1–10 of 10').waitFor() + expect(await page.getByText('50 picked').isVisible(), 'the picked count after searching') + await shot('search') + await page.getByRole('searchbox', { name: 'Search repositories' }).fill('') + await page.getByText('1–50 of 300').waitFor() + await page.getByRole('button', { name: 'Next page' }).click() + await page.getByText('51–100 of 300').waitFor() + await pageBox.uncheck() + await page.getByText('Nothing picked yet').waitFor() + expect(await page.getByRole('button', { name: 'Add repositories' }).isDisabled(), 'the add button with nothing picked') + await page.getByRole('button', { name: 'Previous page' }).click() + await page.getByText('1–50 of 300').waitFor() + for (const name of ['journey-big/repo-001', 'journey-big/repo-002']) { + await page.getByRole('checkbox', { name }).check() + } + await page.getByText('2 picked').waitFor() + await shot('picked') + await page.getByRole('button', { name: 'Add 2 repositories' }).click() + await page.getByRole('heading', { name: 'Added 2 projects' }).waitFor({ timeout: 30000 }) + await shot('added') + const after = await api(page, `/api/ui/orgs/${org}`) + expect(after.projects.length === 2, `picking two made ${after.projects.length} projects`) + await page.getByRole('button', { name: 'Next: add VisualCI to CI' }).click() + await page.waitForURL((url) => url.pathname === `/${org}`) + await shot('next-step') +}) + +// 9. Uninstalled and installed again (Nathan's case on 3 Dec 2026, a new installation ID): the same organization, its +// projects moved to the new installation, no new organization and no new projects. +await journey('reinstall-keeps-the-organization-and-projects', async ({ page, shot }) => { + await signInAs(page, shot, bigOwner) + const old = (await (await page.request.get(`${GITHUB}/_stub/installations`)).json()).find((i) => i.account.login === 'journey-big' && !i.deleted) + expect(old, 'no installation on journey-big to remove') + await stub(page, '/_stub/uninstall', { id: old.id }) + await stub(page, '/_stub/target', { reuse: old.id }) + const { org, installation } = await install(page) + expect(org === 'journey-big', `installed again, it was set up for ${org}`) + expect(installation !== String(old.id), 'the same installation ID') + const slugs = (await api(page, '/api/ui/me')).organizations.map((o) => o.slug) + expect(!slugs.some((s) => s.startsWith('journey-big-')), `a second organization: ${slugs.join(', ')}`) + const projects = (await api(page, `/api/ui/orgs/${org}`)).projects + expect(projects.length === 2, `${projects.length} projects after installing again`) + await page.getByText('Already a project').first().waitFor() + await shot('picker-after-reinstall') +}) + +// 10. One person, two installations: their own account sets up their own organization, an organization's makes one +// named after it, and each has its own picker. Someone else can't claim the person's installation. +await journey('personal-and-organization-installations', async ({ page, shot }) => { + await signInAs(page, shot, { id: 600002, login: 'journey-solo', name: 'Sol Journey', email: 'solo@journeys.test' }) + const personal = await install(page) + const me = await api(page, '/api/ui/me') + expect(personal.org !== 'journey-team', `own account set up for ${personal.org}`) + await page.getByText('1–3 of 3').waitFor() + await shot('own-account-picker') + await stub(page, '/_stub/target', { account: { id: 880002, login: 'journey-team', type: 'Organization' }, selection: 'selected', count: 5 }) + const team = await install(page) + expect(team.org === 'journey-team', `the organization's installation set up for ${team.org}`) + await page.getByText('1–5 of 5').waitFor() + await shot('organization-picker') + await page.goto(`${APP}/${personal.org}/repositories`) + await page.getByText('1–3 of 3').waitFor() + expect((await page.locator('body').innerText()).includes('journey-solo/repo-001'), `own picker: ${me.email}`) + + // Someone else, signed in, can't set up journey-solo's installation + await stub(page, '/_stub/person', { id: 600003, login: 'journey-other', name: 'Otto Journey', email: 'other@journeys.test' }) + await page.evaluate(() => fetch('/auth/logout', { method: 'POST', headers: { accept: 'application/json' } })) + await page.context().clearCookies() + await signInFromSite(page, shot) + await page.goto(`${APP}/github/setup?installation_id=${personal.installation}&refreshed=1`) + await page.getByText("That installation isn't yours").waitFor() + await shot('not-yours') +}) + +// 11. The App is public: an installation on an account with no VisualCI user stays unclaimed, and its deliveries +// answer 200 without errors (nothing queued to retry). +await journey('strangers-installation-stays-unclaimed', async ({ page }) => { + const account = { id: 990001, login: 'journey-stranger', type: 'User' } + const repo = { id: 990101, full_name: 'journey-stranger/site' } + const deliveries = [ + ['installation', { action: 'created', installation: { id: 99001, account }, repositories: [repo], sender: { id: 990001 } }], + ['push', { ref: 'refs/heads/old', deleted: true, repository: repo, installation: { id: 99001 } }], + ['workflow_run', { action: 'completed', repository: repo, installation: { id: 99001 }, + workflow_run: { head_sha: 'abc', conclusion: 'failure', html_url: 'https://github.com/journey-stranger/site/actions/runs/1' } }], + ['installation_repositories', { action: 'added', installation: { id: 99001, account }, repositories_added: [repo], sender: { id: 990001 } }], + ] + for (const [kind, event] of deliveries) { + const r = await stub(page, '/_stub/webhook', { kind, event }) + expect(r.status === 200, `${kind}: HTTP ${r.status} ${r.body}`) + } + const status = await (await page.request.get(`${APP.replace('app.', 'api.')}/status`)).json() + expect(status.forge_posts_failed === 0 && status.forge_posts_retrying === 0, `forge posts failing: ${JSON.stringify(status)}`) +}) + // 7. With sign-ups closed (VISUALCI_WAITLIST=true, as production runs until launch), someone new signing in from the // site lands on the waitlist page, never in the app. await journey('waitlist-keeps-new-people-out', async ({ page, shot }) => { diff --git a/scripts/screenshots/pages.mjs b/scripts/screenshots/pages.mjs index c00c3a4c..798d0b8d 100644 --- a/scripts/screenshots/pages.mjs +++ b/scripts/screenshots/pages.mjs @@ -35,6 +35,11 @@ export function pages() { ['app/snapshot/text', snapshot('web', 3, 'cli/help.txt'), true, ALL], // The slider view, last of the snapshot pages: a ?mode= link is remembered, like the buttons. ['app/snapshot/slider', async (api) => `${await snapshot('web', 3, 'dashboard/1440-light')(api)}?mode=slider`, true, ALL], + // The repository picker: Acme's 60 repositories (web already a project, some only written to, some archived), a + // search, and side-project's pick half made + ['app/repositories', '/acme/repositories', true, ALL], + ['app/repositories/search', '/acme/repositories?q=pdf', true, ['1440-light', '390-light']], + ['app/repositories/progress', '/side-project/repositories', true, ALL], ['app/billing/team', '/acme/billing', true, ALL], ['app/billing/free', '/side-project/billing', true, ALL], ['app/account', '/account', true, ALL], diff --git a/skills/visualci/SKILL.md b/skills/visualci/SKILL.md index 7a5066ba..5aa075ec 100644 --- a/skills/visualci/SKILL.md +++ b/skills/visualci/SKILL.md @@ -1,6 +1,6 @@ --- name: visualci -description: "Sets up VisualCI, visual regression and snapshot review for PDFs, screenshots, images, JSON, HTML and text: installs the GitHub App (which makes a project per repository) and the CLI, creates a CI token, sends the first build, and picks the visualci-* skill for the user's CI provider and test tools. Use when the user mentions VisualCI, wants visual regression testing, screenshot or PDF comparison, or snapshot changes that wait for review instead of failing CI. Not for a specific CI provider or test tool once VisualCI is set up: use that skill." +description: "Sets up VisualCI, visual regression and snapshot review for PDFs, screenshots, images, JSON, HTML and text: installs the GitHub App (the person picks which repositories become projects) and the CLI, creates a CI token, sends the first build, and picks the visualci-* skill for the user's CI provider and test tools. Use when the user mentions VisualCI, wants visual regression testing, screenshot or PDF comparison, or snapshot changes that wait for review instead of failing CI. Not for a specific CI provider or test tool once VisualCI is set up: use that skill." license: Apache-2.0 metadata: docs: https://visualci.com/docs/quick-start.md @@ -14,9 +14,9 @@ To see what a review looks like first, open the [demo build](https://app.visualc ## 1. Install the GitHub App -Sign in at [app.visualci.com](https://app.visualci.com) with GitHub, then choose **Install on GitHub** in the setup steps and pick the repositories to test. VisualCI makes a project for each repository you can maintain (an admin or maintainer on GitHub), linked to it, so its pull requests get a VisualCI check. Installed on your own account, the projects go into your personal organization; installed on a GitHub organization, into a VisualCI organization named after it, which your teammates join from their permission on the repositories when they sign in. See [Members and access](https://visualci.com/docs/reference/access.md). +Sign in at [app.visualci.com](https://app.visualci.com) with GitHub, then choose **Install on GitHub** in the setup steps and install it on your account or a GitHub organization. Installed on your own account, it's set up for your personal organization; installed on a GitHub organization, for a VisualCI organization named after it, which your teammates join from their permission on the repositories when they sign in. See [Members and access](https://visualci.com/docs/reference/access.md). -Repositories you can't maintain are listed with the reason: ask an admin of the repository to set it up. Already installed the App? The setup steps offer that installation: choose **Set it up**. +Back in VisualCI, pick the repositories to test: search and page through everything the App can reach, even an organization with hundreds of repositories. Each one you pick becomes a project, linked to the repository, so its pull requests get a VisualCI check. You can pick repositories you maintain or administer on GitHub; the others say why not. **Add repositories** on the organization's page picks more later. Already installed the App? The setup steps offer that installation: choose **Set it up**. Then create a project token on the project's **Tokens** tab (the **Add VisualCI to CI** step does it for you). Project tokens start with `vci_`.