diff --git a/webui/e2e/visual.spec.ts b/webui/e2e/visual.spec.ts index e47708b..f6cdc55 100644 --- a/webui/e2e/visual.spec.ts +++ b/webui/e2e/visual.spec.ts @@ -98,3 +98,23 @@ for (const theme of THEMES) { await expect(page.locator('text=Previous period >> visible=true').first()).toBeVisible() }) } + +// Usage ranges whose model detail the API refuses (400 range too large): the page falls back to the plain ranking. +for (const scenario of ['live', 'empty'] as const) { + for (const [vp, size] of Object.entries(VIEWPORTS)) { + for (const theme of THEMES) { + test(`usage-48h ${scenario} ${vp} ${theme}`, async ({ page }) => { + await page.setViewportSize(size) + await exercise(page, 'usage-48h', '#usage?range=48h', scenario, vp as keyof typeof VIEWPORTS, theme) + }) + } + } +} + +for (const theme of THEMES) { + test(`usage-cmp live desktop ${theme}`, async ({ page }) => { + await page.setViewportSize(VIEWPORTS.desktop) + await exercise(page, 'usage-cmp', '#usage?cmp=prev', 'live', 'desktop', theme) + await expect(page.locator('text=Previous period >> visible=true').first()).toBeVisible() + }) +} diff --git a/webui/src/App.vue b/webui/src/App.vue index e1642cf..d45d763 100644 --- a/webui/src/App.vue +++ b/webui/src/App.vue @@ -45,7 +45,7 @@ function lazyPage(loader: () => Promise): Component { // still lives inside the Models page and events inside Reliability. const PAGES: Record = { overview: lazyPage(() => import('@/pages/OverviewPage.vue')), - usage: lazyPage(() => import('@/pages/SpendPage.vue')), + usage: lazyPage(() => import('@/pages/UsagePage.vue')), reliability: lazyPage(() => import('@/pages/ReliabilityPage.vue')), users: lazyPage(() => import('@/pages/ConsumersPage.vue')), models: lazyPage(() => import('@/pages/ModelsPage.vue')), diff --git a/webui/src/assets/main.css b/webui/src/assets/main.css index 76c13b1..baf8819 100644 --- a/webui/src/assets/main.css +++ b/webui/src/assets/main.css @@ -211,3 +211,10 @@ /* Phone cards layout: drop the share bar from compact top lists. */ @media (max-width: 639px) { .wb-hide-share-sm .wb-share { display: none; } } @media (min-width: 640px) { .wb-clip td.wb-text { max-width: 9rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } } + +/* Model id cell: provider as a muted prefix, model name ellipsized at its end; the column takes the free width. */ +.wb-model { display: inline-flex; align-items: baseline; gap: 1px; max-width: 100%; min-width: 0; vertical-align: bottom; } +.wb-model-provider { flex: none; color: var(--muted-foreground); font-size: 0.75rem; } +.wb-model-provider::after { content: '/'; } +.wb-model-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +@media (min-width: 640px) { .wb-table td.wb-text:has(.wb-model) { width: 100%; max-width: 0; overflow: hidden; } } diff --git a/webui/src/lib/model-id.spec.ts b/webui/src/lib/model-id.spec.ts new file mode 100644 index 0000000..cce032f --- /dev/null +++ b/webui/src/lib/model-id.spec.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest' + +import { splitModelId } from './model-id' + +describe('splitModelId', () => { + it('splits a provider-prefixed id at the first slash', () => { + expect(splitModelId('uni/glm-5.3-flash')).toEqual({ provider: 'uni', model: 'glm-5.3-flash' }) + }) + + it('keeps further slashes in the model part', () => { + expect(splitModelId('nvidia-nim/nvidia/nemotron-3-super')).toEqual({ provider: 'nvidia-nim', model: 'nvidia/nemotron-3-super' }) + }) + + it('returns a null provider for a bare id', () => { + expect(splitModelId('gpt-5')).toEqual({ provider: null, model: 'gpt-5' }) + }) + + it('treats a leading or trailing slash as part of a bare id', () => { + expect(splitModelId('/x')).toEqual({ provider: null, model: '/x' }) + expect(splitModelId('x/')).toEqual({ provider: null, model: 'x/' }) + }) + + it('returns an empty model for an empty id', () => { + expect(splitModelId('')).toEqual({ provider: null, model: '' }) + }) +}) diff --git a/webui/src/lib/model-id.ts b/webui/src/lib/model-id.ts new file mode 100644 index 0000000..e47341a --- /dev/null +++ b/webui/src/lib/model-id.ts @@ -0,0 +1,11 @@ +export interface SplitModelId { + provider: string | null + model: string +} + +/** Splits `provider/model` at the first slash; later slashes stay in the model part. A bare id has no provider. */ +export function splitModelId(id: string): SplitModelId { + const slash = id.indexOf('/') + if (slash <= 0 || slash === id.length - 1) return { provider: null, model: id } + return { provider: id.slice(0, slash), model: id.slice(slash + 1) } +} diff --git a/webui/src/lib/overview-metrics.ts b/webui/src/lib/overview-metrics.ts index b2a103a..b79fcee 100644 --- a/webui/src/lib/overview-metrics.ts +++ b/webui/src/lib/overview-metrics.ts @@ -13,7 +13,7 @@ export interface Delta { export interface ChartLine { name: string data: number[] - tone?: 'muted' | 'primary' + tone?: 'muted' | 'primary' | 'danger' stack?: false } diff --git a/webui/src/lib/range.spec.ts b/webui/src/lib/range.spec.ts index db4a9db..4a735a1 100644 --- a/webui/src/lib/range.spec.ts +++ b/webui/src/lib/range.spec.ts @@ -8,6 +8,7 @@ import { DEFAULT_RANGE, isCmpMode, isRangeKey, + modelDetailSupported, RANGE_KEYS, RANGE_PRESETS, seriesUrl, @@ -138,3 +139,17 @@ describe('totalsUrl', () => { expect(url).toBe('/admin/api/usage/totals?kind=usermodel&window=month&span=1&metrics=req%2Ccost&limit=5&user=alice') }) }) + +describe('modelDetailSupported', () => { + it('rejects the ranges the API answers 400 for', () => { + expect(modelDetailSupported('hour', 48)).toBe(false) + expect(modelDetailSupported('day', 30)).toBe(false) + }) + + it('accepts the other presets', () => { + for (const key of RANGE_KEYS) { + const { window, span } = RANGE_PRESETS[key] + expect(modelDetailSupported(window, span)).toBe(key !== '48h' && key !== '30d') + } + }) +}) diff --git a/webui/src/lib/range.ts b/webui/src/lib/range.ts index 7d13f01..c7b2a3c 100644 --- a/webui/src/lib/range.ts +++ b/webui/src/lib/range.ts @@ -75,6 +75,15 @@ export function comparison(range: RangeKey): ComparisonResult { return { available: true, offset: span } } +/** Spans from which GET /usage/models?detail=1 answers 400 "range too large" (observed on the live API: 48h and 30d fail, 24h and 14d pass). */ +const DETAIL_REJECTED_FROM_SPAN: Partial> = { hour: 48, day: 30 } + +/** modelDetailSupported is false for ranges where asking for per-model detail is known to fail, so callers skip the doomed request. */ +export function modelDetailSupported(window: HistoryWindow, span: number): boolean { + const limit = DETAIL_REJECTED_FROM_SPAN[window] + return limit === undefined || span < limit +} + /** * dayOrMonthWindow clamps an arbitrary HistoryWindow/span pair (usually the * global filters store's current range) down to the day/month-only window diff --git a/webui/src/lib/scope.spec.ts b/webui/src/lib/scope.spec.ts index e525522..0bcfbc1 100644 --- a/webui/src/lib/scope.spec.ts +++ b/webui/src/lib/scope.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { drilldownLevel, makeScope, parseScope, scopeBudgetLimits, scopeId } from './scope' +import { drilldownLevel, makeScope, parseScope, scopeBudgetLimits, scopeId, scopeMtdMicros } from './scope' import type { AdminGroupView, AdminUsageEntryView } from '@/types/api' function group(overrides: Partial = {}): AdminGroupView { @@ -112,3 +112,23 @@ describe('scopeBudgetLimits', () => { expect(scopeBudgetLimits('provider:openai', groups, users)).toBeUndefined() }) }) + +describe('scopeMtdMicros', () => { + const entry = (id: string, micros: number) => ({ id, costPerMonthMicroUsd: micros }) as never + const usage = { total: entry('total', 900), groups: [entry('g1', 300)], users: [entry('u1', 100)] } as never + + it('reads the fleet total for the all scope', () => { + expect(scopeMtdMicros('all', usage)).toBe(900) + }) + + it('reads a group or user entry by id', () => { + expect(scopeMtdMicros('group:g1', usage)).toBe(300) + expect(scopeMtdMicros('user:u1', usage)).toBe(100) + }) + + it('is 0 for an unknown entity, a provider scope, or no usage yet', () => { + expect(scopeMtdMicros('user:nobody', usage)).toBe(0) + expect(scopeMtdMicros('provider:x', usage)).toBe(0) + expect(scopeMtdMicros('all', null)).toBe(0) + }) +}) diff --git a/webui/src/lib/scope.ts b/webui/src/lib/scope.ts index 6a1abb9..eb6bccf 100644 --- a/webui/src/lib/scope.ts +++ b/webui/src/lib/scope.ts @@ -10,7 +10,7 @@ // function here directly, no component mount required. import { sumGroupBudgetMicros } from '@/lib/kpi' import { microsToUsd } from '@/lib/usage-bars' -import type { AdminGroupView, AdminUsageEntryView, LimitsConfig } from '@/types/api' +import type { AdminGroupView, AdminUsageEntryView, AdminUsageResponse, LimitsConfig } from '@/types/api' /** ScopeKind is every prefix a "kind:id" scope string can carry across this panel — not every caller accepts every kind (a Spend burn-down scope never carries 'provider', a Reliability series scope never carries 'group'/'user'), but the prefix syntax itself is the same everywhere. */ export type ScopeKind = 'group' | 'user' | 'model' | 'provider' @@ -89,3 +89,13 @@ export function scopeBudgetLimits(scope: string, groups: AdminGroupView[], users if (parsed.kind === 'user') return users.find((u) => u.id === parsed.id)?.limits return undefined } + +/** scopeMtdMicros reads the month-to-date cost (micro-USD) of the scope's own entry in the polled usage snapshot; 0 when it has none (provider scope, unknown id, no snapshot yet). */ +export function scopeMtdMicros(scope: string, usage: AdminUsageResponse | null): number { + if (!usage) return 0 + const parsed = parseScope(scope) + if (!parsed) return usage.total.costPerMonthMicroUsd + if (parsed.kind === 'group') return usage.groups.find((g) => g.id === parsed.id)?.costPerMonthMicroUsd ?? 0 + if (parsed.kind === 'user') return usage.users.find((u) => u.id === parsed.id)?.costPerMonthMicroUsd ?? 0 + return 0 +} diff --git a/webui/src/lib/series.spec.ts b/webui/src/lib/series.spec.ts index 31437b9..4d5c89a 100644 --- a/webui/src/lib/series.spec.ts +++ b/webui/src/lib/series.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { activeScopes, activeSeries, other, ratioSeries, stackTopN, sumByProvider } from './series' +import { activeScopes, activeSeries, other, ratioSeries, seriesToStacked, stackTopN, sumByProvider } from './series' describe('stackTopN', () => { it('returns the n series with the largest total, descending', () => { @@ -155,3 +155,31 @@ describe('activeSeries / activeScopes', () => { expect([...activeScopes(series)].sort()).toEqual(['provider:a', 'provider:b']) }) }) + +describe('seriesToStacked', () => { + const s = (scope: string, ...points: number[]) => ({ scope, points }) + + it('groups beyond top into other', () => { + const out = seriesToStacked([s('a', 1, 1), s('b', 10, 10), s('c', 5, 5), s('d', 2, 0)], 2) + expect(out.series.map((x) => x.scope)).toEqual(['b', 'c']) + expect(out.other).toEqual([3, 1]) + }) + + it('returns null other when nothing falls beyond top', () => { + const out = seriesToStacked([s('a', 1), s('b', 2)], 5) + expect(out.series.map((x) => x.scope)).toEqual(['b', 'a']) + expect(out.other).toBeNull() + }) + + it('puts everything into other when top is 0', () => { + expect(seriesToStacked([s('a', 1, 2)], 0)).toEqual({ series: [], other: [1, 2] }) + }) + + it('handles an empty input', () => { + expect(seriesToStacked([], 5)).toEqual({ series: [], other: null }) + }) + + it('pads short series so other stays bucket-aligned', () => { + expect(seriesToStacked([s('a', 9, 9), s('b', 1)], 1).other).toEqual([1, 0]) + }) +}) diff --git a/webui/src/lib/series.ts b/webui/src/lib/series.ts index a848fb3..f3b2f47 100644 --- a/webui/src/lib/series.ts +++ b/webui/src/lib/series.ts @@ -123,3 +123,21 @@ export function activeScopes(series: Series[]): Set { export function ratioSeries(numerator: number[], denominator: number[]): (number | null)[] { return denominator.map((d, i) => (d > 0 ? (numerator[i] ?? 0) / d : null)) } + +export interface StackedSeries { + series: Series[] + /** Per-bucket sum of every series beyond `top`; null when none fall beyond it. */ + other: number[] | null +} + +/** seriesToStacked keeps the `top` series by total for stacking and folds the rest into one bucket-aligned `other`. */ +export function seriesToStacked(series: Series[], top: number): StackedSeries { + const ranked = [...series].sort((a, b) => sumSeries(b.points) - sumSeries(a.points)) + const kept = ranked.slice(0, Math.max(0, top)) + const rest = ranked.slice(kept.length) + if (rest.length === 0) return { series: kept, other: null } + const width = Math.max(...series.map((s) => s.points.length)) + const sum = new Array(width).fill(0) + for (const s of rest) for (let i = 0; i < width; i++) sum[i] = (sum[i] ?? 0) + (s.points[i] ?? 0) + return { series: kept, other: sum } +} diff --git a/webui/src/pages/OverviewPage.vue b/webui/src/pages/OverviewPage.vue index 6cb5c5d..58ea5c2 100644 --- a/webui/src/pages/OverviewPage.vue +++ b/webui/src/pages/OverviewPage.vue @@ -17,6 +17,7 @@ import { useFiltersStore } from '@/stores/filters' import { useNavStore } from '@/stores/nav' import { useOverviewStore } from '@/stores/overview' import HealthStrip from '@/widgets/HealthStrip.vue' +import ModelName from '@/widgets/ModelName.vue' import NeedsAttention from '@/widgets/NeedsAttention.vue' import RecentEvents from '@/widgets/RecentEvents.vue' import StateView from '@/widgets/StateView.vue' @@ -286,6 +287,7 @@ onUnmounted(() => { label="Top models by requests" @row-activate="(row: RankRow) => openEntity('model', row.id)" > + diff --git a/webui/src/pages/UsagePage.vue b/webui/src/pages/UsagePage.vue new file mode 100644 index 0000000..0c50202 --- /dev/null +++ b/webui/src/pages/UsagePage.vue @@ -0,0 +1,533 @@ + + + diff --git a/webui/src/stores/spend.spec.ts b/webui/src/stores/spend.spec.ts index 229169e..af60288 100644 --- a/webui/src/stores/spend.spec.ts +++ b/webui/src/stores/spend.spec.ts @@ -732,3 +732,68 @@ describe('useSpendStore.refresh: breakdown depends on the ranking', () => { expect(spend.breakdown.map((s) => s.scope)).toContain('group:a') }) }) + +describe('useSpendStore detail fallback', () => { + const tooLarge = () => new AdminApiError('range too large; narrow span or filter', 400) + + it('retries the ranking without detail on a 400 and flags detailAvailable false', async () => { + const urls: string[] = [] + mockedAdminFetch.mockImplementation((async (path: string) => { + urls.push(path) + if (path.includes('detail=1')) throw tooLarge() + return { ...rankingWith(['a/one']), detail: false, models: [{ id: 'a/one', value: 5 }] } + }) as typeof adminFetch) + const spend = useSpendStore() + await spend.fetchModelRanking() + expect(urls).toHaveLength(2) + expect(urls[1]).not.toContain('detail=1') + expect(spend.modelRanking.map((m) => m.id)).toEqual(['a/one']) + expect(spend.detailAvailable).toBe(false) + expect(spend.rankingError).toBe('') + }) + + it('does the same for the pricing-health ranking', async () => { + mockedAdminFetch.mockImplementation((async (path: string) => { + if (path.includes('detail=1')) throw tooLarge() + return { ...rankingWith(['a/one']), detail: false, models: [{ id: 'a/one', value: 5 }] } + }) as typeof adminFetch) + const spend = useSpendStore() + await spend.fetchPricingHealthRanking() + expect(spend.pricingHealthRanking).toHaveLength(1) + expect(spend.pricingHealthError).toBe('') + expect(spend.detailAvailable).toBe(false) + }) + + it('keeps surfacing non-400 failures', async () => { + mockedAdminFetch.mockRejectedValue(new AdminApiError('boom', 503)) + const spend = useSpendStore() + await spend.fetchModelRanking() + expect(spend.rankingError).toBe('boom') + expect(mockedAdminFetch).toHaveBeenCalledTimes(1) + }) + + it('stays detailAvailable when the server accepts detail', async () => { + mockRoutes({ models: () => rankingWith(['a/one']) }) + const spend = useSpendStore() + await spend.fetchModelRanking() + expect(spend.detailAvailable).toBe(true) + }) + + it('skips the doomed detail request on 48h and 30d', async () => { + const urls: string[] = [] + mockedAdminFetch.mockImplementation((async (path: string) => { + urls.push(path) + return { ...rankingWith(['a/one']), detail: false, models: [{ id: 'a/one', value: 5 }] } + }) as typeof adminFetch) + const filters = useFiltersStore() + const spend = useSpendStore() + for (const range of ['48h', '30d'] as const) { + urls.length = 0 + filters.setFilters({ range }) + await spend.fetchModelRanking() + expect(urls).toHaveLength(1) + expect(urls[0]).not.toContain('detail=1') + expect(spend.detailAvailable).toBe(false) + } + }) +}) diff --git a/webui/src/stores/spend.ts b/webui/src/stores/spend.ts index 86d1279..5a317db 100644 --- a/webui/src/stores/spend.ts +++ b/webui/src/stores/spend.ts @@ -3,7 +3,7 @@ import { defineStore } from 'pinia' import { AdminApiError, adminFetch, isAuthRejection, messageOf } from '@/lib/api' import { currentMonthDaySpan } from '@/lib/burndown' import { createVisibilityPoller, type VisibilityPoller } from '@/lib/polling' -import { dayOrMonthWindow, seriesUrl, totalsUrl } from '@/lib/range' +import { dayOrMonthWindow, modelDetailSupported, seriesUrl, totalsUrl } from '@/lib/range' import type { TotalsUrlParams } from '@/lib/range' import { drilldownLevel, scopeBudgetLimits } from '@/lib/scope' import { other, stackTopN, sumByProvider, type Series } from '@/lib/series' @@ -130,6 +130,8 @@ export const useSpendStore = defineStore('spend', { * longer discards a row specifically BECAUSE it is unpriced. */ pricingHealthRanking: [] as AdminUsageModelsResponse['models'], + /** False when the server refused `detail=1` for this range (400 range too large) and the rankings fell back to value-only rows, so per-model tokens, cost and free flags are absent. */ + detailAvailable: true, // --- burn-down (BurnDownChart) --- burndownBuckets: [] as string[], @@ -312,11 +314,10 @@ export const useSpendStore = defineStore('spend', { const filters = useFiltersStore() const requestId = ++this.rankingReqId try { - const res = await adminFetch( - `/admin/api/usage/models?metric=${this.metric}&window=${filters.window}&span=${filters.span}&limit=${MODEL_RANKING_LIMIT}&detail=1`, - ) + const { res, detail } = await fetchModelsRanking(this.metric, filters.window, filters.span) if (requestId !== this.rankingReqId) return false this.modelRanking = res.models + this.detailAvailable = detail this.rankingError = '' return true } catch (err) { @@ -344,11 +345,10 @@ export const useSpendStore = defineStore('spend', { const requestId = ++this.pricingHealthReqId this.pricingHealthLoading = true try { - const res = await adminFetch( - `/admin/api/usage/models?metric=req&window=${filters.window}&span=${filters.span}&limit=${MODEL_RANKING_LIMIT}&detail=1`, - ) + const { res, detail } = await fetchModelsRanking('req', filters.window, filters.span) if (requestId !== this.pricingHealthReqId) return this.pricingHealthRanking = res.models + this.detailAvailable = detail this.pricingHealthError = '' this.pricingHealthLoaded = true } catch (err) { @@ -628,6 +628,18 @@ export const useSpendStore = defineStore('spend', { }, }) +/** fetchModelsRanking asks for `detail=1` except on ranges the server is known to refuse (48h, 30d); a 400 elsewhere retries once without detail. Reports which form it got. */ +async function fetchModelsRanking(metric: string, window: HistoryWindow, span: number): Promise<{ res: AdminUsageModelsResponse; detail: boolean }> { + const base = `/admin/api/usage/models?metric=${metric}&window=${window}&span=${span}&limit=${MODEL_RANKING_LIMIT}` + if (!modelDetailSupported(window, span)) return { res: await adminFetch(base), detail: false } + try { + return { res: await adminFetch(`${base}&detail=1`), detail: true } + } catch (err) { + if (!(err instanceof AdminApiError) || err.status !== 400) throw err + return { res: await adminFetch(base), detail: false } + } +} + /** burndownScopeParam maps the global scope filter to the /usage/series scope this store's burn-down line requests — null for a provider scope, which has no cost series and no budget concept (see useSpendStore's own doc comment). */ function burndownScopeParam(filtersScope: string): string | null { if (filtersScope === 'all') return 'total' diff --git a/webui/src/stores/usage-users.spec.ts b/webui/src/stores/usage-users.spec.ts new file mode 100644 index 0000000..a8ce063 --- /dev/null +++ b/webui/src/stores/usage-users.spec.ts @@ -0,0 +1,59 @@ +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/api', async () => { + const actual = await vi.importActual('@/lib/api') + return { ...actual, adminFetch: vi.fn() } +}) + +import { AdminApiError, adminFetch } from '@/lib/api' +import { useAuthStore } from '@/stores/auth' +import { useDashboardStore } from '@/stores/dashboard' +import { USERS_RANGE_TOO_LARGE, useUsageUsersStore } from '@/stores/usage-users' + +const mocked = vi.mocked(adminFetch) + +function route(url: string): unknown { + const u = new URL(url, 'http://x') + if (u.pathname.endsWith('/usage/totals')) { + return { rows: [{ id: 'bob', values: { cost: 3 } }, { id: 'alice', values: { cost: 9 } }, { id: 'idle', values: { cost: 0 } }] } + } + const scopes = u.searchParams.getAll('scope') + return { series: scopes.map((scope) => ({ scope, points: scope === 'total' ? [20, 20] : [4, 4] })) } +} + +describe('useUsageUsersStore.refresh', () => { + beforeEach(() => { + setActivePinia(createPinia()) + mocked.mockReset() + mocked.mockImplementation(async (url: string) => route(url) as never) + useAuthStore().submit('test-admin-key') + }) + + it('ranks active users by the metric and derives the other bucket from the total', async () => { + const s = useUsageUsersStore() + await s.refresh('cost') + expect(s.rows).toEqual([{ id: 'alice', value: 9 }, { id: 'bob', value: 3 }]) + expect(s.series.map((x) => x.scope)).toEqual(['user:alice', 'user:bob']) + expect(s.otherPoints).toEqual([12, 12]) + expect(s.loaded).toBe(true) + expect(s.error).toBe('') + }) + + it('refuses ranges whose user count would exceed the per-request key cap', async () => { + const dashboard = useDashboardStore() + dashboard.usage = { users: new Array(20000).fill({ id: 'u' }) } as never + const s = useUsageUsersStore() + await s.refresh('cost') + expect(s.error).toBe(USERS_RANGE_TOO_LARGE) + expect(mocked).not.toHaveBeenCalled() + }) + + it('reports a fetch failure and stays unloaded', async () => { + mocked.mockRejectedValue(new AdminApiError('boom', 503)) + const s = useUsageUsersStore() + await s.refresh('cost') + expect(s.error).toBe('boom') + expect(s.loaded).toBe(false) + }) +}) diff --git a/webui/src/stores/usage-users.ts b/webui/src/stores/usage-users.ts new file mode 100644 index 0000000..b7d9d65 --- /dev/null +++ b/webui/src/stores/usage-users.ts @@ -0,0 +1,78 @@ +import { defineStore } from 'pinia' + +import { adminFetch, isAuthRejection, messageOf } from '@/lib/api' +import { seriesUrl } from '@/lib/range' +import { other } from '@/lib/series' +import type { Series } from '@/lib/series' +import { topUsersCapCheckResult } from '@/lib/top-users' +import { useAuthStore } from '@/stores/auth' +import { useDashboardStore } from '@/stores/dashboard' +import { useFiltersStore } from '@/stores/filters' +import type { AdminSeriesResponse, AdminTotalsResponse, HistoryMetric } from '@/types/api' + +/** Users given their own chart series; the rest fold into "Other". */ +export const USER_SERIES_LIMIT = 10 +const TOTALS_LIMIT = 1000 +const TOTAL_SCOPE = 'total' + +export const USERS_RANGE_TOO_LARGE = 'Too many configured users to rank for this range. Pick a shorter range.' + +export interface UserRow { + id: string + value: number +} + +/** Per-user ranking and top-user series for the Usage page's user breakdown. */ +export const useUsageUsersStore = defineStore('usage-users', { + state: () => ({ + rows: [] as UserRow[], + series: [] as Series[], + otherPoints: null as number[] | null, + loaded: false, + error: '', + fetchedFor: '', + reqId: 0, + }), + actions: { + async refresh(metric: HistoryMetric): Promise { + if (!useAuthStore().isAuthenticated) return + const { window, span } = useFiltersStore() + const key = `${metric}:${window}:${span}` + if (key !== this.fetchedFor) { + this.rows = [] + this.series = [] + this.otherPoints = null + this.loaded = false + } + this.fetchedFor = key + const id = ++this.reqId + const configured = useDashboardStore().usage?.users.length ?? null + if (topUsersCapCheckResult(configured, 1, span)) { + this.error = USERS_RANGE_TOO_LARGE + return + } + try { + const q = new URLSearchParams({ kind: 'user', window, span: String(span), offset: '0', metrics: metric, limit: String(TOTALS_LIMIT) }) + const totals = await adminFetch(`/admin/api/usage/totals?${q.toString()}`) + const rows = totals.rows.map((r) => ({ id: r.id, value: r.values[metric] ?? 0 })).filter((r) => r.value > 0).sort((a, b) => b.value - a.value) + const top = rows.slice(0, USER_SERIES_LIMIT) + const scopes = top.map((r) => `user:${r.id}`) + let series: Series[] = [] + let totalPoints: number[] = [] + if (scopes.length > 0) { + const res = await adminFetch(seriesUrl({ scope: [TOTAL_SCOPE, ...scopes], metric, window, span })) + series = res.series.filter((s) => s.scope !== TOTAL_SCOPE) + totalPoints = res.series.find((s) => s.scope === TOTAL_SCOPE)?.points ?? [] + } + if (id !== this.reqId) return + this.rows = rows + this.series = series + this.otherPoints = totalPoints.length > 0 ? other(totalPoints, series) : null + this.loaded = true + this.error = '' + } catch (err) { + if (id === this.reqId && !isAuthRejection(err)) this.error = messageOf(err) + } + }, + }, +}) diff --git a/webui/src/widgets/ModelName.vue b/webui/src/widgets/ModelName.vue new file mode 100644 index 0000000..cd51339 --- /dev/null +++ b/webui/src/widgets/ModelName.vue @@ -0,0 +1,15 @@ + + +