mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
feat(webui): targets and events pages
This commit is contained in:
+1
-3
@@ -41,8 +41,6 @@ function lazyPage(loader: () => Promise<Component>): Component {
|
||||
return defineAsyncComponent({ loader, errorComponent: PageLoadError, timeout: 30_000 })
|
||||
}
|
||||
|
||||
// Legacy pages stand in until their redesigned replacements land:
|
||||
// events still lives inside Reliability.
|
||||
const PAGES: Record<PageId, Component> = {
|
||||
overview: lazyPage(() => import('@/pages/OverviewPage.vue')),
|
||||
usage: lazyPage(() => import('@/pages/UsagePage.vue')),
|
||||
@@ -51,7 +49,7 @@ const PAGES: Record<PageId, Component> = {
|
||||
models: lazyPage(() => import('@/pages/ModelsPage.vue')),
|
||||
routers: lazyPage(() => import('@/pages/RoutersPage.vue')),
|
||||
targets: lazyPage(() => import('@/pages/TargetsPage.vue')),
|
||||
events: lazyPage(() => import('@/pages/LegacyReliabilityPage.vue')),
|
||||
events: lazyPage(() => import('@/pages/EventsPage.vue')),
|
||||
config: lazyPage(() => import('@/pages/ConfigPage.vue')),
|
||||
}
|
||||
|
||||
|
||||
@@ -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' })
|
||||
})
|
||||
})
|
||||
@@ -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' }
|
||||
}
|
||||
@@ -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({})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<script setup lang="ts">
|
||||
import { Button, Card, CardAction, CardContent, CardHeader, CardTitle, FilterBar, StatusDot } from '@perfect-design/ui'
|
||||
import type { FilterField, FilterItem } from '@perfect-design/ui'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
|
||||
import { EVENT_KIND_LABEL, EVENT_KINDS, eventFilterFromParams, filterEvents, itemsFromFilter, paramsFromItems } from '@/lib/events-filter'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { EVENTS_POLL_MS, useEventsStore } from '@/stores/events'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
import RecentEvents from '@/widgets/RecentEvents.vue'
|
||||
import StateView from '@/widgets/StateView.vue'
|
||||
import type { ViewState } from '@/widgets/StateView.vue'
|
||||
|
||||
const PAGE_STEP = 50
|
||||
const POLL_SECONDS = EVENTS_POLL_MS / 1000
|
||||
|
||||
const events = useEventsStore()
|
||||
const nav = useNavStore()
|
||||
|
||||
// --- Filters (all state lives in the hash: kind, user, provider, route) ---
|
||||
const filter = computed(() => eventFilterFromParams(nav.params))
|
||||
const items = computed<FilterItem[]>(() => itemsFromFilter(filter.value))
|
||||
|
||||
const providerOptions = computed(() => {
|
||||
const names = new Set(events.events.flatMap((e) => (e.provider ? [e.provider] : [])))
|
||||
if (filter.value.provider) names.add(filter.value.provider)
|
||||
return [...names].sort().map((value) => ({ value, label: value }))
|
||||
})
|
||||
const fields = computed<FilterField[]>(() => [
|
||||
{ id: 'kind', label: 'Kind', type: 'select', operators: ['eq'], options: EVENT_KINDS.map((k) => ({ value: k, label: EVENT_KIND_LABEL[k] })) },
|
||||
{ id: 'user', label: 'User or group', type: 'text', operators: ['contains'], placeholder: 'name' },
|
||||
// The select needs at least one option; until events name a provider it is a plain text field.
|
||||
{ id: 'provider', label: 'Provider', type: providerOptions.value.length > 0 ? 'select' : 'text', operators: ['eq'], options: providerOptions.value },
|
||||
{ id: 'route', label: 'Route', type: 'text', operators: ['contains'], placeholder: 'chat/completions' },
|
||||
])
|
||||
|
||||
function setItems(next: FilterItem[]): void {
|
||||
const keep = Object.fromEntries(Object.entries(nav.params).filter(([k]) => !(k in filter.value)))
|
||||
nav.goTo('events', { ...keep, ...paramsFromItems(next) })
|
||||
}
|
||||
|
||||
const filtered = computed(() => filterEvents(events.events, filter.value))
|
||||
const shown = ref(PAGE_STEP)
|
||||
watch(filter, () => (shown.value = PAGE_STEP))
|
||||
const visible = computed(() => filtered.value.slice(0, shown.value))
|
||||
const remaining = computed(() => filtered.value.length - visible.value.length)
|
||||
|
||||
// --- Live tail: the store polls while mounted and not paused ---
|
||||
const live = ref(true)
|
||||
function toggleLive(): void {
|
||||
live.value = !live.value
|
||||
}
|
||||
watch(live, (on) => (on ? events.startPolling() : events.stopPolling()))
|
||||
onMounted(() => events.startPolling())
|
||||
onUnmounted(() => events.stopPolling())
|
||||
|
||||
const state = computed<ViewState>(() => {
|
||||
const s = loadState({ loading: events.refreshing, hasData: events.lastUpdated !== null, error: events.error })
|
||||
if (s === 'skeleton') return 'loading'
|
||||
if (s === 'error') return 'error'
|
||||
return filtered.value.length === 0 ? 'empty' : 'ready'
|
||||
})
|
||||
const filterActive = computed(() => items.value.length > 0)
|
||||
const emptyTitle = computed(() => (filterActive.value && events.events.length > 0 ? 'No events match the filter' : 'No events recorded'))
|
||||
const emptyDescription = computed(() =>
|
||||
filterActive.value && events.events.length > 0 ? 'Change or clear a filter to see more of the last events.' : 'Rate-limit, budget and upstream events show up here as they happen.',
|
||||
)
|
||||
const sourceNote = computed(() => {
|
||||
if (events.lastUpdated === null) return ''
|
||||
return events.source === 'redis' ? 'All replicas' : `This replica only (${events.replica || 'unknown'})`
|
||||
})
|
||||
const countNote = computed(() => (filtered.value.length === events.events.length ? `${events.events.length.toLocaleString('en-US')} events` : `${filtered.value.length.toLocaleString('en-US')} of ${events.events.length.toLocaleString('en-US')} events`))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<Card size="sm">
|
||||
<CardHeader class="items-center">
|
||||
<CardTitle>Events</CardTitle>
|
||||
<CardAction class="flex items-center gap-2 self-center">
|
||||
<span class="text-muted-foreground flex items-center gap-1.5 text-xs" data-testid="events-live-status" role="status">
|
||||
<StatusDot :tone="live ? 'success' : 'neutral'" size="md" />
|
||||
{{ live ? `Live, every ${POLL_SECONDS}s` : 'Paused' }}
|
||||
</span>
|
||||
<Button variant="outline" size="sm" :aria-pressed="!live" @click="toggleLive">{{ live ? 'Pause' : 'Resume' }}</Button>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-2">
|
||||
<p v-if="events.degraded" role="note" class="border-border bg-card text-muted-foreground m-0 rounded-md border px-3 py-2 text-sm">
|
||||
Redis could not be read. Showing this replica's own events, which may miss events from other replicas.
|
||||
</p>
|
||||
<FilterBar :model-value="items" :fields="fields" variant="compact" size="sm" clearable @update:model-value="setItems" />
|
||||
<div v-if="events.lastUpdated !== null" class="text-muted-foreground flex flex-wrap items-center justify-between gap-2 text-xs">
|
||||
<span>{{ countNote }}</span>
|
||||
<span>{{ sourceNote }}</span>
|
||||
</div>
|
||||
<StateView :state="state" :empty-title="emptyTitle" :empty-description="emptyDescription" :error-message="events.error" :updated-at="events.lastUpdated ?? undefined" @retry="events.refresh()">
|
||||
<RecentEvents :events="visible" label="Events" with-message />
|
||||
<div v-if="remaining > 0" class="flex items-center justify-between gap-2">
|
||||
<span class="text-muted-foreground text-xs">Showing {{ visible.length.toLocaleString('en-US') }} of {{ filtered.length.toLocaleString('en-US') }}</span>
|
||||
<Button variant="outline" size="sm" @click="shown += PAGE_STEP">Show {{ Math.min(PAGE_STEP, remaining) }} more</Button>
|
||||
</div>
|
||||
</StateView>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,82 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive } from 'vue'
|
||||
|
||||
import TargetCallers from '@/components/TargetCallers.vue'
|
||||
import TargetsView from '@/components/TargetsView.vue'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { resolveTargetRef } from '@/lib/target-columns'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
/**
|
||||
* TargetsPage (redesign-plan.md section 3.4, "MCP & Agents") is
|
||||
* TargetsView.vue's pre-redesign listing (unchanged: MCP servers/agents,
|
||||
* their access lists, and request counters), plus the per-target caller
|
||||
* breakdown ("TargetCallers.vue expander") and a fleet-wide "top callers"
|
||||
* card, both reading GET /admin/api/usage/totals?kind=targetcaller.
|
||||
*
|
||||
* `target` (hash param) deep-links directly to one target's own callers —
|
||||
* read as a computed straight off nav.params (P2 item 10: a local ref set
|
||||
* only once on mount ignored a LATER hashchange — browser back/forward, a
|
||||
* hand-edited URL — while the page stayed mounted) and kept in sync
|
||||
* afterwards via nav.goTo so a reader who clicks a different target gets a
|
||||
* bookmarkable/shareable URL, mirroring EntityLink.vue's own
|
||||
* one-param-at-a-time convention. The raw param is normalized through
|
||||
* lib/target-columns.ts's resolveTargetRef before it ever reaches
|
||||
* TargetCallers — the backend only accepts "mcp/{name}"/"agent/{name}"
|
||||
* (stats_read.go's parseTargetRef), so a hand-typed bare name like
|
||||
* `#targets?target=demo-mcp` used to 400 instead of resolving.
|
||||
*/
|
||||
const nav = useNavStore()
|
||||
const dashboard = useDashboardStore()
|
||||
|
||||
const selectedTargetId = computed<string>(() => nav.params.target ?? '')
|
||||
|
||||
/**
|
||||
* targetResolution is selectedTargetId run through resolveTargetRef
|
||||
* against the live dashboard.targets listing — null when there is no
|
||||
* `target` param at all (resolveTargetRef has no "empty" case of its
|
||||
* own; an empty string would otherwise fall through its bare-name
|
||||
* lookup and misreport 'notice: No MCP server or agent named "" is
|
||||
* configured.', a spurious message on the plain, no-deep-link Targets
|
||||
* page — caught live via the states-plan.md visual verification pass).
|
||||
* Otherwise: 'ref' renders TargetCallers, 'notice' renders the Alert
|
||||
* below instead of calling the API, 'pending' (targets not loaded yet,
|
||||
* only possible for a bare-name param) renders neither until the next
|
||||
* dashboard poll resolves it.
|
||||
*/
|
||||
const targetResolution = computed(() => (selectedTargetId.value === '' ? null : resolveTargetRef(selectedTargetId.value, dashboard.targets)))
|
||||
|
||||
/**
|
||||
* knownLabels remembers the real display name TargetsView.vue's own click
|
||||
* handed selectTarget, keyed by composed id — selectedTargetLabel below
|
||||
* falls back to the resolved bare name (targetResolution's own `name`)
|
||||
* whenever the CURRENT selectedTargetId has no recorded label, e.g. a
|
||||
* fresh deep link that never went through a click (the label is cosmetic
|
||||
* only — TargetCallers.vue's own card title, not a lookup key — so this
|
||||
* never blocks on the targets listing having loaded).
|
||||
*/
|
||||
const knownLabels = reactive<Record<string, string>>({})
|
||||
const selectedTargetLabel = computed<string>(() => {
|
||||
const resolution = targetResolution.value
|
||||
return knownLabels[selectedTargetId.value] ?? (resolution?.kind === 'ref' ? resolution.name : selectedTargetId.value)
|
||||
})
|
||||
|
||||
function selectTarget(id: string, label: string): void {
|
||||
knownLabels[id] = label
|
||||
nav.goTo('targets', { ...nav.params, target: id })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<TargetsView @select="selectTarget" />
|
||||
|
||||
<TargetCallers v-if="targetResolution?.kind === 'ref'" :target="targetResolution.ref" :title="`Callers of ${selectedTargetLabel}`" />
|
||||
<Alert v-else-if="targetResolution?.kind === 'notice'" variant="destructive">
|
||||
<AlertDescription>{{ targetResolution.message }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<TargetCallers title="Top callers, across every target" />
|
||||
</div>
|
||||
</template>
|
||||
+106
-63
@@ -1,82 +1,125 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive } from 'vue'
|
||||
import { Card, CardAction, CardContent, CardHeader, CardTitle, Pagination, SearchInput, StatusBadge } from '@perfect-design/ui'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
import TargetCallers from '@/components/TargetCallers.vue'
|
||||
import TargetsView from '@/components/TargetsView.vue'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { pageWindow } from '@/lib/paging'
|
||||
import { resolveSel } from '@/lib/panel-selection'
|
||||
import { resolveTargetRef } from '@/lib/target-columns'
|
||||
import { findTarget, targetRows } from '@/lib/target-rows'
|
||||
import type { TargetRow } from '@/lib/target-rows'
|
||||
import { sortThenSlice } from '@/lib/table-sort'
|
||||
import type { SortSpec } from '@/lib/table-sort'
|
||||
import { wbColumns } from '@/lib/wb-columns'
|
||||
import TargetPanel from '@/panels/TargetPanel.vue'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
import StateView from '@/widgets/StateView.vue'
|
||||
import type { ViewState } from '@/widgets/StateView.vue'
|
||||
import WbTable from '@/widgets/WbTable.vue'
|
||||
|
||||
const PAGE_SIZE = 12
|
||||
const HEALTH_TONE = { healthy: 'success', unhealthy: 'danger', unknown: 'neutral' } as const
|
||||
|
||||
/**
|
||||
* TargetsPage (redesign-plan.md section 3.4, "MCP & Agents") is
|
||||
* TargetsView.vue's pre-redesign listing (unchanged: MCP servers/agents,
|
||||
* their access lists, and request counters), plus the per-target caller
|
||||
* breakdown ("TargetCallers.vue expander") and a fleet-wide "top callers"
|
||||
* card, both reading GET /admin/api/usage/totals?kind=targetcaller.
|
||||
*
|
||||
* `target` (hash param) deep-links directly to one target's own callers —
|
||||
* read as a computed straight off nav.params (P2 item 10: a local ref set
|
||||
* only once on mount ignored a LATER hashchange — browser back/forward, a
|
||||
* hand-edited URL — while the page stayed mounted) and kept in sync
|
||||
* afterwards via nav.goTo so a reader who clicks a different target gets a
|
||||
* bookmarkable/shareable URL, mirroring EntityLink.vue's own
|
||||
* one-param-at-a-time convention. The raw param is normalized through
|
||||
* lib/target-columns.ts's resolveTargetRef before it ever reaches
|
||||
* TargetCallers — the backend only accepts "mcp/{name}"/"agent/{name}"
|
||||
* (stats_read.go's parseTargetRef), so a hand-typed bare name like
|
||||
* `#targets?target=demo-mcp` used to 400 instead of resolving.
|
||||
*/
|
||||
const nav = useNavStore()
|
||||
const dashboard = useDashboardStore()
|
||||
const nav = useNavStore()
|
||||
|
||||
const selectedTargetId = computed<string>(() => nav.params.target ?? '')
|
||||
const all = computed(() => targetRows(dashboard.targets))
|
||||
const query = computed<string>({
|
||||
get: () => nav.params.q ?? '',
|
||||
set: (v) => {
|
||||
const { q: _q, ...rest } = nav.params
|
||||
nav.goTo('targets', v ? { ...rest, q: v } : rest)
|
||||
},
|
||||
})
|
||||
const needle = computed(() => query.value.trim().toLowerCase())
|
||||
const rows = computed(() => (needle.value === '' ? all.value : all.value.filter((r) => r.name.toLowerCase().includes(needle.value) || r.host.toLowerCase().includes(needle.value))))
|
||||
|
||||
/**
|
||||
* targetResolution is selectedTargetId run through resolveTargetRef
|
||||
* against the live dashboard.targets listing — null when there is no
|
||||
* `target` param at all (resolveTargetRef has no "empty" case of its
|
||||
* own; an empty string would otherwise fall through its bare-name
|
||||
* lookup and misreport 'notice: No MCP server or agent named "" is
|
||||
* configured.', a spurious message on the plain, no-deep-link Targets
|
||||
* page — caught live via the states-plan.md visual verification pass).
|
||||
* Otherwise: 'ref' renders TargetCallers, 'notice' renders the Alert
|
||||
* below instead of calling the API, 'pending' (targets not loaded yet,
|
||||
* only possible for a bare-name param) renders neither until the next
|
||||
* dashboard poll resolves it.
|
||||
*/
|
||||
const targetResolution = computed(() => (selectedTargetId.value === '' ? null : resolveTargetRef(selectedTargetId.value, dashboard.targets)))
|
||||
const columns = wbColumns<TargetRow>([
|
||||
{ key: 'kind', header: 'Kind', kind: 'text' },
|
||||
{ key: 'name', header: 'Name', kind: 'text' },
|
||||
{ key: 'health', header: 'Health', kind: 'status', sortable: true },
|
||||
{ key: 'host', header: 'Host', kind: 'text' },
|
||||
])
|
||||
|
||||
/**
|
||||
* knownLabels remembers the real display name TargetsView.vue's own click
|
||||
* handed selectTarget, keyed by composed id — selectedTargetLabel below
|
||||
* falls back to the resolved bare name (targetResolution's own `name`)
|
||||
* whenever the CURRENT selectedTargetId has no recorded label, e.g. a
|
||||
* fresh deep link that never went through a click (the label is cosmetic
|
||||
* only — TargetCallers.vue's own card title, not a lookup key — so this
|
||||
* never blocks on the targets listing having loaded).
|
||||
*/
|
||||
const knownLabels = reactive<Record<string, string>>({})
|
||||
const selectedTargetLabel = computed<string>(() => {
|
||||
const resolution = targetResolution.value
|
||||
return knownLabels[selectedTargetId.value] ?? (resolution?.kind === 'ref' ? resolution.name : selectedTargetId.value)
|
||||
const sort = ref<SortSpec | null>(null)
|
||||
const page = ref(1)
|
||||
const sortSpec = computed<SortSpec | null>(() => (sort.value?.key === 'health' ? { ...sort.value, key: 'healthRank' } : sort.value))
|
||||
const paged = computed(() => sortThenSlice(rows.value, sortSpec.value, PAGE_SIZE, pageWindow(rows.value.length, PAGE_SIZE, page.value - 1).index))
|
||||
function onSort(next: SortSpec | null): void {
|
||||
sort.value = next
|
||||
page.value = 1
|
||||
}
|
||||
watch(needle, () => {
|
||||
page.value = 1
|
||||
})
|
||||
|
||||
function selectTarget(id: string, label: string): void {
|
||||
knownLabels[id] = label
|
||||
nav.goTo('targets', { ...nav.params, target: id })
|
||||
const state = computed<ViewState>(() => {
|
||||
const s = loadState({ loading: dashboard.lastUpdated === null, hasData: dashboard.targets !== null, error: dashboard.error })
|
||||
if (s === 'skeleton') return 'loading'
|
||||
if (s === 'error') return 'error'
|
||||
return rows.value.length === 0 ? 'empty' : 'ready'
|
||||
})
|
||||
const emptyTitle = computed(() => (needle.value !== '' ? `No targets match "${query.value.trim()}"` : 'No MCP servers or agents configured'))
|
||||
const emptyDescription = computed(() => (needle.value !== '' ? undefined : 'Add an mcpServers or agents entry to the middleware config to see them here.'))
|
||||
const unhealthy = computed(() => all.value.filter((r) => r.health === 'unhealthy').length)
|
||||
const summary = computed(() => (all.value.length === 0 ? '' : `${all.value.length.toLocaleString('en-US')} targets · ${unhealthy.value} unhealthy`))
|
||||
|
||||
const selection = computed(() => nav.selection)
|
||||
const activeKey = computed(() => (selection.value?.kind === 'target' ? selection.value.id : null))
|
||||
// A selection may name a target by bare name; rows carry the composed id.
|
||||
const activeRow = computed(() => {
|
||||
const res = activeKey.value === null ? null : resolveTargetRef(activeKey.value, dashboard.targets)
|
||||
return res?.kind === 'ref' ? res.ref : null
|
||||
})
|
||||
|
||||
function exists(kind: string, id: string): boolean {
|
||||
return kind === 'target' && findTarget(dashboard.targets, id) !== null
|
||||
}
|
||||
watch(
|
||||
[selection, () => dashboard.targets],
|
||||
([sel, loaded]) => {
|
||||
if (!sel || loaded === null) return
|
||||
if (resolveSel(sel, exists) === null) nav.closePanel()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
const openSel = computed(() => (dashboard.targets !== null ? resolveSel(selection.value, exists) : null))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<TargetsView @select="selectTarget" />
|
||||
<div class="flex flex-col gap-4">
|
||||
<Card size="sm">
|
||||
<CardHeader class="items-center">
|
||||
<CardTitle>MCP servers and agents</CardTitle>
|
||||
<CardAction v-if="summary" class="text-muted-foreground self-center text-xs">{{ summary }}</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-2">
|
||||
<SearchInput v-model="query" size="sm" class="max-w-sm" placeholder="Filter by name or host" aria-label="Filter targets" />
|
||||
<StateView :state="state" :empty-title="emptyTitle" :empty-description="emptyDescription" :error-message="dashboard.error" :updated-at="dashboard.lastUpdated ?? undefined" @retry="dashboard.refresh()">
|
||||
<WbTable
|
||||
class="wb-clip"
|
||||
:columns="columns"
|
||||
:rows="paged"
|
||||
:sort="sort"
|
||||
row-key="id"
|
||||
:active-key="activeRow"
|
||||
label="MCP servers and agents"
|
||||
@update:sort="onSort"
|
||||
@row-activate="(row: TargetRow) => nav.openPanel('target', row.id)"
|
||||
>
|
||||
<template #cell-name="{ value }"><span class="font-mono">{{ value }}</span></template>
|
||||
<template #cell-health="{ value }"><StatusBadge :status="value as string" :tones="HEALTH_TONE" size="sm" /></template>
|
||||
<template #cell-host="{ value }"><span class="font-mono">{{ value }}</span></template>
|
||||
</WbTable>
|
||||
<div v-if="rows.length > PAGE_SIZE" class="flex items-center justify-between gap-2">
|
||||
<span class="text-muted-foreground text-xs">{{ rows.length.toLocaleString('en-US') }} targets</span>
|
||||
<Pagination v-model:page="page" :total="rows.length" :page-size="PAGE_SIZE" variant="compact" size="sm" />
|
||||
</div>
|
||||
</StateView>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<TargetCallers v-if="targetResolution?.kind === 'ref'" :target="targetResolution.ref" :title="`Callers of ${selectedTargetLabel}`" />
|
||||
<Alert v-else-if="targetResolution?.kind === 'notice'" variant="destructive">
|
||||
<AlertDescription>{{ targetResolution.message }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<TargetCallers title="Top callers, across every target" />
|
||||
<TargetPanel v-if="openSel?.kind === 'target'" :id="openSel.id" @close="nav.closePanel()" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
<script setup lang="ts">
|
||||
import { Button, DescriptionItem, DescriptionList, StatusBadge } from '@perfect-design/ui'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
import { useCopyFeedback } from '@/composables/useCopyFeedback'
|
||||
import { useEntityLinks } from '@/composables/useEntityLinks'
|
||||
import { adminFetch, messageOf } from '@/lib/api'
|
||||
import { copyText } from '@/lib/clipboard'
|
||||
import { formatCompactCount, formatElapsedAgo, formatLatencyMs } from '@/lib/format'
|
||||
import { dayOrMonthClampNotice, dayOrMonthWindow, totalsUrl } from '@/lib/range'
|
||||
import { parseTargetCallerId, resolveTargetRef } from '@/lib/target-columns'
|
||||
import { findTarget, hostOf } from '@/lib/target-rows'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useFiltersStore } from '@/stores/filters'
|
||||
import type { AdminTotalsResponse } from '@/types/api'
|
||||
import DetailPanel from '@/widgets/DetailPanel.vue'
|
||||
import PanelSection from '@/widgets/PanelSection.vue'
|
||||
import StateView from '@/widgets/StateView.vue'
|
||||
import type { ViewState } from '@/widgets/StateView.vue'
|
||||
|
||||
const CALLER_ROWS = 8
|
||||
const HEALTH_TONE = { healthy: 'success', unhealthy: 'danger', unknown: 'neutral' } as const
|
||||
const COPY_LABEL = { idle: 'Copy', copied: 'Copied', selected: 'Selected', failed: 'Copy failed' } as const
|
||||
|
||||
const props = defineProps<{ id: string }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const dashboard = useDashboardStore()
|
||||
const filters = useFiltersStore()
|
||||
const { openEntity } = useEntityLinks()
|
||||
const copy = useCopyFeedback()
|
||||
const urlEl = ref<HTMLElement | null>(null)
|
||||
|
||||
const target = computed(() => findTarget(dashboard.targets, props.id))
|
||||
const targetRef = computed(() => {
|
||||
const res = resolveTargetRef(props.id, dashboard.targets)
|
||||
return res.kind === 'ref' ? res.ref : null
|
||||
})
|
||||
const title = computed(() => target.value?.name ?? props.id)
|
||||
const kindLabel = computed(() => (targetRef.value?.startsWith('agent/') ? 'Agent' : 'MCP server'))
|
||||
const health = computed(() => target.value?.health)
|
||||
const healthState = computed(() => (health.value?.state === 'healthy' || health.value?.state === 'unhealthy' ? health.value.state : 'unknown'))
|
||||
const checkedAgo = computed(() => formatElapsedAgo(health.value?.lastCheck))
|
||||
const access = computed(() => {
|
||||
const a = target.value?.access
|
||||
if (a == null) return 'every group'
|
||||
return a.length === 0 ? 'no group' : a.join(', ')
|
||||
})
|
||||
|
||||
async function copyUrl(): Promise<void> {
|
||||
copy.set(await copyText(target.value?.url ?? '', urlEl.value ?? undefined))
|
||||
}
|
||||
|
||||
const clampNote = computed(() => dayOrMonthClampNotice(filters.window, filters.span))
|
||||
const callers = ref<AdminTotalsResponse['rows']>([])
|
||||
const callersState = ref<ViewState>('loading')
|
||||
const callersError = ref('')
|
||||
let reqId = 0
|
||||
|
||||
async function loadCallers(): Promise<void> {
|
||||
const requestId = ++reqId
|
||||
const reference = targetRef.value
|
||||
if (!reference) return
|
||||
callersState.value = 'loading'
|
||||
callersError.value = ''
|
||||
try {
|
||||
const { window, span } = dayOrMonthWindow(filters.window, filters.span)
|
||||
const res = await adminFetch<AdminTotalsResponse>(totalsUrl({ kind: 'targetcaller', window, span, metrics: ['req'], limit: CALLER_ROWS, target: reference }))
|
||||
if (requestId !== reqId) return
|
||||
callers.value = res.rows
|
||||
callersState.value = res.rows.length === 0 ? 'empty' : 'ready'
|
||||
} catch (err) {
|
||||
if (requestId !== reqId) return
|
||||
callersError.value = messageOf(err)
|
||||
callersState.value = 'error'
|
||||
}
|
||||
}
|
||||
watch([targetRef, () => filters.window, () => filters.span], () => void loadCallers(), { immediate: true })
|
||||
|
||||
const callerRows = computed(() =>
|
||||
callers.value
|
||||
.map((r) => ({ id: r.id, caller: parseTargetCallerId(r.id).caller || r.id, requests: r.values.req ?? 0 }))
|
||||
.sort((a, b) => b.requests - a.requests || a.caller.localeCompare(b.caller)),
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DetailPanel kind="target" :id="id" :title="title" @close="emit('close')">
|
||||
<div class="flex flex-col divide-y px-1 pb-4" data-testid="target-panel">
|
||||
<div v-if="!target" class="text-muted-foreground py-3 text-sm">This MCP server or agent is not configured.</div>
|
||||
<template v-else>
|
||||
<PanelSection title="Health">
|
||||
<DescriptionList variant="inline" size="sm" density="compact">
|
||||
<DescriptionItem term="Kind">{{ kindLabel }}</DescriptionItem>
|
||||
<DescriptionItem term="Status"><StatusBadge :status="healthState" :tones="HEALTH_TONE" size="sm" /></DescriptionItem>
|
||||
<DescriptionItem v-if="health?.latencyMs !== undefined" term="Latency">
|
||||
<span class="font-mono tabular-nums">{{ formatLatencyMs(health.latencyMs) }}</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem v-if="checkedAgo" term="Last check">{{ checkedAgo }}{{ health?.source ? ` via ${health.source}` : '' }}</DescriptionItem>
|
||||
<DescriptionItem v-if="health && health.consecutiveFailures > 0" term="Consecutive failures">
|
||||
<span class="font-mono tabular-nums">{{ health.consecutiveFailures }}</span>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
<p v-if="health?.lastError" class="text-destructive m-0 text-sm break-words whitespace-pre-wrap" data-testid="target-last-err">{{ health.lastError }}</p>
|
||||
<p v-else-if="healthState === 'unknown'" class="text-muted-foreground m-0 text-sm">Not observed yet: no traffic, and probes are off or have not run.</p>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Endpoint">
|
||||
<DescriptionList variant="inline" size="sm" density="compact">
|
||||
<DescriptionItem term="Host"><span class="font-mono">{{ hostOf(target.url) }}</span></DescriptionItem>
|
||||
<DescriptionItem term="Access">{{ access }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
<div class="flex items-center gap-2">
|
||||
<code ref="urlEl" class="bg-muted min-w-0 flex-1 rounded px-2 py-1 font-mono text-xs break-all">{{ target.url }}</code>
|
||||
<Button variant="outline" size="sm" class="shrink-0" :aria-label="`Copy URL of ${title}`" @click="copyUrl">{{ COPY_LABEL[copy.state.value] }}</Button>
|
||||
</div>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Requests">
|
||||
<DescriptionList variant="inline" size="sm" density="compact">
|
||||
<DescriptionItem term="Per minute"><span class="font-mono tabular-nums">{{ formatCompactCount(target.counters.requestsPerMinute) }}</span></DescriptionItem>
|
||||
<DescriptionItem term="Today"><span class="font-mono tabular-nums">{{ formatCompactCount(target.counters.requestsPerDay) }}</span></DescriptionItem>
|
||||
<DescriptionItem term="This month"><span class="font-mono tabular-nums">{{ formatCompactCount(target.counters.requestsPerMonth) }}</span></DescriptionItem>
|
||||
</DescriptionList>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Top callers">
|
||||
<p v-if="clampNote" class="text-muted-foreground m-0 text-xs" data-testid="clamped-range">{{ clampNote }}</p>
|
||||
<StateView :state="callersState" empty-title="No callers in this range" :error-message="callersError" :rows="3" @retry="loadCallers()">
|
||||
<ul class="m-0 flex list-none flex-col p-0" aria-label="Top callers">
|
||||
<li v-for="c in callerRows" :key="c.id">
|
||||
<button type="button" class="hover:bg-accent flex h-8 w-full items-center justify-between gap-3 rounded px-2 text-left text-sm" :title="c.caller" @click="openEntity('user', c.caller)">
|
||||
<span class="min-w-0 truncate">{{ c.caller }}</span>
|
||||
<span class="shrink-0 font-mono text-xs tabular-nums">{{ formatCompactCount(c.requests) }} req</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</StateView>
|
||||
</PanelSection>
|
||||
</template>
|
||||
</div>
|
||||
</DetailPanel>
|
||||
</template>
|
||||
@@ -7,7 +7,7 @@ import { useToastsStore } from '@/stores/toasts'
|
||||
import type { AdminEventsResponse, AdminEventView } from '@/types/api'
|
||||
|
||||
/** How often the Events view polls while mounted — same cadence as the Providers/Usage/Targets dashboard poll (stores/dashboard.ts's own POLL_MS): a rate-limit/upstream event is exactly the kind of thing an operator wants to see within a few seconds, not thirty. */
|
||||
const POLL_MS = 5000
|
||||
export const EVENTS_POLL_MS = 5000
|
||||
|
||||
/** EVENTS_LIMIT matches the ring's own fixed capacity (events.go: eventRingCap, admin.go: adminEventsMaxLimit) — asking for fewer would silently hide events the ring/Redis list still holds. */
|
||||
const EVENTS_LIMIT = 200
|
||||
@@ -56,7 +56,7 @@ export const useEventsStore = defineStore('events', {
|
||||
kindFilter: '',
|
||||
userFilter: '',
|
||||
poller: undefined as VisibilityPoller | undefined,
|
||||
/** Mirrors dashboard.ts's own in-flight guard: a round trip slower than POLL_MS must never stack a second refresh() on top of the first. */
|
||||
/** Mirrors dashboard.ts's own in-flight guard: a round trip slower than EVENTS_POLL_MS must never stack a second refresh() on top of the first. */
|
||||
refreshing: false,
|
||||
/** toastedForFailure mirrors dashboard.ts's own flag: states-plan.md item 3's "one toast per failure streak per store until it recovers". */
|
||||
toastedForFailure: false,
|
||||
@@ -108,10 +108,10 @@ export const useEventsStore = defineStore('events', {
|
||||
setUserFilter(user: string): void {
|
||||
this.userFilter = user
|
||||
},
|
||||
/** startPolling is idempotent, driven by the shared createVisibilityPoller (lib/polling.ts, F5) — an immediate fetch, then every POLL_MS while the tab is visible. */
|
||||
/** startPolling is idempotent, driven by the shared createVisibilityPoller (lib/polling.ts, F5) — an immediate fetch, then every EVENTS_POLL_MS while the tab is visible. */
|
||||
startPolling(): void {
|
||||
if (this.poller) return
|
||||
this.poller = createVisibilityPoller({ intervalMs: POLL_MS, tick: () => void this.refresh() })
|
||||
this.poller = createVisibilityPoller({ intervalMs: EVENTS_POLL_MS, tick: () => void this.refresh() })
|
||||
this.poller.start()
|
||||
},
|
||||
stopPolling(): void {
|
||||
|
||||
@@ -668,6 +668,8 @@ export type AdminEventKind =
|
||||
| 'unpriced'
|
||||
| 'capacity'
|
||||
| 'paced'
|
||||
| 'router_escalation'
|
||||
| 'router_timeout_fallback'
|
||||
|
||||
/**
|
||||
* One row in GET /admin/api/events (admin.go/events.go: gatewayEvent — the
|
||||
|
||||
@@ -1,20 +1,33 @@
|
||||
<script setup lang="ts">
|
||||
import { StatusDot } from '@perfect-design/ui'
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { useEntityLinks } from '@/composables/useEntityLinks'
|
||||
import { eventLink } from '@/lib/event-link'
|
||||
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' }
|
||||
const TONE: Record<string, Tone> = {
|
||||
rate_limit: 'warning',
|
||||
budget: 'warning',
|
||||
timeout: 'warning',
|
||||
capacity: 'warning',
|
||||
store_down: 'danger',
|
||||
upstream: 'danger',
|
||||
unpriced: 'info',
|
||||
paced: 'info',
|
||||
router_escalation: 'info',
|
||||
router_timeout_fallback: 'warning',
|
||||
}
|
||||
|
||||
defineProps<{ events: AdminEventView[] }>()
|
||||
const props = withDefaults(defineProps<{ events: AdminEventView[]; label?: string; withMessage?: boolean }>(), { label: 'Recent events', withMessage: false })
|
||||
const nav = useNavStore()
|
||||
const { openEntity } = useEntityLinks()
|
||||
const { openLink } = useEntityLinks()
|
||||
|
||||
function subject(e: AdminEventView): string {
|
||||
return e.user || e.provider || e.model || e.route || e.message
|
||||
return e.user || e.group || e.provider || e.model || e.route || e.message
|
||||
}
|
||||
|
||||
function clock(iso: string): string {
|
||||
@@ -22,27 +35,41 @@ function clock(iso: string): string {
|
||||
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 })
|
||||
// A link back to the page already showing, with nothing to open, would do nothing.
|
||||
function linkOf(e: AdminEventView) {
|
||||
const link = eventLink(e)
|
||||
return link && !(link.page === nav.page && !link.sel) ? link : null
|
||||
}
|
||||
|
||||
const rows = computed(() => {
|
||||
const seen = new Map<string, number>()
|
||||
return props.events.map((e) => {
|
||||
const base = `${e.time}|${e.replica}|${e.kind}|${e.message}`
|
||||
const n = seen.get(base) ?? 0
|
||||
seen.set(base, n + 1)
|
||||
return { e, key: `${base}|${n}`, link: linkOf(e) }
|
||||
})
|
||||
})
|
||||
</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)"
|
||||
<ul class="m-0 flex list-none flex-col p-0" :aria-label="label">
|
||||
<li v-for="r in rows" :key="r.key">
|
||||
<component
|
||||
:is="r.link ? 'button' : 'div'"
|
||||
:type="r.link ? 'button' : undefined"
|
||||
class="flex h-8 w-full items-center gap-2 rounded-md px-2 text-left text-sm"
|
||||
:class="r.link ? 'hover:bg-accent' : ''"
|
||||
:title="`${kindLabel(r.e.kind)}: ${r.e.message}`"
|
||||
@click="r.link && openLink(r.link)"
|
||||
>
|
||||
<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>
|
||||
<StatusDot class="shrink-0" :tone="TONE[r.e.kind] ?? 'neutral'" size="md" />
|
||||
<span class="text-muted-foreground shrink-0 font-mono text-xs tabular-nums">{{ clock(r.e.time) }}</span>
|
||||
<span class="text-muted-foreground shrink-0">{{ kindLabel(r.e.kind) }}</span>
|
||||
<span class="min-w-0 flex-1 truncate">
|
||||
{{ subject(r.e) }}<span v-if="withMessage" class="text-muted-foreground hidden sm:inline"> · {{ r.e.message }}</span>
|
||||
</span>
|
||||
</component>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
|
||||
Reference in New Issue
Block a user