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

53 lines
2.0 KiB
JavaScript

/* The stylesheet, and the three ways a gate reads a rule out of it.
*
* Several invariants on this page are facts about paint and layout rather than
* about the DOM -- happy-dom does no layout and applies no stylesheet, so a
* rule that occupies space and one that does not are the same assertion there.
* The gates that pin those facts read src/styles/page.css directly, and each
* one had grown its own copy of the same parser.
*
* Comments come out before anything is matched: what sits between two rules is
* captured as the next one's selector, prose and all, so a comment naming a
* selector would otherwise be read as one.
*
* Not a CSS parser -- one regex over balanced braces, which is why an at-rule's
* body is seen as rules and the at-rule itself is not. A gate that needs the
* `@media` wrapper matches `css` itself (see desk-reserve-css).
*/
import { readFileSync } from 'node:fs'
/** The page stylesheet, as written. */
export const css = readFileSync(new URL('../../src/styles/page.css', import.meta.url), 'utf8')
/** Every rule whose selector matches, as `[selector, declarations]` pairs. */
export function rules(pattern, source = css) {
const stripped = source.replace(/\/\*[\s\S]*?\*\//g, ' ')
const found = []
for (const match of stripped.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
const selector = match[1].trim()
if (!pattern || pattern.test(selector)) found.push([selector, match[2]])
}
return found
}
/** One rule's declarations, by exact selector, or null if there is no such rule. */
export function rule(selector, source = css) {
for (const [found, body] of rules(null, source)) {
if (found === selector) return body
}
return null
}
/** The same rule as a property -> value map, or null. */
export function decls(selector, source = css) {
const body = rule(selector, source)
if (body === null) return null
const out = new Map()
for (const decl of body.split(';')) {
const at = decl.indexOf(':')
if (at > 0) out.set(decl.slice(0, at).trim(), decl.slice(at + 1).trim())
}
return out
}