diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 09457da1..5e30db86 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,7 +5,7 @@ "plugins": [ { "name": "visualci", - "version": "0.1.32", + "version": "0.1.33", "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 adfa0daf..b04c1584 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.32", + "version": "0.1.33", "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 cf4cb403..5656560c 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "visualci", "displayName": "VisualCI", - "version": "0.1.32", + "version": "0.1.33", "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 b921712a..5683630e 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.32", + "version": "0.1.33", "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 86af8f5d..d20ec647 100644 --- a/server/frontend/content/docs/agents.md +++ b/server/frontend/content/docs/agents.md @@ -171,7 +171,8 @@ unreviewed changes can pile up on main without anyone noticing. Three things kee - The commit's VisualCI check stays pending until the build is reviewed, as on a pull request. - `whoami` lists the newest builds waiting for a review, and `list_builds` with `waiting_for_review: true` lists a - project's. Add a line to your agents' instructions: after a push, review its VisualCI build. + 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. - 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. diff --git a/server/frontend/src/api/types.ts b/server/frontend/src/api/types.ts index 8db9bb32..1a41d5a3 100644 --- a/server/frontend/src/api/types.ts +++ b/server/frontend/src/api/types.ts @@ -146,7 +146,7 @@ export type StaffFeedback = { } export type BuildState = 'receiving' | 'processing' | 'completed' | 'failed' -export type ReviewState = 'none' | 'pending' | 'approved' | 'rejected' | 'auto_approved' | 'superseded' +export type ReviewState = 'none' | 'pending' | 'approved' | 'rejected' | 'auto_approved' | 'superseded' | 'closed' export type Conclusion = 'unchanged' | 'changes' | 'failed' | null export type Stats = { diff --git a/server/frontend/src/components/ui.tsx b/server/frontend/src/components/ui.tsx index 78485c4f..c9fd2bfa 100644 --- a/server/frontend/src/components/ui.tsx +++ b/server/frontend/src/components/ui.tsx @@ -40,6 +40,8 @@ export function ReviewPill({ review }: { review: ReviewState | SnapshotReview }) return auto-approved case 'superseded': return superseded + case 'closed': + return closed default: return null } diff --git a/server/migration/src/lib.rs b/server/migration/src/lib.rs index 96da73cd..0728c611 100644 --- a/server/migration/src/lib.rs +++ b/server/migration/src/lib.rs @@ -43,6 +43,7 @@ mod m20261202_000036_tokens_can_approve; mod m20261202_000037_review_source; mod m20261202_000038_matches_approved; mod m20261202_000039_repository_id; +mod m20261202_000040_closed_builds; pub struct Migrator; @@ -92,6 +93,7 @@ impl MigratorTrait for Migrator { Box::new(m20261202_000037_review_source::Migration), Box::new(m20261202_000038_matches_approved::Migration), Box::new(m20261202_000039_repository_id::Migration), + Box::new(m20261202_000040_closed_builds::Migration), // inject-above (do not remove this comment) ] } diff --git a/server/migration/src/m20261202_000040_closed_builds.rs b/server/migration/src/m20261202_000040_closed_builds.rs new file mode 100644 index 00000000..767e0d7a --- /dev/null +++ b/server/migration/src/m20261202_000040_closed_builds.rs @@ -0,0 +1,43 @@ +//! A build waiting for review whose pull request was closed without merging, or whose branch was deleted, stops +//! waiting: its review state is `closed` (`builds::Model::close_waiting`). `branch_checks` records when the forge +//! sync last asked whether a branch with builds waiting still exists, so each is asked at most once a day. +use sea_orm_migration::prelude::*; + +pub struct Migration; + +impl MigrationName for Migration { + fn name(&self) -> &str { + "m20261202_000040_closed_builds" + } +} + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection() + .execute_unprepared( + "ALTER TABLE builds DROP CONSTRAINT builds_review_state_check, \ + ADD CONSTRAINT builds_review_state_check CHECK (review_state IN \ + ('none', 'pending', 'approved', 'rejected', 'auto_approved', 'superseded', 'closed')); \ + CREATE TABLE branch_checks ( \ + project_id BIGINT NOT NULL REFERENCES projects(id) ON DELETE CASCADE, \ + branch TEXT NOT NULL, \ + checked_at TIMESTAMPTZ NOT NULL DEFAULT now(), \ + PRIMARY KEY (project_id, branch));", + ) + .await?; + Ok(()) + } + + async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection() + .execute_unprepared( + "DROP TABLE branch_checks; UPDATE builds SET review_state = 'pending' WHERE review_state = 'closed'; \ + ALTER TABLE builds DROP CONSTRAINT builds_review_state_check, \ + ADD CONSTRAINT builds_review_state_check CHECK (review_state IN \ + ('none', 'pending', 'approved', 'rejected', 'auto_approved', 'superseded'));", + ) + .await?; + Ok(()) + } +} diff --git a/server/src/access.rs b/server/src/access.rs index b182aae6..4032a9ee 100644 --- a/server/src/access.rs +++ b/server/src/access.rs @@ -761,6 +761,22 @@ pub async fn handle_event(ctx: &AppContext, forge: &Forge, event: ForgeEvent) -> tracing::info!(repo = repository.path, head, base, merge_commit, recorded, "pull request merged"); serde_json::json!({ "recorded": recorded }) } + ForgeEvent::Closed { repository, branch, why } => { + let mut closed = 0; + for project in linked(db, &repository).await? { + closed += crate::workers::close_branch(ctx, project.id, &branch, why).await?; + } + tracing::info!(repo = repository.path, branch, why, closed, "branch closed"); + serde_json::json!({ "closed": closed }) + } + ForgeEvent::Reopened { repository, branch } => { + let mut reopened = 0; + for project in linked(db, &repository).await? { + reopened += crate::workers::reopen_branch(ctx, project.id, &branch).await?; + } + tracing::info!(repo = repository.path, branch, reopened, "pull request reopened"); + serde_json::json!({ "reopened": reopened }) + } ForgeEvent::Installation { installation, previous, repositories } => { let mut changed = 0; let mut affected = HashSet::new(); diff --git a/server/src/controllers/forge_webhooks.rs b/server/src/controllers/forge_webhooks.rs index bfd38b35..7a1cee3b 100644 --- a/server/src/controllers/forge_webhooks.rs +++ b/server/src/controllers/forge_webhooks.rs @@ -85,6 +85,13 @@ async fn gitlab_project( crate::models::baselines::record_merge(&ctx.db, project.id, &head, &base, &merge_commit).await?; serde_json::json!({ "recorded": recorded }) } + // This project only, like merges: the hook belongs to it. + crate::forge::ForgeEvent::Closed { branch, why, .. } => { + serde_json::json!({ "closed": crate::workers::close_branch(&ctx, project.id, &branch, why).await? }) + } + crate::forge::ForgeEvent::Reopened { branch, .. } => { + serde_json::json!({ "reopened": crate::workers::reopen_branch(&ctx, project.id, &branch).await? }) + } other => access::handle_event(&ctx, &forge, other).await?, }; tracing::info!(forge = "gitlab", kind, repo = repository.path, project = %project.pid, outcome = %outcome, "webhook"); diff --git a/server/src/forge.rs b/server/src/forge.rs index 6a50a3c4..112ac2e4 100644 --- a/server/src/forge.rs +++ b/server/src/forge.rs @@ -268,6 +268,11 @@ pub struct SignIn { pub enum ForgeEvent { /// A pull request merged: its approvals become the base branch's at the merge commit. Merged { repository: Repository, head: String, base: String, merge_commit: String }, + /// A pull request closed without merging (`why` "pull_request"), or a branch deleted ("branch_deleted"): the + /// branch's builds waiting for review stop waiting (`closed`). + Closed { repository: Repository, branch: String, why: &'static str }, + /// A closed pull request reopened: its branch's newest closed build waits for review again. + Reopened { repository: Repository, branch: String }, /// The forge app was installed on these repositories (`installation` set) or removed from them (`None`). Installation { installation: Option, previous: Option, repositories: Vec }, /// These people's access may have changed (forge user IDs). @@ -453,6 +458,24 @@ impl Forge { } } + /// Whether a branch still exists (`None` when the repository can't be seen). + /// + /// # Errors + /// When the forge can't be reached or refuses the app's credentials. + pub async fn branch_exists( + &self, + repository: &Repository, + installation: &str, + branch: &str, + ) -> Result> { + match self { + Self::Github(s) => github::branch_exists(s, &repository.path, installation, branch).await, + Self::Gitlab(s) => { + gitlab::branch_exists(s, &repository.path, gitlab::token(s, installation)?, branch).await + } + } + } + /// How someone gives VisualCI access to a repository: install the GitHub App, invite the GitLab bot. #[must_use] pub fn install_hint(&self, repository: &Repository) -> String { diff --git a/server/src/forge/github.rs b/server/src/forge/github.rs index a8cec2a7..81c20ede 100644 --- a/server/src/forge/github.rs +++ b/server/src/forge/github.rs @@ -112,6 +112,25 @@ pub async fn visibility( })) } +/// Whether a branch exists in a repository (`None` when the repository can't be seen). Needs only the Metadata +/// permission. +/// +/// # Errors +/// When GitHub can't be reached or refuses the app's credentials. +pub async fn branch_exists( + settings: &GithubSettings, + repo: &str, + installation: &str, + branch: &str, +) -> Result> { + let token = installation_token(settings, installation).await?; + if get(&token, &format!("/repos/{repo}")).await?.is_none() { + return Ok(None); + } + let branch: String = url::form_urlencoded::byte_serialize(branch.as_bytes()).collect(); + Ok(Some(get(&token, &format!("/repos/{repo}/branches/{branch}")).await?.is_some())) +} + /// GitHub's role name for a collaborator (`admin`, `maintain`, `write`, `triage`, `read`, or a custom role's base). fn permission_from(role: &str) -> Option { match role { @@ -322,6 +341,32 @@ pub fn parse_webhook( /// /// # Errors /// `BadRequest` for a merged pull request without its branches or merge commit. +/// The repository an event names, with GitHub's ID for it (which survives a rename). +fn repository(event: &Value) -> Option { + event["repository"]["full_name"] + .as_str() + .and_then(Repository::parse) + .map(|r| r.with_id(event["repository"]["id"].as_i64().map(|i| i.to_string()))) +} + +/// A pull request event's branch: a fork's goes by its head label (`octocat:main`), as the CLI names it, so a fork's +/// `main` isn't taken for the base repository's. +fn pr_branch(event: &Value) -> Option<&str> { + let pr = &event["pull_request"]; + let head_repo = pr["head"]["repo"]["full_name"].as_str(); + let from_fork = head_repo.is_some() && head_repo != event["repository"]["full_name"].as_str(); + if from_fork { pr["head"]["label"].as_str() } else { pr["head"]["ref"].as_str() } +} + +fn deleted_branch(event: &Value, branch: Option<&str>) -> ForgeEvent { + match (repository(event), branch) { + (Some(repository), Some(branch)) => { + ForgeEvent::Closed { repository, branch: branch.to_string(), why: "branch_deleted" } + } + _ => ForgeEvent::Ignored, + } +} + pub fn read_event(kind: &str, event: &Value) -> Result { let action = event["action"].as_str().unwrap_or_default(); let installation = event["installation"]["id"].as_i64().map(|i| i.to_string()); @@ -329,20 +374,9 @@ pub fn read_event(kind: &str, event: &Value) -> Result { Ok(match (kind, action) { ("pull_request", "closed") if event["pull_request"]["merged"] == true => { let pr = &event["pull_request"]; - // A fork's branch goes by its head label (`octocat:main`), as the CLI names it, so a fork's `main` - // isn't taken for the base repository's. - let head_repo = pr["head"]["repo"]["full_name"].as_str(); - let from_fork = head_repo.is_some() && head_repo != event["repository"]["full_name"].as_str(); - let head = if from_fork { pr["head"]["label"].as_str() } else { pr["head"]["ref"].as_str() }; - let (Some(repository), Some(head), Some(base), Some(merge)) = ( - event["repository"]["full_name"] - .as_str() - .and_then(Repository::parse) - .map(|r| r.with_id(event["repository"]["id"].as_i64().map(|i| i.to_string()))), - head, - pr["base"]["ref"].as_str(), - pr["merge_commit_sha"].as_str(), - ) else { + let (Some(repository), Some(head), Some(base), Some(merge)) = + (repository(event), pr_branch(event), pr["base"]["ref"].as_str(), pr["merge_commit_sha"].as_str()) + else { return Err(Error::BadRequest("a merged pull request without its branches or merge commit".into())); }; ForgeEvent::Merged { @@ -352,6 +386,18 @@ pub fn read_event(kind: &str, event: &Value) -> Result { merge_commit: merge.to_string(), } } + ("pull_request", "closed" | "reopened") => match (repository(event), pr_branch(event)) { + (Some(repository), Some(branch)) if action == "closed" => { + ForgeEvent::Closed { repository, branch: branch.to_string(), why: "pull_request" } + } + (Some(repository), Some(branch)) => ForgeEvent::Reopened { repository, branch: branch.to_string() }, + _ => ForgeEvent::Ignored, + }, + // A branch deleted: GitHub sends `delete` (ref_type branch) and a `push` with `deleted: true`. + ("delete", _) if event["ref_type"] == "branch" => deleted_branch(event, event["ref"].as_str()), + ("push", _) if event["deleted"] == true => { + deleted_branch(event, event["ref"].as_str().and_then(|r| r.strip_prefix("refs/heads/"))) + } ("installation", "created" | "unsuspend") => ForgeEvent::Installation { installation, previous: None, @@ -517,6 +563,46 @@ mod tests { assert_eq!(permission_from("none"), None); } + #[test] + fn reads_closed_and_reopened_pull_requests_and_deleted_branches() { + let repo = serde_json::json!({ "full_name": "acme/web" }); + let pr = |action: &str, merged: bool| { + serde_json::json!({ "action": action, "repository": repo, + "pull_request": { "merged": merged, "head": { "ref": "feature" }, "base": { "ref": "main" } } }) + }; + let web = Repository::parse("acme/web").unwrap(); + assert_eq!( + read_event("pull_request", &pr("closed", false)).unwrap(), + ForgeEvent::Closed { repository: web.clone(), branch: "feature".into(), why: "pull_request" } + ); + assert_eq!( + read_event("pull_request", &pr("reopened", false)).unwrap(), + ForgeEvent::Reopened { repository: web.clone(), branch: "feature".into() } + ); + assert_eq!( + read_event("delete", &serde_json::json!({ "ref": "feature", "ref_type": "branch", "repository": repo })) + .unwrap(), + ForgeEvent::Closed { repository: web.clone(), branch: "feature".into(), why: "branch_deleted" } + ); + assert_eq!( + read_event("delete", &serde_json::json!({ "ref": "v1", "ref_type": "tag", "repository": repo })).unwrap(), + ForgeEvent::Ignored + ); + assert_eq!( + read_event( + "push", + &serde_json::json!({ "ref": "refs/heads/feature", "deleted": true, "repository": repo }) + ) + .unwrap(), + ForgeEvent::Closed { repository: web, branch: "feature".into(), why: "branch_deleted" } + ); + assert_eq!( + read_event("push", &serde_json::json!({ "ref": "refs/tags/v1", "deleted": true, "repository": repo })) + .unwrap(), + ForgeEvent::Ignored + ); + } + #[test] fn reads_membership_events() { let event = serde_json::json!({ "action": "removed", "member": { "id": 7, "login": "octo" } }); diff --git a/server/src/forge/gitlab.rs b/server/src/forge/gitlab.rs index d964e05f..4de647ac 100644 --- a/server/src/forge/gitlab.rs +++ b/server/src/forge/gitlab.rs @@ -303,6 +303,29 @@ pub fn read_event(kind: &str, event: &Value) -> Result { }; ForgeEvent::Merged { repository, head, base: base.to_string(), merge_commit: merge.to_string() } } + "Merge Request Hook" if matches!(event["object_attributes"]["action"].as_str(), Some("close" | "reopen")) => { + let mr = &event["object_attributes"]; + let head = mr["source_branch"].as_str().map(|head| match mr["source"]["path_with_namespace"].as_str() { + Some(fork) if mr["source_project_id"] != mr["target_project_id"] => format!("{fork}:{head}"), + _ => head.to_string(), + }); + match (project(), head) { + (Some(repository), Some(branch)) if mr["action"] == "close" => { + ForgeEvent::Closed { repository, branch, why: "pull_request" } + } + (Some(repository), Some(branch)) => ForgeEvent::Reopened { repository, branch }, + _ => ForgeEvent::Ignored, + } + } + // A branch deleted: a push whose new commit is all zeros. + "Push Hook" if event["after"].as_str().is_some_and(|a| !a.is_empty() && a.bytes().all(|b| b == b'0')) => { + match (project(), event["ref"].as_str().and_then(|r| r.strip_prefix("refs/heads/"))) { + (Some(repository), Some(branch)) => { + ForgeEvent::Closed { repository, branch: branch.to_string(), why: "branch_deleted" } + } + _ => ForgeEvent::Ignored, + } + } // Group membership changed (a group webhook): `user_add_to_group`, `user_remove_from_group`, // `user_update_for_group`, `user_access_request_*`. "Member Hook" => ForgeEvent::Access { people: person(&event["user_id"]) }, @@ -362,6 +385,20 @@ pub async fn bot_level(settings: &GitlabSettings, path: &str) -> Result 0)) } +/// Whether a branch exists in a project (`None` when the project can't be seen). +/// +/// # Errors +/// When GitLab can't be reached or refuses the token. +pub async fn branch_exists(settings: &GitlabSettings, path: &str, token: &str, branch: &str) -> Result> { + if get(settings, token, &format!("/projects/{}", project_id(path))).await?.is_none() { + return Ok(None); + } + let encoded: String = url::form_urlencoded::byte_serialize(branch.as_bytes()).collect(); + Ok(Some( + get(settings, token, &format!("/projects/{}/repository/branches/{encoded}", project_id(path))).await?.is_some(), + )) +} + /// Whether a project is public and which licence GitLab detected, as an SPDX id where it's one VisualCI knows /// (GitLab names licences by a lowercase key: `mit`, `apache-2.0`). /// @@ -416,7 +453,8 @@ pub async fn ensure_hook(settings: &GitlabSettings, path: &str, token: &str, url "url": url, "token": secret, "merge_requests_events": true, - "push_events": false, + // Pushes only for branches deleted (`after` all zeros): their builds stop waiting for review. + "push_events": true, "enable_ssl_verification": url.starts_with("https://"), })) .send() @@ -537,6 +575,31 @@ mod tests { assert_eq!(read_event("Push Hook", &serde_json::json!({})).unwrap(), ForgeEvent::Ignored); } + #[test] + fn reads_closed_and_reopened_merge_requests_and_deleted_branches() { + let project = serde_json::json!({ "web_url": "https://gitlab.com/acme/web" }); + let mr = |action: &str| { + serde_json::json!({ "project": project, "object_attributes": { + "action": action, "source_branch": "feature", "target_branch": "main", + "source_project_id": 1, "target_project_id": 1 } }) + }; + let web = Repository::parse_gitlab("https://gitlab.com/acme/web").unwrap(); + assert_eq!( + read_event("Merge Request Hook", &mr("close")).unwrap(), + ForgeEvent::Closed { repository: web.clone(), branch: "feature".into(), why: "pull_request" } + ); + assert_eq!( + read_event("Merge Request Hook", &mr("reopen")).unwrap(), + ForgeEvent::Reopened { repository: web.clone(), branch: "feature".into() } + ); + let push = |after: &str| serde_json::json!({ "project": project, "ref": "refs/heads/feature", "after": after }); + assert_eq!( + read_event("Push Hook", &push("0000000000000000000000000000000000000000")).unwrap(), + ForgeEvent::Closed { repository: web, branch: "feature".into(), why: "branch_deleted" } + ); + assert_eq!(read_event("Push Hook", &push("1a2b3c")).unwrap(), ForgeEvent::Ignored); + } + #[test] fn checks_the_hook_token() { assert!(token_matches("s3cret", "s3cret")); diff --git a/server/src/models/builds.rs b/server/src/models/builds.rs index 39c2f3c3..5c6389f8 100644 --- a/server/src/models/builds.rs +++ b/server/src/models/builds.rs @@ -1018,6 +1018,59 @@ impl Model { } } +/// 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. +pub const CLOSED_BRANCH_DELETED: &str = "Closed without review: the branch was deleted."; + +impl Model { + /// A pull request closed without merging (`why` "pull_request") or its branch deleted ("branch_deleted"): the + /// branch's builds waiting for review in this project stop waiting. They become `closed`, leave the waiting lists + /// and say why; their snapshots stay. Returns their ids, so their checks can say so. + /// + /// # Errors + /// On a database error. + pub async fn close_waiting( + db: &impl ConnectionTrait, + project_id: i64, + branch: &str, + why: &str, + ) -> ModelResult> { + let note = if why == "branch_deleted" { CLOSED_BRANCH_DELETED } else { CLOSED_PULL_REQUEST }; + let rows = db + .query_all_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "UPDATE builds SET review_state = 'closed', warnings = warnings || jsonb_build_array($3::TEXT), \ + updated_at = now() \ + WHERE project_id = $1 AND branch = $2 AND review_state = 'pending' RETURNING id", + [project_id.into(), branch.into(), note.into()], + )) + .await?; + Ok(rows.iter().filter_map(|r| r.try_get::("", "id").ok()).collect()) + } + + /// A closed pull request reopened: its branch's newest closed build waits for review again (older ones stay closed: + /// the newest covers them). Returns its id. + /// + /// # Errors + /// On a database error. + pub async fn reopen_latest(db: &impl ConnectionTrait, project_id: i64, branch: &str) -> ModelResult> { + let row = db + .query_one_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "UPDATE builds SET review_state = 'pending', updated_at = now(), \ + warnings = COALESCE((SELECT jsonb_agg(w) FROM jsonb_array_elements(warnings) w \ + WHERE w #>> '{}' NOT IN ($3, $4)), '[]'::jsonb) \ + WHERE id = (SELECT id FROM builds WHERE project_id = $1 AND branch = $2 AND review_state = 'closed' \ + ORDER BY id DESC LIMIT 1) \ + RETURNING id", + [project_id.into(), branch.into(), CLOSED_PULL_REQUEST.into(), CLOSED_BRANCH_DELETED.into()], + )) + .await?; + Ok(row.and_then(|r| r.try_get::("", "id").ok())) + } +} + fn stats_of(snapshots: &[snapshots::Model]) -> Stats { let mut stats = Stats::default(); for s in snapshots { diff --git a/server/src/tasks/forge_sync.rs b/server/src/tasks/forge_sync.rs index a6c0e149..bbdb2a46 100644 --- a/server/src/tasks/forge_sync.rs +++ b/server/src/tasks/forge_sync.rs @@ -65,6 +65,13 @@ impl Task for ForgeSync { return Err(e); } } + // Builds waiting on branches deleted without a pull request: the forge doesn't send that event to VisualCI (the + // app has no Contents permission), so each such branch is asked about once a day. + match crate::workers::close_deleted_branches(ctx, 500).await { + Ok(0) => {} + Ok(n) => println!("branches: {n} builds of deleted branches closed"), + Err(e) => tracing::warn!(error = %e, "closing builds of deleted branches"), + } // GitLab projects whose webhook isn't working yet: their bot may have become a Maintainer since they were // linked, so VisualCI can add it now. let waiting = crate::models::_entities::projects::Entity::find() diff --git a/server/src/workers/forge_check.rs b/server/src/workers/forge_check.rs index 5e281bea..6958e416 100644 --- a/server/src/workers/forge_check.rs +++ b/server/src/workers/forge_check.rs @@ -47,6 +47,8 @@ pub fn check_state( ("completed", _, "superseded") => { done("neutral", superseded_by.map_or_else(|| "Superseded".to_string(), |n| format!("Superseded by #{n}"))) } + // Its pull request was closed without merging, or its branch deleted. + ("completed", _, "closed") => done("neutral", "Closed without review".to_string()), ("completed", _, _) if build.mode == "local" => done("neutral", format!("{changes} changes (local run)")), ("completed", _, _) if build.settings(project).ci_mode() == "strict" => { done("failure", format!("{changes} changes to review")) diff --git a/server/src/workers/mod.rs b/server/src/workers/mod.rs index 942670cc..eadf272c 100644 --- a/server/src/workers/mod.rs +++ b/server/src/workers/mod.rs @@ -33,6 +33,82 @@ pub async fn expire_abandoned(ctx: &AppContext, project_id: Option) -> Resu Ok(expired.failed.len() + expired.finished.len()) } +/// A branch's pull request closed without merging, or the branch deleted: its builds waiting for review in this project +/// stop waiting, and their checks and pull request comment say so. Returns how many. +/// +/// # Errors +/// On a database or queue error. +pub async fn close_branch(ctx: &AppContext, project_id: i64, branch: &str, why: &str) -> Result { + let ids = crate::models::builds::Model::close_waiting(&ctx.db, project_id, branch, why).await?; + for id in &ids { + build_changed(ctx, *id).await?; + } + Ok(ids.len()) +} + +/// Builds waiting for review on branches that no longer exist (deleted without a pull request, which the forge doesn't +/// tell VisualCI about): asked of the forge by the hourly sync, each branch with builds waiting at most once a day and +/// at most `limit` branches a run, and their builds closed. Fork branches (`owner:branch`) aren't asked. Returns how +/// many builds it closed. +/// +/// # Errors +/// On a database error. A forge that can't be asked is skipped (and asked again the next day). +pub async fn close_deleted_branches(ctx: &AppContext, limit: i64) -> Result { + use sea_orm::{ConnectionTrait, DbBackend, Statement}; + let settings = crate::settings::Settings::from_context(ctx)?; + let rows = ctx + .db + .query_all_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "SELECT DISTINCT b.project_id, b.branch FROM builds b \ + LEFT JOIN branch_checks c ON c.project_id = b.project_id AND c.branch = b.branch \ + WHERE b.review_state = 'pending' AND b.mode = 'ci' AND b.branch <> '' AND position(':' in b.branch) = 0 \ + AND (c.checked_at IS NULL OR c.checked_at < now() - interval '1 day') \ + ORDER BY b.project_id, b.branch LIMIT $1", + [limit.into()], + )) + .await?; + let mut closed = 0; + for row in rows { + let (project_id, branch): (i64, String) = (row.try_get("", "project_id")?, row.try_get("", "branch")?); + let project = crate::models::projects::Model::find_by_id(&ctx.db, project_id).await?; + let Some((forge, repository, installation)) = + crate::forge::Forge::for_project(&ctx.db, &settings, &project).await? + else { + continue; + }; + match forge.branch_exists(&repository, &installation, &branch).await { + Ok(Some(false)) => closed += close_branch(ctx, project_id, &branch, "branch_deleted").await?, + Ok(_) => {} + Err(e) => { + tracing::warn!(error = %e, repo = repository.path, branch, "asking whether a branch exists"); + continue; + } + } + ctx.db + .execute_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "INSERT INTO branch_checks (project_id, branch) VALUES ($1, $2) \ + ON CONFLICT (project_id, branch) DO UPDATE SET checked_at = now()", + [project_id.into(), branch.into()], + )) + .await?; + } + Ok(closed) +} + +/// A closed pull request reopened: its branch's newest closed build waits for review again. Returns how many (0 or 1). +/// +/// # Errors +/// On a database or queue error. +pub async fn reopen_branch(ctx: &AppContext, project_id: i64, branch: &str) -> Result { + let id = crate::models::builds::Model::reopen_latest(&ctx.db, project_id, branch).await?; + if let Some(id) = id { + build_changed(ctx, id).await?; + } + Ok(usize::from(id.is_some())) +} + /// A build's state changed (processed, reviewed, superseded): update its check and pull request comment on the forge, /// and purge the public gallery's cached copies it makes stale. /// diff --git a/server/src/workers/pr_comment.rs b/server/src/workers/pr_comment.rs index efdf4d8f..f1e56715 100644 --- a/server/src/workers/pr_comment.rs +++ b/server/src/workers/pr_comment.rs @@ -77,6 +77,7 @@ fn status_line(s: &Suite) -> String { (_, "approved" | "auto_approved") if s.stats.changes() > 0 => "approved".to_string(), (_, "rejected") => "rejected".to_string(), (_, "superseded") => "superseded by a newer build".to_string(), + (_, "closed") => "closed without review".to_string(), _ if s.stats.changes() == 0 => "no changes".to_string(), _ => s.review_state.replace('_', " "), } diff --git a/server/tests/requests/forge_webhooks.rs b/server/tests/requests/forge_webhooks.rs index 9d9c3f22..7051807f 100644 --- a/server/tests/requests/forge_webhooks.rs +++ b/server/tests/requests/forge_webhooks.rs @@ -8,7 +8,7 @@ use serial_test::serial; use sha2::Sha256; use visualci_server::{ app::App, - models::{_entities::users, organizations, projects}, + models::{_entities::users, builds, organizations, projects}, }; async fn send(request: &axum_test::TestServer, event: &str, body: serde_json::Value) -> axum_test::TestResponse { @@ -140,7 +140,106 @@ async fn a_merged_pull_request_is_recorded_and_a_closed_one_ignored() { assert_eq!(merged.status_code(), 200); assert_eq!(merged.json::()["recorded"], 0, "nothing approved on the branch yet"); let closed = send(&request, "pull_request", pr(false)).await; - assert_eq!(closed.json::()["ignored"], true); + assert_eq!(closed.json::()["closed"], 0, "no builds waiting on the branch"); + }) + .await; +} + +/// A build of `branch` waiting for review. +async fn waiting_build(ctx: &loco_rs::prelude::AppContext, project: &projects::Model, branch: &str) -> i64 { + use sea_orm::{ConnectionTrait, DbBackend, Statement}; + let params: builds::CreateParams = + serde_json::from_value(serde_json::json!({ "commit": "abc123", "branch": branch })).unwrap(); + let build = builds::Model::create(&ctx.db, project, ¶ms).await.unwrap(); + ctx.db + .execute_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "UPDATE builds SET state = 'completed', conclusion = 'changes', review_state = 'pending' WHERE id = $1", + [build.id.into()], + )) + .await + .unwrap(); + build.id +} + +async fn review_state(ctx: &loco_rs::prelude::AppContext, id: i64) -> (String, Vec) { + let b = builds::Model::find_by_id(&ctx.db, id).await.unwrap(); + (b.review_state, serde_json::from_value(b.warnings).unwrap()) +} + +#[tokio::test] +#[serial] +async fn a_closed_pull_request_or_deleted_branch_stops_its_builds_waiting() { + request::(|request, ctx| async move { + use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, IntoActiveModel, PaginatorTrait, QueryFilter, Set}; + // Linked to the repository, without an installation: the builds' checks have nowhere to go here (they'd ask + // GitHub). + let p = linked_project(&ctx).await; + let mut a = p.into_active_model(); + a.forge_installation = Set(None); + let p = a.update(&ctx.db).await.unwrap(); + let pr = |action: &str| { + serde_json::json!({ + "action": action, + "repository": { "full_name": full_name(&p) }, + "pull_request": { "merged": false, "head": { "ref": "feature" }, "base": { "ref": "main" } }, + }) + }; + let older = waiting_build(&ctx, &p, "feature").await; + let newer = waiting_build(&ctx, &p, "feature").await; + let other = waiting_build(&ctx, &p, "other").await; + + // Closed without merging: the branch's waiting builds stop waiting, and say why; another branch's don't. + let r = send(&request, "pull_request", pr("closed")).await; + assert_eq!(r.status_code(), 200, "{}", r.text()); + assert_eq!(r.json::()["closed"], 2); + for id in [older, newer] { + let (state, warnings) = review_state(&ctx, id).await; + assert_eq!(state, "closed"); + assert_eq!(warnings, [builds::CLOSED_PULL_REQUEST]); + } + assert_eq!(review_state(&ctx, other).await.0, "pending"); + let waiting = builds::Entity::find() + .filter(builds::builds::Column::ProjectId.eq(p.id)) + .filter(builds::builds::Column::ReviewState.eq("pending")) + .count(&ctx.db) + .await + .unwrap(); + assert_eq!(waiting, 1, "only the other branch's build still waits"); + + // Reopened: the newest waits again, without the note; the older stays closed (the newest covers it). + let r = send(&request, "pull_request", pr("reopened")).await; + assert_eq!(r.json::()["reopened"], 1); + assert_eq!(review_state(&ctx, newer).await, ("pending".to_string(), vec![])); + assert_eq!(review_state(&ctx, older).await.0, "closed"); + + // The branch deleted (GitHub sends `delete`, and a `push` with deleted: true). + let repo = serde_json::json!({ "full_name": full_name(&p) }); + let r = + send(&request, "delete", serde_json::json!({ "ref": "feature", "ref_type": "branch", "repository": repo })) + .await; + assert_eq!(r.json::()["closed"], 1); + assert_eq!( + review_state(&ctx, newer).await, + ("closed".to_string(), vec![builds::CLOSED_BRANCH_DELETED.to_string()]) + ); + let r = send( + &request, + "push", + serde_json::json!({ "ref": "refs/heads/other", "deleted": true, "repository": repo }), + ) + .await; + assert_eq!(r.json::()["closed"], 1); + assert_eq!(review_state(&ctx, other).await.0, "closed"); + + // Its check: neutral, closed without review. + let project = projects::Model::find_by_id(&ctx.db, p.id).await.unwrap(); + let build = builds::Model::find_by_id(&ctx.db, other).await.unwrap(); + let (status, conclusion, title) = visualci_server::workers::forge_check::check_state(&build, &project, None); + assert_eq!( + (status.as_str(), conclusion.as_deref(), title.as_str()), + ("completed", Some("neutral"), "Closed without review") + ); }) .await; } @@ -188,3 +287,33 @@ async fn a_repository_made_private_makes_its_projects_private() { }) .await; } + +#[tokio::test] +#[serial] +async fn the_daily_branch_check_skips_projects_it_cannot_ask() { + request::(|_request, ctx| async move { + use sea_orm::{ActiveModelTrait, ConnectionTrait, DbBackend, IntoActiveModel, Set, Statement}; + // No installation: the forge can't be asked, so the branch is neither closed nor marked checked. + let p = linked_project(&ctx).await; + let mut a = p.into_active_model(); + a.forge_installation = Set(None); + let p = a.update(&ctx.db).await.unwrap(); + let id = waiting_build(&ctx, &p, "gone").await; + assert_eq!(visualci_server::workers::close_deleted_branches(&ctx, 10).await.unwrap(), 0); + assert_eq!(review_state(&ctx, id).await.0, "pending"); + let checked = ctx + .db + .query_one_raw(Statement::from_sql_and_values( + DbBackend::Postgres, + "SELECT count(*) AS n FROM branch_checks WHERE project_id = $1", + [p.id.into()], + )) + .await + .unwrap() + .unwrap() + .try_get::("", "n") + .unwrap(); + assert_eq!(checked, 0, "asked again on the next run"); + }) + .await; +} diff --git a/skills/visualci-review/SKILL.md b/skills/visualci-review/SKILL.md index ba42107f..d36e9fcb 100644 --- a/skills/visualci-review/SKILL.md +++ b/skills/visualci-review/SKILL.md @@ -176,7 +176,8 @@ unreviewed changes can pile up on main without anyone noticing. Three things kee - The commit's VisualCI check stays pending until the build is reviewed, as on a pull request. - `whoami` lists the newest builds waiting for a review, and `list_builds` with `waiting_for_review: true` lists a - project's. Add a line to your agents' instructions: after a push, review its VisualCI build. + 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. - 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.