Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(ui): fold removed Sources into one Usage identity and never show raw IDs (#2212)
Call Whited3962f00020e
diff --git a/docs/plans/model-hub-contracts/usage-summary.schema.json b/docs/plans/model-hub-contracts/usage-summary.schema.jsonindex aae72f61d..858231d63 100644--- a/docs/plans/model-hub-contracts/usage-summary.schema.json+++ b/docs/plans/model-hub-contracts/usage-summary.schema.json@@ -306,7 +306,7 @@"minLength": 1},"label": {- "description": "Joined from current Source config; null once the Source is gone.",+ "description": "Joined from current Source config; null exactly when config no longer holds the Source (a live Source always has a display name). The UI folds every null-label Source into one Removed providers identity and never displays source_id.","type": ["string","null"@@ -376,12 +376,12 @@"additionalProperties": false,"properties": {"model_id": {- "description": "Ledger key, which for a long identifier is a head plus a digest rather than the identifier itself. Display label, never model_id.",+ "description": "Ledger key: the metered model identifier verbatim up to 200 characters, otherwise a head plus a digest. Display label when present; an unlisted model under a live Source displays this key only while it is verbatim.","type": "string","minLength": 1},"label": {- "description": "The model identity this row was metered under, joined from current Source config; null once the model is gone.",+ "description": "The model identity this row was metered under, joined from current Source config; null once the Source no longer lists the model.","type": ["string","null"diff --git a/docs/plans/model-hub-usage-metering.md b/docs/plans/model-hub-usage-metering.mdindex d4b94aa05..8d15ecf85 100644--- a/docs/plans/model-hub-usage-metering.md+++ b/docs/plans/model-hub-usage-metering.md@@ -1062,8 +1062,12 @@ be a lie rather than a glitch, and each is a catalog row (MH-USAGE-016..020):control asked for;- a `token_reports` shortfall reads as reports that never arrived, never as unusedcapacity, 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.+- no row ever displays an ID. A Source config no longer holds (report `label: null`)+ folds with every other such Source into one muted, last-sorted "Removed providers"+ identity, so totals stay exact without a `src_*` string on screen; a model its live+ Source no longer lists shows the model identifier it was metered under, marked+ removed, and only a digest-folded ledger key reads as "Unknown model"+ (MH-USAGE-017, MH-USAGE-034). The CSV keeps the raw IDs for machines.**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@@ -1144,7 +1148,7 @@ 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-levelrouting fork, so the Frame 09 landing replaced the whole tab shell — including the Usagetab. 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+exists precisely because a vanished Source keeps its usage in the report. A user whodeletes their last source loses the only route to what it cost, and a user reading thereport when a deletion lands is thrown off the tab mid-read.diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex d3592d1a2..0c65de089 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -620,7 +620,7 @@ scenarios:layer: unittest: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-016- id: MH-USAGE-017- name: A vanished model's ledger key never reaches the screen, while a vanished Source stays identifiable+ name: A vanished Source reads as Removed providers in the table, legend and filter, and no ID reaches the screenstatus: coveredkind: observationlayer: unit@@ -730,6 +730,17 @@ scenarios:test: ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-033related_tests:- ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-024+ - id: MH-USAGE-034+ name: Usage from Sources config let go folds into one muted, last identity with exact totals, and an unlisted model on a live Source reads by the model ID it was metered under+ status: covered+ kind: contract+ layer: unit+ test: ui/src/components/settings/models/usageProjection.test.ts::MH-USAGE-034+ related_tests:+ - tests/test_model_hub_l3.py::test_a_deleted_source_keeps_its_usage_and_reads_as_removed+ - ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-017+ - ui/src/components/settings/models/UsageTab.test.tsx::MH-USAGE-034+ - ui/e2e/model-catalog/usage.spec.ts- id: MH-USAGE-BACKEND-001name: Modern usage reports keep dense hourly buckets and distinct Unicode Source/model identitiesstatus: covereddiff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex 28ba0647a..e3d7cf4f9 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -11015,6 +11015,59 @@ def test_a_call_that_reached_no_model_is_never_metered(tmp_path: Path) -> None:asyncio.run(exercise())+def test_a_deleted_source_keeps_its_usage_and_reads_as_removed(tmp_path: Path) -> None:+ """MH-USAGE-034: the Usage tab folds a Source by the null label this report gives it.++ Deleting a Source lets config go, not the usage it metered: every row stays,+ with its counts, under the ID it was metered under, and only the label goes,+ because a configured Source always carries its name. A model its live Source+ stops listing keeps that Source's label and loses only its own.+ """++ async def exercise() -> None:+ gone = _source("src_usagegone01", "Deleted supplier")+ live = _source("src_usagelive01", "Live supplier")+ service = _service(tmp_path, sources=[gone, live])+ _canonicalize_fixed_test_routes(service)+ metered = [+ (gone.id, "glm-5.3", 100),+ (gone.id, "kimi-k2", 40),+ (live.id, "shared-model", 7),+ (live.id, "glm-4.6-air", 3),+ ]+ for source_id, model_id, input_tokens in metered:+ service.usage.record(+ source_id=source_id,+ model_id=model_id,+ usage=ProtocolUsageReport.of(input_tokens=input_tokens, cached_input_tokens=0, output_tokens=1),+ at=NOW,+ )+ with pytest.raises(ModelHubError) as guard:+ await service.delete_source(gone.id)+ await service.delete_source(+ gone.id,+ force=True,+ confirmed_remove_hops=guard.value.data["would_remove_hops"],+ confirmed_interruptions=guard.value.data["would_interrupt"],+ )++ report = service.usage_summary(window="24h")+ sources = {source["source_id"]: source for source in report["sources"]}+ labels = {+ source_id: (source["label"], {model["model_id"]: model["label"] for model in source["models"]})+ for source_id, source in sources.items()+ }+ assert labels == {+ gone.id: (None, {"glm-5.3": None, "kimi-k2": None}),+ live.id: ("Live supplier", {"shared-model": "shared-model", "glm-4.6-air": None}),+ }+ assert sources[gone.id]["input_tokens"] == 140+ assert report["totals"]["input_tokens"] == 150+ assert sum(row["input_tokens"] for bucket in report["buckets"] for row in bucket["rows"]) == 150++ asyncio.run(exercise())++def test_a_downstream_disconnect_meters_the_terminal_frame_exactly_once(tmp_path: Path,) -> None:diff --git a/ui/e2e/model-catalog/usage.spec.ts b/ui/e2e/model-catalog/usage.spec.tsindex 4ea819786..0785a7847 100644--- a/ui/e2e/model-catalog/usage.spec.ts+++ b/ui/e2e/model-catalog/usage.spec.ts@@ -234,6 +234,48 @@ test.describe('hermetic UsageTab', () => {expect(await scrollOwner.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);});+ // The fixture's deleted Sources are real `src_…` IDs, as the ledger keeps them.+ for (const width of [1280, 390]) {+ test(`MH-USAGE-034: removed providers fold into one muted, last identity at ${width}px, never an ID`, async ({ page }) => {+ await page.setViewportSize({ width, height: 844 });+ await openUsage(page, 'dark', '&removed=1');+ const body = page.locator('body');+ const legend = page.locator('.model-hub-usage-legend');+ const legendItems = legend.locator('.model-hub-usage-legend-item');+ const groups = page.getByRole('group', { name: 'Group' });+ const rowNames = page.locator('.model-hub-usage-details tbody .model-hub-usage-row-name');++ for (const group of ['Model', 'Source']) {+ await groups.getByRole('button', { name: group, exact: true }).click();+ await expect(legendItems.last()).toContainText('Removed providers');+ await expect(legendItems.filter({ hasText: 'Removed providers' })).toHaveCount(1);+ expect(await legendItems.last().locator('.model-hub-usage-legend-swatch')+ .evaluate((node) => (node as HTMLElement).style.background)).toBe('var(--muted)');+ await expect(legend).not.toContainText('src_');+ const hitAreas = page.locator('.model-hub-usage-hit-area');+ await hitAreas.nth((await hitAreas.count()) - 3).hover();+ const dialog = page.getByRole('dialog', { name: 'Usage bucket details' });+ await expect(dialog).toContainText('Removed providers');+ await expect(dialog).not.toContainText('src_');+ await page.mouse.click(4, 4);+ }+ await groups.getByRole('button', { name: 'Model', exact: true }).click();+ await expect(legend).toContainText('Same supplier · glm-4.6-air');++ await expect(rowNames.last()).toHaveText('Removed providers');+ await expect(page.locator('.model-hub-usage-details')).toContainText('Same supplier · glm-4.6-air');+ await page.getByRole('button', { name: 'By source' }).click();+ await expect(rowNames.last()).toHaveText('Removed providers');+ await expect(rowNames.filter({ hasText: 'Removed providers' })).toHaveCount(1);++ await page.getByRole('button', { name: 'All Source' }).click();+ await expect(page.getByRole('option', { name: /Removed providers/ })).toBeVisible();+ await expect(body).not.toContainText('src_');+ await expect(body).not.toContainText('Unknown model');+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);+ });+ }+test('MH-USAGE-029: the API-price value holds the narrow layout and plots as dollars', async ({ page }) => {await page.setViewportSize({ width: 360, height: 844 });await openUsage(page, 'dark', '&priced=1');diff --git a/ui/e2e/model-catalog/usageFixture.tsx b/ui/e2e/model-catalog/usageFixture.tsxindex d837323cf..b030c7e14 100644--- a/ui/e2e/model-catalog/usageFixture.tsx+++ b/ui/e2e/model-catalog/usageFixture.tsx@@ -35,11 +35,24 @@ const localAt = (ms: number): string => {const dayKey = (ms: number): string => localAt(ms).slice(0, 10);+// `?removed=1` adds what the ledger keeps after config lets go: a deleted+// Source that metered two models, a second deleted Source, and a model its+// live Source no longer lists.+const REMOVED = params.get('removed') === '1';+const REMOVED_SOURCES = ['src_d1f4adc47c3f', 'src_b52ba34d0659'];+const rowsFor = (index: number, count: number): UsageBucketRow[] => {- if (index === 1) return [row({ source_id: 'source-alpha' })];- if (index === Math.floor(count / 2)) return [row({ source_id: 'source-beta' })];- if (index === count - 2) return [row({ source_id: 'source-alpha', model_id: 'model-second' })];- return [];+ const rows: UsageBucketRow[] = [];+ if (index === 1) rows.push(row({ source_id: 'source-alpha' }));+ if (index === Math.floor(count / 2)) rows.push(row({ source_id: 'source-beta' }));+ if (index === count - 2) rows.push(row({ source_id: 'source-alpha', model_id: 'model-second' }));+ if (REMOVED) {+ if (index === 2) rows.push(row({ source_id: REMOVED_SOURCES[0], model_id: 'glm-5.3' }));+ if (index === count - 3) rows.push(row({ source_id: REMOVED_SOURCES[0], model_id: 'kimi-k2' }));+ if (index === count - 3) rows.push(row({ source_id: REMOVED_SOURCES[1], model_id: 'deepseek-v3' }));+ if (index === Math.floor(count / 2)) rows.push(row({ source_id: 'source-alpha', model_id: 'glm-4.6-air' }));+ }+ return rows;};// `?priced=1` serves the report as a server with API-price valuation does.@@ -85,6 +98,7 @@ const makeReport = (windowKey: UsageWindowKey): UsageReport => {models: [{ model_id: 'model-shared', label: 'Same model', ...counters(cost(1.5)) },{ model_id: 'model-second', label: 'Second model', ...counters(cost(1.5)) },+ ...(REMOVED ? [{ model_id: 'glm-4.6-air', label: null, ...counters(cost(1.5)) }] : []),],},{@@ -94,6 +108,14 @@ const makeReport = (windowKey: UsageWindowKey): UsageReport => {...counters(cost(1.5)),models: [{ model_id: 'model-shared', label: 'Same model', ...counters(cost(1.5)) }],},+ ...(REMOVED ? REMOVED_SOURCES.map((source_id) => ({+ source_id,+ label: null,+ last_metered_at: null,+ ...counters(cost(1.5)),+ models: (source_id === REMOVED_SOURCES[0] ? ['glm-5.3', 'kimi-k2'] : ['deepseek-v3'])+ .map((model_id) => ({ model_id, label: null, ...counters(cost(1.5)) })),+ })) : []),],days: [],window_key: windowKey,diff --git a/ui/src/components/settings/models/UsageTab.test.tsx b/ui/src/components/settings/models/UsageTab.test.tsxindex 2657e553d..a12f20dbc 100644--- a/ui/src/components/settings/models/UsageTab.test.tsx+++ b/ui/src/components/settings/models/UsageTab.test.tsx@@ -106,22 +106,85 @@ describe('UsageTab', () => {expect(heading?.textContent).not.toContain('Sep 24, 2026');});- it('MH-USAGE-017: keeps a vanished Source identifiable and a vanished model unnamed', () => {+ it('MH-USAGE-017: folds a vanished Source into Removed providers and never shows its IDs', async () => {const vanishedModelId = 'model-opaque-digest-9f2c1d';const { container } = draw(report({- sources: [{- source_id: 'source-vanished',- label: null,- last_metered_at: null,- ...counters(),- models: [{ model_id: vanishedModelId, label: null, ...counters() }],- }],- buckets: [bucket('00', [row({ source_id: 'source-vanished', model_id: vanishedModelId })])],+ sources: [+ {+ source_id: 'source-a',+ label: 'Live supplier',+ last_metered_at: null,+ ...counters(),+ models: [{ model_id: 'model-a', label: 'Live model', ...counters() }],+ },+ {+ source_id: 'src_vanished01',+ label: null,+ last_metered_at: null,+ ...counters({ requests: 4 }),+ models: [+ { model_id: vanishedModelId, label: null, ...counters() },+ { model_id: 'glm-5.3', label: null, ...counters() },+ ],+ },+ ],+ buckets: [bucket('00', [+ row({ source_id: 'src_vanished01', model_id: vanishedModelId, requests: 5 }),+ row({ source_id: 'src_vanished01', model_id: 'glm-5.3', requests: 5 }),+ row(),+ ])],}));+ const table = () => within(screen.getByRole('table'));+ const names = () => [...container.querySelectorAll('tbody .model-hub-usage-row-name')].map((cell) => cell.textContent);++ expect(names()).toEqual(['Live supplier · Live model', 'Removed providers']);+ expect(table().getByText('Usage kept after these providers were deleted')).toBeTruthy();+ expect(table().getByText('10')).toBeTruthy();+ await userEvent.click(screen.getByRole('button', { name: 'By source' }));+ expect(names()).toEqual(['Live supplier', 'Removed providers']);+ // The aggregate closes the table whichever way it is sorted.+ await userEvent.click(screen.getByRole('button', { name: /sorted descending/i }));+ expect(names()).toEqual(['Live supplier', 'Removed providers']);+ await userEvent.click(screen.getByRole('button', { name: 'Model' }));+ expect(container.querySelector('.model-hub-usage-legend')?.textContent).toContain('Removed providers');+ await userEvent.click(screen.getByRole('button', { name: 'All Source' }));+ expect(screen.getByRole('option', { name: /Removed providers/ })).toBeTruthy();+ for (const hidden of ['src_vanished01', vanishedModelId, 'glm-5.3', 'Unknown model']) {+ expect(container.textContent).not.toContain(hidden);+ }+ });- expect(container.textContent).toContain('source-vanished');- expect(container.textContent).toContain('Unknown model');- expect(container.textContent).not.toContain(vanishedModelId);+ it('MH-USAGE-034: a picked Source deleted before the next report reads as the whole Removed providers aggregate', async () => {+ const source = (source_id: string, label: string | null) => ({+ source_id, label, last_metered_at: null, ...counters(), models: [],+ });+ const rows = [+ row({ source_id: 'source-a', requests: 1 }),+ row({ source_id: 'src_doomed01', model_id: 'model-d', requests: 2 }),+ row({ source_id: 'src_gone01', model_id: 'model-g', requests: 4 }),+ ];+ const page = (value: UsageReport) => (+ <I18nextProvider i18n={i18n}>+ <UsageTab usage={readyRegion(value)} windowKey="24h" onWindowChange={vi.fn()} />+ </I18nextProvider>+ );+ const before = report({+ sources: [source('source-a', 'Live supplier'), source('src_doomed01', 'Doomed supplier'), source('src_gone01', null)],+ buckets: [bucket('00', rows)],+ });+ const { container, rerender } = render(page(before));+ await userEvent.click(screen.getByRole('button', { name: 'All Source' }));+ await userEvent.click(screen.getByRole('option', { name: /Doomed supplier/ }));+ await userEvent.keyboard('{Escape}');+ await userEvent.click(screen.getByRole('button', { name: 'By source' }));+ const names = () => [...container.querySelectorAll('tbody .model-hub-usage-row-name')].map((cell) => cell.textContent);+ expect(names()).toEqual(['Doomed supplier']);++ rerender(page({ ...before, sources: [source('source-a', 'Live supplier'), source('src_doomed01', null), source('src_gone01', null)] }));+ expect(screen.getByRole('button', { name: 'Removed providers' })).toBeTruthy();+ expect(names()).toEqual(['Removed providers']);+ expect(within(screen.getByRole('table')).getAllByText('6').length).toBeGreaterThan(0);+ expect(container.textContent).not.toContain('src_');});it('MH-USAGE-018: reads a shortfall as reports that never arrived', () => {@@ -142,43 +205,42 @@ describe('UsageTab', () => {expect(container.textContent).toContain('All tokens');});- it('uses the translated historical-model label for filters, chart, table, and collisions', async () => {+ it('names an unlisted model by its model ID and keeps the translated unknown name for a folded key', async () => {const translated = createInstance();await translated.use(initReactI18next).init({lng: 'de',fallbackLng: 'en',resources: {en: { translation: en },- de: { translation: { settings: { models: { usage: { unknownModel: 'Historisches Modell' } } } } },+ de: { translation: { settings: { models: { usage: { unknownModel: 'Historisches Modell', removedModel: 'Entfernt' } } } } },},interpolation: { escapeValue: false },});+ const foldedKey = `${'m'.repeat(200)}~${'0'.repeat(64)}`;const value = report({sources: [{source_id: 'source-a',label: 'Supplier',last_metered_at: null,...counters(),- models: [{ model_id: 'model-a', label: 'Historisches Modell', ...counters() }],+ models: [{ model_id: 'model-a', label: 'Model', ...counters() }],}],- buckets: [bucket('00', [row({ model_id: 'removed-model' }), row()])],+ buckets: [bucket('00', [row({ model_id: 'removed-model' }), row({ model_id: foldedKey }), row()])],});const { container } = render(<I18nextProvider i18n={translated}><UsageTab usage={readyRegion(value)} windowKey="24h" onWindowChange={vi.fn()} /></I18nextProvider>,);- const labels = [- 'Supplier · Historisches Modell · source-a · removed-model',- 'Supplier · Historisches Modell · source-a · model-a',- ];+ const labels = ['Supplier · removed-model', 'Supplier · Historisches Modell', 'Supplier · Model'];for (const label of labels) expect(within(screen.getByRole('table')).getByText(label)).toBeTruthy();+ expect(within(screen.getByRole('table')).getAllByText('Supplier · Entfernt')).toHaveLength(2);await userEvent.click(screen.getByRole('button', { name: 'All Model' }));for (const label of labels) expect(screen.getByRole('option', { name: new RegExp(label) })).toBeTruthy();fireEvent.pointerDown(document.body);await userEvent.click(screen.getByRole('button', { name: 'Model' }));for (const label of labels) expect(container.querySelector('.model-hub-usage-legend')?.textContent).toContain(label);- expect(container.textContent).not.toContain('Unknown model');+ expect(container.textContent).not.toContain(foldedKey);});it('formats every percentage in the active locale even when translations fall back', async () => {@@ -529,8 +591,8 @@ describe('UsageTab', () => {});draw(value);- expect(screen.getByText('Same source label · Same model label · source-a')).toBeTruthy();- expect(screen.getByText('Same source label · Same model label · source-b')).toBeTruthy();+ expect(screen.getByText('Same source label · Same model label')).toBeTruthy();+ expect(screen.getByText('Same source label (2) · Same model label')).toBeTruthy();expect(screen.getByText('All tokens = input + output. Cache reads are included in input and shown separately.')).toBeTruthy();expect(screen.getAllByText('50.0%').length).toBeGreaterThan(0);});diff --git a/ui/src/components/settings/models/UsageTab.tsx b/ui/src/components/settings/models/UsageTab.tsxindex bca68f9c7..598329d2a 100644--- a/ui/src/components/settings/models/UsageTab.tsx+++ b/ui/src/components/settings/models/UsageTab.tsx@@ -29,21 +29,19 @@ import {costIsUnpriced,filterBucketRows,filteredRows,+ foldUsageSelection,formatBucketAxisLabel,formatBucketLabel,formatBucketHeading,formatBucketRange,- identityDisplayLabel,- modelLabel,- pairKey,+ emptyCounters,reportHasPartialHistory,reportIsPriced,reportHasUnknownTokens,+ resolveUsageFilter,seriesFor,- sourceIdentityLabel,- sourceLabel,- usageLabelContext,usageCachedInputShare,+ usageIdentities,usageIsEmpty,usageIsPriced,usageHasNoPrice,@@ -53,9 +51,9 @@ import {usageTokensAreKnown,type UsageFilter,type UsageGroup,- type UsageIdentity,type UsageMetric,type UsageSeries,+ type UsageText,} from './usageProjection';import { USAGE_WINDOW_OPTIONS } from './usageProjection';import { buildUsageCsv } from './usageCsv';@@ -70,6 +68,11 @@ const SERIES_COLORS = ['var(--primary)',] as const;+/** The removed-Sources aggregate reads as history, not as one more supplier. */+const seriesColor = (item: UsageSeries): string => (item.removed+ ? 'var(--muted)'+ : SERIES_COLORS[item.colorIndex % SERIES_COLORS.length]);+type FilterOption = { key: string; label: string; detail?: string };type UsageTranslate = (key: string, options?: Record<string, unknown>) => string;@@ -88,6 +91,11 @@ const useUsageTranslation = () => {};};+const usageText = (t: UsageTranslate): UsageText => ({+ unknownModel: t('settings.models.usage.unknownModel'),+ removedSources: t('settings.models.usage.removedSources'),+});+const useCount = () => {const { i18n } = useTranslation();return React.useCallback((value: number) => new Intl.NumberFormat(i18n.language).format(value), [i18n.language]);@@ -270,7 +278,7 @@ const ChartLegend: React.FC<{className={cn('model-hub-usage-legend-item', isHidden && 'is-hidden')}onClick={() => onToggle(item.key)}>- <span className="model-hub-usage-legend-swatch" style={{ background: SERIES_COLORS[item.colorIndex % SERIES_COLORS.length] }} />+ <span className="model-hub-usage-legend-swatch" style={{ background: seriesColor(item) }} /><span>{labels.get(item.key) ?? item.label}</span><strong>{values.length === 0 ? blank : unpriced ? noPrice : atLeast(count(total), floor)}</strong></button>@@ -351,8 +359,11 @@ function UsageChart({? requestedIndex: null;const bars = report.window_key === '30d' || report.window_key === '60d';- const unknownModelLabel = t('settings.models.usage.unknownModel');- const series = React.useMemo(() => seriesFor(report, filter, group, metric, unknownModelLabel), [filter, group, metric, unknownModelLabel, report]);+ const { unknownModel, removedSources } = usageText(t);+ const series = React.useMemo(+ () => seriesFor(report, filter, group, metric, { unknownModel, removedSources }),+ [filter, group, metric, removedSources, report, unknownModel],+ );const labels = React.useMemo(() => new Map(series.map((item) => [item.key,item.key === 'total'@@ -413,7 +424,7 @@ function UsageChart({? (index + 0.5) / bucketCount: index / Math.max(1, bucketCount - 1)) * plotWidth;const yAt = (value: number) => top + plotHeight * (1 - value / max);- const colorOf = (item: UsageSeries) => SERIES_COLORS[item.colorIndex % SERIES_COLORS.length];+ const colorOf = seriesColor;const columnWidth = plotWidth / Math.max(1, bucketCount);if (bars) {return report.buckets.map((currentBucket, index) => {@@ -512,7 +523,7 @@ function UsageChart({y={y(offset)}width={columnWidth * 0.64}height={value === null ? 4 : Math.max(0, y(start) - y(offset))}- fill={value === null ? 'url(#usage-unknown-pattern)' : SERIES_COLORS[item.colorIndex % SERIES_COLORS.length]}+ fill={value === null ? 'url(#usage-unknown-pattern)' : seriesColor(item)}opacity={0.88}rx="2"/>@@ -767,7 +778,7 @@ function UsageChart({cx={x(activeIndex)}cy={y(value)}r="4"- fill={SERIES_COLORS[item.colorIndex % SERIES_COLORS.length]}+ fill={seriesColor(item)}stroke="var(--background)"strokeWidth="2"/>@@ -868,7 +879,7 @@ function UsageChart({<div className="model-hub-usage-tooltip-lines">{visibleSeries.map((item) => (<div key={item.key}>- <span><i style={{ background: SERIES_COLORS[item.colorIndex % SERIES_COLORS.length] }} />{labels.get(item.key) ?? item.label}</span>+ <span><i style={{ background: seriesColor(item) }} />{labels.get(item.key) ?? item.label}</span><b>{item.values[activeIndex as number] === null? t('settings.models.usage.blank'): item.unpriced[activeIndex as number]@@ -902,6 +913,7 @@ type TableRow = {key: string;label: string;detail: string;+ removed: boolean;counters: UsageCounters;};@@ -910,34 +922,22 @@ function tableRows(filter: UsageFilter,group: 'model' | 'source',pinnedKey: string | null,- unknownModelLabel: string,+ t: UsageTranslate,): TableRow[] {const buckets = pinnedKey === null ? report.buckets : report.buckets.filter((bucket) => bucket.key === pinnedKey);const rows = buckets.flatMap((bucket) => filterBucketRows(bucket, filter));- const grouped = new Map<string, TableRow>();- const labelContext = usageLabelContext(report, filteredRows(report, filter), unknownModelLabel);- for (const row of rows) {- const key = group === 'source' ? row.source_id : pairKey(row.source_id, row.model_id);- const identity = group === 'source'- ? null- : {- key,- sourceId: row.source_id,- modelId: row.model_id,- sourceLabel: sourceLabel(report, row.source_id),- modelLabel: modelLabel(report, row.source_id, row.model_id),- } satisfies UsageIdentity;- const previous = grouped.get(key);- grouped.set(key, {- key,- label: group === 'source'- ? sourceIdentityLabel(report, row.source_id, labelContext)- : identityDisplayLabel(identity!, unknownModelLabel, labelContext),- detail: group === 'source' ? '' : sourceIdentityLabel(report, row.source_id, labelContext),- counters: aggregateCounters([...(previous ? [previous.counters] : []), row]),- });- }- return [...grouped.values()];+ const identities = usageIdentities(report, group, usageText(t));+ return identities.of(rows).map((identity) => ({+ key: identity.key,+ label: identity.label,+ detail: identity.removed+ ? t('settings.models.usage.removedSourcesHint')+ : identity.unlisted+ ? `${identity.sourceLabel} · ${t('settings.models.usage.removedModel')}`+ : identity.sourceLabel,+ removed: identity.removed,+ counters: aggregateCounters(rows.filter((row) => identities.keyOf(row) === identity.key)),+ }));}const StatCard: React.FC<{ label: string; value: React.ReactNode; note: React.ReactNode }> = ({ label, value, note }) => (@@ -1009,30 +1009,18 @@ export const UsageTab: React.FC<{}const allRows = filteredRows(report, { sourceIds: [], modelKeys: [] });- const unknownModelLabel = t('settings.models.usage.unknownModel');- const labelContext = usageLabelContext(report, allRows, unknownModelLabel);- const sourceOptions: FilterOption[] = report.sources.map((source) => ({- key: source.source_id,- label: sourceIdentityLabel(report, source.source_id, labelContext),+ // A Source that metered nothing in this window still offers itself.+ const sourceOptions: FilterOption[] = usageIdentities(report, 'source', usageText(t))+ .of([...allRows, ...report.sources.map((source) => ({ ...emptyCounters(), source_id: source.source_id, model_id: '' }))])+ .map((identity) => ({ key: identity.key, label: identity.label }));+ const modelOptions: FilterOption[] = usageIdentities(report, 'model', usageText(t)).of(allRows).map((identity) => ({+ key: identity.key,+ label: identity.label,+ detail: identity.unlisted ? t('settings.models.usage.removedModel') : undefined,}));- const modelOptions = [...new Map(- allRows.map((row) => {- const key = pairKey(row.source_id, row.model_id);- const identity = {- key,- sourceId: row.source_id,- modelId: row.model_id,- sourceLabel: sourceLabel(report, row.source_id),- modelLabel: modelLabel(report, row.source_id, row.model_id),- } satisfies UsageIdentity;- return [key, {- key,- label: identityDisplayLabel(identity, unknownModelLabel, labelContext),- detail: identity.modelLabel ? undefined : unknownModelLabel,- }];- }),- ).values()];- const filter: UsageFilter = { sourceIds, modelKeys };+ // What the filters show selected; a Source deleted since it was picked reads as the aggregate.+ const selection = foldUsageSelection(report, { sourceIds, modelKeys });+ const filter = resolveUsageFilter(report, selection);const scopedRows = filteredRows(report, filter);const totals = aggregateCounters(scopedRows);const partialHistory = reportHasPartialHistory(report, filter);@@ -1043,9 +1031,11 @@ export const UsageTab: React.FC<{? null: report.buckets.find((bucket) => bucket.key === pinnedKey) ?? null;const activePinnedKey = pinnedBucket?.key ?? null;- const rows = tableRows(report, filter, tableGroup, activePinnedKey, unknownModelLabel);+ const rows = tableRows(report, filter, tableGroup, activePinnedKey, t);const sortValue = (row: TableRow): number => usageMetricValue(row.counters, metric) ?? -1;- const sortedRows = [...rows].sort((left, right) => (sortValue(right) - sortValue(left)) * (sortAscending ? -1 : 1));+ // The removed aggregate closes the list whichever way it is sorted.+ const sortedRows = [...rows].sort((left, right) => (Number(left.removed) - Number(right.removed))+ || (sortValue(right) - sortValue(left)) * (sortAscending ? -1 : 1));const tableTotal = aggregateCounters((activePinnedKey === null ? report.buckets : report.buckets.filter((bucket) => bucket.key === activePinnedKey)).flatMap((bucket) => filterBucketRows(bucket, filter)),@@ -1097,14 +1087,14 @@ export const UsageTab: React.FC<{label={t('settings.models.usage.filters.source') as string}icon={<Network aria-hidden className="size-3.5" />}options={sourceOptions}- selected={sourceIds}+ selected={selection.sourceIds}onChange={setSourceIds}/><MultiFilterlabel={t('settings.models.usage.filters.model') as string}icon={<Cpu aria-hidden className="size-3.5" />}options={modelOptions}- selected={modelKeys}+ selected={selection.modelKeys}onChange={setModelKeys}/><div className="model-hub-usage-select">@@ -1135,9 +1125,9 @@ export const UsageTab: React.FC<{</Button>)}<span className="model-hub-usage-filter-context">- {sourceIds.length > 0 ? t('settings.models.usage.filters.sourceCount', { count: sourceIds.length }) : t('settings.models.usage.filters.allSources')}+ {selection.sourceIds.length > 0 ? t('settings.models.usage.filters.sourceCount', { count: selection.sourceIds.length }) : t('settings.models.usage.filters.allSources')}<span>·</span>- {modelKeys.length > 0 ? t('settings.models.usage.filters.modelCount', { count: modelKeys.length }) : t('settings.models.usage.filters.allModels')}+ {selection.modelKeys.length > 0 ? t('settings.models.usage.filters.modelCount', { count: selection.modelKeys.length }) : t('settings.models.usage.filters.allModels')}</span></div>@@ -1285,7 +1275,7 @@ export const UsageTab: React.FC<{|| tableTotal.api_cost_lower_bound === true || usageHasNoPrice(row.counters));const share = shareUnknown || value === null || totalValue === null || totalValue === 0 ? null : value / totalValue;return (- <tr key={row.key}>+ <tr key={row.key} className={cn(row.removed && 'is-removed')}><th scope="row"><span className="model-hub-usage-row-name">{row.label}</span>{row.detail && <span className="model-hub-usage-row-detail">{row.detail}</span>}diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex e9766764e..43d562054 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -2877,6 +2877,11 @@background: var(--model-hub-wash-03);}+/* Usage that outlived its providers: kept in every total, set back from the live rows. */+.model-hub-usage-table-scroll tbody tr.is-removed th {+ color: var(--muted);+}+.model-hub-usage-row-name,.model-hub-usage-row-detail {display: block;diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 44ab97731..fb812c6d8 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -824,18 +824,20 @@ export type UsageByModel = UsageCounters & {/** False when no price is known for the model: its tokens are in* `excluded_tokens`. Present exactly when the report is priced. */priced?: boolean;- /** 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. */+ /** Ledger key: the metered model identifier verbatim up to 200 characters,+ * otherwise a head plus a digest — a string nobody typed. Display `label`;+ * without one, `usageProjection.usageModelName` shows this key only while+ * it is verbatim. */model_id: string;/** The model identity this row was metered under, joined from current Source- * config; null once the model is gone. */+ * config; null once the Source no longer lists the model. */label: string | null;};export type UsageBySource = UsageCounters & {source_id: string;- /** Joined from current Source config; null once the Source is gone. */+ /** Joined from current Source config; null exactly when config no longer+ * holds the Source. The UI folds all such Sources into one identity. */label: string | null;/** When this Source last had a call metered, served or billed-and-failed. */last_metered_at: string | null;diff --git a/ui/src/components/settings/models/usageCsv.ts b/ui/src/components/settings/models/usageCsv.tsindex d3771cf7b..d13175bf0 100644--- a/ui/src/components/settings/models/usageCsv.ts+++ b/ui/src/components/settings/models/usageCsv.ts@@ -3,15 +3,10 @@ import {filterBucketRows,emptyCounters,modelLabel,- pairKey,- sourceIdentityLabel,- sourceLabel,- usageLabelContext,usageNonCachedInput,usageTokensAreKnown,usageTotalTokens,type UsageFilter,- type UsageIdentity,} from './usageProjection';export function csvCell(value: string | number): string {@@ -47,7 +42,10 @@ export function buildUsageCsv(headers: UsageCsvHeaders,unknownModel: string,): string {- const labelContext = usageLabelContext(report, report.buckets.flatMap((bucket) => bucket.rows), unknownModel);+ // The export keeps every row under the IDs it was metered under; a label is+ // what config names that ID, and a Source config let go reads as its ID.+ const sourceLabel = (sourceId: string) => report.sources+ .find((source) => source.source_id === sourceId)?.label?.trim() || sourceId;const buckets = pinnedKey === null? report.buckets: report.buckets.filter((bucket) => bucket.key === pinnedKey);@@ -57,23 +55,17 @@ export function buildUsageCsv(return exportRows.map((row) => {const counters = row ?? (bucket.history_complete ? emptyCounters() : null);const knownTokens = counters !== null && usageTokensAreKnown(counters);- const identity = row === null ? null : {- key: pairKey(row.source_id, row.model_id),- sourceId: row.source_id,- modelId: row.model_id,- sourceLabel: sourceLabel(report, row.source_id),- modelLabel: modelLabel(report, row.source_id, row.model_id),- } satisfies UsageIdentity;+ const label = row === null ? null : modelLabel(report, row.source_id, row.model_id);return [bucket.key,bucket.start_at,bucket.end_at,String(bucket.history_complete),row?.source_id ?? '',- identity?.modelLabel ?? '',+ label ?? '',row?.model_id ?? '',- row === null ? '' : sourceIdentityLabel(report, row.source_id, labelContext),- row === null ? '' : identity?.modelLabel || unknownModel,+ row === null ? '' : sourceLabel(row.source_id),+ row === null ? '' : label || unknownModel,row?.requests ?? (bucket.history_complete ? 0 : ''),row?.token_reports ?? (bucket.history_complete ? 0 : ''),knownTokens ? counters.input_tokens : '',diff --git a/ui/src/components/settings/models/usageProjection.test.ts b/ui/src/components/settings/models/usageProjection.test.tsindex f1715e463..d9bede21a 100644--- a/ui/src/components/settings/models/usageProjection.test.ts+++ b/ui/src/components/settings/models/usageProjection.test.ts@@ -3,16 +3,17 @@ import { describe, expect, it } from 'vitest';import type { UsageBucket, UsageBucketRow, UsageCounters, UsageReport } from './types';import {aggregateCounters,+ filteredRows,formatBucketAxisLabel,formatBucketHeading,formatBucketRange,- identityLabel,pairKey,+ REMOVED_SOURCES_KEY,reportHasPartialHistory,reportIsPriced,+ resolveUsageFilter,seriesFor,- sourceIdentityLabel,- usageLabelContext,+ usageIdentities,usageIsEmpty,usageIsPriced,usageMetricValue,@@ -20,6 +21,10 @@ import {usageTotalTokens,} from './usageProjection';+const TEXT = { unknownModel: 'Unknown model', removedSources: 'Removed providers' };+const TEXT_ZH = { unknownModel: '未知模型', removedSources: '已移除的供应商' };+const NO_FILTER = { sourceIds: [], modelKeys: [] };+const counters = (over: Partial<UsageCounters> = {}): UsageCounters => ({requests: 2,token_reports: 2,@@ -71,7 +76,7 @@ describe('usageProjection', () => {expect(usageNonCachedInput(value)).toBe(52_220);});- it('keeps source/model identity separate even when labels match', () => {+ it('keeps source/model identity separate even when labels match, without printing an ID', () => {const value = reportWith([bucket('00', [row()]),bucket('01', [row({ source_id: 'source-b' })]),@@ -83,107 +88,97 @@ describe('usageProjection', () => {...counters(),models: [{ model_id: 'model-a', label: 'Model', ...counters() }],});- const series = seriesFor(value, { sourceIds: [], modelKeys: [] }, 'model', 'tokens', 'Unknown model');+ const series = seriesFor(value, NO_FILTER, 'model', 'tokens', TEXT);expect(series.map((item) => item.key)).toEqual([pairKey('source-a', 'model-a'), pairKey('source-b', 'model-a')]);- expect(series.map((item) => item.label)).toEqual([- 'Supplier · Model · source-a',- 'Supplier · Model · source-b',- ]);+ expect(series.map((item) => item.label)).toEqual(['Supplier · Model', 'Supplier (2) · Model']);+ expect(seriesFor(value, NO_FILTER, 'source', 'tokens', TEXT).map((item) => item.label)).toEqual(['Supplier', 'Supplier (2)']);});- it('localizes an unknown model in model-grouped series', () => {- const value = reportWith([bucket('00', [row({ model_id: 'removed-model' })])]);- expect(seriesFor(value, { sourceIds: [], modelKeys: [] }, 'model', 'tokens', '未知模型')[0]?.label).toBe('Supplier · 未知模型');- expect(identityLabel({- key: pairKey('source-a', 'removed-model'),- sourceId: 'source-a',- modelId: 'removed-model',- sourceLabel: 'Supplier',- modelLabel: null,- }, '未知模型')).toBe('Supplier · 未知模型');+ it('names a model its live Source no longer lists by the model ID it was metered under', () => {+ const value = reportWith([bucket('00', [row({ model_id: 'glm-5.3' })])]);+ expect(usageIdentities(value, 'model', TEXT_ZH).get(pairKey('source-a', 'glm-5.3')))+ .toMatchObject({ label: 'Supplier · glm-5.3', sourceLabel: 'Supplier', unlisted: true, removed: false });});- it('disambiguates localized unknown-model collisions', () => {- const value = reportWith([bucket('00', [- row({ model_id: 'removed-model' }),- row({ model_id: 'model-a' }),- ])]);- value.sources[0]!.models = [- { model_id: 'model-a', label: '未知模型', ...counters() },- ];-- expect(seriesFor(value, { sourceIds: [], modelKeys: [] }, 'model', 'tokens', '未知模型').map((item) => item.label)).toEqual([- 'Supplier · 未知模型 · source-a · removed-model',- 'Supplier · 未知模型 · source-a · model-a',- ]);+ it('keeps the unknown-model name only for a ledger key that no longer spells a model ID', () => {+ const foldedKey = `${'m'.repeat(200)}~${'0'.repeat(64)}`;+ // The ledger counts code points: 200 astral characters are still verbatim.+ const astralId = '🧠'.repeat(200);+ const value = reportWith([bucket('00', [row({ model_id: foldedKey }), row({ model_id: astralId })])]);+ expect(seriesFor(value, NO_FILTER, 'model', 'tokens', TEXT_ZH).map((item) => item.label))+ .toEqual(['Supplier · 未知模型', `Supplier · ${astralId}`]);});- it('keeps final source labels unique when a suffix collides with a literal label', () => {- const value = reportWith([- bucket('00', [- row({ source_id: 'source-a' }),- row({ source_id: 'source-b' }),- row({ source_id: 'source-c' }),- ]),+ it('keeps a configured model name over an unlisted one that reads the same', () => {+ const value = reportWith([bucket('00', [row({ model_id: 'Model' }), row()])]);+ const labels = seriesFor(value, NO_FILTER, 'model', 'tokens', TEXT);+ expect(labels.map((item) => [item.key, item.label])).toEqual([+ [pairKey('source-a', 'Model'), 'Supplier · Model (2)'],+ [pairKey('source-a', 'model-a'), 'Supplier · Model'],]);- value.sources = [- { source_id: 'source-a', label: 'Provider', last_metered_at: null, ...counters(), models: [] },- { source_id: 'source-b', label: 'Provider', last_metered_at: null, ...counters(), models: [] },- { source_id: 'source-c', label: 'Provider · source-a', last_metered_at: null, ...counters(), models: [] },- ];- const context = usageLabelContext(value, value.buckets.flatMap((bucket) => bucket.rows), 'Unknown model');- const labels = ['source-a', 'source-b', 'source-c'].map((sourceId) => (- sourceIdentityLabel(value, sourceId, context)- ));-- expect(new Set(labels).size).toBe(labels.length);- expect(labels.every((label) => label.length > 0)).toBe(true);});- it('keeps final identity labels unique after collision suffixes are added', () => {- const value = reportWith([- bucket('00', [- row({ model_id: 'old-a' }),- row({ model_id: 'old-b' }),- row({ source_id: 'source-b', model_id: 'literal-model' }),- ]),- ]);- value.sources = [- {- source_id: 'source-a',- label: 'Supplier',- last_metered_at: null,- ...counters(),- models: [],- },- {- source_id: 'source-b',- label: 'Supplier',- last_metered_at: null,- ...counters(),- models: [{- model_id: 'literal-model',- label: 'Unknown model · source-a · old-a',- ...counters(),- }],- },- ];-- const labels = seriesFor(- value,- { sourceIds: [], modelKeys: [] },- 'model',- 'tokens',- 'Unknown model',- ).map((series) => series.label);-- expect(new Set(labels).size).toBe(labels.length);- expect(labels).toContain('Supplier · Unknown model · source-a · old-a');+ // The report leaves a Source's label null exactly when config let it go.+ describe('Sources config let go', () => {+ const withRemoved = () => {+ const value = reportWith([+ bucket('00', [+ row({ source_id: 'src_d1f4adc47c3f', model_id: 'glm-5.3', requests: 3 }),+ row(),+ ]),+ bucket('01', [+ row({ source_id: 'src_d1f4adc47c3f', model_id: 'kimi-k2' }),+ row({ source_id: 'src_b52ba34d0659', model_id: 'deepseek-v3' }),+ ]),+ ]);+ value.sources.push(+ { source_id: 'src_d1f4adc47c3f', label: null, last_metered_at: null, ...counters(), models: [] },+ { source_id: 'src_b52ba34d0659', label: null, last_metered_at: null, ...counters(), models: [] },+ );+ return value;+ };++ it('MH-USAGE-034: fold into one last, muted series in either grouping, keeping every count', () => {+ const value = withRemoved();+ const total = seriesFor(value, NO_FILTER, 'total', 'requests', TEXT)[0]!.values;+ for (const group of ['model', 'source'] as const) {+ const series = seriesFor(value, NO_FILTER, group, 'requests', TEXT);+ expect(series.map((item) => item.label)).toEqual([group === 'model' ? 'Supplier · Model' : 'Supplier', 'Removed providers']);+ expect(series.at(-1)).toMatchObject({ key: REMOVED_SOURCES_KEY, removed: true, values: [3, 4] });+ expect(series.flatMap((item) => item.label)).not.toContainEqual(expect.stringContaining('src_'));+ expect(series.reduce((sum, item) => sum + (item.values[0] ?? 0) + (item.values[1] ?? 0), 0))+ .toBe((total[0] ?? 0) + (total[1] ?? 0));+ }+ });++ it('select every folded row when the aggregate is picked in either filter', () => {+ const value = withRemoved();+ for (const selection of [+ { sourceIds: [REMOVED_SOURCES_KEY], modelKeys: [] },+ { sourceIds: [], modelKeys: [REMOVED_SOURCES_KEY] },+ ]) {+ const rows = filteredRows(value, resolveUsageFilter(value, selection));+ expect(rows.map((item) => item.model_id).sort()).toEqual(['deepseek-v3', 'glm-5.3', 'kimi-k2']);+ }+ const live = filteredRows(value, resolveUsageFilter(value, { sourceIds: ['source-a'], modelKeys: [REMOVED_SOURCES_KEY] }));+ expect(live).toEqual([]);+ });++ it('never fold a live Source, even one that metered nothing in the window', () => {+ const value = reportWith([bucket('00', [row({ source_id: 'src_d1f4adc47c3f', model_id: 'glm-5.3' })])]);+ value.sources = [+ { source_id: 'source-a', label: 'Supplier', last_metered_at: null, ...counters(), models: [] },+ { source_id: 'src_d1f4adc47c3f', label: null, last_metered_at: null, ...counters(), models: [] },+ ];+ const identities = usageIdentities(value, 'source', TEXT);+ expect(identities.of([row({ source_id: 'source-a' }), row({ source_id: 'src_d1f4adc47c3f' })]).map((item) => item.label))+ .toEqual(['Supplier', 'Removed providers']);+ });});it('renders incomplete empty buckets as unavailable gaps, not zero', () => {const value = reportWith([bucket('00', [], false), bucket('01', [], false)]);- const series = seriesFor(value, { sourceIds: [], modelKeys: [] }, 'total', 'tokens', 'Unknown model');+ const series = seriesFor(value, NO_FILTER, 'total', 'tokens', TEXT);expect(series[0]?.values).toEqual([null, null]);expect(usageIsEmpty(value)).toBe(false);expect(reportHasPartialHistory(value, { sourceIds: [], modelKeys: [] })).toBe(true);diff --git a/ui/src/components/settings/models/usageProjection.ts b/ui/src/components/settings/models/usageProjection.tsindex 02257272a..ffb847023 100644--- a/ui/src/components/settings/models/usageProjection.ts+++ b/ui/src/components/settings/models/usageProjection.ts@@ -17,22 +17,6 @@ export type UsageFilter = {modelKeys: readonly string[];};-export type UsageIdentity = {- sourceId: string;- modelId: string;- sourceLabel: string;- modelLabel: string | null;- key: string;-};--export type UsageLabelContext = {- sourceCollisionLabels: ReadonlySet<string>;- sourceDisplayLabels: ReadonlyMap<string, string>;- identityCollisionLabels: ReadonlySet<string>;- identityModelCollisionKeys: ReadonlySet<string>;- identityDisplayLabels: ReadonlyMap<string, string>;-};-export type UsageSeries = {key: string;label: string;@@ -42,6 +26,8 @@ export type UsageSeries = {floors: boolean[];/** Per bucket, whether nothing in the value is priced, so it reads as no price, never $0; cost only. */unpriced: boolean[];+ /** The removed-Sources aggregate, drawn in a neutral colour rather than a palette one. */+ removed?: boolean;};export const PAIR_SEPARATOR = '\u0000';@@ -222,165 +208,212 @@ export function formatBucketHeading(bucket: UsageBucket, locale: string): { rangreturn { range, zone };}-export function sourceLabel(report: UsageReport, sourceId: string): string {- const source = report.sources.find((candidate) => candidate.source_id === sourceId);- return source?.label?.trim() || sourceId;-}+/**+ * Every Source config no longer holds, as one identity. It sorts before any+ * Source ID or pair key, and neither can spell it: a pair key never starts with+ * its separator.+ */+export const REMOVED_SOURCES_KEY = `${PAIR_SEPARATOR}removed`;++/**+ * The longest ledger key, in code points as the ledger counts them, that is+ * still the identifier itself; a longer one is a head plus a digest.+ */+const LEDGER_VERBATIM_MAX_LENGTH = 200;++export type UsageText = {+ unknownModel: string;+ removedSources: string;+};++export type UsageIdentity = {+ key: string;+ label: string;+ /** Beside a model, the Source it was metered under; empty for a Source and for the removed aggregate. */+ sourceLabel: string;+ /** The aggregate of every Source config no longer holds. */+ removed: boolean;+ /** A model its live Source does not list, named by the ID it was metered under. */+ unlisted: boolean;+};++export type UsageIdentities = {+ keyOf: (row: UsageBucketRow) => string;+ get: (key: string) => UsageIdentity;+ /** These rows' identities in first-metered order, the removed aggregate last. */+ of: (rows: readonly UsageBucketRow[]) => UsageIdentity[];+};++const allRows = (report: UsageReport): UsageBucketRow[] => report.buckets.flatMap((bucket) => bucket.rows);++/**+ * The Sources config still holds, by ID. A configured Source always carries its+ * name, so the report leaves the label null exactly when config let it go.+ */+const liveSources = (report: UsageReport) => new Map(report.sources+ .filter((source) => source.label != null)+ .map((source) => [source.source_id, source.label!.trim()] as const));+/** The model label config holds for this pair, or null when the Source does not list the model. */export function modelLabel(report: UsageReport, sourceId: string, modelId: string): string | null {const source = report.sources.find((candidate) => candidate.source_id === sourceId);const model = source?.models.find((candidate) => candidate.model_id === modelId);return model?.label?.trim() || null;}-export function usageIdentities(report: UsageReport, rows: readonly UsageBucketRow[]): UsageIdentity[] {- const keys = new Set(rows.map((row) => pairKey(row.source_id, row.model_id)));- return [...keys].map((key) => {- const separator = key.indexOf(PAIR_SEPARATOR);- const sourceId = key.slice(0, separator);- const modelId = key.slice(separator + 1);- return {- key,- sourceId,- modelId,- sourceLabel: sourceLabel(report, sourceId),- modelLabel: modelLabel(report, sourceId, modelId),- };- });+/**+ * The name a model reads by: its configured label, else the model ID it was+ * metered under, which the ledger key is. Only a folded key, a head plus a+ * digest, has no name left to show.+ */+export function usageModelName(report: UsageReport, sourceId: string, modelId: string, unknownModel: string): string {+ const label = modelLabel(report, sourceId, modelId);+ if (label) return label;+ return !modelId.trim() || [...modelId].length > LEDGER_VERBATIM_MAX_LENGTH ? unknownModel : modelId;}-export function identityLabel(identity: UsageIdentity, unknownModelLabel: string): string {- const model = identity.modelLabel || unknownModelLabel;- return `${identity.sourceLabel} · ${model}`;-}+const byKey = <T extends readonly [string, ...unknown[]]>([left]: T, [right]: T) => (left < right ? -1 : left > right ? 1 : 0);-export function usageLabelContext(- report: UsageReport,- rows: readonly UsageBucketRow[],- unknownModelLabel: string,-): UsageLabelContext {- const sourceIds = [...new Set([- ...report.sources.map((source) => source.source_id),- ...rows.map((row) => row.source_id),- ])];- const sourceLabels = new Map(- sourceIds.map((sourceId) => [sourceId, sourceLabel(report, sourceId)] as const),- );- const sourceLabelCounts = new Map<string, number>();- for (const label of sourceLabels.values()) {- sourceLabelCounts.set(label, (sourceLabelCounts.get(label) ?? 0) + 1);- }- const sourceCollisionLabels = new Set(- [...sourceLabelCounts.entries()]- .filter(([, count]) => count > 1)- .map(([label]) => label),- );- const sourceDisplayLabels = new Map(- [...sourceLabels.entries()].map(([sourceId, label]) => [- sourceId,- sourceCollisionLabels.has(label) ? `${label} · ${sourceId}` : label,- ]),- );- for (;;) {- const displayCounts = new Map<string, number>();- for (const label of sourceDisplayLabels.values()) {- displayCounts.set(label, (displayCounts.get(label) ?? 0) + 1);- }- const collisions = [...displayCounts.entries()]- .filter(([, count]) => count > 1)- .map(([label]) => label);- if (collisions.length === 0) break;- for (const [sourceId, label] of sourceDisplayLabels) {- if (collisions.includes(label)) {- sourceDisplayLabels.set(sourceId, `${label} · ${sourceId}`);- }+/**+ * Keep labels that name different identities apart without printing an ID:+ * the first holder of a label keeps it, and each later one, in the order+ * given, reads 「label (2)」, 「label (3)」 …+ */+function distinctLabels(entries: ReadonlyArray<readonly [string, string]>): Map<string, string> {+ const counts = new Map<string, number>();+ for (const [, label] of entries) counts.set(label, (counts.get(label) ?? 0) + 1);+ const used = new Set(entries.filter(([, label]) => counts.get(label) === 1).map(([, label]) => label));+ const labels = new Map<string, string>();+ for (const [key, label] of entries) {+ if (counts.get(label) === 1) {+ labels.set(key, label);+ continue;}+ let candidate = label;+ for (let ordinal = 2; used.has(candidate); ordinal += 1) candidate = `${label} (${ordinal})`;+ used.add(candidate);+ labels.set(key, candidate);}+ return labels;+}- const identityLabelCounts = new Map<string, number>();- const identities = usageIdentities(report, rows);- for (const identity of identities) {- const label = identityLabel(identity, unknownModelLabel);- identityLabelCounts.set(label, (identityLabelCounts.get(label) ?? 0) + 1);- }- const sourceQualifiedIdentityCounts = new Map<string, number>();- for (const identity of identities) {- const label = identityLabel(identity, unknownModelLabel);- if (identityLabelCounts.get(label) === 1) continue;- const qualifiedLabel = `${label} · ${identity.sourceId}`;- sourceQualifiedIdentityCounts.set(qualifiedLabel, (sourceQualifiedIdentityCounts.get(qualifiedLabel) ?? 0) + 1);+/**+ * The identities a report's rows are shown under. A live Source, or a model+ * under one, keeps its own identity; every row of a Source config no longer+ * holds folds into one removed aggregate, so its counters still add up while+ * no Source ID reaches the screen. Labels come from the whole report, so a+ * filter never renames what stays on screen.+ */+export function usageIdentities(report: UsageReport, group: 'model' | 'source', text: UsageText): UsageIdentities {+ const live = liveSources(report);+ const removed = (sourceId: string) => !live.has(sourceId);+ const keyOf = (row: UsageBucketRow) => (removed(row.source_id)+ ? REMOVED_SOURCES_KEY+ : group === 'source' ? row.source_id : pairKey(row.source_id, row.model_id));+ const rows = allRows(report);+ const hasRemoved = report.sources.some((source) => removed(source.source_id))+ || rows.some((row) => removed(row.source_id));+ const removedEntry = hasRemoved ? [[REMOVED_SOURCES_KEY, text.removedSources] as const] : [];+ // The aggregate keeps the product's own name; live Sources tie-break by ID.+ const sourceLabels = distinctLabels([...removedEntry, ...[...live].sort(byKey)]);+ const identities = new Map<string, UsageIdentity>();+ if (hasRemoved) {+ identities.set(REMOVED_SOURCES_KEY, {+ key: REMOVED_SOURCES_KEY,+ label: text.removedSources,+ sourceLabel: '',+ removed: true,+ unlisted: false,+ });}-- const identityCollisionLabels = new Set(- [...identityLabelCounts.entries()]- .filter(([, count]) => count > 1)- .map(([label]) => label),- );- const identityByKey = new Map(identities.map((identity) => [identity.key, identity] as const));- const identityCandidates = new Map(- identities.map((identity) => {- const label = identityLabel(identity, unknownModelLabel);- const modelSuffix = (- (sourceQualifiedIdentityCounts.get(`${label} · ${identity.sourceId}`) ?? 0) > 1- ) ? ` · ${identity.modelId}` : '';- const candidate = identityCollisionLabels.has(label)- ? `${label} · ${identity.sourceId}${modelSuffix}`- : label;- return [identity.key, candidate] as const;- }),- );- const identityDisplayLabels = new Map<string, string>();- const usedIdentityLabels = new Set<string>();- for (const [key, candidate] of identityCandidates) {- const identity = identityByKey.get(key)!;- let displayLabel = candidate;- let suffix = 0;- while (usedIdentityLabels.has(displayLabel)) {- suffix += 1;- const identitySuffix = ` · ${identity.sourceId} · ${identity.modelId}`;- displayLabel = `${candidate}${identitySuffix}${suffix > 1 ? ` (${suffix})` : ''}`;+ if (group === 'source') {+ for (const sourceId of live.keys()) {+ identities.set(sourceId, {+ key: sourceId,+ label: sourceLabels.get(sourceId) ?? '',+ sourceLabel: '',+ removed: false,+ unlisted: false,+ });+ }+ } else {+ const pairs = new Map(rows+ .filter((row) => !removed(row.source_id))+ .map((row) => [pairKey(row.source_id, row.model_id), row] as const));+ const models = new Map([...pairs].map(([key, row]) => [key, {+ sourceLabel: sourceLabels.get(row.source_id) ?? '',+ name: usageModelName(report, row.source_id, row.model_id, text.unknownModel),+ unlisted: modelLabel(report, row.source_id, row.model_id) === null,+ }] as const));+ // A configured model keeps its name over one that only reads like it.+ const labels = distinctLabels([+ ...removedEntry,+ ...[...models]+ .sort((left, right) => Number(left[1].unlisted) - Number(right[1].unlisted) || byKey(left, right))+ .map(([key, model]) => [key, `${model.sourceLabel} · ${model.name}`] as const),+ ]);+ for (const [key, model] of models) {+ identities.set(key, {+ key,+ label: labels.get(key) ?? '',+ sourceLabel: model.sourceLabel,+ removed: false,+ unlisted: model.unlisted,+ });}- usedIdentityLabels.add(displayLabel);- identityDisplayLabels.set(key, displayLabel);}+ const get = (key: string) => identities.get(key)!;return {- sourceCollisionLabels,- sourceDisplayLabels,- identityCollisionLabels,- identityModelCollisionKeys: new Set(- identities- .filter((identity) => {- const label = identityLabel(identity, unknownModelLabel);- return identityCollisionLabels.has(label)- && (sourceQualifiedIdentityCounts.get(`${label} · ${identity.sourceId}`) ?? 0) > 1;- })- .map((identity) => identity.key),- ),- identityDisplayLabels,+ keyOf,+ get,+ of: (selected) => {+ const keys = [...new Set(selected.map(keyOf))];+ return [+ ...keys.filter((key) => key !== REMOVED_SOURCES_KEY),+ ...keys.filter((key) => key === REMOVED_SOURCES_KEY),+ ].map(get);+ },};}-export function sourceIdentityLabel(- report: UsageReport,- sourceId: string,- context: UsageLabelContext,-): string {- const label = sourceLabel(report, sourceId);- return context.sourceDisplayLabels.get(sourceId)- ?? (context.sourceCollisionLabels.has(label) ? `${label} · ${sourceId}` : label);+/**+ * A selection made while a Source was live still names its ID, or its pairs,+ * after config lets it go. From then on it names the removed aggregate, the+ * only identity the filters and the table still offer for that Source.+ */+export function foldUsageSelection(report: UsageReport, selection: UsageFilter): UsageFilter {+ const live = liveSources(report);+ const known = new Set([...report.sources.map((source) => source.source_id), ...allRows(report).map((row) => row.source_id)]);+ const removed = (sourceId: string) => known.has(sourceId) && !live.has(sourceId);+ const fold = (keys: readonly string[], sourceOf: (key: string) => string) => [...new Set(keys.map((key) => (+ removed(sourceOf(key)) ? REMOVED_SOURCES_KEY : key+ )))];+ return {+ sourceIds: fold(selection.sourceIds, (key) => key),+ modelKeys: fold(selection.modelKeys, (key) => key.slice(0, Math.max(0, key.indexOf(PAIR_SEPARATOR)))),+ };}-export function identityDisplayLabel(- identity: UsageIdentity,- unknownModelLabel: string,- context?: UsageLabelContext,-): string {- const displayLabel = context?.identityDisplayLabels.get(identity.key);- if (displayLabel) return displayLabel;- const label = identityLabel(identity, unknownModelLabel);- if (!context?.identityCollisionLabels.has(label)) return label;- const modelSuffix = context.identityModelCollisionKeys.has(identity.key) ? ` · ${identity.modelId}` : '';- return `${label} · ${identity.sourceId}${modelSuffix}`;+/**+ * A selection names identities; the rows it keeps are named by the IDs they+ * were metered under. The removed aggregate therefore stands for every Source+ * ID, and every pair, it folded. It stays in the list too, matching no row, so+ * a selection whose rows are gone never widens to everything.+ */+export function resolveUsageFilter(report: UsageReport, picked: UsageFilter): UsageFilter {+ const selection = foldUsageSelection(report, picked);+ if (!selection.sourceIds.includes(REMOVED_SOURCES_KEY) && !selection.modelKeys.includes(REMOVED_SOURCES_KEY)) {+ return selection;+ }+ const live = liveSources(report);+ const removedRows = allRows(report).filter((row) => !live.has(row.source_id));+ const expand = (keys: readonly string[], folded: string[]) => [...new Set(keys.flatMap((key) => (+ key === REMOVED_SOURCES_KEY ? [key, ...folded] : [key]+ )))];+ return {+ sourceIds: expand(selection.sourceIds, removedRows.map((row) => row.source_id)),+ modelKeys: expand(selection.modelKeys, removedRows.map((row) => pairKey(row.source_id, row.model_id))),+ };}export function filterBucketRows(bucket: UsageBucket, filter: UsageFilter): UsageBucketRow[] {@@ -452,7 +485,7 @@ export function seriesFor(filter: UsageFilter,group: UsageGroup,metric: UsageMetric,- unknownModelLabel: string,+ text: UsageText,): UsageSeries[] {const rows = filteredRows(report, filter);if (group === 'type') {@@ -496,53 +529,20 @@ export function seriesFor(}];}- if (group === 'source') {- const labelContext = usageLabelContext(report, rows, unknownModelLabel);- const sourceIds = [...new Set(rows.map((row) => row.source_id))];- return sourceIds.map((sourceId, index) => ({- key: sourceId,- label: sourceIdentityLabel(report, sourceId, labelContext),+ const identities = usageIdentities(report, group, text);+ return identities.of(rows).map((identity, index) => {+ const rowsOf = (bucket: UsageBucket) => filterBucketRows(bucket, filter)+ .filter((row) => identities.keyOf(row) === identity.key);+ return {+ key: identity.key,+ label: identity.label,colorIndex: index,- values: report.buckets.map((bucket) => {- const rowsForSource = filterBucketRows(bucket, filter).filter((row) => row.source_id === sourceId);- return bucketMetricValue(bucket, rowsForSource, metric);- }),- floors: report.buckets.map((bucket) => costIsFloor(- filterBucketRows(bucket, filter).filter((row) => row.source_id === sourceId),- metric,- )),- unpriced: report.buckets.map((bucket) => costIsUnpriced(- filterBucketRows(bucket, filter).filter((row) => row.source_id === sourceId),- metric,- )),- }));- }-- const identities = usageIdentities(report, rows);- const labelContext = usageLabelContext(report, rows, unknownModelLabel);- return identities.map((identity, index) => ({- key: identity.key,- label: identityDisplayLabel(identity, unknownModelLabel, labelContext),- colorIndex: index,- values: report.buckets.map((bucket) => {- const rowsForIdentity = filterBucketRows(bucket, filter).filter((row) => (- row.source_id === identity.sourceId && row.model_id === identity.modelId- ));- return bucketMetricValue(bucket, rowsForIdentity, metric);- }),- floors: report.buckets.map((bucket) => costIsFloor(- filterBucketRows(bucket, filter).filter((row) => (- row.source_id === identity.sourceId && row.model_id === identity.modelId- )),- metric,- )),- unpriced: report.buckets.map((bucket) => costIsUnpriced(- filterBucketRows(bucket, filter).filter((row) => (- row.source_id === identity.sourceId && row.model_id === identity.modelId- )),- metric,- )),- }));+ removed: identity.removed,+ values: report.buckets.map((bucket) => bucketMetricValue(bucket, rowsOf(bucket), metric)),+ floors: report.buckets.map((bucket) => costIsFloor(rowsOf(bucket), metric)),+ unpriced: report.buckets.map((bucket) => costIsUnpriced(rowsOf(bucket), metric)),+ };+ });}export function reportHasPartialHistory(report: UsageReport, filter: UsageFilter): boolean {diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 071d14e55..0913e9d49 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1567,6 +1567,9 @@"partialHistory": "Some buckets have incomplete history","historicalHourly": "Includes historical usage without hourly time","unknownModel": "Unknown model",+ "removedSources": "Removed providers",+ "removedSourcesHint": "Usage kept after these providers were deleted",+ "removedModel": "Removed","granularity": {"hour": "hourly","day": "daily"diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex cde2f974a..08d4d2a48 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1567,6 +1567,9 @@"partialHistory": "部分时间桶的历史记录不完整","historicalHourly": "含无具体小时记录的历史用量","unknownModel": "未知模型",+ "removedSources": "已移除的供应商",+ "removedSourcesHint": "这些供应商删除前留下的用量",+ "removedModel": "已移除","granularity": {"hour": "按小时","day": "按天"