feat(webui): usage and spend page

This commit is contained in:
2026-11-25 11:52:36 +00:00
parent bbb397cd75
commit ed57488980
19 changed files with 940 additions and 12 deletions
+20
View File
@@ -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()
})
}
+1 -1
View File
@@ -45,7 +45,7 @@ function lazyPage(loader: () => Promise<Component>): Component {
// still lives inside the Models page and events inside Reliability.
const PAGES: Record<PageId, Component> = {
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')),
+7
View File
@@ -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; } }
+26
View File
@@ -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: '' })
})
})
+11
View File
@@ -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) }
}
+1 -1
View File
@@ -13,7 +13,7 @@ export interface Delta {
export interface ChartLine {
name: string
data: number[]
tone?: 'muted' | 'primary'
tone?: 'muted' | 'primary' | 'danger'
stack?: false
}
+15
View File
@@ -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')
}
})
})
+9
View File
@@ -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<Record<HistoryWindow, number>> = { 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
+21 -1
View File
@@ -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> = {}): 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)
})
})
+11 -1
View File
@@ -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
}
+29 -1
View File
@@ -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])
})
})
+18
View File
@@ -123,3 +123,21 @@ export function activeScopes(series: Series[]): Set<string> {
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<number>(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 }
}
+2
View File
@@ -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)"
>
<template #cell-name="{ value }"><ModelName :id="value as string" /></template>
<template #cell-value="{ value }">{{ formatCompactCount(value as number) }}</template>
</WbTable>
</StateView>
+533
View File
@@ -0,0 +1,533 @@
<script setup lang="ts">
import { Badge, Button, Card, CardAction, CardContent, CardHeader, CardTitle, KpiTile, LineChart, NativeSelect, Pagination, SegmentedControl, StatGroup } from '@perfect-design/ui'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useEntityLinks } from '@/composables/useEntityLinks'
import { useNow } from '@/composables/useNow'
import { budgetLineVisible, cumulative, runOutDate } from '@/lib/burndown'
import { cacheSavingsStatus } from '@/lib/cache-savings'
import { toCsv } from '@/lib/csv'
import { costAvoidedMicros, freeRows, pickReferenceModel } from '@/lib/cost-avoided'
import { downloadText } from '@/lib/download'
import type { DownloadOutcome } from '@/lib/download'
import { headroom, monthProgress, NOT_ENOUGH_DATA, projectMonthEnd } from '@/lib/forecast'
import { formatBucketLabel, formatCompactCount, formatCostDisplay, formatModelPriceShort, formatShortDate } from '@/lib/format'
import { joinPricingHealth, pricingHealthOrder } from '@/lib/pricing-health'
import type { PricingHealthRow } from '@/lib/pricing-health'
import { loadState } from '@/lib/load-state'
import { pageWindow } from '@/lib/paging'
import { createVisibilityPoller } from '@/lib/polling'
import type { VisibilityPoller } from '@/lib/polling'
import { deltaOf, sumPoints } from '@/lib/overview-metrics'
import type { ChartLine } from '@/lib/overview-metrics'
import { parseScope, scopeBudgetLimits, scopeId, scopeMtdMicros } from '@/lib/scope'
import { seriesToStacked } from '@/lib/series'
import { usageCsv } from '@/lib/usage-csv'
import { wbColumns } from '@/lib/wb-columns'
import { useCatalogStore } from '@/stores/catalog'
import { useDashboardStore } from '@/stores/dashboard'
import { useFiltersStore } from '@/stores/filters'
import { useNavStore } from '@/stores/nav'
import { isSpendMetric, SPEND_METRIC_LABEL, SPEND_METRICS, useSpendStore } from '@/stores/spend'
import { USERS_RANGE_TOO_LARGE, useUsageUsersStore } from '@/stores/usage-users'
import type { HistoryMetric } from '@/types/api'
import ModelName from '@/widgets/ModelName.vue'
import StateView from '@/widgets/StateView.vue'
import type { ViewState } from '@/widgets/StateView.vue'
import WbTable from '@/widgets/WbTable.vue'
const BREAKDOWNS = ['model', 'group', 'user'] as const
type Breakdown = (typeof BREAKDOWNS)[number]
const BREAKDOWN_LABEL: Record<Breakdown, string> = { model: 'Model', group: 'Group', user: 'User' }
const BREAKDOWN_ENTITY: Record<Breakdown, 'model' | 'group' | 'user'> = { model: 'model', group: 'group', user: 'user' }
const CHART_TOP = 5
const TABLE_PAGE_SIZE = 10
const HEALTH_PAGE_SIZE = 10
const USERS_POLL_MS = 60_000
const FEEDBACK_MS = 2500
const DETAIL_NOTICE = 'Per-model tokens and cost are not available for this range: the server limits detail to shorter ranges.'
const nav = useNavStore()
const filters = useFiltersStore()
const dashboard = useDashboardStore()
const catalog = useCatalogStore()
const spend = useSpendStore()
const users = useUsageUsersStore()
const { openEntity } = useEntityLinks()
const { now, start: startClock, stop: stopClock } = useNow()
// --- Page params (hash): by, metric, ref ------------------------------------
const by = computed<Breakdown>(() => (BREAKDOWNS as readonly string[]).includes(nav.params.by ?? '') ? (nav.params.by as Breakdown) : 'model')
const metric = computed<HistoryMetric>(() => (nav.params.metric && isSpendMetric(nav.params.metric) ? nav.params.metric : 'cost'))
const refParam = computed(() => nav.params.ref ?? '')
function updateParams(next: Partial<{ by: Breakdown; metric: HistoryMetric; ref: string }>): void {
const merged = { by: next.by ?? by.value, metric: next.metric ?? metric.value, ref: next.ref ?? refParam.value }
const params: Record<string, string> = {}
if (merged.by !== 'model') params.by = merged.by
if (merged.metric !== 'cost') params.metric = merged.metric
if (merged.ref !== '') params.ref = merged.ref
nav.goTo('usage', params)
}
const metricOptions = SPEND_METRICS.map((m) => ({ value: m, label: SPEND_METRIC_LABEL[m] }))
const byOptions = BREAKDOWNS.map((b) => ({ value: b, label: BREAKDOWN_LABEL[b] }))
function onMetric(v: string): void {
if (isSpendMetric(v)) updateParams({ metric: v })
}
function onBy(v: string): void {
if ((BREAKDOWNS as readonly string[]).includes(v)) updateParams({ by: v as Breakdown })
}
// --- Data wiring -------------------------------------------------------------
const userMode = computed(() => by.value === 'user' && filters.scope === 'all')
let usersPoller: VisibilityPoller | undefined
function syncStore(): void {
spend.setSelection({ by: by.value === 'group' ? 'group' : 'model', metric: metric.value, drill: '' })
if (by.value === 'user') void users.refresh(metric.value)
}
watch([by, metric], syncStore)
watch(
() => [filters.range, filters.cmp, filters.scope],
() => {
void spend.refresh()
if (by.value === 'user') void users.refresh(metric.value)
},
)
onMounted(() => {
spend.$patch({ by: by.value === 'group' ? 'group' : 'model', metric: metric.value, drill: '' })
void catalog.ensureLoaded()
spend.startPolling()
startClock()
if (by.value === 'user') void users.refresh(metric.value)
usersPoller = createVisibilityPoller({ intervalMs: USERS_POLL_MS, tick: () => (by.value === 'user' ? users.refresh(metric.value) : undefined) })
usersPoller.start()
})
onUnmounted(() => {
spend.stopPolling()
usersPoller?.stop()
stopClock()
})
// --- Formatting -------------------------------------------------------------
const fmt = computed<(n: number) => string>(() => (metric.value === 'cost' ? formatCostDisplay : formatCompactCount))
const fmtValue = (v: unknown): string => (typeof v === 'number' && Number.isFinite(v) ? fmt.value(v) : '—')
// --- Chart -----------------------------------------------------------------
const labels = computed(() => spend.buckets.map((b) => formatBucketLabel(b, filters.window)))
function addPoints(a: number[] | null, b: number[] | null): number[] | null {
if (!a) return b
if (!b) return a
return a.map((v, i) => v + (b[i] ?? 0))
}
const lines = computed<ChartLine[]>(() => {
const src = userMode.value ? { series: users.series, other: users.otherPoints } : { series: spend.breakdown, other: spend.otherPoints }
const stacked = seriesToStacked(src.series, CHART_TOP)
const out: ChartLine[] = stacked.series.map((s) => ({ name: scopeId(s.scope), data: s.points }))
const rest = addPoints(stacked.other, src.other)
if (rest?.some((v) => v > 0)) out.push({ name: 'Other', data: rest, tone: 'muted' })
if (out.length === 0) return []
if (spend.comparisonPoints) out.push({ name: 'Previous period', data: spend.comparisonPoints, tone: 'primary', stack: false })
return out
})
const chartState = computed<ViewState>(() => {
const s = loadState({ loading: spend.loading, hasData: spend.buckets.length > 0, error: spend.breakdownError })
if (s === 'ready') return lines.value.some((l) => l.data.some((v) => v > 0)) ? 'ready' : 'empty'
return s === 'skeleton' ? 'loading' : s
})
const totalInRange = computed(() => sumPoints(spend.totalPoints))
const previousTotal = computed(() => (spend.comparisonPoints ? sumPoints(spend.comparisonPoints) : null))
const rangeDelta = computed(() => deltaOf(totalInRange.value, previousTotal.value))
const sparkline = computed(() => (spend.totalPoints.length >= 2 && spend.totalPoints.some((v) => v > 0) ? spend.totalPoints : undefined))
const totalReady = computed(() => spend.buckets.length > 0)
const scopeNote = computed(() => (filters.scope === 'all' ? '' : `Chart shows ${filters.scope} directly; clear the scope filter to break it down by ${by.value}.`))
const compareNote = computed(() => (filters.cmpSpec.requested ? spend.comparisonUnavailableReason : null))
// --- Breakdown table -------------------------------------------------------
interface BreakdownRow {
id: string
name: string
value: number
share: number | null
}
const columns = computed(() =>
wbColumns<BreakdownRow>([
{ key: 'name', header: BREAKDOWN_LABEL[by.value], kind: 'text', sortable: false },
{ key: 'value', header: SPEND_METRIC_LABEL[metric.value], kind: 'number', sortable: false },
{ key: 'share', header: 'Share', kind: 'share', sortable: false },
]),
)
const sourceRows = computed<{ id: string; value: number }[]>(() => {
if (by.value === 'model') return spend.modelRanking.map((m) => ({ id: m.id, value: m.value }))
if (by.value === 'group') return spend.drilldownRows.map((r) => ({ id: r.id, value: r.values[metric.value] ?? 0 }))
return users.rows
})
const tableRows = computed<BreakdownRow[]>(() => {
const rows = sourceRows.value.filter((r) => r.value > 0 || by.value === 'model').sort((a, b) => b.value - a.value)
const sum = rows.reduce((acc, r) => acc + r.value, 0)
const total = filters.scope === 'all' && totalInRange.value > 0 ? totalInRange.value : sum
return rows.map((r) => ({ id: r.id, name: r.id, value: r.value, share: total > 0 ? Math.min(1, r.value / total) : null }))
})
const tablePage = ref(1)
const tableWindow = computed(() => pageWindow(tableRows.value.length, TABLE_PAGE_SIZE, tablePage.value - 1))
const pagedRows = computed(() => tableRows.value.slice(tableWindow.value.from, tableWindow.value.to))
watch([by, metric, () => filters.range, () => filters.scope], () => (tablePage.value = 1))
const tableError = computed(() => {
if (by.value === 'model') return spend.rankingError
if (by.value === 'group') return spend.drilldownError
return users.error
})
const tableState = computed<ViewState>(() => {
const loading = by.value === 'model' ? spend.loading : by.value === 'group' ? spend.drilldownLoading : !users.loaded
const hasData = by.value === 'user' ? users.loaded : by.value === 'group' ? spend.drilldownLoaded : spend.modelRanking.length > 0 || (spend.rankingError === '' && !spend.loading)
const s = loadState({ loading, hasData, error: tableError.value })
if (s === 'ready') return tableRows.value.length === 0 ? 'empty' : 'ready'
return s === 'skeleton' ? 'loading' : s
})
const tableRetryable = computed(() => tableError.value !== USERS_RANGE_TOO_LARGE)
function retryTable(): void {
if (by.value === 'user') void users.refresh(metric.value)
else void spend.refresh()
}
// --- Burn-down + forecast --------------------------------------------------
const forecastAvailable = computed(() => {
const parsed = parseScope(filters.scope)
return !parsed || parsed.kind === 'group' || parsed.kind === 'user'
})
const mtdMicros = computed(() => scopeMtdMicros(filters.scope, dashboard.usage))
const limits = computed(() => scopeBudgetLimits(filters.scope, dashboard.overview?.groups ?? [], dashboard.usage?.users ?? []))
const projected = computed(() => projectMonthEnd(mtdMicros.value, monthProgress(now.value)))
const room = computed(() => headroom(projected.value, limits.value?.costPerMonthUSD))
const burnLabels = computed(() => spend.burndownBuckets.map((b) => formatBucketLabel(b, 'day')))
const burnSpent = computed(() => cumulative(spend.burndownPoints))
const burnTotal = computed(() => burnSpent.value.at(-1) ?? 0)
const burnLines = computed<ChartLine[]>(() => {
if (burnSpent.value.length === 0) return []
const out: ChartLine[] = [{ name: 'Spent (MTD)', data: burnSpent.value, tone: 'primary' }]
const budget = spend.burndownBudgetMicros
if (budget !== null && budgetLineVisible(burnTotal.value, budget)) out.push({ name: 'Budget', data: burnSpent.value.map(() => budget), tone: 'danger' })
return out
})
const runOut = computed(() => (spend.burndownBudgetMicros === null ? null : runOutDate(burnTotal.value, spend.burndownBudgetMicros, now.value)))
const burnState = computed<ViewState>(() => {
const s = loadState({ loading: spend.burndownLoading, hasData: spend.burndownBuckets.length > 0, error: spend.burndownError })
return s === 'skeleton' ? 'loading' : s
})
// --- Cost avoided -----------------------------------------------------------
const cacheSavings = computed(() => cacheSavingsStatus(filters.window))
const cacheEnabled = computed(() => dashboard.overview?.features.cacheStats ?? false)
const referenceOptions = computed(() =>
spend.modelRanking
.filter((m) => {
const c = catalog.modelsById.get(m.id)
return c && c.priceSource !== 'free' && c.priceSource !== 'unpriced'
})
.sort((a, b) => (b.requests ?? 0) - (a.requests ?? 0))
.slice(0, 100)
.map((m) => ({ value: m.id, label: m.id })),
)
const effectiveRef = computed(() => refParam.value || pickReferenceModel(spend.modelRanking, catalog.modelsById) || '')
const avoidedMicros = computed(() => {
const cat = effectiveRef.value ? catalog.modelsById.get(effectiveRef.value) : undefined
if (!cat || cat.inputPerMTokUsd === undefined || cat.outputPerMTokUsd === undefined) return null
return costAvoidedMicros(freeRows(spend.modelRanking), cat.inputPerMTokUsd, cat.outputPerMTokUsd)
})
const cacheSavedMicros = computed(() => spend.modelRanking.reduce((acc, m) => acc + (m.cacheSavedMicroUsd ?? 0), 0))
const avoidedHint = computed(() => {
if (!spend.detailAvailable) return 'needs per-model detail'
if (referenceOptions.value.length === 0) return 'no priced model served in range'
return avoidedMicros.value === null ? 'pick a reference model' : `at ${effectiveRef.value} rates`
})
const avoidedState = computed<ViewState>(() => {
if (spend.rankingError && spend.modelRanking.length === 0) return 'error'
return spend.modelRanking.length === 0 && spend.loading ? 'loading' : 'ready'
})
// --- Pricing health ----------------------------------------------------------
const healthColumns = computed(() =>
wbColumns<PricingHealthRow>([
{ key: 'id', header: 'Model', kind: 'text', sortable: false },
{ key: 'priceSource', header: 'Source', kind: 'status', sortable: false },
{ key: 'inputPerMTokUsd', header: 'Price in / out per MTok', kind: 'text', sortable: false },
...(spend.detailAvailable
? [
{ key: 'requests', header: 'Requests', kind: 'number' as const, sortable: false },
{ key: 'costMicroUsd', header: 'Cost', kind: 'number' as const, sortable: false },
]
: []),
]),
)
const healthRows = computed(() => pricingHealthOrder(joinPricingHealth(spend.pricingHealthRanking, catalog.modelsById)))
const healthPage = ref(1)
const healthWindow = computed(() => pageWindow(healthRows.value.length, HEALTH_PAGE_SIZE, healthPage.value - 1))
const healthPaged = computed(() => healthRows.value.slice(healthWindow.value.from, healthWindow.value.to))
watch(() => [filters.range, filters.scope], () => (healthPage.value = 1))
const healthError = computed(() => spend.pricingHealthError || catalog.error)
const healthState = computed<ViewState>(() => {
const s = loadState({ loading: spend.pricingHealthLoading || catalog.loading, hasData: spend.pricingHealthLoaded && !catalog.error, error: healthError.value })
if (s === 'ready') return healthRows.value.length === 0 ? 'empty' : 'ready'
return s === 'skeleton' ? 'loading' : s
})
const unpricedCount = computed(() => healthRows.value.filter((r) => r.priceSource === 'unpriced').length)
function priceText(row: PricingHealthRow): string {
if (row.priceSource === 'unpriced' || row.inputPerMTokUsd === undefined || row.outputPerMTokUsd === undefined) return '—'
return formatModelPriceShort(row.inputPerMTokUsd, row.outputPerMTokUsd)
}
function retryHealth(): void {
void spend.fetchPricingHealthRanking()
if (catalog.error) void catalog.fetch()
}
// --- CSV export ---------------------------------------------------------------
const feedback = ref<DownloadOutcome | null>(null)
const FEEDBACK_LABEL: Record<DownloadOutcome, string> = { downloaded: 'Downloaded', copied: 'Copied', selected: 'Selected', failed: 'Export failed' }
let feedbackTimer: ReturnType<typeof setTimeout> | undefined
function groupMemberCount(id: string): string {
return String((dashboard.usage?.users ?? []).filter((u) => (u.groups ?? (u.groupName === undefined ? [] : [u.groupName])).includes(id)).length)
}
function buildCsv(): string {
if (by.value === 'group') return usageCsv(dashboard.usage?.groups ?? [], 'groups', (e) => groupMemberCount(e.id), now.value)
if (by.value === 'user') return usageCsv(dashboard.usage?.users ?? [], 'users', (e) => (e.groups ?? (e.groupName === undefined ? [] : [e.groupName])).join(', '), now.value)
return toCsv(['model', metric.value, 'share'], tableRows.value.map((r) => [r.id, r.value, r.share ?? '']))
}
async function exportCsv(): Promise<void> {
feedback.value = await downloadText(`usage-${by.value}.csv`, buildCsv())
if (feedbackTimer !== undefined) clearTimeout(feedbackTimer)
feedbackTimer = setTimeout(() => (feedback.value = null), FEEDBACK_MS)
}
onUnmounted(() => {
if (feedbackTimer !== undefined) clearTimeout(feedbackTimer)
})
const rangeLabel = computed(() => `last ${filters.range}`)
const money = (micros: number | null): string | null => (micros === null ? null : formatCostDisplay(micros))
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex flex-wrap items-center gap-3">
<SegmentedControl :model-value="metric" :options="metricOptions" size="sm" aria-label="Metric" @update:model-value="onMetric" />
<SegmentedControl :model-value="by" :options="byOptions" size="sm" aria-label="Break down by" @update:model-value="onBy" />
</div>
<Button variant="outline" size="sm" @click="exportCsv">{{ feedback ? FEEDBACK_LABEL[feedback] : 'Export CSV' }}</Button>
</div>
<StatGroup :columns="4" gap="sm" aria-label="Spend summary">
<KpiTile
:label="`${SPEND_METRIC_LABEL[metric]} in range`"
size="compact"
:value="totalReady ? fmt(totalInRange) : null"
:loading="!totalReady && !spend.breakdownError"
:delta="rangeDelta?.text"
:trend="rangeDelta?.trend"
:good-when="metric === 'cost' ? 'down' : 'none'"
:sparkline="sparkline"
:hint="rangeLabel"
/>
<KpiTile
label="Month to date"
size="compact"
:value="forecastAvailable && dashboard.usage ? money(mtdMicros) : null"
:loading="forecastAvailable && !dashboard.usage"
good-when="down"
:hint="forecastAvailable ? 'UTC calendar month' : 'no budget for a provider scope'"
/>
<KpiTile
label="Projected month-end"
size="compact"
:value="forecastAvailable && dashboard.usage ? (projected === null ? NOT_ENOUGH_DATA : money(projected)) : null"
:loading="forecastAvailable && !dashboard.usage"
:tone="room.willExceed ? 'danger' : undefined"
good-when="down"
:hint="room.limitMicros !== null ? `limit ${formatCostDisplay(room.limitMicros)}` : 'no limit configured'"
/>
<KpiTile
label="Budget run-out"
size="compact"
:value="spend.burndownBudgetMicros === null ? 'none' : runOut === null ? NOT_ENOUGH_DATA : formatShortDate(runOut)"
:loading="spend.burndownLoading && spend.burndownBuckets.length === 0"
:tone="runOut !== null && spend.burndownBudgetMicros !== null && burnTotal >= spend.burndownBudgetMicros ? 'danger' : undefined"
good-when="none"
:hint="spend.burndownBudgetMicros === null ? 'no budget for this scope' : `budget ${formatCostDisplay(spend.burndownBudgetMicros)}`"
/>
</StatGroup>
<p v-if="scopeNote" class="text-muted-foreground m-0 text-sm">{{ scopeNote }}</p>
<p v-if="compareNote" class="text-muted-foreground m-0 text-sm">{{ compareNote }}</p>
<Card size="sm">
<CardHeader><CardTitle>{{ SPEND_METRIC_LABEL[metric] }} over time</CardTitle></CardHeader>
<CardContent>
<StateView :state="chartState" empty-title="No usage in this range" :error-message="spend.breakdownError" @retry="spend.refresh()">
<div data-wb-ignore-numeric>
<LineChart
:labels="labels"
:series="lines"
variant="area"
stacked
:height="240"
:value-formatter="fmt"
:label="`${SPEND_METRIC_LABEL[metric]} per bucket by ${by}`"
/>
</div>
</StateView>
</CardContent>
</Card>
<div class="grid grid-cols-1 items-start gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,24rem)]">
<Card size="sm">
<CardHeader><CardTitle>By {{ BREAKDOWN_LABEL[by].toLowerCase() }}</CardTitle></CardHeader>
<CardContent class="flex flex-col gap-2">
<StateView
:state="tableState"
:empty-title="`No ${by} usage in this range`"
:error-message="tableError"
:retryable="tableRetryable"
@retry="retryTable"
>
<WbTable
:columns="columns"
:rows="pagedRows"
row-key="id"
:label="`${SPEND_METRIC_LABEL[metric]} by ${by}`"
@row-activate="(row: BreakdownRow) => openEntity(BREAKDOWN_ENTITY[by], row.id)"
>
<template #cell-name="{ value }">
<ModelName v-if="by === 'model'" :id="value as string" />
<template v-else>{{ value }}</template>
</template>
<template #cell-value="{ value }">{{ fmtValue(value) }}</template>
</WbTable>
<div v-if="tableRows.length > TABLE_PAGE_SIZE" class="flex items-center justify-between gap-2">
<span class="text-muted-foreground text-xs">{{ tableRows.length.toLocaleString('en-US') }} rows</span>
<Pagination v-model:page="tablePage" :total="tableRows.length" :page-size="TABLE_PAGE_SIZE" variant="compact" size="sm" />
</div>
</StateView>
</CardContent>
</Card>
<div class="flex flex-col gap-4">
<Card size="sm">
<CardHeader><CardTitle>Burn-down</CardTitle></CardHeader>
<CardContent>
<p v-if="!spend.burndownAvailable" class="text-muted-foreground m-0 text-sm">Not available for a provider scope.</p>
<StateView v-else :state="burnState" empty-title="No spend this month" :error-message="spend.burndownError" @retry="spend.fetchBurndown()">
<div data-wb-ignore-numeric>
<LineChart
:labels="burnLabels"
:series="burnLines"
variant="line"
:height="160"
:value-formatter="formatCostDisplay"
label="Cumulative spend this month against the budget"
/>
</div>
<p v-if="spend.burndownBudgetMicros === null" class="text-muted-foreground mt-2 mb-0 text-xs">No budget configured for this scope.</p>
</StateView>
</CardContent>
</Card>
<Card size="sm">
<CardHeader>
<CardTitle>Cost avoided</CardTitle>
</CardHeader>
<CardContent class="flex flex-col gap-3">
<StateView :state="avoidedState" :error-message="spend.rankingError" @retry="spend.refresh()">
<StatGroup :columns="cacheEnabled ? 2 : 1" gap="sm" aria-label="Savings">
<KpiTile
label="Free-tier traffic"
size="compact"
:value="spend.detailAvailable ? money(avoidedMicros) : null"
good-when="none"
:hint="avoidedHint"
/>
<KpiTile
v-if="cacheEnabled"
label="Cache savings"
size="compact"
:value="spend.detailAvailable && cacheSavings.available ? formatCostDisplay(cacheSavedMicros) : 'n/a'"
good-when="none"
:hint="cacheSavings.note ?? rangeLabel"
/>
</StatGroup>
<NativeSelect
v-if="spend.detailAvailable && referenceOptions.length > 0"
:model-value="effectiveRef"
:options="referenceOptions"
size="sm"
aria-label="Reference model"
@update:model-value="(v: string) => updateParams({ ref: v })"
/>
<p v-if="!spend.detailAvailable" class="text-muted-foreground m-0 text-xs">{{ DETAIL_NOTICE }}</p>
</StateView>
</CardContent>
</Card>
</div>
</div>
<Card size="sm">
<CardHeader class="items-center">
<CardTitle>Pricing health</CardTitle>
<CardAction v-if="healthState === 'ready'" class="self-center">
<Badge variant="outline" size="sm" :tone="unpricedCount > 0 ? 'danger' : 'neutral'">{{ unpricedCount }} unpriced</Badge>
</CardAction>
</CardHeader>
<CardContent class="flex flex-col gap-2">
<StateView :state="healthState" empty-title="No served models in this range" :error-message="healthError" @retry="retryHealth">
<p v-if="!spend.detailAvailable" class="text-muted-foreground m-0 text-xs">{{ DETAIL_NOTICE }}</p>
<WbTable
:columns="healthColumns"
:rows="healthPaged"
row-key="id"
label="Pricing health by model"
@row-activate="(row: PricingHealthRow) => openEntity('model', row.id)"
>
<template #cell-id="{ value }"><ModelName :id="value as string" /></template>
<template #cell-priceSource="{ value }">
<Badge variant="outline" size="sm" :tone="value === 'unpriced' ? 'danger' : 'neutral'">{{ value }}</Badge>
</template>
<template #cell-inputPerMTokUsd="{ row }"><span class="font-mono text-xs">{{ priceText(row as PricingHealthRow) }}</span></template>
<template #cell-requests="{ value }">{{ formatCompactCount(value as number) }}</template>
<template #cell-costMicroUsd="{ value }">{{ formatCostDisplay(value as number) }}</template>
</WbTable>
<div v-if="healthRows.length > HEALTH_PAGE_SIZE" class="flex items-center justify-between gap-2">
<span class="text-muted-foreground text-xs">{{ healthRows.length.toLocaleString('en-US') }} models</span>
<Pagination v-model:page="healthPage" :total="healthRows.length" :page-size="HEALTH_PAGE_SIZE" variant="compact" size="sm" />
</div>
</StateView>
</CardContent>
</Card>
</div>
</template>
+65
View File
@@ -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)
}
})
})
+19 -7
View File
@@ -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<AdminUsageModelsResponse>(
`/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<AdminUsageModelsResponse>(
`/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<AdminUsageModelsResponse>(base), detail: false }
try {
return { res: await adminFetch<AdminUsageModelsResponse>(`${base}&detail=1`), detail: true }
} catch (err) {
if (!(err instanceof AdminApiError) || err.status !== 400) throw err
return { res: await adminFetch<AdminUsageModelsResponse>(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'
+59
View File
@@ -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<typeof import('@/lib/api')>('@/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)
})
})
+78
View File
@@ -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<void> {
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<AdminTotalsResponse>(`/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<AdminSeriesResponse>(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)
}
},
},
})
+15
View File
@@ -0,0 +1,15 @@
<script setup lang="ts">
import { computed } from 'vue'
import { splitModelId } from '@/lib/model-id'
const props = defineProps<{ id: string }>()
const parts = computed(() => splitModelId(props.id))
</script>
<template>
<span class="wb-model" :title="id">
<span v-if="parts.provider" class="wb-model-provider">{{ parts.provider }}</span>
<span class="wb-model-name">{{ parts.model }}</span>
</span>
</template>