From 209d68472fe15b1829c29d86f84d03886f5b3931 Mon Sep 17 00:00:00 2001
From: Nathan Broadbent
Date: Sat, 5 Dec 2026 11:54:02 +0000
Subject: [PATCH 1/3] Gallery versions (sc-9563): visualci release records what
the gallery published at a commit, kept for good at
/g//@.json and its own image URLs; every manifest lists
the versions newest first; versions on the project page; retention and
project deletion keep their blobs; a version's thumbnails filled in by the
sync; POST/GET /api/v1/versions; a guide with GitHub Actions, CircleCI and
GitLab examples; CLI 0.2.30; plugin 0.1.68
---
Cargo.lock | 8 +-
Cargo.toml | 2 +-
.../2026_12_14_000000_gallery_versions.rs | 48 ++
app/src/domain/baselines.rs | 34 +-
app/src/domain/builds.rs | 7 +-
app/src/domain/gallery.rs | 58 ++-
app/src/domain/gallery_thumbs.rs | 47 +-
app/src/domain/gallery_versions.rs | 428 ++++++++++++++++++
app/src/domain/mod.rs | 1 +
app/src/domain/project_deletion.rs | 5 +
app/src/domain/retention.rs | 4 +
app/src/http/api/mod.rs | 10 +
app/src/http/api/versions.rs | 76 ++++
app/src/http/gallery.rs | 85 +++-
app/tests/gallery.rs | 118 +++++
.../get_project.json | 5 +-
.../get_project.json | 5 +-
.../get_project-2.json | 5 +-
.../get_project.json | 5 +-
clients/circleci-orb/orb.yml | 10 +-
clients/github-action/action.yml | 2 +-
.../examples/release/circleci.yml | 22 +
.../examples/release/github-actions.yml | 21 +
.../examples/release/gitlab-ci.yml | 12 +
crates/visualci-cli/src/ci.rs | 32 ++
crates/visualci-cli/src/client.rs | 5 +
crates/visualci-cli/src/config_file.rs | 13 +
crates/visualci-cli/src/main.rs | 40 ++
frontend/content/docs/gallery.md | 2 +
frontend/content/docs/gallery/versions.md | 116 +++++
frontend/content/docs/reference/api.md | 4 +
frontend/content/docs/reference/cli.md | 4 +
frontend/src/api/types.ts | 2 +
frontend/src/docs/nav.ts | 2 +-
frontend/src/pages/ProjectPage.tsx | 13 +
plugin/skills/visualci-gallery/SKILL.md | 2 +
36 files changed, 1198 insertions(+), 55 deletions(-)
create mode 100644 app/database/migrations/2026_12_14_000000_gallery_versions.rs
create mode 100644 app/src/domain/gallery_versions.rs
create mode 100644 app/src/http/api/versions.rs
create mode 100644 crates/visualci-cli/examples/release/circleci.yml
create mode 100644 crates/visualci-cli/examples/release/github-actions.yml
create mode 100644 crates/visualci-cli/examples/release/gitlab-ci.yml
create mode 100644 frontend/content/docs/gallery/versions.md
diff --git a/Cargo.lock b/Cargo.lock
index ddd79d659..5a0089495 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5470,7 +5470,7 @@ dependencies = [
[[package]]
name = "visualci-cli"
-version = "0.2.29"
+version = "0.2.30"
dependencies = [
"anyhow",
"base64 0.22.1",
@@ -5487,7 +5487,7 @@ dependencies = [
[[package]]
name = "visualci-core"
-version = "0.2.29"
+version = "0.2.30"
dependencies = [
"globset",
"hex",
@@ -5507,7 +5507,7 @@ dependencies = [
[[package]]
name = "visualci-renderer"
-version = "0.2.29"
+version = "0.2.30"
dependencies = [
"anyhow",
"image",
@@ -5522,7 +5522,7 @@ dependencies = [
[[package]]
name = "visualci-wasm"
-version = "0.2.29"
+version = "0.2.30"
dependencies = [
"image",
"serde",
diff --git a/Cargo.toml b/Cargo.toml
index 4a85f16be..f3c38e155 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,7 +4,7 @@ resolver = "3"
members = ["crates/*", "app"]
[workspace.package]
-version = "0.2.29"
+version = "0.2.30"
edition = "2024"
license = "Apache-2.0"
repository = "https://github.com/DocSpring/visualci"
diff --git a/app/database/migrations/2026_12_14_000000_gallery_versions.rs b/app/database/migrations/2026_12_14_000000_gallery_versions.rs
new file mode 100644
index 000000000..33d903d28
--- /dev/null
+++ b/app/database/migrations/2026_12_14_000000_gallery_versions.rs
@@ -0,0 +1,48 @@
+//! Gallery versions (sc-9563): a project that reports a release (`visualci release v2.0.0`) keeps what its gallery
+//! published at that commit, for good, at its own URLs (`/g//@.json`). A version's rows never
+//! change once recorded, except that a thumbnail made after it is filled in. Its screenshots and thumbnails are blobs
+//! these rows keep: retention and project deletion leave a blob a row names alone.
+
+use laravel::db::AnyTransaction;
+
+pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
+ tx.query(SCHEMA).unprepared().await?;
+ Ok(())
+}
+
+const SCHEMA: &str = r"
+SET LOCAL lock_timeout = '5s';
+CREATE TABLE gallery_versions (
+ id bigserial PRIMARY KEY,
+ project_id bigint NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
+ key text NOT NULL,
+ label text NOT NULL,
+ commit_sha text NOT NULL,
+ released_at timestamp with time zone NOT NULL,
+ groups jsonb NOT NULL,
+ created_at timestamp with time zone NOT NULL DEFAULT now(),
+ UNIQUE (project_id, key)
+);
+CREATE TABLE gallery_version_items (
+ version_id bigint NOT NULL REFERENCES gallery_versions(id) ON DELETE CASCADE,
+ position integer NOT NULL,
+ group_name text NOT NULL,
+ name text NOT NULL,
+ platform text NOT NULL,
+ path text NOT NULL,
+ sha256 text NOT NULL,
+ content_type text NOT NULL,
+ width integer,
+ height integer,
+ bytes bigint NOT NULL,
+ since text NOT NULL,
+ thumb_wanted boolean NOT NULL,
+ thumb_sha256 text,
+ thumb_width integer,
+ thumb_height integer,
+ thumb_bytes bigint,
+ PRIMARY KEY (version_id, path)
+);
+CREATE INDEX gallery_version_items_sha256 ON gallery_version_items (sha256);
+CREATE INDEX gallery_version_items_thumb_sha256 ON gallery_version_items (thumb_sha256);
+";
diff --git a/app/src/domain/baselines.rs b/app/src/domain/baselines.rs
index dcc634bf1..d27071d85 100644
--- a/app/src/domain/baselines.rs
+++ b/app/src/domain/baselines.rs
@@ -273,7 +273,28 @@ pub async fn resolve(
build: &Build,
project: &Project,
) -> laravel::Result<(HashMap<(String, String), Resolved>, Option)> {
- let anchor = anchor(build, project).await?;
+ resolve_inner(build, project, false).await
+}
+
+/// [`resolve`] as at the build's commit, for a gallery version (`domain::gallery_versions`): only what was approved at
+/// that commit or its ancestors counts. No anchor beyond its history, and no approval just for being on the same
+/// branch (a later commit's).
+///
+/// # Errors
+/// On a database error.
+pub async fn resolve_at_commit(
+ build: &Build,
+ project: &Project,
+) -> laravel::Result<(HashMap<(String, String), Resolved>, Option)> {
+ resolve_inner(build, project, true).await
+}
+
+async fn resolve_inner(
+ build: &Build,
+ project: &Project,
+ at_commit: bool,
+) -> laravel::Result<(HashMap<(String, String), Resolved>, Option)> {
+ let anchor = if at_commit { nearest_approved(build).await? } else { anchor(build, project).await? };
let from_anchor = match &anchor {
Some(a) => effective(a, build, project).await?,
None => HashMap::new(),
@@ -295,14 +316,17 @@ pub async fn resolve(
// own branch; on the base branch (and the default branch when the anchor came from it) only CI approvals count for
// other branches.
let trusted = trusted_branches(build, project, anchor.as_ref());
- let (project_id, build_name, id, branch) = (build.project_id, build.name.as_str(), build.id, build.branch.as_str());
+ let (project_id, build_name, id) = (build.project_id, build.name.as_str(), build.id);
+ // As at a commit, no row counts for its branch alone.
+ let branch = build.branch.as_str();
let rows: Vec = db::query!(
"SELECT * FROM baselines WHERE project_id = {project_id} AND build_name = {build_name} AND build_id <> {id} \
AND ( \
(approval <> 'merged' AND (build_id > {after} OR commit_sha IN ({...nearer_or_none})) \
- AND ((mode = 'ci' AND commit_sha IN ({...history})) OR branch = {branch})) \
+ AND ((mode = 'ci' AND commit_sha IN ({...history})) OR (branch = {branch} AND NOT {at_commit}))) \
OR (approval = 'merged' AND commit_sha IN ({...history})) \
- OR (environment NOT IN ('', 'ci') AND (branch = {branch} OR (branch IN ({...trusted}) AND mode = 'ci'))) \
+ OR (environment NOT IN ('', 'ci') AND ((branch = {branch} AND NOT {at_commit}) OR (branch IN ({...trusted}) AND mode = 'ci')) \
+ AND (NOT {at_commit} OR commit_sha IN ({...history}))) \
) ORDER BY id"
)
.select_as()
@@ -318,7 +342,7 @@ pub async fn resolve(
// default-branch ones.
let mut latest: HashMap<(String, String, String), Baseline> = HashMap::new();
let newer = |r: &Baseline| r.build_id > after || nearer_set.contains(&r.commit_sha);
- let rank = |r: &Baseline| (newer(r) || r.branch == build.branch || merged_and_new(r), r.id);
+ let rank = |r: &Baseline| (newer(r) || (!at_commit && r.branch == build.branch) || merged_and_new(r), r.id);
// Between two merged pull requests' approvals, the nearer merge in this build's history wins (it was merged later
// on this line), whatever order the webhooks arrived in.
let nearness = |r: &Baseline| history.iter().position(|c| c == &r.commit_sha).unwrap_or(usize::MAX);
diff --git a/app/src/domain/builds.rs b/app/src/domain/builds.rs
index 042a8beb7..27c4aaa5d 100644
--- a/app/src/domain/builds.rs
+++ b/app/src/domain/builds.rs
@@ -127,6 +127,12 @@ fn server(e: laravel::Error) -> Outcome {
/// Make a build (or, for a nonce that already made one, return that build).
///
+/// Whether a string can be a commit: 1 to 64 letters and digits (a commit SHA).
+#[must_use]
+pub fn id_like(s: &str) -> bool {
+ (1..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric())
+}
+
/// # Errors
/// `Invalid` for bad parameters; else on a database error.
pub async fn create(project: &Project, params: &CreateParams, creator: Option) -> Outcome {
@@ -136,7 +142,6 @@ pub async fn create(project: &Project, params: &CreateParams, creator: Option &'static str {
}
/// A time as today's server wrote it (RFC 3339 in UTC, `+00:00`, with milli- or microseconds when there are any).
-fn rfc3339(t: laravel::time::Timestamp) -> String {
+pub(crate) fn rfc3339(t: laravel::time::Timestamp) -> String {
let micros = t.subsec_microsecond();
let fraction = if micros == 0 {
String::new()
@@ -71,8 +71,9 @@ fn rfc3339(t: laravel::time::Timestamp) -> String {
format!("{utc}{fraction}+00:00")
}
-/// The newest completed CI build of each suite on the default branch.
-async fn newest_builds(project: &Project) -> laravel::Result> {
+/// The newest completed CI build of each suite on the default branch: of those at one of the `at` commits, when given
+/// (a version's commit and its ancestors, newest first).
+async fn newest_builds(project: &Project, at: Option<&[String]>) -> laravel::Result> {
let (project_id, branch) = (project.id, project.default_branch.clone());
let all: Vec = db::query!(
"SELECT * FROM builds WHERE project_id = {project_id} AND branch = {branch} AND mode = 'ci' \
@@ -81,7 +82,17 @@ async fn newest_builds(project: &Project) -> laravel::Result> {
.select_as()
.await?;
let mut seen = HashSet::new();
- Ok(all.into_iter().filter(|b| seen.insert(b.name.clone())).collect())
+ let Some(at) = at else { return Ok(all.into_iter().filter(|b| seen.insert(b.name.clone())).collect()) };
+ // The nearest commit's build of each suite, its newest build there.
+ let mut out = Vec::new();
+ for commit in at {
+ for b in all.iter().filter(|b| &b.commit_sha == commit) {
+ if seen.insert(b.name.clone()) {
+ out.push(b.clone());
+ }
+ }
+ }
+ Ok(out)
}
/// The gallery a build's visualci.yml asks for, if any. A file that no longer validates has none: the public page can't
@@ -137,7 +148,7 @@ pub async fn published(project: &Project) -> laravel::Result {
if let Some(p) = hit {
return Ok(p);
}
- let computed = compute(project).await?;
+ let computed = compute(project, None).await?;
if let Ok(mut c) = cache.lock() {
if c.len() > 10_000 {
c.retain(|_, (_, _, at, _)| at.elapsed() < CACHE_FOR);
@@ -147,28 +158,46 @@ pub async fn published(project: &Project) -> laravel::Result {
Ok(computed)
}
-async fn compute(project: &Project) -> laravel::Result {
+/// What a project's gallery published at a commit (its ancestry, newest first: the commit, then its parents), for a
+/// version (`super::gallery_versions`): the same as [`published`], from the default-branch builds at or before it.
+///
+/// # Errors
+/// On a database error.
+pub async fn published_at(project: &Project, history: &[String]) -> laravel::Result {
+ compute(project, Some(history)).await
+}
+
+async fn compute(project: &Project, at: Option<&[String]>) -> laravel::Result {
let mut out = Published::default();
let mut found = Vec::new();
// A screenshot two suites both publish (CI's and `visualci publish`'s) comes from the newest build's suite.
let mut taken: HashSet<(String, String)> = HashSet::new();
- for newest in newest_builds(project).await? {
+ for newest in newest_builds(project, at).await? {
let Some(gallery) = gallery_of(&newest) else { continue };
for g in &gallery.groups {
if !out.groups.iter().any(|(n, _)| n == &g.name) {
out.groups.push((g.name.clone(), g.title.clone()));
}
}
- // What the next build on the default branch would compare with: resolve as a build just after the newest.
+ // What the next build on the default branch would compare with: resolve as a build just after the newest
+ // (for a version, one on its commit).
let mut next = newest.clone();
next.id = i64::MAX;
next.parent_commits =
Json(std::iter::once(newest.commit_sha.clone()).chain(newest.parent_commits.iter().cloned()).collect());
+ if let Some((commit, parents)) = at.and_then(<[String]>::split_first) {
+ next.commit_sha.clone_from(commit);
+ next.parent_commits = Json(parents.to_vec());
+ }
// The gallery's environment (`ci` unless visualci.yml names another, such as a laptop's): only its own
// screenshots, never another environment's a lookup falls back to.
let environment = gallery.environment().to_string();
next.environment.clone_from(&environment);
- let (resolved, _) = super::baselines::resolve(&next, project).await?;
+ let (resolved, _) = if at.is_some() {
+ super::baselines::resolve_at_commit(&next, project).await?
+ } else {
+ super::baselines::resolve(&next, project).await?
+ };
for ((name, _), r) in resolved {
if r.snapshot.kind != "image" || r.snapshot.environment != environment {
continue;
@@ -401,10 +430,21 @@ pub async fn public_list(app_url: &str, org: &str, project: &Project) -> laravel
})
})
.collect();
+ let versions: Vec = super::gallery_versions::list(project.id)
+ .await?
+ .iter()
+ .map(|v| {
+ serde_json::json!({
+ "key": v.key, "label": v.label, "commit": v.commit_sha, "released_at": v.released_at,
+ "manifest": manifest_url(app_url, org, &format!("{}@{}", project.slug, v.key)),
+ })
+ })
+ .collect();
Ok(serde_json::json!({
"enabled": project.gallery_enabled,
"manifest_url": (!items.is_empty()).then(|| manifest_url(app_url, org, &project.slug)),
"items": items,
+ "versions": versions,
}))
}
diff --git a/app/src/domain/gallery_thumbs.rs b/app/src/domain/gallery_thumbs.rs
index 91efac2be..d9358f9d1 100644
--- a/app/src/domain/gallery_thumbs.rs
+++ b/app/src/domain/gallery_thumbs.rs
@@ -101,11 +101,18 @@ pub async fn sync(project: &Project, budget: std::time::Duration) -> laravel::Re
let have = gallery::thumbs(project.id).await?;
let wanted: HashMap<&str, &gallery::Item> =
published.items.iter().filter(|i| i.wants_thumb()).map(|i| (i.sha256.as_str(), i)).collect();
+ // Screenshots a version recorded before their thumbnail was made (`gallery_versions`), whether the gallery still
+ // publishes them or not.
+ let for_versions: HashSet = super::gallery_versions::thumbs_wanted(project.id).await?.into_iter().collect();
let mut changed: Vec = Vec::new();
let mut out = Synced::default();
let project_id = project.id;
- let gone: Vec = have.keys().filter(|sha| !wanted.contains_key(sha.as_str())).cloned().collect();
+ let gone: Vec = have
+ .keys()
+ .filter(|sha| !wanted.contains_key(sha.as_str()) && !for_versions.contains(sha.as_str()))
+ .cloned()
+ .collect();
if !gone.is_empty() {
let rows = db::query!(
"DELETE FROM gallery_thumbnails WHERE project_id = {project_id} AND source_sha256 IN ({...gone}) \
@@ -122,39 +129,52 @@ pub async fn sync(project: &Project, budget: std::time::Duration) -> laravel::Re
let mut missing: Vec<&gallery::Item> = wanted.values().filter(|i| !have.contains_key(&i.sha256)).copied().collect();
// In the gallery's order, so the cards a visitor sees first get theirs first.
missing.sort_by(|a, b| a.path.cmp(&b.path));
+ let versions_missing: Vec<&String> =
+ for_versions.iter().filter(|sha| !have.contains_key(*sha) && !wanted.contains_key(sha.as_str())).collect();
let mut failed: Option = None;
- if !missing.is_empty() {
+ if !missing.is_empty() || !versions_missing.is_empty() {
let store = BlobStore::current().await?;
let store = &store;
- let total = missing.len();
- let mut queue = missing.into_iter().cloned();
+ let total = missing.len() + versions_missing.len();
+ // The published screenshots first, then the ones only a version keeps.
+ let mut queue = missing
+ .into_iter()
+ .map(|i| (i.sha256.clone(), Some(i.clone())))
+ .chain(versions_missing.into_iter().map(|sha| (sha.clone(), None)));
let mut running = futures_util::stream::FuturesUnordered::new();
let (mut started, mut recorded) = (0, 0);
loop {
while running.len() < CONCURRENCY && (started == 0 || std::time::Instant::now() < deadline) {
- let Some(item) = queue.next() else { break };
+ let Some((sha, item)) = queue.next() else { break };
started += 1;
running.push(async move {
- let result = make_one(store, project_id, &item).await;
- (item, result)
+ let result = make_one(store, project_id, &sha).await;
+ (sha, item, result)
});
}
- let Some((item, result)) = running.next().await else { break };
+ let Some((sha, item, result)) = running.next().await else { break };
match result {
Ok(true) => {
recorded += 1;
out.made += 1;
- changed.push(item.thumb_path());
+ // A published screenshot's thumbnail URL changed; a version's manifest is cached briefly until its
+ // thumbnails are all in.
+ if let Some(item) = item {
+ changed.push(item.thumb_path());
+ }
}
Ok(false) => recorded += 1,
Err(e) => {
- tracing::warn!(project_id, sha256 = item.sha256, error = %e, "gallery thumbnail failed; tried again later");
+ tracing::warn!(project_id, sha256 = sha.as_str(), error = %e, "gallery thumbnail failed; tried again later");
failed.get_or_insert(e);
}
}
}
out.more = started < total && recorded > 0;
}
+ if !for_versions.is_empty() {
+ super::gallery_versions::fill_thumbs(project_id).await?;
+ }
if out.made + out.deleted > 0 {
let org = crate::models::Organization::find_or_fail(project.organization_id).await?;
@@ -171,9 +191,9 @@ pub async fn sync(project: &Project, budget: std::time::Duration) -> laravel::Re
/// Make one screenshot's thumbnail and record it: `true` when one was made, `false` when none can be (recorded, so
/// it isn't tried again).
-async fn make_one(store: &BlobStore, project_id: i64, item: &gallery::Item) -> laravel::Result {
- let bytes = store.get(&item.sha256).await?;
- let sha = item.sha256.clone();
+async fn make_one(store: &BlobStore, project_id: i64, sha: &str) -> laravel::Result {
+ let bytes = store.get(sha).await?;
+ let sha = sha.to_string();
let permit =
DECODES.acquire().await.map_err(|e| laravel::Error::msg(format!("waiting to make a thumbnail: {e}")))?;
let made = tokio::task::spawn_blocking(move || {
@@ -219,6 +239,7 @@ async fn delete_blobs(shas: Vec) -> laravel::Result<()> {
let marked: Vec = db::query!(
"UPDATE blobs SET deleting = true, updated_at = now() WHERE sha256 IN ({...shas}) AND NOT deleting \
AND NOT EXISTS (SELECT 1 FROM gallery_thumbnails t WHERE t.thumb_sha256 = blobs.sha256) \
+ AND NOT EXISTS (SELECT 1 FROM gallery_version_items v WHERE v.thumb_sha256 = blobs.sha256) \
RETURNING sha256"
)
.select()
diff --git a/app/src/domain/gallery_versions.rs b/app/src/domain/gallery_versions.rs
new file mode 100644
index 000000000..a0e203fed
--- /dev/null
+++ b/app/src/domain/gallery_versions.rs
@@ -0,0 +1,428 @@
+//! Gallery versions (sc-9563): what a project's gallery published at a release, kept for good. A project reports a
+//! version only when its setup says so (`visualci release v2.0.0`, or the CI provider's tag); nothing changes for one
+//! that doesn't. Each version is served at its own URLs, `/g//@.json` and
+//! `/g//@/`, and the main manifest lists the versions, newest first.
+//!
+//! A version's screenshots, groups and names never change once it's recorded: its rows hold them, and its blobs are
+//! kept by retention and project deletion for as long as the rows are. The one thing filled in later is a thumbnail
+//! made after it ([`fill_thumbs`]); until then its manifest is cached for a minute, then like the main manifest (it
+//! lists every version, so recording one purges it). Its images never change, and are cached for a year.
+
+use std::collections::HashMap;
+
+use laravel::db;
+
+use super::gallery::{self, Item, Published, Thumb};
+use crate::models::Project;
+
+/// The longest version label.
+pub const MAX_LABEL: usize = 64;
+
+/// A recorded version.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Version {
+ pub id: i64,
+ pub key: String,
+ pub label: String,
+ pub commit_sha: String,
+ pub released_at: String,
+}
+
+/// A version's key, from its label: lowercase, each run of anything but letters and digits one hyphen, no hyphen at
+/// either end (`v1.0.0+build.5` → `v1-0-0-build-5`), so it's a URL segment and the gallery libraries' value key
+/// (`^[a-z0-9]+(-[a-z0-9]+)*$`). `None` when that leaves nothing, or `latest`, the libraries' name for the main
+/// manifest.
+#[must_use]
+pub fn key_of(label: &str) -> Option {
+ let mut key = String::with_capacity(label.len());
+ for c in label.chars() {
+ if c.is_ascii_alphanumeric() {
+ key.push(c.to_ascii_lowercase());
+ } else if !key.is_empty() && !key.ends_with('-') {
+ key.push('-');
+ }
+ }
+ while key.ends_with('-') {
+ key.pop();
+ }
+ (!key.is_empty() && key != "latest").then_some(key)
+}
+
+/// Whether a version label is acceptable: 1 to [`MAX_LABEL`] letters, digits, dots, dashes, pluses and underscores.
+#[must_use]
+pub fn valid_label(label: &str) -> bool {
+ !label.is_empty()
+ && label.len() <= MAX_LABEL
+ && label.bytes().all(|b| b.is_ascii_alphanumeric() || b".-+_".contains(&b))
+}
+
+/// Why a version wasn't recorded.
+#[derive(Debug, PartialEq, Eq)]
+pub enum Refused {
+ /// The label or its key isn't acceptable.
+ Invalid(String),
+ /// The version is already recorded at another commit.
+ Taken(String),
+ /// The gallery published nothing at that commit.
+ Nothing(String),
+ /// The project has [`MAX_VERSIONS`] already.
+ Full(String),
+}
+
+/// The most versions a project keeps: a guard against a setup that tags every commit, not a price (support can raise
+/// it for a project that needs more).
+pub const MAX_VERSIONS: i64 = 500;
+
+/// A version just recorded (`true`) or recorded before at the same commit (`false`).
+pub type Recorded = (Version, bool);
+
+/// Record a version at a commit (`history`: the commit, then its ancestors, newest first): what the gallery
+/// published there, frozen. The same version at the same commit again answers the one recorded; at another commit it's
+/// refused, since a version's screenshots never change.
+///
+/// # Errors
+/// On a database error.
+pub async fn record(project: &Project, label: &str, history: &[String]) -> laravel::Result> {
+ let label = label.trim();
+ if !valid_label(label) {
+ return Ok(Err(Refused::Invalid(format!(
+ "version must be 1 to {MAX_LABEL} letters, digits, dots, dashes, pluses and underscores (v2.0.0)"
+ ))));
+ }
+ let Some(key) = key_of(label) else {
+ return Ok(Err(Refused::Invalid(format!(
+ "{label:?} can't be a version: it needs a letter or digit, and isn't latest"
+ ))));
+ };
+ let Some(commit) = history.first().cloned() else {
+ return Ok(Err(Refused::Invalid("commit is required".into())));
+ };
+ let project_id = project.id;
+ if let Some(existing) = find(project_id, &key).await? {
+ return Ok(if existing.commit_sha == commit { Ok((existing, false)) } else { Err(taken(&existing)) });
+ }
+ let count: i64 = db::query!("SELECT count(*) FROM gallery_versions WHERE project_id = {project_id}")
+ .scalar::()
+ .await?
+ .unwrap_or(0);
+ if count >= MAX_VERSIONS {
+ return Ok(Err(Refused::Full(format!(
+ "this project has {count} versions, the most a project keeps ({MAX_VERSIONS}); contact support \
+ (support@visualci.com) if you need more"
+ ))));
+ }
+ let published = gallery::published_at(project, history).await?;
+ if published.items.is_empty() {
+ return Ok(Err(Refused::Nothing(format!(
+ "the gallery published nothing at {commit}: it needs an approved default-branch CI build at or before \
+ that commit whose visualci.yml has a gallery section"
+ ))));
+ }
+ let groups = serde_json::json!(
+ published
+ .groups
+ .iter()
+ .map(|(name, title)| serde_json::json!({ "name": name, "title": title }))
+ .collect::>()
+ );
+ let created = db::transaction(async |_| {
+ let id: Option = db::query!(
+ "INSERT INTO gallery_versions (project_id, key, label, commit_sha, released_at, groups) \
+ VALUES ({project_id}, {key}, {label}, {commit}, now(), {groups}) \
+ ON CONFLICT (project_id, key) DO NOTHING RETURNING id"
+ )
+ .scalar()
+ .await?;
+ let Some(id) = id else { return Ok(None) };
+ // The thumbnails it copies, held until it commits: a thumbnail sync deleting one meanwhile waits, and then
+ // finds this version naming its blob, which it leaves alone.
+ let thumbs = locked_thumbs(project_id).await?;
+ for (position, item) in published.items.iter().enumerate() {
+ insert_item(id, i32::try_from(position).unwrap_or(i32::MAX), item, &thumbs).await?;
+ }
+ let waiting = published.items.iter().any(|i| i.wants_thumb() && !thumbs.contains_key(&i.sha256));
+ Ok::<_, laravel::Error>(Some(waiting))
+ })
+ .await?;
+ let Some(version) = find(project_id, &key).await? else {
+ return Err(laravel::Error::msg("the version just recorded is gone"));
+ };
+ let Some(waiting) = created else {
+ // Recorded meanwhile by another request.
+ return Ok(if version.commit_sha == commit { Ok((version, false)) } else { Err(taken(&version)) });
+ };
+ // Its missing thumbnails, made now (not through `request`'s debounce, which a manifest request may have just used).
+ if waiting && let Err(e) = (crate::jobs::gallery_thumbs::SyncGalleryThumbs { project_id }).dispatch().await {
+ tracing::error!(project_id, error = %e, "couldn't queue the version's thumbnails");
+ }
+ // Every manifest lists the versions: the main one and each version's, cached at Cloudflare, are purged.
+ if crate::jobs::purge_gallery::configured().is_some() {
+ let org = crate::models::Organization::find_or_fail(project.organization_id).await?;
+ let app_url = crate::http::api::builds::app_url();
+ let mut urls = vec![gallery::manifest_url(&app_url, &org.slug, &project.slug)];
+ for v in list(project_id).await? {
+ urls.push(gallery::manifest_url(&app_url, &org.slug, &format!("{}@{}", project.slug, v.key)));
+ }
+ let purge = crate::jobs::purge_gallery::PurgeGallery { build_id: None, project_id: Some(project_id), urls };
+ if let Err(e) = purge.dispatch().await {
+ tracing::error!(project_id, error = %e, "couldn't queue the purge of the gallery's manifests");
+ }
+ }
+ Ok(Ok((version, true)))
+}
+
+fn taken(existing: &Version) -> Refused {
+ Refused::Taken(format!(
+ "{} is already recorded at commit {}; a version's screenshots never change",
+ existing.label, existing.commit_sha
+ ))
+}
+
+/// The project's thumbnails, as [`gallery::thumbs`], each row share-locked until the transaction ends.
+async fn locked_thumbs(project_id: i64) -> laravel::Result>> {
+ let rows = db::query!(
+ "SELECT source_sha256, thumb_sha256, width, height, bytes FROM gallery_thumbnails \
+ WHERE project_id = {project_id} FOR SHARE"
+ )
+ .select()
+ .await?;
+ let mut out = HashMap::with_capacity(rows.len());
+ for r in rows {
+ let thumb = match r.try_get::
diff --git a/plugin/skills/visualci-gallery/SKILL.md b/plugin/skills/visualci-gallery/SKILL.md
index edcf81cf5..654ca0769 100644
--- a/plugin/skills/visualci-gallery/SKILL.md
+++ b/plugin/skills/visualci-gallery/SKILL.md
@@ -100,6 +100,8 @@ Always the approved version on the default branch: what the next build there wou
}
```
+Once the project [reports versions](https://visualci.com/docs/gallery/versions.md), the manifest also lists them, each with a manifest of its own that keeps the gallery as it was at that release.
+
The manifest changes only when an image does, so a site can build its own gallery from it. Light and dark, or phone and desktop, are separate screenshots with their own URLs; pairing them is up to your page.
Every gallery URL works from any site (`Access-Control-Allow-Origin: *`), including one that turns on cross-origin isolation (`Cross-Origin-Resource-Policy: cross-origin`). They take no query parameters: anything else is a 404.
From 0ac598575fcc35446d497f40bd1ae74189a5cc38 Mon Sep 17 00:00:00 2001
From: Nathan Broadbent
Date: Sat, 5 Dec 2026 11:55:00 +0000
Subject: [PATCH 2/3] Gallery versions after #288 and #290: version-only
thumbnails join the time-budgeted queue; the changelog line is an entry file;
no plugin version
---
frontend/content/changelog/2026-12-06-0054-gallery-versions.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 frontend/content/changelog/2026-12-06-0054-gallery-versions.md
diff --git a/frontend/content/changelog/2026-12-06-0054-gallery-versions.md b/frontend/content/changelog/2026-12-06-0054-gallery-versions.md
new file mode 100644
index 000000000..43fa45520
--- /dev/null
+++ b/frontend/content/changelog/2026-12-06-0054-gallery-versions.md
@@ -0,0 +1 @@
+**CLI 0.2.30: gallery versions.** `visualci release v2.0.0` (or bare `visualci release` in a tag workflow) keeps what your gallery showed at that release, for good, at its own URLs (`/g//@v2-0-0.json`), and every manifest lists the versions, newest first, so a page can show v1.0.0 beside v2.0.0. Opt-in: nothing changes until you report one. [Gallery versions](/docs/gallery/versions/)
From 91e39ca3c032c6516f941c3960efb2727f219fa1 Mon Sep 17 00:00:00 2001
From: Nathan Broadbent
Date: Sat, 5 Dec 2026 12:02:13 +0000
Subject: [PATCH 3/3] Gallery versions: the version thumbnails test passes the
sync's budget (#288); version-only thumbnails in a stable order
---
app/src/domain/gallery_thumbs.rs | 3 ++-
app/tests/gallery.rs | 2 +-
2 files changed, 3 insertions(+), 2 deletions(-)
diff --git a/app/src/domain/gallery_thumbs.rs b/app/src/domain/gallery_thumbs.rs
index d9358f9d1..4e66e428f 100644
--- a/app/src/domain/gallery_thumbs.rs
+++ b/app/src/domain/gallery_thumbs.rs
@@ -129,8 +129,9 @@ pub async fn sync(project: &Project, budget: std::time::Duration) -> laravel::Re
let mut missing: Vec<&gallery::Item> = wanted.values().filter(|i| !have.contains_key(&i.sha256)).copied().collect();
// In the gallery's order, so the cards a visitor sees first get theirs first.
missing.sort_by(|a, b| a.path.cmp(&b.path));
- let versions_missing: Vec<&String> =
+ let mut versions_missing: Vec<&String> =
for_versions.iter().filter(|sha| !have.contains_key(*sha) && !wanted.contains_key(sha.as_str())).collect();
+ versions_missing.sort();
let mut failed: Option = None;
if !missing.is_empty() || !versions_missing.is_empty() {
let store = BlobStore::current().await?;
diff --git a/app/tests/gallery.rs b/app/tests/gallery.rs
index 1cc9ae01b..0d2f2d628 100644
--- a/app/tests/gallery.rs
+++ b/app/tests/gallery.rs
@@ -648,7 +648,7 @@ async fn versions(app: Application) -> laravel::Result<()> {
app.get(format!("{base}@v9/web/home.png")).await.assert_status(404);
app.get(format!("{base}@v1-0-0/web/nope.png")).await.assert_status(404);
// Thumbnails are made in the background (the sync queue runs at once in tests): the version's is filled in.
- app::domain::gallery_thumbs::sync(&w.project).await?;
+ app::domain::gallery_thumbs::sync(&w.project, app::domain::gallery_thumbs::BUDGET).await?;
let manifest: Value = app.get(format!("{base}@v1-0-0.json")).await.json().clone();
let home = manifest["groups"][0]["items"].as_array().unwrap().iter().find(|i| i["name"] == "web/home").unwrap();
assert_eq!(home["thumb"]["width"], 640, "{manifest}");