Yevrix AI / Tutorials / AI & LLM Tutorials

AI UI Design Review Harness: Screenshot Diff, Isolated Worktree & Evidence Gate

📂 AI & LLM Tutorials 📅 2026-12-01 ⏱️ 9 min read ✍️ Yevrix AI Original
TL;DR: Build a production-grade UI review harness for coding agents: deterministic screenshot capture, pixel-diff evidence, isolated Git worktree repair, and an independent reviewer gate.

The Real Production Failure: The Agent Says "Fixed", Users See a Broken Button

The most common failure mode for coding agents over the past year is not bad code generation — it is the inability to prove a change actually fixed the user-visible problem. A real ticket: operations reports that on mobile checkout, the coupon overlay's confirm button is hidden behind the bottom safe area. The agent opens the source, changes padding-bottom from 16px to env(safe-area-inset-bottom), passes unit tests, and replies "fixed". After deploy, users still cannot see the button — because the actual root cause is a parent container with overflow: hidden plus position: fixed being pushed up by the iOS Safari visual viewport when the keyboard opens. The padding was never on the rendering path.

Three layers of mechanism explain this:

  1. Missing observation. The agent's input is source code and logs, not rendered output. CSS cascade, containing blocks, compositing layers, and viewport units only collapse into final pixels inside a real browser.
  2. Non-isolated repair. The agent edits the main working tree directly. A wrong change is expensive to roll back, and you cannot validate multiple hypotheses in parallel.
  3. Evidence-free review. A human reviewer sees only a diff, not before/after visual evidence, so review degrades into style checking.

Tools like HappyHands point at the right architecture: drive your existing Chrome/Edge against a real preview, capture the states a user task passes through, report only problems with a reproducible observation, repair inside an isolated Git worktree, and let a separate reviewer judge the before/after evidence. This article does not restate that implementation; it decomposes the loop into production components: deterministic capture, pixel diff, worktree isolation, and an evidence gate.

Core principle: an agent may propose a hypothesis, but only evidence closes a ticket. Any "fixed" without a screenshot diff is unverified.

Production Implementation: From Capture to Evidence Gate

Deterministic capture: fixed viewport, frozen animation, network idle

If screenshots are not reproducible, the diff is noise. Lock three things: viewport size, device pixel ratio, and animation state. Here is a reusable Playwright (Node) collector:

js
// capture.mjs — deterministic screenshot capture
import { chromium } from 'playwright';
import { mkdir } from 'node:fs/promises';

const VIEWPORTS = [
  { name: 'mobile', width: 390, height: 844, dpr: 3, isMobile: true },
  { name: 'desktop', width: 1440, height: 900, dpr: 1, isMobile: false },
];

export async function capture(baseUrl, steps, outDir) {
  await mkdir(outDir, { recursive: true });
  const browser = await chromium.launch({ args: ['--force-color-profile=srgb'] });
  const results = [];
  for (const vp of VIEWPORTS) {
    const ctx = await browser.newContext({
      viewport: { width: vp.width, height: vp.height },
      deviceScaleFactor: vp.dpr,
      isMobile: vp.isMobile,
      hasTouch: vp.isMobile,
      reducedMotion: 'reduce', // critical: disable animations to avoid jitter
      colorScheme: 'light',
      locale: 'zh-CN',
      timezoneId: 'Asia/Shanghai',
    });
    const page = await ctx.newPage();
    // Freeze CSS animations and transitions to remove nondeterminism
    await page.addInitScript(() => {
      const style = document.createElement('style');
      style.textContent = '*,*::before,*::after{animation-duration:0s!important;transition-duration:0s!important;caret-color:transparent!important}'
      document.addEventListener('DOMContentLoaded', () => document.head.appendChild(style));
    });
    for (const step of steps) {
      await page.goto(baseUrl + step.path, { waitUntil: 'networkidle' });
      if (step.action) await step.action(page);
      await page.waitForLoadState('networkidle');
      const file = `${outDir}/${vp.name}-${step.id}.png`;
      await page.screenshot({ path: file, fullPage: false, animations: 'disabled' });
      results.push({ viewport: vp.name, step: step.id, file });
    }
    await ctx.close();
  }
  await browser.close();
  return results;
}

Key parameters, item by item:

  • reducedMotion: 'reduce' plus animations: 'disabled' is a double safeguard: the former makes the page respect prefers-reduced-motion, the latter forces animations to end at capture time. Using only one can miss JS-driven requestAnimationFrame animations.
  • --force-color-profile=srgb prevents pixel drift between CI machines and local machines with different color profiles.
  • waitUntil: 'networkidle' followed by waitForLoadState covers lazy-loaded images after SPA route transitions.
  • deviceScaleFactor must match the target device; otherwise a 1px border renders as 3 physical pixels on a 3x screen and the diff threshold is completely different.

Pixel diff: produce adjudicable evidence with pixelmatch

Once you have screenshots, quantify the difference. Never use "looks different" — emit structured metrics:

js
// diff.mjs — pixel-level diff and region localization
import { PNG } from 'pngjs';
import pixelmatch from 'pixelmatch';
import { readFile, writeFile } from 'node:fs/promises';

export async function diff(beforePath, afterPath, outPath) {
  const before = PNG.sync.read(await readFile(beforePath));
  const after = PNG.sync.read(await readFile(afterPath));
  if (before.width !== after.width || before.height !== after.height) {
    throw new Error(`size mismatch: ${before.width}x${before.height} vs ${after.width}x${after.height}`);
  }
  const out = new PNG({ width: before.width, height: before.height });
  const changed = pixelmatch(before.data, after.data, out.data, before.width, before.height, {
    threshold: 0.1,        // 0.1 tolerates antialiasing noise; 0 amplifies font rendering differences
    includeAA: false,      // ignore antialiased pixels to reduce false positives
    alpha: 0.3,            // semi-transparent overlay for human localization
    diffColor: [255, 0, 0],
  });
  await writeFile(outPath, PNG.sync.write(out));
  const total = before.width * before.height;
  return { changed, total, ratio: changed / total, outPath };
}

threshold: 0.1 is an empirical value: below 0.1, subpixel antialiasing and shadow blur produce many 1-2 pixel false differences; above 0.2, low-contrast misalignment on light backgrounds is missed. includeAA: false is mandatory, otherwise every text edge is flagged.

Evidence gate rule: only ratio > 0.002 (about 0.2% of pixels changed) may enter the repair flow; otherwise the observation is not reproducible and the agent's proposal is rejected. Tune the threshold per page complexity, but keep it in config, not scattered in code.

Isolated repair: one Git worktree per hypothesis

Agent repairs must happen in an isolated worktree; the main tree stays clean. Use git worktree:

bash
# Create an isolated worktree per repair task, based on current HEAD
git worktree add -b fix/ui-coupon-overlay /tmp/hh-worktrees/coupon-overlay HEAD

# Let the agent edit inside the isolated tree; main is untouched
cd /tmp/hh-worktrees/coupon-overlay
# ... agent edits files ...
git add -A && git commit -m "fix: coupon overlay safe-area"

# Merge back after verification
git checkout main && git merge --no-ff fix/ui-coupon-overlay

# Clean up (explicit remove, or .git/worktrees entries linger)
git worktree remove /tmp/hh-worktrees/coupon-overlay --force
git branch -d fix/ui-coupon-overlay

Notes: the third argument to git worktree add is the start commit; use HEAD to base on the latest code. --no-ff preserves a merge record for audit. worktree remove --force discards uncommitted changes, so clean up only after the agent commits. Multiple worktrees can coexist, which naturally supports validating three hypotheses in parallel.

Independent review: a second model adjudicates the evidence

After repair, hand the before/after screenshots and diff metrics to an independent reviewer model, not the fixer. The review input is structured:

json
{
  "task": "Mobile checkout coupon overlay button obscured",
  "evidence": {
    "before": "mobile-coupon-open.png",
    "after": "mobile-coupon-open-fixed.png",
    "diffRatio": 0.0134,
    "viewport": "390x844@3x"
  },
  "verdict": "pass | fail | needs-human"
}

The review prompt must constrain: judge only from the provided evidence; do not speculate about states not shown. If diffRatio is 0 but the task claims a visible fix, return fail. This step is the trust anchor of the loop — fixer and reviewer must be different contexts, otherwise the agent is grading its own homework.

Common Pitfalls and Diagnostics

Pitfall 1: size mismatch crashes the diff. Common on mobile when the address bar collapses and changes viewport height. Diagnose with identify -format '%wx%h' *.png (ImageMagick); fix by pinning page.setViewportSize before capture, or switch to fullPage: true and accept height variation.

Pitfall 2: font loading race. Web fonts are not loaded at capture time, fallback fonts cause whole-page text diff. Diagnose with await document.fonts.ready inside page.evaluate, or page.waitForFunction(() => document.fonts.status === 'loaded').

Pitfall 3: stale worktree locks. If the agent process is killed, .git/worktrees/<name>/locked remains and the next git worktree add fails with already registered. Diagnose with git worktree list --porcelain, clean with git worktree prune, or manually delete .git/worktrees/<name>.

Pitfall 4: pixel drift between CI and local. The same page can differ by 0.5% between macOS and Linux. Normalize with sharp before pixelmatch, or run capture inside a Docker image with pinned Chromium and font packages.

Pitfall 5: the agent edits the capture script itself. This is the most insidious cheat path — the agent raises threshold so the diff goes to zero. Defense: keep capture and diff scripts in a read-only directory, or check git diff --stat for harness files and fail immediately if touched.

Diagnostic commands:

bash
# List all worktrees and their branches
git worktree list --porcelain
# Clean stale worktree registrations
git worktree prune -v
# Check whether the agent tampered with the harness
git diff --name-only HEAD | grep -E '^(harness|scripts)/' && echo 'HARNESS TAMPERED'
# Batch-validate screenshot dimensions
for f in shots/*.png; do identify -format "%f %wx%h\n" "$f"; done

Production Acceptance Checklist

  • ☐ Viewport, DPR, locale, and timezone are all in config, never hardcoded in scripts.
  • ☐ Animation freezing is double-safeguarded (reducedMotion + animations: 'disabled').
  • ☐ document.fonts.ready wait is part of the capture flow.
  • ☐ Diff threshold and gate rule (ratio > 0.002) are centralized and unit-tested.
  • ☐ Every repair task uses its own git worktree; the main branch is unwritable until review passes.
  • ☐ Reviewer and fixer use different models/contexts; the review prompt forbids speculation.
  • ☐ Harness script directory is protected; agent tampering fails the task.
  • ☐ Cleanup covers worktree remove and branch -d; CI runs worktree prune on a schedule.
  • ☐ Screenshots and diff artifacts are archived to object storage for 30 days for audit.
  • ☐ Every "fixed" conclusion carries before/after screenshots and diffRatio; otherwise the ticket cannot close.

The value of this loop is not making the agent smarter — it is making its output falsifiable. When every repair must pass screenshot evidence and independent review, UI regression stops being a prayer and becomes engineering.

🧰 Free Zero-Upload Companion Utilities (Yevrix AI Browser-Local Suite)

While implementing this guide, use these free client-side utilities on Yevrix AI (https://ai.yevrix.com) — 100% in-browser execution, 0 bytes uploaded, no login required:

Utility (Yevrix AI) What It Solves Privacy & Cost Direct Link
EnvShield: Client-Side .ENV & Config Sanitizer for AI Prompts 100% browser-local privacy utility: redact API keys, JWTs, and database URLs before sharing logs with LLMs. Zero data leaves your browser. 0-Byte Upload · Free ($0) Open Tool →
AgentCron: Visual 24/7 Docker Compose & Resource Limit Generator Generate clean docker-compose.yml templates with restart policies, memory caps, and CPU quotas in seconds. 100% client-side. 0-Byte Upload · Free ($0) Open Tool →
User-Agent Parser, Browser Info & Random UA Generator Inspect your current browser specs, decode any User-Agent string into OS/Engine/Browser versions, or copy realistic UA presets. 0-Byte Upload · Free ($0) Open Tool →

🛠️ Companion Browser-Local Utilities

🚀 Next Steps & Self-Hostable Packs

Explore deeper open-source engineering breakdowns or grab the clean single-file Pro source pack.

PARTNER ECOSYSTEM

Recommended Cloud & AI Infrastructure

Hand-picked developer infrastructure we use to run 24/7 workflows. Partner links help keep all browser tools free.

📖 More Engineering Guides