fix(webui): users page filter, labels, panel fetches

This commit is contained in:
2026-11-25 11:52:37 +00:00
parent a138b186b6
commit 19950c40f6
15 changed files with 202 additions and 50 deletions
+21
View File
@@ -107,6 +107,27 @@ for (const { page: pageId, kind, scenario = 'live' } of PANEL_PAGES) {
}
}
// The limits snippet form inside the user panel, opened.
for (const [vp, size] of Object.entries(VIEWPORTS)) {
for (const theme of THEMES) {
test(`users panel snippet limits-hot ${vp} ${theme}`, async ({ page }) => {
await page.setViewportSize(size)
const sel = (await sampleIds(page, 'limits-hot')).user
await visit(page, `#users?sel=${encodeURIComponent(sel)}`, 'limits-hot', theme)
await page.getByRole('button', { name: 'Generate limits snippet' }).click()
await page.getByLabel('Requests/minute').fill('45')
const snippet = page.locator('pre', { hasText: 'requestsPerMinute' })
await snippet.scrollIntoViewIfNeeded()
await expect(snippet).toBeVisible()
const name = `users-panel-snippet-limits-hot-${vp}-${theme}`
mkdirSync(OUT, { recursive: true })
await page.screenshot({ path: join(OUT, `${name}.png`), fullPage: true })
const results = await runChecks(page, [])
for (const r of results) expect.soft(r.ok, `${r.name}: ${r.detail}`).toBe(true)
})
}
}
// Compare mode: tiles show a delta and the chart adds a dashed previous-period series.
for (const theme of THEMES) {
test(`overview-cmp live desktop ${theme}`, async ({ page }) => {
+3 -3
View File
@@ -487,7 +487,7 @@
"total": 0
},
"minimax": {
"allowed": 0,
"allowed": 1,
"total": 9
},
"nvidia-nim": {
@@ -515,7 +515,7 @@
"total": 0
},
"uni": {
"allowed": 0,
"allowed": 14,
"total": 14
},
"xai": {
@@ -739,4 +739,4 @@
"memberCount": 1
}
]
}
}
+29 -1
View File
@@ -31,6 +31,10 @@ const HOT_MINUTE_FRACTION = 0.93
const HOT_DAY_FRACTION = 0.9
const BREAKER_OPEN_MS = 90_000
const HUGE_FACTOR = 3
/** Each captured user becomes this many in the huge scenario. */
const HUGE_USER_FACTOR = 20
const HOT_TOKENS_IN_PER_REQUEST = 1500
const HOT_TOKENS_OUT_PER_REQUEST = 400
export interface ScenarioContext {
now: number
@@ -231,7 +235,20 @@ function limitsHot(path: string, body: Obj, ctx: ScenarioContext) {
addToGroupAndTotal(body, HOT_GROUP, 'tokensPerMinute', tpm - (u.tokensPerMinute ?? 0))
u.tokensPerMinute = tpm
}
if (u.limits.requestsPerDay > 0) u.requestsPerDay = Math.floor(u.limits.requestsPerDay * HOT_DAY_FRACTION)
if (u.limits.requestsPerDay > 0) {
const day = Math.floor(u.limits.requestsPerDay * HOT_DAY_FRACTION)
addToGroupAndTotal(body, HOT_GROUP, 'requestsPerDay', day - u.requestsPerDay)
u.requestsPerDay = day
}
const tokensIn = u.requestsPerDay * HOT_TOKENS_IN_PER_REQUEST
const tokensOut = u.requestsPerDay * HOT_TOKENS_OUT_PER_REQUEST
addToGroupAndTotal(body, HOT_GROUP, 'tokensInPerDay', tokensIn - u.tokensInPerDay)
addToGroupAndTotal(body, HOT_GROUP, 'tokensOutPerDay', tokensOut - u.tokensOutPerDay)
u.tokensInPerDay = tokensIn
u.tokensOutPerDay = tokensOut
u.tokensInPerMonth = Math.max(u.tokensInPerMonth ?? 0, tokensIn)
u.tokensOutPerMonth = Math.max(u.tokensOutPerMonth ?? 0, tokensOut)
u.lastSeen = Math.floor(ctx.now / 1000)
u.rejectionsPerDay = Math.max(u.rejectionsPerDay ?? 0, 9)
}
} else if (path === '/admin/api/events') {
@@ -261,6 +278,13 @@ function hugeModelIds(id: string): string[] {
const expandRows = (rows: Obj[], ids: (id: string) => string[]): Obj[] => rows.flatMap((r) => ids(r.id).map((id) => ({ ...r, id })))
/** A clone of one user with a distinct id and a spread of traffic, so rankings and shares differ. */
function hugeUser(u: Obj, n: number): Obj {
const scale = 1 / (n + 1)
const scaled = (v: unknown) => (typeof v === 'number' ? Math.floor(v * scale) : v)
return { ...u, id: `${u.id}-${n + 1}`, requestsPerDay: scaled(u.requestsPerDay), tokensInPerDay: scaled(u.tokensInPerDay), tokensOutPerDay: scaled(u.tokensOutPerDay) }
}
function huge(path: string, body: Obj) {
if (path === '/admin/api/overview') {
body.providers = (body.providers as Obj[]).flatMap((p) =>
@@ -278,6 +302,10 @@ function huge(path: string, body: Obj) {
return { ...p, name, models }
}),
)
} else if (path === '/admin/api/usage' && Array.isArray(body.users)) {
body.users = (body.users as Obj[]).flatMap((u) => copies(HUGE_USER_FACTOR, (n) => (n === 0 ? u : hugeUser(u, n))))
} else if (path === '/admin/api/consumers' && Array.isArray(body.users)) {
body.users = (body.users as Obj[]).flatMap((u) => copies(HUGE_USER_FACTOR, (n) => (n === 0 ? u : { ...u, name: `${u.name}-${n + 1}` })))
} else if (path === '/admin/api/usage/models' && Array.isArray(body.models)) {
body.models = expandRows(body.models, hugeModelIds)
} else if (path === '/admin/api/performance' && Array.isArray(body.rows)) {
+1 -1
View File
@@ -57,6 +57,6 @@ const BUTTON_LABEL: Record<typeof state.value, string> = {
{{ BUTTON_LABEL[state] }}
</Button>
</div>
<pre ref="pre" class="overflow-x-auto rounded-md border bg-muted p-3 font-mono text-xs select-text whitespace-pre">{{ text }}</pre>
<pre ref="pre" tabindex="0" class="overflow-x-auto rounded-md border bg-muted p-3 font-mono text-xs select-text whitespace-pre">{{ text }}</pre>
</div>
</template>
+5 -5
View File
@@ -66,24 +66,24 @@ const raw = reactive<Record<LimitKey, string>>({
/** invalidFields lists every field whose entered text is non-empty but fails its own domain check (fieldValid above) — surfaced individually rather than one generic "invalid input" message, so the operator can see exactly which field to fix. Split by INTEGER_FIELDS so the error text is accurate for both: a fraction is invalid for requestsPerMinute etc. but perfectly valid for costPerDayUSD/costPerMonthUSD. */
const invalidFields = computed(() =>
FIELDS.filter(({ key }) => raw[key].trim() !== '' && !fieldValid(key, Number(raw[key]))).map((f) => f.label),
FIELDS.filter(({ key }) => String(raw[key]).trim() !== '' && !fieldValid(key, Number(raw[key]))).map((f) => f.label),
)
/** fieldInvalid is the per-input twin of invalidFields, so each input can carry aria-invalid. */
function fieldInvalid(key: (typeof FIELDS)[number]['key']): boolean {
return raw[key].trim() !== '' && !fieldValid(key, Number(raw[key]))
return String(raw[key]).trim() !== '' && !fieldValid(key, Number(raw[key]))
}
const invalidIntegerFields = computed(() =>
FIELDS.filter(({ key }) => INTEGER_FIELDS.has(key) && raw[key].trim() !== '' && !fieldValid(key, Number(raw[key]))).map((f) => f.label),
FIELDS.filter(({ key }) => INTEGER_FIELDS.has(key) && String(raw[key]).trim() !== '' && !fieldValid(key, Number(raw[key]))).map((f) => f.label),
)
const invalidDecimalFields = computed(() =>
FIELDS.filter(({ key }) => !INTEGER_FIELDS.has(key) && raw[key].trim() !== '' && !fieldValid(key, Number(raw[key]))).map((f) => f.label),
FIELDS.filter(({ key }) => !INTEGER_FIELDS.has(key) && String(raw[key]).trim() !== '' && !fieldValid(key, Number(raw[key]))).map((f) => f.label),
)
const limits = computed<LimitsConfig>(() => {
const out: LimitsConfig = {}
for (const { key } of FIELDS) {
const value = Number(raw[key])
if (raw[key].trim() !== '' && fieldValid(key, value) && value > 0) out[key] = value
if (String(raw[key]).trim() !== '' && fieldValid(key, value) && value > 0) out[key] = value
}
return out
})
+1 -1
View File
@@ -30,7 +30,7 @@ describe('EVENT_KIND_LABEL', () => {
describe('EVENT_KINDS', () => {
it('contains every known AdminEventKind, derived from EVENT_KIND_LABEL', () => {
expect(EVENT_KINDS).toEqual(Object.keys(EVENT_KIND_LABEL))
expect(EVENT_KINDS).toEqual(['rate_limit', 'budget', 'store_down', 'upstream', 'timeout', 'unpriced', 'capacity'])
expect(EVENT_KINDS).toEqual(['rate_limit', 'budget', 'store_down', 'upstream', 'timeout', 'unpriced', 'capacity', 'paced'])
})
it('every entry has a truthy label (no silently-empty display text)', () => {
+1
View File
@@ -9,6 +9,7 @@ export const EVENT_KIND_LABEL: Record<AdminEventKind, string> = {
timeout: 'Timeout',
unpriced: 'Unpriced model',
capacity: 'Capacity',
paced: 'Paced',
}
/**
+5
View File
@@ -82,6 +82,11 @@ describe('effectiveLimitRows', () => {
expect(rows.find((r) => r.label === 'Requests/day')).toMatchObject({ value: '3,000', source: 'user' })
expect(rows.find((r) => r.label === 'Pacing')).toMatchObject({ value: 'from 80%, up to 10s delay' })
})
it('formats cost limits with the shared cost format and marks pacing as prose', () => {
const rows = effectiveLimitRows({ costPerMonthUSD: 25, pacing: PACING }, undefined)
expect(rows.find((r) => r.key === 'costPerMonthUSD')?.value).toBe('$25.00')
expect(rows.find((r) => r.key === 'pacing')?.prose).toBe(true)
})
it('returns no rows without limits', () => {
expect(effectiveLimitRows(undefined, undefined)).toEqual([])
})
+5 -3
View File
@@ -1,4 +1,4 @@
import { formatCompactCount } from '@/lib/format'
import { formatCompactCount, formatCostDisplay, usdToMicros } from '@/lib/format'
import type { AdminUsageEntryView, LimitSources, LimitsConfig } from '@/types/api'
/** Pacing starts here when a scope sets no pacing block; matches the budget bars' amber tier. */
@@ -75,6 +75,8 @@ export interface LimitRow {
label: string
value: string
source: string
/** Prose rather than a number: the value is not set in mono. */
prose?: boolean
}
const LIMIT_FIELDS: Array<{ key: Exclude<keyof LimitsConfig, 'pacing'>; label: string; usd?: boolean }> = [
@@ -100,10 +102,10 @@ export function effectiveLimitRows(limits: LimitsConfig | undefined, sources: Li
const rows: LimitRow[] = []
for (const f of LIMIT_FIELDS) {
const v = limits[f.key]
if (has(v)) rows.push({ key: f.key, label: f.label, value: f.usd ? `$${v}` : formatCompactCount(v), source: sourceLabel(sources?.[f.key]) })
if (has(v)) rows.push({ key: f.key, label: f.label, value: f.usd ? formatCostDisplay(usdToMicros(v)) : formatCompactCount(v), source: sourceLabel(sources?.[f.key]) })
}
if (limits.pacing) {
rows.push({ key: 'pacing', label: 'Pacing', value: `from ${limits.pacing.startPct}%, up to ${limits.pacing.maxDelay} delay`, source: sourceLabel(sources?.pacing) })
rows.push({ key: 'pacing', label: 'Pacing', value: `from ${limits.pacing.startPct}%, up to ${limits.pacing.maxDelay} delay`, source: sourceLabel(sources?.pacing), prose: true })
}
return rows
}
+22 -8
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { Card, CardAction, CardContent, CardHeader, CardTitle, Pagination, SegmentedControl } from '@perfect-design/ui'
import { Card, CardAction, CardContent, CardHeader, CardTitle, Pagination, SearchInput, SegmentedControl } from '@perfect-design/ui'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useNow } from '@/composables/useNow'
@@ -78,29 +78,40 @@ function toRow(e: AdminUsageEntryView): Row {
const byRequests = (a: Row, b: Row): number => b.requests - a.requests || a.name.localeCompare(b.name)
const userRows = computed<Row[]>(() => (usage.value?.users ?? []).map(toRow).sort(byRequests))
const groupRows = computed<Row[]>(() => (usage.value?.groups ?? []).map(toRow).sort(byRequests))
const rows = computed(() => (tab.value === 'users' ? userRows.value : groupRows.value))
const query = computed<string>({
get: () => nav.params.q ?? '',
set: (v) => {
const { q: _q, ...rest } = nav.params
nav.goTo('users', v ? { ...rest, q: v } : rest)
},
})
const needle = computed(() => query.value.trim().toLowerCase())
const allRows = computed(() => (tab.value === 'users' ? userRows.value : groupRows.value))
const rows = computed(() =>
needle.value === '' ? allRows.value : allRows.value.filter((r) => r.name.toLowerCase().includes(needle.value) || (tab.value === 'users' && r.group.toLowerCase().includes(needle.value))),
)
const userColumns = wbColumns<Row>([
{ key: 'name', header: 'Name', kind: 'text' },
{ key: 'group', header: 'Group', kind: 'text' },
{ key: 'lastSeen', header: 'Last seen', kind: 'time', sortable: false },
{ key: 'requests', header: 'Req/day', kind: 'number' },
{ key: 'tokens', header: 'Tokens/day', kind: 'number' },
{ key: 'requests', header: 'Req today', kind: 'number' },
{ key: 'tokens', header: 'Tokens today', kind: 'number' },
{ key: 'share', header: 'Share', kind: 'share' },
{ key: 'limit', header: 'Limit', kind: 'limit', sortable: false },
])
const groupColumns = wbColumns<Row>([
{ key: 'name', header: 'Name', kind: 'text' },
{ key: 'members', header: 'Members', kind: 'number' },
{ key: 'requests', header: 'Req/day', kind: 'number' },
{ key: 'tokens', header: 'Tokens/day', kind: 'number' },
{ key: 'requests', header: 'Req today', kind: 'number' },
{ key: 'tokens', header: 'Tokens today', kind: 'number' },
{ key: 'share', header: 'Share', kind: 'share' },
{ key: 'limit', header: 'Limit', kind: 'limit', sortable: false },
])
const columns = computed(() => (tab.value === 'users' ? userColumns : groupColumns))
const page = ref(1)
watch(tab, () => (page.value = 1))
watch([tab, needle], () => (page.value = 1))
const window_ = computed(() => pageWindow(rows.value.length, PAGE_SIZE, page.value - 1))
const paged = computed(() => rows.value.slice(window_.value.from, window_.value.to))
@@ -110,7 +121,9 @@ const state = computed<ViewState>(() => {
if (s === 'error') return 'error'
return rows.value.length === 0 ? 'empty' : 'ready'
})
const emptyTitle = computed(() => (tab.value === 'users' ? 'No users configured' : 'No groups configured'))
const emptyTitle = computed(() =>
needle.value !== '' ? `No ${tab.value} match "${query.value.trim()}"` : tab.value === 'users' ? 'No users configured' : 'No groups configured',
)
const selection = computed(() => nav.selection)
const activeKey = computed(() => (selection.value?.kind === (tab.value === 'users' ? 'user' : 'group') ? selection.value.id : null))
@@ -149,6 +162,7 @@ onUnmounted(stopClock)
</CardAction>
</CardHeader>
<CardContent class="flex flex-col gap-2">
<SearchInput v-model="query" size="sm" class="max-w-sm" :placeholder="tab === 'users' ? 'Filter by name or group' : 'Filter by name'" :aria-label="`Filter ${tab}`" />
<StateView :state="state" :empty-title="emptyTitle" :error-message="dashboard.error" :updated-at="dashboard.lastUpdated ?? undefined" @retry="dashboard.refresh()">
<WbTable
class="wb-clip"
+14 -11
View File
@@ -24,7 +24,6 @@ const members = computed(() =>
.filter((u) => (u.groups ?? [u.groupName]).includes(props.id))
.sort((a, b) => b.requestsPerDay - a.requestsPerDay || a.id.localeCompare(b.id)),
)
const memberCount = computed(() => dashboard.overview?.groups.find((g) => g.name === props.id)?.memberCount ?? members.value.length)
const shownMembers = computed(() => members.value.slice(0, MEMBER_ROWS))
const meters = computed(() => (entry.value ? meterModel(entry.value, entry.value.limits) : []))
@@ -50,26 +49,19 @@ const usageRows = computed(() => {
<div class="flex flex-col divide-y px-1 pb-4" data-testid="group-panel">
<div v-if="!entry" class="text-muted-foreground py-3 text-sm">This group has no usage data yet.</div>
<template v-else>
<PanelSection title="Usage">
<DescriptionList variant="inline" size="sm" density="compact">
<DescriptionItem term="Members"><span class="font-mono tabular-nums">{{ formatCompactCount(memberCount) }}</span></DescriptionItem>
<DescriptionItem v-for="r in usageRows" :key="r.term" :term="r.term"><span class="font-mono tabular-nums">{{ r.value }}</span></DescriptionItem>
</DescriptionList>
</PanelSection>
<PanelSection title="Aggregate limits">
<div v-if="meters.length" class="flex flex-col gap-3">
<MeterBar v-for="m in meters" :key="m.label" :meter="m" />
</div>
<p v-else class="text-muted-foreground m-0 text-sm">No aggregate limits. Members are limited individually.</p>
<DescriptionList v-if="aggregateRows.length" variant="inline" size="sm" density="compact">
<DescriptionItem v-for="r in aggregateRows" :key="r.key" :term="r.label"><span class="font-mono tabular-nums">{{ r.value }}</span></DescriptionItem>
<DescriptionItem v-for="r in aggregateRows" :key="r.key" :term="r.label"><span :class="r.prose ? '' : 'font-mono tabular-nums'">{{ r.value }}</span></DescriptionItem>
</DescriptionList>
</PanelSection>
<PanelSection title="Per-member limits">
<DescriptionList v-if="memberRows.length" variant="inline" size="sm" density="compact">
<DescriptionItem v-for="r in memberRows" :key="r.key" :term="r.label"><span class="font-mono tabular-nums">{{ r.value }}</span></DescriptionItem>
<DescriptionItem v-for="r in memberRows" :key="r.key" :term="r.label"><span :class="r.prose ? '' : 'font-mono tabular-nums'">{{ r.value }}</span></DescriptionItem>
</DescriptionList>
<p v-else class="text-muted-foreground m-0 text-sm">No per-member limits.</p>
</PanelSection>
@@ -84,7 +76,18 @@ const usageRows = computed(() => {
</li>
</ul>
<p v-else class="text-muted-foreground m-0 text-sm">No members.</p>
<p v-if="members.length > MEMBER_ROWS" class="text-muted-foreground m-0 px-2 text-xs">Top {{ MEMBER_ROWS }} by requests. {{ (members.length - MEMBER_ROWS).toLocaleString('en-US') }} more on the Users tab.</p>
<p v-if="members.length > MEMBER_ROWS" class="text-muted-foreground m-0 px-2 text-xs">
Top {{ MEMBER_ROWS }} by requests.
<button type="button" class="text-primary underline-offset-2 hover:underline" @click="nav.goTo('users', { q: id }, { replace: false })">
Show all {{ members.length.toLocaleString('en-US') }} on the Users tab
</button>
</p>
</PanelSection>
<PanelSection title="Usage">
<DescriptionList variant="inline" size="sm" density="compact">
<DescriptionItem v-for="r in usageRows" :key="r.term" :term="r.term"><span class="font-mono tabular-nums">{{ r.value }}</span></DescriptionItem>
</DescriptionList>
</PanelSection>
</template>
</div>
+31 -17
View File
@@ -48,13 +48,13 @@ const exempt = computed(() => entry.value?.exemptRequestsPerMonth ?? 0)
// --- Models used ------------------------------------------------------------
const userModelStats = computed(() => dashboard.overview?.features.userModelStats ?? false)
const detail = computed(() => consumers.detail[props.id])
const detail = computed(() => consumers.models[props.id])
const modelRows = computed(() =>
[...(detail.value?.modelTotals?.rows ?? [])].sort((a, b) => (b.values.req ?? 0) - (a.values.req ?? 0)),
[...(detail.value?.totals?.rows ?? [])].sort((a, b) => (b.values.req ?? 0) - (a.values.req ?? 0)),
)
const modelsState = computed<ViewState>(() => {
if (dashboard.overview !== null && (!userModelStats.value || detail.value?.modelTotalsUnavailable)) return 'empty'
const s = loadState({ loading: detail.value?.loading ?? true, hasData: detail.value?.modelTotals != null, error: detail.value?.modelError ?? '' })
if (dashboard.overview !== null && (!userModelStats.value || detail.value?.unavailable)) return 'empty'
const s = loadState({ loading: detail.value?.loading ?? true, hasData: detail.value?.totals != null, error: detail.value?.error ?? '' })
if (s === 'skeleton') return 'loading'
if (s === 'error') return 'error'
return modelRows.value.length === 0 ? 'empty' : 'ready'
@@ -63,7 +63,7 @@ const modelsEmptyTitle = computed(() => (userModelStats.value ? 'No model traffi
const modelsEmptyDescription = computed(() => (userModelStats.value ? undefined : 'Enable admin.stats.userModel to see which models this user calls.'))
function loadModels(): Promise<void> {
return consumers.fetchUserDetail(props.id, filters.window, filters.span, userModelStats.value)
return userModelStats.value ? consumers.fetchUserModels(props.id, filters.window, filters.span) : Promise.resolve()
}
// --- Throttle events --------------------------------------------------------
@@ -85,15 +85,25 @@ function clock(iso: string): string {
// --- Access ----------------------------------------------------------------
const groupRows = computed(() => (consumers.data?.groups ?? []).filter((g) => groups.value.includes(g.name)))
const providers = computed(() => {
const out = new Map<string, string>()
interface ProviderAccess {
name: string
detail: string
zero: boolean
allowed: number
}
// With several groups, the most permissive one decides what the user can reach.
const providers = computed<ProviderAccess[]>(() => {
const best = new Map<string, ProviderAccess>()
for (const g of groupRows.value) {
for (const p of g.allowedProviders) {
const cell = providerAccessCell(g, p)
if (!out.has(p) || (cell.detail && !out.get(p))) out.set(p, cell.detail ?? '')
for (const name of g.allowedProviders) {
const cell = providerAccessCell(g, name)
const allowed = g.modelAccess[name]?.allowed ?? Number.POSITIVE_INFINITY
const prev = best.get(name)
if (!prev || allowed > prev.allowed) best.set(name, { name, detail: cell.detail ?? '', zero: cell.zero === true, allowed })
}
}
return [...out].map(([name, detail]) => ({ name, detail })).sort((a, b) => a.name.localeCompare(b.name))
return [...best.values()].sort((a, b) => a.name.localeCompare(b.name))
})
const accessState = computed<ViewState>(() => (consumers.data ? 'ready' : consumers.error ? 'error' : 'loading'))
@@ -147,19 +157,23 @@ onUnmounted(() => {
<PanelSection title="Effective limits">
<DescriptionList v-if="limitRows.length || exempt" variant="inline" size="sm" density="compact">
<DescriptionItem v-for="r in limitRows" :key="r.key" :term="r.label">
<span class="font-mono tabular-nums">{{ r.value }}</span>
<span v-if="r.source" class="text-muted-foreground"> · {{ r.source }}</span>
<span class="flex flex-col items-end text-right">
<span :class="r.prose ? '' : 'font-mono tabular-nums'">{{ r.value }}</span>
<span v-if="r.source" class="text-muted-foreground text-xs">{{ r.source }}</span>
</span>
</DescriptionItem>
<DescriptionItem v-if="exempt" term="Exempt requests/month">
<span class="font-mono tabular-nums">{{ formatCompactCount(exempt) }}</span>
<span class="text-muted-foreground"> · limitExemptKinds</span>
<span class="flex flex-col items-end text-right">
<span class="font-mono tabular-nums">{{ formatCompactCount(exempt) }}</span>
<span class="text-muted-foreground text-xs">limitExemptKinds</span>
</span>
</DescriptionItem>
</DescriptionList>
<p v-else class="text-muted-foreground m-0 text-sm">No limits set.</p>
</PanelSection>
<PanelSection title="Models used">
<StateView :state="modelsState" :empty-title="modelsEmptyTitle" :empty-description="modelsEmptyDescription" :error-message="detail?.modelError" :rows="3" @retry="loadModels()">
<StateView :state="modelsState" :empty-title="modelsEmptyTitle" :empty-description="modelsEmptyDescription" :error-message="detail?.error" :rows="3" @retry="loadModels()">
<ul class="m-0 flex list-none flex-col p-0" aria-label="Models used">
<li v-for="m in modelRows" :key="m.id" class="flex h-8 items-center justify-between gap-3 px-2 text-sm">
<ModelName :id="m.id" class="min-w-0" />
@@ -188,7 +202,7 @@ onUnmounted(() => {
<DescriptionItem term="Providers">
<span v-if="providers.length === 0" class="text-muted-foreground">None granted by group</span>
<span v-else class="flex flex-wrap gap-1">
<Badge v-for="p in providers" :key="p.name" tone="neutral" variant="outline" size="sm" class="font-mono">{{ p.name }}<template v-if="p.detail"> · {{ p.detail }}</template></Badge>
<Badge v-for="p in providers" :key="p.name" :tone="p.zero ? 'warning' : 'neutral'" variant="outline" size="sm" class="font-mono" :title="p.zero ? 'Provider granted, but no model matches the group model list' : undefined">{{ p.name }}<template v-if="p.detail"> · {{ p.detail }}</template></Badge>
</span>
</DescriptionItem>
<DescriptionItem v-if="consumer?.providers?.length" term="Personal providers">
+32
View File
@@ -334,3 +334,35 @@ describe('evictOldestDetails', () => {
expect(Object.keys(detail).sort()).toEqual(want)
})
})
describe('useConsumersStore.fetchUserModels', () => {
beforeEach(() => {
setActivePinia(createPinia())
mockedAdminFetch.mockReset()
useAuthStore().submit('test-admin-key')
})
it('fetches only the usermodel totals', async () => {
mockedAdminFetch.mockResolvedValue(emptyTotals)
const store = useConsumersStore()
await store.fetchUserModels('alice', 'day', 7)
expect(mockedAdminFetch).toHaveBeenCalledTimes(1)
expect(String(mockedAdminFetch.mock.calls[0]?.[0])).toContain('kind=usermodel')
expect(store.models.alice).toMatchObject({ loading: false, error: '', unavailable: false })
expect(store.models.alice?.totals).toEqual(emptyTotals)
})
it('a 404 marks the feature unavailable without an error', async () => {
mockedAdminFetch.mockRejectedValue(new AdminApiError('not found', 404))
const store = useConsumersStore()
await store.fetchUserModels('alice', 'day', 7)
expect(store.models.alice).toMatchObject({ unavailable: true, error: '', totals: null })
})
it('other failures surface as an error', async () => {
mockedAdminFetch.mockRejectedValue(new AdminApiError('boom', 500))
const store = useConsumersStore()
await store.fetchUserModels('alice', 'day', 7)
expect(store.models.alice?.error).not.toBe('')
})
})
+31
View File
@@ -43,6 +43,16 @@ export interface UserDetailState {
span: number | null
}
/** UserModelsState is one user's per-model totals alone (UserPanel), without the two series UserDetail also fetches. */
export interface UserModelsState {
loading: boolean
error: string
totals: AdminTotalsResponse | null
/** The usermodel call came back 404: the feature is off server-side. */
unavailable: boolean
reqId: number
}
/** MAX_CACHED_USER_DETAILS caps how many opened users' detail the store keeps in memory. */
export const MAX_CACHED_USER_DETAILS = 20
@@ -96,6 +106,7 @@ export const useConsumersStore = defineStore('consumers', {
error: '',
fetchedAt: null as number | null,
detail: {} as Record<string, UserDetailState>,
models: {} as Record<string, UserModelsState>,
}),
actions: {
/**
@@ -130,6 +141,26 @@ export const useConsumersStore = defineStore('consumers', {
if (this.data && this.fetchedAt !== null && Date.now() - this.fetchedAt < REFRESH_STALE_MS) return
await this.fetchConsumers()
},
/** fetchUserModels loads only the usermodel totals (latest request wins); a 404 sets `unavailable` instead of an error. */
async fetchUserModels(userId: string, window: HistoryWindow, span: number): Promise<void> {
const auth = useAuthStore()
if (!auth.isAuthenticated) return
const prev = this.models[userId]
const reqId = (prev?.reqId ?? 0) + 1
this.models[userId] = { loading: true, error: '', totals: prev?.totals ?? null, unavailable: false, reqId }
const clamped = dayOrMonthWindow(window, span)
try {
const totals = await adminFetch<AdminTotalsResponse>(
totalsUrl({ kind: 'usermodel', user: userId, window: clamped.window, span: clamped.span, metrics: ['req', 'cost'] }),
)
if (this.models[userId]?.reqId !== reqId) return
this.models[userId] = { loading: false, error: '', totals, unavailable: false, reqId }
} catch (err) {
if (this.models[userId]?.reqId !== reqId || isAuthRejection(err)) return
const unavailable = err instanceof AdminApiError && err.status === 404
this.models[userId] = { loading: false, error: unavailable ? '' : messageOf(err), totals: null, unavailable, reqId }
}
},
/**
* fetchUserDetail loads one user's timeline (req + cost series) and,
* only when `userModelStatsEnabled` is true (AdminFeaturesView.
+1
View File
@@ -665,6 +665,7 @@ export type AdminEventKind =
| 'timeout'
| 'unpriced'
| 'capacity'
| 'paced'
/**
* One row in GET /admin/api/events (admin.go/events.go: gatewayEvent — the