feat(webui): targets and events pages

This commit is contained in:
2026-11-25 11:52:37 +00:00
parent ec9df6a92d
commit 55f1e743fe
14 changed files with 762 additions and 99 deletions
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { eventLink } from './event-link'
import type { AdminEventView } from '@/types/api'
function event(overrides: Partial<AdminEventView> = {}): AdminEventView {
return { time: '2026-11-25T12:00:00Z', replica: 'pod-a', route: 'chat/completions', kind: 'rate_limit', message: 'limit exceeded', ...overrides }
}
describe('eventLink', () => {
it('rate_limit links to user panel', () => {
expect(eventLink(event({ kind: 'rate_limit', user: '[email protected]' }))).toEqual({ page: 'users', sel: 'user:alice%40example.com' })
})
it('upstream links to provider panel', () => {
expect(eventLink(event({ kind: 'upstream', provider: 'alibaba' }))).toEqual({ page: 'models', sel: 'provider:alibaba' })
})
it('unknown kind → null', () => {
expect(eventLink(event({ kind: 'from_the_future', user: 'alice' }))).toBeNull()
})
it('prefers the user over the provider', () => {
expect(eventLink(event({ kind: 'upstream', user: 'alice', provider: 'alibaba' }))).toEqual({ page: 'users', sel: 'user:alice' })
})
it('falls back to the group panel for a group-scoped event', () => {
expect(eventLink(event({ kind: 'budget', group: 'friends' }))).toEqual({ page: 'users', sel: 'group:friends' })
})
it('links a known kind without an entity to the events page', () => {
expect(eventLink(event({ kind: 'store_down' }))).toEqual({ page: 'events' })
})
it('links router_escalation to its provider panel', () => {
expect(eventLink(event({ kind: 'router_escalation', provider: 'gx10' }))).toEqual({ page: 'models', sel: 'provider:gx10' })
})
})
+18
View File
@@ -0,0 +1,18 @@
import type { AttentionLink } from '@/lib/attention'
import { EVENT_KINDS } from '@/lib/events-filter'
import { formatSel, PANEL_PAGE } from '@/lib/panel-selection'
import type { PanelKind } from '@/lib/panel-selection'
import type { AdminEventView } from '@/types/api'
function panelLink(kind: PanelKind, id: string): AttentionLink {
return { page: PANEL_PAGE[kind], sel: formatSel(kind, id) }
}
/** Where an event row leads: the user, group or provider it names, else the events page; null for a kind this build does not know. */
export function eventLink(event: AdminEventView): AttentionLink | null {
if (!(EVENT_KINDS as readonly string[]).includes(event.kind)) return null
if (event.user) return panelLink('user', event.user)
if (event.group) return panelLink('group', event.group)
if (event.provider) return panelLink('provider', event.provider)
return { page: 'events' }
}
+46 -2
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { eventKindVariant, EVENT_KIND_LABEL, EVENT_KINDS, filterEvents, kindLabel } from './events-filter'
import { eventFilterFromParams, eventKindVariant, EVENT_KIND_LABEL, EVENT_KINDS, filterEvents, itemsFromFilter, kindLabel, paramsFromItems } from './events-filter'
import type { AdminEventView } from '@/types/api'
function event(overrides: Partial<AdminEventView> = {}): AdminEventView {
@@ -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', 'paced'])
expect(EVENT_KINDS).toEqual(['rate_limit', 'budget', 'store_down', 'upstream', 'timeout', 'unpriced', 'capacity', 'paced', 'router_escalation', 'router_timeout_fallback'])
})
it('every entry has a truthy label (no silently-empty display text)', () => {
@@ -126,3 +126,47 @@ describe('filterEvents', () => {
expect(filterEvents(events, { kind: 'unpriced', user: '' })).toEqual([])
})
})
describe('filterEvents provider and route', () => {
const rows = [
event({ provider: 'alibaba', route: 'chat/completions' }),
event({ provider: 'amd', route: 'embeddings' }),
event({ route: 'pricing', kind: 'unpriced' }),
]
it('matches provider exactly, case-insensitively', () => {
expect(filterEvents(rows, { kind: '', user: '', provider: 'AMD' })).toHaveLength(1)
})
it('matches route by substring', () => {
expect(filterEvents(rows, { kind: '', user: '', route: 'chat' })).toHaveLength(1)
})
it('ignores absent provider and route filters', () => {
expect(filterEvents(rows, { kind: '', user: '' })).toHaveLength(3)
})
})
describe('EVENT_KIND_LABEL router_escalation and paced', () => {
it('labels both', () => {
expect(EVENT_KIND_LABEL.paced).toBeTruthy()
expect(EVENT_KIND_LABEL.router_escalation).toBeTruthy()
})
})
describe('event filter hash params', () => {
it('reads the four params, dropping empties', () => {
expect(eventFilterFromParams({ kind: 'upstream', user: ' bob ', provider: 'amd', route: '' })).toEqual({ kind: 'upstream', user: 'bob', provider: 'amd', route: '' })
})
it('round-trips through filter items', () => {
const f = { kind: 'upstream', user: 'bob', provider: 'amd', route: 'chat' }
expect(eventFilterFromParams(paramsFromItems(itemsFromFilter(f)))).toEqual(f)
})
it('keeps one value per field, the last winning', () => {
const items = [
{ id: 'a', field: 'kind', value: 'budget' },
{ id: 'b', field: 'kind', value: 'upstream' },
]
expect(paramsFromItems(items)).toEqual({ kind: 'upstream' })
})
it('ignores unknown fields', () => {
expect(paramsFromItems([{ id: 'a', field: 'nope', value: 'x' }])).toEqual({})
})
})
+47 -7
View File
@@ -10,6 +10,8 @@ export const EVENT_KIND_LABEL: Record<AdminEventKind, string> = {
unpriced: 'Unpriced model',
capacity: 'Capacity',
paced: 'Paced',
router_escalation: 'Router escalation',
router_timeout_fallback: 'Router timeout fallback',
}
/**
@@ -67,29 +69,67 @@ export function eventKindVariant(kind: string): 'destructive' | 'secondary' | 'o
}
}
/** EventFilter is filterEvents' own query shape — kind is an exact AdminEventKind match ('' means "every kind"); user is matched, case-insensitively, against EITHER the event's user OR its group (a group-scoped event has no user, and vice versa — see AdminEventView's own doc comment). */
/** EventFilter is filterEvents' own query shape — kind is an exact AdminEventKind match ('' means "every kind"); user is matched, case-insensitively, against EITHER the event's user OR its group; provider is an exact match and route a substring match, both case-insensitive and ignored when absent or empty. */
export interface EventFilter {
kind: string
user: string
provider?: string
route?: string
}
/**
* filterEvents narrows the (already newest-first) event list to the
* current kind/user selection. `filter.user` is matched pre-normalized —
* callers pair this with useSearchQuery()'s own `normalized` the same way
* every other search filter in this panel does (ProviderHealthPanel.vue's
* modelMatches, lib/usage-search.ts) — this function itself does no
* trimming or casing of its own beyond a defensive `.trim().toLowerCase()`
* so it is still correct if a caller passes the raw query directly.
* current selection. `filter.user` is matched pre-normalized by the
* caller; a defensive trim and lower-casing keeps it correct on raw input.
*/
export function filterEvents(events: AdminEventView[], filter: EventFilter): AdminEventView[] {
const kind = filter.kind
const user = filter.user.trim().toLowerCase()
const provider = (filter.provider ?? '').trim().toLowerCase()
const route = (filter.route ?? '').trim().toLowerCase()
return events.filter((e) => {
if (kind && e.kind !== kind) return false
if (provider && (e.provider ?? '').toLowerCase() !== provider) return false
if (route && !e.route.toLowerCase().includes(route)) return false
if (!user) return true
const userMatch = e.user?.toLowerCase().includes(user) ?? false
const groupMatch = e.group?.toLowerCase().includes(user) ?? false
return userMatch || groupMatch
})
}
/** The hash params the Events page reads; each maps to one FilterBar field of the same id. */
export const EVENT_FILTER_FIELDS = ['kind', 'user', 'provider', 'route'] as const
export type EventFilterField = (typeof EVENT_FILTER_FIELDS)[number]
type ParamBag = Record<string, string | undefined>
export function eventFilterFromParams(params: ParamBag): Required<EventFilter> {
const get = (k: EventFilterField): string => (params[k] ?? '').trim()
return { kind: get('kind'), user: get('user'), provider: get('provider'), route: get('route') }
}
export interface EventFilterItem {
id: string
field: string
value: string | number | boolean | string[]
}
/** One chip per non-empty filter; the chip id is its field so a re-applied filter replaces the old one. */
export function itemsFromFilter(filter: Partial<EventFilter>): EventFilterItem[] {
return EVENT_FILTER_FIELDS.flatMap((field) => {
const value = (filter[field] ?? '').trim()
return value ? [{ id: field, field, value }] : []
})
}
/** Back to hash params: one value per field (the last chip wins), unknown fields and empty values dropped. */
export function paramsFromItems(items: EventFilterItem[]): Partial<Record<EventFilterField, string>> {
const out: Partial<Record<EventFilterField, string>> = {}
for (const item of items) {
if (!(EVENT_FILTER_FIELDS as readonly string[]).includes(item.field)) continue
const value = String(item.value).trim()
if (value) out[item.field as EventFilterField] = value
}
return out
}
+68
View File
@@ -0,0 +1,68 @@
import { describe, expect, it } from 'vitest'
import { findTarget, hostOf, targetRows } from './target-rows'
import type { AdminTargetsResponse, AdminTargetView } from '@/types/api'
function target(name: string, overrides: Partial<AdminTargetView> = {}): AdminTargetView {
return {
name,
url: `http://${name}.svc.internal:8080/mcp`,
access: null,
counters: { requestsPerMinute: 0, requestsPerDay: 1, requestsPerMonth: 2 },
health: { state: 'healthy', consecutiveFailures: 0 },
...overrides,
}
}
const targets: AdminTargetsResponse = {
mcpServers: [target('fetch'), target('maps', { health: { state: 'unhealthy', consecutiveFailures: 3 } })],
agents: [target('fetch', { url: 'https://agent.example.com' }), target('planner', { health: { state: 'unknown', consecutiveFailures: 0 } })],
}
describe('hostOf', () => {
it('returns host and port of a URL', () => {
expect(hostOf('http://mcp-fetch.svc.internal:8088/mcp')).toBe('mcp-fetch.svc.internal:8088')
})
it('falls back to the raw text for an unparseable URL', () => {
expect(hostOf('not a url')).toBe('not a url')
})
it('never returns an empty string', () => {
expect(hostOf('')).toBe('—')
})
})
describe('targetRows', () => {
it('lists MCP servers then agents with composed ids, so equal names stay distinct', () => {
expect(targetRows(targets).map((r) => r.id)).toEqual(['mcp/fetch', 'mcp/maps', 'agent/fetch', 'agent/planner'])
})
it('labels the kind and keeps the host', () => {
const [mcp, , agent] = targetRows(targets)
expect([mcp.kind, agent.kind]).toEqual(['MCP', 'Agent'])
expect(agent.host).toBe('agent.example.com')
})
it('ranks unhealthy above unknown above healthy', () => {
const rank = Object.fromEntries(targetRows(targets).map((r) => [r.id, r.healthRank]))
expect(rank['mcp/maps']).toBeGreaterThan(rank['agent/planner'])
expect(rank['agent/planner']).toBeGreaterThan(rank['mcp/fetch'])
})
it('treats a health state this build does not know as unknown', () => {
const odd = { mcpServers: [target('x', { health: { state: 'weird' as never, consecutiveFailures: 0 } })], agents: [] }
expect(targetRows(odd)[0].health).toBe('unknown')
})
it('is empty for no targets', () => {
expect(targetRows(null)).toEqual([])
})
})
describe('findTarget', () => {
it('finds a target by composed id', () => {
expect(findTarget(targets, 'agent/fetch')?.url).toBe('https://agent.example.com')
})
it('resolves a bare name only when it is unambiguous', () => {
expect(findTarget(targets, 'planner')?.name).toBe('planner')
expect(findTarget(targets, 'fetch')).toBeNull()
})
it('is null for an unknown id', () => {
expect(findTarget(targets, 'mcp/nope')).toBeNull()
})
})
+53
View File
@@ -0,0 +1,53 @@
import { composeTargetId, resolveTargetRef } from '@/lib/target-columns'
import type { TargetKind } from '@/lib/target-columns'
import type { AdminTargetsResponse, AdminTargetView } from '@/types/api'
export type TargetHealth = 'healthy' | 'unhealthy' | 'unknown'
export interface TargetRow {
id: string
kind: 'MCP' | 'Agent'
name: string
health: TargetHealth
/** Sort key for the health column: worst first when descending. */
healthRank: number
host: string
}
const HEALTH_RANK: Record<TargetHealth, number> = { unhealthy: 2, unknown: 1, healthy: 0 }
const KIND_LABEL: Record<TargetKind, TargetRow['kind']> = { mcp: 'MCP', agent: 'Agent' }
const NONE = '—'
/** Host (with port) of a target URL; the raw text when it does not parse, a dash when empty. */
export function hostOf(url: string): string {
if (!url) return NONE
try {
return new URL(url).host || url
} catch {
return url
}
}
function healthOf(t: AdminTargetView): TargetHealth {
const state = t.health?.state
return state === 'healthy' || state === 'unhealthy' ? state : 'unknown'
}
function toRow(kind: TargetKind, t: AdminTargetView): TargetRow {
const health = healthOf(t)
return { id: composeTargetId(kind, t.name), kind: KIND_LABEL[kind], name: t.name, health, healthRank: HEALTH_RANK[health], host: hostOf(t.url) }
}
/** MCP servers then agents; ids are composed so an MCP server and an agent may share a name. */
export function targetRows(targets: AdminTargetsResponse | null): TargetRow[] {
if (!targets) return []
return [...targets.mcpServers.map((t) => toRow('mcp', t)), ...targets.agents.map((t) => toRow('agent', t))]
}
/** The target a composed ("mcp/x") or unambiguous bare id names, else null. */
export function findTarget(targets: AdminTargetsResponse | null, id: string): AdminTargetView | null {
const res = resolveTargetRef(id, targets)
if (res.kind !== 'ref') return null
const list = res.ref.startsWith('agent/') ? targets?.agents : targets?.mcpServers
return list?.find((t) => t.name === res.name) ?? null
}