← Commit history
Publish 0.1.0
6 files changed
+406
SKILL.mdadded+338@@ -0,0 +1,338 @@+---+name: app-testing+description: >+ Build and maintain a browser-driven end-to-end test suite for a web app that+ actually RENDERS the page in real Chrome, clicks every control, and fails on+ any page error — plus an interaction-coverage gate that fails when a NEW+ control ships without a test. Use when the user asks to test a web UI, add+ UI/E2E tests, "click through every button", verify every control works, catch+ UI regressions, set up Puppeteer/pup tests, or asks "why did the tests pass+ while the app was broken". Covers the harness (self-hosted server + seeded+ state + in-container Chrome), the page-error gate, the control-coverage+ manifest, viewport matrix, and the pitfalls that make UI tests lie.+ Trigger words: test the app, UI test, E2E test, end-to-end test, functional+ test, click every button, interaction coverage, coverage gate, puppeteer+ test, pup test, catch UI regression, headless chrome test, assert behavior+ not placement, control walk, test suite.+---++# app-testing — a browser-driven suite that clicks every control and can't lie++## What this is (and the vocabulary)++Driving the real rendered app, clicking every control, and asserting each does+its intended thing is **end-to-end (E2E) functional / UI-acceptance testing**.+The specific discipline of *systematically exercising every interactive+control* is **interaction-coverage testing**.++- The crude cousin — "click things at random and see if it crashes" — is+ **monkey / smoke testing**. Useful, cheap, shallow.+- What you want is the deterministic, assert-the-effect version: a fixed seeded+ state, every control reached on purpose, each effect checked.++The trap this skill exists to kill: **a test that reads the HTML file as a+string can go fully green while the app cannot render.** On the canonical+Session Monitor case a Python suite went 338/338 while the app could not open a+single card (a handler dereferenced an element a refactor had removed, and it+ran before the overlay was shown). No amount of string-matching `index.html`+catches that. **You must render the page in a real browser.**++## The two layers (build both)++1. **Flow tests** — open a screen, drive a specific journey, assert the+ *behavior* (card opens, message sends, list numbers 1·2·3, no horizontal+ overflow). This is where effects are verified.+2. **Coverage gate** — enumerate *every* control the app renders in *every*+ state and fail if any control isn't declared+tested. This is the inverse of+ a normal test: **a control you FORGET to test is what turns the suite red.**+ Ship a new button with no entry → red until someone accounts for it. Nothing+ reaches a user unverified.++Neither replaces the other. Flow tests prove intended effects; the gate proves+you didn't miss a control. Together they mean "every button verified to work as+intended."++The reference implementation is **`session-monitor/ui_test.mjs`** — read it as+the worked example; the pieces below map onto it directly.++## The non-negotiable GATE: fail on ANY page error++Every page you drive gets this, and it is the single most valuable line:++```js+const errors = [];+page.on('pageerror', e => errors.push(`pageerror: ${e.message}`));+page.on('console', m => { if (m.type() === 'error') errors.push(`console: ${m.text().slice(0,200)}`); });+// … the whole walk …+check('NO uncaught page errors during the walk', errors.length === 0, errors.slice(0,3).join(' | '));+```++A `pageerror` is an uncaught exception in the app. If your walk clicked the+control that throws, this catches it even when you forgot to assert the effect.+Where a state *legitimately* produces console errors (e.g. designed 403s), scope+the ignore narrowly — `!/status of 403/.test(t)` — never blanket-disable it.++## Harness recipe (self-contained, safe to run on every change)++The suite spawns its **own** server on a scratch port with **seeded,+deterministic state** — no live backend, no real side effects, no credentials+burned. From `ui_test.mjs`:++- **Chrome**: use the Puppeteer-managed Chrome, never the distro `chromium`+ (the container's is a dead snap stub). Discover the newest:+ ```js+ const glob = '/home/adom/.cache/puppeteer/chrome';+ const dirs = readdirSync(glob).filter(d => d.startsWith('linux-'))+ .sort((a,b) => parseInt(a.split('-')[1]) - parseInt(b.split('-')[1]));+ const CHROME = join(glob, dirs.at(-1), 'chrome-linux64', 'chrome');+ ```+ Launch with `headless:'new'`, `--no-sandbox --disable-gpu --disable-dev-shm-usage --hide-scrollbars`.+- **puppeteer-core** is vendored in-repo (`headless/node_modules/...`) — import+ the ESM entry directly; don't rely on a global install.+- **Server**: `spawn('python3', ['server.py'], { env })` where every state file+ path (`SM_*_FILE`) points into a fresh `mkdtempSync` dir, and a scratch+ `PORT`. Poll `/api/health` until it answers before driving.+- **Seed** via the app's own ingest endpoint (SM: `POST /api/keeper/report`)+ with a fixed fleet that covers **each card/screen state you need to render**+ — idle, held, asking-a-question, working, long-thread. Deterministic data =+ deterministic assertions.+- **Fakes for identity**: to render "signed in" or "pending approval" without a+ real account, serve a tiny fake identity endpoint on `127.0.0.1` and point+ `CARBON_API` at it (SM serves a fake Carbon giving back an email per bearer+ token). This lets you render auth-gated states honestly.+- **Cleanup** always: kill the server, close the fake, `rmSync` the temp dir+ (unless `--keep` for debugging screenshots).++## The coverage gate (the part most suites lack)++A flat **manifest** declares every control; a runtime pass enumerates what's+actually on screen and diffs. Each manifest entry:++```js+{ sel, label,+ required: false, // may legitimately be absent in the seeded state (conditional UI)+ safe: true, // non-destructive → the gate CLICKS it and asserts no page error+ terminal: true, // destructive/navigational → declared + presence only; effect covered by a flow test+ by: 'flow name' } // which flow test verifies this terminal control's effect+```++`sel` recognizes a live control four ways — `#id`, `.class`, `[onclick*="fn"]`,+or a bare `tag`:++```js+function ctrlMatches(c, sel) {+ if (sel.startsWith('#')) return c.id === sel.slice(1);+ if (sel.startsWith('.')) return c.cls.split(/\s+/).includes(sel.slice(1));+ if (sel.startsWith('[onclick')) { const m = sel.match(/\*="([^"]+)"/); return m && c.onclick.includes(m[1]); }+ return c.tag === sel;+}+```++Enumerate every **visible** control. Use `Element.checkVisibility` — it walks+**ancestors** (opacity, visibility, display, content-visibility), which a+naive `getComputedStyle(el)+rect` check does NOT:++```js+const vis = e => {+ if (e.checkVisibility && !e.checkVisibility({ checkOpacity:true, checkVisibilityCSS:true,+ opacityProperty:true, visibilityProperty:true })) return false;+ const r = e.getBoundingClientRect(); return r.width > 0 && r.height > 0;+};+const controls = [...document.querySelectorAll(+ 'button,[onclick],select,textarea,input:not([type=hidden]),[role="button"]')].filter(vis);+```++> Why `checkVisibility` matters: overlays that hide via `opacity:0`+> (not `display:none`) leave their buttons sized and "on screen" to a naive+> check, so closed-modal close buttons masquerade as visible board controls.+> `checkVisibility` sees the ancestor's `opacity:0` and correctly rejects them.++Then walk every **state** that reveals controls (board, each modal/overlay,+each distinct card kind), snapshot the live controls, and:++```js+const seen = new Set(), orphans = [];+for (const [name, open, reset] of STATES) {+ await open();+ for (const c of await liveControls(page)) {+ const hit = MANIFEST.find(d => ctrlMatches(c, d.sel));+ if (hit) seen.add(hit.sel);+ else orphans.push(`[${name}] <${c.tag} id="${c.id}" onclick="${c.onclick.slice(0,40)}">`);+ }+ if (reset) await reset();+}+check('every rendered control is declared (no orphan buttons)', orphans.length === 0, orphans.slice(0,6).join(' | '));+const missing = MANIFEST.filter(d => d.required !== false && !seen.has(d.sel)).map(d => d.sel);+check('every required control was present in some state', missing.length === 0, missing.join(', '));+```++- **Gate 1 — no orphans.** A live control matching no entry is an untested+ control → fail, and print its selector so the dev knows exactly what to add.+- **Gate 2 — no fiction.** Every `required` entry must actually render in some+ state, so the manifest can't rot into claims about controls that no longer+ exist.+- **Gate 3 — click every `safe` control**, assert no page error. Guard the+ click on `boundingBox()` (null when pointer-gated/`display:none`) so a+ legitimately-hidden control is skipped, not force-clicked into a throw.+- **Terminal controls** (close, send, sign-out, open-card, start) are declared+ and presence-checked here but effect-tested by the named `by:` flow — don't+ blindly click them mid-enumeration or you'll tear down the state you're+ walking.++Two shared collapses worth knowing: a close **button** and its tap-**scrim**+usually share `onclick="closeX()"`, so one `[onclick*="closeX"]` entry covers+both; and one `.fsbtn` entry covers the fullscreen button in every overlay.++## Viewport matrix++Render the states the users actually use, and emulate the input modality —+headless reports *no pointer*, so hover/pointer media queries never match and+pointer-gated affordances look broken:++```js+await page.emulateMediaFeatures(isMobile+ ? [{name:'any-hover',value:'none'}, {name:'any-pointer',value:'coarse'}]+ : [{name:'any-hover',value:'hover'},{name:'any-pointer',value:'fine'}]);+```++Test at least: a **real** phone CSS width (iPhone 15/16 is **393px**, not 402 —+the extra 9px is exactly where a `1fr`/`minmax(auto,1fr)` row silently pushed SM+into horizontal overflow on a real device), and a desktop width. Assert+**`document.documentElement.scrollWidth - clientWidth <= 0`** — the page must+never scroll sideways.++## Assert behavior, not placement++The recurring failure mode: a test checks that a string or element exists in the+file, a later refactor moves/renames it, and the test stays green while the+feature is dead. Rules:++- Assert the **effect**: after clicking send, the message bubble appears and the+ input clears — not "a `#vsend` element exists".+- Prefer computed geometry over hard-coded coordinates: "the card's top meets+ the header's bottom (`|v.top - h.bottom| <= 2`)", not "card top is 63px".+- When you assert an element was removed, also assert **no JS still references+ it** (a dangling `getElementById` that returns null and throws on+ `.classList`). The page-error gate backs this up.++## Pitfalls (each cost a red-herring debugging session)++- **Detached nodes.** Lists that repaint on a timer detach the handle you+ captured a moment ago (`Node is detached from document`). Re-query right+ before clicking and retry once — see `clickFresh()` in `ui_test.mjs`.+- **Opacity-hide vs display-hide.** Covered above — use `checkVisibility`.+- **Pointer-gated controls** are in the DOM but `display:none` in headless.+ `page.$` finds them; `page.click` throws. Guard on `boundingBox()`.+- **Token/identity context bleed.** Loading `?token=…` leaves the SPA+ authenticated as that owner. To render a *different* tenant, use a fresh+ `browser.createBrowserContext()` (incognito), not the same page.+- **Designed error noise.** A state that intentionally 403s makes Chrome log a+ console error per failed request; ignore *exactly* those, stay strict on the+ rest.+- **Autoplay/media.** If a control plays audio, launch with+ `--autoplay-policy=no-user-gesture-required` so the tap doesn't hang.++## Beyond functional: the test types that catch what clicks can't++Rendering + clicking covers the UI. Three more layers cover what the UI layer is+blind to. Add them as separate runnable suites, each exit-non-zero on failure.++### Integration / protocol e2e — run the REAL backend, stub only the outermost edge++The UI suite MOCKS the backend (it never actually drains a job / runs the real+worker), and the unit suite exercises server functions but never runs the worker+process. So a break in the actual **over-the-wire loop between two of your own+processes** slips through both — and that seam is where the nastiest "it looked+like it worked but nothing happened" bugs live (a job accepted, queued, and+silently never executed).++Close it by running your **real** processes against each other and stubbing only+the single outermost dependency you can't run in CI (the paid API, the physical+device, the third-party). The highest-leverage trick: **many tools already read+the path to that dependency from an env var** — point it at a fake.++> Worked example: Session Monitor's keeper shells out to `claude`, and it honours+> a `CLAUDE_BIN` override. `protocol_test.py` boots the real server AND the real+> keeper as subprocesses, sets `CLAUDE_BIN` to a 20-line fake that *writes a+> transcript* instead of calling Anthropic, then drives the real HTTP protocol:+> enqueue → the keeper drains it → runs the fake binary → reports back → the job's+> result appears in the fleet. Every line of the real loop runs; nothing is+> stubbed but the model itself. It's deterministic, needs no account or network,+> and it's the only layer that would have caught the "new session created but the+> card looked dead" bug end-to-end.++Pattern: temp `HOME`/state per run, a fake binary written to a tempfile and made+executable, both real processes launched with env pointing at each other, then+poll the public API for the expected end state (with a timeout). Assert the whole+chain: accepted → executed → reported → idempotent on a duplicate/replay.++### Performance + leak budgets — the functional suite runs too small to notice++Functional tests seed a handful of items, so they never surface an O(n²) render+or a slow leak that only an *unattended, long-running* client accumulates. Seed a+**big** fleet and budget it:++- **Render budget** — time one full re-render over N× the realistic item count;+ assert it stays under a ceiling (catches accidental quadratic work).+- **Leak watch** — the highest-value check for anything that polls. Capture+ `page.metrics()` (`JSHeapUsedSize`, `JSEventListeners`, `Nodes`), run ~40 repaint+ cycles, capture again. A handler re-added every poll or a detached subtree never+ GC'd shows as steady growth. Budget each: heap `< ~12MB`, **listeners `≈ +0`**+ (a per-poll `addEventListener` with no matching remove is the classic bug),+ nodes bounded. `+0 listeners over 40 repaints` is the signal you want.++### Visual-regression — assert the pixels, noise-tolerantly++Behavioural tests pass while a screen renders visibly broken (a collapsed layout,+a contrast/theme regression, an element off-screen). Diff each captured screenshot+against a committed **golden baseline** — but tolerantly, or timestamp drift and+anti-alias jitter make it flaky:++- Ignore per-channel deltas below a **noise floor** (~24/255), and fail only when+ more than a **gate %** of pixels changed (~2%). A drifting "3m ago" is a few+ hundred pixels (≪ gate); a real layout break is many thousands (≫ gate). Tuned+ right: cross-run jitter reads ~0.3%, a genuine regression ~3–4%.+- A **dimension change is always a fail** (that IS a layout regression), and a+ baseline image with **no current shot = a screen that stopped rendering**.+- Ship an `--update` mode to bless the current screens as the new golden set, and+ commit the baselines. Keep the per-run screenshots OUT of git (they regenerate+ every run) — track only `screenshots/baseline/`.+- Pillow + numpy is enough: `ratio = (abs(cur-base).max(axis=2) > NOISE).mean()*100`.++## Running++```bash+node ui_test.mjs # functional + coverage gate + perf/leak (mobile + desktop + auth states)+node ui_test.mjs --mobile # one viewport, fast inner-loop+node ui_test.mjs --keep # leave screenshots + temp state for debugging+python3 protocol_test.py # live real-worker <-> real-server e2e (fake outermost binary)+python3 e2e.py # backend API + unit (needs the server up)+node ui_test.mjs --keep && python3 visual_test.py # visual-regression vs golden+python3 visual_test.py --update # bless current screens as the new baseline+```++Exit non-zero on any failure so CI/precommit blocks. Per-run screenshots land in+`screenshots/ui-test/` (git-ignored, the fastest way to see what rendered);+golden baselines live in `screenshots/baseline/` (committed).++## Checklist for a new app's suite++- [ ] Spawn the app's own server on a scratch port, all state files in a temp dir.+- [ ] Seed deterministic state covering every screen/card kind you'll render.+- [ ] Real Chrome (Puppeteer-managed), `headless:'new'`, page-error gate on every page.+- [ ] Flow test per journey — assert **effects**, not element existence.+- [ ] Coverage manifest of every control; enumerate with `checkVisibility`;+ fail on orphans and on missing required controls.+- [ ] Click every `safe` control (guard on `boundingBox`), assert no page error.+- [ ] Terminal controls declared with a `by:` pointing at the flow that proves them.+- [ ] Viewport matrix incl. a real phone width; assert zero horizontal overflow.+- [ ] Emulate hover/pointer media features per viewport.+- [ ] Always clean up (kill server, close fakes, rm temp) unless `--keep`.+- [ ] **Integration/protocol e2e**: run your real processes against each other,+ stub only the outermost dependency (fake binary via its path env var);+ assert accepted → executed → reported → idempotent on replay.+- [ ] **Perf/leak**: seed a big fleet; budget one full render; watch+ heap/listeners/nodes across ~40 repaints (listeners ≈ +0).+- [ ] **Visual-regression**: diff screens vs committed golden baselines with a+ noise floor + gate %; dimension change / missing screen = fail; `--update`+ to re-bless; per-run shots git-ignored, baselines committed.
docs/HERO.mdadded+8@@ -0,0 +1,8 @@+Generate `hero.png` for this folder in Hero Studio. It is the page-header image, reused on the homepage and the screensaver; the page overlays live stats on its lower third, so the image carries the title and artwork only.++New app/skill heroes MUST come from Hero Studio (the server rejects anything else with HERO_STUDIO_REQUIRED; the studio stamps provenance into the PNG and exports at 2000x1250):++1. `adom-wiki pkg install adom/hero-studio`+2. start it (`hero-studio`, port 8846) and open the webview so the human sees it+3. pose the hero (the UI, or POST /state), then Generate+4. copy `generated/latest.png` here as `docs/hero.png`
docs/hero.pngadded⋯ 1 unchanged line ⋯
install.shadded+7@@ -0,0 +1,7 @@+#!/bin/sh+set -e++# Symlink your install targets back into the module dir so edits+# propagate and reinstalls do not clobber, e.g.:+# ln -sfn "$PWD/bin/run" "$HOME/.local/bin/run"+echo "installed"
package.jsonadded+48@@ -0,0 +1,48 @@+{+ "slug": "app-testing",+ "title": "App Testing",+ "type": "skill",+ "version": "0.1.0",+ "description": "Build a browser-driven end-to-end test suite that RENDERS your web app in real Chrome, clicks every control, fails on any page error, and gates on interaction coverage so a new untested button turns the suite red.",+ "tags": [+ "skill",+ "testing",+ "e2e",+ "puppeteer",+ "ui",+ "coverage",+ "quality"+ ],+ "dependencies": {},+ "discovery_triggers": [+ "test my web app",+ "add UI tests",+ "click through every button",+ "why did the tests pass while the app was broken",+ "set up puppeteer tests",+ "catch UI regressions",+ "end-to-end test my UI"+ ],+ "discovery_pitch": "Reach for this to build UI tests that actually render the app and can't go green while it's broken \u2014 plus a coverage gate that fails when a control ships untested.",+ "sample_prompts": [+ {+ "label": "Add a suite",+ "prompt": "Add an end-to-end test suite that clicks through every control in my web app"+ },+ {+ "label": "Coverage gate",+ "prompt": "Make the tests fail if I add a button with no test for it"+ },+ {+ "label": "Diagnose",+ "prompt": "My tests are green but the app is broken \u2014 why, and how do I catch it?"+ }+ ],+ "scripts": {+ "install": "./install.sh",+ "uninstall": "./uninstall.sh"+ },+ "hero": {+ "path": "docs/hero.png"+ }+}
uninstall.shadded+5@@ -0,0 +1,5 @@+#!/bin/sh+set -e++# Undo what install.sh did (remove the symlinks you created).+echo "uninstalled"