Raven-1/ui-web/scripts/boot-snapshot.mjs
KT 1bed0cdb9e refactor(ui-web): the conventions a domain follows, with the gates that hold them (#481)
Stacked on #475 (`refactor/ui_web_architecture`): the conventions that
keep the rebuilt `ui-web/` from drifting, written down in
`ui-web/CONTRIBUTING.md` and enforced by gates. Twenty-two commits, each
landed with every gate green. Three of them change what a DOM diff sees
and are named below; the rest are DOM-invisible.

- **One store shape.** `state/store.ts` exports `makeStore<T>()` with
`get / set / subscribe / _resetForTests`; 33 hand-rolled stores
migrated, `getState` / `put` / `commit` / `wipe` retired; the
`store-shape` gate pins the eight modules that keep a different shape,
each with its reason.
- **One source seam.** `ds<K extends keyof Sources>(domain: K)` is
key-typed, so a renamed or missing domain is a compile error; every
`gateway()` call lives in a domain's `source.ts` (`rpc-names` enforces
placement); `app/install.ts` is the only module that assigns
`sources.*`; skills has its own `source.ts` and the shared `ext.list`
read is `features/installed/source.ts`.
- **No island bag.** `features/registry.ts`'s `islands` object is gone;
page-wide code imports a domain's store directly, and the three
callbacks `state/page.ts` needed are registered from `app/install.ts`.
That one edge was 18% of the import graph's closure weight and held the
tree's only module-evaluation-order hazard. The `import-direction` gate
now pins the layering (`lib <- components <- chrome <- app`, `lib <- rpc
<- state <- chrome, features, app`, `features -/-> features` except
`source.ts`/`types.ts`) with today's upward and cross-domain edges as a
down-or-gone list. Two of the four pinned import cycles are dissolved
the way the gate prescribes (a state module declares a slot, the domain
fills it): `state/page.ts` no longer reads `state/caps.ts`,
`state/navfly.ts` no longer imports the rail store; 17 files sit in a
cycle now, in two components, down from 21 in four.
- **Language is resolved at boot** (localStorage, then config, then
`<html lang>`), so `t(key)` is the only way to take a string; every
island root subscribes to the language store and the hand-kept repaint
list shrinks to the two imperative steps. `T()` and `lang.text()` are
retired, and so are the 61 inert `data-i18n*` attributes the old
document walk used to read.
- **Each domain declares itself once.** `features/<domain>/manifest.ts`
(aggregated in `features/manifests.ts`) and `state/pages.ts` drive the
page sections, the Escape order, the body order, the rail buttons, the
mounts and the region goldens; `domain-shape` and `domain-registration`
gates hold the two tables together.
- **Homes and names.** The desk is its own domain (`features/desk/`);
`resume` lives with the session runtime; the composer's three sheets
live in the composer; the session naming protocol is
`state/session/naming.ts`; `features/xa/` is `features/extAgents/` with
matching ids and exports; wiring modules are all `wire.ts`; page roots
are all `<Domain>App`; `popover`, `pane`, `escapeOrder`, `installEntry`
/ `installSkill`, `Frame` replace the competing words; `useInTask` (not
a hook) is `startTaskWith`; the `file-names` gate pins the case rules.
- **Hooks and types.** `react-hooks/rules-of-hooks` is an error (the
seven warnings were a misnamed verb and one hook after an early return,
now `PlainCallRow`); `tsconfig` adds `noUnusedParameters` and the eight
sites it named are gone; `npm run lint` is down to seven warnings, all
`exhaustive-deps` effects that deliberately run once plus one guarded
expression.
- **Gates and tooling.** The stylesheet hash pin is retired (the eleven
declaration-level CSS gates remain), the six CSS gates share one parser,
`check-css` and `check-class-namespace` run under `npm test`; the
class-namespace gate covers every domain with a per-domain prefix, reads
class literals inside `className={...}` expressions as well as
attributes, and pins today's debt as three down-or-gone lists (86
shared, 342 unprefixed, 91 unprefixed in expressions); fixture
responders return `Wire<ResultOf<M>>` instead of `as`-asserted literals
(which exposed five fixture answers that did not match the contract),
and the turn script fixture is a typed union with no cast left; the
offline library's coverage of every called method is gated with a named
exemption list; `boot-order` is three gates by concern; eslint with
import sorting and unused checks (the tui's config) runs as `npm run
lint` after a one-time 206-file sweep, and `make lint-ui` and the CI ui
job run it.
- **Docs and comments.** `ui-web/CONTRIBUTING.md` (layout, domain
skeleton, store shape, rendering, source and fixtures, naming, CSS,
tests and gates, tooling, the adding-a-domain checklist, and a table of
every pinned exception), new `ui-web/CONTEXT.md` entries, a README whose
layout table matches the tree, and `tests/test_living_docs.py` scanning
all three. Every code comment that explained a decision by what the
deleted script layers used to do now names the live owner or is gone.

What a reader can see change:

- The offline `?stub=1` page and the first live frame before the config
answers now render in one resolved language instead of Chinese markup
with English dynamic text; two tooltip strings in the boot golden moved
with it, and the golden now records tooltip attributes by name rather
than by sentence.
- Domain ids follow their directory: `#extAgentsPage`,
`#connectionsPage`, `#memoryPage`, `#playbooksPage` and their bodies and
rail buttons. `page.css` referenced none of them; the knowledge page
keeps `#kbPage` because the stylesheet pins it.
- The 61 `data-i18n`, `-ph`, `-title`, `-aria` and `-tip` attributes are
gone from the chrome markup. No selector, dataset read, stylesheet rule
or gate named one; the 14 goldens that carried them change by exactly
those attributes and nothing else (each new golden diffs clean against
the old one with the attribute text stripped).

Also restored: the cron page's run-history refetch on a language change,
which the earlier `redrawAll` deletion had dropped.

Outside `ui-web/`, three files: the `Makefile`'s `lint-ui` target and
the CI ui job gain `npm run lint`, and `tests/test_living_docs.py` scans
the three `ui-web/` documents.

Not in this PR, each recorded in `CONTRIBUTING.md`'s exceptions table:
i18n namespaces still use their old abbreviations because the catalogue
(`i18n/messages.json`) is shared with the TUI and lives outside
`ui-web/`; the two remaining import cycles (the six-file
composer/transcript/workspace knot and the eleven-file session knot);
the class names still defined in `page.css` rather than per domain; the
three places `rpc-schema/openrpc.json` disagrees with its own
descriptions, which is the backend's to settle.

- [ ] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [x] Refactor
- [ ] Other

From the repo root, on the branch head:

- `cd ui-web && npm run type-check && npm run lint` -> clean, 7 warnings
(from 14 on the base's first lint run), 0 errors
- `cd ui-web && HOME=$(mktemp -d) npx vitest run` -> 162 files, 2534
tests passed, 0 skipped (from 152 / 2494 on the base; one test whose
subject was deleted went with it)
- `make build-ui` -> `boot-snapshot: OK (284 nodes match golden)` and
`boot-snapshot: OK (285 nodes match golden)`
- `make lint-ui` -> `gen:check`, `npm run lint`, `type-check` all clean
- `cd ui-web && node scripts/check-page.mjs && node
scripts/check-css.mjs && node scripts/check-class-namespace.mjs && npm
run gen:check` -> all OK
- `uv run --frozen pytest tests/test_ui_agent_marks.py
tests/test_ui_provider_marks.py tests/test_ui_css_token_gate.py
tests/test_living_docs.py -q` -> 55 passed
- `make check-source-language` over `origin/main..HEAD` -> exit 0
- `uv run --frozen pre-commit run --from-ref
refactor/ui_web_architecture --to-ref HEAD` -> all passed
- `git diff --stat refactor/ui_web_architecture..HEAD -- . ':!ui-web'`
-> exactly `Makefile`, `.github/workflows/ci.yml`,
`tests/test_living_docs.py`
- Every new gate was mutation-checked (one-line breakage red, restored
green); per-step happy-dom dumps of the body order, listener sequence,
boot walk and language flips are byte-identical across the DOM-invisible
steps and differ only as described above in the other three.
- Not done: a real-browser pass.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

- Security: none; no protocol or auth path changes.
- Backward compatibility: build entry points, script paths CI calls, URL
flags and DOM ids the stylesheet references are unchanged; renamed ids
and the dropped `data-i18n*` attributes appear only in goldens.
- Rollback: revert the squash merge into `refactor/ui_web_architecture`.

---------

Co-authored-by: Claude (claude-fable-5-1) <noreply@anthropic.com>
2026-09-22 01:05:18 +08:00

134 lines
6.2 KiB
JavaScript

import { Window } from 'happy-dom'
// Boots the assembled page in happy-dom and compares the DOM shape it settles
// into against a golden. This is the gate on the structural switches of the
// refactor -- concatenated script to modules, one build shape to another --
// none of which may move a single element.
//
// node scripts/boot-snapshot.mjs dist/index.html # stub mode
// node scripts/boot-snapshot.mjs dist/index.html \
// --url http://127.0.0.1:18792/ --golden scripts/__golden__/boot-live-noserver.txt
// node scripts/boot-snapshot.mjs dist/index.html --update # rewrite the golden
//
// build.py runs the compare form twice, once per mode. Stub mode is the demo
// shell on its fixtures; live mode is what a reader sees when the page loads
// and the gateway is not there, which is a different tree and its own golden.
// A missing golden is written on a developer machine and refused under CI, so
// a fresh checkout cannot pass by accident.
//
// What is recorded: tag, #id, .classes and [data-*] per element, indented by
// depth, text dropped, script and style skipped (the build changes how many
// there are). The two data attributes that carry a phrase rather than a flag
// are recorded by name alone, for the reason beside PHRASE below. Determinism rests on the timer clamps below: the splash lifts on
// a 250ms floor plus a fade, and clamping every timer to 50ms makes the tree
// stop moving within the tick budget rather than depending on wall time.
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
/** The data attributes whose value is a sentence, not a state. */
const PHRASE = new Set(['data-tip', 'data-label'])
const usage = () => {
console.error('usage: node scripts/boot-snapshot.mjs <dist/index.html> [--url <url>] [--golden <path>] [--update]')
process.exit(2)
}
let dist = null
let url = 'http://127.0.0.1:18792/?stub=1'
let golden = fileURLToPath(new URL('./__golden__/boot-stub.txt', import.meta.url))
let update = false
for (let i = 2; i < process.argv.length; i++) {
const arg = process.argv[i]
if (arg === '--update') update = true
else if (arg === '--url') url = process.argv[++i] ?? usage()
else if (arg === '--golden') golden = resolve(process.argv[++i] ?? usage())
else if (arg.startsWith('--') || dist) usage()
else dist = arg
}
if (!dist) usage()
/* Without ?stub=1 the live layer installs and reaches for a gateway. This
snapshot is taken with none running on purpose -- "what the reader gets when
serve is down" is a shape worth pinning -- so a refused connection is the
expected condition here, not a failure. */
const offline = !url.includes('stub=1')
const NETWORK = /ECONNREFUSED|ECONNRESET|ENOTFOUND|EPIPE|socket hang up|fetch failed|Failed to fetch|NetworkError/i
const FATAL = /^(ReferenceError|TypeError|SyntaxError)\b/
const TICKS = 40
const html = readFileSync(dist, 'utf8')
const win = new Window({
url,
settings: {
enableJavaScriptEvaluation: true,
suppressInsecureJavaScriptEnvironmentWarning: true,
disableJavaScriptFileLoading: true,
disableCSSFileLoading: true,
enableImageFileLoading: false,
disableComputedStyleRendering: true,
handleDisabledFileLoadingAsSuccess: true,
timer: { maxTimeout: 50, maxIntervalTime: 50, maxIntervalIterations: 2, preventTimerLoops: true },
},
})
const errors = []
win.addEventListener('error', (e) => errors.push(String(e.error?.stack || e.error || e.message)))
win.document.write(html)
for (let i = 0; i < TICKS; i++) await new Promise((r) => setTimeout(r, 25))
const lines = []
const walk = (node, depth) => {
if (node.nodeType !== 1) return
const tag = node.tagName.toLowerCase()
if (tag === 'script' || tag === 'style') return
const parts = [tag]
if (node.id) parts.push(`#${node.id}`)
const classes = (node.getAttribute('class') || '').trim()
if (classes) parts.push(`.${classes.split(/\s+/).join('.')}`)
const data = node.getAttributeNames().filter((a) => a.startsWith('data-')).sort()
/* A flag's value is shape and is recorded; a phrase's is text and is not.
Two data attributes carry a sentence from the catalogue rather than a
state -- the hover pill's words and the copy button's label -- so what
goes in the golden is that the element carries one. Their wording is the
catalogue's business (scripts/gates/i18n-keys.test.mjs), and recording it
here made every copy edit, and the language the page boots in, a golden
change in a file whose subject is the shape. */
for (const a of data) parts.push(PHRASE.has(a) ? `[${a}]` : `[${a}=${node.getAttribute(a)}]`)
lines.push(`${' '.repeat(depth)}${parts.join('')}`)
for (const child of node.children) walk(child, depth + 1)
}
for (const child of win.document.body.children) walk(child, 0)
await win.happyDOM.close()
const actual = lines.join('\n') + '\n'
/* Offline, only a broken program counts: a name that is not there, a call on
nothing, a script that does not parse. Everything else reaching the window
with no gateway behind it is the absent gateway. */
const fatal = offline ? errors.filter((e) => FATAL.test(e) && !NETWORK.test(e)) : errors
if (fatal.length) {
console.error(`boot-snapshot: ${fatal.length} page error(s) during boot:\n ${fatal.join('\n ')}`)
process.exit(1)
}
if (update || (!existsSync(golden) && !process.env.CI)) {
mkdirSync(dirname(golden), { recursive: true })
writeFileSync(golden, actual)
console.log(`boot-snapshot: golden written (${lines.length} nodes)`)
process.exit(0)
}
if (!existsSync(golden)) {
console.error('boot-snapshot: golden missing under CI; run with --update on a developer machine and commit it')
process.exit(1)
}
const expected = readFileSync(golden, 'utf8')
if (expected === actual) {
console.log(`boot-snapshot: OK (${lines.length} nodes match golden)`)
process.exit(0)
}
const a = expected.split('\n')
const b = actual.split('\n')
let first = 0
while (first < a.length && first < b.length && a[first] === b[first]) first++
console.error(`boot-snapshot: DOM shape differs from golden (${a.length - 1} vs ${b.length - 1} nodes); first difference at line ${first + 1}:`)
console.error(` golden: ${a[first] ?? '<end>'}`)
console.error(` actual: ${b[first] ?? '<end>'}`)
process.exit(1)