hwatu
AGENTS.md121 starsChanged 38 days agoMITView on GitHub
hwatu is a headless browser driven through a CLI and MCP. Scope and constraints are in VISION.md. Plan of record: roadmap. Skills are not part of this project. A skill is a plain-text SKILL.md that the agent harness stores, discovers, and loads. A skill that uses this browser contains hwatu commands. - On Linux, opening a window takes 13 to 16 ms from a warm daemon (benchmarks). Other platforms are not yet measured. - N windows share one engine network…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 33,398 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repositoryOne other file it gives its agents.
- llms.txtllms.txt
The file
We split this agents.md into the rules it gives an agent
9 rules. About 0 are common, 3 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 136
When id is omitted, commands target the focused window, else the window your last automation command targeted (including open), else the …
- Distinctive: line 139
Only genuine ambiguity (several windows, none focused, none driven yet) is an error: an agent driving the wrong window is worse than a …
- Very specific: line 178
If the agent cannot clear the challenge, challenge returns a structured block and the session is kept.
- Very specific: line 237
If the page navigates while the script runs (a click handler that follows a link, location =, form submit), the document's JS context is …
- Very specific: line 320
Every window buffers, from document start: console.* calls, uncaught exceptions, unhandled promise rejections, failed resource loads, and …
- Very specific: line 420
Every fit carries fit_r2; treat entries below ~0.9 as "something moved" rather than a law of motion.
- Very specific: line 472
Use hwatu verify when the verification contract also needs to own a preflight gate, local server lifecycle, responsive viewport sweep, …
- Distinctive: line 585
Every state-changing action needs a post-action assertion.
- Distinctive: line 673
Add a block like this to AGENTS.md or CLAUDE.md:
≈ “Common” is an estimate: at least 1 in 5 of the 43,423 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
hwatu for coding agents
hwatu is a headless browser driven through a CLI and MCP. Scope and constraints are in VISION.md. Plan of record: roadmap.
Skills are not part of this project. A skill is a plain-text SKILL.md that
the agent harness stores, discovers, and loads. A skill that uses this
browser contains hwatu commands.
Properties
- On Linux, opening a window takes 13 to 16 ms from a warm daemon (benchmarks). Other platforms are not yet measured.
- N windows share one engine network process. One binary plus the OS web engine. No Node, no browser download.
- Rendering is the OS engine: WebKitGTK on Linux, WKWebView on macOS.
- Windows are headless. They are never mapped unless
showis requested. - The protocol is newline-delimited JSON over a Unix socket (Linux, macOS), a named pipe (Windows), or authenticated loopback TCP.
Commands by kind
| Kind | Commands |
| act | goto, click, type, fill, scroll, upload |
| observe | snapshot, content, eval, shot, console, net |
| assert | expect, diff, motion |
| human | show, structured stops |
Other commands: clone copies a live page and reports pixel match, seek
pins animations at time t, render --stdin renders generated HTML without a
server, challenge detects CAPTCHA and anti-bot pages, resize sets the
viewport, batch runs a sequence in one call. Ambiguity is an error with a
match count. Refs from snapshot are live element handles and stale refs
return an error.
The protocol
Socket: $XDG_RUNTIME_DIR/hwatu.sock (fallback
/tmp/hwatu-$UID.sock). One request per connection: connect, write
one JSON line, read one JSON line, disconnect.
printf '{"cmd":"open","url":"http://localhost:3000","mode":"headless"}\n' \
| socat - UNIX-CONNECT:$XDG_RUNTIME_DIR/hwatu.sockOr use the CLI, which is the same protocol with argv parsing:
hwatu --headless localhost:3000 # open without a window (returns id)
hwatu check localhost:3000 --eval 'document.title' --shot=/tmp/c.png
# one-shot: open+wait+eval+shot+close
hwatu wait-load # block until the load settles
hwatu wait-load --until dom # release at DOMContentLoaded (faster)
hwatu wait-load --until quiescent # settled + DOM stopped mutating (SPA hydration done)
hwatu snapshot # text + interactables, cheaper than a shot
hwatu expect '#status' --text ready # assert page state (polls up to 5s)
hwatu expect '#status' --text ready --watch # stream initial state + truth flips until navigation
hwatu eval 'document.title' # id-less: follows the window you opened
hwatu click a --contains "Sign in" # real pointer-event click
hwatu click --ref 4 # click interactable #4 from the snapshot
hwatu type 'input[name=q]' hi --enter # fill and submit
hwatu console # console.*, exceptions, failed requests
hwatu challenge # detect CAPTCHA / anti-bot UI, as JSON
hwatu challenge --wait --timeout-ms 30000 # wait while the user clears it
hwatu shot /tmp/check.png # PNG of the rendered viewport
hwatu shot --full /tmp/page.png # PNG of the whole document
hwatu scroll h2 --contains Pricing # scroll into view, reports what it hit
hwatu goto --id 3 /settings # navigate, waits by default
hwatu upload --id 3 'input[type=file]' ./avatar.png
hwatu show 3 # render for the user
hwatu close 3Remote client over SSH
hwatud can additionally expose authenticated TCP on loopback for an SSH
tunnel. It never binds a non-loopback address. Create a private bearer-token
file on the daemon host and start the opt-in listener:
install -d -m 700 ~/.config/hwatu
umask 077
openssl rand -hex 32 > ~/.config/hwatu/tcp-token
hwatud --listen 8741 --token-file ~/.config/hwatu/tcp-tokenForward that loopback port from the client host, place the same token in a
mode-0600 file there, and point hwatu at the tunnel:
ssh -N -L 8741:127.0.0.1:8741 browser-host
HWATU_ENDPOINT=tcp://127.0.0.1:8741 \
HWATU_TOKEN_FILE=~/.config/hwatu/tcp-token \
hwatu check localhost:3000 --shot=check.pngThe CLI transparently transfers upload and baseline inputs inline and writes
returned screenshots or heatmaps on the client host. Each decoded inline
artifact is capped at 16 MiB. A response may contain one inline screenshot or
heatmap: request both separately, request multi-viewport screenshots one
viewport at a time, and include at most one artifact-producing action in a
batch. Unix-socket behavior and HWATU_SOCKET remain unchanged;
HWATU_ENDPOINT takes precedence when set.
Requests
| cmd | fields | what it does |
open | url?, app_id?, mode? | new window; mode is headless (default) |
list | all windows: id, url, title, focused, suspended, mode | |
close | id | close a window |
show | id | render the live session as a visible window; hide returns it to headless. focus and unfocus are aliases |
eval | id?, js, timeout_ms? | run JS, result as JSON |
navigate | id?, url, wait?, timeout_ms? | navigate, optionally wait for the load |
screenshot | id?, path?, full? | PNG of the viewport (full: true = whole document), returns the file path |
wait_load | id?, until?, timeout_ms? | block until the load reaches until (committed/dom/settled/quiescent; quiescent = settled, then no DOM mutations for 300 ms, 5 s cap, so SPA hydration is done) |
check | url or render (+base?), eval?, shot?, shot_path?, full?, baseline?, tolerance?, min_region_px?, heatmap?, viewports?, baseline_dir?, until?, keep?, timeout_ms? | one-roundtrip verify pass: open headless, load the url (or render inline HTML directly, CLI: hwatu render), eval/shot/diff-vs-baseline, close; replies with everything at once. viewports (CLI: --viewports 360x640,1920x1080) sweeps the same pass at N sizes on the one window, replying with per-size results under viewports: [{size, eval, shot, diff, pass_ms}]; screenshots get a -<WxH> suffix and baseline_dir supplies per-size baselines <dir>/<WxH>.png |
prefetch | url | start loading in a headless window and return immediately; the next check of the same url adopts the warm window (30 s TTL, max 3) |
challenge | id?, wait?, timeout_ms? | detect CAPTCHA/anti-bot UI; optionally wait for manual/user resolution |
scroll | id?, selector?, nth?, contains?, to_y?, by_pages? | scroll and report where it landed |
snapshot | id? | token-cheap page state: url, title, text, indexed interactables |
expect | id?, selector, nth?, contains?, text?, absent?, visible?, timeout_ms? | assert page state, polling until it holds (default 5 s); failure names what WAS found. visible additionally requires a real rendered element: nonzero box, no display/visibility/opacity hiding (self or ancestor), in viewport, and not covered by another element (occlusion via elementFromPoint); failure names the exact cause, e.g. what covers it |
click | id?, selector?, nth?, contains?, ref? | click an element (real pointer events), reports what it hit |
type | id?, selector?/ref?, text, clear?, enter? | fill input/textarea/select/contenteditable |
console | id?, clear?, limit? | read the console/error/network capture buffer |
net | id?, clear?, limit? | structured per-window network request log (method, final url, HTTP status, resource type inferred from response MIME, start_ms offset from navigation start, duration_ms); bounded 500-entry ring buffer, clear empties it |
upload | id?, selector, path | set a file input's files from disk |
clock | id?, action (pause/resume/step/set/seed/status), ms?, seed? | control the page's virtual clock: freeze, step, or scrub every time source the page can read |
motion | id?, observe?, observe_ms? | declared animation inventory (CSS/WAAPI/CSSOM); with observe, also samples the live page under virtual time and fits models to script-driven motion (velocity, period, easing, r²) |
ping | health check; returns {build, version} and the CLI warns when the running daemon's build differs from the client's (restart with hwatu quit && hwatu ping) |
When id is omitted, commands target the focused window, else the
window your last automation command targeted (including open), else
the only window. So open → eval → shot chains never need an id.
Only genuine ambiguity (several windows, none focused, none driven
yet) is an error: an agent driving the wrong window is worse than a
retry.
Challenge
hwatu challenge detects CAPTCHA and anti-bot pages and returns JSON:
hwatu challenge
{"status":"challenge","challenge_type":"turnstile","confidence":0.5,
"evidence":[{"kind":"turnstile","detail":"iframe ...","weight":4}],
"actionable":true,"elapsed_ms":0,
"url":"https://example.com/","title":"Just a moment..."}The agent solves the challenge with standard commands: shot and snapshot
to read it, click --trusted and type to answer it in the real engine,
then challenge again to confirm the status is cleared. challenge --wait
--timeout-ms 60000 polls until the challenge disappears.
click --trusted and type --trusted deliver events the page sees with
isTrusted === true. A selector resolves in the top document first, then
in child frames, including cross-origin challenge frames
(click --trusted '#recaptcha-anchor'). For a target with no selector,
such as an image region, click --trusted --at X,Y clicks a point in
top-viewport CSS pixels (a shot pixel divided by devicePixelRatio).
challenge reports clear once the widget's response token is set.
ping reports capabilities.trusted_input_headless. When it is true,
trusted input reaches headless windows and nothing appears on the user's
screen. On macOS input goes to the web view. On Linux the daemon moves the
window to a private Wayland compositor (sway, cage, or labwc) for the call;
keys need wtype. On GNOME and KDE, which accept no virtual input, shown
windows take the same route. It is false on an X11 session, or when no
compositor is installed; then trusted input answers an error that says what
is missing.
doctor reports the same.
--trusted does not bypass the irreversible-action stop.
If the agent cannot clear the challenge, challenge returns a structured
block and the session is kept. The agent can call show, tell the user what
is needed, and continue once the status is cleared.
There are no third-party solver services, injected challenge tokens, fingerprint changes, or access-control bypasses.
Structured stops
The browser does not talk to the user. A stopped command returns
{"status": "err", "message": ..., "stop": {"reason": ...}} and the agent
relays the reason through its harness. In a batch, the failing step's
response.stop carries the same object.
irreversible_action: a click on a payment, send, or delete control (pay, place order, buy, send, delete account). The click is not performed.stop.kindandstop.labelname the control. The agent asks the user, then retries with--confirm(CLI) orconfirm: true(MCP). Page content cannot supply the confirmation. The classifier (page-scripts/irreversible.js) knows final-action phrases in English, German, French, Spanish, Portuguese, Italian, Dutch, Russian, Japanese, Chinese and Korean. On a checkout page (the URL or title names checkout, or a total with a currency is shown) it also stops short button labels built on a pay, order or buy stem in those languages, and generic Finish/Confirm/Submit. It is a heuristic: on a held-out label set it missed 5 of 27 final actions and stopped 1 of 21 non-final controls (tests/conformance/irreversible-labels.json). Do not rely on it as the only safeguard before an irreversible step.login_required: reported byauth-contextas thelogin_requiredfield when a visible password or one-time-code field is on the page.needsiscredentialsorone_time_code. The agent asks the user, enters the value once, and the session persists across runs. On pages that render the form with JavaScript, runwait-load --until quiescentfirst:settledcan return before the form exists (measured on saucedemo.com from a fresh daemon: 3 to 7 misses in 15 runs withsettled, 0 in 15 withquiescent).challenge: returned bychallenge --waitwhen a challenge is still present at the deadline.retry.commandisshow.
hwatu ping lists the stops a daemon supports under
capabilities.structured_stops.
Eval semantics
js can be an expression or a function body; the daemon
picks the right form with a daemon-side parse (nothing but the code
that actually runs ever reaches the page), so both just work:
hwatu eval 'document.title' # expression
hwatu eval '1+1' # expression
hwatu eval 'return document.title' # function body
hwatu eval 'const n = 6*7; return n' # statements need returnawait works in both forms and a returned Promise is awaited before
the response. undefined maps to JSON null. Default timeout 15 s,
override with timeout_ms.
If the page navigates while the script runs (a click handler that
follows a link, location =, form submit), the document's JS context
is destroyed and the eval can never resolve. Instead of a silent
null or a full timeout, the daemon replies immediately with an
error naming the destination URL; wait-load then re-syncs you with
the new document. For click, type --enter, and challenge --wait
the same navigation is treated as success: the reply waits for the
load to finish and returns {"navigated": true, "url": ...}.
hwatu eval 'return {
title: document.title,
errors: [...document.querySelectorAll(".error")].map(e => e.textContent),
}'Scroll semantics
Exactly one way to say "where": selector (scrolled into view,
centered; disambiguate with nth and/or contains), to_y
(absolute pixels), or by_pages (viewport-heights, default 1.0,
negative = up). The response tells you what happened, so no
screenshot is needed to confirm a scroll:
hwatu scroll h2 --contains History
{"matched":{"matches":1,"tag":"h2","text":"History"},"x":0,"y":431,"max_y":8902,"at_bottom":false}
hwatu scroll --by 2 # two viewports down
hwatu scroll --to-y 0 # back to topA selector that matches nothing (or nth past the end) is an error
that reports the match count, not a silent scroll to the wrong place.
Snapshot: page state without pixels
hwatu snapshot returns the page as structured JSON: url, title, the
visible text (bounded to ~4 KB), the scroll position, and up to 120
visible interactables (links, buttons, inputs, selects,
role=button, contenteditable), each with a ref index, tag, label
text, and, where useful, href/type/value/name/checked:
hwatu snapshot
{"url":"http://localhost:5173/","title":"My app","text":"…",
"interactables":[{"ref":0,"tag":"a","text":"Docs","href":"/docs"},
{"ref":1,"tag":"input","type":"text","name":"q","text":"Search"}],
"scroll":{"y":0,"max_y":1180}}The refs are live element handles held by the page: hwatu click
--ref 0 or hwatu type --ref 1 hello target them directly, no
selector engineering. Refs go stale on navigation (you get a clear
error, not a wrong click); re-snapshot after the page changes. For
"did it render right" use shot; for "what is on this page and what
can I do" use snapshot, at a fraction of the tokens.
Click and type
Both target elements the same way: a CSS selector (disambiguated
with --nth / --contains, like scroll) or --ref <n> from the
last snapshot. Both scroll the element into view first and report
what they hit.
hwatu click button --contains "Save"
{"clicked":{"matches":1,"tag":"button","text":"Save"},"url":"http://localhost:5173/"}
hwatu type 'input[name=email]' user@example.com
hwatu type 'textarea' "line one" --no-clear # append instead of replace
hwatu type 'select[name=lang]' Korean # picks the matching <option>
hwatu type 'input[name=q]' query --enter # Enter; submits the form if unhandledclick dispatches a full pointer sequence (pointerdown, mousedown,
focus, pointerup, mouseup, click), so handlers listening on any of
those fire. type sets values through the native setter and fires
input/change, which framework-controlled inputs (React et al.)
observe. Ambiguity and misses are structured errors with match
counts, not silent no-ops.
Console and network capture
Every window buffers, from document start: console.* calls,
uncaught exceptions, unhandled promise rejections, failed resource
loads, and HTTP >= 400 responses (last 500 entries). This answers
"why is the page broken" without screenshot archaeology:
hwatu console
[{"ts_ms":1784737800442,"kind":"console","level":"error","text":"something bad happened {\"code\":42}","page":"http://localhost:5173/"},
{"ts_ms":1784737800448,"kind":"exception","level":"error","text":"unhandled rejection: lost promise\n…","page":"http://localhost:5173/"},
{"ts_ms":1784737800449,"kind":"network","level":"error","status":404,"text":"HTTP 404","url":"http://localhost:5173/api/x","page":"http://localhost:5173/"}]
hwatu console --clear # read and drain, so the next read is a clean diff
hwatu console --limit 10 # just the tailA tight verify loop: hwatu console --clear before the action,
act, then hwatu console shows only what the action caused.
Virtual time: hwatu clock
hwatu seek pins declarative animation (CSS/WAAPI) by pausing it and
setting currentTime. Script-driven motion has no such handle: a
requestAnimationFrame loop that integrates timestamp deltas (the
classic marquee/carousel/physics pattern) sails straight through a
seek. hwatu clock fixes that by putting every clock the page can
read behind one controllable virtual timeline: performance.now,
Date.now, new Date()/Date(), setTimeout/setInterval,
requestAnimationFrame (a
user script wraps them at document start, before any page code runs),
with CSS/WAAPI currentTime driven from the same clock.
hwatu clock pause # freeze: rAF stops, timers stop, now() stops
hwatu clock step 1000 # advance exactly 1000 virtual ms (60fps ticks:
# due timers fire, one rAF batch per tick)
hwatu clock set 5000 # step to absolute virtual time 5000 ms
hwatu clock resume # back to real time, monotonic
hwatu clock seed 42 # Math.random -> seeded deterministic PRNG
hwatu clock status # {installed, paused, virtual_ms, pending_*, seed}Until the first pause/step/set the clock is dormant passthrough:
timers delegate 1:1 to native timers, virtual time equals real time,
and pages behave natively. After pause, equal steps give equal
frames: two hwatu shots at the same virtual time are byte-identical,
so animated pages become diffable stills even mid-flight. In headless
windows, where the engine never grants rendering opportunities,
step is also what drives rAF and IntersectionObserver callbacks,
so visibility-gated animation runs at all.
Caveats, in the same spirit as the eval-navigation note: the clock
controls time after page scripts start reading it, not the page's
load. Two loads of the same URL reach clock pause at slightly
different real moments (network, decode), so set 5000 on two fresh
loads is not pixel-reproducible unless you pause before the motion
starts and step from there; within one loaded page, determinism is
exact. The harness's own commands (expect polling, challenge
--wait, click settle delays) run on the native clock, so a paused
page never deadlocks the tool driving it. Pages that captured
performance.now into a closure before the wrapper ran (impossible
for normal loads, possible for pages loaded by a pre-clock daemon
build) report installed: false errors; reload the page.
Math.random is the one visible entropy source the clock does not
cover, so clock seed <u64> replaces it with a deterministic PRNG
(mulberry32). The seed applies to the current page immediately and,
via a document-start script, to every future load in that window, so
same seed + same virtual timeline (which fixes the order of
Math.random() calls) gives identical sequences across loads.
Without a seed, pages keep native Math.random.
Observed motion: hwatu motion --observe
hwatu motion reads the page's declared animation inventory
(CSS/WAAPI/CSSOM). Script-driven motion (the rAF marquee, a canvas
container repositioned by JS, a physics tween) is invisible to all
of it. --observe closes the gap by watching the live page and
fitting models, not capturing frames:
hwatu motion --observe --ms 2500
# ... declared inventory as before, plus:
# "observed": [{"target":"ul.logo-carousel__marquee","property":"transform",
# "axis":"x","model":"linear","velocity_px_s":-29.99,
# "period_s":103.23,"phase_s":103.15,"fit_r2":1.0,
# "source":"observed"}],
# "observed_meta": {"frames":150,"window_ms":2500,"wrap_hunt_ms":100800,
# "virtual_time":true}A sampler injected into the page finds moving elements
(MutationObserver for style writers + a two-frame rect diff, topmost
movers only), samples getBoundingClientRect once per frame over the
window, and then wrap-hunts: fast-forwards time in coarse chunks
until looping tracks jump, pinning loop periods that are minutes long
without waiting minutes. The daemon fits each position series and
reports per track: linear (robust velocity in px/s, immune to
loop-wrap outliers; loop period_s/phase_s when evidence exists),
periodic (oscillation period via autocorrelation), or bezier
(one-shot move: duration, distance, fitted cubic-bezier easing).
Every fit carries fit_r2; treat entries below ~0.9 as "something
moved" rather than a law of motion. Identical sibling fits (one
layout shift moving a whole column) are collapsed into one entry with
also_targets.
Sampling runs on the virtual clock, which is not an implementation
detail but the reason this works at all: in headless windows native
rAF never ticks (hidden pages get no rendering opportunities), so
any real-time observer sees a frozen page. Clock-stepped sampling
drives rAF itself with virtual timestamps, and is faster than real
time (2.5 s of animation measured in about a second, plus the wrap
hunt covering minutes of virtual time). The observation perturbs the
page's timeline (time is stepped, then resumed), so run it before or
after, not during, a seek-pinned screenshot comparison. The output
is token-cheap JSON: positions and fits, never pixels.
A verification loop
For a one-shot check, hwatu check is the whole loop in one command
(and one daemon roundtrip): it opens a headless window, waits for the
load, runs your JS, screenshots, closes the window, and replies with
url/title/eval/shot-path/console/timings as one JSON object. It can
never leak a window, even on timeout.
hwatu check localhost:5173 --eval 'document.title' --shot=/tmp/after.png
hwatu check localhost:5173 --until dom # don't wait for slow images
hwatu check localhost:5173 --keep # keep the window, returns id
hwatu check localhost:5173 --baseline /tmp/before.png --heatmap /tmp/heat.png
# + pixel diff vs a baseline PNGWith --baseline, the reply gains a diff field: match_percent,
mismatch regions, worst_region, significant_regions, and the
envelope (engine/viewport/caveats), same output as hwatu diff. One
command answers both "is the DOM right" (--eval) and "does it look
right" (--baseline).
Gate on significant_regions == 0, not on match_percent. The mean
is diluted by unchanged background: a moved button on a mostly-empty
page still scores 99%+, while spread antialiasing noise can cost the
same pixel count without mattering. A region only becomes
significant once a connected cluster holds at least --min-region
mismatched pixels (default 1024, one 32x32 cell), and worst_region
names the largest one with its bounding box and density. Keep
match_percent as the trend/convergence number, per-pixel
--tolerance for AA noise, and --min-region for what counts as a
real difference; the three knobs are deliberately separate so a
threshold stays explainable in review.
Verification jobs: one contract for every harness
Use hwatu verify when the verification contract also needs to own a
preflight gate, local server lifecycle, responsive viewport sweep, source
staleness check, and evidence report:
{
"version": 1,
"name": "about-layout",
"cwd": "..",
"url": "http://127.0.0.1:4321/about",
"tier": "layout",
"preflight": { "argv": ["npm", "run", "build"], "timeout_ms": 120000 },
"server": { "argv": ["npm", "run", "dev", "--", "--host", "127.0.0.1"] },
"viewports": ["390x844", "768x1024", "1440x1000"],
"assertion_js": "return { ok: !!document.querySelector('main') };",
"baseline_dir": "golden/about",
"source_files": ["src/pages/about.astro"]
}hwatu verify .hwatu/about.verify.jsonCommands are argv arrays, never shell strings. The client reuses an existing
TCP server or starts and owns one, polls readiness, sends one daemon check,
then cleans up the owned process group, including on SIGINT or SIGTERM. It
fingerprints the parsed job contract, sources before and after browser work,
and screenshot artifacts, then atomically writes the stable JSON report under
.hwatu/verify/<name>/report.json by default. The interactive tier requires
an explicit assertion_js. With baseline_dir (per-size golden PNGs,
<dir>/<WxH>.png), each viewport is also pixel-diffed and a viewport whose
diff clusters into significant regions fails the job, worst region named in
the finding; the global match percent is reported as evidence but never
gates, and min_region_px tunes the significance floor.
MCP clients call verify_ui with the same spec_path, so Jcode, Claude Code,
and other MCP harnesses execute the same implementation rather than recreating
the loop in prompts. Inline MCP specs are browser-only. They reject process
commands, working-directory and output-path overrides, and source paths or
symlinks that escape the MCP working directory. Their evidence is written to a
runtime-scoped Hwatu directory. Command-bearing job files should be reviewed as
executable project configuration.
First render: verify before a baseline exists
A new page has nothing trustworthy to pixel-diff against. Do not seed a baseline merely because the page loaded, and do not infer visibility from DOM existence. Establish semantic and rendered invariants first:
id=$(hwatu --headless --json localhost:5173 | jq .id)
hwatu wait-load --id "$id"
hwatu snapshot --id "$id" # expected controls/text exist
hwatu expect --id "$id" 'main' --visible # rendered and unobscured
hwatu expect --id "$id" 'button' --contains Save --visible
hwatu console --id "$id" # no runtime/load failures
hwatu shot --id "$id" /tmp/baseline.png # seed only after checks pass
hwatu close "$id"expect --visible records the current scroll position, temporarily scrolls a
fully off-screen match into view, hit-tests its center and four inset corners,
and restores the original position. After a scroll inspection completes, it
reports inspection-induced document or target-geometry changes instead of
trusting a layout created by the check itself. Effective opacity is calculated
through the ancestor chain, and two matching samples are required so a
transitional frame cannot false-pass.
Requiring every hit-test sample to resolve to the element or its subtree also
catches partial overlaps such as a sticky header over the top edge. On failure,
the message identifies the instability, sampled point, or covering element.
Once the first render is approved, use that screenshot as the baseline for
subsequent check --baseline or diff --baseline passes.
Recommended agent policy: snapshot for structure, expect for invariants, console for runtime health, screenshot for human evidence, diff for regressions. These layers complement each other; no single layer is proof.
Speculative pre-render: pay the load while you think
hwatu prefetch <url> starts loading the page in a headless window
and returns immediately. The next check of the same URL adopts the
warm window instead of navigating, reporting "prefetched": true and
load_ms near 0. Fire it right after writing a file, then compose
your check; by the time you run it, the render is done (measured
medians on a local fixture: check 84 ms, prefetched check 1 ms; see
benchmarks.md).
hwatu prefetch localhost:5173 # returns immediately, page loads in background
# ... agent formulates the verification ...
hwatu check localhost:5173 --eval '...' --shot # adopts the warm window, ~5 msUnclaimed prefetches expire after 30 s (the page would be stale anyway); at most 3 are held at once. A prefetch is never required for correctness: a check with no matching prefetch just loads normally.
For multi-step interaction, sticky targeting means the loop needs no ids: each command follows the window the previous one drove.
id=$(hwatu --headless --json localhost:5173 | jq .id) # ~14 ms
hwatu wait-load
hwatu snapshot # what's on the page, what can be clicked
hwatu click --ref 2 # act on it
hwatu expect '#status' --text Saved --visible # did the intended effect happen?
hwatu console # supplementary runtime/request diagnostics
hwatu shot /tmp/after.png
hwatu close $idEvery state-changing action needs a post-action assertion. A dispatched click
does not prove that its handler existed or that the application responded, and
a clean console cannot reveal a handler that was never attached. Verify the
specific effect: a DOM or class change, navigation, request-driven result,
element disappearance, or a value that survives reload. console is
supplementary diagnostic evidence, never the success condition by itself.
Measured cost of that whole loop against a local dev page, medians over 10 runs (full data):
| step | median |
open --headless | 9 ms |
wait-load | 49 ms |
eval | 2 ms |
shot (1024x768 PNG) | 15 ms |
close | 6 ms |
| total, 5 separate commands | 87 ms |
total, one hwatu check | 35-39 ms |
A full check with a screenshot costs ~35-39 ms as one command
(window recycling skips construction), faster than the same pass
through a warm in-process Playwright connection (82 ms), and ~9x
faster than warm-server Playwright driven the same service shape
(341 ms).
eval at 2 ms is cheap enough to poll.
wait-load (and goto, and check) default to the full settle:
every subresource loaded. Real pages drag that out with slow images
and third-party scripts; when the check only reads the DOM, pass
--until dom to release at DOMContentLoaded instead (a fixture
with one 800 ms-slow image: 68 ms vs 1581 ms, same DOM either way;
see benchmarks.md).
To let the user see the session:
hwatu show $id # visible window; state is kept
hwatu hide $id # returns it to headless
hwatu show $id --as shot out.png # screenshot, stays headless
hwatu show $id --as diff --baseline b.png # diff, stays headlessfocus and unfocus remain accepted aliases of show and hide.
Display and environment
hwatud is a GTK app and needs a display connection, even for headless
windows. With no display (CI, a bare ssh login) the daemon enters
display-free mode and hosts its own child Wayland compositor (cage, labwc, or
sway on the wlroots headless backend). resize measures the viewport the
page sees and corrects the allocation.
On a bare ssh login there is usually no D-Bus session bus, and WebKit portal
lookups can stall the first load. Start the daemon under one:
dbus-run-session -- hwatud.
GTK derives surface scale from the monitors, so a fractional-scale output can
change devicePixelRatio. Set HWATU_DPR=<integer> on the daemon to pin it.
This forces the X11 backend unless GDK_BACKEND is set. resize replies
report the dpr the page sees.
Integrations
hwatu setup # detect clients; change nothing
hwatu doctor # dependency and rendering checks
hwatu setup --client claude --scope project --dry-run
hwatu setup --client claude --scope projectsetup supports claude, cursor, jcode, and generic. --dry-run
previews the change and --undo removes only hwatu's entry.
- Jcode uses the socket directly as its
browserbackend. hwatu mcpserves MCP over stdio. Manual configuration is one entry:{ "mcpServers": { "hwatu": { "command": "hwatu", "args": ["mcp"] } } }The daemon starts on the first tool call. Id-less calls follow the last-driven window, as in the CLI. For Claude Code:
claude mcp add hwatu -- hwatu mcp.- Any other agent can use the CLI or the socket protocol above.
Project instructions
Add a block like this to AGENTS.md or CLAUDE.md:
## hwatu
- Verify frontend changes with `hwatu` instead of launching Chrome.
- `hwatu snapshot` returns page state. `hwatu click --ref <n>` and
`hwatu type --ref <n> <text>` act on it.
- After every state-changing action, assert the effect with `hwatu expect`.
A successful click is not proof.
- `hwatu console` returns errors and failed requests. A clean console is
supplementary evidence.
- `hwatu shot out.png` takes a screenshot. `hwatu show <id>` lets the user
see the session.
- A click on pay, place order, send, or delete returns a structured stop.
Ask the user, then retry with `--confirm`.
- Docs: https://github.com/hongnoul/hwatu/blob/main/docs/agents.mdEngine scope
Pixels and behavior come from the OS engine. Pages that behave differently in Chromium need a separate Chromium check.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

