Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -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/",
Expand Down
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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/",
Expand Down
2 changes: 1 addition & 1 deletion .cursor-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
2 changes: 1 addition & 1 deletion gemini-extension.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down
3 changes: 2 additions & 1 deletion server/frontend/content/docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion server/frontend/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
2 changes: 2 additions & 0 deletions server/frontend/src/components/ui.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ export function ReviewPill({ review }: { review: ReviewState | SnapshotReview })
return <Pill title="Nothing needed a person: the build was approved automatically">auto-approved</Pill>
case 'superseded':
return <Pill title="A later build's review covered these changes">superseded</Pill>
case 'closed':
return <Pill title="Its pull request was closed without merging, or its branch was deleted">closed</Pill>
default:
return null
}
Expand Down
2 changes: 2 additions & 0 deletions server/migration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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)
]
}
Expand Down
43 changes: 43 additions & 0 deletions server/migration/src/m20261202_000040_closed_builds.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
}
16 changes: 16 additions & 0 deletions server/src/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
7 changes: 7 additions & 0 deletions server/src/controllers/forge_webhooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
23 changes: 23 additions & 0 deletions server/src/forge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>, previous: Option<String>, repositories: Vec<Repository> },
/// These people's access may have changed (forge user IDs).
Expand Down Expand Up @@ -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<Option<bool>> {
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 {
Expand Down
114 changes: 100 additions & 14 deletions server/src/forge/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<bool>> {
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<Permission> {
match role {
Expand Down Expand Up @@ -322,27 +341,42 @@ 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<Repository> {
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<ForgeEvent> {
let action = event["action"].as_str().unwrap_or_default();
let installation = event["installation"]["id"].as_i64().map(|i| i.to_string());
let person = |v: &Value| v["id"].as_i64().map(|i| vec![i.to_string()]).unwrap_or_default();
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 {
Expand All @@ -352,6 +386,18 @@ pub fn read_event(kind: &str, event: &Value) -> Result<ForgeEvent> {
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,
Expand Down Expand Up @@ -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" } });
Expand Down
Loading
Loading