diff --git a/app/database/migrations/2026_12_06_000000_organization_settings.rs b/app/database/migrations/2026_12_06_000000_organization_settings.rs new file mode 100644 index 00000000..8fc64d3a --- /dev/null +++ b/app/database/migrations/2026_12_06_000000_organization_settings.rs @@ -0,0 +1,26 @@ +//! The organization's settings page. +//! +//! `setup_shown` replaces `setup_dismissed_at`: whether an admin chose to show (`true`) or hide (`false`) the setup +//! checklist, or nobody has (`NULL`), when it shows until it's complete. A hidden one moves over as `false`. +//! +//! `project_threshold` and `project_comment_when_unchanged` are the settings a new project starts with (the projects +//! table's `threshold` and `comment_when_unchanged`, with the same defaults). Changing them leaves existing projects +//! as they are. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r#" +ALTER TABLE organizations ADD COLUMN setup_shown BOOLEAN; +UPDATE organizations SET setup_shown = false WHERE setup_dismissed_at IS NOT NULL; +ALTER TABLE organizations DROP COLUMN setup_dismissed_at; + +ALTER TABLE organizations + ADD COLUMN project_threshold DOUBLE PRECISION NOT NULL DEFAULT 0 + CHECK (project_threshold >= 0 AND project_threshold <= 1), + ADD COLUMN project_comment_when_unchanged BOOLEAN NOT NULL DEFAULT false; +"#; diff --git a/app/src/auth/invitations.rs b/app/src/auth/invitations.rs index b4635535..a2ed0bc5 100644 --- a/app/src/auth/invitations.rs +++ b/app/src/auth/invitations.rs @@ -24,6 +24,7 @@ pub fn routes(route: &mut Router) { route.delete("/api/ui/orgs/{org}/invitations/{id}", withdraw); route.patch("/api/ui/orgs/{org}/members/{id}", update_member); route.delete("/api/ui/orgs/{org}/members/{id}", remove_member); + route.post("/api/ui/orgs/{org}/leave", leave); } /// Invitation emails an organization may send in a day, and one address may receive from all organizations: inviting, @@ -545,6 +546,36 @@ pub async fn remove_member( Ok(Json(json!({ "members": members_json(org_id, true).await? }))) } +/// `POST /api/ui/orgs/{org}/leave` (any member): leave the organization. Refused for the person's own organization +/// (made at sign-up), for access the forge decides (it would come back at their next sign-in), and for its last admin. +pub async fn leave( + Authenticated(user): Authenticated, + Params(org): Params, +) -> laravel::Result> { + let (org_id, _, _) = org_role(&user, &org).await?; + let user_id = user.id; + let row = db::query!( + "SELECT m.source, u.personal_organization_id = {org_id} AS personal FROM memberships m \ + JOIN users u ON u.id = m.user_id WHERE m.organization_id = {org_id} AND m.user_id = {user_id}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + if row.try_get::>("personal")?.unwrap_or(false) { + return Err(laravel::abort_with(422, "this is your own organization: you can't leave it")); + } + if let Some(forge) = ForgeKind::parse(&row.try_get::("source")?) { + return Err(laravel::abort_with( + 422, + format!("your access comes from {}: it follows your permission on the repository there", forge.label()), + )); + } + if !change_member(org_id, user_id, None).await? { + return Err(laravel::abort_with(422, "the organization needs another admin first")); + } + Ok(Json(json!({ "ok": true }))) +} + #[cfg(test)] mod tests { use super::*; diff --git a/app/src/auth/orgs.rs b/app/src/auth/orgs.rs index 2297f70f..45660584 100644 --- a/app/src/auth/orgs.rs +++ b/app/src/auth/orgs.rs @@ -13,6 +13,7 @@ use crate::models::{Build, Organization, User}; pub fn routes(route: &mut Router) { route.post("/api/ui/orgs", create); route.get("/api/ui/orgs/{org}", show); + route.patch("/api/ui/orgs/{org}", update); route.get("/api/ui/org-exists/{slug}", exists); } @@ -158,7 +159,8 @@ async fn usage_by_project(org_id: i64) -> laravel::Result> { /// `GET /api/ui/orgs/{org}`: the organization's page for a member: its projects with their newest build, the last 50 /// charges, this month's usage (in all and by project), its members, and for admins its billing email and pending -/// invitations. Self-managed GitLab is off until sc-8634, so its section is empty and hidden. +/// invitations; for its settings page, whether it's the person's own (made at sign-up) and where their access comes from, the settings new projects +/// start with and its GitHub App installations. Self-managed GitLab is off until sc-8634, so its section is empty and hidden. pub async fn show( Authenticated(user): Authenticated, Params(org): Params, @@ -195,6 +197,14 @@ pub async fn show( }) .collect::>()?; let invitations = if admin { super::invitations::pending(org_id).await? } else { Vec::new() }; + let user_id = user.id; + let mine = db::query!( + "SELECT u.personal_organization_id IS NOT DISTINCT FROM {org_id} AS personal, m.source FROM users u \ + JOIN memberships m ON m.user_id = u.id AND m.organization_id = {org_id} WHERE u.id = {user_id}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; Ok(Json(json!({ "slug": org.slug, "name": org.name, "role": role.as_str(), "usage": crate::domain::credits::usage(&org).await?, @@ -203,6 +213,86 @@ pub async fn show( "projects": list, "history": history, "usage_by_project": usage_by_project(org_id).await?, "members": super::invitations::members_json(org_id, admin).await?, "invitations": invitations, "setup": super::setup::state(org_id, Some(user.pid)).await?, + "personal": mine.try_get::("personal")?, + "source": mine.try_get::("source")?, + "project_defaults": { + "threshold": org.project_threshold, "comment_when_unchanged": org.project_comment_when_unchanged, + }, + "github_installations": installations(org_id).await?, "gitlab_instances": [], "gitlab_instances_enabled": false, }))) } + +/// The GitHub App's installations set up for an organization, for its settings page: the account, whether it's a +/// person's or a GitHub organization's, and how many repositories its projects link through it. +async fn installations(org_id: i64) -> laravel::Result> { + let rows = db::query!( + "SELECT g.installation_id, g.account_login, g.account_type, g.suspended_at IS NOT NULL AS suspended, \ + (SELECT count(DISTINCT p.repository_id) FROM projects p \ + WHERE p.organization_id = {org_id} AND p.forge_installation = g.installation_id)::bigint AS repositories \ + FROM github_installations g WHERE g.organization_id = {org_id} AND g.deleted_at IS NULL \ + ORDER BY lower(g.account_login)" + ) + .select() + .await?; + rows.iter() + .map(|r| { + Ok(json!({ + "installation_id": r.try_get::("installation_id")?, + "account_login": r.try_get::("account_login")?, + "account_type": r.try_get::("account_type")?, + "suspended": r.try_get::("suspended")?, + "repositories": r.try_get::("repositories")?, + })) + }) + .collect() +} + +#[laravel::input] +#[validate(authenticated)] +pub struct UpdateInput { + /// The organization's display name. + name: Option, + /// The diff threshold a new project starts with, 0 to 1. + project_threshold: Option, + /// Whether a new project comments on pull requests whose builds are unchanged. + project_comment_when_unchanged: Option, +} + +/// `PATCH /api/ui/orgs/{org}` (admins): its name and the settings new projects start with; fields left out stay as +/// they are. Existing projects keep their own settings. +pub async fn update( + Authenticated(user): Authenticated, + Params(slug): Params, + Valid(p): Valid, +) -> laravel::Result> { + let (org_id, _, role) = super::invitations::org_role(&user, &slug).await?; + if role < Role::Admin { + return Err(laravel::abort_with(403, "only admins can change the organization's settings")); + } + let name = p.name.as_deref().map(str::trim).map(str::to_string); + if let Some(name) = &name + && (name.is_empty() || name.chars().count() > MAX_NAME) + { + return Err(laravel::abort_with(422, format!("an organization's name is 1 to {MAX_NAME} characters"))); + } + if p.project_threshold.is_some_and(|t| !(0.0..=1.0).contains(&t)) { + return Err(laravel::abort_with(422, "threshold must be between 0 and 1")); + } + let (threshold, comment) = (p.project_threshold, p.project_comment_when_unchanged); + db::query!( + "UPDATE organizations SET name = COALESCE({name}, name), \ + project_threshold = COALESCE({threshold}, project_threshold), \ + project_comment_when_unchanged = COALESCE({comment}, project_comment_when_unchanged), \ + updated_at = now() WHERE id = {org_id}" + ) + .update() + .await?; + let org = Organization::find_or_fail(org_id).await?; + Ok(Json(json!({ + "slug": org.slug, "name": org.name, + "project_defaults": { + "threshold": org.project_threshold, "comment_when_unchanged": org.project_comment_when_unchanged, + }, + }))) +} diff --git a/app/src/auth/setup.rs b/app/src/auth/setup.rs index 2feb0ce6..0ef42e90 100644 --- a/app/src/auth/setup.rs +++ b/app/src/auth/setup.rs @@ -1,5 +1,6 @@ //! The "Set up VisualCI" checklist (sc-8900, ported from today's server): each step ticks itself from what has actually -//! happened, with no "mark done". An organization's admins can close it, or open it again. +//! happened, with no "mark done". It shows until it's complete; an organization's admins can hide it or show it again +//! at any time, complete or not (`organizations.setup_shown`, `NULL` until one of them chooses). use laravel::auth::Authenticated; use laravel::db; @@ -19,7 +20,8 @@ pub const STEPS: &[&str] = &["install_github_app", "connect_agent", "add_to_ci", /// The checklist for an organization as `user_pid` sees it (a connected agent is per person: an MCP connection, or a /// personal token that has been used; with no person, such as a project token, it isn't done): each step and whether -/// it's done, the next one, whether it's complete (a build has been approved) and whether someone closed it. Callers +/// it's done, the next one, whether it's complete (a build has been approved) and whether it shows: an admin's choice, +/// else until it's complete. Callers /// check first that the person may see the organization: this reads it as asked. /// /// # Errors @@ -40,7 +42,7 @@ pub async fn state(org_id: i64, user_pid: Option) -> laravel WHERE p.organization_id = {org_id} AND b.mode = 'ci') AS add_to_ci, \ EXISTS (SELECT 1 FROM reviews r JOIN builds b ON b.id = r.build_id JOIN projects p ON p.id = b.project_id \ WHERE p.organization_id = {org_id} AND r.action = 'approve') AS review_changes, \ - (SELECT setup_dismissed_at IS NOT NULL FROM organizations WHERE id = {org_id}) AS dismissed" + (SELECT setup_shown FROM organizations WHERE id = {org_id}) AS shown" ) .select_one() .await? @@ -83,7 +85,7 @@ pub async fn state(org_id: i64, user_pid: Option) -> laravel "steps": steps.iter().map(|(key, done)| json!({ "key": key, "done": done })).collect::>(), "next": next, "complete": complete, - "dismissed": row.try_get::>("dismissed")?.unwrap_or(false), + "shown": row.try_get::>("shown")?.unwrap_or(!complete), "install_url": "/github/install", "installations": offers, // How the listing after their last GitHub sign-in is going (`sign_in_sync::State`): the offers above wait for it @@ -95,10 +97,10 @@ pub async fn state(org_id: i64, user_pid: Option) -> laravel #[laravel::input] #[validate(authenticated)] pub struct SetupInput { - dismissed: bool, + shown: bool, } -/// `POST /api/ui/orgs/{org}/setup` (admins): close the checklist, or open it again. +/// `POST /api/ui/orgs/{org}/setup` (admins): show the checklist or hide it, complete or not. pub async fn update( Authenticated(user): Authenticated, Params(org): Params, @@ -118,12 +120,9 @@ pub async fn update( Some(_) => return Err(laravel::abort_with(403, "only admins can change the setup checklist")), None => return Err(laravel::abort(404)), } - let dismissed = p.dismissed; - db::query!( - "UPDATE organizations SET setup_dismissed_at = CASE WHEN {dismissed} THEN now() END, updated_at = now() \ - WHERE id = {org_id}" - ) - .update() - .await?; + let shown = p.shown; + db::query!("UPDATE organizations SET setup_shown = {shown}, updated_at = now() WHERE id = {org_id}") + .update() + .await?; Ok(Json(state(org_id, Some(user.pid)).await?)) } diff --git a/app/src/domain/projects.rs b/app/src/domain/projects.rs index cd59413b..76616648 100644 --- a/app/src/domain/projects.rs +++ b/app/src/domain/projects.rs @@ -41,14 +41,17 @@ pub fn renderer_key(engine: &str, dpi: i32, renderer_version: &str) -> String { format!("{engine}/{dpi}dpi/{renderer_version}") } -/// Lowercase letters, digits and dashes, at most 60, and not `billing` (the organization's billing page is -/// `app.visualci.com//billing`). +/// The organization's own pages under `app.visualci.com//`, which a project's slug can't take. +pub const RESERVED_SLUGS: &[&str] = &["billing", "repositories", "settings"]; + +/// Lowercase letters, digits and dashes, at most 60, and not one of the organization's own pages +/// ([`RESERVED_SLUGS`]). #[must_use] pub fn valid_slug(s: &str) -> bool { !s.is_empty() && s.len() <= 60 && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') - && s != "billing" + && !RESERVED_SLUGS.contains(&s) } /// A project's settings, as the web app shows them and the MCP server returns them. @@ -189,7 +192,8 @@ pub enum Refused { } /// The message for a slug that isn't valid. -pub const INVALID_SLUG: &str = "project slugs use lowercase letters, digits and dashes, and can't be billing"; +pub const INVALID_SLUG: &str = + "project slugs use lowercase letters, digits and dashes, and can't be billing, repositories or settings"; /// Whether a database error is a unique violation (PostgreSQL's 23505): a row another request inserted first. #[must_use] @@ -198,7 +202,7 @@ pub fn is_unique_violation(e: &laravel::Error) -> bool { text.contains("23505") || text.contains("duplicate key value violates unique constraint") } -/// Make a project in an organization, with the default settings. +/// Make a project in an organization, with the organization's settings for new projects. /// /// # Errors /// `Ok(Err(_))` for a slug that isn't valid or is taken; `Err` on a database error. @@ -212,11 +216,15 @@ pub async fn create(organization_id: i64, slug: &str, name: &str) -> laravel::Re return Ok(Err(Refused::Taken)); } let name = name.trim(); + // It starts with the organization's defaults for new projects + let org = crate::models::Organization::find_or_fail(organization_id).await?; match laravel::model::create!(Project { pid: laravel::str::uuid7(), organization_id: organization_id, slug: slug, name: name, + threshold: org.project_threshold, + comment_when_unchanged: org.project_comment_when_unchanged, }) .await { diff --git a/app/src/models/organizations.rs b/app/src/models/organizations.rs index cf0cb8f3..f422d20c 100644 --- a/app/src/models/organizations.rs +++ b/app/src/models/organizations.rs @@ -22,9 +22,15 @@ pub struct Organization { pub reload_started_at: Option, pub billing_problem: Option, pub reloads_paused_at: Option, - pub setup_dismissed_at: Option, pub billing_email: Option, pub stripe_event_at: Option, + /// An admin's choice to show or hide the setup checklist; `None` shows it until it's complete. + pub setup_shown: Option, + /// The diff threshold and the unchanged-PR comment a new project starts with. + #[default] + pub project_threshold: f64, + #[default] + pub project_comment_when_unchanged: bool, } /// Paths an organization's slug can't take. diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json index 041e1d5c..9f990d26 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", "type": "text" } ], @@ -43,12 +43,12 @@ "role": "admin", "setup": { "complete": false, - "dismissed": false, "github": [], "github_sync": "done", "install_url": "/github/install", "installations": [], "next": "install_github_app", + "shown": true, "steps": [ { "done": false, diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json index ab688bfb..1a31f1cb 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"via\":{\"source\":\"personal_token\",\"token_name\":\"agent\"},\"waiting_for_review\":[]}", + "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"via\":{\"source\":\"personal_token\",\"token_name\":\"agent\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -24,12 +24,12 @@ "role": "admin", "setup": { "complete": false, - "dismissed": false, "github": [], "github_sync": "done", "install_url": "/github/install", "installations": [], "next": "install_github_app", + "shown": true, "steps": [ { "done": false, diff --git a/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json b/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json index 7f08643d..ca990893 100644 --- a/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json +++ b/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"}],\"role\":\"project\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"}],\"role\":\"project\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", "type": "text" } ], @@ -25,12 +25,12 @@ "role": "project", "setup": { "complete": false, - "dismissed": false, "github": [], "github_sync": "done", "install_url": "/github/install", "installations": [], "next": "install_github_app", + "shown": true, "steps": [ { "done": false, diff --git a/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json b/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json index 70b82653..b0959df4 100644 --- a/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json +++ b/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"auto_approved\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":1,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":1,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]},\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":1,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[{\"created_at\":\"\",\"credits\":1,\"kind\":\"build\",\"reference\":\"build pdfs/1: 1 snapshot checked\"}]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"auto_approved\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":1,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":1,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]},\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":1,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[{\"created_at\":\"\",\"credits\":1,\"kind\":\"build\",\"reference\":\"build pdfs/1: 1 snapshot checked\"}]}", "type": "text" } ], @@ -77,12 +77,12 @@ "role": "admin", "setup": { "complete": false, - "dismissed": false, "github": [], "github_sync": "done", "install_url": "/github/install", "installations": [], "next": "install_github_app", + "shown": true, "steps": [ { "done": false, diff --git a/app/tests/org_settings.rs b/app/tests/org_settings.rs new file mode 100644 index 00000000..c12fbe68 --- /dev/null +++ b/app/tests/org_settings.rs @@ -0,0 +1,135 @@ +//! The organization's settings page: admins rename it and set what new projects start with, members read it, anyone +//! outside gets a 404; members leave, except from their own organization, access the forge decides, or as its last +//! admin. + +use app::models::User; +use app::testing::fixtures; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +async fn person(name: &str, email: &str) -> laravel::Result { + create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await +} + +async fn role_of(org: i64, user: &User) -> laravel::Result> { + let id = user.id; + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {id}").scalar().await +} + +#[laravel::test] +async fn admins_change_the_settings_and_new_projects_start_with_them(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + let bob = person("Bob", "bob@example.com").await?; + let eve = person("Eve", "eve@example.com").await?; + let org = fixtures::organization("acme").await?; + fixtures::member(&org, &ada, "admin").await?; + fixtures::member(&org, &bob, "member").await?; + let before = fixtures::project(&org, "old").await?; + let patch = |user: &User, body: serde_json::Value| { + app.patch("/api/ui/orgs/acme").acting_as(user).header("sec-fetch-site", "same-origin").json(body) + }; + + patch(&eve, json!({ "name": "Evil" })).await.assert_status(404); + patch(&bob, json!({ "name": "Bob's" })).await.assert_status(403); + patch(&ada, json!({ "name": "x".repeat(101) })).await.assert_status(422); + patch(&ada, json!({ "project_threshold": 1.5 })).await.assert_status(422); + patch(&ada, json!({ "name": " Acme Ltd ", "project_threshold": 0.1, "project_comment_when_unchanged": true })) + .await + .assert_ok() + .assert_json_path("name", "Acme Ltd") + .assert_json_path("slug", "acme") + .assert_json_path("project_defaults.threshold", 0.1) + .assert_json_path("project_defaults.comment_when_unchanged", true); + // Fields left out stay as they are + patch(&ada, json!({ "project_comment_when_unchanged": false })) + .await + .assert_ok() + .assert_json_path("name", "Acme Ltd") + .assert_json_path("project_defaults.threshold", 0.1); + + // Members read them; the page also names its installations + let org_id = org.id; + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type, organization_id) \ + VALUES ('77', '1', 'acme-gh', 'Organization', {org_id})" + ) + .insert() + .await?; + db::query!( + "UPDATE projects SET forge = 'github', forge_installation = '77', repository_id = '501' WHERE organization_id = {org_id}" + ) + .update() + .await?; + app.get("/api/ui/orgs/acme") + .acting_as(&bob) + .await + .assert_ok() + .assert_json_path("name", "Acme Ltd") + .assert_json_path("personal", false) + .assert_json_path("project_defaults.threshold", 0.1) + .assert_json_path("github_installations.0.account_login", "acme-gh") + .assert_json_path("github_installations.0.account_type", "Organization") + .assert_json_path("github_installations.0.repositories", 1); + + // A project made now starts with the defaults; the one made before keeps its own + let Ok(new) = app::domain::projects::create(org_id, "new", "New").await? else { panic!("not created") }; + assert!((new.threshold - 0.1).abs() < f64::EPSILON, "{}", new.threshold); + assert!(!new.comment_when_unchanged); + let old = app::models::Project::find_or_fail(before.id).await?; + assert!(old.threshold.abs() < f64::EPSILON, "{}", old.threshold); + // The organization's own pages aren't project slugs + for slug in ["settings", "repositories", "billing"] { + assert!(app::domain::projects::create(org_id, slug, slug).await?.is_err(), "{slug}"); + } + Ok(()) +} + +#[laravel::test] +async fn members_leave_but_not_their_own_organization_forge_access_or_as_the_last_admin( + app: Application, +) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + let bob = person("Bob", "bob@example.com").await?; + let linus = person("Linus", "linus@example.com").await?; + let eve = person("Eve", "eve@example.com").await?; + let org = fixtures::organization("acme").await?; + fixtures::member(&org, &ada, "admin").await?; + fixtures::member(&org, &bob, "member").await?; + let (org_id, linus_id) = (org.id, linus.id); + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org_id}, {linus_id}, 'admin', 'github', now(), now())" + ) + .insert() + .await?; + let leave = |user: &User, slug: &str| { + app.post(format!("/api/ui/orgs/{slug}/leave")) + .acting_as(user) + .header("sec-fetch-site", "same-origin") + .json(json!({})) + }; + + leave(&eve, "acme").await.assert_status(404); + // Access from GitHub follows the repository: leaving would undo itself at the next sign-in + leave(&linus, "acme").await.assert_status(422); + leave(&bob, "acme").await.assert_ok(); + assert_eq!(role_of(org_id, &bob).await?, None); + // Ada is the only admin by invitation or creation, but Linus is an admin too: she can go + leave(&ada, "acme").await.assert_ok(); + + // The last admin can't leave + let solo = fixtures::organization("solo").await?; + fixtures::member(&solo, &ada, "admin").await?; + leave(&ada, "solo").await.assert_status(422); + + // Nor can anyone leave their own organization + let own = fixtures::organization("bobs").await?; + fixtures::member(&own, &bob, "member").await?; + fixtures::member(&own, &eve, "admin").await?; + let (own_id, bob_id) = (own.id, bob.id); + db::query!("UPDATE users SET personal_organization_id = {own_id} WHERE id = {bob_id}").update().await?; + leave(&bob, "bobs").await.assert_status(422); + app.get("/api/ui/orgs/bobs").acting_as(&bob).await.assert_ok().assert_json_path("personal", true); + Ok(()) +} diff --git a/app/tests/setup.rs b/app/tests/setup.rs index d34aaa76..9810c706 100644 --- a/app/tests/setup.rs +++ b/app/tests/setup.rs @@ -47,13 +47,51 @@ async fn the_checklist_follows_what_happened(app: Application) -> laravel::Resul assert_eq!(state["next"], "add_to_ci"); assert_eq!(state["complete"], false); - let close = |dismissed: bool| { + assert_eq!(state["shown"], true, "shown until it's complete"); + + let show = |user: &User, shown: bool| { app.post("/api/ui/orgs/acme/setup") - .acting_as(&ada) + .acting_as(user) .header("sec-fetch-site", "same-origin") - .json(json!({ "dismissed": dismissed })) + .json(json!({ "shown": shown })) }; - close(true).await.assert_ok().assert_json_path("dismissed", true); - close(false).await.assert_ok().assert_json_path("dismissed", false); + show(&ada, false).await.assert_ok().assert_json_path("shown", false); + show(&ada, true).await.assert_ok().assert_json_path("shown", true); + // Only admins choose; anyone outside gets a 404 + let bob = create!(User { pid: laravel::str::uuid7(), name: "Bob", email: "bob@example.com", staff: false }).await?; + let eve = create!(User { pid: laravel::str::uuid7(), name: "Eve", email: "eve@example.com", staff: false }).await?; + let bob_id = bob.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {bob_id}, 'member', 'invite', now(), now())" + ) + .insert() + .await?; + show(&bob, false).await.assert_status(403); + show(&eve, false).await.assert_status(404); + + // Complete: hidden by default, every step ticked, and an admin can show it again + db::query!("UPDATE organizations SET setup_shown = NULL WHERE id = {org}").update().await?; + let project: i64 = db::query!("SELECT id FROM projects WHERE organization_id = {org}").scalar().await?.unwrap(); + let build: i64 = db::query!( + "INSERT INTO builds (pid, project_id, number, mode, branch, commit_sha, created_at, updated_at) \ + VALUES (gen_random_uuid(), {project}, 1, 'ci', 'main', 'abc', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + db::query!( + "INSERT INTO reviews (build_id, user_id, action, created_at, updated_at) \ + VALUES ({build}, {ada_id}, 'approve', now(), now())" + ) + .insert() + .await?; + let state = app::auth::setup::state(org, Some(ada.pid)).await?; + assert_eq!(state["complete"], true); + assert_eq!(state["next"], json!(null)); + assert!(state["steps"].as_array().unwrap().iter().all(|s| s["done"] == true), "{}", state["steps"]); + assert_eq!(state["shown"], false, "hidden once complete"); + show(&ada, true).await.assert_ok().assert_json_path("shown", true).assert_json_path("complete", true); + show(&ada, false).await.assert_ok().assert_json_path("shown", false); Ok(()) } diff --git a/docs/design.md b/docs/design.md index 42dfbac4..b0e27a0a 100644 --- a/docs/design.md +++ b/docs/design.md @@ -409,7 +409,10 @@ retry when it failed or took over 90 s (`POST /api/ui/github/sync`, or a new sig 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`, `connect_agent`, `add_to_ci`, `review_changes`: the coding agent comes before CI because it adds VisualCI to CI, from a prompt the step pre-fills for the project) offers -installations the person can reach that aren't set up yet (`POST /api/ui/installations/{id}/setup`). +installations the person can reach that aren't set up yet (`POST /api/ui/installations/{id}/setup`). It shows until +it's complete (a build approved); an admin can hide it or show it again at any time, complete or not, from the +organization's page or its settings (`organizations.setup_shown`: `NULL` until an admin chooses, then `true` or +`false`), and a complete one shows every step ticked. **A public App: bounded work for strangers (sc-9144, sc-9124).** Anyone can install the GitHub App, so its webhook must stay cheap when strangers' installations flood it. `/webhooks/github` refuses a missing or malformed @@ -530,6 +533,16 @@ records its **source**: Forge-derived rows never overwrite the other sources: someone invited or added by staff keeps that role. +**Organization settings** (`//settings`): every member reads them, admins change them. The display name (the +slug never changes); the setup checklist shown or hidden; members (invite, change a role, remove: never the last +admin, never a forge-derived membership); the GitHub App's installations with a link to manage each on GitHub; the +settings a new project starts with (`organizations.project_threshold` and `project_comment_when_unchanged`, copied +when the project is made; existing projects keep their own); the billing email (admins); and leaving +(`POST /api/ui/orgs/{org}/leave`), refused for the person's own organization, for a forge-derived membership (it would +come back at the next sign-in) and for the last admin. Deleting an organization stays with staff +(the `org:delete` console command, which refuses one with projects or billing history). Project slugs can't take the +organization's own pages (`billing`, `repositories`, `settings`). + **Keeping in step.** A sign-in recomputes the person's forge memberships from what the forge says they can reach (GitHub: the user's App installations and their repositories' permissions). The forge's webhooks recompute the people they name (GitHub: `member`, `membership`, `organization`, `team`), and the hourly forge sync (`app/src/forge/sync.rs`) rechecks diff --git a/frontend/src/__tests__/menu.test.tsx b/frontend/src/__tests__/menu.test.tsx index 51a5ffbe..78c77e16 100644 --- a/frontend/src/__tests__/menu.test.tsx +++ b/frontend/src/__tests__/menu.test.tsx @@ -36,7 +36,7 @@ describe('the account menu', () => { const menu = container.querySelector('details.menu') as HTMLDetailsElement const items = Array.from(container.querySelectorAll('.menu-item')) expect(items.map((i) => i.textContent?.trim())).toEqual( - expect.arrayContaining(['Acme', 'Other', 'All organizations', 'Add a GitHub organization', 'Account and tokens', 'Billing', 'Sign out']), + expect.arrayContaining(['Acme', 'Other', 'All organizations', 'Add a GitHub organization', 'Account and tokens', 'Billing', 'Settings', 'Sign out']), ) for (const item of items) { menu.open = true diff --git a/frontend/src/__tests__/org-settings.test.ts b/frontend/src/__tests__/org-settings.test.ts new file mode 100644 index 00000000..d03352ae --- /dev/null +++ b/frontend/src/__tests__/org-settings.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest' +import type { Member } from '../api/types' +import { githubManageUrl, leaveRefusal, parseThreshold } from '../lib/orgSettings' + +const member = (role: Member['role']): Member => ({ + id: role + Math.random(), + name: role, + email: '', + avatar_url: null, + login: null, + identities: [], + role, + source: 'invite', + synced_at: null, + since: '2026-12-01T00:00:00Z', +}) + +describe('organization settings', () => { + it('links an installation to where GitHub manages it', () => { + expect(githubManageUrl({ installation_id: '42', account_login: 'acme', account_type: 'Organization' })).toBe( + 'https://github.com/organizations/acme/settings/installations/42', + ) + expect(githubManageUrl({ installation_id: '7', account_login: 'ada', account_type: 'User' })).toBe( + 'https://github.com/settings/installations/7', + ) + }) + + it('says why someone can’t leave', () => { + const base = { personal: false, source: 'invite' as const, role: 'member' as const, members: [member('admin'), member('member')] } + expect(leaveRefusal(base)).toBeNull() + expect(leaveRefusal({ ...base, personal: true })).toMatch(/your own/) + expect(leaveRefusal({ ...base, source: 'github' })).toMatch(/GitHub/) + expect(leaveRefusal({ ...base, role: 'admin' })).toMatch(/someone else an admin/) + expect(leaveRefusal({ ...base, role: 'admin', members: [member('admin'), member('admin')] })).toBeNull() + }) + + it('reads a threshold from 0 to 1', () => { + expect(parseThreshold('0')).toBe(0) + expect(parseThreshold('0.25')).toBe(0.25) + for (const bad of ['', ' ', '1.5', '-0.1', 'abc']) expect(parseThreshold(bad), bad).toBeNull() + }) +}) diff --git a/frontend/src/api/hooks.ts b/frontend/src/api/hooks.ts index e274a4c4..e8aa5104 100644 --- a/frontend/src/api/hooks.ts +++ b/frontend/src/api/hooks.ts @@ -458,12 +458,42 @@ export function useStaffSignups() { }) } -/** Close the setup checklist, or open it again. */ +/** Show the setup checklist or hide it, complete or not. */ export function useUpdateSetup(org: string) { const qc = useQueryClient() return useMutation({ - mutationFn: (dismissed: boolean) => post(`${orgPath(org)}/setup`, { dismissed }), - onSuccess: () => qc.invalidateQueries({ queryKey: keys.org(org) }), + mutationFn: (shown: boolean) => post(`${orgPath(org)}/setup`, { shown }), + // The answer is the checklist as it is now: shown at once, before the page's refetch + onSuccess: (setup) => { + qc.setQueryData(keys.org(org), (o) => (o ? { ...o, setup } : o)) + qc.invalidateQueries({ queryKey: keys.org(org) }) + }, + }) +} + +export type OrgChange = { name?: string; project_threshold?: number; project_comment_when_unchanged?: boolean } + +/** Rename the organization, or change the settings new projects start with (admins). */ +export function useUpdateOrg(org: string) { + const qc = useQueryClient() + return useMutation({ + mutationFn: (change: OrgChange) => patch(orgPath(org), change), + onSuccess: () => { + qc.invalidateQueries({ queryKey: keys.org(org) }) + qc.invalidateQueries({ queryKey: keys.me }) + }, + }) +} + +/** Leave the organization. */ +export function useLeaveOrg(org: string) { + const qc = useQueryClient() + return useMutation({ + mutationFn: () => post(`${orgPath(org)}/leave`, {}), + onSuccess: () => { + qc.removeQueries({ queryKey: keys.org(org) }) + qc.invalidateQueries({ queryKey: keys.me }) + }, }) } diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index 613386cd..3e9bd05f 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -180,7 +180,8 @@ export type Setup = { next: SetupStepKey | null /** A build has been reviewed. */ complete: boolean - dismissed: boolean + /** Whether it shows: an admin's choice, else until it's complete. */ + shown: boolean /** Where to install the GitHub App. */ install_url: string /** The person's installations of the App. */ @@ -272,6 +273,24 @@ export type Org = OrgSummary & { gitlab_instances: GitlabInstance[] /** Whether this server can add them (it has a key to store their secrets with). */ gitlab_instances_enabled: boolean + /** The person's own organization, made at sign-up: they can't leave it. */ + personal: boolean + /** Where the person's own access comes from. */ + source: MemberSource + /** The settings a new project starts with. */ + project_defaults: { threshold: number; comment_when_unchanged: boolean } + /** The GitHub App's installations set up for it. */ + github_installations: GithubInstallation[] +} + +export type GithubInstallation = { + installation_id: string + account_login: string + /** `User` or `Organization`. */ + account_type: string + suspended: boolean + /** Repositories its projects link through it. */ + repositories: number } export type GitlabInstance = { diff --git a/frontend/src/components/AppShell.tsx b/frontend/src/components/AppShell.tsx index 15a6fda8..04588cf4 100644 --- a/frontend/src/components/AppShell.tsx +++ b/frontend/src/components/AppShell.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, type MouseEvent, type ReactNode } from 'react' import { Link, Outlet, useNavigate, useParams } from '@tanstack/react-router' -import { ChatTextIcon, CreditCardIcon, GithubLogoIcon, KeyIcon, MonitorIcon, MoonIcon, PaperPlaneTiltIcon, SignOutIcon, SunIcon, UsersIcon } from '@phosphor-icons/react' +import { ChatTextIcon, CreditCardIcon, GearSixIcon, GithubLogoIcon, KeyIcon, MonitorIcon, MoonIcon, PaperPlaneTiltIcon, SignOutIcon, SunIcon, UsersIcon } from '@phosphor-icons/react' import { useInvitationAnswer, useLogout, useMe, useProject, useSnapshot } from '../api/hooks' import { errorMessage } from '../api/client' import { useTheme, type ThemePref } from '../lib/theme' @@ -42,6 +42,19 @@ function billingOrg(me: NonNullable['data']>, current: return admin(current) ?? admin(last) ?? me.organizations.find((o) => o.role === 'admin')?.slug } +/** The organization whose settings the menu's Settings link opens: the one on screen, else the last one visited, else + * the first. Every member sees them; only admins change them. */ +function settingsOrg(me: NonNullable['data']>, current: string | undefined): string | undefined { + const mine = (slug: string | null | undefined) => (slug ? me.organizations.find((o) => o.slug === slug)?.slug : undefined) + let last: string | null = null + try { + last = window.localStorage.getItem('vci-last-org') + } catch { + // Storage blocked: fall through. + } + return mine(current) ?? mine(last) ?? me.organizations[0]?.slug +} + export function UserMenu() { const me = useMe().data const logout = useLogout() @@ -57,6 +70,7 @@ export function UserMenu() { const menu = useRef(null) if (!me) return null const billing = billingOrg(me, current) + const settings = settingsOrg(me, current) // Any item closes the menu, including a link to the page already open (which doesn't navigate). const close = (e: MouseEvent) => { if ((e.target as Element).closest('.menu-item')) menu.current?.removeAttribute('open') @@ -94,6 +108,11 @@ export function UserMenu() { Billing )} + {settings && ( + + Settings + + )} Ask for something @@ -253,13 +272,16 @@ function DemoBanner() { ) } +/** An organization's own pages, which no project's slug can take. */ +const ORG_PAGES = new Set(['billing', 'repositories', 'settings']) + /** Top-level paths that are pages of their own, not organizations. */ const NOT_ORGS = new Set(['account', 'staff', 'device', 'oauth', 'g']) /** The project a path is in (`/acme/web/builds/3` → acme/web), for letting signed-out visitors see public projects. */ export function projectOfPath(path: string): { org: string; project: string } | null { const [org, project] = path.split('/').filter(Boolean) - if (!org || !project || NOT_ORGS.has(org) || project === 'billing') return null + if (!org || !project || NOT_ORGS.has(org) || ORG_PAGES.has(project)) return null return { org, project } } diff --git a/frontend/src/components/Logo.tsx b/frontend/src/components/Logo.tsx index 98bc2232..14376508 100644 --- a/frontend/src/components/Logo.tsx +++ b/frontend/src/components/Logo.tsx @@ -1,4 +1,5 @@ -import { Link } from '@tanstack/react-router' +import { Link, useRouterState } from '@tanstack/react-router' +import { siteUrl } from '../lib/hosts' /** Two offset pages: base and head. */ export function Mark({ size = 20 }: { size?: number }) { @@ -10,24 +11,40 @@ export function Mark({ size = 20 }: { size?: number }) { ) } -/** `plain`: an ordinary link, for the prerendered landing page, which has no router. */ -export function Logo({ plain = false }: { plain?: boolean }) { - const inner = ( +function Inner() { + return ( <> VisualCI ) +} + +/** `plain`: an ordinary link, for the prerendered landing page, which has no router. */ +export function Logo({ plain = false }: { plain?: boolean }) { if (plain) { return ( - {inner} + + + ) + } + return +} + +/** In the app: back to the app's home, and from the app's home on to the site. */ +function AppLogo() { + const home = useRouterState({ select: (s) => s.location.pathname === '/' }) + if (home) { + return ( + + ) } return ( - {inner} + ) } diff --git a/frontend/src/components/SetupChecklist.tsx b/frontend/src/components/SetupChecklist.tsx index cc6e0427..26692737 100644 --- a/frontend/src/components/SetupChecklist.tsx +++ b/frontend/src/components/SetupChecklist.tsx @@ -90,6 +90,13 @@ function InstallGithubApp({ org, data, onCreateProject }: { org: string; data: O your code. + {setup.github.length > 0 && ( +

+ + Manage installations + +

+ )} {elsewhere.length > 0 && ( // Installations set up in other organizations: for reference, below this step's action
@@ -331,9 +338,11 @@ export function SetupChecklist({

Set up VisualCI {doneCount} of {setup.steps.length}

- + {data.role === 'admin' && ( + + )}
{just && (

diff --git a/frontend/src/lib/orgSettings.ts b/frontend/src/lib/orgSettings.ts new file mode 100644 index 00000000..fd81f0a3 --- /dev/null +++ b/frontend/src/lib/orgSettings.ts @@ -0,0 +1,25 @@ +import type { GithubInstallation, Org } from '../api/types' +import { isForge } from './forges' + +/** Where an installation of the GitHub App is managed on GitHub: a person's own settings, or the organization's. */ +export function githubManageUrl(i: Pick): string { + const id = encodeURIComponent(i.installation_id) + return i.account_type === 'Organization' + ? `https://github.com/organizations/${encodeURIComponent(i.account_login)}/settings/installations/${id}` + : `https://github.com/settings/installations/${id}` +} + +/** Why the person can't leave the organization, or `null` when they can (the server checks the same). */ +export function leaveRefusal(o: Pick): string | null { + if (o.personal) return 'It’s your own organization.' + if (isForge(o.source)) return 'Your access follows your permission on its repositories on GitHub.' + if (o.role === 'admin' && o.members.filter((m) => m.role === 'admin').length <= 1) return 'Make someone else an admin first.' + return null +} + +/** A threshold typed into the form: a number from 0 to 1, or `null`. */ +export function parseThreshold(text: string): number | null { + if (text.trim() === '') return null + const n = Number(text) + return Number.isFinite(n) && n >= 0 && n <= 1 ? n : null +} diff --git a/frontend/src/pages/BillingPage.tsx b/frontend/src/pages/BillingPage.tsx index fb544765..0c2da2b4 100644 --- a/frontend/src/pages/BillingPage.tsx +++ b/frontend/src/pages/BillingPage.tsx @@ -538,7 +538,7 @@ function Invoices({ org }: { org: string }) { } /** Where billing emails go: an address of its own, or (empty) the organization's admins. */ -function BillingEmail({ org, current }: { org: string; current: string | null }) { +export function BillingEmail({ org, current }: { org: string; current: string | null }) { const save = useBillingEmail(org) const [value, setValue] = useState(current ?? '') return ( diff --git a/frontend/src/pages/OrgPage.tsx b/frontend/src/pages/OrgPage.tsx index 1f8a3886..24f573d3 100644 --- a/frontend/src/pages/OrgPage.tsx +++ b/frontend/src/pages/OrgPage.tsx @@ -1,11 +1,10 @@ import { useState } from 'react' import { Link, getRouteApi, useNavigate } from '@tanstack/react-router' -import { PlusIcon } from '@phosphor-icons/react' -import { useCreateProject, useMe, useOrg, useUpdateSetup } from '../api/hooks' +import { GearSixIcon, PlusIcon } from '@phosphor-icons/react' +import { useCreateProject, useMe, useOrg } from '../api/hooks' import { CreateForm } from '../components/CreateForm' import { HeardAboutCard } from '../components/HeardAboutCard' import { GitlabInstances } from '../components/GitlabInstances' -import { Members } from '../components/Members' import { SetupChecklist } from '../components/SetupChecklist' import { QueryState } from '../components/QueryState' import { BuildResult, Button, Empty, StatCounts } from '../components/ui' @@ -21,12 +20,12 @@ export function OrgPage() { const navigate = useNavigate() const [creating, setCreating] = useState(false) const me = useMe() - const reopen = useUpdateSetup(org) if (!q.data) return const o = q.data const canCreate = o.role === 'admin' - const showSetup = !o.setup.complete && !o.setup.dismissed + // Shown until it's complete, unless an admin chose otherwise (its Hide, or Settings' toggle) + const showSetup = o.setup.shown return (

@@ -66,11 +65,6 @@ export function OrgPage() {

Projects

- {!o.setup.complete && o.setup.dismissed && ( - - )} {canCreate && o.setup.github.length > 0 && ( Add repositories @@ -81,6 +75,11 @@ export function OrgPage() { New project )} + {/* On a phone the label is hidden and the gear stays: still named "Settings" for screen readers */} + + + Settings +
@@ -195,7 +194,6 @@ export function OrgPage() { )} - {(o.gitlab_instances_enabled || (o.gitlab_instances ?? []).length > 0) && ( )} diff --git a/frontend/src/pages/RepositoriesPage.tsx b/frontend/src/pages/RepositoriesPage.tsx index 40d41fa6..7ed87857 100644 --- a/frontend/src/pages/RepositoriesPage.tsx +++ b/frontend/src/pages/RepositoriesPage.tsx @@ -42,7 +42,16 @@ export function RepositoriesPage() { const o = orgQ.data const p = picker.data const shown = progress.data ?? (importId == null ? running : null) - if (shown) return setImportId(null)} /> + // The pick stays as it was until the importer replaces the picker, and is cleared only on coming back for more + if (shown) { + const more = () => { + setPicked(new Map()) + setImportId(null) + } + return + } + const adding = start.isPending || (importId != null && !progress.error) + const addError = start.error ?? (importId != null ? progress.error : 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 @@ -202,25 +211,18 @@ export function RepositoriesPage() { {picked.size === 0 ? 'Nothing picked yet' : `${picked.size} picked`} {picked.size >= PICK_LIMIT && (at most {PICK_LIMIT} at a time)} - {start.error && ( + {addError && ( - {start.error.message} + {addError.message} )}
diff --git a/frontend/src/pages/SettingsPage.tsx b/frontend/src/pages/SettingsPage.tsx new file mode 100644 index 00000000..0011d303 --- /dev/null +++ b/frontend/src/pages/SettingsPage.tsx @@ -0,0 +1,284 @@ +import { useState } from 'react' +import { getRouteApi, useNavigate } from '@tanstack/react-router' +import { ArrowSquareOutIcon, GithubLogoIcon } from '@phosphor-icons/react' +import { errorMessage } from '../api/client' +import { useLeaveOrg, useOrg, useUpdateOrg, useUpdateSetup } from '../api/hooks' +import type { Org } from '../api/types' +import { Members } from '../components/Members' +import { QueryState } from '../components/QueryState' +import { Button, CopyButton, Field, Help } from '../components/ui' +import { BillingEmail } from './BillingPage' +import { githubManageUrl, leaveRefusal, parseThreshold } from '../lib/orgSettings' +import { n } from '../lib/format' + +const route = getRouteApi('/_app/$org/settings') + +/** An organization's settings: every member reads them, its admins change them. */ +export function SettingsPage() { + const { org } = route.useParams() + const q = useOrg(org) + if (!q.data) return + const o = q.data + const admin = o.role === 'admin' + return ( +
+
+
+

Settings

+ {!admin &&

Only admins can change these.

} +
+
+
+ + + + + + {admin && } + +
+
+ ) +} + +function General({ org, admin }: { org: Org; admin: boolean }) { + const update = useUpdateOrg(org.slug) + const [name, setName] = useState(org.name) + const dirty = name.trim() !== org.name + return ( +
+
+

General

+
+
{ + e.preventDefault() + update.mutate({ name: name.trim() }) + }} + > + +
+ setName(e.target.value)} + /> + {admin && ( + + )} +
+
+
+ + Slug + Part of every address and project name: {org.slug}/project. It can’t be changed. + +
+ + {org.slug} + + +
+
+
+
+ ) +} + +function GettingStarted({ org, admin }: { org: Org; admin: boolean }) { + const update = useUpdateSetup(org.slug) + // The box follows the click at once; a refusal puts it back + const [choice, setChoice] = useState(null) + return ( +
+
+

Getting started

+
+ + {update.isError &&

{errorMessage(update.error)}

} +
+ ) +} + +function Github({ org, admin }: { org: Org; admin: boolean }) { + const installs = org.github_installations + return ( +
+
+

GitHub

+ {admin && ( + + Add a GitHub organization + + )} +
+ {installs.length === 0 ? ( +

The GitHub App isn’t installed for this organization.

+ ) : ( +
+ + + + + + + + + {installs.map((i) => ( + + + + + ))} + +
Account + Actions +
+ {i.account_login} + + {i.account_type === 'Organization' ? 'Organization' : 'Personal account'} ·{' '} + {i.repositories === 1 ? '1 repository' : `${n(i.repositories)} repositories`} + {i.suspended && ' · suspended'} + + + + Manage on GitHub + +
+
+ )} +
+ ) +} + +function ProjectDefaults({ org, admin }: { org: Org; admin: boolean }) { + const update = useUpdateOrg(org.slug) + const d = org.project_defaults + const [threshold, setThreshold] = useState(String(d.threshold)) + const [comment, setComment] = useState(d.comment_when_unchanged) + const parsed = parseThreshold(threshold) + const dirty = parsed !== d.threshold || comment !== d.comment_when_unchanged + return ( +
+
+

+ Project defaults New projects start with these. Existing projects keep their own. +

+
+
{ + e.preventDefault() + if (parsed === null) return + update.mutate({ project_threshold: parsed, project_comment_when_unchanged: comment }) + }} + > +
+ + setThreshold(e.target.value)} + /> + + +
+ {admin && ( +
+ + {update.isError && {errorMessage(update.error)}} +
+ )} +
+
+ ) +} + +function DangerZone({ org }: { org: Org }) { + const leave = useLeaveOrg(org.slug) + const navigate = useNavigate() + const [confirming, setConfirming] = useState(false) + const refusal = leaveRefusal(org) + return ( +
+
+

Danger zone

+
+
+ + Leave {org.name} + {refusal && {refusal}} + + {confirming ? ( + + + + + ) : ( + + )} +
+ {leave.isError &&

{errorMessage(leave.error)}

} +

+ To delete the organization, email support@visualci.com. +

+
+ ) +} diff --git a/frontend/src/router.tsx b/frontend/src/router.tsx index 625971e0..ede44b98 100644 --- a/frontend/src/router.tsx +++ b/frontend/src/router.tsx @@ -7,6 +7,7 @@ import { Home } from './pages/Home' import { OrgPage } from './pages/OrgPage' import { RepositoriesPage } from './pages/RepositoriesPage' import { BillingPage } from './pages/BillingPage' +import { SettingsPage } from './pages/SettingsPage' import { ProjectPage, type ProjectTab } from './pages/ProjectPage' import { BuildPage } from './pages/BuildPage' import { PullPage } from './pages/PullPage' @@ -75,6 +76,8 @@ const repositoriesRoute = createRoute({ }), }) +// Every member reads the organization's settings; its admins change them +const settingsRoute = createRoute({ getParentRoute: () => appRoute, path: '$org/settings', component: SettingsPage }) const billingRoute = createRoute({ getParentRoute: () => appRoute, path: '$org/billing', component: () => }) const billingUsageRoute = createRoute({ getParentRoute: () => appRoute, path: '$org/billing/usage', component: () => }) const billingMethodsRoute = createRoute({ @@ -141,7 +144,7 @@ const snapshotRoute = createRoute({ const routeTree = rootRoute.addChildren([ homeRoute, authorizeRoute, - appRoute.addChildren([accountRoute, askRoute, deviceRoute, staffRoute, staffFeedbackRoute, staffEmailsRoute, orgRoute, repositoriesRoute, billingRoute, billingUsageRoute, billingMethodsRoute, billingInvoicesRoute, projectRoute, buildRoute, pullRoute, snapshotRoute]), + appRoute.addChildren([accountRoute, askRoute, deviceRoute, staffRoute, staffFeedbackRoute, staffEmailsRoute, orgRoute, repositoriesRoute, settingsRoute, billingRoute, billingUsageRoute, billingMethodsRoute, billingInvoicesRoute, projectRoute, buildRoute, pullRoute, snapshotRoute]), ]) export function makeRouter(queryClient: QueryClient) { diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 563e90ba..9b87ea01 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -1338,6 +1338,7 @@ select.input { display: flex; justify-content: space-between; align-items: center; + flex-wrap: wrap; gap: var(--space-3); margin-bottom: var(--space-3); } @@ -1670,6 +1671,93 @@ tr.row-clickable button, color: var(--color-ink); } +/* An organization's settings: one section after another, each under a rule. */ +.org-settings { + display: grid; + gap: var(--space-8); + min-width: 0; +} + +.org-settings > section { + min-width: 0; +} + +.org-settings > section + section { + padding-top: var(--space-6); + border-top: 1px solid var(--color-rule); +} + +.settings-fields { + display: grid; + gap: var(--space-5); + max-width: 560px; + min-width: 0; +} + +.settings-fields .input-row .input { + min-width: 0; +} + +/* A fieldset that only groups (and disables) its fields. */ +.settings-plain { + margin: 0; + padding: 0; + border: 0; + display: grid; + gap: var(--space-5); + min-width: 0; +} + +.settings-value { + display: inline-flex; + align-items: center; + min-height: 34px; + padding: 0 var(--space-3); + border-radius: var(--radius); + background: var(--color-sunken); + color: var(--color-ink); + font-size: var(--text-sm); + overflow-wrap: anywhere; + min-width: 0; +} + +/* An installation's kind and repositories, under its account */ +.install-meta { + display: block; + font-size: var(--text-sm); +} + +.danger-zone { + display: grid; + gap: var(--space-3); +} + +.danger-row { + display: flex; + justify-content: space-between; + align-items: center; + gap: var(--space-4); + flex-wrap: wrap; + padding: var(--space-4); + border: 1px solid var(--color-removed-line); + border-radius: var(--radius); +} + +.danger-text { + display: grid; + gap: 2px; + min-width: 0; +} + +.danger-text .muted { + font-size: var(--text-sm); +} + +.danger-row strong { + color: var(--color-ink); + font-weight: 500; +} + textarea.input { height: auto; min-height: 84px; @@ -4585,9 +4673,26 @@ svg.regions-dim { } } +/* The organization page's Settings: the gear alone on a phone, its label kept for screen readers. */ +@media (max-width: 640px) { + .settings-btn-label { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; + } +} + .section-actions { display: flex; align-items: center; + justify-content: flex-end; + flex-wrap: wrap; gap: var(--space-2); } diff --git a/scripts/screenshots/capture.mjs b/scripts/screenshots/capture.mjs index 2392d8f8..7bde1ebf 100644 --- a/scripts/screenshots/capture.mjs +++ b/scripts/screenshots/capture.mjs @@ -10,7 +10,7 @@ import { mkdir, readFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { chromium } from 'playwright' -import { EMAIL, NOW, pages } from './pages.mjs' +import { NOW, pages, signInEmail } from './pages.mjs' import { STEADY_RASTER } from './raster.mjs' /** VisualCI's production gallery, as frontend/src/components/GalleryImage.tsx names it. */ @@ -154,7 +154,7 @@ async function main() { globalThis.Date = FixedDate }, NOW) if (signedIn) { - const res = await ctx.request.post('/auth/dev-login', { data: { email: EMAIL } }) + const res = await ctx.request.post('/auth/dev-login', { data: { email: signInEmail(signedIn) } }) if (!res.ok()) throw new Error(`dev-login: HTTP ${res.status()}`) } contexts.set(key, ctx) diff --git a/scripts/screenshots/checks.mjs b/scripts/screenshots/checks.mjs index 6a60b5b4..9d0d9f5d 100644 --- a/scripts/screenshots/checks.mjs +++ b/scripts/screenshots/checks.mjs @@ -11,7 +11,7 @@ // - No captured page is wider than a 390 px phone: nothing laid out past the right edge (the page clips sideways, so // that would be cut off), except inside a box that scrolls on its own (a code block). Waits like capture.mjs does. import { chromium } from 'playwright' -import { EMAIL, pages } from './pages.mjs' +import { EMAIL, pages, signInEmail } from './pages.mjs' import { checkLightbox } from './lightbox.mjs' import { STEADY_RASTER } from './raster.mjs' @@ -73,7 +73,7 @@ try { if (contexts[signedIn]) return contexts[signedIn] const ctx = await browser.newContext({ baseURL: BASE, viewport: { width: 390, height: 844 } }) if (signedIn) { - const res = await ctx.request.post('/auth/dev-login', { data: { email: EMAIL } }) + const res = await ctx.request.post('/auth/dev-login', { data: { email: signInEmail(signedIn) } }) if (!res.ok()) throw new Error(`dev-login: HTTP ${res.status()}`) } contexts[signedIn] = ctx diff --git a/scripts/screenshots/journeys.mjs b/scripts/screenshots/journeys.mjs index 000e0252..0a676ed7 100644 --- a/scripts/screenshots/journeys.mjs +++ b/scripts/screenshots/journeys.mjs @@ -90,6 +90,18 @@ await journey('sign-in-from-the-site', async ({ page, shot }) => { await shot('dashboard') const me = await page.evaluate(() => fetch('/api/ui/me', { headers: { accept: 'application/json' } }).then((r) => r.status)) expect(me === 200, `signed in, /api/ui/me answers ${me}`) + // The logo: on an organization's page back to the app's home, on the app's home on to the site + const slug = await page.evaluate(() => + fetch('/api/ui/me', { headers: { accept: 'application/json' } }).then((r) => r.json()).then((m) => m.organizations[0].slug), + ) + await page.goto(`${APP}/${slug}`) + await page.locator('h1').first().waitFor() + const inApp = await page.locator('header .logo').getAttribute('href') + expect(inApp === '/', `the logo on /${slug} links to ${inApp}`) + await page.goto(`${APP}/?all=1`) + await page.locator('h1').first().waitFor() + const onHome = await page.locator('header .logo').getAttribute('href') + expect(onHome === `${SITE}/`, `the logo on the app's home links to ${onHome}`) }) // 2. Signed in, the site's "Open app" stays in the app (the cookie-name bounce: the app's / sent everyone back to @@ -381,8 +393,27 @@ await journey('setup-picks-from-300-repositories', async ({ page, shot }) => { } await page.getByText('2 picked').waitFor() await shot('picked') + // From the click until the importer replaces the picker, the pick stays exactly as it was (it flashed "Nothing + // picked yet" with its boxes cleared while the importer loaded) + await page.evaluate(() => { + const seen = (window.__pickChanges = []) + const check = () => { + const bar = document.querySelector('.picker-bar') + if (!bar) return + const text = bar.textContent ?? '' + if (!text.includes('2 picked')) seen.push(`bar: ${text}`) + for (const row of document.querySelectorAll('.picker-row label')) { + const name = row.querySelector('.picker-name')?.textContent ?? '' + const box = row.querySelector('input[type=checkbox]') + if (['journey-big/repo-001', 'journey-big/repo-002'].includes(name) && box && !box.checked) seen.push(`${name} unchecked`) + } + } + new MutationObserver(check).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true }) + }) await page.getByRole('button', { name: 'Add 2 repositories' }).click() await page.getByRole('heading', { name: 'Added 2 projects' }).waitFor({ timeout: 30000 }) + const changes = await page.evaluate(() => window.__pickChanges) + expect(changes.length === 0, `the pick changed before the importer showed: ${[...new Set(changes)].join('; ')}`) // The finished state, settled: the bar full, the next step offered, and the refetches that follow it done await page.getByRole('button', { name: 'Next: connect your coding agent' }).waitFor() await page.waitForFunction(() => { @@ -533,6 +564,72 @@ await journey('strangers-installation-stays-unclaimed', async ({ page }) => { expect(status.forge_posts_failed === 0 && status.forge_posts_retrying === 0, `forge posts failing: ${JSON.stringify(status)}`) }) +// 12. The organization's settings: its admin renames it, hides the setup steps and shows them again (complete or +// not, 4 Dec 2026: a finished checklist couldn't be brought back), invites someone, and can't leave their own +// organization; the person invited sees the same page read-only, light and dark. +await journey('organization-settings', async ({ page, shot }) => { + await signInAs(page, shot, { id: 600020, login: 'journey-admin', name: 'Ann Admin', email: 'admin@journeys.test' }) + const slug = (await api(page, '/api/ui/me')).organizations[0].slug + await page.goto(`${APP}/${slug}`) + await page.getByRole('heading', { name: /Set up VisualCI/ }).waitFor() + await page.locator('.section-actions').getByRole('link', { name: 'Settings' }).click() + await page.waitForURL((url) => url.pathname === `/${slug}/settings`) + await page.getByRole('heading', { name: 'Settings', level: 1 }).waitFor() + await shot('admin') + + await page.getByLabel('Display name').fill('Ann’s Team') + await page.getByRole('button', { name: 'Save' }).first().click() + await page.waitForFunction(async (s) => { + const r = await fetch(`/api/ui/orgs/${s}`, { headers: { accept: 'application/json' } }) + return (await r.json()).name === 'Ann’s Team' + }, slug) + + // Hidden here, gone from the organization's page; shown again, back + const steps = page.getByRole('checkbox', { name: /Show getting started steps/ }) + expect(await steps.isChecked(), 'the setup steps start shown') + await steps.uncheck() + await page.waitForFunction(async (s) => { + const r = await fetch(`/api/ui/orgs/${s}`, { headers: { accept: 'application/json' } }) + return (await r.json()).setup.shown === false + }, slug) + await page.goto(`${APP}/${slug}`) + await page.getByRole('heading', { name: 'Projects', exact: true }).waitFor() + expect((await page.getByRole('heading', { name: /Set up VisualCI/ }).count()) === 0, 'the hidden setup steps still show') + await page.goto(`${APP}/${slug}/settings`) + await steps.check() + await page.goto(`${APP}/${slug}`) + await page.getByRole('heading', { name: /Set up VisualCI/ }).waitFor() + + await page.goto(`${APP}/${slug}/settings`) + await page.getByLabel('Email address or GitHub login').fill('journey-reader') + await page.getByRole('button', { name: 'Invite' }).click() + await page.getByText('Invited journey-reader').waitFor() + expect(await page.getByRole('button', { name: 'Leave organization' }).isDisabled(), 'leaving your own organization is offered') + await page.getByText('It’s your own organization.').waitFor() + await shot('admin-invited') + await page.emulateMedia({ colorScheme: 'dark' }) + await shot('admin-dark') + await page.emulateMedia({ colorScheme: 'light' }) + + // The person invited joins, and sees the settings read-only + await stub(page, '/_stub/person', { id: 600021, login: 'journey-reader', name: 'Rhea Reader', email: 'reader@journeys.test' }) + await page.evaluate(() => fetch('/auth/logout', { method: 'POST', headers: { accept: 'application/json' } })) + await page.context().clearCookies() + await signInFromSite(page, shot) + await page.getByRole('button', { name: 'Accept' }).click() + await page.waitForURL((url) => url.pathname === `/${slug}`) + await page.goto(`${APP}/${slug}/settings`) + await page.getByText('Only admins can change these.').waitFor() + expect(await page.getByLabel('Display name').getAttribute('readonly') !== null, 'a read-only member can edit the name') + expect(await page.getByRole('checkbox', { name: /Show getting started steps/ }).isDisabled(), 'a member can hide the setup steps') + expect((await page.getByRole('button', { name: 'Save' }).count()) === 0, 'a member sees Save buttons') + expect((await page.getByLabel('Email address or GitHub login').count()) === 0, 'a member can invite') + expect(!(await page.getByRole('button', { name: 'Leave organization' }).isDisabled()), 'a member can’t leave') + await shot('member') + await page.emulateMedia({ colorScheme: 'dark' }) + await shot('member-dark') +}) + // 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 ce3cd1e9..daed048f 100644 --- a/scripts/screenshots/pages.mjs +++ b/scripts/screenshots/pages.mjs @@ -4,12 +4,18 @@ // NOW is after the seeded data in app/src/domain/demo.rs (screenshots_seed), and EMAIL is its SCREENSHOTS_EMAIL. export const NOW = '2026-11-20T15:00:00Z' export const EMAIL = 'ada@example.com' +/** Grace, a member of Acme through GitHub (not an admin): the read-only views. */ +export const MEMBER_EMAIL = 'grace@example.com' + +/** Who a page is taken as: `true` is Ada (EMAIL), an email address someone else from the seed. */ +export const signInEmail = (signedIn) => (signedIn === true ? EMAIL : signedIn) // Every page at both widths and both themes. The docs share one layout, so only the docs home (with the sidebar) is // taken, to catch a CSS regression across the docs: every page of them was CI minutes for nothing (Nathan, 2 Dec 2026). const ALL = ['1440-light', '1440-dark', '390-light', '390-dark'] -/** The pages: [name, path or async (api) => path, signed in?, variants]. */ +/** The pages: [name, path or async (api) => path, signed in? (true for Ada, or another seeded person's email), + * variants]. */ export function pages() { const snapshot = (project, number, name) => async (api) => { const data = await api(`/api/ui/orgs/acme/projects/${project}/builds/${number}`) @@ -45,6 +51,9 @@ export function pages() { ['app/repositories/progress', '/side-project/repositories', true, ALL], // A personal organization's checklist: Ada's own installation, and Acme's listed under "Your other GitHub installations" ['app/org/personal', '/side-project', true, ['1440-light', '390-light']], + // The organization's settings, for its admin and (read-only) for a member whose access follows GitHub + ['app/org/settings', '/acme/settings', true, ALL], + ['app/org/settings/member', '/acme/settings', MEMBER_EMAIL, ['1440-light', '1440-dark', '390-light']], ['app/billing/team', '/acme/billing', true, ALL], ['app/billing/free', '/side-project/billing', true, ALL], ['app/account', '/account', true, ALL],