Skip to content

Latest commit

 

History

History
640 lines (568 loc) · 55.3 KB

design.md

File metadata and controls

640 lines (568 loc) · 55.3 KB

VisualCI: design (draft, 26 Nov 2026)

Visual regression testing for documents first (PDFs and their pages), plus browser and mobile screenshots. DocSpring is the first customer. It's also a multi-tenant SaaS on visualci.com with credit billing, and an open-source self-hostable version.

Background

  • Existing visual testing services (Percy, Chromatic, Argos, Lost Pixel, Applitools) are built around browser screenshots taken on the client. None of them take a PDF, render it in one consistent environment, or understand pages. Teams that generate documents (invoices, statements, reports, labels, contracts) check them by hand or with home-made scripts.
  • DocSpring is the first user. Today it rasterizes PDFs with PDFBox at 140 dpi and compares the pages with committed PNG baselines, kept twice (ci and local) because Macs and Linux rasterize differently. Failed images are scattered across parallel CircleCI jobs and fetched back with brittle scripts. Its suites: 83 PDF acceptance tests (179 page images), a page design library (17 designs, typical and long data), ironpress's parity suite against Chrome (about 1,725 cases), plus browser and iOS simulator screenshots.
  • The original idea (2024) covered: upload screenshots or PDFs, a pending/ok/fail CI status API, variants for flaky images, SHA256 dedup with a hash check before upload, pausing CI instead of failing, per-key thresholds, test-name context, renderer version tags, credit pricing, an open-source self-hostable version plus a hosted SaaS, and trash and garbage collection.
  • Argos (MIT) was evaluated in November 2026: its review model (SHA256-addressed uploads, diffs skipped for identical files, per-branch baselines, a pending GitHub check until approval, ignore rules for flaky diffs) is good and is borrowed here. It has no PDF input, server-side rendering, PDF fingerprint or page-aware diffs.
  • Later, the same engine can check design-system conformance ("does this screen match its sibling views"), which no incumbent does.

Principles

  1. Render in one place. Sources (PDFs, DOM snapshots) are rendered by the service in pinned images, so a Mac and CI get identical pixels and there's one set of baselines. Client-rendered images (iOS simulator, native apps) are accepted, with a platform tag.
  2. Hash first, at every level. Source fingerprint → render cache → image key → diff cache. A run where nothing changed costs a few small API calls and no uploads, renders or diffs. This is also the cost model behind the pricing.
  3. Strict by default for documents. With a pinned renderer, any pixel difference in a PDF is real. Tolerance for anti-aliasing is opt-in (per project, test or snapshot) and mainly for browsers.
  4. Pages are first-class. Page counts, inserted or removed pages lined up, and a text diff per page.
  5. Never fail CI on a reviewable change. The CI job passes; a GitHub check stays pending until a person approves (Argos's model).
  6. Agents are first-class users. CLI and MCP, with machine-readable diffs.

Concepts

Concept Meaning
Organization Tenant, billing account (credits). Members (admin, member or read), mostly derived from its projects' repositories on their forge
Project One test suite's namespace, such as docspring/pdf-acceptance, docspring/browser or ironpress/parity. Settings: default thresholds, base branch, review rules
Build One CI run (or local run) of a project: commit, branch, PR, parent commits, mode (ci or local), shards. States: receiving → processing → (passed | changes | failed)
Snapshot A named item in a build. name is stable across runs (invoice_typical, signup_form/dark/1280). Kind: document (pages beneath it), image, text. A text snapshot has a format: text, json or html (see Text snapshots)
Source What the client sent: pdf, dom_snapshot or image, identified by its source fingerprint
Renderer A pinned rendering environment: id = engine + version + image digest + settings (for example pdfbox-3.0.5@sha256:…/dpi=140). Part of every render cache key
Render (project, source fingerprint, renderer id) → [page image keys + page text keys]. Cached per project: the fingerprint is the client's word, so a render is never shared with another account
Blob Content-addressed bytes in R2, keyed by sha256, deduplicated across all tenants
Baseline The approved snapshot for a name on a lineage (see Baselines)
Variant An extra accepted image for a name (a flaky render). Matching any variant counts as a match
Diff (base image key, head image key, diff settings) → score, changed-pixel count, mask, bounding boxes, fingerprint. Cached, so the same pair is never diffed twice
Ignore rule A diff fingerprint accepted as noise for one snapshot name (Argos's model), with an optional "after N occurrences". For text snapshots, a project's JSON paths and regular expressions whose matches are ignored; for images, masked areas (region, rects) left out of the diff
Config visualci.yml in the repository, validated by the CLI and the server and stored on the build (builds.config). Each build uses its own commit's file; fields it sets (ignore rules, thresholds by glob, PDF engine and DPI, CI mode) override the project's settings for that build (domain::build_settings). A stored file that no longer validates (a later, stricter version, or a parsing bug) is never treated as absent: processing fails the build with error_code config_invalid and an error naming the field, early comparisons and uploads refuse with the same message, and views of a build compared before its file stopped validating add it to the build's warnings
Review Approve or reject a build, or individual snapshots. Approval moves the baseline

The pipeline

client (CLI / Ruby gem / JS SDK)
  1. POST /builds  {project, commit, branch, pr, parents, mode}
  2. POST /builds/:id/snapshots  [{name, kind, sha256, fingerprint?, size, threshold?, meta}]   (batched)
       ← per snapshot: "known" | "upload": presigned R2 URL
  3. PUT only the sources the server lacks (PDF bytes, DOM snapshot bundle, PNG)
  4. POST /builds/:id/finalize  (or once per shard; the build closes when all shards finish)
server
  5. per snapshot: render cache hit?  no → enqueue render (render node, gVisor)
  6. per page/image: same key as a baseline or variant?  yes → unchanged (no diff)
  7. diff cache hit?  no → enqueue diff
  8. ignore rules, then build summary → GitHub check
client
  9. --wait: poll or stream until done; exit code by mode (see CI behaviour)

Step 2 names each file by its SHA-256, and the fingerprint is optional (sc-8999). Unchanged screenshots are byte-identical from run to run, so the file's hash finds them: the client needn't decode every image to fingerprint it. The server answers per file whether it has it, and for a file it has, the snapshot takes the fingerprint stored on its blob. For a new file, the server computes the fingerprint once the bytes arrive and keeps it on the blob: an image's pixel fingerprint when processing starts (processing::fill_image_fingerprints, outside any transaction, one statement for the snapshots), and a PDF's fingerprint from the renderer, which computes it from the file in its sandbox and reports it with the pages (a PDF it has no fingerprint for yet is drawn under its file's hash, and the render moves to the fingerprint when the project has none under it). A re-encoded file (the same pixels in new bytes, after a browser upgrade) is uploaded once and kept as its own blob under its own hash, with the same fingerprint, so it compares unchanged and later runs match it by hash with no upload or decode. Blobs are never merged by fingerprint.

The CLI sends images by their hash alone and the server fingerprints them (Nathan's decision, sc-8999). PDFs still carry the CLI's fingerprint (with the same open-source library the server and renderer use): a PDF's bytes change on every run (creation dates, IDs) while what it draws doesn't, so without it every PDF would be uploaded, and drawn, on every run. CLIs before 0.2.20 send every fingerprint, and the server takes them as they are. Registration costs the same few statements for 1 snapshot or 1,000 (the blobs' upsert and read, one renders query, the snapshots' upsert).

Large suites: manifest and group hashes (sc-8868)

A run of 500 or more snapshots (the CLI decides; VISUALCI_GROUPS overrides) first sends POST /builds/:id/groups: a hash of the whole run and one hash per group of names (a name's group is its path without the last two segments, or its first group_depth segments). Hashes come from visualci_core::manifest, over each snapshot's name, platform, kind, fingerprint and comparison settings, so the CLI and the server compute them the same way. A client that doesn't decode images sends image_hash: sha256, and an image's entry then holds its file's SHA-256 on both sides. The server computes the baseline's side from its own rows (baselines::resolve), never from a client's claim, records each group in build_groups and answers which groups differ. The client sends only those groups' files.

When the build processes, the snapshots of matched groups (all of them, when the whole run matched: builds.manifest_same_as_build_id) are carried forward from their baselines, as a subset build's missing snapshots are, so every later reader sees a complete build. A matched group costs CREDITS_PER_GROUP_CHECK (1) and a matched run 1 in all; changed groups' snapshots are charged as usual. A group can be sent by one shard only. The UI and get_build show the matched groups collapsed ("N groups unchanged, the same as #M").

Source fingerprints

  • PDF, byte-stable producers (ironpress, which has no dates, IDs or Producer): sha256(bytes) is enough. It's also tried first for every PDF.
  • PDF, "what's drawn" fingerprint (PDFBox merges, Chrome, older PDFs; it replaces the regex DeterministicPDFHash, which misses compressed and XMP metadata):
    1. Parse (lopdf or qpdf), decompress every stream, ignore object numbers and xref layout.
    2. Drop the /Info dictionary, the catalog's /Metadata (XMP), the trailer's /ID and /Producer//CreationDate anywhere.
    3. Normalize font subset tags (ABCDEF+Helvetica → +Helvetica), since some producers randomize them.
    4. Per page, hash in order: MediaBox, CropBox and Rotate, the decompressed content stream bytes, and every resource the page uses, recursively, by the hash of its decompressed stream and normalized dictionary (fonts, XObjects, images, patterns, ExtGState). Annotations that are visible are hashed through their appearance streams.
    5. Document fingerprint = hash(page fingerprints) + algorithm version.
    • Page fingerprints are the alignment key: an inserted page shows up as one insertion in a sequence diff (LCS) of page fingerprints, not as N changed pages.
    • Validate it on DocSpring's corpus: the same input rendered twice must give the same fingerprint for every test, including combining_pdfs_spec. A fingerprint that changes when it shouldn't costs one render; it's never wrong, because identical renders still dedup by image key.
  • DOM snapshot: the client serializes the page (fork or reuse Percy's MIT @percy/dom: inlines form state, canvas → image, shadow DOM, iframes). The bundle is HTML plus a resource manifest {url → sha256}. Fingerprint = hash(normalized HTML, sorted manifest, viewport, device scale factor, color scheme, user agent class). Resources are uploaded content-addressed, so only the new ones go up.
  • Image (client-rendered): sha256 of the decoded RGBA pixels plus dimensions, not the file bytes, so PNG encoder differences don't matter. The server computes it from the uploaded file (vci-img-1); clients send the file's hash. Tagged with platform (ios-26.1/iphone-16), which is part of the snapshot's baseline key.

Renderers

  • pdf-raster: PDFBox (DocSpring's current choice, 140 dpi) and mutool, and later pdfium, each pinned in an image with fonts. A project picks its engine and dpi, so DocSpring can keep PDFBox at 140 dpi and its 179 ci baselines carry over unchanged. Each page's text comes out alongside (PDFBox or mutool text extraction) and is stored as a text blob.
  • chromium: headless Chromium, pinned, run with no network. Every resource comes from the snapshot bundle, so hostile snapshots can't reach anything, and pages can't vary by network timing. Waits for fonts, then captures full page or viewport.
  • All renderers run on render-1 (tainted talira.ai/untrusted, RuntimeClass gvisor), with no service-account token and egress only to the API and R2. They pull jobs from the queue through the API, not straight from Postgres.

Diffing

  • A Rust diff worker with two metrics per pair:
    • exact: number of changed pixels and the fraction changed. That's today's Imatcher-style threshold, where a single checkbox is about 0.00002 and DocSpring's threshold is 0.000001. The default for documents is 0 changed pixels.
    • perceptual: YIQ colour distance with anti-aliasing detection (pixelmatch/odiff style), for browsers.
  • Output: changed-pixel count, bounding boxes of changed regions, a mask PNG, an overlay PNG and a diff fingerprint (a hash of the quantized mask) for ignore rules.
  • Different page sizes are a "size changed" result shown side by side, not an error.
  • Later: layout-shift detection (content moved down by N px), which fits page-break regressions.

Documents and pages

  • A document snapshot holds N page images, N page texts, the page fingerprints, and the page count.
  • Comparing documents: LCS on page fingerprints, falling back to page text similarity. That gives unchanged / changed / inserted / removed per page, and the UI lines them up.
  • Text diff per page, plus a document-level "moved" view: lines whose text moved to another page ("Item 45: page 2 → page 3"). That's the clearest signal for page-break bugs.
  • Page-count assertions are free: a changed page count is always a change.

Text snapshots

Every other snapshot test (API responses, serialized React or component trees, emails, generated config) is reviewed the same way as a screenshot: a change keeps the GitHub check pending instead of failing CI (Nathan, 30 Nov 2026).

  • All of them are kind = 'text', with a format column: text, json or html. The format comes from the client's format field, else the content type, else the file's extension. One kind keeps billing simple: a changed text snapshot is a text diff (CREDITS_PER_TEXT_DIFF), whatever its format.
  • They're normalized on the server when compared (visualci_core::snapshot_text), base and head both in the head's format: JSON parsed and printed with sorted keys and two-space indentation; HTML through a lenient tokenizer that lowercases names, sorts attributes, collapses whitespace in text and puts one node per line (pre, textarea, script and style content kept); JSON that doesn't parse is compared as plain text, with a note. A change only in key order, attribute order or whitespace is unchanged, so it costs no diff.
  • Ignore rules: JSON paths ($.a.b, [n], [*], .*, $..key) and regular expressions, always scoped to a snapshot glob (visualci_core::config::ScopedIgnoreRule; there are no global rules). They come from the build's visualci.yml when it has ignore, else the project's (projects.ignore_rules), plus rules set in the test for one snapshot (snapshots.ignore_rules). The head's rules apply to both sides, so a new rule hides a value without re-approving the baseline. Matches become [ignored] before comparing. They're checked when saved.
  • Image masks (sc-9018): the same scoped rules can carry region (edge bands: top, bottom, left, right, in pixels) and rects (x, y, width, height). For images and rendered pages, BuildSettings::image_mask collects the areas of every rule in force that matches the snapshot (the build's file, else the project's: the same model as text rules, read from builds.config when the build is compared or viewed, never from a later file). diffs::find_or_compute resolves them against the diff's canvas (ImageMask::resolve) and diffs with visualci_core::diff::diff_masked: masked pixels are never changed, so they stay out of the counts, the regions and the fingerprint, and the overlay hatches them. The mask's hash is part of the diff cache key. The result keeps masked (the areas) and masked_pixels (the differing pixels they hid); a page that differs only there is masked, and counts as unchanged. A new mask is a "hides more" change, so it brings the visualci.yml item. Not done: a ±1 px shift tolerance.
  • The page row keeps the normalized texts, so the review shows what was compared: a unified diff with line numbers (3 lines of context, folded in the web app, ?context=all for every line) and, for JSON, the changes by path (items[3].price: 10 → 12), arrays aligned by element so an insertion is one change.
  • Test frameworks' snapshot files are split on the client (visualci_core::adapters, visualci upload --from): Jest and Vitest .snap (one snapshot per exports[...]), insta .snap (header dropped), syrupy .ambr (one per # name:) and rspec-snapshot .snap (one per file). Names are the file's path without __snapshots__/ and the extension, then the test's name.

Baselines and review

  • Baselines are per snapshot, in two layers (domain::baselines):
    1. The anchor: the nearest ancestor commit's completed CI build of the suite (else the default branch's latest approved one). Every build records every snapshot, so the anchor has each one's approved state at that commit: an approved change is its new version, an unapproved change the version it was compared with, an unchanged snapshot itself. The anchor is the build shown as "compared with #N", and its approved visualci.yml is what a config change is compared with.
    2. Approvals since (baselines table, one row per approved change or removal, with build, commit, branch, environment and mode): rows newer than the anchor are laid on top, CI approvals on the build's ancestry and any approval on its own branch. Approving three of four changes keeps those three. Rejecting withdraws the rows.
    3. Merges: the GitHub App's pull_request webhook (/webhooks/github) copies a merged pull request's current CI approvals to the base branch at the merge commit (rows with approval merged). They count for builds whose history has the merge commit and whose anchor doesn't, so a squash merge doesn't ask for the same approvals again, and a later approval on the base branch wins. Installation events keep projects' installations current. This is the only way a pull request's approvals reach its base branch: a build never takes approvals from a branch outside its history.
  • Nothing becomes a baseline unreviewed. A CI build with nothing to compare against is approved on its own only on the project's default branch (projects.default_branch): that first build is the baseline. A pull request branch's first build with no base waits for review like any change, and its approval reaches the default branch at the merge. A build with no changes is approved on any branch (it records nothing). (An unreviewed pull request's first build once became the baseline for unrelated branches, through first-build approval on any branch and a fallback that took any branch's approvals.)
  • Trust: a local approval counts on its own branch only (never through ancestry), so CI on that branch matches a laptop's approved PDFs and text, with "approved locally by … on …" on the snapshot. From a working tree with uncommitted changes, an approval sets only that environment's screenshots. A local build can't use the ci environment, nor a CI build a local-* one. Exact-match passes (an image or text approved in another environment) use only current rows: CI approvals on the default branch or the build's own branch's, not superseded, never another branch's.
  • Environments: ci, local-mac, local-linux (the CLI detects them: a CI provider or CI=true means ci, else the OS; VISUALCI_ENVIRONMENT overrides). Only client-made images (screenshots) keep a set per environment; documents are rendered on VisualCI's servers and text is the same everywhere, so they share one set (environment ""). A screenshot with no baseline in its own environment compares with the closest one (local-linux falls back to ci, then local-mac). One that differs from its own baseline but exactly matches an approved image of another environment passes, and records matched_environment ("matched local-mac").
  • Every review records how it was made (reviews.source: web, oauth, personal_token, project_token, with the OAuth client's name, the agent and the token's name) and an optional note, and a baseline points at the review that approved it (baselines.review_id). Everywhere a review shows (the build's reviews, "approved on main", get_build, the PR comment, the check summary) it reads "Claude Code for Ada Lovelace", "Ada Lovelace" (the web app) or "a project token (CI)" (domain::reviews::by): VisualCI is mostly used by agents, so an agent's approval never reads as the person's own (Nathan, 2 Dec 2026). In the web app the build page's optional "Why?" field is the note for whichever review is made from it (sc-8799).
  • Two pull requests that change the same snapshot and merge separately leave an image neither showed. Between merged approvals in a build's history the nearer merge wins, and a change whose every region is exactly a region a merged PR's build changed and approved (the same box, the same old and new pixels) points at that build (snapshots.matches_build_id, domain::matching, found while processing): "matches PR #8's approved change", a hint that approves nothing; review with only: "matching" approves those (sc-8785).
  • A pull request build compared on top of an unreviewed default-branch build shows that build's changes again. Those that are exactly the base build's unreviewed change (the same snapshot and new content) are marked (domain::inherited, on_main_unreviewed) and the build says "N changes are already on main and unreviewed (build #X)", linking there. Approval and the check still go by approved baselines (sc-8770).
  • Partial approval per snapshot. "Accept as variant" adds the image to the name's variants without replacing the baseline. "Ignore this change" stores the diff fingerprint.
  • GitHub App: check run per project and build name, named VisualCI (default build name) or VisualCI: <name>, so a repository with several suites (one project per repository) gets one check each (pending while there are unreviewed changes, success once approved, failure if rejected).
  • One comment per project and pull request (forge::pr_comment, through Forge::upsert_pr_comment; the id is in pr_comments), edited in place whenever one of its builds changes and only when its text would: each suite's newest build with counts, review state, before/after images of up to eight changed snapshots (week-long signed URLs, since the forge shows them long after VisualCI could refresh them), what was removed, and a link. get_snapshot gives the same week-long embed_urls, so an agent can put images in its own comment. Without permission to comment (403) it logs and waits. The PR-vs-base summary and open threads join it with their stories (sc-8567, sc-8565).
  • Retention (domain::retention, the daily retention:prune task, 90 days): images, PDFs and render rows are deleted once nothing needs them. Kept: everything builds from the last 90 days use (and their base builds), the newest completed default-branch CI build of each suite, every current baseline (the newest baseline row per name on the default branch and on branches with a recent build), the snapshots those compared against, unfinished or recent renders, variants, and blobs created in the last 90 days. Build, snapshot, page and diff rows stay, so results and diff numbers remain and the images show as deleted. A diff whose overlay was deleted is computed again if the same pair comes back.

Comment threads

Threads pinned to pixels (domain::comments, sc-8565): a thread is on one snapshot (name and platform) of a project's branch, drawn on one build: a point, a box or the whole image of a page's base or head side. Coordinates are pixels of that image from its top left (the units of get_snapshot's regions), checked against the image's size when the thread starts. A pin never moves to another build's image, and comments never change what a build is compared with. Newer builds of the snapshot on the branch list an open thread as a line ("1 open comment on build #3") linking to where it was drawn, and an open thread still blocks review approving the snapshot there (the refusal names the build and the thread); rejecting still works, and a reject can carry a comment. Resolving it anywhere unblocks it. A comment's author is a person (the web app) or an agent (MCP, with its client's name, acting for its person or a project token). Replying reopens a resolved thread. Bodies are Markdown, shown as text in the web app (no HTML from customers is rendered). get_build, get_snapshot and whoami list open threads with the build each was drawn on.

"Compared with: Previous build" (Snapshot::review_detail_against): the snapshot page, and get_snapshot with against: "previous" (or an earlier build's number), can compare the new side with the newest earlier build of the snapshot on the branch instead of the baseline, to check a fix against a comment left there. The previous build's new-side pins then show on the old side, the image they were drawn on. It's a view: pages are aligned and diffed on request (diffs cached like any other, no credits), and review, the check and credits always use the baseline.

Coding agents (MCP)

The server has an MCP endpoint (/mcp, Streamable HTTP, project-token auth) for coding agents, which do most of the fixing: list_builds, get_build (the changed snapshots), get_snapshot (per page: the operation, changed pixels and regions, the text diff, lines that moved page, and the base, head and diff images as image content) and review. An agent that broke a page looks at the images itself, in the session that broke it.

VisualCI never runs a model (Nathan, 1 Dec 2026: "the whole point is that the AI model under the customer's own subscription is doing this work already"). It gives the customer's agent the evidence over MCP (regions, crops, text and JSON diffs, contact sheets), and the build's summary line is computed from the comparison (app/src/domain/summary.rs).

Clients and CI behaviour

  • CLI visualci (Rust, single static binary, Mac and Linux): visualci upload <dir|files>, visualci pdf <file.pdf> --name invoice_typical, visualci check (local), visualci build status, and visualci approve for agents with permission.
  • Ruby gem visualci for RSpec: expect_pdf_to_match_visual(name, pdf_path) and expect_screenshot_to_match_visual(name, png_or_page). It batches snapshots per process and finalizes in an after(:suite) hook. Shards via CIRCLE_NODE_INDEX / CIRCLE_NODE_TOTAL and CIRCLE_WORKFLOW_ID as the build nonce.
  • JS SDK / Playwright fixture later, with DOM snapshot capture.
  • MCP server (/mcp): list builds, see changed snapshots, look at changed pages (images, regions, text diffs), approve or reject.
  • CI modes (per project, overridable per run):
    • review (default): the CI step passes; the GitHub check blocks the merge until approved.
    • strict: the CI step fails on any unapproved change (for ironpress parity runs, where a change is a bug).
    • wait: the CI step polls until a person approves or rejects , with a timeout.
  • Local runs: mode=local (the CLI's default outside CI), with the laptop's environment (local-mac, local-linux) and {user, machine, dirty} for the UI. PDFs are rendered on the server, so they match CI. Local builds get no GitHub check and never notify. They can be approved: that records baselines for the branch, in the build's environment for screenshots and in the shared set for documents and text, so CI on the pushed commit matches with no second review. A local build's changes always wait for review, even in a project's first build. This replaces UPDATE_TEST_EXPECTATIONS=1 and the committed local images.

API sketch (REST, JSON, OpenAPI)

POST   /v1/builds                         → {build_id, upload_mode}
POST   /v1/builds/:id/snapshots           [{name, kind, sha256, fingerprint?, size, platform?, threshold?, meta}]
                                          → [{name, status: known|upload, upload:{url, fields}}]
POST   /v1/builds/:id/shards/:n/finalize
POST   /v1/builds/:id/finalize
GET    /v1/builds/:id                     → state, counts, check status
GET    /v1/builds/:id/snapshots?status=changed
GET    /v1/snapshots/:id/diff             → per page: base, head, overlay, score, text diff
POST   /v1/builds/:id/review              {action: approve|reject, snapshots?: [...]}
POST   /v1/snapshots/:id/variants | /ignore

Unknown fields are refused, never ignored: the API's bodies (422 naming the field) and every MCP tool's arguments (additionalProperties: false in the schema, and a refusal that names the argument and lists what the tool takes). An ignored argument once dropped agents' approval notes without a word (sc-8771). The feedback endpoint stays lenient: it follows the Standard Support draft, whose newer versions may add fields.

Auth: a project token for CI (write snapshots, read results), GitHub Actions OIDC later, a user session or PAT for review, and scoped agent tokens for MCP.

Access and forges

A forge is where a project's repository lives: GitHub and GitLab (gitlab.com; self-managed instances next, sc-8515), Bitbucket (sc-8516), Azure DevOps (sc-8517) and Gitea/Forgejo (sc-8518) later. app/src/forge/ is the one interface the rest of the app uses, with a forge-neutral kind (ForgeKind::Github, ForgeKind::Gitlab, one variant per forge) and a module per forge's API, covering:

  • sign-in: the authorization URL and the code exchange, giving the forge identity, its verified emails and the repositories the person can reach with their permission on each;
  • repository permission for one identity on one repository, from the forge's app or installation credentials;
  • webhooks: verified endpoints (/webhooks/github for the App; /webhooks/gitlab/<project> for each GitLab project's own hook and secret, acting on that project only, since several organizations may link one repository), normalised into merges, installation changes and membership changes;
  • the PR check (GitHub's check runs; a commit status named VisualCI on GitLab: pending, running, success or failed, a neutral result counting as success);
  • the repository from CI: the CLI sends the repository URL its CI names (GITHUB_SERVER_URL/GITHUB_REPOSITORY, CI_PROJECT_URL, BITBUCKET_GIT_HTTP_ORIGIN, BUILD_REPOSITORY_URI, …), and a project with no repository yet is linked to it on its first build.

A project links to a forge plus a repository URL (projects.forge, projects.repository_url, projects.forge_installation), never to a forge-specific field. Linking needs Maintain or Admin on the repository; projects.linked_by records who linked it, and the hourly sync unlinks a project whose linker no longer has it (with a notice on the project), so nobody keeps posting VisualCI's checks to a repository they've lost. Permission is always looked up by the person's permanent forge user ID, never a stored login, which can be renamed and taken.

Onboarding through the GitHub App (sc-9027). Signing up makes an empty personal organization; installing the GitHub App maps the installation to an organization, and people pick which repositories become projects. github_installations records every installation VisualCI hears of (from a sign-in, which lists the ones the person can reach into user_installations, and from the installation webhook: created, suspended, removed, with removed rows kept so a reinstall finds its organization again). The App's Setup URL, GET /github/setup?installation_id=…&state=… on the app host, maps the installation to an organization: the person's own account to their personal organization (users.personal_organization_id); a GitHub organization to the one it was set up for before (only its admins add to it), else a new one whose slug is the lowercased login (<login>-github when taken), with the installer as admin and everyone else joining through the hourly sync. Reaching a repository through an installation proves nothing about its account, so a new claim is checked live before anything is written: the person's own account, or for a GitHub organization its owner (GET /orgs/{org}/memberships/{user}, which needs the App's Members: read permission) or whoever installed the App there (the installation webhook's sender, installed_by); another person's account is refused. The mapping is written only where none exists, so two people setting it up at once can't both win. The GET sets up only the install this browser started (/github/install puts a state in the session and sends it to GitHub); anything else lands on the checklist, where a click sets it up. Setting up makes no projects and takes a few GitHub calls at most, so it answers at once even for an organization with hundreds of repositories (3 Dec 2026: making a project per repository inside the request ran past the 30 s limit on DocSpring's 255). It lands on the repository picker (/{org}/repositories), which reads user_repositories: every repository each person can reach through each installation, with their permission, as of their last GitHub sign-in (which lists them anyway), so it pages and searches with no GitHub call. The repositories they pick (Maintain or Admin, not archived, at most 50 at a time) become a repository_imports row and a queued job (ImportRepositories) links them one by one through the usual link checks, saving progress after each; the picker shows it, and /status reports stalled_repository_import_seconds. Nothing becomes a project on its own: repositories added to an installation later wait in the picker too. The checklist (install_github_app, connect_agent, add_to_ci, review_changes: the coding agent comes before CI because it adds VisualCI to CI, from a prompt the step pre-fills for the project) offers installations the person can reach that aren't set up yet (POST /api/ui/installations/{id}/setup).

GitLab. GitLab is parked in app/ (sign-in and the bot's token are read, the rest of this is the design to finish). GitLab has no app installations, so VisualCI acts through a bot user on gitlab.com (@visualci, its personal access token in VISUALCI_GITLAB_BOT_TOKEN). A project's forge_installation is bot once the bot is a member: a Developer can post the commit status and the merge request note (one per MR, edited in place) and check people's access (/projects/:id/members/all/:user_id, inherited group access included); a Maintainer also lets VisualCI add the project's webhook. GitLab sends a hook's secret as a plain X-Gitlab-Token, so each project has its own (secrets::webhook_secret: an HMAC of the project's ID under VISUALCI_SECRETS_KEY, stored nowhere); a delivery is accepted only with the secret of a project linked to the repository it names, which records forge_webhook_at (the project page shows the hook as working, or the URL and secret to add by hand, with "Set it up for me" for a Maintainer bot). The hourly sync adds missing hooks once the bot can, and fails its heartbeat 30 days before the bot's token expires. Sign-in uses VisualCI's OAuth application (read_user read_api): the confirmed primary email counts as verified, and /projects?membership=true gives each project's access level. Access levels map onto the same permissions: Owner → admin, Maintainer → maintain, Developer → write, Reporter → read; Guests and Planners get nothing, since they can't read a private project's code. Group membership webhooks are a Premium feature on gitlab.com, so GitLab access changes reach VisualCI through sign-in and the hourly sync. Repository URLs: gitlab.com projects with nested groups (group/sub/project).

Self-managed GitLab (not in app/ yet, sc-8634). An organization's admin adds its instance: the base URL (at the root of its host) and an OAuth application made there, whose secret is stored encrypted (secrets::encrypt: AES-256-GCM under a key derived from VISUALCI_SECRETS_KEY, which lives only in 1Password). People sign in at /auth/gitlab-<instance id> (its callback is /auth/gitlab-<instance id>/callback); their identity records its site (the instance's base URL; '' for github.com and gitlab.com), since user IDs and logins repeat across instances, and invitations by login are for github.com and gitlab.com only. A project there links with an access token its admin pastes (a project or group access token with api and Developer, or Maintainer so VisualCI adds its webhook), stored encrypted in projects.forge_token_enc with installation token; every call for it goes through Forge::for_project, which builds the instance's forge with that token. Sign-in and the hourly sync (which goes through each instance too) change memberships only in organizations without this forge's projects on another site, so gitlab.com and an instance never undo each other's grants; an organization with projects on both keeps the higher role either gives until the next sign-in. Webhooks work as on gitlab.com, and /webhooks/gitlab/<project> needs no GitLab configured. An instance's URL must be a name, not an address, and VisualCI calls it only at public addresses, with no redirects and limits on time and size (forge::outbound). Instances at a relative URL root (https://example.com/gitlab) aren't supported.

People. A user has one or more forge identities (identities: forge, the forge's user ID, login). Signing in with a forge finds the user by that identity, else by any of its verified emails, else creates one. Signing in with another forge identity while signed in links it to the same user. Accounts come only from a forge sign-in: there are no passwords. A self-managed GitLab instance is added by an organization's admin and says what it likes about its accounts, so its emails are never trusted (they don't find an account, become a new account's address or accept an invitation), and a new identity from one is never linked to whoever is signed in. On GitHub, a person counts for a repository only as a collaborator: GitHub reports read on a public repository for anyone at all.

Roles. An organization member is admin (settings, projects, tokens, billing, members), member (everything a build needs: uploads, review and approval) or read (sees builds and snapshots, changes nothing). Each membership records its source:

  • github, gitlab (one per forge): derived from repository permission, kept in step with the forge. A person's role is the highest their permission gives them on any repository the organization's projects link to: admin or maintain → admin, write → member, triage or read → read. GitHub organization members get whatever their base permission gives, and owners are admins of every repository, so membership of the GitHub organization that installed the App carries over without a separate rule. Losing every such permission removes the membership.
  • invite: an admin invited them by email or forge login (for people the forge doesn't cover, or organizations with no linked repository). An invitation waits for its invitee to accept or decline it in the app, whether or not they have an account (invitations.for_user_id records the account once known); they're emailed either way. Members' email addresses are shown to admins only.
  • staff: DocSpring support added them.
  • created: they made the organization.

Forge-derived rows never overwrite the other sources: someone invited or added by staff keeps that role.

Keeping in step. A sign-in recomputes the person's forge memberships from what the forge says they can reach (GitHub: the user's App installations and their repositories' permissions). The forge's webhooks recompute the people they name (GitHub: member, membership, organization, team), and the hourly forge sync (app/src/forge/sync.rs) rechecks every forge-derived membership through the installation (GitHub's collaborator permission endpoint), so access lost without a webhook goes within the hour. Each row records synced_at; /status reports the oldest as oldest_forge_sync_seconds, which the uptime check alerts on.

  • A repository belongs to one organization; several of its projects may link it. Links match by the forge's permanent repository ID (projects.repository_id, from the forge at link time and filled in by the hourly sync for older links), so a renamed or transferred repository stays linked and a new one that takes its old name doesn't. A link from a second organization is refused, naming the one that has it; a maintainer of the repository (checked live) can move it (move_link), which unlinks the other organization's projects with a notice and emails their admins (sc-8728).

Public galleries

A project can publish screenshots (gallery groups of snapshot globs in visualci.yml; domain::gallery). What's published is decided from the newest completed CI build of each suite on the default branch: its file names the groups, and each screenshot's approved state there (baselines::resolve for a build just after it, so what the next default-branch build would compare with) is the image served. A pending or rejected change keeps the old image: a review is the publish step. Only images from the ci environment are published.

  • URLs: one per published snapshot, /g/<org>/<project>/<name>.<ext> on the app host (@<platform> before the extension when the name is published on more than one platform), serving the stored image as it is, and a manifest at /g/<org>/<project>.json. No query parameters, variants, resizing or conversion: anything else is a 404 (no-store, never cached, so a screenshot published later shows up at once), so nobody can make VisualCI do (and bill) work for junk URLs.
  • Caching: public, max-age=300, s-maxage=86400, with a Cloudflare Cache Rule for app.visualci.com/g/ and Tiered Cache. Every change to a default-branch CI build (events.rs) queues the purge_gallery job, which purges exactly the URLs of the screenshots it changed, added or removed, and the manifest (Cloudflare's API, 30 URLs a call). Turning a gallery off purges everything it published.
  • Cost: each image the origin sends with a 200 costs its organization a credit (credit_transactions.kind = gallery); 304s, 404s and the manifest are free. Serving never stops when the organization is out of credits: breaking a customer's page is worse. A per-address limit (120 a minute per web process) keeps the URLs from being free image hosting.

Multi-tenancy and security

  • Blobs, renders and diffs are deduplicated globally by SHA256, as Argos does.
  • Customer documents are untrusted input: they're parsed and rendered only on the render node, under gVisor, with no network. The renderer computes a PDF's fingerprint in the same sandbox and reports it with the pages (client-side hashing is for the client's own files). Each claimed render gets its own token (its uploads and completion need it), the engines run with a cleared environment, the download is capped as it streams, and a pixel budget is checked before drawing: at most 110 megapixels a page, 2,500 a document and 2,000 pages at the job's DPI (visualci-renderer's budget, sc-8726).
  • Its own namespace, default-deny NetworkPolicies, its own CNPG cluster and R2 bucket (the cluster's per-product rules).
  • Retention per plan, deletion of an organization's data on request, an audit log of approvals.
  • DocSpring's fixtures stay synthetic or blank templates someone has checked (spec/pdf_integration/AGENTS.md rules).

Agent skills

One skill per CI provider and test tool, plus setup, review, local runs and visualci.yml, each generated from its docs page (frontend/scripts/skills.mjs, checked in CI). They're published four ways: the repository is a Claude Code plugin with the MCP server, npx skills add reads skills/ or visualci.com's /.well-known/agent-skills/ index, llms.txt lists them, and the MCP server's get_skill returns them.

Admin tools

DocSpring's own ops agents (triage, support) work on customers' issues through a staff-only MCP endpoint, mcp.visualci.com/mcp/admin (app/src/mcp/admin.rs), never through the regular /mcp.

  • Staff are users with users.staff (user:set-staff). The OAuth server has two resources, <mcp url>/mcp and <mcp url>/mcp/admin, each advertising only its own scope (mcp, admin), so clients never ask everyone for admin. The consent step (app/src/auth/oauth.rs, consent_scopes) decides what's granted whatever a client asked for: admin alone on the admin resource and only for staff (anyone else gets a refusal page), mcp alone on /mcp. The endpoint takes only an OAuth token for its own resource with the admin scope, for someone who is still staff (a 403 once they aren't). Personal and project tokens don't open it: they get a 401 saying so.
  • Tools: feedback (list_feedback, get_feedback), users and organizations with billing (find_user, find_org, get_org), recent failures (recent_failures), emails (list_emails), and the regular build and snapshot tools for any organization (get_project, list_builds, get_build, get_snapshot, snapshot_history, where staff act as an admin of every organization). Writes are few and need a reason: set_plan, mark_feedback_handled, rerun_build (a build stuck processing), resolve_email (retry or dismiss a failed one), set_open_source_withdrawn and set_credit_override (an organization's credit override, Billing). Nothing deletes data or moves money (deleting an organization is left to a person, with org:delete).
  • Every call is written to admin_audit (user, OAuth app, agent, tool, arguments, reason, outcome). Customer-written content comes back under untrusted_customer_data, or after a note saying it's untrusted.
  • In Executor it's its own app, visualci-admin, connected once by Nathan and given only to ops agents.

Billing

  • Prepaid credits that renew automatically (CircleCI-style), Stripe Checkout and Billing, and a double-entry ledger (reuse the design from DocSpring's billing).
  • Charged: renders (per page or snapshot, by renderer: Chromium costs more than a rasterizer), diffs and storage over the included amount. Free: hash hits, unchanged snapshots and the API calls themselves. So the pitch is "you pay when something changed", which the hash-first design makes affordable.
  • A free monthly allowance for small and open-source projects. Prices to be set once real render costs on the cluster are measured.
  • Stripe (VisualCI's own account; app/src/billing/): Team ($29/month) and the credit pack ($15) are Products and Prices, created on first use (fixed product IDs, prices found by lookup key), with the tax code for SaaS for business use. Every payment has an invoice: the subscription invoices itself (flexible billing mode), pack Checkout creates one, and an automatic reload is an invoice finalized and paid off-session. Stripe Tax is on for all of them, with billing addresses and tax IDs collected; it adds tax only where VisualCI registers, and threshold monitoring says when. The customer portal (its own configuration) updates the card, address and tax ID, lists invoices and cancels at the end of the period. A failed payment (a declined reload, invoice.payment_failed, a past-due subscription) shows on the billing page and pauses automatic reloads until an owner saves the reload limit again; a declined reload's invoice is voided, so nothing retries it. Webhook events arrive in any order and are retried for days: an organization applies a subscription event only if it's newer than the last one applied (organizations.stripe_event_at) and about its own subscription; a second Team subscription (two checkout tabs) becomes a billing problem, not the plan. A purchase's credits are added once per reference (a unique index), even when a reload and its invoice.paid race.
  • Credit overrides (app/src/domain/credit_overrides.rs): staff raise an organization's monthly credits until a date, such as a big open source project that needs more than the 1,000,000 open source pool. The override replaces the plan's monthly allowance (never lowering it) and nothing else: the open source pool still comes first and pack credits last. It applies through its until date (UTC, inclusive) and is read whenever the allowance is, so the day after, the organization is back on its plan's allowance with nothing to run; credits already used that month still count. Staff set it through the admin MCP server or org:set-credits, with a reason; each change writes a credit_override_audit row (who, when, the allowance before and after, the reason). The billing page shows only its public label ("Open source sponsorship: 3,000,000 a month until 1 Jun 2027, then 25,000."), never the reason. A week before it ends, credits:override-reminders (daily, its own heartbeat) emails the organization's admins, once per end date.

Stack and hosting

  • Backend: Laravel Rust + Postgres (app/; its own CNPG cluster: one instance, WAL and base backups to its own R2 bucket), with Laravel Rust's database queue, cache and sessions in the same Postgres. One image runs the web server (serve), the worker (queue:work), the scheduler (schedule:work) and the migrations (migrate --force).
  • Configuration (sc-9026): every server setting is a VISUALCI_ environment variable, declared once in app/src/config.rs as a typed struct (crates/envschema's derive): its description, type, default, and whether it's required, required in production or secret. The framework's and the OAuth server's variables keep their own names and are described there too. From that one schema: the app refuses to boot listing every missing or invalid setting, logs its settings with secrets masked, warns about VISUALCI_ variables nothing reads (naming the closest known one), and the docs page self-hosting/environment-variables and app/.env.example are generated (a test fails when they differ).
  • Frontend: React + TanStack (Router, Query), from the original note, in frontend: app/ serves its build as public/, and visualci.com is its static build.
  • Live updates (sc-8897): Postgres LISTEN/NOTIFY on one channel (app/src/live.rs), with no WebSockets and no broadcaster service. A change notifies a topic (build:42, project:7: BuildChanged, a new build, a build starting to process or making progress) and each web process passes it on to its server-sent event streams (app/src/http/live.rs): the project and build pages (/api/ui/live/..., which say "read again") and the CLI's --wait (/api/v1/live/builds/{id}, which carries the build). Every stream starts with a snapshot, so a reconnection or a late start never waits for the next change. Streams authorize with the same Principal as the API and MCP, are capped per principal, per build and per process (VISUALCI_LIVE_*, a 429 past them), hold no database connection while idle, and end after 30 minutes so access is checked again. The pages poll and the CLI polls whenever there's no stream. LISTEN needs a direct or session-mode connection to Postgres, not a transaction-mode PgBouncer. Behind Envoy, the /api/ui/live and /api/v1/live prefixes need a route without a response timeout.
  • Workers: app/'s queue worker (diffs) on products-1, and the renderer images (PDFBox/mutool, Chromium) on render-1 with gVisor.
  • Storage: R2 bucket visualci in the DocSpring Products account, presigned uploads straight from CI.
  • Hosts: visualci.com (landing page, docs, llms.txt, install.sh) is a static site, a Cloudflare Worker with static assets (frontend/site), deployed by CI. app.visualci.com (the web app and sign-in; the session cookie is host-only there), api.visualci.com (/api/v1, the CLI's default) and mcp.visualci.com (/mcp) go through the products-cluster tunnel (DocSpring Products account) → Contour → visualci, one app that routes by Host (app/src/http/hosts.rs). Each host serves only its own paths; anything else is a 404.
  • The pages find the hosts in meta tags (visualci-site-url and the rest): app/ writes them into the app's page from VISUALCI_*_URL (app/src/http/app_shell.rs), and the build into the site's pages (frontend/scripts/hosts.mjs). With no tags (one host, self-hosted) one origin serves everything.
  • Journeys (scripts/journeys/run.sh, CI's journeys job): production's configuration on four .test hosts behind Caddy with TLS, database sessions, and a GitHub stub (GITHUB_URL, refused outside testing and local), clicked through in a browser: signing in from the site, "Open app", signing out, returning to a page after sign-in, MCP on its own host, and the waitlist. Each step's screenshot is the journeys build ("VisualCI: journeys" check). Every sign-in bug of 3 Dec 2026 got through because the tests ran on one host with memory sessions and the development sign-in.
  • Deploys: GitOps (ArgoCD) from the cluster's infra repo, images on ghcr.
  • Monitoring: health checks on the web and API, a worker heartbeat that checks work is being done (the oldest queued job's age, the last completed render), and alerts on queue depth. An agent listens for the alerts and fixes them.
  • Open source: the server and clients in one public repo, all under Apache-2.0 (Nathan, 30 Nov 2026). FSL was the plan, but software like this can be rebuilt in days now, so a licence that forbids competing hosted services protects nothing. The hosted version at visualci.com is what's paid for.

Rollout for DocSpring

  1. Fingerprint library + CLI + PDF renderer: check that the fingerprint is stable over two runs of every PDF acceptance test (including combining_pdfs).
  2. Server MVP: builds, snapshots, render cache, exact diff, baselines on main, the web review UI, the GitHub check. Import the 179 ci expected images as main's baseline (PDFBox at 140 dpi, so they match).
  3. DocSpring PDF acceptance tests on it: the Ruby gem replaces compare_pages!. Run both side by side for a week, then delete the committed PNGs, the local copies, the Redis comparison cache and the CircleCI artifact download scripts.
  4. Page design library spec and ironpress parity (strict mode). Page alignment and text diffs land here.
  5. Browser screenshots: DOM snapshots for the visual forms and signature request specs. Client images for the iOS simulator.
  6. Public launch: landing page, docs, billing, the free allowance, a Talira listing, and an MCP server.

Open questions

  1. Keep PDFBox at 140 dpi as DocSpring's renderer (the baselines carry over), or move to a higher dpi or pdfium while re-baselining anyway?
  2. Should wait mode (CI blocks until approval) be in the MVP, or come after review and strict?
  3. Repo location: a new visualci repo under the DocSpring GitHub org, or a separate org for the products?