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(ui): read a day's activity from its calls, not from its tokens

cyhd22cb4790ce5
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.md
index 726d5ab6a..e3a1e5a6a 100644
--- a/docs/plans/model-hub-usage-metering.md
+++ b/docs/plans/model-hub-usage-metering.md
@@ -1097,3 +1097,57 @@ keeping them only invites someone to wire it back up. What remains is
`types.SourceUsage` and the `mockData` 额度 fields: the type mirrors
`docs/plans/model-hub-contracts/source.schema.json`, which still declares the block,
and is retired when the contract retires it.
+
+### Stage 2, round 2 (head `5957182`)
+
+Two P2 findings, **no class repeat** — head 1 (`7082c882e`) carried one finding about
+catalog evidence resolved textually, which neither of these touches — so the breaker is
+not tripped and the round is two closures rather than a diagnosis.
+
+**F1: the day series read a missing token report as an idle day.** `token_reports <=
+requests` is a contract, and the gap means *reports that never arrived* — the tab already
+says exactly that for the totals (MH-USAGE-018). The day series then contradicted it: it
+scaled and captioned days by tokens alone, so a window whose upstreams all answered
+without token counts drew every bar at zero and captioned itself
+「没有任何一天有计量数据」 — our own missing evidence reported as the user's idleness.
+
+The finding named the peak/quiet copy. The class — *the day series asks tokens a question
+only requests can answer* — has exactly three members inside `ByDayPanel`: that copy, the
+column height, and the per-column tooltip. So the fix is one predicate, not one call site:
+`UsageDayColumn` carries `requests` alongside `tokens`, `usageDayIsMetered` is the single
+place the series asks whether a day ran, and all three members read it. A no-peak window
+now splits into the two different windows it always was — one nobody used, and one whose
+upstreams never said what it cost (`byDay.quiet` vs `byDay.unreported`).
+
+Ruled *out* of the class on evidence rather than by assumption, by reading
+`core/handlers/model_hub/usage.py`: `usageIsEmpty` gates on `sources.length`, and
+`summary()` builds source rows from the same request-driven rows, so an unreported window
+still has sources and is not empty; the stat cards, `cached.none`, and the chart's
+aria-label each state a token figure they really do own.
+
+**F2: deleting the last Source took the ledger with it.** `directEmpty` was a top-level
+routing fork, so the Frame 09 landing replaced the whole tab shell — including the Usage
+tab. But the ledger outlives the Sources it meters: retention is 62 days and MH-USAGE-017
+exists precisely because a vanished Source keeps its `src_*` id in the report. A user who
+deletes their last source loses the only route to what it cost, and a user reading the
+report when a deletion lands is thrown off the tab mid-read.
+
+One rule replaces the fork: **the Hub always has its two tabs, and `directEmpty` decides
+the body of the `sources` tab.** That is fewer concepts than the alternative (a usage
+affordance inside `DirectHome` plus a route back out of it), and it fixes the mid-read
+eviction for free. MH-USAGE-022 states the property over `Record<ModelsSurfaceKind, …>`,
+so a third landing fails to compile rather than shipping without a route.
+
+**Known-by-design: Frame 09 is drawn without the tab strip.** The frame predates this tab
+and the Usage tab has no frame at all, so the frame's silence is the absence of the
+concept, not a decision about it. What Frame 09 decides is the *body* of the `sources`
+tab, and that is still Frame 09 there — asserted, including that no gateway-overview
+content leaks in beside it.
+
+**Evidence.** MH-USAGE-021 draws a window where every request came back unreported and
+asserts the copy plus each day's readout. The bar geometry itself is not asserted there:
+the floor is `max(2px, …)`, an inline CSS function jsdom's parser drops, so `style.height`
+reads empty for drawn and undrawn columns alike. The decision behind the floor is the
+assertable 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 this
+tab already carries.
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 82f1cd52d..b4b2206f6 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -249,6 +249,18 @@ scenarios:
kind: observation
layer: unit
test: ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-USAGE-020
+ - id: MH-USAGE-021
+ name: A day whose calls carried no token report reads as metered rather than idle
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-021
+ - id: MH-USAGE-022
+ name: The usage report stays reachable from every Model Hub landing, including one with no Source left
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/settings/models/SettingsModelsPage.render.test.tsx::MH-USAGE-022
- id: MH-RES-LIVE-001
name: Live turn retries an eligible backup before streaming starts
status: covered
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 818bc7298..5e2a19e24 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -9,6 +9,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { ToastProvider } from '@/context/ToastProvider';
import i18n from '@/i18n';
import { MANAGE_COMMIT_ACTIONS } from './manage';
+import type { ModelsSurfaceKind } from './modelHubSurfaceState';
import { modelsApi } from './modelsApi';
import { SOURCE_MUTATION_REPORT_PROJECTIONS } from './mutationSettlement';
import { SettingsModelsPage } from './SettingsModelsPage';
@@ -183,13 +184,17 @@ describe('SettingsModelsPage surface branches', () => {
expect(listSources).toHaveBeenCalledTimes(refreshesBeforeCreate + 1);
});
- it('renders Frame 09 without tabs when every backend is direct and no source exists', async () => {
+ it('renders Frame 09 as the sources tab when every backend is direct and no source exists', async () => {
renderPage([]);
expect(await screen.findByText(/^Currently: direct$|^当前:直连$/i)).toBeTruthy();
expect(screen.getAllByRole('button', { name: /^Switch to Gateway$|^切换到网关$/i })).toHaveLength(3);
expect(screen.getByText(/^Switch to the gateway and you gain three things$|^切换到网关,你会多出三件事$/i)).toBeTruthy();
- expect(screen.queryByRole('tab')).toBeNull();
+ // Frame 09 is what the `sources` tab shows here — not what the Hub shows
+ // instead of its tabs. It is still Frame 09's body: none of the gateway
+ // overview leaks in beside it.
+ expect(screen.getAllByRole('tab')).toHaveLength(2);
+ expect(screen.queryByText(/^Recent switches$|^最近切换$/i)).toBeNull();
});
it('renders the no-backend state when every authoritative CLI is absent', async () => {
@@ -926,6 +931,32 @@ describe('SettingsModelsPage surface branches', () => {
describe('SettingsModelsPage usage region', () => {
const openUsage = () => userEvent.click(screen.getByRole('tab', { name: /^Usage$|^用量$/ }));
+ // The ledger outlives the Sources it metered — 62 days of retention, and a
+ // vanished Source still named by its id — so the route to it cannot be a branch
+ // of currently having one. Deleting the last source may not delete the only way
+ // to read what it cost, and a user reading the report may not be thrown off it
+ // by their own deletion.
+ it('MH-USAGE-022: reaches the report from every landing the Hub can draw', async () => {
+ // Keyed by the landing itself: a `Record<ModelsSurfaceKind, …>` cannot omit
+ // one, so a landing added later fails to compile here rather than quietly
+ // shipping without a route. The loop stays inside one case because a row's
+ // evidence has to be a case the catalog can resolve by name.
+ const landings: Record<ModelsSurfaceKind, Source[]> = {
+ direct_empty: [],
+ gateway: [retainedSource],
+ };
+
+ for (const [landing, sources] of Object.entries(landings)) {
+ cleanup();
+ vi.restoreAllMocks();
+ renderPage(sources);
+
+ await waitFor(() => expect(screen.getAllByRole('tab'), landing).toHaveLength(2));
+ await openUsage();
+ await waitFor(() => expect(vi.mocked(modelsApi.getUsageSummary), landing).toHaveBeenCalledWith(30));
+ }
+ });
+
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');
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index d119b352f..c703bf715 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -1058,10 +1058,19 @@ export const SettingsModelsPage: React.FC = () => {
onMutationCommitted={sourceMutationReport.present}
/>
: <section className="rounded-xl border border-border bg-surface px-5 py-12 text-center text-[12px] text-muted">{t('settings.models.sourceDetail.gone')}</section>
- : directEmpty ? <DirectHome agents={installedAgents} onSwitch={setAdoptAgent} />
- : <div className="space-y-[22px]">
+ : <div className="space-y-[22px]">
+ {/* The tab strip belongs to the Hub, not to the source
+ inventory. The ledger outlives the Sources it metered — it
+ retains its window and the report names a deleted Source by
+ its id — so deleting the last one may not take the only route
+ to that history with it. Frame 09 is drawn without tabs
+ because it predates this tab, not because usage stops
+ existing once the inventory is empty; what the frame decides
+ is the body of `sources`, which is still Frame 09 there. */}
<HubTabs tab={tab} onChange={setTab} />
- {tab === 'sources' ? <div className="model-hub-overview">
+ {tab === 'usage' ? <UsageTab usage={usageRead} windowDays={usageWindow} onWindowChange={setUsageWindow} onRetry={retryUsage} />
+ : directEmpty ? <DirectHome agents={installedAgents} onSwitch={setAdoptAgent} />
+ : <div className="model-hub-overview">
<div className="model-hub-overview-body">
<div ref={overviewRef} className="model-hub-overview-grid relative flex flex-col gap-4">
<Popover
@@ -1157,7 +1166,7 @@ export const SettingsModelsPage: React.FC = () => {
</div>
<RecentSwitchesCard events={eventsRead} sources={sourcesRead} onRetry={retryEvents} loadingMore={loadingEvents} onLoadMore={loadOlderEvents} />
<AdvancedRow />
- </div> : <UsageTab usage={usageRead} windowDays={usageWindow} onWindowChange={setUsageWindow} onRetry={retryUsage} />}
+ </div>}
</div>}
<SourceMutationReport
report={sourceMutationReport.report}
diff --git a/ui/src/components/settings/models/UsageTab.test.tsx b/ui/src/components/settings/models/UsageTab.test.tsx
index f7dadff51..3b198d49c 100644
--- a/ui/src/components/settings/models/UsageTab.test.tsx
+++ b/ui/src/components/settings/models/UsageTab.test.tsx
@@ -126,6 +126,37 @@ describe('UsageTab', () => {
expect(screen.getByRole('img', { name: /Metered tokens per day/ })).toBeTruthy();
});
+ it('MH-USAGE-021: draws a day of calls whose tokens never came back, and names the window unreported', () => {
+ // Every request in the window answered without a token report, which the
+ // schema permits and the requests card already states as a shortfall. The
+ // series has nothing to scale, so every bar sits on its floor — but the days
+ // ran, and folding them into 「no metered turn」 would report our own missing
+ // evidence as the user's idleness.
+ const unreported = counters({ requests: 4, token_reports: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0 });
+ const { container } = draw(readyRegion(summary({
+ from_day: '2026-08-16',
+ to_day: '2026-08-18',
+ window_days: 3,
+ totals: unreported,
+ sources: [source({ ...unreported, models: [model(unreported)] })],
+ days: [{ ...unreported, day: '2026-08-16' }, { ...unreported, day: '2026-08-18' }],
+ })));
+
+ expect(container.textContent).toContain(en.settings.models.usage.byDay.unreported);
+ expect(container.textContent).not.toContain(en.settings.models.usage.byDay.quiet);
+ // Every column says what its day carried, so a bar the report could not
+ // measure still reads as a day that ran rather than as an unexplained sliver.
+ // (Whether it is floored to one is CSS the DOM cannot answer for; the decision
+ // behind it is `usageDayIsMetered`, asserted over columns in
+ // `usageProjection.test.ts`.)
+ const readouts = [...container.querySelectorAll('.model-hub-usage-track')].map((track) => track.getAttribute('title'));
+ expect(readouts).toEqual([
+ 'Aug 16, 2026 · 0 tokens · 4 requests',
+ 'Aug 17, 2026 · 0 tokens · 0 requests',
+ 'Aug 18, 2026 · 0 tokens · 4 requests',
+ ]);
+ });
+
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.tsx
index 71a3de60a..bf931c236 100644
--- a/ui/src/components/settings/models/UsageTab.tsx
+++ b/ui/src/components/settings/models/UsageTab.tsx
@@ -32,6 +32,7 @@ import {
sourceIdentity,
usageCachedInputShare,
usageDayColumns,
+ usageDayIsMetered,
usageIsEmpty,
usageReportShortfall,
usageTotalTokens,
@@ -190,12 +191,17 @@ const BySourcePanel: React.FC<{ summary: UsageSummary }> = ({ summary }) => {
* makes the zero-fill legible. A bar of zero height in an empty row is
* indistinguishable from a missing bar, and the difference — an idle day versus a
* day the report does not cover — is the whole reason the series is drawn.
+ *
+ * Which day ran is `usageDayIsMetered`'s answer and never a token total: an
+ * upstream can serve a call and report nothing about it, so a window of those has
+ * bars to draw and a peak it cannot name.
*/
const ByDayPanel: React.FC<{ summary: UsageSummary }> = ({ summary }) => {
const { t, i18n } = useTranslation();
const count = useCount();
const columns = React.useMemo(() => usageDayColumns(summary), [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);
return (
<section className="model-hub-usage-card overflow-hidden rounded-xl border border-border bg-background">
@@ -212,21 +218,27 @@ const ByDayPanel: React.FC<{ summary: UsageSummary }> = ({ summary }) => {
<div
key={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) }) as string}
+ title={t('settings.models.usage.byDay.column', { day: day(column.day), tokens: count(column.tokens), requests: count(column.requests) }) as string}
>
{/* A metered day is floored to a visible sliver so the quietest one
- still reads as activity; a day with nothing keeps zero height
- and shows only the track. */}
- <div className="model-hub-usage-column w-full" style={{ height: column.tokens > 0 ? `max(2px, ${column.ratio * 100}%)` : 0 }} />
+ still reads as activity — including one whose tokens never came
+ back, which is why the floor asks about calls and not about
+ tokens. Only a day that carried nothing keeps zero height and
+ shows the track alone. */}
+ <div className="model-hub-usage-column w-full" style={{ height: usageDayIsMetered(column) ? `max(2px, ${column.ratio * 100}%)` : 0 }} />
</div>
))}
</div>
<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">
- {peak === null
- ? t('settings.models.usage.byDay.quiet')
- : t('settings.models.usage.byDay.peak', { tokens: count(peak.tokens), day: day(peak.day) })}
+ {peak !== null
+ ? t('settings.models.usage.byDay.peak', { tokens: count(peak.tokens), day: day(peak.day) })
+ // No peak is two different windows: one nobody used, and one whose
+ // upstreams never reported what they cost. Only the first is quiet.
+ : metered
+ ? t('settings.models.usage.byDay.unreported')
+ : t('settings.models.usage.byDay.quiet')}
</span>
<span className="truncate">{day(summary.to_day)}</span>
</div>
diff --git a/ui/src/components/settings/models/usageProjection.test.ts b/ui/src/components/settings/models/usageProjection.test.ts
index 14314da85..5bd035f29 100644
--- a/ui/src/components/settings/models/usageProjection.test.ts
+++ b/ui/src/components/settings/models/usageProjection.test.ts
@@ -9,6 +9,7 @@ import {
sourceIdentity,
usageCachedInputShare,
usageDayColumns,
+ usageDayIsMetered,
usageIsEmpty,
usageReportShortfall,
usageTotalTokens,
@@ -148,7 +149,9 @@ describe('formatLocalDay', () => {
});
describe('usageDayColumns', () => {
- const day = (value: string, tokens: number) => ({ ...counters({ input_tokens: tokens }), day: value });
+ // A reported day exists because a call was metered on it, so it carries one
+ // unless the case is about a day that carried several.
+ const day = (value: string, tokens: number, requests = 1) => ({ ...counters({ requests, input_tokens: tokens }), day: value });
it('spans the whole window and zero-fills the days that carried no turn', () => {
const columns = usageDayColumns(summary({ from_day: '2026-08-14', to_day: '2026-08-18', days: [day('2026-08-16', 40)] }));
@@ -167,6 +170,22 @@ describe('usageDayColumns', () => {
expect(total).toBe(reported.reduce((sum, entry) => sum + usageTotalTokens(entry), 0));
});
+ // Both counters travel, because they answer different questions: what a day
+ // cost, and whether it ran at all.
+ it('carries the calls of every reported day through, and gives a filled-in day none', () => {
+ const columns = usageDayColumns(summary({ from_day: '2026-08-14', to_day: '2026-08-16', days: [day('2026-08-15', 40, 3)] }));
+ expect(columns.map((column) => column.requests)).toEqual([0, 3, 0]);
+ });
+
+ // The distinction the whole series exists to draw. A day whose upstreams never
+ // reported their tokens still served the calls the user made, so it is a metered
+ // day with nothing to scale — not an idle one.
+ it('reads a day of calls with no token report as metered rather than idle', () => {
+ const columns = usageDayColumns(summary({ from_day: '2026-08-17', to_day: '2026-08-18', days: [day('2026-08-18', 0, 4)] }));
+ expect(columns.map(usageDayIsMetered)).toEqual([false, true]);
+ expect(columns.map((column) => column.tokens)).toEqual([0, 0]);
+ });
+
it('scales every bar against the busiest day on screen', () => {
const columns = usageDayColumns(summary({ from_day: '2026-08-17', to_day: '2026-08-18', days: [day('2026-08-17', 25), day('2026-08-18', 100)] }));
expect(columns.map((column) => column.ratio)).toEqual([0.25, 1]);
diff --git a/ui/src/components/settings/models/usageProjection.ts b/ui/src/components/settings/models/usageProjection.ts
index e230aaa06..c8971d878 100644
--- a/ui/src/components/settings/models/usageProjection.ts
+++ b/ui/src/components/settings/models/usageProjection.ts
@@ -95,11 +95,28 @@ export function usageIsEmpty(summary: UsageSummary): boolean {
export type UsageDayColumn = {
day: string;
+ /** Calls metered on this day, whether or not their tokens came back. */
+ requests: number;
tokens: number;
/** Height against the busiest rendered day, in [0, 1]. */
ratio: number;
};
+/**
+ * Whether a day carried a metered call at all.
+ *
+ * A day's activity is its request counter, never its token total. An upstream
+ * that answered without a token report still served a call the user made, so a
+ * day of those is a day that ran — and drawing it at zero height, or folding it
+ * into 「没有任何一天有计量数据」, reports our own missing evidence as the user's
+ * idleness. That is the rule the requests card states as a shortfall, applied per
+ * day, and it lives here so the series has one place to ask rather than one
+ * `tokens > 0` per thing it draws.
+ */
+export function usageDayIsMetered(column: UsageDayColumn): boolean {
+ return column.requests > 0;
+}
+
/**
* Every day of the window, oldest first, with the days that carried no turn
* filled in at zero.
@@ -116,14 +133,19 @@ export type UsageDayColumn = {
* span falls back to exactly the days reported — fewer bars, no invention.
*/
export function usageDayColumns(summary: UsageSummary): UsageDayColumn[] {
- const tokensByDay = new Map(summary.days.map((day: UsageByDay) => [day.day, usageTotalTokens(day)]));
+ const reportedByDay = new Map(summary.days.map((day: UsageByDay) => [day.day, day]));
const span = windowSpan(summary.from_day, summary.to_day);
const days = span ?? summary.days.map((day) => day.day);
- const counted = days.map((day) => ({ day, tokens: tokensByDay.get(day) ?? 0 }));
+ // Both counters travel, because tokens alone cannot tell a day nobody used
+ // from a day whose upstream never said what it cost.
+ const counted = days.map((day) => {
+ const reported = reportedByDay.get(day);
+ return { day, requests: reported?.requests ?? 0, tokens: reported ? usageTotalTokens(reported) : 0 };
+ });
// Scaled against the days on screen, not every day reported: a stray row
// outside the window would otherwise flatten every bar the user can see.
const peak = counted.reduce((max, column) => Math.max(max, column.tokens), 0);
- return counted.map(({ day, tokens }) => ({ day, tokens, ratio: peak > 0 ? tokens / peak : 0 }));
+ return counted.map((column) => ({ ...column, ratio: peak > 0 ? column.tokens / peak : 0 }));
}
const windowSpan = (fromDay: string, toDay: string): string[] | null => {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index e8e712e15..ee86a1338 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -979,9 +979,10 @@
"byDay": {
"title": "By day",
"chart": "Metered tokens per day, {{from}} to {{to}}",
- "column": "{{day}} · {{tokens}} tokens",
+ "column": "{{day}} · {{tokens}} tokens · {{requests}} requests",
"peak": "Peak {{tokens}} on {{day}}",
- "quiet": "No day in this window carried a metered turn"
+ "quiet": "No day in this window carried a metered turn",
+ "unreported": "Requests ran, but no day reported its tokens"
}
},
"supplyTooltip": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index f63e6002b..23293be64 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -979,9 +979,10 @@
"byDay": {
"title": "按日",
"chart": "每日计量 token,{{from}} 至 {{to}}",
- "column": "{{day}} · {{tokens}} tokens",
+ "column": "{{day}} · {{tokens}} tokens · {{requests}} 次请求",
"peak": "峰值 {{tokens}},出现在 {{day}}",
- "quiet": "这个区间没有任何一天有计量数据"
+ "quiet": "这个区间没有任何一天有计量数据",
+ "unreported": "有请求,但没有任何一天回报了 token"
}
},
"supplyTooltip": {