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
66 changes: 66 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,73 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: Swatinem/rust-cache@v2
# The request tests also write the MCP tools' and REST API's answers as JSON snapshots, for the visual job.
- run: cargo test --locked --workspace
env:
VISUALCI_JSON_SNAPSHOTS: ${{ github.workspace }}/tmp/json-snapshots
- uses: actions/upload-artifact@v4
with:
name: json-snapshots
path: tmp/json-snapshots
if-no-files-found: error
retention-days: 7

# VisualCI tests itself: screenshots of the landing page, docs and app (against seeded data), Vitest component
# snapshots and the JSON snapshots from `test`, sent as one build to the docspring/visualci project. A changed
# snapshot doesn't fail this job: the GitHub check waits for review. Pull requests from forks have no token and skip
# the upload.
visual:
needs: [test]
runs-on: ${{ fromJSON(vars.CI_RUNNER || '"ubuntu-latest"') }}
timeout-minutes: 30
services:
postgres:
image: postgres:17
env:
POSTGRES_USER: loco
POSTGRES_PASSWORD: loco
POSTGRES_DB: visualci_screenshots
ports: ["55433:5432"]
options: --health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
env:
VISUALCI_TOKEN: ${{ secrets.VISUALCI_TOKEN }}
VISUAL_JSON_DIR: ${{ github.workspace }}/tmp/json-snapshots
steps:
- uses: actions/checkout@v4
with:
# The CLI sends parent commits, so the build finds its baseline.
fetch-depth: 101
# S3 storage for the seeded blobs: RustFS (Apache-2.0), since MinIO's images are no longer public. A step rather
# than a service, so the job doesn't wait on a health check the image doesn't define.
- run: |
docker run -d --name s3 -p 59000:9000 \
-e RUSTFS_ACCESS_KEY=visualci -e RUSTFS_SECRET_KEY=visualci-dev-secret rustfs/rustfs:1.0.6
for _ in $(seq 1 30); do curl -s -o /dev/null http://127.0.0.1:59000/ && break; sleep 1; done
- uses: Swatinem/rust-cache@v2
- run: cargo build --locked -p visualci_server -p visualci-cli
- uses: pnpm/action-setup@v4
with:
package_json_file: server/frontend/package.json
- uses: actions/setup-node@v4
with:
node-version: "24"
- run: pnpm install --frozen-lockfile && pnpm build
working-directory: server/frontend
- run: pnpm install --frozen-lockfile && pnpm exec playwright install --with-deps chromium
working-directory: scripts/screenshots
- run: scripts/ci/visual.sh capture
- uses: actions/download-artifact@v4
with:
name: json-snapshots
path: tmp/json-snapshots
- if: env.VISUALCI_TOKEN != ''
run: scripts/ci/visual.sh upload
- if: failure()
uses: actions/upload-artifact@v4
with:
name: visual
path: tmp/visual
retention-days: 7

clients:
runs-on: ${{ fromJSON(vars.CI_RUNNER || '"ubuntu-latest"') }}
Expand Down
80 changes: 80 additions & 0 deletions scripts/ci/visual.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/usr/bin/env bash
# VisualCI tests itself: seed a database, start the server against it, take screenshots of the landing page, docs and
# app, and send them to VisualCI in one build with the Vitest component snapshots, the request tests' JSON snapshots
# and a few files the site serves to agents. CI runs it in the `visual` job (.github/workflows/ci.yml); it also runs on
# a dev machine with Postgres and S3 storage (MinIO or RustFS) up.
#
# scripts/ci/visual.sh capture seed, serve, take screenshots and component snapshots into tmp/visual
# scripts/ci/visual.sh upload send tmp/visual (and $VISUAL_JSON_DIR) to VisualCI as one build, and finalize it
#
# Needs: target/debug/visualci-server and visualci (cargo build), server/frontend/dist (pnpm build), and
# scripts/screenshots/node_modules with Playwright's Chromium. Settings: PORT (5151), DATABASE_URL (a database this
# script drops and recreates), S3_BUCKET, VISUAL_JSON_DIR (the request tests' JSON snapshots), VISUALCI_TOKEN.
set -euo pipefail
root=$(cd "$(dirname "$0")/../.." && pwd)
out=$root/tmp/visual
port=${PORT:-5151}
export DATABASE_URL=${DATABASE_URL:-postgres://loco:loco@127.0.0.1:55433/visualci_screenshots}
export S3_BUCKET=${S3_BUCKET:-visualci-screenshots}
export LOCO_ENV=development
# The month the seeded credit usage falls in (server/src/tasks/screenshots_seed.rs NOW).
export VISUALCI_NOW=2026-11-20T15:00:00Z
server=$root/target/debug/visualci-server
cli=$root/target/debug/visualci

capture() {
rm -rf "$out"
mkdir -p "$out"
cd "$root/server"
# A fresh database every time, so the seeded ids are the same.
local db=${DATABASE_URL##*/}
psql "${DATABASE_URL%/*}/postgres" -tAc "SELECT 1 FROM pg_database WHERE datname = '$db'" | grep -q 1 ||
psql "${DATABASE_URL%/*}/postgres" -qc "CREATE DATABASE $db"
"$server" db reset >"$out/seed.log" 2>&1 || { cat "$out/seed.log"; exit 1; }
"$server" task screenshots:seed >>"$out/seed.log" 2>&1 || { cat "$out/seed.log"; exit 1; }
PORT=$port "$server" start --binding 127.0.0.1 --no-banner >"$out/server.log" 2>&1 &
server_pid=$!
trap 'kill $server_pid 2>/dev/null || true' EXIT
for _ in $(seq 1 60); do
curl -fsS "http://127.0.0.1:$port/_ping" >/dev/null 2>&1 && break
sleep 1
done
curl -fsS "http://127.0.0.1:$port/_ping" >/dev/null || { tail -50 "$out/server.log"; exit 1; }

(cd "$root/scripts/screenshots" && node capture.mjs --base-url "http://127.0.0.1:$port" --out "$out/screenshots")

# Files the site serves to agents.
mkdir -p "$out/site/docs"
curl -fsS "http://127.0.0.1:$port/llms.txt" -o "$out/site/llms.txt"
curl -fsS "http://127.0.0.1:$port/docs/quick-start.md" -o "$out/site/docs/quick-start.md"
if curl -fsS "http://127.0.0.1:$port/visualci.schema.json" -o "$out/site/visualci.schema.json" 2>/dev/null; then :; else
rm -f "$out/site/visualci.schema.json"
fi

# Component snapshots, written fresh: the baselines are on VisualCI.
cd "$root/server/frontend"
find src -name __snapshots__ -type d -prune -exec rm -rf {} +
npx vitest run -u
}

upload() {
: "${VISUALCI_TOKEN:?VISUALCI_TOKEN is needed to upload}"
local id
id=$("$cli" build create)
export VISUALCI_BUILD_ID=$id
"$cli" upload "$out/screenshots" --prefix screenshots/ --platform chrome-linux
"$cli" upload "$out/site" --prefix site/
# `upload` skips .md files in a directory, so the docs page goes up by name.
"$cli" snapshot site/docs/quick-start "$out/site/docs/quick-start.md" --format text
"$cli" upload "$root/server/frontend/src" --from vitest --prefix components/
if [ -n "${VISUAL_JSON_DIR:-}" ] && [ -d "$VISUAL_JSON_DIR" ]; then
"$cli" upload "$VISUAL_JSON_DIR" --prefix json/ --format json
fi
"$cli" build finalize
}

case ${1:-} in
capture) capture ;;
upload) upload ;;
*) sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//' >&2; exit 2 ;;
esac
2 changes: 2 additions & 0 deletions scripts/screenshots/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
out/
196 changes: 196 additions & 0 deletions scripts/screenshots/capture.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
// VisualCI's own screenshots: the landing page, the docs and the app, against a server seeded with
// `visualci-server task screenshots:seed` (server/src/tasks/screenshots_seed.rs). Each page is taken at 1440 and 390 px
// wide, light and dark, as `<page>/<width>-<theme>.png` under the output folder, for `visualci upload`.
//
// node capture.mjs [--base-url http://127.0.0.1:5151] [--out out/shots] [--only <substring>]
//
// Pages must come out the same on every run of unchanged code (`node stable.mjs` checks): the browser's clock is frozen
// at the seed's NOW, animations and transitions are off, and each shot waits for the network, fonts and images.
import { mkdir } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { chromium } from 'playwright'

// Matches NOW and EMAIL in server/src/tasks/screenshots_seed.rs.
const NOW = '2026-11-20T15:00:00Z'
const EMAIL = 'ada@example.com'

const DOCS = [
'index', 'quick-start', 'agents', 'pdfs', 'screenshots', 'support',
'ci/github-actions', 'ci/circleci', 'ci/buildkite', 'ci/gitlab', 'ci/other',
'snapshots/jest', 'snapshots/vitest', 'snapshots/insta', 'snapshots/syrupy', 'snapshots/rspec-snapshot',
'reference/cli', 'reference/api', 'reference/credits',
]

// Every page at both widths and both themes, except the docs: they share one layout, so each docs page is taken at
// 1440 light and 390 dark, which still covers both widths and both themes.
const ALL = ['1440-light', '1440-dark', '390-light', '390-dark']
const DOCS_VARIANTS = ['1440-light', '390-dark']

/** The pages: [name, path or async (api) => path, signed in?, variants]. */
function pages() {
const snapshot = (project, number, name) => async (api) => {
const data = await api(`/api/ui/orgs/acme/projects/${project}/builds/${number}`)
const row = data.snapshots.find((s) => s.name === name)
if (!row) throw new Error(`no snapshot ${name} in ${project} build ${number}`)
return `/acme/${project}/builds/${number}/snapshots/${row.id}`
}
return [
['landing', '/', false, ALL],
...DOCS.map((slug) => [`docs/${slug}`, slug === 'index' ? '/docs/' : `/docs/${slug}/`, false, DOCS_VARIANTS]),
['app/orgs', '/', true, ALL],
['app/org', '/acme', true, ALL],
['app/project/builds', '/acme/web', true, ALL],
['app/project/settings', '/acme/web?tab=settings', true, ALL],
['app/project/tokens', '/acme/web?tab=tokens', true, ALL],
['app/build/changes', '/acme/web/builds/3', true, ALL],
['app/build/approved', '/acme/web/builds/4', true, ALL],
['app/build/failed', '/acme/invoices/builds/2', true, ALL],
['app/snapshot/image', snapshot('web', 3, 'dashboard/1440-light'), true, ALL],
['app/snapshot/pdf', snapshot('web', 3, 'receipt.pdf'), true, ALL],
['app/snapshot/json', snapshot('web', 3, 'api/orders.json'), true, ALL],
['app/snapshot/html', snapshot('web', 3, 'emails/welcome.html'), true, ALL],
['app/snapshot/text', snapshot('web', 3, 'cli/help.txt'), true, ALL],
['app/billing/team', '/acme/billing', true, ALL],
['app/billing/free', '/side-project/billing', true, ALL],
['app/account', '/account', true, ALL],
]
}

const NO_MOTION = `*, *::before, *::after {
animation: none !important; transition: none !important; caret-color: transparent !important;
scroll-behavior: auto !important;
}`

function args() {
const out = { baseUrl: 'http://127.0.0.1:5151', out: 'out/shots', only: null }
const argv = process.argv.slice(2)
for (let i = 0; i < argv.length; i++) {
const key = argv[i].replace(/^--/, '').replace(/-(\w)/g, (_, c) => c.toUpperCase())
if (!(key in out)) throw new Error(`unknown option ${argv[i]}`)
out[key] = argv[++i]
}
return out
}

async function settle(page) {
await page.waitForLoadState('networkidle')
// Lazy images below the fold (or hidden by the other theme) never load on their own: load them all now, so a full-page
// shot doesn't catch them half-loaded.
const pending = await page.evaluate(async () => {
await document.fonts.ready
const waits = [...document.images].map((img) => {
img.loading = 'eager'
if (img.complete) return null
return new Promise((resolve) => {
img.addEventListener('load', resolve, { once: true })
img.addEventListener('error', resolve, { once: true })
})
})
const timeout = new Promise((resolve) => setTimeout(() => resolve('timeout'), 10_000))
const result = await Promise.race([Promise.all(waits), timeout])
return result === 'timeout' ? [...document.images].filter((i) => !i.complete).map((i) => i.src) : []
})
if (pending.length) throw new Error(`images still loading after 10s: ${pending.join(', ')}`)
await page.waitForLoadState('networkidle')
// Loading states that outlast network idle (a query retrying) would make a flaky shot: wait them out.
await page.waitForFunction(() => !document.querySelector('.spinner, .skeleton, [aria-busy="true"]'), null, { timeout: 15_000 })
// Two frames, so layout after the last image or font has painted.
await page.evaluate(
() =>
new Promise((r) => {
requestAnimationFrame(() => requestAnimationFrame(r))
setTimeout(r, 1000)
}),
)
}

async function main() {
const opts = args()
// Software rasterising on one thread, one colour profile and greyscale text: with the GPU and partial raster, small SVG
// icons came out a few pixels different from run to run.
const browser = await chromium.launch({
...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}),
args: [
'--disable-gpu',
'--force-color-profile=srgb',
'--disable-partial-raster',
'--disable-skia-runtime-opts',
'--disable-lcd-text',
'--font-render-hinting=none',
'--num-raster-threads=1',
],
})
const contexts = new Map()
async function context(variant, signedIn) {
const key = `${variant}/${signedIn}`
if (contexts.has(key)) return contexts.get(key)
const [width, theme] = variant.split('-')
const ctx = await browser.newContext({
baseURL: opts.baseUrl,
viewport: { width: Number(width), height: 900 },
deviceScaleFactor: 1,
colorScheme: theme,
reducedMotion: 'reduce',
locale: 'en-US',
timezoneId: 'UTC',
})
await ctx.addInitScript((css) => {
document.addEventListener('DOMContentLoaded', () => {
const style = document.createElement('style')
style.textContent = css
document.head.appendChild(style)
})
}, NO_MOTION)
// The clock reads NOW, without Playwright's fake timers: those also take over requestAnimationFrame and
// setTimeout, which the app and the waits below need running.
await ctx.addInitScript((now) => {
const fixed = new Date(now).getTime()
const RealDate = Date
class FixedDate extends RealDate {
constructor(...args) {
super(...(args.length ? args : [fixed]))
}
static now() {
return fixed
}
}
globalThis.Date = FixedDate
}, NOW)
if (signedIn) {
const res = await ctx.request.post('/auth/dev-login', { data: { email: EMAIL } })
if (!res.ok()) throw new Error(`dev-login: HTTP ${res.status()}`)
}
contexts.set(key, ctx)
return ctx
}

let count = 0
for (const [name, target, signedIn, variants] of pages()) {
if (opts.only && !name.includes(opts.only)) continue
for (const variant of variants) {
const ctx = await context(variant, signedIn)
const page = await ctx.newPage()
const api = async (path) => {
const res = await ctx.request.get(path)
if (!res.ok()) throw new Error(`${path}: HTTP ${res.status()}`)
return res.json()
}
const path = typeof target === 'function' ? await target(api) : target
const response = await page.goto(path, { waitUntil: 'load' })
if (!response || response.status() >= 400) throw new Error(`${name}: ${path} gave HTTP ${response?.status()}`)
await settle(page)
const file = join(opts.out, `${name}/${variant}.png`)
await mkdir(dirname(file), { recursive: true })
await page.screenshot({ path: file, fullPage: true, animations: 'disabled', caret: 'hide' })
await page.close()
count++
}
}
await browser.close()
console.log(`${count} screenshots in ${opts.out}`)
}

main().catch((e) => {
console.error(e)
process.exit(1)
})
13 changes: 13 additions & 0 deletions scripts/screenshots/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "visualci-screenshots",
"private": true,
"type": "module",
"packageManager": "pnpm@10.12.4",
"scripts": {
"capture": "node capture.mjs",
"stable": "node stable.mjs"
},
"dependencies": {
"playwright": "1.65.1"
}
}
Loading
Loading