fix(webui): compact overview events and request-ranked top lists

This commit is contained in:
2026-11-25 11:52:36 +00:00
parent d2334d879b
commit bbb397cd75
10 changed files with 114 additions and 89 deletions
+9
View File
@@ -89,3 +89,12 @@ for (const { page: pageId, kind } of PANEL_PAGES) {
}
}
}
// 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 }) => {
await page.setViewportSize(VIEWPORTS.desktop)
await exercise(page, 'overview-cmp', '#overview?cmp=prev', 'live', 'desktop', theme)
await expect(page.locator('text=Previous period >> visible=true').first()).toBeVisible()
})
}
+5 -1
View File
@@ -155,7 +155,11 @@ export function nearestFixture(manifest: Fixture[], path: string, query: URLSear
for (const k of ID_PARAMS[path]!) if (want[k]?.join() === have[k]?.join()) score += 30
score += need.length === got.length ? 10 : 0
} else if (path === '/admin/api/usage/models') {
if (!want.detail !== !have.detail) continue
// A detail fixture holds the full ranking, so it can answer a plain request for any metric; a
// plain fixture is a top-N cut of one metric and only answers that metric.
if (want.detail && !have.detail) continue
if (!have.detail && have.metric?.[0] !== want.metric?.[0]) continue
score += have.metric?.[0] === want.metric?.[0] ? 100 : 0
} else if (path === '/admin/api/performance') {
if (want.kind?.[0] !== have.kind?.[0] || !want.series !== !have.series) continue
if (!want.id !== !have.id) continue
+4
View File
@@ -207,3 +207,7 @@
.wb-table :is(th, td).wb-num { text-align: right; }
.wb-table th.wb-num > * { justify-content: flex-end; }
.wb-table .wb-share-bar { min-width: 96px; }
/* 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; } }
+8
View File
@@ -89,6 +89,14 @@ describe('respond', () => {
expect(r.body).toEqual({ error: { message: expect.any(String), type: 'invalid_request_error', code: '404' } })
})
it('ranks usage/models by the requested metric, not by a top-N cut of another one', () => {
const r = get('/admin/api/usage/models', 'metric=req&window=day&span=7&limit=5')
const ids = ((r.body as Any).models as Any[]).map((m) => m.id)
expect(ids[0]).toBe('uni/text-embedding-multilingual-e5-base')
expect(ids).toHaveLength(5)
expect(ids).toContain('uni/deepseek-v4-flash-0731')
})
it('404s an unknown path', () => {
expect(get('/admin/api/nope').status).toBe(404)
})
+23 -51
View File
@@ -1,11 +1,9 @@
<script setup lang="ts">
import { ActivityFeed, Button, Card, CardAction, CardContent, CardHeader, CardTitle, KpiTile, LineChart, StatGroup } from '@perfect-design/ui'
import type { ActivityEvent } from '@perfect-design/ui'
import { Button, Card, CardAction, CardContent, CardHeader, CardTitle, KpiTile, LineChart, StatGroup } from '@perfect-design/ui'
import { computed, onMounted, onUnmounted, watch } from 'vue'
import { useEntityLinks } from '@/composables/useEntityLinks'
import { deriveAttention } from '@/lib/attention'
import { eventKindVariant, kindLabel } from '@/lib/events-filter'
import { formatBucketLabel, formatCompactCount, formatCostDisplay } from '@/lib/format'
import { errorRateTier, fleetErrorRate } from '@/lib/kpi'
import { loadState } from '@/lib/load-state'
@@ -20,16 +18,14 @@ import { useNavStore } from '@/stores/nav'
import { useOverviewStore } from '@/stores/overview'
import HealthStrip from '@/widgets/HealthStrip.vue'
import NeedsAttention from '@/widgets/NeedsAttention.vue'
import RecentEvents from '@/widgets/RecentEvents.vue'
import StateView from '@/widgets/StateView.vue'
import type { ViewState } from '@/widgets/StateView.vue'
import WbTable from '@/widgets/WbTable.vue'
const EVENT_ROWS = 8
const EVENT_ROWS = 6
const MIN_SPARK_POINTS = 2
type FeedTone = NonNullable<ActivityEvent['tone']>
const EVENT_TONE: Record<string, FeedTone> = { rate_limit: 'warning', budget: 'warning', timeout: 'warning', capacity: 'warning', store_down: 'danger', upstream: 'danger', unpriced: 'info', paced: 'info' }
interface RankRow {
id: string
name: string
@@ -106,7 +102,7 @@ const userColumns = wbColumns<RankRow>([
])
const modelColumns = wbColumns<RankRow>([
{ key: 'name', header: 'Model', kind: 'text', sortable: false },
{ key: 'value', header: 'Spend', kind: 'number', sortable: false },
{ key: 'value', header: 'Requests', kind: 'number', sortable: false },
{ key: 'share', header: 'Share', kind: 'share', sortable: false },
])
@@ -119,39 +115,20 @@ const topUsers = computed<RankRow[]>(() => {
return rankTopUsers(data.topUserRows, 'req', TOP_USERS_RANK_LIMIT).map((r) => ({ id: r.id, name: r.id, value: r.value, share: share(r.value, total) }))
})
const topModels = computed<RankRow[]>(() => {
const total = sumPoints(data.totals.cost)
return data.topModelsByCost.filter((m) => m.value > 0).map((m) => ({ id: m.id, name: m.id, value: m.value, share: share(m.value, total) }))
const total = sumPoints(data.totals.req)
return data.topModels.filter((m) => m.value > 0).map((m) => ({ id: m.id, name: m.id, value: m.value, share: share(m.value, total) }))
})
const usersState = computed(() => sectionState(data.usersLoaded, data.error.users, topUsers.value.length === 0))
const modelsState = computed(() => sectionState(data.modelsLoaded, data.error.models, topModels.value.length === 0))
const modelsState = computed(() => sectionState(data.trafficLoaded, data.error.traffic, topModels.value.length === 0))
// --- Recent events ----------------------------------------------------------
const feed = computed<ActivityEvent[]>(() =>
events.events.slice(0, EVENT_ROWS).map((e, i) => ({
id: `${e.time}-${e.replica}-${i}`,
actor: e.user,
action: `${kindLabel(e.kind)}: ${e.message}`,
time: e.time,
tone: EVENT_TONE[e.kind] ?? (eventKindVariant(e.kind) === 'destructive' ? 'danger' : 'neutral'),
details: [e.provider, e.model, e.route].filter(Boolean).join(' · ') || e.route,
})),
)
const recent = computed(() => events.events.slice(0, EVENT_ROWS))
const eventsState = computed<ViewState>(() => {
const s = loadState({ loading: events.refreshing, hasData: events.lastUpdated !== null, error: events.error })
if (s === 'ready') return feed.value.length === 0 ? 'empty' : 'ready'
if (s === 'ready') return recent.value.length === 0 ? 'empty' : 'ready'
return s === 'skeleton' ? 'loading' : s === 'error' ? 'error' : 'empty'
})
const eventById = computed(() => new Map(feed.value.map((f, i) => [f.id, events.events[i]])))
function eventLinks(id: string | number): Array<{ label: string; open: () => void }> {
const e = eventById.value.get(String(id))
if (!e) return []
const out: Array<{ label: string; open: () => void }> = []
if (e.user) out.push({ label: `Open ${e.user}`, open: () => openEntity('user', e.user as string) })
if (e.provider) out.push({ label: `Open ${e.provider}`, open: () => openEntity('provider', e.provider as string) })
return out
}
// --- Lifecycle --------------------------------------------------------------
@@ -228,7 +205,7 @@ onUnmounted(() => {
:value="count(throttledTotal)"
:loading="events.lastUpdated === null && !events.error"
good-when="down"
:hint="`${throttled.rateLimited} rate limited · ${throttled.paced} paced`"
:hint="`${throttled.rateLimited} rate limited · ${throttled.paced} paced, recent events`"
/>
</StatGroup>
@@ -264,9 +241,9 @@ onUnmounted(() => {
<div class="grid grid-cols-1 items-start gap-4 lg:grid-cols-3">
<Card size="sm">
<CardHeader>
<CardHeader class="items-center">
<CardTitle>Top users</CardTitle>
<CardAction><Button variant="ghost" size="sm" @click="nav.goTo('users', {}, { replace: false })">View all</Button></CardAction>
<CardAction class="self-center"><Button variant="ghost" size="sm" @click="nav.goTo('users', {}, { replace: false })">View all</Button></CardAction>
</CardHeader>
<CardContent>
<StateView
@@ -277,6 +254,7 @@ onUnmounted(() => {
@retry="data.refresh()"
>
<WbTable
class="wb-hide-share-sm wb-clip"
:columns="userColumns"
:rows="topUsers"
row-key="id"
@@ -289,44 +267,38 @@ onUnmounted(() => {
</CardContent>
</Card>
<Card size="sm">
<CardHeader>
<CardHeader class="items-center">
<CardTitle>Top models</CardTitle>
<CardAction><Button variant="ghost" size="sm" @click="nav.goTo('models', {}, { replace: false })">View all</Button></CardAction>
<CardAction class="self-center"><Button variant="ghost" size="sm" @click="nav.goTo('models', {}, { replace: false })">View all</Button></CardAction>
</CardHeader>
<CardContent>
<StateView
:state="modelsState"
empty-title="No model spend in this range"
:error-message="data.error.models"
empty-title="No model traffic in this range"
:error-message="data.error.traffic"
@retry="data.refresh()"
>
<WbTable
class="wb-hide-share-sm wb-clip"
:columns="modelColumns"
:rows="topModels"
row-key="id"
label="Top models by spend"
label="Top models by requests"
@row-activate="(row: RankRow) => openEntity('model', row.id)"
>
<template #cell-value="{ value }">{{ formatCostDisplay(value as number) }}</template>
<template #cell-value="{ value }">{{ formatCompactCount(value as number) }}</template>
</WbTable>
</StateView>
</CardContent>
</Card>
<Card size="sm">
<CardHeader>
<CardHeader class="items-center">
<CardTitle>Recent events</CardTitle>
<CardAction><Button variant="ghost" size="sm" @click="nav.goTo('events', {}, { replace: false })">View all</Button></CardAction>
<CardAction class="self-center"><Button variant="ghost" size="sm" @click="nav.goTo('events', {}, { replace: false })">View all</Button></CardAction>
</CardHeader>
<CardContent>
<StateView :state="eventsState" empty-title="No events recorded" :error-message="events.error" @retry="events.refresh()">
<ActivityFeed :events="feed" label="Recent events" variant="compact" size="sm" density="compact">
<template #details="{ event }">
<p class="text-muted-foreground m-0 text-xs">{{ event.details }}</p>
<div class="flex flex-wrap gap-2 pt-1">
<Button v-for="l in eventLinks(event.id)" :key="l.label" variant="outline" size="sm" @click="l.open()">{{ l.label }}</Button>
</div>
</template>
</ActivityFeed>
<RecentEvents :events="recent" />
</StateView>
</CardContent>
</Card>
+2 -2
View File
@@ -39,10 +39,10 @@ describe('useOverviewStore.refresh', () => {
await s.refresh()
expect(s.totals.req).toEqual([1, 2])
expect(s.topModelSeries.map((m) => m.scope)).toEqual(['model:p/m1', 'model:p/m2'])
expect(s.topModelsByCost.map((m) => m.id)).toEqual(['p/m1', 'p/m2'])
expect(s.topModels.map((m) => m.id)).toEqual(['p/m1', 'p/m2'])
expect(s.topUserRows).toHaveLength(1)
expect(s.previous).toBeNull()
expect(s.error).toEqual({ traffic: '', models: '', users: '' })
expect(s.error).toEqual({ traffic: '', users: '' })
expect(s.lastUpdated).not.toBeNull()
})
+6 -19
View File
@@ -21,7 +21,7 @@ type TotalMetric = (typeof TOTAL_METRICS)[number]
type Points = Record<TotalMetric, number[]>
const emptyPoints = (): Points => ({ req: [], tokin: [], tokout: [], cost: [] })
const emptyError = () => ({ traffic: '', models: '', users: '' })
const emptyError = () => ({ traffic: '', users: '' })
export const RANGE_TOO_LARGE = 'Too many configured users to rank for this range. Pick a shorter range.'
@@ -31,10 +31,9 @@ export const useOverviewStore = defineStore('overview', {
totals: emptyPoints(),
previous: null as Pick<Points, 'req' | 'tokin' | 'cost'> | null,
topModelSeries: [] as Series[],
topModelsByCost: [] as AdminUsageModelsResponse['models'],
topModels: [] as AdminUsageModelsResponse['models'],
topUserRows: [] as AdminTotalsResponse['rows'],
trafficLoaded: false,
modelsLoaded: false,
usersLoaded: false,
error: emptyError(),
lastUpdated: null as Date | null,
@@ -52,7 +51,7 @@ export const useOverviewStore = defineStore('overview', {
const id = ++this.reqId
const { window, span } = filters
const offset = filters.cmpSpec.requested ? filters.cmpSpec.offset : 0
await Promise.all([this.loadTraffic(id, window, span, offset), this.loadModels(id, window, span), this.loadUsers(id, window, span)])
await Promise.all([this.loadTraffic(id, window, span, offset), this.loadUsers(id, window, span)])
if (id === this.reqId) this.lastUpdated = new Date()
},
clearData(): void {
@@ -60,9 +59,9 @@ export const useOverviewStore = defineStore('overview', {
this.totals = emptyPoints()
this.previous = null
this.topModelSeries = []
this.topModelsByCost = []
this.topModels = []
this.topUserRows = []
this.trafficLoaded = this.modelsLoaded = this.usersLoaded = false
this.trafficLoaded = this.usersLoaded = false
this.error = emptyError()
},
async series(scope: string[], metric: HistoryMetric, window: HistoryWindow, span: number, offset: number): Promise<AdminSeriesResponse> {
@@ -85,6 +84,7 @@ export const useOverviewStore = defineStore('overview', {
this.buckets = current[0]?.buckets ?? []
this.totals = { req: current[0]!.points, tokin: current[1]!.points, tokout: current[2]!.points, cost: current[3]!.points }
this.previous = prior ? { req: prior[0]!.points, tokin: prior[1]!.points, cost: prior[2]!.points } : null
this.topModels = ranking.models
this.topModelSeries = top
this.trafficLoaded = true
this.error.traffic = ''
@@ -92,19 +92,6 @@ export const useOverviewStore = defineStore('overview', {
if (id === this.reqId && !isAuthRejection(err)) this.error.traffic = messageOf(err)
}
},
async loadModels(id: number, window: HistoryWindow, span: number): Promise<void> {
try {
const res = await adminFetch<AdminUsageModelsResponse>(
`/admin/api/usage/models?metric=cost&window=${window}&span=${span}&limit=${TOP_N}`,
)
if (id !== this.reqId) return
this.topModelsByCost = res.models
this.modelsLoaded = true
this.error.models = ''
} catch (err) {
if (id === this.reqId && !isAuthRejection(err)) this.error.models = messageOf(err)
}
},
async loadUsers(id: number, window: HistoryWindow, span: number): Promise<void> {
const configured = useDashboardStore().usage?.users.length ?? null
if (topUsersCapCheckResult(configured, TOP_USERS_METRICS_BY_MODE.req.length, span)) {
+8 -15
View File
@@ -2,8 +2,8 @@
import { StatusDot } from '@perfect-design/ui'
import { computed } from 'vue'
import { useEntityLinks } from '@/composables/useEntityLinks'
import { openBreakerCount } from '@/lib/kpi'
import { useNavStore } from '@/stores/nav'
import type { AdminProviderView, AdminRedisView } from '@/types/api'
type ChipTone = 'success' | 'warning' | 'danger' | 'neutral'
@@ -12,13 +12,11 @@ interface Chip {
tone: ChipTone
text: string
title?: string
provider?: string
link?: boolean
}
const MAX_FAILING_CHIPS = 3
const props = defineProps<{ providers: AdminProviderView[]; redis: AdminRedisView; eventsSource: 'redis' | 'replica' | null }>()
const { openEntity } = useEntityLinks()
const nav = useNavStore()
const failing = computed(() => props.providers.filter((p) => p.healthState !== 'closed' || !!p.lastErr))
const healthy = computed(() => props.providers.length - failing.value.length)
@@ -29,12 +27,7 @@ const chips = computed<Chip[]>(() => {
const out: Chip[] = []
const providerTone: ChipTone = total === 0 ? 'neutral' : healthy.value === total ? 'success' : healthy.value === 0 ? 'danger' : 'warning'
out.push({ key: 'providers', tone: providerTone, text: total === 0 ? 'No providers' : `${healthy.value} of ${total} providers healthy` })
for (const p of failing.value.slice(0, MAX_FAILING_CHIPS)) {
const reason = p.lastErr || 'breaker open'
out.push({ key: `fail-${p.name}`, tone: 'danger', text: `${p.name}: ${reason}`, title: `${p.name}: ${reason}`, provider: p.name })
}
const more = failing.value.length - MAX_FAILING_CHIPS
if (more > 0) out.push({ key: 'more', tone: 'danger', text: `+${more} more failing` })
if (failing.value.length > 0) out.push({ key: 'failing', tone: 'danger', text: `${failing.value.length} failing`, link: true })
if (!props.redis.configured) out.push({ key: 'redis', tone: 'neutral', text: 'Redis not configured' })
else if (props.eventsSource === null) out.push({ key: 'redis', tone: 'neutral', text: 'Redis checking' })
else if (props.eventsSource === 'redis') out.push({ key: 'redis', tone: 'success', text: 'Redis connected' })
@@ -52,12 +45,12 @@ const chips = computed<Chip[]>(() => {
<ul class="m-0 flex list-none flex-wrap gap-2 p-0" aria-label="Fleet health">
<li v-for="chip in chips" :key="chip.key" class="min-w-0 max-w-full">
<component
:is="chip.provider ? 'button' : 'span'"
:is="chip.link ? 'button' : 'span'"
class="border-border bg-card text-foreground inline-flex h-8 max-w-full sm:max-w-md items-center gap-2 rounded-md border px-3 text-sm"
:class="chip.provider ? 'hover:bg-accent cursor-pointer' : ''"
:class="chip.link ? 'hover:bg-accent cursor-pointer' : ''"
:title="chip.title"
:type="chip.provider ? 'button' : undefined"
@click="chip.provider && openEntity('provider', chip.provider)"
:type="chip.link ? 'button' : undefined"
@click="chip.link && nav.goTo('reliability', {}, { replace: false })"
>
<StatusDot :tone="chip.tone" size="md" />
<span class="truncate">{{ chip.text }}</span>
+1 -1
View File
@@ -24,7 +24,7 @@ const { openLink } = useEntityLinks()
@click="openLink(item.link)"
>
<StatusDot class="mt-1.5 shrink-0" :tone="TONE[item.severity]" size="md" />
<span class="min-w-0 break-words">{{ item.text }}</span>
<span class="line-clamp-2 min-w-0 break-words" :title="item.text">{{ item.text }}</span>
</button>
</li>
</ul>
+48
View File
@@ -0,0 +1,48 @@
<script setup lang="ts">
import { StatusDot } from '@perfect-design/ui'
import { useEntityLinks } from '@/composables/useEntityLinks'
import { kindLabel } from '@/lib/events-filter'
import { useNavStore } from '@/stores/nav'
import type { AdminEventView } from '@/types/api'
type Tone = 'danger' | 'warning' | 'info' | 'neutral'
const TONE: Record<string, Tone> = { rate_limit: 'warning', budget: 'warning', timeout: 'warning', capacity: 'warning', store_down: 'danger', upstream: 'danger', unpriced: 'info', paced: 'info' }
defineProps<{ events: AdminEventView[] }>()
const nav = useNavStore()
const { openEntity } = useEntityLinks()
function subject(e: AdminEventView): string {
return e.user || e.provider || e.model || e.route || e.message
}
function clock(iso: string): string {
const d = new Date(iso)
return Number.isNaN(d.getTime()) ? '' : d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
}
function open(e: AdminEventView): void {
if (e.user) openEntity('user', e.user)
else if (e.provider) openEntity('provider', e.provider)
else nav.goTo('events', {}, { replace: false })
}
</script>
<template>
<ul class="m-0 flex list-none flex-col p-0" aria-label="Recent events">
<li v-for="(e, i) in events" :key="`${e.time}-${e.replica}-${i}`">
<button
type="button"
class="hover:bg-accent flex h-8 w-full items-center gap-2 rounded-md px-2 text-left text-sm"
:title="`${kindLabel(e.kind)}: ${e.message}`"
@click="open(e)"
>
<StatusDot class="shrink-0" :tone="TONE[e.kind] ?? 'neutral'" size="md" />
<span class="text-muted-foreground shrink-0 font-mono text-xs">{{ clock(e.time) }}</span>
<span class="text-muted-foreground shrink-0">{{ kindLabel(e.kind) }}</span>
<span class="min-w-0 flex-1 truncate">{{ subject(e) }}</span>
</button>
</li>
</ul>
</template>