Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): resolve UI catalog evidence with vitest, and read the day series without a pointer
cyh82c46d5a06ed
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.mdindex e3a1e5a6a..0cb80a145 100644--- a/docs/plans/model-hub-usage-metering.md+++ b/docs/plans/model-hub-usage-metering.md@@ -1151,3 +1151,60 @@ reads empty for drawn and undrawn columns alike. The decision behind the floor iassertable part and it is asserted where it lives — `usageDayIsMetered` over columns in`usageProjection.test.ts` — leaving only the pixel to the residual visual check that thistab already carries.++### Stage 2, round 3 (head `d22cb479`) — breaker tripped++Two P2 findings. **F1 repeats head 1's class on a second reviewed head**, so the breaker+is mechanical: stop patching, diagnose at orchestrator level, record the scope decision.++**The class: a text scan deciding which vitest declarations execute.** Head 1 flagged that+the catalog accepted a non-executable case; the round-2 fix answered with a hand-written+JS lexer in `test_model_hub_catalog.py` — comments, string and template literals, a regex+heuristic. Head 3 then flagged a regex opening after `return`, which the heuristic reads as+division because it only inspects the previous *character*.++Naming the remaining members is what ends this. Measured against the fixture, the lexer+accepted a fake declaration in **five** shapes — a regex after a keyword, JSX text, a+`describe.skip` body, an `if (false)` body, and its own division heuristic — and the+reviewer had reached one. Two of the four it never reached (`describe.skip`, `if (false)`)+are ordinary code, not adversarial constructions. The class has no last member by+construction: telling a regex from division needs the parser's state, and telling a skipped+or unreachable declaration from a live one needs the run. Every future round buys one more+patch and leaves the property unproved.++**Scope decision (orchestrator, no owner escalation needed): delete the lexer and ask the+collector.** `vitest list` answers "does this case run" definitively, and `npm test` — which+is `vitest run` — already executes in CI's `build-linux-artifacts` job on the same commit,+so the real collector costs no new job and no new dependency beyond a declared `js-yaml`.+The action is reversible, contract-preserving (row shape and `path::ID` syntax unchanged),+and smaller than what it replaces: 219 lines of scanner deleted for 126 lines of resolver+plus gate.++Duties split so neither side overclaims:++| Question | Owner | Why there |+| --- | --- | --- |+| Row shape, cited file exists, ID greppable in it, no `expected_fail` on a UI row | `test_model_hub_catalog.py` | `ast`/text answers these exactly |+| Does the cited ID name exactly one case vitest **runs** | `ui/scripts/validate-scenario-catalog.mjs` | only the collector knows |++`scenarioCatalog.mjs` holds the resolution rules with no subprocess in them, so they stay+unit-testable; the gate discovers `tests/scenarios/*/catalog.yaml` rather than listing+them, reads each catalog's own `status_legend` so the two sides cannot drift into+disagreeing policies, and throws if `tests/scenarios` is absent — this gate must never+report "nothing to check" for the one input it exists to read. It collects only the cited+files (9 rows, 3 files, ~0.3 s), not the whole 231-file suite.++MH-CATALOG-002 moves to `ui/scripts/scenarioCatalog.test.mjs`, seeds one declaration of+every shape, and asserts the set that resolves *equals* the set the fixture names as+running — derived from the fixture text, so a shape added later is covered without editing+the assertion. `it.each` is no longer disqualified on principle: the surviving property is+"exactly one collected case named for the row", and a 2-row `it.each` fails it by count.++**F2: every non-peak day's figures existed only in a hover `title`.** Keyboard,+screen-reader, and touch users could reach the endpoints and the peak from the axis and+nothing else — and `role="img"` on the chart hides the columns from assistive tech by+design. One `readout(column)` helper now feeds both the tooltip and an `sr-only` list+rendered as a *sibling* of the image (inside it, it would be hidden with everything else).+No new i18n key: `byDay.column` is the same wording, so the two readings cannot disagree —+which is how MH-USAGE-023 asserts it, tooltips against list items rather than against a+list of days.diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 1b475617f..9ef9b9089 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -122,6 +122,7 @@ capabilities:- tests/test_opencode_server.py- ui/src/components/settings/models/UsageTab.test.tsx- ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+ - ui/scripts/scenarioCatalog.test.mjs- id: harness_failure_recoveryname: Harness per-Session failure recoverystatus: activediff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex b4b2206f6..aaba590c8 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -15,6 +15,9 @@ capability:# properties can be observed, so the catalog checker resolves both shapes.- ui/src/components/settings/models/UsageTab.test.tsx- ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+ # The gate that resolves those rows against vitest's own collection, and+ # its own evidence.+ - ui/scripts/scenarioCatalog.test.mjs- tests/scenarios/model_hub/test_model_hub_catalog.py- tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py- tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py@@ -49,7 +52,7 @@ scenarios:status: coveredkind: contractlayer: unit- test: tests/scenarios/model_hub/test_model_hub_catalog.py::test_mh_catalog_002_ui_evidence_resolves_only_to_an_executable_declaration+ test: ui/scripts/scenarioCatalog.test.mjs::MH-CATALOG-002- id: MH-S1-001name: Live conditions never change the exact configured hop identitystatus: covered@@ -261,6 +264,12 @@ scenarios:kind: observationlayer: unittest: ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-USAGE-022+ - id: MH-USAGE-023+ name: Every day of the window states its figures in text, not only in a pointer tooltip+ status: covered+ kind: observation+ layer: unit+ test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-023- id: MH-RES-LIVE-001name: Live turn retries an eligible backup before streaming startsstatus: covereddiff --git a/tests/scenarios/model_hub/test_model_hub_catalog.py b/tests/scenarios/model_hub/test_model_hub_catalog.pyindex 1bf448dde..bbe50f13e 100644--- a/tests/scenarios/model_hub/test_model_hub_catalog.py+++ b/tests/scenarios/model_hub/test_model_hub_catalog.py@@ -3,10 +3,8 @@from __future__ import annotationsimport ast-import refrom pathlib import Path-import pytestimport yaml@@ -14,10 +12,10 @@ SCENARIO_ROOT = Path("tests/scenarios/model_hub")PROJECT_INDEX = Path("tests/scenarios/INDEX.yaml")CAPABILITY_ID = "model_hub"-#: A vitest case declaration: the bare `it(` call form followed by a name literal.-#: The lookbehind rejects `xit(` and `suite.it(`, and requiring `(` immediately-#: after the identifier rejects every modifier form (`it.skip`, `it.each`, …).-_IT_CALL = re.compile(r"(?<![A-Za-z0-9_$.])it\s*\(\s*(?=['\"`])")+#: Suffixes whose evidence is a vitest case rather than a pytest function. Kept in+#: step with `UI_SUFFIXES` in `ui/scripts/scenarioCatalog.mjs`, which resolves those+#: rows against vitest's own collection.+_UI_SUFFIXES = {".ts", ".tsx", ".mts", ".mjs"}def _document(name: str) -> dict:@@ -45,159 +43,6 @@ def _test_function(path: Path, function_name: str) -> ast.FunctionDef | ast.Asynreturn function-def _advance(source: str, index: int) -> int:- """Index just past the comment, literal, or regex at `index`; the next character otherwise.-- This is the whole lexer: everything the scan must not read as code is a comment,- a literal, or a regex, and skipping one is always "jump to where it ends".- """-- pair = source[index : index + 2]- if pair == "//":- end = source.find("\n", index)- return len(source) if end == -1 else end- if pair == "/*":- end = source.find("*/", index)- return len(source) if end == -1 else end + 2- if source[index] in "'\"`":- return _skip_literal(source, index)- if source[index] == "/" and _opens_regex(source, index):- return _skip_regex(source, index)- return index + 1---def _skip_literal(source: str, index: int) -> int:- """Index just past the string or template literal opening at `index`."""-- quote = source[index]- index += 1- while index < len(source):- char = source[index]- if char == "\\":- index += 2- elif char == quote:- return index + 1- elif quote == "`" and char == "$" and source[index + 1 : index + 2] == "{":- # A substitution is code again, so comments and nested literals apply.- index = _skip_substitution(source, index + 1)- else:- index += 1- return index---def _skip_substitution(source: str, index: int) -> int:- """Index just past the balanced `{`…`}` of a template substitution opening at `index`."""-- depth = 0- while index < len(source):- char = source[index]- if char == "{":- depth += 1- index += 1- elif char == "}":- depth -= 1- index += 1- if not depth:- return index- else:- index = _advance(source, index)- return index---def _opens_regex(source: str, index: int) -> bool:- """Whether the `/` at `index` opens a regex rather than dividing.-- Only the previous token can tell the two apart, and the distinction matters- because a regex holding an apostrophe — `/Couldn't refresh/i`, ordinary in this- suite's assertions — reads as a string opening otherwise. A value can be divided,- so a `/` after a name, a number, or a closing `)` / `]` is division; every other- position is one where a value has to start.- """-- before = source[:index].rstrip()- return not before or not (before[-1].isalnum() or before[-1] in "_$)]")---def _skip_regex(source: str, index: int) -> int:- """Index just past the regex literal opening at `index`.-- A character class is tracked because `/` inside one needs no escape (`/[/]/`),- and an unterminated line ends the scan: no regex spans a newline, so a division- misread as a regex costs one line rather than the rest of the file.- """-- index += 1- within_class = False- while index < len(source):- char = source[index]- if char == "\\":- index += 2- elif char == "\n":- return index- elif char == "[":- within_class = True- index += 1- elif char == "]":- within_class = False- index += 1- elif char == "/" and not within_class:- return index + 1- else:- index += 1- return index---def _vitest_case_names(source: str) -> list[str]:- """The name of every executable `it('name', …)` declaration, in source order."""-- names: list[str] = []- index = 0- while index < len(source):- match = _IT_CALL.match(source, index)- if match is None:- index = _advance(source, index)- continue- end = _skip_literal(source, match.end())- names.append(source[match.end() + 1 : end - 1])- index = end- return names---def _vitest_case_name(path: Path, scenario_id: str) -> str:- """The full name of the one executable vitest case that carries `scenario_id`.-- A user-visible half of this capability is evidenced by a vitest case rather than- a pytest function, and it has to be checkable the same way: the row must resolve- to a case that really runs, and that case must state its catalog ID where a- Python test would carry a docstring. A vitest case's name *is* its docstring, so- that is where the ID goes — which also makes the evidence runnable by ID- (`vitest -t MH-USAGE-018`) rather than merely greppable.-- Reading names alone is what keeps this fail-closed. Resolution has to be lexical,- because every shape that would fool a text search executes nothing: a- commented-out case is not a declaration and neither is a name quoted inside a- string. One shape a scan this size cannot decide is a regex literal against- division, since that needs the previous token's type rather than its last- character. Because a name is all this reads, the worst a wrong guess can do is- lose a declaration — the row stops resolving, loudly. It cannot hand a row a- neighbour's ID, which is exactly what an earlier version that sliced each case's- body got wrong: it bounded the slice by re-running this same scan, so a desync- agreed with itself and the row passed on a sibling's ID.-- Only the bare `it(` form resolves, so a modifier this checker cannot verify- (`it.skip`, `it.only`, `it.fails`) never counts as evidence, and a parameterized- `it.each` — whose names are built at run time — cannot be cited as a row's proof.- """-- prefix = f"{scenario_id}:"- names = [name for name in _vitest_case_names(path.read_text()) if name.startswith(prefix)]- assert len(names) == 1, (- f"Catalog points to {len(names)} executable UI cases named `{prefix} …` in {path}, expected exactly one; "- "a commented-out, skipped, parameterized, or merely quoted case is not executable evidence"- )- return names[0]--def _decorator_names(function: ast.FunctionDef | ast.AsyncFunctionDef) -> set[str]:names: set[str] = set()for decorator in function.decorator_list:@@ -234,15 +79,20 @@ def test_mh_catalog_001_scenario_catalog_is_complete_and_executable() -> None:path = Path(path_text)assert path_text in canonical_testsassert path.is_file()- if path.suffix in {".ts", ".tsx"}:- # Only the bare `it(` form resolves, so a UI-evidenced row has no way to- # declare an expected failure and may not claim one.+ if path.suffix in _UI_SUFFIXES:+ # An expected failure is declared here with `pytest.mark.xfail`, which a+ # UI case cannot carry, so a UI-evidenced row may not claim one.assert not status["expected_fail"], (f"Scenario {scenario['id']} is evidenced by a UI case, which cannot carry an expected failure")- # A UI row cites its ID, and the case it resolves to is the evidence that- # the ID names something vitest runs.- evidence = _vitest_case_name(path, function_name)+ # Whether that ID names a case vitest actually *runs* is a question only+ # vitest answers; `ui/scripts/validate-scenario-catalog.mjs` asks it in+ # the `npm test` run CI already does over this suite. Approximating it+ # here would mean re-deciding, from text, which declarations execute —+ # the answer would be wrong for a skipped, unreachable, or run-time-named+ # case, and wrong quietly. So this side stops at what it reads exactly:+ # the file exists and states the ID.+ evidence = path.read_text()else:function = _test_function(path, function_name)expected_fail = "xfail" in _decorator_names(function)@@ -279,58 +129,3 @@ def test_mh_catalog_001_scenario_catalog_is_complete_and_executable() -> None:for observation in observations["observations"]for scenario_id in observation["affects"])---#: Executable, and so citable as evidence.-_RUNS = "MH-FIXTURE-RUNS"-#: Present in the file, executed by nothing, and so citable by nothing.-_DEAD = "MH-FIXTURE-DEAD"--#: One declaration of every shape a `.tsx` file can carry: each is named for whether-#: vitest runs it, and the assertions read that name rather than a list of cases. A-#: shape added here is covered by the same two properties without editing them.-#:-#: The apostrophe inside a regex literal is what a scan gets wrong by default —-#: read as a string opening, it swallows every declaration that follows, which is-#: why a live case sits after it.-_RESOLVER_FIXTURE = f"""-describe('resolver fixture', () => {{- // it('{_DEAD}-COMMENTED: commented out', () => {{}});- /* it('{_DEAD}-BLOCK: commented out in a block', () => {{}}); */- it.skip('{_DEAD}-SKIPPED: declared with a modifier', () => {{}});- it.each([1, 2])('{_DEAD}-EACH: named at run time %i', () => {{}});- it('{_RUNS}-QUOTES: quotes declarations and matches on apostrophes', () => {{- expect(label).toBe("it('{_DEAD}-INSTRING: quoted in a string', () => {{}})");- expect(hint).toBe(`it('{_DEAD}-INTEMPLATE: quoted in a template', ${{suffix}})`);- expect(text).toMatch(/Couldn't refresh, please retry/i);- expect(share).toBe(total / count);- }});- it('{_RUNS}-AFTER: runs after every shape above', () => {{- expect(true).toBe(true);- }});-}});-"""---def test_mh_catalog_002_ui_evidence_resolves_only_to_an_executable_declaration(tmp_path: Path) -> None:- """MH-CATALOG-002: a UI-evidenced row resolves to the one vitest case that runs under its ID.-- The failure this closes is the one a text search cannot tell apart from evidence:- a catalog ID that appears in a `.tsx` file which vitest executes no matching case- from, leaving a row `covered` by text alone.- """-- path = tmp_path / "fixture.test.tsx"- path.write_text(_RESOLVER_FIXTURE)- resolved = _vitest_case_names(_RESOLVER_FIXTURE)-- # Nothing dead resolves, and nothing live is missed — a scan that desynced on the- # regex above would come up short here rather than resolve past its declaration.- assert all(name.startswith(_RUNS) for name in resolved), resolved- assert len(resolved) == _RESOLVER_FIXTURE.count(f"'{_RUNS}")-- # A row cites an ID, which resolves to exactly the case that carries it.- for name in resolved:- assert _vitest_case_name(path, name.split(":")[0]) == name- with pytest.raises(AssertionError):- _vitest_case_name(path, _DEAD)diff --git a/ui/package-lock.json b/ui/package-lock.jsonindex b48a923a9..e047df863 100644--- a/ui/package-lock.json+++ b/ui/package-lock.json@@ -71,6 +71,7 @@"eslint-plugin-react-hooks": "^7.0.1","eslint-plugin-react-refresh": "^0.4.24","globals": "^16.5.0",+ "js-yaml": "^4.1.0","jsdom": "^29.1.1","postcss": "^8.5.15","tailwindcss": "^4.1.18",diff --git a/ui/package.json b/ui/package.jsonindex dc46cee81..17b510680 100644--- a/ui/package.json+++ b/ui/package.json@@ -14,8 +14,9 @@"lint:report": "eslint .","lint:baseline": "node scripts/lint-baseline.mjs --update","preview": "vite preview",- "test": "vitest run",+ "test": "vitest run && npm run validate:catalog","test:crypto": "vitest run src/lib/vaultCrypto.test.ts",+ "validate:catalog": "node scripts/validate-scenario-catalog.mjs","validate:theme": "node scripts/validate-theme.mjs"},"dependencies": {@@ -82,6 +83,7 @@"eslint-plugin-react-hooks": "^7.0.1","eslint-plugin-react-refresh": "^0.4.24","globals": "^16.5.0",+ "js-yaml": "^4.1.0","jsdom": "^29.1.1","postcss": "^8.5.15","tailwindcss": "^4.1.18",diff --git a/ui/scripts/scenarioCatalog.mjs b/ui/scripts/scenarioCatalog.mjsnew file mode 100644index 000000000..e9df23d82--- /dev/null+++ b/ui/scripts/scenarioCatalog.mjs@@ -0,0 +1,126 @@+/**+ * Resolving a scenario catalog's UI evidence against vitest's own collection.+ *+ * A row marked `covered` claims one executable case carries its ID. For a pytest+ * row `ast.parse` answers that exactly; for a vitest row nothing on the Python+ * side can, and the scan that tried read a live declaration out of five shapes+ * that execute nothing — a regex literal after a keyword, JSX text, a+ * `describe.skip` body, an `if (false)` body, and its own division heuristic.+ * Those are one class with no last member: telling a regex from division needs+ * the parser's state, and telling a skipped or unreachable block from a live one+ * needs the run. So the question goes to the only thing that answers it+ * definitively, and already runs in CI on the same commit: vitest's collection.+ *+ * The gate is `validate-scenario-catalog.mjs`; this module is the part with no+ * subprocess in it, so the resolution rules are testable without one.+ */++import { execFileSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const UI_ROOT = fileURLToPath(new URL('..', import.meta.url));++/** vitest's CLI entry, invoked rather than imported so `list` behaves as it does in CI. */+const VITEST_BIN = path.join(UI_ROOT, 'node_modules', 'vitest', 'vitest.mjs');++/** Suffixes the catalog may cite as UI evidence — every one a file vitest collects. */+const UI_SUFFIXES = new Set(['.ts', '.tsx', '.mts', '.mjs']);++/** The file half of a `path::name` catalog reference. */+const citedPath = (testRef) => testRef.split('::')[0];++export const isUiEvidence = (testRef) => UI_SUFFIXES.has(path.extname(citedPath(testRef)));++/**+ * Every catalog row whose declared status requires a test and whose test is a UI case.+ *+ * Which statuses require one is read from the catalog's own legend, so this side+ * cannot drift from the Python checker into a second, disagreeing policy.+ */+export const uiEvidenceRows = (catalog) => {+ const legend = catalog.status_legend ?? {};+ return (catalog.scenarios ?? [])+ .filter((row) => legend[row.status]?.test_required && typeof row.test === 'string' && isUiEvidence(row.test))+ .map((row) => {+ const [file, cited] = row.test.split('::');+ return { id: row.id, file, cited };+ });+};++/** A collected case's own name, without the `describe` path vitest prefixes to it. */+const caseName = (fullName) => fullName.split(' > ').at(-1);++const sameFile = (collectedFile, file) => {+ const normalized = collectedFile.replaceAll('\\', '/');+ return normalized === file || normalized.endsWith(`/${file}`);+};++/**+ * What is wrong with these rows, given everything vitest collected — nothing if+ * each resolves to exactly one collected case named for the row itself.+ *+ * Zero is the interesting count: a case that is commented out, skipped, named at+ * run time by `it.each`, sitting in an unreachable branch, or merely quoted in a+ * string is absent from a collection, so it cannot stand as a row's evidence.+ */+export const resolveUiEvidence = (rows, collected) => {+ const problems = [];+ for (const row of rows) {+ if (row.cited !== row.id) {+ problems.push(+ `${row.id} cites \`${row.cited}\` as its evidence; a UI row resolves through a case named for the row itself`,+ );+ continue;+ }+ const prefix = `${row.id}:`;+ const matches = collected.filter(+ (entry) => sameFile(entry.file, row.file) && caseName(entry.name).startsWith(prefix),+ );+ if (matches.length !== 1) {+ problems.push(+ `${row.id}: vitest collects ${matches.length} cases named \`${prefix} …\` in ${row.file}, expected exactly one — `+ + 'a commented-out, skipped, parameterized, unreachable or merely quoted case is not executable evidence',+ );+ }+ }+ return problems;+};++/**+ * Every case vitest collects for `files`, as `{ name, file }`.+ *+ * `list` collects without running, so this is what the suite would execute rather+ * than what its source looks like. Filters keep it to the cited files: the gate+ * only asks about those, and collecting the whole suite twice per `npm test`+ * would be the slowest possible way to learn the same thing.+ */+export const collectCases = ({ root = UI_ROOT, files = [], globals = false } = {}) => {+ if (!fs.existsSync(VITEST_BIN)) {+ throw new Error(`vitest is not installed at ${VITEST_BIN}; run \`npm ci\` in ui/ before validating the catalog`);+ }+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'vitest-list-'));+ const output = path.join(directory, 'collected.json');+ try {+ execFileSync(+ process.execPath,+ [+ VITEST_BIN,+ 'list',+ `--json=${output}`,+ '--root',+ root,+ '--dir',+ root,+ ...(globals ? ['--globals'] : []),+ ...files,+ ],+ { cwd: root, stdio: ['ignore', 'ignore', 'inherit'] },+ );+ return JSON.parse(fs.readFileSync(output, 'utf8'));+ } finally {+ fs.rmSync(directory, { recursive: true, force: true });+ }+};diff --git a/ui/scripts/scenarioCatalog.test.mjs b/ui/scripts/scenarioCatalog.test.mjsnew file mode 100644index 000000000..9bc5bbcd7--- /dev/null+++ b/ui/scripts/scenarioCatalog.test.mjs@@ -0,0 +1,116 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterAll, describe, expect, it } from 'vitest';++import { collectCases, isUiEvidence, resolveUiEvidence, uiEvidenceRows } from './scenarioCatalog.mjs';++/** Executable, and so citable as evidence. */+const RUNS = 'MH-FIXTURE-RUNS';+/** Present in the file, executed by nothing, and so citable by nothing. */+const DEAD = 'MH-FIXTURE-DEAD';++const FIXTURE_FILE = 'probe.test.tsx';++/**+ * One declaration of every shape a test file can carry, each named for whether+ * vitest runs it. The assertion below reads those names instead of a list of+ * cases, so a shape added here is covered without editing it.+ *+ * The shapes a source scan got wrong are here: a regex literal opening after a+ * keyword, a `describe.skip` body, an unreachable branch, and a name quoted+ * inside a literal. `list` collects by importing, so a shape whose declaration+ * never executes is absent from the collection for the same reason the suite+ * never runs it — which is why the one remaining scan-only shape, a name written+ * as JSX text, needs no seed here: it is not a declaration, and this fixture+ * cannot resolve the React runtime from a temp directory anyway.+ */+const FIXTURE = `+describe('resolver fixture', () => {+ // it('${DEAD}-COMMENTED: commented out', () => {});+ /* it('${DEAD}-BLOCK: commented out in a block', () => {}); */+ it.skip('${DEAD}-SKIPPED: declared with a modifier', () => {});+ it.each([1, 2])('${DEAD}-EACH: named at run time %i', () => {});+ it('${RUNS}-QUOTES: quotes declarations and matches on apostrophes', () => {+ expect(label).toBe("it('${DEAD}-INSTRING: quoted in a string', () => {})");+ expect(hint).toBe(\`it('${DEAD}-INTEMPLATE: quoted in a template', \${suffix})\`);+ expect(pattern(() => { return /it('${DEAD}-REGEX: held in a regex literal', () => {})/ })).toBe(true);+ expect(text).toMatch(/Couldn't refresh, please retry/i);+ expect(share).toBe(total / count);+ });+ it('${RUNS}-AFTER: runs after every shape above', () => {+ expect(true).toBe(true);+ });+});++describe.skip('skipped suite', () => {+ it('${DEAD}-INSKIPPEDSUITE: declared inside a skipped suite', () => {});+});++if (false) {+ it('${DEAD}-UNREACHABLE: declared in a branch that never runs', () => {});+}+`;++const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'mh-scenario-catalog-'));+fs.writeFileSync(path.join(directory, FIXTURE_FILE), FIXTURE);+afterAll(() => fs.rmSync(directory, { recursive: true, force: true }));++/** Every ID the fixture mentions, in any shape, deduplicated. */+const fixtureIds = [...new Set([...FIXTURE.matchAll(/MH-FIXTURE-(?:RUNS|DEAD)-[A-Z]+/g)].map(([id]) => id))];++describe('UI evidence resolution', () => {+ // The failure this closes is the one a text search cannot tell apart from+ // evidence: a catalog ID that appears in a `.tsx` file vitest executes no+ // matching case from, leaving a row `covered` by text alone.+ it(+ 'MH-CATALOG-002: a UI-evidenced row resolves only to a vitest case that runs under its catalog ID',+ () => {+ // `--globals` because the fixture lives outside this package and cannot+ // resolve `vitest` from there; collection is otherwise the CI call.+ const collected = collectCases({ root: directory, globals: true });+ const resolves = (id) => resolveUiEvidence([{ id, cited: id, file: FIXTURE_FILE }], collected).length === 0;++ // The IDs that resolve are exactly the ones the fixture names as running —+ // not a list of the shapes that must fail, which would pass forever while+ // the one shape nobody named went on resolving.+ expect(fixtureIds.filter(resolves).sort()).toEqual(fixtureIds.filter((id) => id.startsWith(RUNS)).sort());+ },+ 60_000,+ );++ it('reports a row whose evidence is absent, duplicated, or in another file', () => {+ const collected = [+ { name: 'suite > MH-ROW-A: runs', file: `/checkout/${FIXTURE_FILE}` },+ { name: 'suite > MH-ROW-B: runs, but in another file', file: '/checkout/other.test.tsx' },+ { name: 'suite > MH-ROW-C: runs', file: `/checkout/${FIXTURE_FILE}` },+ { name: 'suite > MH-ROW-C: runs again', file: `/checkout/${FIXTURE_FILE}` },+ ];+ const row = (id, extra = {}) => ({ id, cited: id, file: FIXTURE_FILE, ...extra });++ expect(resolveUiEvidence([row('MH-ROW-A')], collected)).toEqual([]);+ // Present in the collection, but not in the file the row points at.+ expect(resolveUiEvidence([row('MH-ROW-B')], collected)).toHaveLength(1);+ expect(resolveUiEvidence([row('MH-ROW-C')], collected)).toHaveLength(1);+ expect(resolveUiEvidence([row('MH-ROW-D')], collected)).toHaveLength(1);+ // A row may only resolve through a case named for itself, so it cannot pass+ // by citing a sibling's evidence.+ expect(resolveUiEvidence([row('MH-ROW-D', { cited: 'MH-ROW-A' })], collected)).toHaveLength(1);+ });++ it('asks about a row only when its declared status requires a test', () => {+ const catalog = {+ status_legend: { covered: { test_required: true }, gap: { test_required: false } },+ scenarios: [+ { id: 'MH-UI', status: 'covered', test: 'ui/src/a.test.tsx::MH-UI' },+ { id: 'MH-SCRIPT', status: 'covered', test: 'ui/scripts/a.test.mjs::MH-SCRIPT' },+ { id: 'MH-PY', status: 'covered', test: 'tests/test_a.py::test_a' },+ { id: 'MH-GAP', status: 'gap', test: null },+ ],+ };++ expect(uiEvidenceRows(catalog).map((row) => row.id)).toEqual(['MH-UI', 'MH-SCRIPT']);+ expect(isUiEvidence('tests/test_a.py::test_a')).toBe(false);+ });+});diff --git a/ui/scripts/validate-scenario-catalog.mjs b/ui/scripts/validate-scenario-catalog.mjsnew file mode 100644index 000000000..7bcc22f26--- /dev/null+++ b/ui/scripts/validate-scenario-catalog.mjs@@ -0,0 +1,65 @@+#!/usr/bin/env node+/**+ * Gate: every scenario-catalog row evidenced by a UI case resolves to exactly one+ * case vitest collects, in the file the row cites.+ *+ * This runs from `npm test`, which is the UI suite's own CI step, because that is+ * where the collector lives. The Python catalog checker owns everything it can+ * answer exactly — the row's shape, its file, and the ID being greppable inside+ * that file — and defers executability here rather than approximating it.+ */++import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import yaml from 'js-yaml';++import { collectCases, resolveUiEvidence, uiEvidenceRows } from './scenarioCatalog.mjs';++const UI_ROOT = fileURLToPath(new URL('..', import.meta.url));+const REPO_ROOT = path.resolve(UI_ROOT, '..');+const SCENARIO_ROOT = path.join(REPO_ROOT, 'tests', 'scenarios');++/**+ * Every capability catalog in the checkout.+ *+ * Discovered rather than listed: a catalog that starts citing UI evidence is+ * gated by existing, and no list has to be remembered. A checkout without the+ * directory at all is a failure, not an empty pass — this gate cannot report+ * "nothing to check" for the one input it exists to read.+ */+const catalogPaths = () => {+ if (!fs.existsSync(SCENARIO_ROOT)) {+ throw new Error(`${path.relative(REPO_ROOT, SCENARIO_ROOT)} is missing; run this from a full checkout`);+ }+ return fs+ .readdirSync(SCENARIO_ROOT, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .map((entry) => path.join(SCENARIO_ROOT, entry.name, 'catalog.yaml'))+ .filter((file) => fs.existsSync(file));+};++const main = () => {+ const rows = catalogPaths().flatMap((file) => {+ const catalog = yaml.load(fs.readFileSync(file, 'utf8'));+ return uiEvidenceRows(catalog).map((row) => ({ ...row, catalog: path.relative(REPO_ROOT, file) }));+ });+ if (rows.length === 0) {+ console.log('scenario catalogs: no rows are evidenced by a UI case');+ return;+ }++ const files = [...new Set(rows.map((row) => path.relative(UI_ROOT, path.join(REPO_ROOT, row.file))))];+ const problems = resolveUiEvidence(rows, collectCases({ files }));+ if (problems.length > 0) {+ console.error(`\nUI-evidenced scenario rows that do not resolve to a collected vitest case:\n`);+ for (const problem of problems) console.error(` - ${problem}`);+ console.error('');+ process.exitCode = 1;+ return;+ }+ console.log(`scenario catalogs: ${rows.length} UI-evidenced rows resolve to a collected vitest case`);+};++main();diff --git a/ui/src/components/settings/models/UsageTab.test.tsx b/ui/src/components/settings/models/UsageTab.test.tsxindex 3b198d49c..b83186267 100644--- a/ui/src/components/settings/models/UsageTab.test.tsx+++ b/ui/src/components/settings/models/UsageTab.test.tsx@@ -157,6 +157,19 @@ describe('UsageTab', () => {]);});+ it('MH-USAGE-023: states every day of the window in text, not only in a pointer tooltip', () => {+ const { container } = draw(readyRegion(summary()));+ const chart = screen.getByRole('img', { name: /Metered tokens per day/ });+ const tooltips = [...container.querySelectorAll('.model-hub-usage-track')].map((track) => track.getAttribute('title'));++ // A `title` opens on hover alone, and the chart is one image whose columns+ // assistive tech never enumerates — so the same readouts have to exist as+ // text outside it. Asserted against the tooltips rather than against a list+ // of days: the two readings cannot disagree, whatever the window holds.+ const items = [...container.querySelectorAll('li')].filter((item) => !chart.contains(item));+ expect(items.map((item) => item.textContent)).toEqual(tooltips);+ });+it('keeps the last report on screen while a new one is read, and claims no failure', () => {const { container } = draw(degradedRegion(summary(), 'refreshing', false));expect(container.textContent).toContain('Contract source');diff --git a/ui/src/components/settings/models/UsageTab.tsx b/ui/src/components/settings/models/UsageTab.tsxindex bf931c236..55bb57f75 100644--- a/ui/src/components/settings/models/UsageTab.tsx+++ b/ui/src/components/settings/models/UsageTab.tsx@@ -203,6 +203,14 @@ const ByDayPanel: React.FC<{ summary: UsageSummary }> = ({ summary }) => {const peak = columns.reduce<UsageDayColumn | null>((best, column) => (column.tokens > (best?.tokens ?? 0) ? column : best), null);const metered = columns.some(usageDayIsMetered);const day = (value: string) => formatLocalDay(value, i18n.language);+ // One day's figures, in the one wording both the pointer tooltip and the list+ // below read from — a second phrasing would be a second answer to drift from.+ const readout = (column: UsageDayColumn) =>+ t('settings.models.usage.byDay.column', {+ day: day(column.day),+ tokens: count(column.tokens),+ requests: count(column.requests),+ }) as string;return (<section className="model-hub-usage-card overflow-hidden rounded-xl border border-border bg-background"><h3 className="model-hub-usage-card-head model-hub-usage-section-title border-b border-border font-semibold text-foreground">@@ -218,7 +226,7 @@ const ByDayPanel: React.FC<{ summary: UsageSummary }> = ({ summary }) => {<divkey={column.day}className="model-hub-usage-track flex flex-1 items-end"- title={t('settings.models.usage.byDay.column', { day: day(column.day), tokens: count(column.tokens), requests: count(column.requests) }) as string}+ title={readout(column)}>{/* A metered day is floored to a visible sliver so the quietest onestill reads as activity — including one whose tokens never came@@ -229,6 +237,17 @@ const ByDayPanel: React.FC<{ summary: UsageSummary }> = ({ summary }) => {</div>))}</div>+ {/* Every day's figures, in text. A pointer tooltip is the one readout a+ keyboard or screen-reader user cannot open, and `role="img"` above+ hides the columns from assistive tech by design — so the series is+ also a list, and the axis stops being the only reachable reading of+ it. Sibling rather than child: inside the image it would be hidden+ with everything else. */}+ <ul className="sr-only">+ {columns.map((column) => (+ <li key={column.day}>{readout(column)}</li>+ ))}+ </ul><div className="model-hub-usage-axis flex items-baseline justify-between gap-3"><span className="truncate">{day(summary.from_day)}</span><span className="model-hub-usage-peak truncate">