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.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/",
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.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/",
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.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"
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.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": {
Expand Down
13 changes: 10 additions & 3 deletions server/frontend/content/docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
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 @@ -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;

Expand Down Expand Up @@ -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)
]
}
Expand Down
28 changes: 28 additions & 0 deletions server/migration/src/m20261202_000041_build_creator.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
}
16 changes: 16 additions & 0 deletions server/src/controllers/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,15 @@ impl axum::extract::FromRequestParts<AppContext> 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 {
Expand Down Expand Up @@ -205,13 +214,20 @@ fn model_error(e: ModelError) -> Error {
async fn create_build(
ProjectAuth(project): ProjectAuth,
State(ctx): State<AppContext>,
headers: axum::http::HeaderMap,
Body(params): Body<builds::CreateParams>,
) -> Result<Response> {
let settings = Settings::from_context(&ctx)?;
// The project's earlier builds that stopped arriving are given up on now (also every few minutes by
// `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, &params).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)
Expand Down
32 changes: 23 additions & 9 deletions server/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ pub struct ListBuildsArgs {
pub branch: Option<String>,
/// How many, newest first (default 20, at most 100).
pub limit: Option<u64>,
/// 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<bool>,
}

Expand Down Expand Up @@ -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<Vec<serde_json::Value>, 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<i64>,
) -> Result<Vec<serde_json::Value>, ErrorData> {
let ids: Vec<i64> = reachable.iter().map(|p| p.id).collect();
let pending = builds::Entity::find()
let pending: Vec<builds::Model> = 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 };
Expand Down Expand Up @@ -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)?
Expand All @@ -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)?;
Expand Down Expand Up @@ -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?);
Expand Down Expand Up @@ -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, &params).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())),
}
}
Expand Down
2 changes: 2 additions & 0 deletions server/src/models/_entities/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<i64>,
pub finalized_at: Option<DateTimeWithTimeZone>,
pub completed_at: Option<DateTimeWithTimeZone>,
pub created_at: DateTimeWithTimeZone,
Expand Down
52 changes: 52 additions & 0 deletions server/src/models/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<i64>) -> 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<Vec<i64>> {
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::<i64>("", "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.
Expand Down
5 changes: 5 additions & 0 deletions server/src/tasks/builds_expire.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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?;
Expand Down
Loading
Loading