diff --git a/.github/workflows/frontend-ci.yml b/.github/workflows/frontend-ci.yml index e186b433..62c4f71b 100644 --- a/.github/workflows/frontend-ci.yml +++ b/.github/workflows/frontend-ci.yml @@ -89,6 +89,9 @@ jobs: - name: Assistant deployment browser regressions working-directory: frontend run: npm run test:ai-operations + - name: Layout screenshot regressions + working-directory: frontend + run: npm run test:layout - name: Upload Settings screenshots if: always() uses: actions/upload-artifact@v7 diff --git a/.gitignore b/.gitignore index e2e4800f..34077ef3 100644 --- a/.gitignore +++ b/.gitignore @@ -132,6 +132,10 @@ SECURITY_AND_CODE_AUDIT.md !/docs/screenshots/ !/docs/screenshots/*.png +# Layout screenshot baselines compared by `npm run test:layout`. +!/frontend/tests/layout-baselines/ +!/frontend/tests/layout-baselines/*.png + # Video walkthrough thumbnails linked from the README. !/docs/videos/*.png diff --git a/frontend/README.md b/frontend/README.md index 6932d11b..570d311b 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -86,6 +86,14 @@ VITE_API_URL=https://api.example.com Access them in code via `import.meta.env.VITE_API_URL`. +## Layout screenshot regressions + +`npm run test:layout` renders the main pages at 390, 768 and 1440 px from synthetic +fixtures and compares them with `tests/layout-baselines/`. After an intended UI +change run `LAYOUT_UPDATE=1 npm run test:layout` and commit the new PNGs; failures +leave actual/diff images in `test-results/layout/`. See the header of +`scripts/layout-screenshots-browser.mjs` for the options. + ## Contributing See the documentation files for AI agent permissions and guidelines. diff --git a/frontend/package.json b/frontend/package.json index 0a976641..dbf34cc8 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -11,6 +11,7 @@ "test:settings-ui": "node scripts/settings-ui-browser.mjs", "lint": "node scripts/lint.mjs && node scripts/check-font-integrity.mjs && node scripts/check-settings-index.mjs && node scripts/check-theme-tokens.mjs && node scripts/check-frontend-boundaries.mjs && node scripts/check-style-ownership.mjs && node scripts/check-status-one-door.mjs && node scripts/check-shared-fields.mjs && node scripts/check-tables.mjs && node scripts/check-type-scale.mjs && node scripts/check-geometry.mjs && node scripts/check-status-scss.mjs && node scripts/check-i18n-literals.mjs && node scripts/check-intl-door.mjs && node scripts/extract-i18n.mjs --check && node scripts/check-i18n.mjs && node scripts/check-logical-properties.mjs && node scripts/generate-vendor-shims.mjs --check && node ../scripts/check-html-sinks.mjs && node scripts/check-orphan-files.mjs && node scripts/check-label-association.mjs", "lint:baseline": "node scripts/lint.mjs --update", + "test:layout": "node scripts/layout-screenshots-browser.mjs", "test:controls": "node scripts/controls-browser.mjs", "test:metrics": "node scripts/metrics-browser.mjs", "measure:build": "node scripts/measure-build.mjs", diff --git a/frontend/scripts/layout-fixtures.mjs b/frontend/scripts/layout-fixtures.mjs new file mode 100644 index 00000000..177c4599 --- /dev/null +++ b/frontend/scripts/layout-fixtures.mjs @@ -0,0 +1,37 @@ +// Synthetic API responses for layout-screenshots-browser.mjs. example.test data only. +const T = '2026-01-14T09:30:00Z'; +const user = { id: 1, username: 'operator', email: 'operator@example.test', role: 'admin', is_active: true, auth_provider: 'local', permissions: {}, created_at: T, totp_enabled: false }; +const servers = [ + { id: 'srv-1', name: 'web-01.example.test', hostname: 'web-01.example.test', ip_address: '192.0.2.10', status: 'online', is_local: true, os_type: 'linux', os_version: 'Ubuntu 24.04', agent_version: '1.0.0', permission_level_effective: 'standard', created_at: T, last_seen: T }, + { id: 'srv-2', name: 'db-01.example.test', hostname: 'db-01.example.test', ip_address: '192.0.2.11', status: 'offline', os_type: 'linux', os_version: 'Debian 12', agent_version: '1.0.0', permission_level_effective: 'standard', created_at: T, last_seen: T }, +]; +const apps = [ + { id: 1, name: 'blog', domains: ['blog.example.test'], status: 'running', app_type: 'docker', stack: 'node', created_at: T, updated_at: T }, + { id: 2, name: 'shop', domains: ['shop.example.test'], status: 'stopped', app_type: 'php', stack: 'php', created_at: T, updated_at: T }, +]; +const notifications = [ + { delivery_id: 1, title: 'Backup completed', body: 'Nightly backup finished for blog.example.test', severity: 'info', category: 'backup', read: false, is_read: false, created_at: T }, + { delivery_id: 2, title: 'Certificate expiring', body: 'shop.example.test expires in 12 days', severity: 'warning', category: 'ssl', read: true, is_read: true, created_at: T }, +]; +const certificates = [ + { domain: 'blog.example.test', issuer: "Let's Encrypt", status: 'valid', days_remaining: 62, expires_at: '2026-03-18T00:00:00Z', auto_renew: true }, + { domain: 'shop.example.test', issuer: "Let's Encrypt", status: 'expiring', days_remaining: 12, expires_at: '2026-01-27T00:00:00Z', auto_renew: false }, +]; + +// Longest-prefix-free rules, first match wins. Anything else answers `{}`. +const RULES = [ + [/^\/auth\/setup-status/, { needs_setup: false, registration_enabled: false }], + [/^\/auth\/me/, { user }], + [/^\/plugins\/contributions/, { contributions: [], routes: [], items: [] }], + [/^\/servers\/groups/, []], + [/^\/servers\/?$/, servers], + [/^\/servers\/available/, { servers }], + [/^\/(apps|services)/, { apps, services: apps, total: apps.length }], + [/^\/notifications/, { notifications, items: notifications, unread_count: 1, total: 2 }], + [/^\/ssl/, { certificates, items: certificates }], + [/^\/queues?/, { groups: [], queues: [] }], +]; + +export function fixtureFor(path) { + return RULES.find(([re]) => re.test(path))?.[1]; +} diff --git a/frontend/scripts/layout-screenshots-browser.mjs b/frontend/scripts/layout-screenshots-browser.mjs new file mode 100644 index 00000000..433d15ac --- /dev/null +++ b/frontend/scripts/layout-screenshots-browser.mjs @@ -0,0 +1,180 @@ +/** + * Layout screenshot regressions: main pages at phone (390x844), tablet + * (768x1024) and desktop (1440x900), rendered from synthetic API fixtures + * (no backend, no network), compared with committed baselines. + * + * Per snapshot it asserts: no page-level horizontal scroll, no visible control + * clipped by the viewport edge (outside intentional overflow-x scrollers), the + * page header is present and there is no uncaught page error. Then it diffs the + * viewport screenshot against tests/layout-baselines/-[-light].png + * (per-channel tolerance, fails above LAYOUT_DIFF_RATIO of pixels differing). + * A pixel only counts as different if it mismatches the baseline at the same + * position AND no pixel within 1px in the other image matches it, checked in + * both directions (like pixelmatch's AA detection): text anti-aliasing/hinting + * differences between machines pass, moved or resized boxes still fail. + * Chromium is launched with fixed font-rendering flags to keep text stable. + * + * npm run test:layout # check + * LAYOUT_UPDATE=1 npm run test:layout # rewrite baselines + * LAYOUT_ONLY=dashboard,ssl npm run test:layout + * LAYOUT_DIFF_RATIO=0.01 npm run test:layout + * + * A missing baseline is created locally and fails under CI. On a diff, the + * actual and diff (magenta) images land in test-results/layout/. Diffs appear + * when layout/CSS changes (update the baselines in the same commit if intended) + * or when fonts/rendering differ from the machine that made the baselines; + * regenerate with the Playwright chromium that CI installs. + */ +import { createServer } from 'vite'; +import { chromium } from 'playwright'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { existsSync } from 'node:fs'; +import { fixtureFor } from './layout-fixtures.mjs'; + +const DIFF_RATIO = Number(process.env.LAYOUT_DIFF_RATIO ?? 0.002); +const TOLERANCE = 24; +const LAUNCH_ARGS = ['--font-render-hinting=none', '--disable-font-subpixel-positioning', '--disable-lcd-text', '--force-color-profile=srgb']; +const OUT = 'test-results/layout'; +const BASE_DIR = 'tests/layout-baselines'; +const NOW = '2026-01-15T12:00:00Z'; +const WIDTHS = { 390: 844, 768: 1024, 1440: 900 }; +const PAGES = [ + { key: 'dashboard', path: '/' }, + { key: 'servers', path: '/servers' }, + { key: 'services', path: '/services' }, + { key: 'monitoring', path: '/monitoring' }, + { key: 'notifications', path: '/notifications' }, + { key: 'settings', path: '/settings/general' }, + { key: 'ssl', path: '/ssl' }, + { key: 'queue', path: '/queue' }, +]; +const only = (process.env.LAYOUT_ONLY || '').split(',').filter(Boolean); +const jobs = []; +for (const p of PAGES) { + if (only.length && !only.includes(p.key)) continue; + for (const w of Object.keys(WIDTHS)) jobs.push({ ...p, width: Number(w), theme: 'dark' }); +} +if (!only.length || only.includes('dashboard')) jobs.push({ ...PAGES[0], width: 1440, theme: 'light' }); + +const FREEZE_CSS = `*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important;scroll-behavior:auto!important}`; + +// Runs inside the page: loads both PNGs into canvases and counts differing pixels. +const diffInPage = async ({ a, b, tol }) => { + const load = (src) => new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = src; }); + const [ia, ib] = await Promise.all([load(a), load(b)]); + if (ia.width !== ib.width || ia.height !== ib.height) return { size: false }; + const read = (img) => { const c = document.createElement('canvas'); c.width = img.width; c.height = img.height; const x = c.getContext('2d'); x.drawImage(img, 0, 0); return x.getImageData(0, 0, c.width, c.height); }; + const da = read(ia); const db = read(ib); + const out = new ImageData(ia.width, ia.height); + const { width: W, height: H } = ia; + const near = (x, y, i, o) => Math.abs(x[i] - y[o]) <= tol && Math.abs(x[i + 1] - y[o + 1]) <= tol && Math.abs(x[i + 2] - y[o + 2]) <= tol; + // true if any pixel of `d` within 1px of (px,py) matches pixel i of `s` (AA shifts glyph edges by <=1px) + const matchesAround = (s, d, i, px, py) => { + for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) { + const x = px + dx; const y = py + dy; + if (x >= 0 && y >= 0 && x < W && y < H && near(s, d, i, (y * W + x) * 4)) return true; + } + return false; + }; + let count = 0; + for (let i = 0; i < da.data.length; i += 4) { + const px = (i / 4) % W; const py = Math.floor(i / 4 / W); + const bad = !near(da.data, db.data, i, i) && !matchesAround(da.data, db.data, i, px, py) && !matchesAround(db.data, da.data, i, px, py); + if (bad) { count++; out.data.set([255, 0, 255, 255], i); } else out.data.set([db.data[i], db.data[i + 1], db.data[i + 2], 80], i); + } + const c = document.createElement('canvas'); c.width = ia.width; c.height = ia.height; c.getContext('2d').putImageData(out, 0, 0); + return { size: true, count, total: ia.width * ia.height, diff: c.toDataURL('image/png') }; +}; + +// Runs inside the page: layout invariants; returns a list of problems. +const invariants = () => { + const problems = []; + const root = document.documentElement; + if (root.scrollWidth > root.clientWidth + 1) problems.push(`page scrolls horizontally (${root.scrollWidth} > ${root.clientWidth})`); + if (!document.querySelector('header, [role=banner], .page-header, .topbar, .header')) problems.push('page header/topbar missing'); + const inScroller = (el) => { for (let p = el.parentElement; p && p !== document.body; p = p.parentElement) { if (/(auto|scroll)/.test(getComputedStyle(p).overflowX) && p.scrollWidth > p.clientWidth) return true; } return false; }; + for (const el of document.querySelectorAll('button, a, input, select, [role=button]')) { + const r = el.getBoundingClientRect(); const s = getComputedStyle(el); + if (!r.width || !r.height || s.visibility === 'hidden' || s.display === 'none' || el.closest('[hidden],[aria-hidden=true],[inert]')) continue; + if ((r.left < -1 || r.right > root.clientWidth + 1) && !inScroller(el)) { + problems.push(`control clipped horizontally: <${el.tagName.toLowerCase()}> "${(el.getAttribute('aria-label') || el.textContent || '').trim().slice(0, 40)}" [${Math.round(r.left)}..${Math.round(r.right)}]`); + if (problems.length > 8) break; + } + } + return problems; +}; + +const server = await createServer({ server: { host: '127.0.0.1', port: 0, strictPort: false, open: false } }); +let browser; +const failures = []; +const started = Date.now(); +try { + await server.listen(); + const base = server.resolvedUrls.local[0]; + const origin = new URL(base).origin; + browser = await chromium.launch({ headless: true, args: LAUNCH_ARGS }); + await mkdir(OUT, { recursive: true }); + await mkdir(BASE_DIR, { recursive: true }); + const diffPage = await browser.newPage(); + for (const job of jobs) { + const name = `${job.key}-${job.width}${job.theme === 'light' ? '-light' : ''}`; + const context = await browser.newContext({ + viewport: { width: job.width, height: WIDTHS[job.width] }, locale: 'en-US', timezoneId: 'UTC', + reducedMotion: 'reduce', colorScheme: job.theme, deviceScaleFactor: 1, + }); + await context.addInitScript((theme) => { + localStorage.setItem('access_token', 'synthetic-browser-fixture'); + localStorage.setItem('theme', theme); + document.addEventListener('DOMContentLoaded', () => document.documentElement.setAttribute('data-theme', theme), { once: true }); + }, job.theme); + const page = await context.newPage(); + await page.clock.install({ time: new Date(NOW) }); + const errors = []; + page.on('pageerror', (e) => errors.push(e.message)); + await page.routeWebSocket(/socket\.io/, (ws) => ws.close()); + await page.route('**/*', (route) => { + const url = new URL(route.request().url()); + // .env may point the API at a local backend port; serve that from fixtures too + const local = ['localhost', '127.0.0.1'].includes(url.hostname); + if (!local || (url.origin !== origin && !url.pathname.startsWith('/api/v1/'))) { if (process.env.LAYOUT_DEBUG) console.log(' abort', url.href); return route.abort(); } + if (url.pathname.startsWith('/socket.io/')) return route.abort(); // no live socket: keeps data static + if (!url.pathname.startsWith('/api/v1/')) return route.continue(); + const body = fixtureFor(url.pathname.slice('/api/v1'.length), route.request().method()); + if (process.env.LAYOUT_DEBUG) console.log(` api ${name} ${url.pathname}${body === undefined ? ' (unhandled)' : ''}`); + return route.fulfill({ json: body ?? {} }); + }); + await page.goto(`${base.replace(/\/$/, '')}${job.path}`, { waitUntil: 'networkidle' }); + await page.addStyleTag({ content: FREEZE_CSS }); + await page.evaluate(() => document.fonts.ready); + await page.clock.runFor(1000); + await page.waitForLoadState('networkidle'); + await page.waitForFunction(() => !document.querySelector('[class*=skeleton], [aria-busy=true], [role=progressbar], .spinner, .loading'), null, { timeout: 10000 }).catch(async () => { if (process.env.LAYOUT_DEBUG) console.log(' busy:', await page.evaluate(() => [...document.querySelectorAll('[class*=skeleton], [aria-busy=true], [role=progressbar], .spinner, .loading')].map((e) => e.className).join(' | '))); }); + const problems = await page.evaluate(invariants); + errors.forEach((e) => problems.push(`uncaught page error: ${e}`)); + const shot = await page.screenshot({ animations: 'disabled', caret: 'hide' }); + await context.close(); + + const file = `${BASE_DIR}/${name}.png`; + if (process.env.LAYOUT_UPDATE || !existsSync(file)) { + if (!process.env.LAYOUT_UPDATE && process.env.CI) problems.push(`baseline ${file} is missing (run LAYOUT_UPDATE=1 npm run test:layout and commit it)`); + else await writeFile(file, shot); + } else { + const res = await diffPage.evaluate(diffInPage, { a: `data:image/png;base64,${shot.toString('base64')}`, b: `data:image/png;base64,${(await readFile(file)).toString('base64')}`, tol: TOLERANCE }); + if (!res.size || res.count / res.total > DIFF_RATIO) { + await writeFile(`${OUT}/${name}.actual.png`, shot); + if (res.size) await writeFile(`${OUT}/${name}.diff.png`, Buffer.from(res.diff.split(',')[1], 'base64')); + problems.push(res.size ? `pixel diff ${(100 * res.count / res.total).toFixed(2)}% > ${(100 * DIFF_RATIO).toFixed(2)}% (see ${OUT}/${name}.diff.png)` : 'screenshot size differs from baseline'); + } + } + for (const p of problems) failures.push(`${job.key}@${job.width}${job.theme === 'light' ? ' (light)' : ''}: ${p}`); + console.log(`${problems.length ? 'FAIL' : 'ok '} ${name}`); + } +} finally { + await browser?.close(); + await server.close(); +} +console.log(`${jobs.length} snapshots in ${((Date.now() - started) / 1000).toFixed(1)}s`); +if (failures.length) { + console.error(`\nLayout regressions:\n - ${failures.join('\n - ')}`); + process.exitCode = 1; +} diff --git a/frontend/tests/layout-baselines/dashboard-1440-light.png b/frontend/tests/layout-baselines/dashboard-1440-light.png new file mode 100644 index 00000000..c7eededd Binary files /dev/null and b/frontend/tests/layout-baselines/dashboard-1440-light.png differ diff --git a/frontend/tests/layout-baselines/dashboard-1440.png b/frontend/tests/layout-baselines/dashboard-1440.png new file mode 100644 index 00000000..3a4ec623 Binary files /dev/null and b/frontend/tests/layout-baselines/dashboard-1440.png differ diff --git a/frontend/tests/layout-baselines/dashboard-390.png b/frontend/tests/layout-baselines/dashboard-390.png new file mode 100644 index 00000000..3e49869b Binary files /dev/null and b/frontend/tests/layout-baselines/dashboard-390.png differ diff --git a/frontend/tests/layout-baselines/dashboard-768.png b/frontend/tests/layout-baselines/dashboard-768.png new file mode 100644 index 00000000..a9b82455 Binary files /dev/null and b/frontend/tests/layout-baselines/dashboard-768.png differ diff --git a/frontend/tests/layout-baselines/monitoring-1440.png b/frontend/tests/layout-baselines/monitoring-1440.png new file mode 100644 index 00000000..6da9022d Binary files /dev/null and b/frontend/tests/layout-baselines/monitoring-1440.png differ diff --git a/frontend/tests/layout-baselines/monitoring-390.png b/frontend/tests/layout-baselines/monitoring-390.png new file mode 100644 index 00000000..a9b6f311 Binary files /dev/null and b/frontend/tests/layout-baselines/monitoring-390.png differ diff --git a/frontend/tests/layout-baselines/monitoring-768.png b/frontend/tests/layout-baselines/monitoring-768.png new file mode 100644 index 00000000..5517fa2f Binary files /dev/null and b/frontend/tests/layout-baselines/monitoring-768.png differ diff --git a/frontend/tests/layout-baselines/notifications-1440.png b/frontend/tests/layout-baselines/notifications-1440.png new file mode 100644 index 00000000..d4e6835d Binary files /dev/null and b/frontend/tests/layout-baselines/notifications-1440.png differ diff --git a/frontend/tests/layout-baselines/notifications-390.png b/frontend/tests/layout-baselines/notifications-390.png new file mode 100644 index 00000000..e73dd12a Binary files /dev/null and b/frontend/tests/layout-baselines/notifications-390.png differ diff --git a/frontend/tests/layout-baselines/notifications-768.png b/frontend/tests/layout-baselines/notifications-768.png new file mode 100644 index 00000000..c327907a Binary files /dev/null and b/frontend/tests/layout-baselines/notifications-768.png differ diff --git a/frontend/tests/layout-baselines/queue-1440.png b/frontend/tests/layout-baselines/queue-1440.png new file mode 100644 index 00000000..2c80c244 Binary files /dev/null and b/frontend/tests/layout-baselines/queue-1440.png differ diff --git a/frontend/tests/layout-baselines/queue-390.png b/frontend/tests/layout-baselines/queue-390.png new file mode 100644 index 00000000..a7c77be2 Binary files /dev/null and b/frontend/tests/layout-baselines/queue-390.png differ diff --git a/frontend/tests/layout-baselines/queue-768.png b/frontend/tests/layout-baselines/queue-768.png new file mode 100644 index 00000000..18c671f0 Binary files /dev/null and b/frontend/tests/layout-baselines/queue-768.png differ diff --git a/frontend/tests/layout-baselines/servers-1440.png b/frontend/tests/layout-baselines/servers-1440.png new file mode 100644 index 00000000..b13c8b2c Binary files /dev/null and b/frontend/tests/layout-baselines/servers-1440.png differ diff --git a/frontend/tests/layout-baselines/servers-390.png b/frontend/tests/layout-baselines/servers-390.png new file mode 100644 index 00000000..46d59f3d Binary files /dev/null and b/frontend/tests/layout-baselines/servers-390.png differ diff --git a/frontend/tests/layout-baselines/servers-768.png b/frontend/tests/layout-baselines/servers-768.png new file mode 100644 index 00000000..b51437bc Binary files /dev/null and b/frontend/tests/layout-baselines/servers-768.png differ diff --git a/frontend/tests/layout-baselines/services-1440.png b/frontend/tests/layout-baselines/services-1440.png new file mode 100644 index 00000000..c6389edd Binary files /dev/null and b/frontend/tests/layout-baselines/services-1440.png differ diff --git a/frontend/tests/layout-baselines/services-390.png b/frontend/tests/layout-baselines/services-390.png new file mode 100644 index 00000000..1cdeba00 Binary files /dev/null and b/frontend/tests/layout-baselines/services-390.png differ diff --git a/frontend/tests/layout-baselines/services-768.png b/frontend/tests/layout-baselines/services-768.png new file mode 100644 index 00000000..14b910d1 Binary files /dev/null and b/frontend/tests/layout-baselines/services-768.png differ diff --git a/frontend/tests/layout-baselines/settings-1440.png b/frontend/tests/layout-baselines/settings-1440.png new file mode 100644 index 00000000..af599e23 Binary files /dev/null and b/frontend/tests/layout-baselines/settings-1440.png differ diff --git a/frontend/tests/layout-baselines/settings-390.png b/frontend/tests/layout-baselines/settings-390.png new file mode 100644 index 00000000..a8de8397 Binary files /dev/null and b/frontend/tests/layout-baselines/settings-390.png differ diff --git a/frontend/tests/layout-baselines/settings-768.png b/frontend/tests/layout-baselines/settings-768.png new file mode 100644 index 00000000..37c04e64 Binary files /dev/null and b/frontend/tests/layout-baselines/settings-768.png differ diff --git a/frontend/tests/layout-baselines/ssl-1440.png b/frontend/tests/layout-baselines/ssl-1440.png new file mode 100644 index 00000000..a6a1f936 Binary files /dev/null and b/frontend/tests/layout-baselines/ssl-1440.png differ diff --git a/frontend/tests/layout-baselines/ssl-390.png b/frontend/tests/layout-baselines/ssl-390.png new file mode 100644 index 00000000..16997a29 Binary files /dev/null and b/frontend/tests/layout-baselines/ssl-390.png differ diff --git a/frontend/tests/layout-baselines/ssl-768.png b/frontend/tests/layout-baselines/ssl-768.png new file mode 100644 index 00000000..97e1e9dd Binary files /dev/null and b/frontend/tests/layout-baselines/ssl-768.png differ