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
feat(ui): draw the Model Hub usage tab from the metering ledger
cyh7082c882e5d8
diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.mdindex ff7c40d1d..5a07b21b5 100644--- a/docs/plans/model-hub-usage-metering.md+++ b/docs/plans/model-hub-usage-metering.md@@ -1024,11 +1024,61 @@ verbatim.- [x] `ModelHubService.usage_summary` + RPC + `GET /api/models/usage`- [x] Contract row, response registry entry, and usage schema- [x] Unit and contract coverage-- [ ] Stage 2: draw the 用量与额度 tab against this data--## Stage 2 note--The tab is currently named 用量与额度 / "Usage and quota". After this stage the-用量 half is real and the 额度 half is still unobtainable, so the label needs a-design decision before stage 2 ships — renaming the tab to 用量 is the honest-option unless a quota source appears.+- [x] Stage 2: draw the tab against this data, as 用量++## Stage 2 — what shipped++**The tab is named 用量 / "Usage".** The label was 用量与额度 / "Usage and quota",+and the 额度 half has exactly one production writer:+`core/handlers/model_hub/migration.py` writes `"cycle_used_pct": None`. Every+non-null value in the repo is a mock or a schema example. So this is not a naming+preference — a quota reading would be an invention, and the tab is named for what+it can show. If a quota source ever appears, the label grows back with it.++**Where the data becomes a view.** `usageProjection.ts` owns every derivation the+tab could get wrong — the trailing local-day window, what a row may display, and+the densification of a sparse trend — so each one is asserted as a property rather+than inspected in JSX. `UsageTab.tsx` owns layout and copy and translates nothing+into numbers. Three properties are worth naming because getting them wrong would+be a lie rather than a glitch, and each is a catalog row (MH-USAGE-016..020):++- the caption states the `window_days` the server *served*, never the number the+ control asked for;+- a `token_reports` shortfall reads as reports that never arrived, never as unused+ capacity, which the schema forbids in as many words;+- a model whose label is gone shows no identity at all, because its ledger key is a+ digest; a gone Source keeps its `src_*` id, which is a string the user has seen.++**The read is the tab's own.** It is deliberately not a member of+`FIRST_PAINT_REGION_WHITELIST`: the landing decides routing, and a report nobody+is looking at must not delay it. One effect owns both the open and the window+change, since a window change is the same read over a different span, and+`beginRegionRead` keeps the previous figure on screen while the new one lands.++**Geometry.** `design.pen` has no frame for this tab on the local surface, so the+block adapts `MS/ConfigPanel → cp-usage-body` and otherwise follows the source+table directly above it — same 18px gutter, 36px head, 11px column labels, 12px+radius. Importing a second panel's spacing into the middle of this one would read+as two surfaces stitched together. Two deliberate departures: the day series is a+column chart because the day count is a window parameter rather than a fixed five,+and the panels stack because the table carries nested rows. No light-mode branch+was needed — every ink resolves through a step both light blocks already re-anchor,+and the chart's two colors are a wash and a `color-mix` accent, which flip on their+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.++**Dead 额度 code removed with the rename.** Copy: `settings.models.usage.monthSpend`,+`settings.models.usageTab`, and `settings.models.tabs` (a zero-caller duplicate of+`shell.tab`). Formatters: `formatSpend` and `currencySymbol`, which had zero callers+already on `master` — they render `month_spend_cents`, whose one writer is+`migration.py`'s `None`, so the amount they format is unobtainable in production and+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.diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 848a9bbcb..1b475617f 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -120,6 +120,8 @@ capabilities:- tests/test_model_hub_l3.py- tests/test_model_hub_usage.py- tests/test_opencode_server.py+ - ui/src/components/settings/models/UsageTab.test.tsx+ - ui/src/components/settings/models/SettingsModelsPage.render.test.tsx- 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 f0e819ecd..43027f94f 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -11,6 +11,10 @@ capability:- tests/test_model_hub_l3.py- tests/test_model_hub_usage.py- tests/test_opencode_server.py+ # The user-visible half of metering. A vitest case is the only place these+ # 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- 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@@ -209,6 +213,36 @@ scenarios:kind: recoverylayer: unittest: tests/test_model_hub_usage.py::test_a_wedged_ledger_write_cannot_hold_the_process_open+ - id: MH-USAGE-016+ name: The usage report names the window the server served, not the one the view asked for+ 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+ - 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+ - 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+ - 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+ - 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- 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 9a1a69225..b8fed03fb 100644--- a/tests/scenarios/model_hub/test_model_hub_catalog.py+++ b/tests/scenarios/model_hub/test_model_hub_catalog.py@@ -38,6 +38,27 @@ def _test_function(path: Path, function_name: str) -> ast.FunctionDef | ast.Asynreturn function+def _vitest_case(path: Path, case_name: str) -> str:+ """One `it(...)` case's own source.++ 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.+ """++ source = path.read_text()+ start = next(+ (found for quote in ("'", '"') if (found := source.find(f"it({quote}{case_name}{quote}")) != -1),+ -1,+ )+ 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]++def _decorator_names(function: ast.FunctionDef | ast.AsyncFunctionDef) -> set[str]:names: set[str] = set()for decorator in function.decorator_list:@@ -74,10 +95,19 @@ 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()- function = _test_function(path, function_name)- expected_fail = "xfail" in _decorator_names(function)- assert expected_fail == status["expected_fail"]- assert scenario["id"] in (ast.get_docstring(function) or ""), (+ 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.+ 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)+ else:+ function = _test_function(path, function_name)+ expected_fail = "xfail" in _decorator_names(function)+ assert expected_fail == status["expected_fail"]+ 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")diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex e4e8fc5d4..122ee5ac1 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -12,7 +12,7 @@ import { MANAGE_COMMIT_ACTIONS } from './manage';import { modelsApi } from './modelsApi';import { SOURCE_MUTATION_REPORT_PROJECTIONS } from './mutationSettlement';import { SettingsModelsPage } from './SettingsModelsPage';-import type { AgentBackend, AgentChain, AgentSupply, RuntimeDependency, Source } from './types';+import type { AgentBackend, AgentChain, AgentSupply, RuntimeDependency, Source, UsageSummary } from './types';const directAgent = (backend: AgentBackend): AgentSupply => ({backend,@@ -84,6 +84,25 @@ const takeoverChain: AgentChain = {supply_state: 'ok',};+const usageSummary: UsageSummary = {+ window_days: 30,+ from_day: '2026-07-20',+ to_day: '2026-08-18',+ totals: { requests: 12, token_reports: 12, input_tokens: 148230, cached_input_tokens: 96010, output_tokens: 4120 },+ sources: [{+ source_id: 'src_retained',+ label: 'Retained source',+ last_metered_at: '2026-08-18T03:14:00+00:00',+ requests: 12,+ token_reports: 12,+ input_tokens: 148230,+ cached_input_tokens: 96010,+ output_tokens: 4120,+ models: [{ model_id: 'claude-opus-4-6', label: 'claude-opus-4-6', requests: 12, token_reports: 12, input_tokens: 148230, cached_input_tokens: 96010, output_tokens: 4120 }],+ }],+ days: [{ day: '2026-08-18', requests: 12, token_reports: 12, input_tokens: 148230, cached_input_tokens: 96010, output_tokens: 4120 }],+};+const deferred = <T,>() => {let resolve!: (value: T) => void;const promise = new Promise<T>((done) => {@@ -101,6 +120,7 @@ const renderPage = (sources: Source[]) => {]);vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'getUsageSummary').mockResolvedValue(usageSummary);return render(<ToastProvider><I18nextProvider i18n={i18n}>@@ -899,3 +919,57 @@ describe('SettingsModelsPage surface branches', () => {expect(screen.getAllByText('—').length).toBeGreaterThan(0);});});++// How the usage report is READ. What it says once read is `UsageTab.test.tsx`'s+// subject; the property here is that the read is the tab's own — off the first+// paint, live on every open, and spanning whatever the control was left on.+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 () => {+ 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.+ expect(read).not.toHaveBeenCalled();+ await openUsage();+ await waitFor(() => expect(read).toHaveBeenCalledWith(30));+ });++ it('re-reads with the span the control was moved to', async () => {+ renderPage([retainedSource]);+ await screen.findByText('Retained source');+ await openUsage();+ const read = vi.mocked(modelsApi.getUsageSummary);+ await waitFor(() => expect(read).toHaveBeenCalledTimes(1));++ await userEvent.click(screen.getByRole('radio', { name: /^7d$|^7 天$/ }));+ await waitFor(() => expect(read).toHaveBeenLastCalledWith(7));+ });++ it('re-reads on every open, because the figure is live', async () => {+ renderPage([retainedSource]);+ await screen.findByText('Retained source');+ const read = vi.mocked(modelsApi.getUsageSummary);+ await openUsage();+ await waitFor(() => expect(read).toHaveBeenCalledTimes(1));++ await userEvent.click(screen.getByRole('tab', { name: /^Sources & gateway$|^来源与网关$/ }));+ await openUsage();+ await waitFor(() => expect(read).toHaveBeenCalledTimes(2));+ });++ it('retries the read the tab failed on, at the same span', async () => {+ renderPage([retainedSource]);+ const read = vi.mocked(modelsApi.getUsageSummary);+ read.mockRejectedValueOnce(new TypeError('usage unread'));+ await screen.findByText('Retained source');+ await openUsage();++ await userEvent.click(await screen.findByRole('button', { name: /^Retry$|^重试$/ }));+ await waitFor(() => expect(read).toHaveBeenCalledTimes(2));+ expect(read.mock.calls.map(([days]) => days)).toEqual([30, 30]);+ });+});diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex ad2fd0b3a..d119b352f 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -1,5 +1,5 @@import * as React from 'react';-import { ArrowLeft, Gauge, Info, LoaderCircle, Route } from 'lucide-react';+import { ArrowLeft, Gauge, LoaderCircle, Route } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Badge } from '@/components/ui/badge';@@ -30,6 +30,7 @@ import {releaseSuspendedRouteAttempt,} from './suspendedRouteAttempts';import { SupplyGraph, SupplyLegend } from './SupplyGraph';+import { UsageTab } from './UsageTab';import './modelHubSurface.css';import { agentsWithEcho, createLatestAsyncAuthority, createLatestAsyncAuthorityByKey, createLatestEntityAuthorityByKey, createPendingWrites, mapWithConcurrency } from './asyncLifetime';import { createAgentCollectionReadAuthority, createSourceCollectionReadAuthority } from './collectionReadAuthority';@@ -51,6 +52,7 @@ import {foldRegionRead,degradedRegion,loadingRegion,+ readRegion,readyRegion,settleRegionRead,unreadRegion,@@ -60,7 +62,8 @@ import { freshRuntimeProjection, pollRuntimeStatus, runtimeCanAttemptInstall, stimport { createRouteProjectionReconciler, type RouteProjectionStatus } from './routeProjectionReconciliation';import { useSourceMutationReport } from './useSourceMutationReport';import { backendVisual } from './vendorMeta';-import type { AgentBackend, AgentSupply, ResolutionEvent, RuntimeDependency, Source } from './types';+import { USAGE_DEFAULT_WINDOW_DAYS, type AgentBackend, type AgentSupply, type ResolutionEvent, type RuntimeDependency, type Source, type UsageSummary } from './types';+import type { UsageWindowOption } from './usageProjection';const CHAIN_READ_CONCURRENCY = 6;const EVENT_PAGE = 20;@@ -292,6 +295,8 @@ export const SettingsModelsPage: React.FC = () => {const [eventsRead, setEventsRead] = React.useState<RegionRead<EventFeed>>(loadingRegion);const [loadingEvents, setLoadingEvents] = React.useState(false);const [tab, setTab] = React.useState<'sources' | 'usage'>('sources');+ const [usageRead, setUsageRead] = React.useState<RegionRead<UsageSummary>>(loadingRegion);+ const [usageWindow, setUsageWindow] = React.useState<UsageWindowOption>(USAGE_DEFAULT_WINDOW_DAYS);const [startingRuntime, setStartingRuntime] = React.useState(false);const [runtimeRecoveryPending, setRuntimeRecoveryPending] = React.useState(false);const [installOpen, setInstallOpen] = React.useState(false);@@ -517,6 +522,37 @@ export const SettingsModelsPage: React.FC = () => {});}));+ const [usageReadAuthority] = React.useState(() => createLatestAsyncAuthority<RegionRead<UsageSummary>>((incoming) => {+ if (!aliveRef.current) return;+ setUsageRead((previous) => settleRegionRead(previous, incoming));+ }));++ const refreshUsage = React.useCallback(async (days: UsageWindowOption) => {+ setUsageRead(beginRegionRead);+ await usageReadAuthority.run(() => readRegion(() => modelsApi.getUsageSummary(days)));+ }, [usageReadAuthority]);++ /**+ * The usage report is read lazily, when the tab is opened.+ *+ * It is deliberately NOT a first-paint region (see `firstPaintRegions.ts`,+ * whose whitelist is a policy list of exactly the three reads the landing+ * cannot be drawn without): a report nobody is looking at must not delay the+ * surface that decides routing. Re-reading on every open is the point — the+ * figure is live, and `beginRegionRead` keeps the previous one on screen while+ * the new one lands, so returning to the tab never flashes empty. A window+ * change is the same read with a different span, which is why one effect owns+ * both.+ */+ React.useEffect(() => {+ if (tab !== 'usage') return;+ void refreshUsage(usageWindow);+ }, [tab, usageWindow, refreshUsage]);++ const retryUsage = React.useCallback(async () => {+ await refreshUsage(usageWindow);+ }, [refreshUsage, usageWindow]);+const refreshEventHead = React.useCallback(async () => {setEventsRead(beginRegionRead);await eventReadAuthority.run(async () => {@@ -1121,7 +1157,7 @@ export const SettingsModelsPage: React.FC = () => {</div><RecentSwitchesCard events={eventsRead} sources={sourcesRead} onRetry={retryEvents} loadingMore={loadingEvents} onLoadMore={loadOlderEvents} /><AdvancedRow />- </div> : <section className="rounded-xl border border-border bg-surface px-5 py-8"><div className="flex items-start gap-3"><Info className="mt-0.5 size-4 text-muted" /><div><h2 className="text-[14px] font-semibold text-foreground">{t('settings.models.usageTab.title')}</h2><p className="mt-1 text-[12px] text-muted">{t('settings.models.usageTab.detail')}</p></div></div></section>}+ </div> : <UsageTab usage={usageRead} windowDays={usageWindow} onWindowChange={setUsageWindow} onRetry={retryUsage} />}</div>}<SourceMutationReportreport={sourceMutationReport.report}diff --git a/ui/src/components/settings/models/UsageTab.test.tsx b/ui/src/components/settings/models/UsageTab.test.tsxnew file mode 100644index 000000000..4c325ab33--- /dev/null+++ b/ui/src/components/settings/models/UsageTab.test.tsx@@ -0,0 +1,165 @@+// @vitest-environment jsdom+// What the 用量 tab is allowed to SAY about a report. The derivations themselves+// are `usageProjection.test.ts`'s subject; every assertion here is about a claim+// 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 userEvent from '@testing-library/user-event';+import { createInstance } from 'i18next';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import en from '../../../i18n/en.json';+import { degradedRegion, loadingRegion, readyRegion, unreadRegion, type RegionRead } from './regionRead';+import type { UsageByModel, UsageBySource, UsageCounters, UsageSummary } from './types';+import { UsageTab } from './UsageTab';++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'en',+ fallbackLng: 'en',+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+});++const counters = (over: Partial<UsageCounters> = {}): UsageCounters => ({+ requests: 12,+ token_reports: 12,+ input_tokens: 148230,+ cached_input_tokens: 96010,+ output_tokens: 4120,+ ...over,+});++const model = (over: Partial<UsageByModel> = {}): UsageByModel => ({+ ...counters(),+ model_id: 'claude-opus-4-6',+ label: 'claude-opus-4-6',+ ...over,+});++const source = (over: Partial<UsageBySource> = {}): UsageBySource => ({+ ...counters(),+ source_id: 'src_conform001',+ label: 'Contract source',+ last_metered_at: '2026-08-18T03:14:00+00:00',+ models: [model()],+ ...over,+});++const summary = (over: Partial<UsageSummary> = {}): UsageSummary => ({+ window_days: 30,+ from_day: '2026-07-20',+ to_day: '2026-08-18',+ totals: counters(),+ sources: [source()],+ days: [{ ...counters(), day: '2026-08-18' }],+ ...over,+});++const draw = (+ usage: RegionRead<UsageSummary>,+ over: { windowDays?: 7 | 30 | 60; onWindowChange?: (days: number) => void; onRetry?: () => void } = {},+) =>+ render(+ <I18nextProvider i18n={i18n}>+ <UsageTab+ usage={usage}+ windowDays={over.windowDays ?? 30}+ onWindowChange={over.onWindowChange ?? (() => {})}+ onRetry={over.onRetry}+ />+ </I18nextProvider>,+ );++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.+ 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.+ 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 })] })] })),+ );+ expect(container.textContent).toContain('src_conform001');+ expect(container.textContent).toContain(en.settings.models.usage.bySource.goneSource);+ expect(container.textContent).toContain(en.settings.models.usage.bySource.goneModel);+ expect(container.textContent).not.toContain(key);+ 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.+ 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);+ });++ it('confirms full reporting when every request carried its tokens', () => {+ const { container } = draw(readyRegion(summary()));+ expect(container.textContent).toContain(en.settings.models.usage.requests.reported);+ });++ it('says nothing was metered instead of drawing a table of zeroes', () => {+ const { container } = draw(readyRegion(summary({ sources: [], days: [] })));+ expect(container.textContent).toContain(en.settings.models.usage.empty);+ expect(container.textContent).not.toContain(en.settings.models.usage.bySource.title);+ 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.+ const { container } = draw(readyRegion(summary()));+ expect(container.querySelectorAll('.model-hub-usage-track')).toHaveLength(30);+ expect(screen.getByRole('img', { name: /Metered tokens per day/ })).toBeTruthy();+ });++ 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');+ expect(container.textContent).not.toContain(en.settings.models.toast.refreshFailed);+ });++ it('keeps the last report on screen when a refresh fails, under a retry', async () => {+ // The alternative is an empty state, which would read as "nothing was ever+ // metered" — a different claim from "the figure could not be refreshed".+ const onRetry = vi.fn();+ const { container } = draw(degradedRegion(summary(), 'read_failed', true), { onRetry });+ expect(container.textContent).toContain('Contract source');+ expect(container.textContent).toContain(en.settings.models.toast.refreshFailed);+ await userEvent.click(screen.getByRole('button', { name: en.settings.models.upstream.retry }));+ expect(onRetry).toHaveBeenCalledTimes(1);+ });++ it('offers a retry with no report to show when the first read never landed', () => {+ const { container } = draw(unreadRegion<UsageSummary>());+ expect(container.textContent).toContain(en.settings.models.toast.refreshFailed);+ expect(container.textContent).not.toContain(en.settings.models.usage.empty);+ });++ it('draws no report and no failure while the first read is in flight', () => {+ const { container } = draw(loadingRegion<UsageSummary>());+ expect(container.textContent).not.toContain(en.settings.models.toast.refreshFailed);+ expect(container.textContent).not.toContain(en.settings.models.usage.empty);+ });++ it('hands its owner a window the contract accepts, as a number', async () => {+ // The control speaks strings; `days` is a bounded number on the wire.+ const onWindowChange = vi.fn();+ draw(readyRegion(summary()), { onWindowChange });+ await userEvent.click(screen.getByRole('radio', { name: '7d' }));+ expect(onWindowChange).toHaveBeenCalledWith(7);+ });+});diff --git a/ui/src/components/settings/models/UsageTab.tsx b/ui/src/components/settings/models/UsageTab.tsxnew file mode 100644index 000000000..71a3de60a--- /dev/null+++ b/ui/src/components/settings/models/UsageTab.tsx@@ -0,0 +1,303 @@+// 用量 — the metered-token report over a trailing local-day window+// (`usage-summary.schema.json`).+//+// It is a report and only a report: nothing on this tab feeds resolution,+// admission, or cooldown, and the span it names is the `window_days` the server+// answered with rather than the number the user asked for. The two are the same+// for every option offered here, which is a property `usageProjection.test.ts`+// enforces rather than a coincidence to rely on.+//+// The 額度 half the tab label used to promise is absent on purpose. `cycle_used_pct`+// has exactly one production writer and it writes `None`, so a quota reading would+// be an invention; the tab is named for what it can actually show.+//+// Drawn against `design.pen MS/ConfigPanel → cp-usage-body`. No frame exists for+// this tab on the local surface, so the geometry follows the source table's own+// vocabulary — 12px card radius, 18px gutter, 11px column labels — instead of+// importing a second panel's spacing into the middle of this one. Two deliberate+// departures from that frame: the day series is a column chart because the day+// count is a window parameter and not a fixed five, and the panels stack instead+// of splitting because the table carries nested rows and a trend reads wide.+import * as React from 'react';+import { useTranslation } from 'react-i18next';++import { SegmentedRadio } from '@/components/ui/segmented';+import { formatCount, formatDayTime, formatPercent } from './format';+import { foldRegionRead, regionFailed, type RegionRead } from './regionRead';+import type { UsageByModel, UsageBySource, UsageSummary } from './types';+import {+ USAGE_WINDOW_OPTIONS,+ formatLocalDay,+ modelIdentity,+ sourceIdentity,+ usageCachedInputShare,+ usageDayColumns,+ usageIsEmpty,+ usageReportShortfall,+ usageTotalTokens,+ type UsageDayColumn,+ type UsageIdentity,+ type UsageWindowOption,+} from './usageProjection';++/** A number that reads against a vendor's own console: grouped, never compacted. */+const useCount = () => {+ const { i18n } = useTranslation();+ return (value: number) => formatCount(value, i18n.language);+};++/**+ * A row's own name, or the honest absence of one.+ *+ * A Source that has left the inventory keeps its canonical id, so the reader can+ * still tell which line of the report is which. A model has no displayable+ * identity at all once its label is gone — its ledger key is a digest — so the+ * row says so in words instead of printing the key.+ */+const RowIdentity: React.FC<{ identity: UsageIdentity; goneKey: string }> = ({ identity, goneKey }) => {+ const { t } = useTranslation();+ if (identity.kind === 'label') return <span className="truncate" title={identity.text}>{identity.text}</span>;+ return (+ <span className="flex min-w-0 items-baseline gap-1.5">+ {identity.id !== null && <span className="truncate font-mono" title={identity.id}>{identity.id}</span>}+ <span className="model-hub-usage-gone shrink-0">{t(goneKey)}</span>+ </span>+ );+};++/**+ * One measured cell.+ *+ * 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.+ */+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 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">+ <span className="model-hub-usage-stat-label">{label}</span>+ <span className="model-hub-usage-stat-value font-semibold text-foreground">{value}</span>+ <span className="model-hub-usage-stat-note">{note}</span>+ </div>+);++const StatGrid: React.FC<{ summary: UsageSummary }> = ({ summary }) => {+ const { t, i18n } = useTranslation();+ const count = useCount();+ const totals = summary.totals;+ const shortfall = usageReportShortfall(totals);+ const cachedShare = usageCachedInputShare(totals);+ return (+ <div className="grid gap-4 sm:grid-cols-3">+ <StatCard+ label={t('settings.models.usage.tokens.label') as string}+ value={count(usageTotalTokens(totals))}+ note={t('settings.models.usage.tokens.detail', { input: count(totals.input_tokens), output: count(totals.output_tokens) }) as string}+ />+ <StatCard+ label={t('settings.models.usage.requests.label') as string}+ value={count(totals.requests)}+ // A shortfall means reports that never arrived, never capacity left+ // unused, and the copy has to say which of the two it is.+ note={(shortfall > 0+ ? t('settings.models.usage.requests.shortfall', { count: shortfall })+ : t('settings.models.usage.requests.reported')) as string}+ />+ <StatCard+ label={t('settings.models.usage.cached.label') as string}+ value={cachedShare === null ? (t('settings.models.usage.blank') as string) : formatPercent(cachedShare, i18n.language)}+ note={(cachedShare === null+ ? t('settings.models.usage.cached.none')+ : t('settings.models.usage.cached.detail', { cached: count(totals.cached_input_tokens), input: count(totals.input_tokens) })) as string}+ />+ </div>+ );+};++const ModelRow: React.FC<{ model: UsageByModel }> = ({ model }) => {+ const { t, i18n } = useTranslation();+ 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">+ <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}>+ {share === null ? (t('settings.models.usage.blank') as string) : formatPercent(share, i18n.language)}+ </Cell>+ <span className="hidden md:block" />+ </div>+ );+};++const SourceRows: React.FC<{ source: UsageBySource }> = ({ source }) => {+ const { t, i18n } = useTranslation();+ 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">+ <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}>+ {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}>+ {source.last_metered_at === null ? (t('settings.models.usage.blank') as string) : formatDayTime(source.last_metered_at, i18n.language)}+ </Cell>+ </div>+ {source.models.map((model) => <ModelRow key={model.model_id} model={model} />)}+ </div>+ );+};++const BySourcePanel: React.FC<{ summary: UsageSummary }> = ({ summary }) => {+ const { t } = useTranslation();+ 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">+ {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>+ </div>+ {summary.sources.map((source) => <SourceRows key={source.source_id} source={source} />)}+ </section>+ );+};++/**+ * The trend, over every day of the window rather than every day reported.+ *+ * `usageDayColumns` is what densifies it; the track behind each column is what+ * 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.+ */+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 day = (value: string) => formatLocalDay(value, i18n.language);+ 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">+ {t('settings.models.usage.byDay.title')}+ </h3>+ <div className="model-hub-usage-plot flex flex-col">+ <div+ role="img"+ aria-label={t('settings.models.usage.byDay.chart', { from: day(summary.from_day), to: day(summary.to_day) }) as string}+ className="model-hub-usage-chart flex items-end"+ >+ {columns.map((column) => (+ <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}+ >+ {/* 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 }} />+ </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) })}+ </span>+ <span className="truncate">{day(summary.to_day)}</span>+ </div>+ </div>+ </section>+ );+};++export const UsageTab: React.FC<{+ usage: RegionRead<UsageSummary>;+ /** The window the user asked for. The report answers with what it served. */+ windowDays: UsageWindowOption;+ onWindowChange: (days: UsageWindowOption) => void;+ onRetry?: () => void | Promise<void>;+}> = ({ usage: usageRead, windowDays, onWindowChange, onRetry }) => {+ const { t, i18n } = useTranslation();+ const summary = foldRegionRead<UsageSummary, UsageSummary | null>(usageRead, {+ loading: () => null,+ ready: (data) => data,+ unread: () => null,+ // A stale report is still the last true one; it stays on screen under the+ // failure strip rather than being replaced by an empty state that would read+ // as "nothing was ever metered".+ degraded: (staleData) => staleData,+ });+ const options = React.useMemo(+ () => USAGE_WINDOW_OPTIONS.map((option) => ({ id: String(option), label: t('settings.models.usage.window.option', { days: option }) as string })),+ [t],+ );+ const pickWindow = (id: string) => {+ const next = USAGE_WINDOW_OPTIONS.find((option) => String(option) === id);+ if (next !== undefined) onWindowChange(next);+ };+ const day = (value: string) => formatLocalDay(value, i18n.language);++ return (+ <div className="model-hub-usage">+ <div className="model-hub-usage-bar flex flex-col gap-3 rounded-xl border border-border bg-surface sm:flex-row sm:items-center sm:justify-between">+ <div className="flex min-w-0 flex-col gap-1">+ <h2 className="model-hub-usage-title font-semibold text-foreground">{t('settings.models.usage.title')}</h2>+ <p className="model-hub-usage-note truncate">+ {summary === null+ ? t('settings.models.usage.detail')+ : t('settings.models.usage.range', { from: day(summary.from_day), to: day(summary.to_day), days: summary.window_days })}+ </p>+ </div>+ <SegmentedRadio+ value={String(windowDays)}+ onChange={pickWindow}+ options={options}+ ariaLabel={t('settings.models.usage.window.label') as string}+ className="shrink-0 sm:w-auto"+ />+ </div>+ {regionFailed(usageRead) && (+ <div className="model-hub-usage-failure flex items-center justify-between gap-3 rounded-xl border border-border bg-background text-destructive-ink">+ <span>{t('settings.models.toast.refreshFailed')}</span>+ <button type="button" onClick={() => void onRetry?.()} className="model-hub-action-mint shrink-0 font-semibold">+ {t('settings.models.upstream.retry')}+ </button>+ </div>+ )}+ {summary === null+ ? usageRead.kind === 'loading' && <p className="model-hub-usage-pending text-muted">{t('common.loading')}</p>+ : usageIsEmpty(summary)+ ? <p className="model-hub-usage-empty rounded-xl border border-border bg-background text-center text-muted">{t('settings.models.usage.empty')}</p>+ : <>+ <StatGrid summary={summary} />+ <BySourcePanel summary={summary} />+ <ByDayPanel summary={summary} />+ </>}+ </div>+ );+};diff --git a/ui/src/components/settings/models/format.test.ts b/ui/src/components/settings/models/format.test.tsindex 3b5e193fc..c17dd428b 100644--- a/ui/src/components/settings/models/format.test.ts+++ b/ui/src/components/settings/models/format.test.ts@@ -1,54 +1,47 @@import { describe, expect, it } from 'vitest';-import { cooldownEtaMinutes, currencySymbol, formatNameList, formatSpend } from './format';+import { cooldownEtaMinutes, formatCount, formatDayTime, formatNameList, formatPercent } from './format';-describe('currencySymbol', () => {- it('falls back to USD when the backend reports no currency', () => {- expect(currencySymbol(null)).toBe('$');- expect(currencySymbol(undefined)).toBe('$');- expect(currencySymbol()).toBe('$');+describe('formatCount', () => {+ it('groups so a figure can be read against a vendor console', () => {+ expect(formatCount(2_968_500, 'en-US')).toBe('2,968,500');+ expect(formatCount(2_968_500, 'zh-CN')).toBe('2,968,500');});- it('honors an explicitly reported currency', () => {- expect(currencySymbol('USD')).toBe('$');- expect(currencySymbol('CNY')).toBe('¥');- expect(currencySymbol('EUR')).toBe('€');+ it('leaves a small count ungrouped', () => {+ expect(formatCount(0, 'en-US')).toBe('0');+ expect(formatCount(12, 'en-US')).toBe('12');});- it('returns no symbol for a code it cannot map', () => {- expect(currencySymbol('JPY')).toBe('');- });-- it('agrees with the symbol formatSpend uses, for every currency', () => {- for (const currency of [null, undefined, 'USD', 'CNY', 'EUR', 'JPY'] as const) {- expect(formatSpend(1240, currency).startsWith(currencySymbol(currency))).toBe(true);- const stripped = formatSpend(1240, currency).slice(currencySymbol(currency).length);- expect(stripped).toBe('12.4');- }+ // A token count is a count: rounding it up, or rendering a negative one, would+ // put a claim on screen the ledger never made.+ it('never renders a fractional or negative count', () => {+ expect(formatCount(12.9, 'en-US')).toBe('12');+ expect(formatCount(-5, 'en-US')).toBe('0');});});-describe('formatSpend', () => {- it('falls back to USD when the backend reports no currency', () => {- expect(formatSpend(1240, null)).toBe('$12.4');- expect(formatSpend(1240, undefined)).toBe('$12.4');- expect(formatSpend(1240)).toBe('$12.4');- });-- it('honors an explicitly reported currency', () => {- expect(formatSpend(1240, 'USD')).toBe('$12.4');- expect(formatSpend(1240, 'CNY')).toBe('¥12.4');- expect(formatSpend(1240, 'EUR')).toBe('€12.4');+describe('formatPercent', () => {+ it('renders a share as whole percent', () => {+ expect(formatPercent(0, 'en-US')).toBe('0%');+ expect(formatPercent(0.647, 'en-US')).toBe('65%');+ expect(formatPercent(1, 'en-US')).toBe('100%');});+});- it('omits the symbol for a currency it cannot map', () => {- expect(formatSpend(1240, 'JPY')).toBe('12.4');+describe('formatDayTime', () => {+ it('keeps the day and the minute of the instant it was given', () => {+ // Fixed as an offset-bearing stamp so the assertion is about the formatter+ // rather than about the machine the test happens to run on.+ const rendered = formatDayTime('2026-08-18T03:14:00+00:00', 'en-US');+ const local = new Date('2026-08-18T03:14:00+00:00');+ expect(rendered).toContain(String(local.getDate()));+ expect(rendered).toContain(String(local.getMinutes()).padStart(2, '0'));});- it('converts cents to one decimal without applying any FX rate', () => {- expect(formatSpend(0, null)).toBe('$0.0');- expect(formatSpend(5, null)).toBe('$0.1');- expect(formatSpend(1234567, null)).toBe('$12345.7');+ it('renders an unparseable stamp verbatim rather than inventing a time', () => {+ expect(formatDayTime('never', 'en-US')).toBe('never');+ expect(formatDayTime('', 'en-US')).toBe('');});});diff --git a/ui/src/components/settings/models/format.ts b/ui/src/components/settings/models/format.tsindex a7fb574cc..5750322dd 100644--- a/ui/src/components/settings/models/format.ts+++ b/ui/src/components/settings/models/format.ts@@ -1,24 +1,5 @@// Pure formatting helpers for the Model Hub UI (no i18n — callers wrap the// returned values in translated templates).-const CURRENCY_SYMBOL: Record<string, string> = { USD: '$', CNY: '¥', EUR: '€' };--/**- * Symbol for an ISO 4217 code — the ONLY place a currency symbol is resolved.- *- * USD is the fallback because every upstream vendor bills in USD; a CNY default- * was our own invention. The mapping is kept, so a source that really does report- * CNY (or EUR) still renders in its own currency. Returns '' for a code we cannot- * map, so callers can fall back to a currency-free label rather than print a- * misleading symbol.- */-export function currencySymbol(currency?: string | null): string {- return CURRENCY_SYMBOL[currency ?? 'USD'] ?? '';-}--/** Monthly spend as symbol + amount (1 decimal), e.g. "$12.4". */-export function formatSpend(cents: number, currency?: string | null): string {- return `${currencySymbol(currency)}${(cents / 100).toFixed(1)}`;-}/*** A list of names in the reader's own punctuation — 「A、B、C」 for a Chinese@@ -34,6 +15,40 @@ export function formatNameList(names: readonly string[], locale: string): stringreturn new Intl.ListFormat(locale, { style: 'narrow', type: 'conjunction' }).format(names);}+/**+ * A counted quantity in the reader's own grouping — 「2,968,500」.+ *+ * Grouped rather than compacted (「3M」) because a usage report is read to be+ * reconciled against a vendor's own console, and a rounded figure cannot be.+ * `Intl` is what makes the separator the reader's rather than ours; the value is+ * floored because a token count is a count, and a fractional one would be a bug+ * upstream rendered as truth here.+ */+export function formatCount(value: number, locale: string): string {+ return new Intl.NumberFormat(locale).format(Math.max(0, Math.floor(value)));+}++/** A ratio in [0, 1] as a whole-percent string — 「65%」. */+export function formatPercent(ratio: number, locale: string): string {+ return new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 0 }).format(ratio);+}++/**+ * An instant as a short day-and-time in the reader's own zone — 「8/18 03:14」.+ *+ * The host zone is the frame on purpose: what this answers is "when did this last+ * happen to me", and a UTC stamp is a time the reader cannot reconcile against+ * their own day. The year is dropped because the report this appears in spans at+ * most a couple of months, so the year is never the ambiguous part; the month is+ * kept because the day alone is. An unparseable stamp renders verbatim rather+ * than as an invented time.+ */+export function formatDayTime(instant: string, locale: string): string {+ const ms = Date.parse(instant);+ if (Number.isNaN(ms)) return instant;+ return new Intl.DateTimeFormat(locale, { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(ms);+}+/** Whole minutes until a cooldown retry_at (never negative). */export function cooldownEtaMinutes(retryAt?: string | null): number {if (!retryAt) return 0;diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex a6412d2d7..2744f4cad 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -1455,6 +1455,150 @@font-weight: 600;}+/* 用量 tab.+ *+ * design.pen has no frame for this tab on the local surface, so the geometry is+ * borrowed from the source table above rather than invented: the same 18px+ * gutter, 36px head, 11px column label, and wash-05 head fill. Importing a+ * second panel's spacing into the middle of this one would read as two+ * surfaces stitched together.+ *+ * Every ink here resolves through a step the light blocks already re-anchor+ * (ink-73 / ink-8c / muted-b3), so this block needs no light branch of its own.+ * The one genuinely new unit is the day chart, and its two colors are a wash and+ * an accent fill — both of which flip correctly on their own.+ */+.model-hub-usage {+ --model-hub-usage-gap: 16px;+ --model-hub-usage-bar-padding-y: 13px;+ --model-hub-usage-bar-padding-x: 18px;+ --model-hub-usage-padding-x: 18px;+ --model-hub-usage-head-height: 36px;+ --model-hub-usage-row-min-height: 46px;+ --model-hub-usage-row-padding-y: 9px;+ --model-hub-usage-columns: minmax(0, 1fr) 104px 84px 84px 116px;+ --model-hub-usage-gutter: 16px;+ --model-hub-usage-title-size: 13px;+ --model-hub-usage-section-size: 12px;+ --model-hub-usage-label-size: 11px;+ --model-hub-usage-value-size: 20px;+ --model-hub-usage-cell-size: 12px;+ --model-hub-usage-note-size: 10.5px;+ --model-hub-usage-model-indent: 14px;+ --model-hub-usage-chart-height: 132px;+ --model-hub-usage-chart-gap: 3px;+ --model-hub-usage-column-radius: 2px;+ --model-hub-usage-head-fill: var(--model-hub-wash-05);+ --model-hub-usage-label-ink: var(--model-hub-ink-73);+ --model-hub-usage-note-ink: var(--model-hub-muted-b3);+ --model-hub-usage-model-ink: var(--model-hub-ink-8c);+ --model-hub-usage-track-fill: var(--model-hub-wash-08);+ --model-hub-usage-column-fill: color-mix(in srgb, var(--mint) 55%, transparent);+ display: flex;+ flex-direction: column;+ gap: var(--model-hub-usage-gap);+}+.model-hub-usage-bar {+ padding: var(--model-hub-usage-bar-padding-y) var(--model-hub-usage-bar-padding-x);+}+.model-hub-usage-title { font-size: var(--model-hub-usage-title-size); }+.model-hub-usage-note {+ color: var(--model-hub-usage-note-ink);+ font-size: var(--model-hub-usage-note-size);+}+.model-hub-usage-failure {+ padding: 11px var(--model-hub-usage-padding-x);+ font-size: var(--model-hub-usage-cell-size);+}+.model-hub-usage-pending { font-size: var(--model-hub-usage-title-size); }+.model-hub-usage-empty {+ padding: 26px var(--model-hub-usage-padding-x);+ font-size: var(--model-hub-usage-cell-size);+}+.model-hub-usage-stat {+ padding: 13px var(--model-hub-usage-padding-x) 14px;+ gap: 5px;+}+.model-hub-usage-stat-label {+ color: var(--model-hub-usage-label-ink);+ font-size: var(--model-hub-usage-label-size);+}+.model-hub-usage-stat-value {+ font-size: var(--model-hub-usage-value-size);+ line-height: 1.15;+ font-variant-numeric: tabular-nums;+}+.model-hub-usage-stat-note {+ color: var(--model-hub-usage-note-ink);+ font-size: var(--model-hub-usage-note-size);+}+.model-hub-usage-card-head {+ padding: 11px var(--model-hub-usage-padding-x);+}+.model-hub-usage-section-title { font-size: var(--model-hub-usage-section-size); }+/* Grid items stretch by default, which would leave a plain text cell drawing its+ * glyphs against the top of the box while a flex cell beside it centres them. */+.model-hub-usage-head {+ min-height: var(--model-hub-usage-head-height);+ padding: 0 var(--model-hub-usage-padding-x);+ grid-template-columns: var(--model-hub-usage-columns);+ gap: var(--model-hub-usage-gutter);+ align-items: center;+ background: var(--model-hub-usage-head-fill);+ color: var(--model-hub-usage-label-ink);+ font-size: var(--model-hub-usage-label-size);+}+.model-hub-usage-row {+ min-height: var(--model-hub-usage-row-min-height);+ padding: var(--model-hub-usage-row-padding-y) var(--model-hub-usage-padding-x);+ grid-template-columns: var(--model-hub-usage-columns);+ gap: var(--model-hub-usage-gutter);+ font-size: var(--model-hub-usage-cell-size);+}+.model-hub-usage-row--model {+ padding-left: calc(var(--model-hub-usage-padding-x) + var(--model-hub-usage-model-indent));+ color: var(--model-hub-usage-model-ink);+}+.model-hub-usage-source,+.model-hub-usage-model,+.model-hub-usage-cell { min-width: 0; }+.model-hub-usage-cell { font-variant-numeric: tabular-nums; }+.model-hub-usage-cell-label {+ color: var(--model-hub-usage-label-ink);+ font-size: var(--model-hub-usage-note-size);+ font-variant-numeric: normal;+}+.model-hub-usage-gone {+ color: var(--model-hub-usage-note-ink);+ font-size: var(--model-hub-usage-note-size);+}+.model-hub-usage-plot {+ padding: 16px var(--model-hub-usage-padding-x) 12px;+ gap: 9px;+}+.model-hub-usage-chart {+ height: var(--model-hub-usage-chart-height);+ gap: var(--model-hub-usage-chart-gap);+}+/* The track is drawn even where the column is not: a bar of zero height in an+ * empty row cannot be told apart from a day the report never covered, and that+ * distinction is the reason the series is plotted day by day at all. */+.model-hub-usage-track {+ min-width: 0;+ height: 100%;+ border-radius: var(--model-hub-usage-column-radius);+ background: var(--model-hub-usage-track-fill);+}+.model-hub-usage-column {+ border-radius: var(--model-hub-usage-column-radius);+ background: var(--model-hub-usage-column-fill);+}+.model-hub-usage-axis {+ color: var(--model-hub-usage-note-ink);+ font-size: var(--model-hub-usage-note-size);+}+.model-hub-usage-peak { color: var(--model-hub-usage-label-ink); }+@media (min-width: 1024px) {.model-hub-direct-grid {grid-template-columns: minmax(0, 1fr) var(--model-hub-direct-benefits-width);@@ -1468,6 +1612,9 @@.model-hub-source-bar { align-items: stretch; }.model-hub-source-action { width: auto; flex: 1 1 0; }.model-hub-direct-card { min-height: 0; }+ /* Stacked, each cell carries its own label, so the column gutter becomes a+ * line gap and 16px of it would read as four separate rows. */+ .model-hub-usage-row { grid-template-columns: minmax(0, 1fr); gap: 7px; }}@media (min-width: 1024px) {diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex 92e7b591b..b431accf1 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -33,7 +33,9 @@ import type {SourceRepaired,SupplyChannel,SupplyGap,+ UsageSummary,} from './types';+import { USAGE_DEFAULT_WINDOW_DAYS } from './types';/** Add-time Route placement returned by both source-creation paths. */export type Adoption = { added_to: AddedTo[]; adopted_by: AdoptedBy[] };@@ -127,6 +129,10 @@ export type ModelsApi = {applyMigration(itemIds: string[]): Promise<MigrationApplyResult>;/** `before` is an event id cursor (「查看全部」 pagination). */listEvents(limit?: number, before?: string): Promise<ResolutionEvent[]>;+ /** Metered token report over a trailing local-day window. `days` is a REQUEST:+ * the server clamps it to retention and echoes what it served in+ * `window_days`, which is the only number a view may display. */+ getUsageSummary(days?: number): Promise<UsageSummary>;getRuntimeStatus(): Promise<RuntimeDependency>;/** Start the contract-owned client installation transaction. */installRuntime(): Promise<RuntimeDependency>;@@ -457,6 +463,8 @@ export const modelsApi: ModelsApi = {call<{ events: ResolutionEvent[] }>(`/api/models/events?limit=${limit}${before ? `&before=${encodeURIComponent(before)}` : ''}`,).then((r) => r.events),+ getUsageSummary: (days = USAGE_DEFAULT_WINDOW_DAYS) =>+ call<{ usage: UsageSummary }>(`/api/models/usage?days=${days}`).then((r) => r.usage),getRuntimeStatus: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/status').then((r) => (r.runtime ?? r) as RuntimeDependency),installRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/install', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),startRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/start', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 9128c9fc4..78a119f6a 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -66,10 +66,19 @@ export type SourceState = {detail_key?: SourceDetailKey | null;};+/**+ * The 額度 block of `source.schema.json`, mirrored so the contract stays typed.+ *+ * Nothing renders it: `cycle_used_pct` and `month_spend_cents` have one writer+ * each (`migration.py`, both `None`), so every value the UI could receive is+ * absent. The tab that used to promise 額度 reports metered tokens instead — see+ * `UsageTab.tsx`. Kept as a mirror rather than deleted because the contract file+ * still declares the fields; drop it when the contract does.+ */export type SourceUsage = {cycle_used_pct?: number | null;month_spend_cents?: number | null;- /** ISO 4217, e.g. USD / CNY. Absent means USD (see formatSpend). */+ /** ISO 4217, e.g. USD / CNY. Absent means USD. */currency?: string | null;/** v3, subscription sources only: when the current cycle is projected to run* out at the observed burn rate. null when unknown or not projectable. */@@ -505,6 +514,79 @@ export type RuntimeDependency = {};};+// ── usage-summary.schema.json ───────────────────────────────────────────+/**+ * Metered token usage over a trailing local-day window. A REPORT ONLY: the+ * schema forbids any consumer feeding it back into resolution, admission, or+ * cooldown, and the UI honours that by never reading it outside the usage tab.+ *+ * FIELD names are the schema's exactly, as everywhere in this file. The three+ * per-dimension TYPE names are `UsageBy*` rather than the schema's `SourceUsage`+ * / `ModelUsage` / `DayUsage`: `SourceUsage` is already taken above by+ * source.schema.json's cycle-quota-and-spend projection, which is a different+ * concept on a different document, and shadowing it would make「用量」ambiguous+ * in exactly the file that exists to remove ambiguity.+ */+export type UsageCounters = {+ /** Self-measured upstream calls that reached the model. One turn contributes+ * more than one when it failed over. Always available. */+ requests: number;+ /** Metered calls whose upstream response carried a token report. Never+ * greater than `requests`; a shortfall means MISSING REPORTS, not zero+ * usage, so no view may present the difference as unused capacity. */+ token_reports: number;+ /** Vendor-reported input tokens composed per protocol, cache included. */+ input_tokens: number;+ /** Subset of `input_tokens` served from cache. */+ cached_input_tokens: number;+ output_tokens: number;+};++export type UsageByModel = UsageCounters & {+ /** Ledger key, which for a long identifier is a head plus a digest rather+ * than the identifier itself — a string nobody typed. Display `label`,+ * never this. `usageProjection.modelIdentity` is the only reader. */+ model_id: string;+ /** The model identity this row was metered under, joined from current Source+ * config; null once the model is gone. */+ label: string | null;+};++export type UsageBySource = UsageCounters & {+ source_id: string;+ /** Joined from current Source config; null once the Source is gone. */+ label: string | null;+ /** When this Source last had a call metered, served or billed-and-failed. */+ last_metered_at: string | null;+ /** Never empty. A model's identity is the (source, model) pair, so this+ * nesting is the contract's own answer to a flat model map. */+ models: UsageByModel[];+};++export type UsageByDay = UsageCounters & { day: string };++export type UsageSummary = {+ /** The window the server actually served, after clamping to retention. Views+ * render THIS, never the number they asked for. */+ window_days: number;+ /** First local day of the window, present even when it carries no turn. */+ from_day: string;+ /** Last local day of the window, which is the host's today. */+ to_day: string;+ totals: UsageCounters;+ /** One entry per Source with at least one metered turn, busiest first. */+ sources: UsageBySource[];+ /** One entry per local day carrying a metered turn, oldest first — a trend+ * series, so a day with no turn is ABSENT rather than reported as zero. */+ days: UsageByDay[];+};++/** `window_days` bounds from the schema. The offered options live in+ * `usageProjection` and are gated against these. */+export const USAGE_WINDOW_MIN_DAYS = 1 as const;+export const USAGE_WINDOW_MAX_DAYS = 62 as const;+export const USAGE_DEFAULT_WINDOW_DAYS = 30 as const;+// ── API envelope + request shapes (api.md) ──────────────────────────────export type ApiOk<T> = { ok: true; contract_version: typeof CONTRACT_VERSION } & T;export type ApiErr = {diff --git a/ui/src/components/settings/models/usageProjection.test.ts b/ui/src/components/settings/models/usageProjection.test.tsnew file mode 100644index 000000000..14314da85--- /dev/null+++ b/ui/src/components/settings/models/usageProjection.test.ts@@ -0,0 +1,224 @@+import { describe, expect, it } from 'vitest';++import { USAGE_WINDOW_MAX_DAYS, USAGE_WINDOW_MIN_DAYS, type UsageByModel, type UsageBySource, type UsageCounters, type UsageSummary } from './types';+import {+ USAGE_WINDOW_OPTIONS,+ formatLocalDay,+ modelIdentity,+ parseLocalDay,+ sourceIdentity,+ usageCachedInputShare,+ usageDayColumns,+ usageIsEmpty,+ usageReportShortfall,+ usageTotalTokens,+} from './usageProjection';++const counters = (over: Partial<UsageCounters> = {}): UsageCounters => ({+ requests: 0,+ token_reports: 0,+ input_tokens: 0,+ cached_input_tokens: 0,+ output_tokens: 0,+ ...over,+});++const model = (over: Partial<UsageByModel> = {}): UsageByModel => ({+ ...counters(),+ model_id: 'claude-opus-4-6',+ label: 'claude-opus-4-6',+ ...over,+});++const source = (over: Partial<UsageBySource> = {}): UsageBySource => ({+ ...counters(),+ source_id: 'src_conform001',+ label: 'Contract source',+ last_metered_at: null,+ models: [model()],+ ...over,+});++const summary = (over: Partial<UsageSummary> = {}): UsageSummary => ({+ window_days: 30,+ from_day: '2026-07-20',+ to_day: '2026-08-18',+ totals: counters(),+ sources: [],+ days: [],+ ...over,+});++describe('USAGE_WINDOW_OPTIONS', () => {+ // The reason this file exists: an option outside the contract bounds is a+ // number on screen the report never covered.+ it('offers only windows the contract can serve', () => {+ expect(USAGE_WINDOW_OPTIONS.length).toBeGreaterThan(0);+ for (const option of USAGE_WINDOW_OPTIONS) {+ expect(Number.isInteger(option)).toBe(true);+ expect(option).toBeGreaterThanOrEqual(USAGE_WINDOW_MIN_DAYS);+ expect(option).toBeLessThanOrEqual(USAGE_WINDOW_MAX_DAYS);+ }+ });++ it('offers each window once, shortest first', () => {+ const options = [...USAGE_WINDOW_OPTIONS];+ expect(new Set(options).size).toBe(options.length);+ expect(options).toEqual([...options].sort((left, right) => left - right));+ });+});++describe('usageTotalTokens', () => {+ it('adds input and output without subtracting the cached subset', () => {+ expect(usageTotalTokens(counters({ input_tokens: 148_230, cached_input_tokens: 96_010, output_tokens: 4_120 }))).toBe(152_350);+ });+});++describe('usageReportShortfall', () => {+ it('counts the requests that carried no token report', () => {+ expect(usageReportShortfall(counters({ requests: 12, token_reports: 9 }))).toBe(3);+ expect(usageReportShortfall(counters({ requests: 12, token_reports: 12 }))).toBe(0);+ });++ it('never reports a negative shortfall, whatever the payload claims', () => {+ expect(usageReportShortfall(counters({ requests: 4, token_reports: 9 }))).toBe(0);+ });+});++describe('usageCachedInputShare', () => {+ it('is the cached share of reported input', () => {+ expect(usageCachedInputShare(counters({ input_tokens: 200, cached_input_tokens: 50 }))).toBe(0.25);+ });++ it('has no share to report when nothing was input', () => {+ expect(usageCachedInputShare(counters({ input_tokens: 0, cached_input_tokens: 0 }))).toBeNull();+ expect(usageCachedInputShare(counters({ input_tokens: 0, cached_input_tokens: 90 }))).toBeNull();+ });++ it('stays a share even when the payload breaks the subset promise', () => {+ expect(usageCachedInputShare(counters({ input_tokens: 100, cached_input_tokens: 400 }))).toBe(1);+ expect(usageCachedInputShare(counters({ input_tokens: 100, cached_input_tokens: -40 }))).toBe(0);+ });+});++describe('usageIsEmpty', () => {+ it('is empty exactly when no Source was metered', () => {+ expect(usageIsEmpty(summary())).toBe(true);+ expect(usageIsEmpty(summary({ sources: [source()] }))).toBe(false);+ });+});++describe('parseLocalDay', () => {+ it('accepts a contract LocalDay and rejects anything else', () => {+ expect(parseLocalDay('2026-08-18')).toBe(Date.UTC(2026, 7, 18));+ for (const rejected of ['', '2026-8-18', '2026-08-18T00:00:00Z', 'yesterday', '20260818']) {+ expect(parseLocalDay(rejected)).toBeNull();+ }+ });++ // `Date.parse` rolls these forward instead of refusing them, so a day that+ // survives must read back identical rather than merely parse.+ it('rejects a day the calendar does not have', () => {+ for (const rolled of ['2026-02-30', '2026-13-01', '2026-04-31', '2026-00-10', '2026-01-32']) {+ expect(parseLocalDay(rolled)).toBeNull();+ }+ });++ it('round-trips every day of the widest window it will plot', () => {+ const first = parseLocalDay('2026-01-01');+ expect(first).not.toBeNull();+ for (let index = 0; index < USAGE_WINDOW_MAX_DAYS; index += 1) {+ const day = new Date((first as number) + index * 86_400_000).toISOString().slice(0, 10);+ expect(parseLocalDay(day)).not.toBeNull();+ }+ });+});++describe('formatLocalDay', () => {+ it('keeps the labelled day when read back, in either locale', () => {+ expect(formatLocalDay('2026-08-18', 'en-US')).toContain('18');+ expect(formatLocalDay('2026-08-18', 'en-US')).toContain('2026');+ expect(formatLocalDay('2026-08-18', 'zh-CN')).toContain('18');+ expect(formatLocalDay('2026-08-18', 'zh-CN')).toContain('2026');+ });++ it('renders an unparseable day verbatim rather than inventing one', () => {+ expect(formatLocalDay('not-a-day', 'en-US')).toBe('not-a-day');+ });+});++describe('usageDayColumns', () => {+ const day = (value: string, tokens: number) => ({ ...counters({ 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)] }));+ expect(columns.map((column) => column.day)).toEqual(['2026-08-14', '2026-08-15', '2026-08-16', '2026-08-17', '2026-08-18']);+ expect(columns.map((column) => column.tokens)).toEqual([0, 0, 40, 0, 0]);+ });++ // The property, not a case list: whatever the reported set is, every reported+ // day keeps its own tokens and nothing else gains any.+ it('carries the tokens of every reported day through unchanged', () => {+ const reported = [day('2026-08-14', 10), day('2026-08-16', 40), day('2026-08-18', 25)];+ const columns = usageDayColumns(summary({ from_day: '2026-08-14', to_day: '2026-08-18', days: reported }));+ const byDay = new Map(columns.map((column) => [column.day, column.tokens]));+ for (const entry of reported) expect(byDay.get(entry.day)).toBe(usageTotalTokens(entry));+ const total = columns.reduce((sum, column) => sum + column.tokens, 0);+ expect(total).toBe(reported.reduce((sum, entry) => sum + usageTotalTokens(entry), 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]);+ });++ it('gives a silent window flat bars rather than a division by zero', () => {+ const columns = usageDayColumns(summary({ from_day: '2026-08-17', to_day: '2026-08-18' }));+ expect(columns.map((column) => column.ratio)).toEqual([0, 0]);+ });++ it('falls back to the reported days when the window bounds are unusable', () => {+ // Reversed, malformed, and wider than retention all mean the same thing: the+ // span is not ours to trust, so plot what was actually reported.+ for (const window of [+ { from_day: '2026-08-18', to_day: '2026-08-14' },+ { from_day: 'nope', to_day: '2026-08-18' },+ { from_day: '2020-01-01', to_day: '2026-08-18' },+ ]) {+ const columns = usageDayColumns(summary({ ...window, days: [day('2026-08-16', 40)] }));+ expect(columns.map((column) => column.day)).toEqual(['2026-08-16']);+ expect(columns[0].tokens).toBe(40);+ }+ });++ it('never plots more columns than the maximum window the contract allows', () => {+ const columns = usageDayColumns(summary({ from_day: '2026-06-18', to_day: '2026-08-18' }));+ expect(columns.length).toBeLessThanOrEqual(USAGE_WINDOW_MAX_DAYS);+ });+});++describe('usage row identity', () => {+ it('shows the joined label while there is one', () => {+ expect(sourceIdentity(source({ label: 'Contract source' }))).toEqual({ kind: 'label', text: 'Contract source' });+ expect(modelIdentity(model({ label: 'claude-opus-4-6' }))).toEqual({ kind: 'label', text: 'claude-opus-4-6' });+ });++ it('treats a blank label as no label at all', () => {+ expect(sourceIdentity(source({ label: ' ' })).kind).toBe('gone');+ expect(modelIdentity(model({ label: '' })).kind).toBe('gone');+ });++ it('keeps a gone Source addressable by its canonical id', () => {+ expect(sourceIdentity(source({ label: null, source_id: 'src_gone' }))).toEqual({ kind: 'gone', id: 'src_gone' });+ });++ // The contract's rule, as a property: `model_id` is a head plus a digest for+ // any long identifier, so it is never a string this UI may display.+ it('never offers the ledger key of a gone model as something to display', () => {+ for (const key of ['claude-opus-4-6', 'anthropic/claude-opus-4-6-2026#9f2a1c', 'x'.repeat(200)]) {+ const identity = modelIdentity(model({ label: null, model_id: key }));+ expect(identity).toEqual({ kind: 'gone', id: null });+ expect(JSON.stringify(identity)).not.toContain(key);+ }+ });+});diff --git a/ui/src/components/settings/models/usageProjection.ts b/ui/src/components/settings/models/usageProjection.tsnew file mode 100644index 000000000..e230aaa06--- /dev/null+++ b/ui/src/components/settings/models/usageProjection.ts@@ -0,0 +1,162 @@+// Pure projections over `usage-summary.schema.json` for the 用量 tab.+//+// Everything here is a derivation the tab could get WRONG, kept out of JSX so it+// can be asserted as a property: what the window spans, what a row is allowed to+// display, and how a sparse trend becomes a dense one. Layout and copy stay in+// the component; this module never translates.+//+// It owns the trailing local-day window — `YYYY-MM-DD` labels in and out.+// `localCalendar.ts` answers a different question (is this INSTANT today?) over a+// different input type, so the two are deliberately not merged: an instant needs+// a timezone to become a day, and these strings already are days.+import { USAGE_WINDOW_MAX_DAYS, USAGE_WINDOW_MIN_DAYS, type UsageByDay, type UsageByModel, type UsageBySource, type UsageCounters, type UsageSummary } from './types';++/**+ * The windows the tab offers.+ *+ * Bounded by the schema rather than by the design, which offers 7/30/90: the+ * server clamps `days` to retention and answers with what it served, so a 「90+ * 天」 option would put a number on screen the report never covered. The gate is+ * mechanical — `usageProjection.test.ts` fails if an option leaves the contract+ * bounds — so the next person to add one cannot reintroduce the lie by hand.+ */+export const USAGE_WINDOW_OPTIONS = [7, 30, 60] as const;+export type UsageWindowOption = (typeof USAGE_WINDOW_OPTIONS)[number];++const DAY_MS = 86_400_000;+const LOCAL_DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;++const toLocalDay = (ms: number): string => new Date(ms).toISOString().slice(0, 10);++/**+ * A `LocalDay` as the UTC instant of its midnight, or null when it is not one.+ *+ * UTC is the arithmetic frame on purpose. The string is already a local calendar+ * day, so re-deriving it through the host's zone would let a DST boundary or an+ * offset change move a labelled day by one; stepping in fixed 86 400 s units and+ * reading the label straight back cannot.+ *+ * The pattern alone does not decide it. `Date.parse` rolls an out-of-range day+ * FORWARD rather than refusing it — `2026-02-30` becomes March 2 — and a rolled+ * day silently stops matching the label it was keyed by. Reading the day back out+ * and requiring it unchanged is a check against our own output, so no calendar+ * quirk of the host parser can pass through it.+ */+export function parseLocalDay(day: string): number | null {+ if (!LOCAL_DAY_PATTERN.test(day)) return null;+ const ms = Date.parse(`${day}T00:00:00Z`);+ return Number.isNaN(ms) || toLocalDay(ms) !== day ? null : ms;+}++/** A `LocalDay` in the reader's own date order — 「2026年7月20日」/「Jul 20, 2026」.+ * Formatted in UTC for the same reason the arithmetic is: the label must survive+ * the round trip unshifted. Unparseable input renders verbatim rather than as an+ * invented date. */+export function formatLocalDay(day: string, locale: string): string {+ const ms = parseLocalDay(day);+ if (ms === null) return day;+ return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone: 'UTC' }).format(ms);+}++/** Tokens the window actually moved. Cache is NOT subtracted: a cached input+ * token was still composed into the request, and `cached_input_tokens` is a+ * subset of `input_tokens` reported separately so a view can qualify the total+ * without double-counting it. */+export function usageTotalTokens(counters: UsageCounters): number {+ return counters.input_tokens + counters.output_tokens;+}++/**+ * Requests whose upstream response carried no token report.+ *+ * The schema guarantees `token_reports <= requests`, and this floors at zero+ * anyway: both numbers arrive over the wire, and a view that renders 「-3 次未回+ * 报」 has turned a payload bug into a claim about the user's usage. The honest+ * reading of a shortfall is missing reports, never unused capacity — which is+ * why the caller's copy says so.+ */+export function usageReportShortfall(counters: UsageCounters): number {+ return Math.max(0, counters.requests - counters.token_reports);+}++/** Share of input tokens served from cache, or null when there is no input to+ * take a share of. Clamped to [0, 1] because the subset relation is the+ * server's promise, not something this view can verify. */+export function usageCachedInputShare(counters: UsageCounters): number | null {+ if (counters.input_tokens <= 0) return null;+ return Math.min(1, Math.max(0, counters.cached_input_tokens / counters.input_tokens));+}++/** Nothing was metered in the window. `sources` is the gate because it is what+ * the table renders, and a Source enters it only once it has a metered turn. */+export function usageIsEmpty(summary: UsageSummary): boolean {+ return summary.sources.length === 0;+}++export type UsageDayColumn = {+ day: string;+ tokens: number;+ /** Height against the busiest rendered day, in [0, 1]. */+ ratio: number;+};++/**+ * Every day of the window, oldest first, with the days that carried no turn+ * filled in at zero.+ *+ * `days[]` is sparse by contract — a quiet day is absent, not reported as zero —+ * and a chart drawn straight from it would silently close the gaps and read as+ * continuous traffic. Densifying from `from_day`/`to_day` is what makes an idle+ * stretch visible as an idle stretch.+ *+ * The span comes from the dates rather than from `window_days` so a payload+ * whose two disagree still plots its real dates, and it is refused outright past+ * the contract's own maximum: the bound is ours, measured against the schema, so+ * a `from_day` far in the past cannot ask this for a million columns. A refused+ * 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 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 }));+ // 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 }));+}++const windowSpan = (fromDay: string, toDay: string): string[] | null => {+ const from = parseLocalDay(fromDay);+ const to = parseLocalDay(toDay);+ if (from === null || to === null || to < from) return null;+ const length = (to - from) / DAY_MS + 1;+ if (!Number.isInteger(length) || length < USAGE_WINDOW_MIN_DAYS || length > USAGE_WINDOW_MAX_DAYS) return null;+ return Array.from({ length }, (_, index) => toLocalDay(from + index * DAY_MS));+};++/**+ * What a usage row may put on screen for its own identity.+ *+ * `gone` carries an id only where one is safe to show. A Source keeps its+ * canonical `src_*` id, which is a string the user could have seen elsewhere. A+ * model's ledger key is a head plus a digest for any long identifier — a string+ * nobody typed — so a vanished model has NO displayable identity and gets a bare+ * marker. That asymmetry is the reason both live behind one type instead of two+ * `label ?? id` expressions in JSX.+ */+export type UsageIdentity = { kind: 'label'; text: string } | { kind: 'gone'; id: string | null };++const identify = (label: string | null, fallbackId: string | null): UsageIdentity => {+ const text = label?.trim();+ // A blank label is as unrenderable as a missing one, and the schema permits it.+ return text ? { kind: 'label', text } : { kind: 'gone', id: fallbackId };+};++export function sourceIdentity(source: UsageBySource): UsageIdentity {+ return identify(source.label, source.source_id);+}++export function modelIdentity(model: UsageByModel): UsageIdentity {+ return identify(model.label, null);+}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex c7e7d9a1c..e8e712e15 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -633,10 +633,6 @@"subtitle": "See whether each agent model can run now and which source serves it; set a route for one model when needed.","addSource": "Add source","loadError": "Failed to load: {{detail}}",- "tabs": {- "sources": "Sources & gateway",- "usage": "Usage & quota"- },"sourceKind": {"api_key": "API key","subscription": "Subscription"@@ -659,7 +655,7 @@},"tab": {"hub": "Sources & gateway",- "usage": "Usage & quota"+ "usage": "Usage"}},"direct": {@@ -817,10 +813,6 @@"unavailable": "Supply paused","note": "Route chains are each backend's configured source order."},- "usageTab": {- "title": "Usage and quota",- "detail": "Usage appears after a gateway source serves a request."- },"status": {"allHealthy": "All healthy","needsAction_one": "{{count}} model needs attention",@@ -948,7 +940,49 @@"error": "Needs attention"},"usage": {- "monthSpend": "{{amount}} this month"+ "title": "Usage",+ "detail": "Metered tokens from the turns the gateway proxied, by local day.",+ "window": {+ "label": "Window",+ "option": "{{days}}d"+ },+ "range": "{{from}} – {{to}} · trailing {{days}} days",+ "empty": "Nothing metered yet. A window fills once a gateway source serves a request.",+ "blank": "—",+ "tokens": {+ "label": "Tokens",+ "detail": "{{input}} in · {{output}} out"+ },+ "requests": {+ "label": "Requests",+ "reported": "Every request reported its tokens",+ "shortfall_one": "{{count}} request came back with no token report",+ "shortfall_other": "{{count}} requests came back with no token report"+ },+ "cached": {+ "label": "Cached input",+ "detail": "{{cached}} of {{input}} input tokens",+ "none": "No input tokens in this window"+ },+ "bySource": {+ "title": "By source",+ "col": {+ "source": "Source",+ "tokens": "Tokens",+ "requests": "Requests",+ "cached": "Cached",+ "lastMetered": "Last metered"+ },+ "goneSource": "deleted",+ "goneModel": "model no longer listed"+ },+ "byDay": {+ "title": "By day",+ "chart": "Metered tokens per day, {{from}} to {{to}}",+ "column": "{{day}} · {{tokens}} tokens",+ "peak": "Peak {{tokens}} on {{day}}",+ "quiet": "No day in this window carried a metered turn"+ }},"supplyTooltip": {"label": "Supplies: "diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex c3cf902c7..f63e6002b 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -633,10 +633,6 @@"subtitle": "按 Agent 查看每个型号现在能否运行、由谁供给;需要时可为单个型号指定路由。","addSource": "添加来源","loadError": "加载失败:{{detail}}",- "tabs": {- "sources": "来源与网关",- "usage": "用量与额度"- },"sourceKind": {"api_key": "API Key","subscription": "订阅"@@ -659,7 +655,7 @@},"tab": {"hub": "来源与网关",- "usage": "用量与额度"+ "usage": "用量"}},"direct": {@@ -817,10 +813,6 @@"unavailable": "供给已暂停","note": "路由链就是各后端配置的来源顺序。"},- "usageTab": {- "title": "用量与额度",- "detail": "网关来源完成请求后,用量会显示在这里。"- },"status": {"allHealthy": "全部正常","needsAction_one": "{{count}} 个模型需要处理",@@ -948,7 +940,49 @@"error": "需要处理"},"usage": {- "monthSpend": "本月 {{amount}}"+ "title": "用量",+ "detail": "网关代理的对话所计量的 token,按本地日期汇总。",+ "window": {+ "label": "区间",+ "option": "{{days}} 天"+ },+ "range": "{{from}} – {{to}} · 近 {{days}} 天",+ "empty": "还没有计量数据。网关来源完成请求后,这里就会有内容。",+ "blank": "—",+ "tokens": {+ "label": "Tokens",+ "detail": "输入 {{input}} · 输出 {{output}}"+ },+ "requests": {+ "label": "请求数",+ "reported": "每次请求都回报了 token",+ "shortfall_one": "{{count}} 次请求没有回报 token",+ "shortfall_other": "{{count}} 次请求没有回报 token"+ },+ "cached": {+ "label": "缓存输入",+ "detail": "输入 {{input}} 中有 {{cached}} 来自缓存",+ "none": "这个区间没有输入 token"+ },+ "bySource": {+ "title": "按来源",+ "col": {+ "source": "来源",+ "tokens": "Tokens",+ "requests": "请求",+ "cached": "缓存",+ "lastMetered": "最近计量"+ },+ "goneSource": "已删除",+ "goneModel": "型号已不在列表中"+ },+ "byDay": {+ "title": "按日",+ "chart": "每日计量 token,{{from}} 至 {{to}}",+ "column": "{{day}} · {{tokens}} tokens",+ "peak": "峰值 {{tokens}},出现在 {{day}}",+ "quiet": "这个区间没有任何一天有计量数据"+ }},"supplyTooltip": {"label": "供应:"