diff --git a/webui/src/App.vue b/webui/src/App.vue index 305300d..e1642cf 100644 --- a/webui/src/App.vue +++ b/webui/src/App.vue @@ -44,7 +44,7 @@ function lazyPage(loader: () => Promise): Component { // Legacy pages stand in until their redesigned replacements land: routers // still lives inside the Models page and events inside Reliability. const PAGES: Record = { - overview: lazyPage(() => import('@/pages/HomePage.vue')), + overview: lazyPage(() => import('@/pages/OverviewPage.vue')), usage: lazyPage(() => import('@/pages/SpendPage.vue')), reliability: lazyPage(() => import('@/pages/ReliabilityPage.vue')), users: lazyPage(() => import('@/pages/ConsumersPage.vue')), diff --git a/webui/src/composables/useEntityLinks.ts b/webui/src/composables/useEntityLinks.ts new file mode 100644 index 0000000..7ef73f3 --- /dev/null +++ b/webui/src/composables/useEntityLinks.ts @@ -0,0 +1,26 @@ +import type { AttentionLink } from '@/lib/attention' +import { PANEL_PAGE, parseSel } from '@/lib/panel-selection' +import type { PanelKind } from '@/lib/panel-selection' +import { useNavStore } from '@/stores/nav' + +/** Navigation helpers for rows that link to a directory page or one of its detail panels. */ +export function useEntityLinks() { + const nav = useNavStore() + + function openEntity(kind: PanelKind, id: string): void { + nav.goTo(PANEL_PAGE[kind]) + nav.openPanel(kind, id) + } + + function openLink(link: AttentionLink): void { + const sel = parseSel(link.sel) + if (!sel) { + nav.goTo(link.page, {}, { replace: false }) + return + } + nav.goTo(link.page) + nav.openPanel(sel.kind, sel.id) + } + + return { openEntity, openLink } +} diff --git a/webui/src/lib/attention.spec.ts b/webui/src/lib/attention.spec.ts new file mode 100644 index 0000000..fbb6969 --- /dev/null +++ b/webui/src/lib/attention.spec.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from 'vitest' + +import { deriveAttention } from './attention' +import type { AttentionEvents, AttentionOverview, AttentionRouter, AttentionUsage } from './attention' +import { formatSel } from './panel-selection' + +const provider = (over: Partial = {}) => ({ name: 'uni', healthState: 'closed' as const, ...over }) +const overview = (over: Partial = {}): AttentionOverview => ({ + providers: [provider()], + pricing: { unpriced: 0 }, + redis: { configured: true }, + ...over, +}) +const usage: AttentionUsage = { users: [{ id: 'alice' }, { id: 'bob' }] } +const events = (over: Partial = {}): AttentionEvents => ({ source: 'redis', events: [], ...over }) +const router = (over: Partial = {}): AttentionRouter => ({ name: 'auto', stats: { escalations: [] }, ...over }) + +describe('deriveAttention', () => { + it('returns nothing when nothing is wrong', () => { + expect(deriveAttention(overview(), usage, events(), [router()])).toEqual([]) + }) + + it('returns nothing before data loads', () => { + expect(deriveAttention(null, null, null, [])).toEqual([]) + }) + + it('flags an open breaker as danger linking to the provider', () => { + const items = deriveAttention(overview({ providers: [provider({ healthState: 'open' })] }), usage, events(), []) + expect(items).toHaveLength(1) + expect(items[0]).toMatchObject({ severity: 'danger', link: { page: 'models', sel: formatSel('provider', 'uni') } }) + expect(items[0]?.text).toContain('uni') + }) + + it('flags a provider lastErr as danger with the provider sel and the reason', () => { + const items = deriveAttention(overview({ providers: [provider({ lastErr: 'HTTP 401 unauthorized' })] }), usage, events(), []) + expect(items).toHaveLength(1) + expect(items[0]).toMatchObject({ severity: 'danger', link: { page: 'models', sel: formatSel('provider', 'uni') } }) + expect(items[0]?.text).toContain('HTTP 401 unauthorized') + }) + + it('merges breaker and lastErr of one provider into a single item', () => { + const items = deriveAttention(overview({ providers: [provider({ healthState: 'open', lastErr: 'boom' })] }), usage, events(), []) + expect(items).toHaveLength(1) + expect(items[0]?.text).toContain('boom') + }) + + it('groups rate_limit events per user as a warning with the user sel', () => { + const ev = events({ + events: [ + { kind: 'rate_limit', user: 'alice' }, + { kind: 'rate_limit', user: 'alice' }, + { kind: 'rate_limit', user: 'bob' }, + { kind: 'upstream', user: 'bob' }, + ], + }) + const items = deriveAttention(overview(), usage, ev, []) + expect(items.map((i) => i.link.sel)).toEqual([formatSel('user', 'alice'), formatSel('user', 'bob')]) + expect(items[0]).toMatchObject({ severity: 'warning', link: { page: 'users' } }) + expect(items[0]?.text).toContain('2') + }) + + it('links a throttled user that no longer exists to the directory without a sel', () => { + const items = deriveAttention(overview(), usage, events({ events: [{ kind: 'rate_limit', user: 'ghost' }] }), []) + expect(items[0]?.link).toEqual({ page: 'users' }) + }) + + it('flags unpriced models as info linking to usage', () => { + const items = deriveAttention(overview({ pricing: { unpriced: 3 } }), usage, events(), []) + expect(items).toEqual([{ severity: 'info', text: expect.stringContaining('3'), link: { page: 'usage' } }]) + }) + + it('flags a configured redis that is not the event source as danger', () => { + const items = deriveAttention(overview(), usage, events({ source: 'replica' }), []) + expect(items).toHaveLength(1) + expect(items[0]).toMatchObject({ severity: 'danger', link: { page: 'config' } }) + expect(items[0]?.text).toMatch(/redis/i) + }) + + it('does not flag replica events when redis is not configured', () => { + expect(deriveAttention(overview({ redis: { configured: false } }), usage, events({ source: 'replica' }), [])).toEqual([]) + }) + + it('flags router escalations as info linking to the router', () => { + const r = router({ stats: { escalations: [{ count: 4 }, { count: 1 }] } }) + const items = deriveAttention(overview(), usage, events(), [r]) + expect(items).toHaveLength(1) + expect(items[0]).toMatchObject({ severity: 'info', link: { page: 'routers', sel: formatSel('router', 'auto') } }) + expect(items[0]?.text).toContain('5') + }) + + it('orders danger before warning before info', () => { + const items = deriveAttention( + overview({ pricing: { unpriced: 1 }, providers: [provider({ healthState: 'open' })] }), + usage, + events({ events: [{ kind: 'rate_limit', user: 'alice' }] }), + [], + ) + expect(items.map((i) => i.severity)).toEqual(['danger', 'warning', 'info']) + }) +}) diff --git a/webui/src/lib/attention.ts b/webui/src/lib/attention.ts new file mode 100644 index 0000000..1a88e8d --- /dev/null +++ b/webui/src/lib/attention.ts @@ -0,0 +1,98 @@ +import type { PageId } from '@/lib/pages' +import { formatSel, PANEL_PAGE } from '@/lib/panel-selection' +import type { PanelKind } from '@/lib/panel-selection' + +export type AttentionSeverity = 'danger' | 'warning' | 'info' + +export interface AttentionLink { + page: PageId + sel?: string +} + +export interface AttentionItem { + severity: AttentionSeverity + text: string + link: AttentionLink +} + +export interface AttentionOverview { + providers: Array<{ name: string; healthState: string; lastErr?: string }> + pricing: { unpriced: number } + redis: { configured: boolean; lastErr?: string } +} +export interface AttentionUsage { + users: Array<{ id: string }> +} +export interface AttentionEvents { + source: string + events: Array<{ kind: string; user?: string }> +} +export interface AttentionRouter { + name: string + stats?: { escalations: Array<{ count: number }> } +} + +const SEVERITY_ORDER: Record = { danger: 0, warning: 1, info: 2 } + +function panelLink(kind: PanelKind, id: string): AttentionLink { + return { page: PANEL_PAGE[kind], sel: formatSel(kind, id) } +} + +function providerItems(overview: AttentionOverview): AttentionItem[] { + const out: AttentionItem[] = [] + for (const p of overview.providers) { + const open = p.healthState === 'open' + if (!open && !p.lastErr) continue + const text = open ? `${p.name} breaker open${p.lastErr ? `: ${p.lastErr}` : ''}` : `${p.name} failing: ${p.lastErr}` + out.push({ severity: 'danger', text, link: panelLink('provider', p.name) }) + } + return out +} + +function throttledUserItems(usage: AttentionUsage | null, events: AttentionEvents): AttentionItem[] { + const counts = new Map() + for (const e of events.events) { + if (e.kind === 'rate_limit' && e.user) counts.set(e.user, (counts.get(e.user) ?? 0) + 1) + } + const known = new Set((usage?.users ?? []).map((u) => u.id)) + return [...counts.entries()] + .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) + .map(([user, n]) => ({ + severity: 'warning' as const, + text: `${user} rate limited ${n} time${n === 1 ? '' : 's'}`, + link: known.has(user) ? panelLink('user', user) : { page: 'users' as const }, + })) +} + +function routerItems(routers: AttentionRouter[]): AttentionItem[] { + const out: AttentionItem[] = [] + for (const r of routers) { + const n = (r.stats?.escalations ?? []).reduce((sum, e) => sum + e.count, 0) + if (n > 0) out.push({ severity: 'info', text: `${r.name} escalated ${n} request${n === 1 ? '' : 's'} to a higher tier`, link: panelLink('router', r.name) }) + } + return out +} + +/** Lists what an operator should look at first, most severe first; empty when the fleet is healthy. */ +export function deriveAttention( + overview: AttentionOverview | null, + usage: AttentionUsage | null, + events: AttentionEvents | null, + routers: AttentionRouter[], +): AttentionItem[] { + const items: AttentionItem[] = [] + if (overview) { + items.push(...providerItems(overview)) + if (overview.redis.configured && events && events.source !== 'redis') { + const why = overview.redis.lastErr ? `: ${overview.redis.lastErr}` : '' + items.push({ severity: 'danger', text: `Redis unreachable, events served from this replica only${why}`, link: { page: 'config' } }) + } + if (overview.pricing.unpriced > 0) { + const n = overview.pricing.unpriced + items.push({ severity: 'info', text: `${n} unpriced model${n === 1 ? '' : 's'}, spend is understated`, link: { page: 'usage' } }) + } + } + if (events) items.push(...throttledUserItems(usage, events)) + items.push(...routerItems(routers)) + return items.sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]) +} diff --git a/webui/src/lib/overview-metrics.spec.ts b/webui/src/lib/overview-metrics.spec.ts new file mode 100644 index 0000000..a142eab --- /dev/null +++ b/webui/src/lib/overview-metrics.spec.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest' + +import { countThrottled, deltaOf, rangeMs, sumPoints, trafficSeries } from './overview-metrics' + +describe('sumPoints', () => { + it('sums and ignores non-finite values', () => { + expect(sumPoints([1, 2, 3])).toBe(6) + expect(sumPoints([1, Number.NaN, 2])).toBe(3) + expect(sumPoints([])).toBe(0) + }) +}) + +describe('deltaOf', () => { + it('is null without a previous value to compare against', () => { + expect(deltaOf(10, 0)).toBeNull() + expect(deltaOf(10, null)).toBeNull() + }) + it('formats a signed whole percent with its trend', () => { + expect(deltaOf(112, 100)).toEqual({ text: '+12%', trend: 'up' }) + expect(deltaOf(50, 100)).toEqual({ text: '-50%', trend: 'down' }) + }) + it('reads under half a percent as flat', () => { + expect(deltaOf(100.2, 100)).toEqual({ text: '0%', trend: 'flat' }) + }) + it('caps absurd swings so the tile never overflows', () => { + expect(deltaOf(100000, 1)?.text).toBe('+999%') + }) +}) + +describe('rangeMs', () => { + it('converts each window to milliseconds', () => { + expect(rangeMs('hour', 24)).toBe(24 * 3_600_000) + expect(rangeMs('day', 7)).toBe(7 * 86_400_000) + expect(rangeMs('month', 3)).toBe(3 * 30 * 86_400_000) + }) +}) + +describe('countThrottled', () => { + const now = Date.parse('2026-11-25T12:00:00Z') + const at = (minsAgo: number) => new Date(now - minsAgo * 60_000).toISOString() + it('counts rate_limit and paced events inside the range only', () => { + const events = [ + { kind: 'rate_limit', time: at(5) }, + { kind: 'rate_limit', time: at(10) }, + { kind: 'paced', time: at(20) }, + { kind: 'rate_limit', time: at(500) }, + { kind: 'upstream', time: at(1) }, + ] + expect(countThrottled(events, now, 60 * 60_000)).toEqual({ rateLimited: 2, paced: 1 }) + }) + it('skips events with an unparseable time', () => { + expect(countThrottled([{ kind: 'rate_limit', time: 'nope' }], now, 60_000)).toEqual({ rateLimited: 0, paced: 0 }) + }) +}) + +describe('trafficSeries', () => { + const top = [ + { scope: 'model:a/x', points: [1, 2] }, + { scope: 'model:b/y', points: [3, 4] }, + ] + it('stacks the top models, then the remainder as Other', () => { + const s = trafficSeries(top, [10, 10], null) + expect(s.map((x) => x.name)).toEqual(['a/x', 'b/y', 'Other']) + expect(s[2]?.data).toEqual([6, 4]) + expect(s.every((x) => x.stack === undefined)).toBe(true) + }) + it('omits Other when the top models cover all traffic', () => { + expect(trafficSeries(top, [4, 6], null).map((x) => x.name)).toEqual(['a/x', 'b/y']) + }) + it('adds the previous period as an unstacked series when compare is on', () => { + const s = trafficSeries(top, [10, 10], [7, 8]) + expect(s.at(-1)).toMatchObject({ name: 'Previous period', data: [7, 8], stack: false }) + }) + it('is empty without any traffic', () => { + expect(trafficSeries([], [0, 0], null)).toEqual([]) + }) +}) diff --git a/webui/src/lib/overview-metrics.ts b/webui/src/lib/overview-metrics.ts new file mode 100644 index 0000000..b2a103a --- /dev/null +++ b/webui/src/lib/overview-metrics.ts @@ -0,0 +1,72 @@ +import { scopeId } from '@/lib/scope' +import { other } from '@/lib/series' +import type { Series } from '@/lib/series' +import type { HistoryWindow } from '@/types/api' + +export type Trend = 'up' | 'down' | 'flat' + +export interface Delta { + text: string + trend: Trend +} + +export interface ChartLine { + name: string + data: number[] + tone?: 'muted' | 'primary' + stack?: false +} + +const MS_PER_HOUR = 3_600_000 +const MS_PER_DAY = 24 * MS_PER_HOUR +const DAYS_PER_MONTH = 30 +const FLAT_BELOW_PCT = 0.5 +const DELTA_CAP_PCT = 999 + +export function sumPoints(points: readonly number[]): number { + let total = 0 + for (const p of points) if (Number.isFinite(p)) total += p + return total +} + +/** Signed whole-percent change against the previous period; null when there is nothing to compare. */ +export function deltaOf(current: number, previous: number | null): Delta | null { + if (previous === null || !(previous > 0) || !Number.isFinite(current)) return null + const pct = ((current - previous) / previous) * 100 + if (Math.abs(pct) < FLAT_BELOW_PCT) return { text: '0%', trend: 'flat' } + const capped = Math.min(DELTA_CAP_PCT, Math.max(-DELTA_CAP_PCT, Math.round(pct))) + return { text: `${capped > 0 ? '+' : ''}${capped}%`, trend: capped > 0 ? 'up' : 'down' } +} + +export function rangeMs(window: HistoryWindow, span: number): number { + if (window === 'hour') return span * MS_PER_HOUR + if (window === 'day') return span * MS_PER_DAY + return span * DAYS_PER_MONTH * MS_PER_DAY +} + +/** Counts rate_limit and paced events whose time falls inside the last `windowMs`. */ +export function countThrottled( + events: ReadonlyArray<{ kind: string; time: string }>, + now: number, + windowMs: number, +): { rateLimited: number; paced: number } { + let rateLimited = 0 + let paced = 0 + for (const e of events) { + const at = Date.parse(e.time) + if (!Number.isFinite(at) || at < now - windowMs) continue + if (e.kind === 'rate_limit') rateLimited++ + else if (e.kind === 'paced') paced++ + } + return { rateLimited, paced } +} + +/** Stacked traffic lines: the top models, the remainder as Other, and optionally the previous period as a plain line. */ +export function trafficSeries(top: Series[], totalPoints: number[], previous: number[] | null): ChartLine[] { + const lines: ChartLine[] = top.map((s) => ({ name: scopeId(s.scope), data: s.points })) + const rest = other(totalPoints, top) + if (rest.some((v) => v > 0)) lines.push({ name: 'Other', data: rest, tone: 'muted' }) + if (lines.length === 0) return [] + if (previous) lines.push({ name: 'Previous period', data: previous, tone: 'primary', stack: false }) + return lines +} diff --git a/webui/src/pages/OverviewPage.vue b/webui/src/pages/OverviewPage.vue new file mode 100644 index 0000000..fc597dd --- /dev/null +++ b/webui/src/pages/OverviewPage.vue @@ -0,0 +1,336 @@ + + + diff --git a/webui/src/stores/overview.spec.ts b/webui/src/stores/overview.spec.ts new file mode 100644 index 0000000..d99bace --- /dev/null +++ b/webui/src/stores/overview.spec.ts @@ -0,0 +1,81 @@ +import { createPinia, setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/api', async () => { + const actual = await vi.importActual('@/lib/api') + return { ...actual, adminFetch: vi.fn() } +}) + +import { adminFetch } from '@/lib/api' +import { useAuthStore } from '@/stores/auth' +import { useFiltersStore } from '@/stores/filters' +import { useOverviewStore } from '@/stores/overview' + +const mocked = vi.mocked(adminFetch) + +function route(url: string): unknown { + const u = new URL(url, 'http://x') + const q = u.searchParams + if (u.pathname.endsWith('/usage/series')) { + const scopes = q.getAll('scope') + const off = q.get('offset') ? 100 : 0 + return { metric: q.get('metric'), buckets: ['a', 'b'], series: scopes.map((scope) => ({ scope, points: [1 + off, 2 + off] })), unknown: [] } + } + if (u.pathname.endsWith('/usage/models')) return { models: [{ id: 'p/m1', value: 5 }, { id: 'p/m2', value: 3 }] } + if (u.pathname.endsWith('/usage/totals')) return { rows: [{ id: 'alice', values: { req: 9 } }] } + throw new Error(`unexpected ${url}`) +} + +describe('useOverviewStore.refresh', () => { + beforeEach(() => { + setActivePinia(createPinia()) + mocked.mockReset() + mocked.mockImplementation(async (url: string) => route(url) as never) + useAuthStore().submit('test-admin-key') + }) + + it('loads totals, top models and top users for the range', async () => { + const s = useOverviewStore() + 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.topUserRows).toHaveLength(1) + expect(s.previous).toBeNull() + expect(s.error).toEqual({ traffic: '', models: '', users: '' }) + expect(s.lastUpdated).not.toBeNull() + }) + + it('fetches the previous period only when compare is requested', async () => { + useFiltersStore().cmp = 'prev' + const s = useOverviewStore() + await s.refresh() + expect(s.previous?.req).toEqual([101, 102]) + expect(mocked.mock.calls.some(([u]) => String(u).includes('offset='))).toBe(true) + }) + + it('keeps the last good data and records the error when a group fails', async () => { + const s = useOverviewStore() + await s.refresh() + mocked.mockImplementation(async (url: string) => { + if (url.includes('/usage/totals')) throw new Error('503') + return route(url) as never + }) + await s.refresh() + expect(s.error.users).toContain('503') + expect(s.topUserRows).toHaveLength(1) + expect(s.totals.req).toEqual([1, 2]) + }) + + it('drops the old selection when the range changes', async () => { + const s = useOverviewStore() + await s.refresh() + mocked.mockImplementation(async () => { + throw new Error('503') + }) + useFiltersStore().range = '24h' + await s.refresh() + expect(s.totals.req).toEqual([]) + expect(s.error.traffic).toContain('503') + }) +}) diff --git a/webui/src/stores/overview.ts b/webui/src/stores/overview.ts new file mode 100644 index 0000000..c8aadef --- /dev/null +++ b/webui/src/stores/overview.ts @@ -0,0 +1,136 @@ +import { defineStore } from 'pinia' + +import { adminFetch, isAuthRejection, messageOf } from '@/lib/api' +import { createVisibilityPoller } from '@/lib/polling' +import type { VisibilityPoller } from '@/lib/polling' +import { seriesUrl } from '@/lib/range' +import { TOP_USERS_METRICS_BY_MODE, topUsersCapCheckResult, topUsersTotalsUrl } from '@/lib/top-users' +import type { Series } from '@/lib/series' +import { useAuthStore } from '@/stores/auth' +import { useDashboardStore } from '@/stores/dashboard' +import { useFiltersStore } from '@/stores/filters' +import type { AdminSeriesResponse, AdminTotalsResponse, AdminUsageModelsResponse, HistoryMetric, HistoryWindow } from '@/types/api' + +const REFRESH_MS = 60_000 +const TOP_N = 5 +const TOTAL_SCOPE = 'total' +const TOTAL_METRICS = ['req', 'tokin', 'tokout', 'cost'] as const +const COMPARED_METRICS = ['req', 'tokin', 'cost'] as const + +type TotalMetric = (typeof TOTAL_METRICS)[number] +type Points = Record + +const emptyPoints = (): Points => ({ req: [], tokin: [], tokout: [], cost: [] }) +const emptyError = () => ({ traffic: '', models: '', users: '' }) + +export const RANGE_TOO_LARGE = 'Too many configured users to rank for this range. Pick a shorter range.' + +export const useOverviewStore = defineStore('overview', { + state: () => ({ + buckets: [] as string[], + totals: emptyPoints(), + previous: null as Pick | null, + topModelSeries: [] as Series[], + topModelsByCost: [] as AdminUsageModelsResponse['models'], + topUserRows: [] as AdminTotalsResponse['rows'], + trafficLoaded: false, + modelsLoaded: false, + usersLoaded: false, + error: emptyError(), + lastUpdated: null as Date | null, + fetchedFor: '', + reqId: 0, + poller: undefined as VisibilityPoller | undefined, + }), + actions: { + async refresh(): Promise { + if (!useAuthStore().isAuthenticated) return + const filters = useFiltersStore() + const key = `${filters.window}:${filters.span}:${filters.cmpSpec.requested}` + if (key !== this.fetchedFor) this.clearData() + this.fetchedFor = key + 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)]) + if (id === this.reqId) this.lastUpdated = new Date() + }, + clearData(): void { + this.buckets = [] + this.totals = emptyPoints() + this.previous = null + this.topModelSeries = [] + this.topModelsByCost = [] + this.topUserRows = [] + this.trafficLoaded = this.modelsLoaded = this.usersLoaded = false + this.error = emptyError() + }, + async series(scope: string[], metric: HistoryMetric, window: HistoryWindow, span: number, offset: number): Promise { + return adminFetch(seriesUrl({ scope, metric, window, span, offset: offset || undefined })) + }, + async loadTraffic(id: number, window: HistoryWindow, span: number, offset: number): Promise { + try { + const totalOf = async (metric: HistoryMetric, off: number) => { + const res = await this.series([TOTAL_SCOPE], metric, window, span, off) + return { buckets: res.buckets, points: res.series.find((s) => s.scope === TOTAL_SCOPE)?.points ?? [] } + } + const current = await Promise.all(TOTAL_METRICS.map((m) => totalOf(m, 0))) + const prior = offset > 0 ? await Promise.all(COMPARED_METRICS.map((m) => totalOf(m, offset))) : null + const ranking = await adminFetch( + `/admin/api/usage/models?metric=req&window=${window}&span=${span}&limit=${TOP_N}`, + ) + const scopes = ranking.models.map((m) => `model:${m.id}`) + const top = scopes.length > 0 ? (await this.series(scopes, 'req', window, span, 0)).series : [] + if (id !== this.reqId) return + 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.topModelSeries = top + this.trafficLoaded = true + this.error.traffic = '' + } catch (err) { + if (id === this.reqId && !isAuthRejection(err)) this.error.traffic = messageOf(err) + } + }, + async loadModels(id: number, window: HistoryWindow, span: number): Promise { + try { + const res = await adminFetch( + `/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 { + const configured = useDashboardStore().usage?.users.length ?? null + if (topUsersCapCheckResult(configured, TOP_USERS_METRICS_BY_MODE.req.length, span)) { + this.topUserRows = [] + this.usersLoaded = false + this.error.users = RANGE_TOO_LARGE + return + } + try { + const res = await adminFetch(topUsersTotalsUrl(window, span, 'req')) + if (id !== this.reqId) return + this.topUserRows = res.rows + this.usersLoaded = true + this.error.users = '' + } catch (err) { + if (id === this.reqId && !isAuthRejection(err)) this.error.users = messageOf(err) + } + }, + startPolling(): void { + if (this.poller) return + this.poller = createVisibilityPoller({ intervalMs: REFRESH_MS, tick: () => this.refresh() }) + this.poller.start() + }, + stopPolling(): void { + this.poller?.stop() + this.poller = undefined + }, + }, +}) diff --git a/webui/src/stores/session.ts b/webui/src/stores/session.ts index 8077940..9e18766 100644 --- a/webui/src/stores/session.ts +++ b/webui/src/stores/session.ts @@ -4,6 +4,7 @@ import { useConsumersStore } from '@/stores/consumers' import { useDashboardStore } from '@/stores/dashboard' import { useEventsStore } from '@/stores/events' import { useModelsStore } from '@/stores/models' +import { useOverviewStore } from '@/stores/overview' import { useReliabilityStore } from '@/stores/reliability' import { useSpendStore } from '@/stores/spend' @@ -16,6 +17,7 @@ export function resetSessionData(): void { useDashboardStore(), useEventsStore(), useModelsStore(), + useOverviewStore(), useReliabilityStore(), useSpendStore(), ]) { diff --git a/webui/src/widgets/HealthStrip.vue b/webui/src/widgets/HealthStrip.vue new file mode 100644 index 0000000..75f9049 --- /dev/null +++ b/webui/src/widgets/HealthStrip.vue @@ -0,0 +1,67 @@ + + + diff --git a/webui/src/widgets/NeedsAttention.vue b/webui/src/widgets/NeedsAttention.vue new file mode 100644 index 0000000..61e9b6d --- /dev/null +++ b/webui/src/widgets/NeedsAttention.vue @@ -0,0 +1,31 @@ + + +