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.

fix(model-hub): gate every cited UI case, and name the column of every figure

cyh28baeb512c32
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.md
index 0cb80a145..0ab62adfa 100644
--- a/docs/plans/model-hub-usage-metering.md
+++ b/docs/plans/model-hub-usage-metering.md
@@ -1208,3 +1208,77 @@ rendered as a *sibling* of the image (inside it, it would be hidden with everyth
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.
+
+### Stage 2, round 4 (head `82c46d5a0`) — breaker tripped again
+
+Two P2 findings, **both class repeats**, so the breaker trips a second time and both
+closures are made at the class owner rather than at the flagged site.
+
+| Class | Heads | What recurs |
+| --- | --- | --- |
+| A | 1, 3, 4 | A row can read `covered` while nothing executable backs it |
+| B | 3, 4 | The report states per-row figures through visual position alone |
+
+**Class A — the gate asked one catalog and passed three in silence.** Round 3's gate
+selected rows through each catalog's own `status_legend`, and `status_legend` maps a status
+to a *description string* in every catalog here but `model_hub`. Reading `test_required`
+off a string yields `undefined`, so `harness_command_task`, `memory_list`, and
+`message_delivery` contributed zero rows — the gate reported a clean 9/9 while three
+catalogs went unasked. That is the same failure the gate exists to prevent, one level up.
+
+The reviewer proposed normalizing the scalar legends. Rejected: inferring `test_required`
+from prose (`'deterministic scenario or contract coverage exists'` → true?) is a heuristic
+over English, the exact species of thing round 3 deleted from the Python side. **A row that
+*cites* a UI file must resolve, whatever its legend looks like** — simpler and strictly
+stronger. A citation is the row's own claim, exists in every catalog, and no legend shape
+can switch it off. Coverage went 9 rows / 1 catalog → 20 rows / 4 catalogs; collection
+still rides `npm test`, 1.7 s.
+
+Three citation shapes now resolve under one rule, because one notion (prefix) is what they
+have in common — a rule per catalog would be a policy each new catalog could contradict:
+
+| Shape | Written as | Resolves against |
+| --- | --- | --- |
+| Catalog ID | `path::MH-USAGE-024` | the case's own name |
+| Readable full name | `path::taskCommandPreview quotes an argv part …` | the full name with `' > '` flattened to `' '` |
+| File only | `path` | the file being collected at all |
+
+Two shapes that resolve to a running case and still prove nothing are rejected explicitly: a
+row citing a **sibling row's ID** (checked against the whole catalog's ID set, including
+pytest-evidenced rows), and a file-only citation whose file collects nothing.
+
+The gate immediately caught a real pre-existing defect it had been unable to see:
+`harness_command_task` **SCT-016** was `covered` on `taskCommandPreview quotes argv the way
+the shell would read it back`, a case name that no longer exists. Re-pointed to the live
+case; the row's claim was true, its citation had rotted.
+
+**Class B — one mechanism for every panel of per-row figures.** Round 3 answered the by-day
+chart with an `sr-only` sentence per day; head 4 flagged the by-source table, whose figures
+were unattributed `<span>`s in a CSS grid. Answering the second panel with a second
+mechanism invites a fifth round, so both panels now carry the same structure.
+
+Why roles and not a native `<table>` for the visible panel: the layout is a CSS grid
+(`--model-hub-usage-columns`) that collapses to one column below 767px, and a `<table>` can
+only stack through a `display` override — overriding `display` is exactly what strips the
+native table semantics it was chosen for. Explicit roles are unaffected by `display` and
+keep both the grid and the structure at every width. The by-day list became an `sr-only`
+native `<table>` (Tailwind's `sr-only` does not touch `display`), so the tab has one answer
+for "figures need row and column association" instead of two.
+
+A figure's column is **its position in its row** — which is what makes the header row an
+answer rather than decoration, in an ARIA table exactly as in a native one — and the cell
+repeats its header as a `md:hidden` label for the width where the header row is `display:none`.
+Between them the two cover both widths, so a per-cell `aria-colindex` restates what position
+already says; it earns its keep only for a row that skips a *middle* column, and the model
+row's empty `lastMetered` cell is the simpler way to not have one. Mutation-checked before
+deciding: dropping `aria-colindex` changed no observable association and no assertion, so it
+went.
+
+MH-USAGE-023 is reframed against the table (its `<li>`s are gone), still deriving every
+expectation from the tooltips so the two readings of a day cannot answer differently.
+MH-USAGE-024 is the class property, asked of *whatever* tables the tab renders: every body
+row has exactly one row header, states as many figures as there are columns (no row ends
+early and shifts the ones before it), and — where the headers can leave the accessibility
+tree — labels every figure with the header at its own position. Four mutations were run
+against it and all four fail: dropping `role="table"`, removing the model row's placeholder
+cell, removing the stacked labels, and reordering `SOURCE_COLUMNS`.
diff --git a/tests/scenarios/harness_command_task/catalog.yaml b/tests/scenarios/harness_command_task/catalog.yaml
index ce49ce585..33ba56660 100644
--- a/tests/scenarios/harness_command_task/catalog.yaml
+++ b/tests/scenarios/harness_command_task/catalog.yaml
@@ -132,7 +132,7 @@ scenarios:
kind: config
layer: unit
backend: shared
- test: ui/src/components/workbench/harnessLifecycle.test.ts::taskCommandPreview quotes argv the way the shell would read it back
+ test: ui/src/components/workbench/harnessLifecycle.test.ts::taskCommandPreview quotes an argv part that would otherwise lose its boundary
- id: SCT-017
name: a fire that produced no exit code clears the one the last fire left
status: covered
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index aaba590c8..ecc00a2fb 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -270,6 +270,12 @@ scenarios:
kind: observation
layer: unit
test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-023
+ - id: MH-USAGE-024
+ name: Every figure in the usage report names the row and the column it answers, not a position on screen
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-024
- id: MH-RES-LIVE-001
name: Live turn retries an eligible backup before streaming starts
status: covered
diff --git a/ui/scripts/scenarioCatalog.mjs b/ui/scripts/scenarioCatalog.mjs
index e9df23d82..cfbc4fa48 100644
--- a/ui/scripts/scenarioCatalog.mjs
+++ b/ui/scripts/scenarioCatalog.mjs
@@ -1,7 +1,7 @@
/**
* 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
+ * A row that cites a test claims one executable case carries it. 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
@@ -35,24 +35,39 @@ 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.
+ * Every catalog row whose evidence is a UI case, whatever its legend looks like.
*
- * 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.
+ * The row set is the rows that *cite* a UI file, never the rows a legend marks as
+ * needing a test. `status_legend` maps a status to a description string in every
+ * catalog here but one, so reading `test_required` off it selected the rows of
+ * that single catalog and passed the other three in silence — the same failure
+ * this gate exists to prevent, one level up. A citation is the row's own claim,
+ * exists in every catalog, and no legend shape can switch it off.
+ *
+ * `cited` is null for a row that names a file and no case in it.
*/
-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))
+export const uiEvidenceRows = (catalog) =>
+ (catalog.scenarios ?? [])
+ .filter((row) => typeof row.test === 'string' && isUiEvidence(row.test))
.map((row) => {
- const [file, cited] = row.test.split('::');
+ const [file, cited = null] = 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);
+/**
+ * The names a citation may be written against: the case's own, and its full path
+ * with vitest's separator flattened to the space the catalogs write instead.
+ *
+ * Two conventions are in use — a catalog ID that the case name begins with, and
+ * the case's readable full name — and both are a prefix of one of these. One
+ * matching rule covers them because that is what they have in common, rather
+ * than a rule per catalog, which is a policy each new catalog could contradict.
+ */
+const citableNames = (entry) => [caseName(entry.name), entry.name.replaceAll(' > ', ' ')];
+
const sameFile = (collectedFile, file) => {
const normalized = collectedFile.replaceAll('\\', '/');
return normalized === file || normalized.endsWith(`/${file}`);
@@ -60,28 +75,40 @@ const sameFile = (collectedFile, 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.
+ * every citation resolves to a case the suite would execute.
*
* 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.
+ *
+ * `ids` is the whole catalog's ID set, which is what makes a borrowed citation
+ * legible: a row naming a *sibling row's* ID resolves to a real running case and
+ * still has no evidence of its own.
*/
-export const resolveUiEvidence = (rows, collected) => {
+export const resolveUiEvidence = (rows, collected, ids = new Set(rows.map((row) => row.id))) => {
const problems = [];
for (const row of rows) {
- if (row.cited !== row.id) {
+ const where = row.catalog ? `${row.catalog} ${row.id}` : row.id;
+ const inFile = collected.filter((entry) => sameFile(entry.file, row.file));
+ if (row.cited === null) {
+ // The row cites a file and names no case inside it, so the only claim there
+ // is to check is the one it makes: that vitest executes that file. Which
+ // case carries the row is the catalog's to say, and this one does not say.
+ if (inFile.length === 0) {
+ problems.push(`${where}: vitest collects no case from ${row.file}, so the file it cites is not executable evidence`);
+ }
+ continue;
+ }
+ if (row.cited !== row.id && ids.has(row.cited)) {
problems.push(
- `${row.id} cites \`${row.cited}\` as its evidence; a UI row resolves through a case named for the row itself`,
+ `${where} cites \`${row.cited}\`, which is another row's ID; a row resolves through evidence named for itself`,
);
continue;
}
- const prefix = `${row.id}:`;
- const matches = collected.filter(
- (entry) => sameFile(entry.file, row.file) && caseName(entry.name).startsWith(prefix),
- );
+ const matches = inFile.filter((entry) => citableNames(entry).some((name) => name.startsWith(row.cited)));
if (matches.length !== 1) {
problems.push(
- `${row.id}: vitest collects ${matches.length} cases named \`${prefix} …\` in ${row.file}, expected exactly one — `
+ `${where}: vitest collects ${matches.length} cases named \`${row.cited}…\` in ${row.file}, expected exactly one — `
+ 'a commented-out, skipped, parameterized, unreachable or merely quoted case is not executable evidence',
);
}
diff --git a/ui/scripts/scenarioCatalog.test.mjs b/ui/scripts/scenarioCatalog.test.mjs
index 9bc5bbcd7..5fec6c0ed 100644
--- a/ui/scripts/scenarioCatalog.test.mjs
+++ b/ui/scripts/scenarioCatalog.test.mjs
@@ -86,6 +86,7 @@ describe('UI evidence resolution', () => {
{ 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}` },
+ { name: 'TaskDetail > command task > states the timeout', file: `/checkout/${FIXTURE_FILE}` },
];
const row = (id, extra = {}) => ({ id, cited: id, file: FIXTURE_FILE, ...extra });
@@ -94,23 +95,37 @@ describe('UI evidence resolution', () => {
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);
+ // A row may only resolve through evidence named for itself, so it cannot pass
+ // by citing a sibling's — which is a citation that does resolve, to a case
+ // that is another row's answer.
+ const ids = new Set(['MH-ROW-A', 'MH-ROW-D']);
+ expect(resolveUiEvidence([row('MH-ROW-D', { cited: 'MH-ROW-A' })], collected, ids)).toHaveLength(1);
+ // The other convention in the checkout: the case's readable full name, which
+ // the catalogs write with vitest's separator flattened to a space.
+ expect(resolveUiEvidence([row('SCT-018', { cited: 'TaskDetail command task states the timeout' })], collected)).toEqual([]);
+ // A row that names a file and no case in it claims only that the file runs.
+ expect(resolveUiEvidence([row('MH-ROW-E', { cited: null })], collected)).toEqual([]);
+ expect(resolveUiEvidence([row('MH-ROW-E', { cited: null, file: 'absent.test.tsx' })], 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 },
- ],
- };
+ it('asks about every row that cites a UI file, whatever its legend looks like', () => {
+ // The legend shape is the hole this closes: `status_legend` is a description
+ // string in every catalog but one, so selecting rows by `test_required` asked
+ // about one catalog and passed the rest without saying so. A citation is the
+ // row's own claim and reads the same in both shapes.
+ const 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-FILE', status: 'covered', test: 'ui/src/b.test.tsx' },
+ { id: 'MH-PY', status: 'covered', test: 'tests/test_a.py::test_a' },
+ { id: 'MH-GAP', status: 'gap', test: null },
+ ];
+ const asked = ['MH-UI', 'MH-SCRIPT', 'MH-FILE'];
- expect(uiEvidenceRows(catalog).map((row) => row.id)).toEqual(['MH-UI', 'MH-SCRIPT']);
+ expect(uiEvidenceRows({ status_legend: { covered: { test_required: true } }, scenarios }).map((row) => row.id)).toEqual(asked);
+ expect(uiEvidenceRows({ status_legend: { covered: 'executable evidence exists' }, scenarios }).map((row) => row.id)).toEqual(asked);
+ expect(uiEvidenceRows({ scenarios }).map((row) => row.id)).toEqual(asked);
+ expect(uiEvidenceRows({ scenarios }).find((row) => row.id === 'MH-FILE').cited).toBe(null);
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.mjs
index 7bcc22f26..cb9f80a26 100644
--- a/ui/scripts/validate-scenario-catalog.mjs
+++ b/ui/scripts/validate-scenario-catalog.mjs
@@ -41,17 +41,27 @@ const catalogPaths = () => {
};
const main = () => {
- const rows = catalogPaths().flatMap((file) => {
+ const catalogs = catalogPaths().map((file) => {
const catalog = yaml.load(fs.readFileSync(file, 'utf8'));
- return uiEvidenceRows(catalog).map((row) => ({ ...row, catalog: path.relative(REPO_ROOT, file) }));
+ const name = path.relative(REPO_ROOT, file);
+ return {
+ // The whole ID set, not just the UI rows': a UI row may borrow the ID of a
+ // row evidenced by pytest, and that is the same empty citation.
+ ids: new Set((catalog.scenarios ?? []).map((row) => row.id)),
+ rows: uiEvidenceRows(catalog).map((row) => ({ ...row, catalog: name })),
+ };
});
+ const rows = catalogs.flatMap((catalog) => catalog.rows);
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 }));
+ // One collection for every catalog: `list` costs a vitest startup, and the
+ // question each row asks is answered by the same collected set.
+ const collected = collectCases({ files });
+ const problems = catalogs.flatMap((catalog) => resolveUiEvidence(catalog.rows, collected, catalog.ids));
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}`);
diff --git a/ui/src/components/settings/models/UsageTab.test.tsx b/ui/src/components/settings/models/UsageTab.test.tsx
index b83186267..1d9093e7a 100644
--- a/ui/src/components/settings/models/UsageTab.test.tsx
+++ b/ui/src/components/settings/models/UsageTab.test.tsx
@@ -4,7 +4,7 @@
// the tab could make that the payload does not support — a span it was not
// served, an identity it cannot render, an empty window drawn as zeroes, or a
// shortfall presented as spare capacity.
-import { cleanup, render, screen } from '@testing-library/react';
+import { cleanup, render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createInstance } from 'i18next';
import { I18nextProvider, initReactI18next } from 'react-i18next';
@@ -73,6 +73,16 @@ const draw = (
</I18nextProvider>,
);
+/** A table's rows that carry figures — the ones headed by a row rather than by a column. */
+const bodyRows = (table: HTMLElement) =>
+ within(table).getAllByRole('row').filter((row) => within(row).queryAllByRole('rowheader').length > 0);
+
+/**
+ * One row's stated figures, its row header first — which is the order that decides
+ * which column each of them answers.
+ */
+const figures = (row: HTMLElement) => [...within(row).getAllByRole('rowheader'), ...within(row).getAllByRole('cell')];
+
afterEach(cleanup);
describe('UsageTab', () => {
@@ -159,15 +169,78 @@ 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'));
+ 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);
+ // assistive tech never enumerates — so the same three figures have to exist
+ // as cells outside it. Read out of the tooltips rather than out of a list of
+ // days: the two readings of a day cannot disagree, whatever the window holds.
+ const rows = bodyRows(screen.getByRole('table', { name: /Metered tokens and requests per day/ }));
+ expect(rows).toHaveLength(tooltips.length);
+ rows.forEach((row, index) => {
+ const said = tooltips[index].split(' · ');
+ const stated = figures(row).map((figure) => figure.textContent ?? '');
+ expect(stated).toHaveLength(said.length);
+ stated.forEach((text, column) => expect(said[column]).toContain(text));
+ });
+ });
+
+ it('MH-USAGE-024: every figure the report states names the row and the column it answers', () => {
+ // The class this closes: a per-row figure stated by visual position alone,
+ // which no reader who cannot see the layout can recover. Asked of whatever
+ // tables the tab renders rather than of a list of them, so a third panel of
+ // figures is covered by existing instead of by an edit here.
+ const { container } = draw(readyRegion(summary({
+ sources: [
+ source({ models: [model({ model_id: 'claude-opus-4-6', label: 'claude-opus-4-6' })] }),
+ // The ragged shape: a Source with no metering timestamp, over a model that
+ // has none by definition. Both stop before the last column.
+ source({
+ source_id: 'src_probe002',
+ label: 'Probe source',
+ last_metered_at: null,
+ models: [model({ model_id: 'claude-haiku-4-5', label: 'claude-haiku-4-5' })],
+ }),
+ ],
+ })));
+
+ const named: string[] = [];
+ for (const table of screen.getAllByRole('table')) {
+ const headers = within(table).getAllByRole('columnheader');
+ expect(headers.length).toBeGreaterThan(1);
+ // Whether this table's headers can leave the accessibility tree, which is
+ // what decides whether position alone is enough. jsdom loads no stylesheet,
+ // so the class is the only readable statement of it.
+ const stacks = /(^|\s)hidden(\s|$)/.test(headers[0].parentElement?.className ?? '');
+ const rows = bodyRows(table);
+ expect(rows.length).toBeGreaterThan(0);
+ for (const row of rows) {
+ const heads = within(row).getAllByRole('rowheader');
+ expect(heads).toHaveLength(1);
+ named.push(heads[0].textContent ?? '');
+ const stated = figures(row);
+ // A figure answers the column it sits in, so no row may end early: the
+ // model row has no metering timestamp of its own and holds that column
+ // open with an empty cell rather than shifting the ones before it under
+ // the wrong header.
+ expect(stated).toHaveLength(headers.length);
+ stated.forEach((figure, column) => {
+ const label = figure.querySelector('.model-hub-usage-cell-label');
+ // Where the headers go, the cell's own label is the association that
+ // stays — so every figure that states something has to carry one, and it
+ // has to name the column the figure sits in. Two statements about one
+ // cell, which a drifting column order would answer differently.
+ if (stacks && figure !== heads[0] && figure.textContent !== '') expect(label).not.toBeNull();
+ if (label !== null) expect(label.textContent).toBe(headers[column].textContent);
+ });
+ }
+ }
+
+ // …and the rows are the whole report's, not the subset that happens to render:
+ // every Source, every model under it, and every day the chart draws.
+ const days = container.querySelectorAll('.model-hub-usage-track').length;
+ expect(named).toHaveLength(4 + days);
+ expect(named).toEqual(expect.arrayContaining(['Contract source', 'Probe source', 'claude-opus-4-6', 'claude-haiku-4-5']));
});
it('keeps the last report on screen while a new one is read, and claims no failure', () => {
diff --git a/ui/src/components/settings/models/UsageTab.tsx b/ui/src/components/settings/models/UsageTab.tsx
index 55bb57f75..34acb3cfe 100644
--- a/ui/src/components/settings/models/UsageTab.tsx
+++ b/ui/src/components/settings/models/UsageTab.tsx
@@ -67,19 +67,39 @@ const RowIdentity: React.FC<{ identity: UsageIdentity; goneKey: string }> = ({ i
};
/**
- * One measured cell.
+ * The by-source table's columns, in the order the rows state them.
*
- * The label is carried on the cell rather than only in the header because the
- * header is the first thing that goes when the surface narrows — the row keeps
- * its own labels there, so a stacked cell is still a labelled number instead of
- * an unattributed one.
+ * One list, read by the header row and by every cell's own label, so the two
+ * cannot come to name a column differently.
*/
-const Cell: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (
- <span className="model-hub-usage-cell flex items-baseline justify-between gap-2 md:justify-end">
- <span className="model-hub-usage-cell-label md:hidden">{label}</span>
- <span className="min-w-0 truncate">{children}</span>
- </span>
-);
+const SOURCE_COLUMNS = ['source', 'tokens', 'requests', 'cached', 'lastMetered'] as const;
+
+type SourceColumn = (typeof SOURCE_COLUMNS)[number];
+
+const columnLabel = (column: SourceColumn) => `settings.models.usage.bySource.col.${column}`;
+
+/**
+ * One measured cell, told which column it answers.
+ *
+ * A cell's column is the position it holds in its row, which is what makes the
+ * header row above it an answer and not decoration — so no row may end early: the
+ * model row holds its empty column open below rather than shifting the cells after
+ * it. The label repeats the header on the cell itself because the header is the
+ * first thing that goes when the surface narrows, and a stacked cell has to remain
+ * a labelled number rather than an unattributed one. Between them the two cover
+ * both widths, so a per-cell `aria-colindex` would restate what position already
+ * says; the index earns its keep only for a row that skips a column in the middle,
+ * and holding the place with an empty cell is the simpler way to not have one.
+ */
+const Cell: React.FC<{ column: SourceColumn; children: React.ReactNode }> = ({ column, children }) => {
+ const { t } = useTranslation();
+ return (
+ <span role="cell" className="model-hub-usage-cell flex items-baseline justify-between gap-2 md:justify-end">
+ <span className="model-hub-usage-cell-label md:hidden">{t(columnLabel(column))}</span>
+ <span className="min-w-0 truncate">{children}</span>
+ </span>
+ );
+};
const StatCard: React.FC<{ label: string; value: string; note: string }> = ({ label, value, note }) => (
<div className="model-hub-usage-stat flex flex-col rounded-xl border border-border bg-background">
@@ -127,16 +147,19 @@ const ModelRow: React.FC<{ model: UsageByModel }> = ({ model }) => {
const count = useCount();
const share = usageCachedInputShare(model);
return (
- <div className="model-hub-usage-row model-hub-usage-row--model grid border-t border-border md:items-center">
- <span className="model-hub-usage-model flex min-w-0 items-baseline">
+ <div role="row" className="model-hub-usage-row model-hub-usage-row--model grid border-t border-border md:items-center">
+ <span role="rowheader" className="model-hub-usage-model flex min-w-0 items-baseline">
<RowIdentity identity={modelIdentity(model)} goneKey="settings.models.usage.bySource.goneModel" />
</span>
- <Cell label={t('settings.models.usage.bySource.col.tokens') as string}>{count(usageTotalTokens(model))}</Cell>
- <Cell label={t('settings.models.usage.bySource.col.requests') as string}>{count(model.requests)}</Cell>
- <Cell label={t('settings.models.usage.bySource.col.cached') as string}>
+ <Cell column="tokens">{count(usageTotalTokens(model))}</Cell>
+ <Cell column="requests">{count(model.requests)}</Cell>
+ <Cell column="cached">
{share === null ? (t('settings.models.usage.blank') as string) : formatPercent(share, i18n.language)}
</Cell>
- <span className="hidden md:block" />
+ {/* A model has no metering timestamp of its own; the column stays empty
+ rather than repeating the Source's, and holds its place so every cell
+ before it still sits under the header it answers. */}
+ <span role="cell" className="hidden md:block" />
</div>
);
};
@@ -146,17 +169,19 @@ const SourceRows: React.FC<{ source: UsageBySource }> = ({ source }) => {
const count = useCount();
const share = usageCachedInputShare(source);
return (
- <div className="border-b border-border last:border-b-0">
- <div className="model-hub-usage-row grid md:items-center">
- <span className="model-hub-usage-source flex min-w-0 items-baseline font-semibold text-foreground">
+ // A Source and the models under it are one group of rows, which is also what
+ // the border draws: the group is the unit a reader scans, not each line.
+ <div role="rowgroup" className="border-b border-border last:border-b-0">
+ <div role="row" className="model-hub-usage-row grid md:items-center">
+ <span role="rowheader" className="model-hub-usage-source flex min-w-0 items-baseline font-semibold text-foreground">
<RowIdentity identity={sourceIdentity(source)} goneKey="settings.models.usage.bySource.goneSource" />
</span>
- <Cell label={t('settings.models.usage.bySource.col.tokens') as string}>{count(usageTotalTokens(source))}</Cell>
- <Cell label={t('settings.models.usage.bySource.col.requests') as string}>{count(source.requests)}</Cell>
- <Cell label={t('settings.models.usage.bySource.col.cached') as string}>
+ <Cell column="tokens">{count(usageTotalTokens(source))}</Cell>
+ <Cell column="requests">{count(source.requests)}</Cell>
+ <Cell column="cached">
{share === null ? (t('settings.models.usage.blank') as string) : formatPercent(share, i18n.language)}
</Cell>
- <Cell label={t('settings.models.usage.bySource.col.lastMetered') as string}>
+ <Cell column="lastMetered">
{source.last_metered_at === null ? (t('settings.models.usage.blank') as string) : formatDayTime(source.last_metered_at, i18n.language)}
</Cell>
</div>
@@ -167,19 +192,27 @@ const SourceRows: React.FC<{ source: UsageBySource }> = ({ source }) => {
const BySourcePanel: React.FC<{ summary: UsageSummary }> = ({ summary }) => {
const { t } = useTranslation();
+ const titleId = React.useId();
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">
+ <h3 id={titleId} className="model-hub-usage-card-head model-hub-usage-section-title border-b border-border font-semibold text-foreground">
{t('settings.models.usage.bySource.title')}
</h3>
- <div className="model-hub-usage-head hidden border-b border-border font-semibold md:grid">
- <span className="truncate">{t('settings.models.usage.bySource.col.source')}</span>
- <span className="flex justify-end truncate">{t('settings.models.usage.bySource.col.tokens')}</span>
- <span className="flex justify-end truncate">{t('settings.models.usage.bySource.col.requests')}</span>
- <span className="flex justify-end truncate">{t('settings.models.usage.bySource.col.cached')}</span>
- <span className="flex justify-end truncate">{t('settings.models.usage.bySource.col.lastMetered')}</span>
+ {/* A table by role rather than by tag. The layout is a CSS grid that stacks
+ into labelled lines on a narrow surface, which a `<table>` can only do
+ through a `display` override — and overriding `display` is exactly what
+ strips a table of the semantics it was chosen for. Explicit roles keep
+ the grid and the structure at every width. */}
+ <div role="table" aria-labelledby={titleId}>
+ <div role="row" className="model-hub-usage-head hidden border-b border-border font-semibold md:grid">
+ {SOURCE_COLUMNS.map((column, index) => (
+ <span key={column} role="columnheader" className={index === 0 ? 'truncate' : 'flex justify-end truncate'}>
+ {t(columnLabel(column))}
+ </span>
+ ))}
+ </div>
+ {summary.sources.map((source) => <SourceRows key={source.source_id} source={source} />)}
</div>
- {summary.sources.map((source) => <SourceRows key={source.source_id} source={source} />)}
</section>
);
};
@@ -203,8 +236,9 @@ 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.
+ // One day's figures as a hover readout. The table below states the same three
+ // values in cells, and MH-USAGE-023 derives its expectation from this sentence
+ // so the two readings of a day cannot answer differently.
const readout = (column: UsageDayColumn) =>
t('settings.models.usage.byDay.column', {
day: day(column.day),
@@ -237,17 +271,32 @@ 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>
+ {/* Every day's figures again, as a table. 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
+ needs a second reading, in cells rather than one sentence per day,
+ which is the same per-column association the Source table carries.
+ Sibling of the image, never a child: inside it, it would be hidden
+ along with everything else. */}
+ <table className="sr-only">
+ <caption>{t('settings.models.usage.byDay.table', { from: day(summary.from_day), to: day(summary.to_day) })}</caption>
+ <thead>
+ <tr>
+ <th scope="col">{t('settings.models.usage.byDay.col.day')}</th>
+ <th scope="col">{t('settings.models.usage.tokens.label')}</th>
+ <th scope="col">{t('settings.models.usage.requests.label')}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {columns.map((column) => (
+ <tr key={column.day}>
+ <th scope="row">{day(column.day)}</th>
+ <td>{count(column.tokens)}</td>
+ <td>{count(column.requests)}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
<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">
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index ee86a1338..156e61882 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -979,6 +979,8 @@
"byDay": {
"title": "By day",
"chart": "Metered tokens per day, {{from}} to {{to}}",
+ "table": "Metered tokens and requests per day, {{from}} to {{to}}",
+ "col": { "day": "Day" },
"column": "{{day}} · {{tokens}} tokens · {{requests}} requests",
"peak": "Peak {{tokens}} on {{day}}",
"quiet": "No day in this window carried a metered turn",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 23293be64..44ad5ade4 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -979,6 +979,8 @@
"byDay": {
"title": "按日",
"chart": "每日计量 token,{{from}} 至 {{to}}",
+ "table": "每日计量 token 与请求数,{{from}} 至 {{to}}",
+ "col": { "day": "日期" },
"column": "{{day}} · {{tokens}} tokens · {{requests}} 次请求",
"peak": "峰值 {{tokens}},出现在 {{day}}",
"quiet": "这个区间没有任何一天有计量数据",