Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

test(model-hub): resolve UI catalog evidence by ID in the vitest case name

cyh59571820970a
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.md
index 5a07b21b5..726d5ab6a 100644
--- a/docs/plans/model-hub-usage-metering.md
+++ b/docs/plans/model-hub-usage-metering.md
@@ -1068,10 +1068,25 @@ own.
**Catalog.** `tests/scenarios/model_hub/test_model_hub_catalog.py` previously
resolved a row's evidence with `ast.parse`, so the capability's user-visible half
-could not be registered at all. It now resolves a `.ts`/`.tsx` row by slicing the
-named `it(...)` case and requiring the catalog ID inside that case — the same
-per-row greppability the Python docstring rule gives, rather than a per-file
-approximation.
+could not be registered at all. A `.ts`/`.tsx` row now cites its own ID
+(`…/UsageTab.test.tsx::MH-USAGE-018`) and resolves to the single executable
+`it('MH-USAGE-018: …')` declaration that carries it. A vitest case's name is its
+docstring, so that is where the ID belongs — the same per-row greppability the
+Python docstring rule gives, and the evidence is runnable by ID
+(`vitest -t MH-USAGE-018`) rather than only greppable.
+
+The first version of this checker sliced each case's body instead and asked whether
+the ID appeared inside the slice. Two properties are why it was replaced rather than
+patched. Deciding where a case *ends* needs balanced delimiters, and a scan that
+small cannot tell a regex literal from division — so `/Couldn't refresh/i`, ordinary
+in this suite, read as a string opening and the slice swallowed eight sibling cases.
+And its guard against exactly that (re-parse the slice, require one declaration) ran
+the same scan, so the desync agreed with itself and passed. Reading only names
+removes the failure instead of guarding it: a wrong guess can lose a declaration,
+which fails the row loudly, but can never hand a row a neighbour's ID. Verified
+against vitest's own collection over the whole Model Hub UI suite — 873 collected
+cases, every unresolved one a parameterized `it.each` whose name does not exist in
+the source, and nothing resolved that vitest does not run.
**Dead 额度 code removed with the rename.** Copy: `settings.models.usage.monthSpend`,
`settings.models.usageTab`, and `settings.models.tabs` (a zero-caller duplicate of
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 43027f94f..82f1cd52d 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -44,6 +44,12 @@ scenarios:
kind: contract
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_catalog.py::test_mh_catalog_001_scenario_catalog_is_complete_and_executable
+ - id: MH-CATALOG-002
+ name: A UI-evidenced row resolves only to a vitest case that runs under its catalog ID
+ status: covered
+ kind: contract
+ layer: unit
+ test: tests/scenarios/model_hub/test_model_hub_catalog.py::test_mh_catalog_002_ui_evidence_resolves_only_to_an_executable_declaration
- id: MH-S1-001
name: Live conditions never change the exact configured hop identity
status: covered
@@ -218,31 +224,31 @@ scenarios:
status: covered
kind: contract
layer: unit
- test: ui/src/components/settings/models/UsageTab.test.tsx::names the window the report was served over, not the one asked for
+ test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-016
- id: MH-USAGE-017
name: A vanished model's ledger key never reaches the screen, while a vanished Source stays identifiable
status: covered
kind: observation
layer: unit
- test: ui/src/components/settings/models/UsageTab.test.tsx::keeps a vanished Source identifiable and a vanished model unnamed
+ test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-017
- id: MH-USAGE-018
name: A token-report shortfall reads as missing reports rather than unused capacity
status: covered
kind: contract
layer: unit
- test: ui/src/components/settings/models/UsageTab.test.tsx::reads a shortfall as reports that never arrived
+ test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-018
- id: MH-USAGE-019
name: A day the window covered without a metered turn is drawn as idle rather than closed over
status: covered
kind: observation
layer: unit
- test: ui/src/components/settings/models/UsageTab.test.tsx::plots every day of the window, including the ones that carried nothing
+ test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-019
- id: MH-USAGE-020
name: The usage report is read when its tab is opened, never as part of the routing surface's first paint
status: covered
kind: observation
layer: unit
- test: ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::leaves the report unread until its tab is opened, then reads the default span
+ test: ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-USAGE-020
- id: MH-RES-LIVE-001
name: Live turn retries an eligible backup before streaming starts
status: covered
diff --git a/tests/scenarios/model_hub/test_model_hub_catalog.py b/tests/scenarios/model_hub/test_model_hub_catalog.py
index b8fed03fb..1bf448dde 100644
--- a/tests/scenarios/model_hub/test_model_hub_catalog.py
+++ b/tests/scenarios/model_hub/test_model_hub_catalog.py
@@ -3,8 +3,10 @@
from __future__ import annotations
import ast
+import re
from pathlib import Path
+import pytest
import yaml
@@ -12,6 +14,11 @@ 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*(?=['\"`])")
+
def _document(name: str) -> dict:
return yaml.safe_load((SCENARIO_ROOT / name).read_text())
@@ -38,25 +45,157 @@ def _test_function(path: Path, function_name: str) -> ast.FunctionDef | ast.Asyn
return function
-def _vitest_case(path: Path, case_name: str) -> str:
- """One `it(...)` case's own source.
+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.
- 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 exists, and that case must name its catalog ID where a
- Python test would carry a docstring. Slicing the case out is what makes the ID
- check per-row instead of per-file, so a second row cannot ride on the first
- one'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.
"""
- source = path.read_text()
- start = next(
- (found for quote in ("'", '"') if (found := source.find(f"it({quote}{case_name}{quote}")) != -1),
- -1,
+ 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"
)
- assert start != -1, f"Catalog points to missing UI case {path}::{case_name}"
- end = source.find("\n it(", start + 1)
- return source[start:] if end == -1 else source[start:end]
+ return names[0]
def _decorator_names(function: ast.FunctionDef | ast.AsyncFunctionDef) -> set[str]:
@@ -96,12 +235,14 @@ def test_mh_catalog_001_scenario_catalog_is_complete_and_executable() -> None:
assert path_text in canonical_tests
assert path.is_file()
if path.suffix in {".ts", ".tsx"}:
- # This checker cannot read a vitest modifier, so a UI-evidenced row may
- # not claim an expected failure it has no way to prove.
+ # Only the bare `it(` form resolves, so a UI-evidenced row has no way to
+ # declare an expected failure and 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"
)
- evidence = _vitest_case(path, function_name)
+ # 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)
else:
function = _test_function(path, function_name)
expected_fail = "xfail" in _decorator_names(function)
@@ -109,7 +250,8 @@ def test_mh_catalog_001_scenario_catalog_is_complete_and_executable() -> None:
evidence = ast.get_docstring(function) or ""
assert scenario["id"] in evidence, (
f"Scenario {scenario['id']} is not named inside {test_ref}; "
- "state the catalog ID in the test docstring so the executable evidence is greppable by ID"
+ "state the catalog ID in the test docstring — for a UI case, in its name — "
+ "so the executable evidence is greppable by ID"
)
if scenario["status"] == "partial":
missing_layer = scenario.get("missing_layer")
@@ -137,3 +279,58 @@ 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/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 122ee5ac1..818bc7298 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -926,13 +926,13 @@ describe('SettingsModelsPage surface branches', () => {
describe('SettingsModelsPage usage region', () => {
const openUsage = () => userEvent.click(screen.getByRole('tab', { name: /^Usage$|^用量$/ }));
- it('leaves the report unread until its tab is opened, then reads the default span', async () => {
+ it('MH-USAGE-020: leaves the report unread until its tab is opened, then reads the default span', async () => {
renderPage([retainedSource]);
await screen.findByText('Retained source');
const read = vi.mocked(modelsApi.getUsageSummary);
- // MH-USAGE-020. The landing is what decides routing. A report nobody is
- // looking at may not be part of the read that draws it.
+ // The landing is what decides routing. A report nobody is looking at may
+ // not be part of the read that draws it.
expect(read).not.toHaveBeenCalled();
await openUsage();
await waitFor(() => expect(read).toHaveBeenCalledWith(30));
diff --git a/ui/src/components/settings/models/UsageTab.test.tsx b/ui/src/components/settings/models/UsageTab.test.tsx
index 4c325ab33..f7dadff51 100644
--- a/ui/src/components/settings/models/UsageTab.test.tsx
+++ b/ui/src/components/settings/models/UsageTab.test.tsx
@@ -76,17 +76,17 @@ const draw = (
afterEach(cleanup);
describe('UsageTab', () => {
- it('names the window the report was served over, not the one asked for', () => {
- // MH-USAGE-016. The server clamps `days` to retention and answers with what
- // it covered. Printing the request back would caption a 62-day report as 7.
+ it('MH-USAGE-016: names the window the report was served over, not the one asked for', () => {
+ // The server clamps `days` to retention and answers with what it covered.
+ // Printing the request back would caption a 62-day report as 7.
const { container } = draw(readyRegion(summary({ window_days: 62 })), { windowDays: 7 });
expect(container.textContent).toContain('trailing 62 days');
expect(container.textContent).not.toContain('trailing 7 days');
});
- it('keeps a vanished Source identifiable and a vanished model unnamed', () => {
- // MH-USAGE-017. Asymmetric by contract: `src_*` is a string the user could
- // have seen elsewhere, a ledger key is a digest nobody typed.
+ it('MH-USAGE-017: keeps a vanished Source identifiable and a vanished model unnamed', () => {
+ // Asymmetric by contract: `src_*` is a string the user could have seen
+ // elsewhere, a ledger key is a digest nobody typed.
const key = 'claude-opus-4-6-20260514-thinking#9f2c1d';
const { container } = draw(
readyRegion(summary({ sources: [source({ label: null, models: [model({ label: null, model_id: key })] })] })),
@@ -98,9 +98,9 @@ describe('UsageTab', () => {
expect(container.textContent).not.toContain('9f2c1d');
});
- it('reads a shortfall as reports that never arrived', () => {
- // MH-USAGE-018. The schema forbids the other reading outright: the gap
- // between requests and token reports is missing evidence, never spare quota.
+ it('MH-USAGE-018: reads a shortfall as reports that never arrived', () => {
+ // The schema forbids the other reading outright: the gap between requests
+ // and token reports is missing evidence, never spare quota.
const { container } = draw(readyRegion(summary({ totals: counters({ requests: 12, token_reports: 9 }) })));
expect(container.textContent).toContain('3 requests came back with no token report');
expect(container.textContent).not.toContain(en.settings.models.usage.requests.reported);
@@ -118,9 +118,9 @@ describe('UsageTab', () => {
expect(container.textContent).not.toContain(en.settings.models.usage.byDay.title);
});
- it('plots every day of the window, including the ones that carried nothing', () => {
- // MH-USAGE-019. One reported day inside a 30-day span. Drawing `days[]`
- // directly would close the gap and read as a month of continuous traffic.
+ it('MH-USAGE-019: plots every day of the window, including the ones that carried nothing', () => {
+ // One reported day inside a 30-day span. Drawing `days[]` directly would
+ // close the gap and read as a month of continuous traffic.
const { container } = draw(readyRegion(summary()));
expect(container.querySelectorAll('.model-hub-usage-track')).toHaveLength(30);
expect(screen.getByRole('img', { name: /Metered tokens per day/ })).toBeTruthy();