From 5ca2f4700f23e72ef0af7b0afc82a6526c59988e Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Wed, 2 Dec 2026 21:34:17 +1300 Subject: [PATCH] Local builds wait only for their person, and close after a week idle: builds.created_by_user_id (migration 000041) from a person's token (REST, MCP); whoami and list_builds' waiting_for_review show a local build only to its person; builds:expire closes local builds idle 7 days with a note; docs: who reviews main's builds, review mode recommended, wait only with a reviewer; plugin 0.1.38 --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .cursor-plugin/plugin.json | 2 +- gemini-extension.json | 2 +- server/frontend/content/docs/agents.md | 13 +- server/migration/src/lib.rs | 2 + .../src/m20261202_000041_build_creator.rs | 28 +++++ server/src/controllers/api.rs | 16 +++ server/src/mcp.rs | 32 +++-- server/src/models/_entities/builds.rs | 2 + server/src/models/builds.rs | 52 ++++++++ server/src/tasks/builds_expire.rs | 5 + server/tests/requests/mcp.rs | 118 ++++++++++++++++++ skills/visualci-review/SKILL.md | 13 +- 14 files changed, 270 insertions(+), 19 deletions(-) create mode 100644 server/migration/src/m20261202_000041_build_creator.rs diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index badbf1ba..4e7f4486 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,7 +5,7 @@ "plugins": [ { "name": "visualci", - "version": "0.1.37", + "version": "0.1.38", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "author": { "name": "DocSpring", "url": "https://visualci.com" }, "homepage": "https://visualci.com/docs/skills/", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 6b600ce5..dbf3251d 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.37", + "version": "0.1.38", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "author": { "name": "DocSpring", "url": "https://visualci.com" }, "homepage": "https://visualci.com/docs/skills/", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 9594fc20..8d56539e 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "visualci", "displayName": "VisualCI", - "version": "0.1.37", + "version": "0.1.38", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "author": { "name": "DocSpring" diff --git a/gemini-extension.json b/gemini-extension.json index 32c04d5f..141bfdde 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.37", + "version": "0.1.38", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "mcpServers": { "visualci": { diff --git a/server/frontend/content/docs/agents.md b/server/frontend/content/docs/agents.md index d2c5c884..8cfbcb35 100644 --- a/server/frontend/content/docs/agents.md +++ b/server/frontend/content/docs/agents.md @@ -179,17 +179,24 @@ account with the Read role, which can see builds but can't approve them (see [Ac ## Repositories without pull requests Where agents push straight to the default branch, there's no pull request for a pending check to hold up, so -unreviewed changes can pile up on main without anyone noticing. Three things keep them in view: +unreviewed changes can pile up on main without anyone noticing. Someone has to review main's builds: name who in the +repository's AGENTS.md (usually "the agent that pushed reviews its push's build"). Three things keep them in view: - The commit's VisualCI check stays pending until the build is reviewed, as on a pull request (with the VisualCI GitHub App installed on the repository; without it there's no check). - `whoami` lists the newest builds waiting for a review, and `list_builds` with `waiting_for_review: true` lists a - project's. A pull request closed without merging, or a deleted branch, takes its builds off those lists: they - become `closed` (reopening the pull request puts its newest build back). Add a line to your agents' instructions: after a push, review its VisualCI build. + project's. Add a line to your agents' instructions: after a push, review its VisualCI build. - To hold the push's CI run until the review, set `ci_mode: wait` in [visualci.yml](/docs/reference/config/) and finish with `visualci build finalize --wait`: CI waits (up to `--timeout`) while the agent reviews, then passes or fails on the result. `strict` fails the run on any unreviewed change instead. +We recommend the default `review` mode with the agent that pushed reviewing its build: CI and deploys never wait, and +an approval later still makes the change the baseline. Choose `wait` when a deploy must not go out with an unreviewed +visual change, and only if an agent or a person is there to review within the timeout: otherwise every push times out. + +A local run's build (from a laptop, `visualci test` or `visualci check`) waits only in its own person's lists, and +leaves them after a week with nothing happening to it (it's kept, closed, in the build list). + Snapshot tests work the same way. With VisualCI, the tests write their snapshots and pass (Jest's `-u`, `INSTA_UPDATE=always INSTA_FORCE_PASS=1`, syrupy's `--snapshot-update`), and the review happens on VisualCI. If a change on main must stop CI before anyone looks, use `ci_mode: strict`, or keep those snapshot files committed and diff --git a/server/migration/src/lib.rs b/server/migration/src/lib.rs index 0728c611..d88398d9 100644 --- a/server/migration/src/lib.rs +++ b/server/migration/src/lib.rs @@ -44,6 +44,7 @@ mod m20261202_000037_review_source; mod m20261202_000038_matches_approved; mod m20261202_000039_repository_id; mod m20261202_000040_closed_builds; +mod m20261202_000041_build_creator; pub struct Migrator; @@ -94,6 +95,7 @@ impl MigratorTrait for Migrator { Box::new(m20261202_000038_matches_approved::Migration), Box::new(m20261202_000039_repository_id::Migration), Box::new(m20261202_000040_closed_builds::Migration), + Box::new(m20261202_000041_build_creator::Migration), // inject-above (do not remove this comment) ] } diff --git a/server/migration/src/m20261202_000041_build_creator.rs b/server/migration/src/m20261202_000041_build_creator.rs new file mode 100644 index 00000000..d0b8000e --- /dev/null +++ b/server/migration/src/m20261202_000041_build_creator.rs @@ -0,0 +1,28 @@ +//! Who made a build, when a person's token made it (`builds.created_by_user_id`): a local build waits for review only +//! for the person whose run it was, never in everyone's waiting lists. +use sea_orm_migration::prelude::*; + +pub struct Migration; + +impl MigrationName for Migration { + fn name(&self) -> &str { + "m20261202_000041_build_creator" + } +} + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection() + .execute_unprepared( + "ALTER TABLE builds ADD COLUMN created_by_user_id BIGINT REFERENCES users(id) ON DELETE SET NULL;", + ) + .await?; + Ok(()) + } + + async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection().execute_unprepared("ALTER TABLE builds DROP COLUMN created_by_user_id;").await?; + Ok(()) + } +} diff --git a/server/src/controllers/api.rs b/server/src/controllers/api.rs index cdb5c291..837b6639 100644 --- a/server/src/controllers/api.rs +++ b/server/src/controllers/api.rs @@ -84,6 +84,15 @@ impl axum::extract::FromRequestParts for ProjectAuth { } } +/// The request's bearer token, if any. +fn bearer(headers: &axum::http::HeaderMap) -> Option<&str> { + headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(str::trim) +} + /// An unknown token is a 401; anything else (the database) is the server's fault, and saying "invalid token" would /// send someone off to rotate a token that's fine. fn token_error(e: loco_rs::model::ModelError, message: &str) -> Error { @@ -205,6 +214,7 @@ fn model_error(e: ModelError) -> Error { async fn create_build( ProjectAuth(project): ProjectAuth, State(ctx): State, + headers: axum::http::HeaderMap, Body(params): Body, ) -> Result { let settings = Settings::from_context(&ctx)?; @@ -212,6 +222,12 @@ async fn create_build( // `builds:expire`), so they don't sit "receiving" beside this one. crate::workers::expire_abandoned(&ctx, Some(project.id)).await?; let build = builds::Model::create(&ctx.db, &project, ¶ms).await.map_err(model_error)?; + // A person's token: the build is theirs (a local one waits for review in their lists only). + if let Some(token) = bearer(&headers).filter(|t| t.starts_with(user_tokens::PREFIX)) + && let Ok((user, _)) = user_tokens::Model::authenticate(&ctx.db, token).await + { + builds::Model::set_creator(&ctx.db, build.id, user.id).await?; + } let slug = org_slug(&ctx, &project).await?; format::json( BuildResponse::new(&build, &project, &slug, &settings) diff --git a/server/src/mcp.rs b/server/src/mcp.rs index 553da8b6..d31c03ea 100644 --- a/server/src/mcp.rs +++ b/server/src/mcp.rs @@ -164,7 +164,7 @@ pub struct ListBuildsArgs { pub branch: Option, /// How many, newest first (default 20, at most 100). pub limit: Option, - /// Only builds whose changes wait for a review. + /// Only builds whose changes wait for a review (a local build only for the person whose run it was). pub waiting_for_review: Option, } @@ -905,16 +905,25 @@ impl VisualCi { /// The newest builds of these projects whose changes wait for a review, at most 10: on a repository that pushes /// straight to the default branch, nothing else would remind the agent that pushed. - async fn waiting_for_review(&self, reachable: &[projects::Model]) -> Result, ErrorData> { + /// A local build waits only for the person whose run it was (`user`; a project token sees none). + async fn waiting_for_review( + &self, + reachable: &[projects::Model], + user: Option, + ) -> Result, ErrorData> { let ids: Vec = reachable.iter().map(|p| p.id).collect(); - let pending = builds::Entity::find() + let pending: Vec = builds::Entity::find() .filter(builds::builds::Column::ProjectId.is_in(ids)) .filter(builds::builds::Column::ReviewState.eq("pending")) .order_by_desc(builds::builds::Column::Id) - .limit(10) + .limit(100) .all(&self.ctx.db) .await - .map_err(internal)?; + .map_err(internal)? + .into_iter() + .filter(|b| b.waits_for(user)) + .take(10) + .collect(); let mut out = Vec::new(); for b in pending { let Some(project) = reachable.iter().find(|p| p.id == b.project_id) else { continue }; @@ -995,7 +1004,7 @@ impl VisualCi { })); reachable.extend(projects::Model::for_organization(&self.ctx.db, org.id).await.map_err(internal)?); } - let waiting = self.waiting_for_review(&reachable).await?; + let waiting = self.waiting_for_review(&reachable, Some(u.id)).await?; let ids = identities::for_users(&self.ctx.db, &[u.id]) .await .map_err(internal)? @@ -1018,7 +1027,7 @@ impl VisualCi { } Some(Principal::Project(p)) => { let org = self.org_slug(&p).await?; - let waiting = self.waiting_for_review(std::slice::from_ref(&p)).await?; + let waiting = self.waiting_for_review(std::slice::from_ref(&p), None).await?; let threads = self.open_threads(std::slice::from_ref(&p)).await?; let organization = organizations::Model::find_by_id(&self.ctx.db, p.organization_id).await.map_err(internal)?; @@ -1457,7 +1466,7 @@ impl VisualCi { if args.branch.as_ref().is_some_and(|br| *br != b.branch) { continue; } - if args.waiting_for_review == Some(true) && b.review_state != "pending" { + if args.waiting_for_review == Some(true) && !b.waits_for(Self::user_id(&rc)) { continue; } list.push(self.build_json(&project, &b, member).await?); @@ -2291,7 +2300,12 @@ impl VisualCi { }; crate::workers::expire_abandoned(&self.ctx, Some(project.id)).await.map_err(internal)?; match builds::Model::create(&self.ctx.db, &project, ¶ms).await { - Ok(build) => Ok(CallToolResult::structured(self.build_json(&project, &build, true).await?)), + Ok(build) => { + if let Some(user) = Self::user_id(&rc) { + builds::Model::set_creator(&self.ctx.db, build.id, user).await.map_err(internal)?; + } + Ok(CallToolResult::structured(self.build_json(&project, &build, true).await?)) + } Err(e) => Ok(tool_error(e.to_string())), } } diff --git a/server/src/models/_entities/builds.rs b/server/src/models/_entities/builds.rs index 3aab50df..04607d16 100644 --- a/server/src/models/_entities/builds.rs +++ b/server/src/models/_entities/builds.rs @@ -58,6 +58,8 @@ pub struct Model { pub environment_info: Json, #[sea_orm(column_type = "JsonBinary")] pub charged: Json, + /// The person whose token made the build, if one did (not a project token). + pub created_by_user_id: Option, pub finalized_at: Option, pub completed_at: Option, pub created_at: DateTimeWithTimeZone, diff --git a/server/src/models/builds.rs b/server/src/models/builds.rs index 5c6389f8..4750cae4 100644 --- a/server/src/models/builds.rs +++ b/server/src/models/builds.rs @@ -1018,6 +1018,58 @@ impl Model { } } +/// The warning on a local build closed after `LOCAL_IDLE_DAYS` with no activity. +pub const LOCAL_IDLE: &str = "Closed without review: a local build, idle for 7 days."; +/// How long a local build waits for its own person's review before it leaves the waiting lists. +pub const LOCAL_IDLE_DAYS: i32 = 7; + +impl Model { + /// Whether this build waits for a review in `user`'s waiting lists (whoami, `list_builds` with + /// `waiting_for_review`): a CI build's pending changes wait for everyone; a local build's only for the person whose + /// run it was (never for a project token, `user` None). + #[must_use] + pub fn waits_for(&self, user: Option) -> bool { + self.review_state == "pending" && (self.mode != "local" || (user.is_some() && self.created_by_user_id == user)) + } + + /// Record the person whose token made this build. + /// + /// # Errors + /// On a database error. + pub async fn set_creator(db: &impl ConnectionTrait, build_id: i64, user_id: i64) -> ModelResult<()> { + db.execute_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "UPDATE builds SET created_by_user_id = $2 WHERE id = $1", + [build_id.into(), user_id.into()], + )) + .await?; + Ok(()) + } + + /// Local builds still waiting for review with nothing happening to them (no review, comment or snapshot change) + /// for `LOCAL_IDLE_DAYS`: they become `closed`, with the LOCAL_IDLE note, and leave the waiting lists. They stay in + /// the build list; a new local run on the branch waits afresh. Returns their ids. + /// + /// # Errors + /// On a database error. + pub async fn close_idle_local(db: &impl ConnectionTrait) -> ModelResult> { + let rows = db + .query_all_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "UPDATE builds b SET review_state = 'closed', warnings = b.warnings || jsonb_build_array($1::TEXT), \ + updated_at = now() \ + WHERE b.mode = 'local' AND b.review_state = 'pending' \ + AND GREATEST(b.updated_at, \ + COALESCE((SELECT MAX(s.updated_at) FROM snapshots s WHERE s.build_id = b.id), b.created_at)) \ + < now() - make_interval(days => $2) \ + RETURNING b.id", + [LOCAL_IDLE.into(), LOCAL_IDLE_DAYS.into()], + )) + .await?; + Ok(rows.iter().filter_map(|r| r.try_get::("", "id").ok()).collect()) + } +} + /// The warning on a build that stopped waiting for review because its pull request was closed without merging. pub const CLOSED_PULL_REQUEST: &str = "Closed without review: the pull request was closed without merging."; /// The same, for a build whose branch was deleted. diff --git a/server/src/tasks/builds_expire.rs b/server/src/tasks/builds_expire.rs index d237d9bf..080d7b25 100644 --- a/server/src/tasks/builds_expire.rs +++ b/server/src/tasks/builds_expire.rs @@ -20,6 +20,11 @@ impl Task for BuildsExpire { async fn run(&self, ctx: &AppContext, _vars: &task::Vars) -> Result<()> { let outcome = async { let expired = crate::workers::expire_abandoned(ctx, None).await?; + // Local builds nobody looked at for a week leave the waiting lists. + let idle = crate::models::builds::Model::close_idle_local(&ctx.db).await?; + if !idle.is_empty() { + println!("builds:expire: {} idle local builds closed", idle.len()); + } // Emails that weren't sent at once (Postmark down, or queued where nothing could send them): the // ten-minute sweep sends them. let emails = crate::notify::deliver_pending(ctx).await?; diff --git a/server/tests/requests/mcp.rs b/server/tests/requests/mcp.rs index 73003eb8..c143a658 100644 --- a/server/tests/requests/mcp.rs +++ b/server/tests/requests/mcp.rs @@ -1049,3 +1049,121 @@ async fn a_project_can_keep_approving_with_people() { }) .await; } + +#[tokio::test] +#[serial] +async fn a_local_build_waits_only_for_its_person_and_closes_after_a_week_idle() { + request::(|request, ctx| async move { + use sea_orm::{ActiveModelTrait, ConnectionTrait, Set}; + use uuid::Uuid; + use visualci_server::models::{_entities::memberships, builds}; + let f = fixture(&ctx).await; + let org = organizations::Model::find_by_slug(&ctx.db, &f.org).await.unwrap(); + // Another member of the organization, with a token of their own. + let bob = users::ActiveModel { + pid: Set(Uuid::new_v4()), + email: Set(format!("{}@example.com", Uuid::new_v4())), + password: Set(String::new()), + api_key: Set(format!("lo-{}", Uuid::new_v4())), + name: Set("bob".to_string()), + ..Default::default() + } + .insert(&ctx.db) + .await + .unwrap(); + memberships::ActiveModel { + organization_id: Set(org.id), + user_id: Set(bob.id), + role: Set("member".to_string()), + source: Set(visualci_server::models::memberships::CREATED.to_string()), + ..Default::default() + } + .insert(&ctx.db) + .await + .unwrap(); + let bob_token = user_tokens::Model::generate(&ctx.db, bob.id, "agent").await.unwrap().1; + + // The owner's local run, and a CI build, both waiting for review. + let project = format!("{}/pdfs", f.org); + let create = |token: String, mode: &'static str, branch: &'static str| { + let (request, project) = (&request, project.clone()); + async move { + let (err, b) = call( + request, + &token, + "create_build", + serde_json::json!({ "project": project, "commit": "abc123", "branch": branch, "mode": mode }), + ) + .await; + assert!(!err, "{b}"); + b["number"].as_i64().unwrap() + } + }; + let local = create(f.user_token.clone(), "local", "my-branch").await; + let ci = create(f.project_token.clone(), "ci", "main").await; + let pid = projects::Model::find_by_slugs(&ctx.db, &f.org, "pdfs").await.unwrap().id; + ctx.db + .execute_raw(sea_orm::Statement::from_sql_and_values( + sea_orm::DbBackend::Postgres, + "UPDATE builds SET state = 'completed', conclusion = 'changes', review_state = 'pending' \ + WHERE project_id = $1", + [pid.into()], + )) + .await + .unwrap(); + + let waiting = |token: String| { + let (request, project) = (&request, project.clone()); + async move { + let (_, me) = call(request, &token, "whoami", serde_json::json!({})).await; + let mut from_whoami: Vec = + me["waiting_for_review"].as_array().unwrap().iter().map(|b| b["build"].as_i64().unwrap()).collect(); + from_whoami.sort_unstable(); + let args = if token.starts_with("vci_") { + serde_json::json!({ "waiting_for_review": true }) + } else { + serde_json::json!({ "project": project, "waiting_for_review": true }) + }; + let (_, list) = call(request, &token, "list_builds", args).await; + let mut from_list: Vec = + list["builds"].as_array().unwrap().iter().map(|b| b["number"].as_i64().unwrap()).collect(); + from_list.sort_unstable(); + assert_eq!(from_whoami, from_list, "whoami and list_builds agree"); + from_whoami + } + }; + let mut both = vec![local, ci]; + both.sort_unstable(); + assert_eq!(waiting(f.user_token.clone()).await, both, "the owner's own local run waits for them"); + assert_eq!(waiting(bob_token.clone()).await, vec![ci], "not for another member"); + assert_eq!(waiting(f.project_token.clone()).await, vec![ci], "nor for a project token"); + + // A week with nothing happening: the local build leaves the waiting lists, saying why; the CI build stays. + ctx.db + .execute_raw(sea_orm::Statement::from_sql_and_values( + sea_orm::DbBackend::Postgres, + "UPDATE builds SET updated_at = now() - interval '8 days', created_at = now() - interval '8 days' \ + WHERE project_id = $1", + [pid.into()], + )) + .await + .unwrap(); + ctx.db + .execute_raw(sea_orm::Statement::from_sql_and_values( + sea_orm::DbBackend::Postgres, + "UPDATE snapshots SET updated_at = now() - interval '8 days' WHERE build_id IN \ + (SELECT id FROM builds WHERE project_id = $1)", + [pid.into()], + )) + .await + .unwrap(); + let closed = builds::Model::close_idle_local(&ctx.db).await.unwrap(); + assert_eq!(closed.len(), 1); + let b = builds::Model::find_by_id(&ctx.db, closed[0]).await.unwrap(); + assert_eq!((b.number as i64, b.review_state.as_str()), (local, "closed")); + let warnings: Vec = serde_json::from_value(b.warnings).unwrap(); + assert_eq!(warnings.last().map(String::as_str), Some(builds::LOCAL_IDLE)); + assert_eq!(waiting(f.user_token.clone()).await, vec![ci]); + }) + .await; +} diff --git a/skills/visualci-review/SKILL.md b/skills/visualci-review/SKILL.md index 0da812ed..e6a43ad5 100644 --- a/skills/visualci-review/SKILL.md +++ b/skills/visualci-review/SKILL.md @@ -184,17 +184,24 @@ account with the Read role, which can see builds but can't approve them (see [Ac ## Repositories without pull requests Where agents push straight to the default branch, there's no pull request for a pending check to hold up, so -unreviewed changes can pile up on main without anyone noticing. Three things keep them in view: +unreviewed changes can pile up on main without anyone noticing. Someone has to review main's builds: name who in the +repository's AGENTS.md (usually "the agent that pushed reviews its push's build"). Three things keep them in view: - The commit's VisualCI check stays pending until the build is reviewed, as on a pull request (with the VisualCI GitHub App installed on the repository; without it there's no check). - `whoami` lists the newest builds waiting for a review, and `list_builds` with `waiting_for_review: true` lists a - project's. A pull request closed without merging, or a deleted branch, takes its builds off those lists: they - become `closed` (reopening the pull request puts its newest build back). Add a line to your agents' instructions: after a push, review its VisualCI build. + project's. Add a line to your agents' instructions: after a push, review its VisualCI build. - To hold the push's CI run until the review, set `ci_mode: wait` in [visualci.yml](https://visualci.com/docs/reference/config.md) and finish with `visualci build finalize --wait`: CI waits (up to `--timeout`) while the agent reviews, then passes or fails on the result. `strict` fails the run on any unreviewed change instead. +We recommend the default `review` mode with the agent that pushed reviewing its build: CI and deploys never wait, and +an approval later still makes the change the baseline. Choose `wait` when a deploy must not go out with an unreviewed +visual change, and only if an agent or a person is there to review within the timeout: otherwise every push times out. + +A local run's build (from a laptop, `visualci test` or `visualci check`) waits only in its own person's lists, and +leaves them after a week with nothing happening to it (it's kept, closed, in the build list). + Snapshot tests work the same way. With VisualCI, the tests write their snapshots and pass (Jest's `-u`, `INSTA_UPDATE=always INSTA_FORCE_PASS=1`, syrupy's `--snapshot-update`), and the review happens on VisualCI. If a change on main must stop CI before anyone looks, use `ci_mode: strict`, or keep those snapshot files committed and