mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
feat(webui): models page
This commit is contained in:
@@ -39,6 +39,9 @@ async function sampleIds(page: Page, scenario: string): Promise<Record<string, s
|
||||
user: `user:${encodeURIComponent(scenario === 'limits-hot' ? hottestUser(usage.users) : usage.users[0].id)}`,
|
||||
group: `group:${encodeURIComponent(memberGroup.id)}`,
|
||||
model: `model:${encodeURIComponent(catalog.providers[0].models[0].id)}`,
|
||||
'routed-model': `model:${encodeURIComponent(catalog.routers[0].tiers[0].models[0])}`,
|
||||
'provider-degraded': `provider:${encodeURIComponent('amd')}`,
|
||||
'provider-open': `provider:${encodeURIComponent('alibaba')}`,
|
||||
router: `router:${encodeURIComponent(catalog.routers[0].name)}`,
|
||||
target: `target:${encodeURIComponent((targets.mcpServers[0] ?? targets.agents[0]).name)}`,
|
||||
}
|
||||
@@ -49,6 +52,9 @@ const PANEL_PAGES: Array<{ page: (typeof PAGE_IDS)[number]; kind: string; scenar
|
||||
{ page: 'users', kind: 'user', scenario: 'limits-hot' },
|
||||
{ page: 'users', kind: 'group', scenario: 'limits-hot' },
|
||||
{ page: 'models', kind: 'model' },
|
||||
{ page: 'models', kind: 'routed-model' },
|
||||
{ page: 'models', kind: 'provider-degraded' },
|
||||
{ page: 'models', kind: 'provider-open', scenario: 'breaker-open' },
|
||||
{ page: 'routers', kind: 'router' },
|
||||
{ page: 'targets', kind: 'target' },
|
||||
]
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ const PAGES: Record<PageId, Component> = {
|
||||
reliability: lazyPage(() => import('@/pages/ReliabilityPage.vue')),
|
||||
users: lazyPage(() => import('@/pages/UsersPage.vue')),
|
||||
models: lazyPage(() => import('@/pages/ModelsPage.vue')),
|
||||
routers: lazyPage(() => import('@/pages/ModelsPage.vue')),
|
||||
routers: lazyPage(() => import('@/pages/LegacyModelsPage.vue')),
|
||||
targets: lazyPage(() => import('@/pages/TargetsPage.vue')),
|
||||
events: lazyPage(() => import('@/pages/LegacyReliabilityPage.vue')),
|
||||
config: lazyPage(() => import('@/pages/ConfigPage.vue')),
|
||||
|
||||
@@ -15,7 +15,9 @@ import { isValidNonNegativeInt, modelMetaSnippet } from '@/lib/snippets'
|
||||
* discovered/override price (pricing.go: modelMetaFree short-circuits
|
||||
* before override/builtin/LiteLLM resolution).
|
||||
*/
|
||||
const modelId = ref('')
|
||||
/** Pre-fills the model id (a detail panel opens the form for its own model). */
|
||||
const props = defineProps<{ presetModelId?: string }>()
|
||||
const modelId = ref(props.presetModelId ?? '')
|
||||
const contextRaw = ref('')
|
||||
const free = ref(false)
|
||||
|
||||
|
||||
@@ -19,7 +19,9 @@ import { isValidNonNegative, pricingSnippet } from '@/lib/snippets'
|
||||
* together — a one-sided price makes no billing sense — unlike
|
||||
* ModelMetaForm.vue's independent contextTokens/free fields.
|
||||
*/
|
||||
const modelId = ref('')
|
||||
/** Pre-fills the model id (a detail panel opens the form for its own model). */
|
||||
const props = defineProps<{ presetModelId?: string }>()
|
||||
const modelId = ref(props.presetModelId ?? '')
|
||||
const inputRaw = ref('')
|
||||
const outputRaw = ref('')
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { groupByProvider, priceStatus, selectModels } from '@/lib/models-view'
|
||||
import type { ModelCatalogRow } from '@/lib/model-table-columns'
|
||||
|
||||
function row(id: string, over: Partial<ModelCatalogRow> = {}): ModelCatalogRow {
|
||||
const slash = id.indexOf('/')
|
||||
return {
|
||||
id,
|
||||
model: id.slice(slash + 1),
|
||||
providerName: id.slice(0, slash),
|
||||
kind: '',
|
||||
endpoint: false,
|
||||
priceSource: 'litellm',
|
||||
aliases: [],
|
||||
requests: 0,
|
||||
tokensIn: 0,
|
||||
tokensOut: 0,
|
||||
costMicroUsd: 0,
|
||||
attempts: 0,
|
||||
failures: 0,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
describe('priceStatus', () => {
|
||||
it('maps price sources to the three filter values', () => {
|
||||
expect(priceStatus(row('a/x', { priceSource: 'override' }))).toBe('priced')
|
||||
expect(priceStatus(row('a/x', { priceSource: 'unpriced' }))).toBe('unpriced')
|
||||
expect(priceStatus(row('a/x', { priceSource: 'free' }))).toBe('free')
|
||||
})
|
||||
it('gives endpoint pseudo-models no price status', () => {
|
||||
expect(priceStatus(row('a/x', { endpoint: true, priceSource: 'unpriced' }))).toBe('none')
|
||||
})
|
||||
})
|
||||
|
||||
describe('selectModels', () => {
|
||||
const rows = [
|
||||
row('a/one', { kind: 'embedding', priceSource: 'free' }),
|
||||
row('a/two', { priceSource: 'unpriced', aliases: ['fast'] }),
|
||||
row('b/three'),
|
||||
]
|
||||
it('returns every row for an empty selection', () => {
|
||||
expect(selectModels(rows, {})).toHaveLength(3)
|
||||
})
|
||||
it('combines provider, kind, price and text with AND', () => {
|
||||
expect(selectModels(rows, { provider: 'a' }).map((r) => r.id)).toEqual(['a/one', 'a/two'])
|
||||
expect(selectModels(rows, { kind: 'embedding' }).map((r) => r.id)).toEqual(['a/one'])
|
||||
expect(selectModels(rows, { price: 'unpriced' }).map((r) => r.id)).toEqual(['a/two'])
|
||||
expect(selectModels(rows, { q: 'FAST' }).map((r) => r.id)).toEqual(['a/two'])
|
||||
expect(selectModels(rows, { provider: 'b', price: 'unpriced' })).toEqual([])
|
||||
})
|
||||
it('treats kind "none" as the unlabelled models', () => {
|
||||
expect(selectModels(rows, { kind: 'none' }).map((r) => r.id)).toEqual(['a/two', 'b/three'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('groupByProvider', () => {
|
||||
it('groups in first-seen order with counts and request totals', () => {
|
||||
const g = groupByProvider([row('b/x', { requests: 2 }), row('a/y', { requests: 5 }), row('b/z', { requests: 3 })])
|
||||
expect(g.map((x) => [x.provider, x.rows.length, x.requests])).toEqual([
|
||||
['b', 2, 5],
|
||||
['a', 1, 5],
|
||||
])
|
||||
})
|
||||
it('sorts rows inside a group by requests then id', () => {
|
||||
const [g] = groupByProvider([row('a/b'), row('a/a'), row('a/c', { requests: 9 })])
|
||||
expect(g!.rows.map((r) => r.id)).toEqual(['a/c', 'a/a', 'a/b'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
import { filterModelRows } from '@/lib/model-filter'
|
||||
import type { ModelCatalogRow } from '@/lib/model-table-columns'
|
||||
|
||||
export type PriceStatus = 'priced' | 'unpriced' | 'free' | 'none'
|
||||
|
||||
/** Filter value for models with no kind label. */
|
||||
export const NO_KIND = 'none'
|
||||
|
||||
export interface ModelSelection {
|
||||
q?: string
|
||||
provider?: string
|
||||
kind?: string
|
||||
price?: string
|
||||
}
|
||||
|
||||
export interface ProviderGroup {
|
||||
provider: string
|
||||
rows: ModelCatalogRow[]
|
||||
requests: number
|
||||
}
|
||||
|
||||
/** Endpoint pseudo-models carry no price, so they are neither priced nor unpriced. */
|
||||
export function priceStatus(r: ModelCatalogRow): PriceStatus {
|
||||
if (r.endpoint) return 'none'
|
||||
if (r.priceSource === 'free') return 'free'
|
||||
return r.priceSource === 'unpriced' ? 'unpriced' : 'priced'
|
||||
}
|
||||
|
||||
export function selectModels(rows: ModelCatalogRow[], sel: ModelSelection): ModelCatalogRow[] {
|
||||
const byText = filterModelRows(rows, sel.q ?? '')
|
||||
return byText.filter(
|
||||
(r) =>
|
||||
(!sel.provider || r.providerName === sel.provider) &&
|
||||
(!sel.kind || (sel.kind === NO_KIND ? r.kind === '' : r.kind === sel.kind)) &&
|
||||
(!sel.price || priceStatus(r) === sel.price),
|
||||
)
|
||||
}
|
||||
|
||||
const byTraffic = (a: ModelCatalogRow, b: ModelCatalogRow): number => b.requests - a.requests || a.id.localeCompare(b.id)
|
||||
|
||||
/** One group per provider in first-seen order; rows busiest first. */
|
||||
export function groupByProvider(rows: ModelCatalogRow[]): ProviderGroup[] {
|
||||
const groups = new Map<string, ProviderGroup>()
|
||||
for (const r of rows) {
|
||||
let g = groups.get(r.providerName)
|
||||
if (!g) groups.set(r.providerName, (g = { provider: r.providerName, rows: [], requests: 0 }))
|
||||
g.rows.push(r)
|
||||
g.requests += r.requests
|
||||
}
|
||||
for (const g of groups.values()) g.rows.sort(byTraffic)
|
||||
return [...groups.values()]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { routersByModel } from '@/lib/router-index'
|
||||
import type { AdminRouterView } from '@/types/api'
|
||||
|
||||
function router(name: string, ...tiers: string[][]): AdminRouterView {
|
||||
return { name, tiers: tiers.map((models, i) => ({ name: `t${i}`, models, minScore: i })) } as unknown as AdminRouterView
|
||||
}
|
||||
|
||||
describe('routersByModel', () => {
|
||||
it('bare and canonical ids both indexed', () => {
|
||||
const idx = routersByModel([router('smartrouter/gx10', ['gx10/Qwen3.8-27B'], ['Inkling-2-Mini'])])
|
||||
expect(idx.get('gx10/Qwen3.8-27B')).toEqual(['smartrouter/gx10'])
|
||||
expect(idx.get('Qwen3.8-27B')).toEqual(['smartrouter/gx10'])
|
||||
expect(idx.get('Inkling-2-Mini')).toEqual(['smartrouter/gx10'])
|
||||
})
|
||||
|
||||
it('lists each router once per model, sorted by name', () => {
|
||||
const idx = routersByModel([router('b', ['p/m'], ['p/m']), router('a', ['p/m'])])
|
||||
expect(idx.get('p/m')).toEqual(['a', 'b'])
|
||||
})
|
||||
|
||||
it('keeps later slashes in the bare id', () => {
|
||||
const idx = routersByModel([router('r', ['openrouter/meta/llama'])])
|
||||
expect(idx.get('meta/llama')).toEqual(['r'])
|
||||
})
|
||||
|
||||
it('is empty for no routers or routers without tiers', () => {
|
||||
expect(routersByModel([]).size).toBe(0)
|
||||
expect(routersByModel(undefined).size).toBe(0)
|
||||
expect(routersByModel([{ name: 'x' } as unknown as AdminRouterView]).size).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import { splitModelId } from '@/lib/model-id'
|
||||
import type { AdminRouterView } from '@/types/api'
|
||||
|
||||
/** Router names per model id. A tier target is indexed as written and, when canonical, by its bare model id too, because configs list both forms. */
|
||||
export function routersByModel(routers: AdminRouterView[] | undefined): Map<string, string[]> {
|
||||
const index = new Map<string, Set<string>>()
|
||||
const add = (key: string, router: string): void => {
|
||||
let set = index.get(key)
|
||||
if (!set) index.set(key, (set = new Set()))
|
||||
set.add(router)
|
||||
}
|
||||
for (const r of routers ?? []) {
|
||||
for (const tier of r.tiers ?? []) {
|
||||
for (const target of tier.models) {
|
||||
add(target, r.name)
|
||||
const { provider, model } = splitModelId(target)
|
||||
if (provider) add(model, r.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Map([...index].map(([k, v]) => [k, [...v].sort()]))
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, watch } from 'vue'
|
||||
|
||||
import ModelCatalogTable from '@/components/ModelCatalogTable.vue'
|
||||
import ProviderHealthPanel from '@/components/ProviderHealthPanel.vue'
|
||||
import SmartRoutersCard from '@/components/SmartRoutersCard.vue'
|
||||
import { useFiltersStore } from '@/stores/filters'
|
||||
import { useModelsStore } from '@/stores/models'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
/**
|
||||
* ModelsPage (redesign-plan.md section 3.4, "Models & providers") — the
|
||||
* catalog table (ModelCatalogTable.vue), the Providers accordion moved
|
||||
* from the pre-redesign ProvidersView.vue (ProviderHealthPanel.vue, now
|
||||
* also carrying fleet-wide performance), and the model-alias table
|
||||
* (bundled into ProviderHealthPanel.vue — see that component's own doc
|
||||
* comment for why it stayed with the accordion it was already part of).
|
||||
*
|
||||
* Page params (redesign-plan.md section 3.1): `q` (free-text search,
|
||||
* ModelCatalogTable.vue's own SearchInput) and `model` (a canonical
|
||||
* "provider/model" id — EntityLink.vue's own deep-link target for a model
|
||||
* row elsewhere in the panel). Both are folded into the SAME `query`
|
||||
* computed getter/setter below (ConsumerDirectory.vue's own `usageQuery`
|
||||
* convention) — bound directly to nav.params rather than a local ref, so a
|
||||
* `q`/`model` change from anywhere else (a ProviderHealthPanel "view
|
||||
* models" link, browser back/forward, a hand-edited hash) is picked up
|
||||
* reactively instead of only once on mount.
|
||||
*/
|
||||
const filters = useFiltersStore()
|
||||
const models = useModelsStore()
|
||||
const nav = useNavStore()
|
||||
|
||||
const query = computed<string>({
|
||||
get: () => nav.params.q ?? nav.params.model ?? '',
|
||||
set: (value) => {
|
||||
// `query` is the single source of truth from here on — a stale
|
||||
// `model` param from a deep link is dropped (not merged forward),
|
||||
// since `q` now carries the exact same information. An empty
|
||||
// `value` is fine to pass straight through: buildHash
|
||||
// (lib/hash-state.ts) already omits an empty-string param from the
|
||||
// URL.
|
||||
const { model: _model, ...rest } = nav.params
|
||||
nav.goTo('models', { ...rest, q: value })
|
||||
},
|
||||
})
|
||||
|
||||
onMounted(() => void models.fetch())
|
||||
|
||||
watch(
|
||||
() => filters.range,
|
||||
() => void models.fetch(),
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<ProviderHealthPanel />
|
||||
<SmartRoutersCard v-if="models.routers.length > 0" :routers="models.routers" />
|
||||
<!-- verify-ui-states-2.md #8: shown only for a BACKGROUND failure
|
||||
(rows already on screen) — a first-load failure already renders via
|
||||
ModelCatalogTable's own ErrorState below, and showing both duplicated
|
||||
the same message twice. -->
|
||||
<p v-if="models.error && models.rows.length > 0" class="text-sm break-words text-destructive">{{ models.error }}</p>
|
||||
<ModelCatalogTable
|
||||
:rows="models.rows"
|
||||
:query="query"
|
||||
:latency-enabled="models.latencyEnabled"
|
||||
:loading="models.loading"
|
||||
:error="models.error"
|
||||
:on-retry="models.fetch"
|
||||
@update:query="query = $event"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
+276
-54
@@ -1,74 +1,296 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, watch } from 'vue'
|
||||
import { Badge, Card, CardAction, CardContent, CardHeader, CardTitle, FilterBar, Pagination, SearchInput, StatusDot } from '@perfect-design/ui'
|
||||
import type { FilterField, FilterItem } from '@perfect-design/ui'
|
||||
import { computed, onMounted, reactive, watch } from 'vue'
|
||||
|
||||
import ModelCatalogTable from '@/components/ModelCatalogTable.vue'
|
||||
import ProviderHealthPanel from '@/components/ProviderHealthPanel.vue'
|
||||
import SmartRoutersCard from '@/components/SmartRoutersCard.vue'
|
||||
import { formatCompactCount, formatContextWindow, formatModelCostHover } from '@/lib/format'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { NO_KIND, groupByProvider, priceStatus, selectModels } from '@/lib/models-view'
|
||||
import type { ModelSelection, PriceStatus } from '@/lib/models-view'
|
||||
import { pageWindow } from '@/lib/paging'
|
||||
import { resolveSel } from '@/lib/panel-selection'
|
||||
import { breakerRows, providerRateStatus, providerSuccessRate } from '@/lib/provider-rate'
|
||||
import type { BreakerRow } from '@/lib/provider-rate'
|
||||
import { routersByModel } from '@/lib/router-index'
|
||||
import { wbColumns } from '@/lib/wb-columns'
|
||||
import ModelPanel from '@/panels/ModelPanel.vue'
|
||||
import ProviderPanel from '@/panels/ProviderPanel.vue'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useFiltersStore } from '@/stores/filters'
|
||||
import { useModelsStore } from '@/stores/models'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
import StateView from '@/widgets/StateView.vue'
|
||||
import type { ViewState } from '@/widgets/StateView.vue'
|
||||
import WbTable from '@/widgets/WbTable.vue'
|
||||
|
||||
/**
|
||||
* ModelsPage (redesign-plan.md section 3.4, "Models & providers") — the
|
||||
* catalog table (ModelCatalogTable.vue), the Providers accordion moved
|
||||
* from the pre-redesign ProvidersView.vue (ProviderHealthPanel.vue, now
|
||||
* also carrying fleet-wide performance), and the model-alias table
|
||||
* (bundled into ProviderHealthPanel.vue — see that component's own doc
|
||||
* comment for why it stayed with the accordion it was already part of).
|
||||
*
|
||||
* Page params (redesign-plan.md section 3.1): `q` (free-text search,
|
||||
* ModelCatalogTable.vue's own SearchInput) and `model` (a canonical
|
||||
* "provider/model" id — EntityLink.vue's own deep-link target for a model
|
||||
* row elsewhere in the panel). Both are folded into the SAME `query`
|
||||
* computed getter/setter below (ConsumerDirectory.vue's own `usageQuery`
|
||||
* convention) — bound directly to nav.params rather than a local ref, so a
|
||||
* `q`/`model` change from anywhere else (a ProviderHealthPanel "view
|
||||
* models" link, browser back/forward, a hand-edited hash) is picked up
|
||||
* reactively instead of only once on mount.
|
||||
*/
|
||||
const PAGE_SIZE = 12
|
||||
const ROUTER_BADGES = 2
|
||||
const FILTER_KEYS = ['provider', 'kind', 'price'] as const
|
||||
type FilterKey = (typeof FILTER_KEYS)[number]
|
||||
const PRICE_OPTIONS: Array<{ value: PriceStatus; label: string }> = [
|
||||
{ value: 'priced', label: 'Priced' },
|
||||
{ value: 'unpriced', label: 'Unpriced' },
|
||||
{ value: 'free', label: 'Free' },
|
||||
]
|
||||
const HEALTH_TONE = { healthy: 'success', degraded: 'warning', severe: 'danger' } as const
|
||||
const BREAKER_TONE = { closed: 'success', open: 'danger', 'half-open': 'warning', degraded: 'warning' } as const
|
||||
|
||||
interface Row {
|
||||
id: string
|
||||
name: string
|
||||
kind: string
|
||||
context: number | null
|
||||
price: PriceStatus
|
||||
priceTitle: string
|
||||
requests: number
|
||||
health: number | null
|
||||
healthTone: 'success' | 'warning' | 'danger' | null
|
||||
routers: string[]
|
||||
}
|
||||
|
||||
const dashboard = useDashboardStore()
|
||||
const filters = useFiltersStore()
|
||||
const models = useModelsStore()
|
||||
const nav = useNavStore()
|
||||
|
||||
const query = computed<string>({
|
||||
get: () => nav.params.q ?? nav.params.model ?? '',
|
||||
set: (value) => {
|
||||
// `query` is the single source of truth from here on — a stale
|
||||
// `model` param from a deep link is dropped (not merged forward),
|
||||
// since `q` now carries the exact same information. An empty
|
||||
// `value` is fine to pass straight through: buildHash
|
||||
// (lib/hash-state.ts) already omits an empty-string param from the
|
||||
// URL.
|
||||
const { model: _model, ...rest } = nav.params
|
||||
nav.goTo('models', { ...rest, q: value })
|
||||
},
|
||||
})
|
||||
|
||||
onMounted(() => void models.fetch())
|
||||
|
||||
watch(
|
||||
() => filters.range,
|
||||
() => void models.fetch(),
|
||||
)
|
||||
|
||||
// --- Filters (hash params q, provider, kind, price) ------------------------------
|
||||
|
||||
function setParams(patch: Record<string, string>): void {
|
||||
const next = { ...nav.params }
|
||||
for (const [k, v] of Object.entries(patch)) {
|
||||
if (v === '') delete next[k]
|
||||
else next[k] = v
|
||||
}
|
||||
nav.goTo('models', next)
|
||||
}
|
||||
|
||||
const query = computed<string>({
|
||||
get: () => nav.params.q ?? '',
|
||||
set: (v) => setParams({ q: v }),
|
||||
})
|
||||
const selection = computed<ModelSelection>(() => ({
|
||||
q: query.value,
|
||||
provider: nav.params.provider,
|
||||
kind: nav.params.kind,
|
||||
price: nav.params.price,
|
||||
}))
|
||||
const filtering = computed(() => query.value.trim() !== '' || FILTER_KEYS.some((k) => nav.params[k]))
|
||||
|
||||
const overviewProviders = computed(() => dashboard.overview?.providers ?? [])
|
||||
const fields = computed<FilterField[]>(() => {
|
||||
const kinds = [...new Set(models.rows.map((r) => r.kind).filter((k) => k !== ''))].sort()
|
||||
const providers = [...new Set([...overviewProviders.value.map((p) => p.name), ...models.rows.map((r) => r.providerName)])].sort()
|
||||
return [
|
||||
{ id: 'provider', label: 'Provider', type: 'select', operators: ['eq'], options: providers.map((p) => ({ value: p, label: p })) },
|
||||
{ id: 'kind', label: 'Kind', type: 'select', operators: ['eq'], options: [{ value: NO_KIND, label: 'No kind' }, ...kinds.map((k) => ({ value: k, label: k }))] },
|
||||
{ id: 'price', label: 'Price', type: 'select', operators: ['eq'], options: PRICE_OPTIONS },
|
||||
]
|
||||
})
|
||||
const filterItems = computed<FilterItem[]>(() =>
|
||||
FILTER_KEYS.filter((k) => nav.params[k]).map((k) => ({ id: k, field: k, operator: 'eq', value: nav.params[k]! })),
|
||||
)
|
||||
function applyFilters(items: FilterItem[]): void {
|
||||
const patch: Record<string, string> = { provider: '', kind: '', price: '' }
|
||||
for (const it of items) {
|
||||
if ((FILTER_KEYS as readonly string[]).includes(it.field) && typeof it.value === 'string') patch[it.field as FilterKey] = it.value
|
||||
}
|
||||
setParams(patch)
|
||||
}
|
||||
|
||||
// --- Rows and groups ---------------------------------------------------------------
|
||||
|
||||
const selected = computed(() => selectModels(models.rows, selection.value))
|
||||
const routerIndex = computed(() => routersByModel(models.routers))
|
||||
const providerViews = computed(() => new Map(overviewProviders.value.map((p) => [p.name, p])))
|
||||
const breakers = computed(() => new Map(breakerRows(dashboard.overview).map((b) => [b.provider, b])))
|
||||
|
||||
const groups = computed(() => {
|
||||
const grouped = groupByProvider(selected.value)
|
||||
if (!filtering.value) {
|
||||
const seen = new Set(grouped.map((g) => g.provider))
|
||||
for (const p of overviewProviders.value) if (!seen.has(p.name)) grouped.push({ provider: p.name, rows: [], requests: 0 })
|
||||
}
|
||||
return grouped.sort((a, b) => b.requests - a.requests || a.provider.localeCompare(b.provider))
|
||||
})
|
||||
|
||||
function breakerStatus(provider: string): keyof typeof BREAKER_TONE {
|
||||
const b: BreakerRow | undefined = breakers.value.get(provider)
|
||||
if (!b) return 'closed'
|
||||
return b.degraded ? 'degraded' : b.state
|
||||
}
|
||||
|
||||
function toRow(r: (typeof models.rows)[number]): Row {
|
||||
const rate = providerViews.value.get(r.providerName)?.modelRates?.[r.model]
|
||||
const success = rate ? providerSuccessRate(rate.attemptsDay, rate.failuresDay) : null
|
||||
const status = providerRateStatus(success)
|
||||
const known = r.inputPerMTokUsd !== undefined && r.outputPerMTokUsd !== undefined
|
||||
const routers = [...new Set([...(r.routers ?? []), ...(routerIndex.value.get(r.id) ?? [])])]
|
||||
return {
|
||||
id: r.id,
|
||||
name: r.model,
|
||||
kind: r.kind,
|
||||
context: r.contextTokens ?? null,
|
||||
price: priceStatus(r),
|
||||
priceTitle: known ? formatModelCostHover(r.inputPerMTokUsd as number, r.outputPerMTokUsd as number) : r.priceSource,
|
||||
requests: r.requests,
|
||||
health: success === null ? null : Math.round(success * 1000) / 10,
|
||||
healthTone: status === 'no-traffic' ? null : HEALTH_TONE[status],
|
||||
routers,
|
||||
}
|
||||
}
|
||||
|
||||
const columns = wbColumns<Row>([
|
||||
{ key: 'name', header: 'Model', kind: 'text' },
|
||||
{ key: 'kind', header: 'Kind', kind: 'text' },
|
||||
{ key: 'context', header: 'Context', kind: 'number' },
|
||||
{ key: 'price', header: 'Price', kind: 'text' },
|
||||
{ key: 'requests', header: 'Requests', kind: 'number' },
|
||||
{ key: 'health', header: 'Health', kind: 'number', sortable: false },
|
||||
{ key: 'routers', header: 'Routers', kind: 'text', sortable: false },
|
||||
])
|
||||
|
||||
// --- Expansion and per-group paging ------------------------------------------------
|
||||
|
||||
const toggled = reactive(new Map<string, boolean>())
|
||||
const pages = reactive(new Map<string, number>())
|
||||
watch([selection], () => {
|
||||
toggled.clear()
|
||||
pages.clear()
|
||||
})
|
||||
|
||||
function isOpen(provider: string, index: number, count: number): boolean {
|
||||
if (count === 0) return false
|
||||
return toggled.get(provider) ?? (filtering.value || index === 0)
|
||||
}
|
||||
function toggle(provider: string, open: boolean): void {
|
||||
toggled.set(provider, !open)
|
||||
}
|
||||
function pageOf(provider: string, total: number): number {
|
||||
return pageWindow(total, PAGE_SIZE, (pages.get(provider) ?? 1) - 1).index + 1
|
||||
}
|
||||
function rowsOf(g: (typeof groups.value)[number]): Row[] {
|
||||
const w = pageWindow(g.rows.length, PAGE_SIZE, pageOf(g.provider, g.rows.length) - 1)
|
||||
return g.rows.slice(w.from, w.to).map(toRow)
|
||||
}
|
||||
|
||||
// --- State, selection ----------------------------------------------------------------
|
||||
|
||||
const state = computed<ViewState>(() => {
|
||||
const s = loadState({ loading: models.lastUpdated === null, hasData: models.lastUpdated !== null, error: models.error })
|
||||
if (s === 'skeleton') return 'loading'
|
||||
if (s === 'error') return 'error'
|
||||
return groups.value.length === 0 ? 'empty' : 'ready'
|
||||
})
|
||||
const emptyTitle = computed(() => (filtering.value ? 'No models match these filters' : 'No models configured'))
|
||||
const summary = computed(() => `${selected.value.length.toLocaleString('en-US')} models · ${groups.value.length.toLocaleString('en-US')} providers`)
|
||||
|
||||
const sel = computed(() => nav.selection)
|
||||
const activeModel = computed(() => (sel.value?.kind === 'model' ? sel.value.id : null))
|
||||
|
||||
function exists(kind: string, id: string): boolean {
|
||||
if (kind === 'model') return models.rows.some((r) => r.id === id)
|
||||
if (kind === 'provider') return providerViews.value.has(id) || models.rows.some((r) => r.providerName === id)
|
||||
return false
|
||||
}
|
||||
watch(
|
||||
[sel, () => models.lastUpdated, () => dashboard.overview],
|
||||
([s, loaded, overview]) => {
|
||||
if (!s || loaded === null || !overview) return
|
||||
if (resolveSel(s, exists) === null) nav.closePanel()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
const openSel = computed(() => (models.lastUpdated !== null && dashboard.overview ? resolveSel(sel.value, exists) : null))
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<ProviderHealthPanel />
|
||||
<SmartRoutersCard v-if="models.routers.length > 0" :routers="models.routers" />
|
||||
<!-- verify-ui-states-2.md #8: shown only for a BACKGROUND failure
|
||||
(rows already on screen) — a first-load failure already renders via
|
||||
ModelCatalogTable's own ErrorState below, and showing both duplicated
|
||||
the same message twice. -->
|
||||
<p v-if="models.error && models.rows.length > 0" class="text-sm break-words text-destructive">{{ models.error }}</p>
|
||||
<ModelCatalogTable
|
||||
:rows="models.rows"
|
||||
:query="query"
|
||||
:latency-enabled="models.latencyEnabled"
|
||||
:loading="models.loading"
|
||||
:error="models.error"
|
||||
:on-retry="models.fetch"
|
||||
@update:query="query = $event"
|
||||
/>
|
||||
<div class="flex flex-col gap-4">
|
||||
<Card size="sm">
|
||||
<CardHeader class="items-center">
|
||||
<CardTitle>Models & providers</CardTitle>
|
||||
<CardAction class="text-muted-foreground self-center text-xs">{{ summary }}</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-2">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<SearchInput v-model="query" size="sm" class="w-full max-w-xs" placeholder="Filter by model or alias" aria-label="Filter models" />
|
||||
<FilterBar :model-value="filterItems" :fields="fields" variant="compact" size="sm" clearable @update:model-value="applyFilters" />
|
||||
</div>
|
||||
<StateView :state="state" :empty-title="emptyTitle" :error-message="models.error" :updated-at="models.lastUpdated ?? undefined" @retry="models.fetch()">
|
||||
<div class="flex flex-col gap-2">
|
||||
<section v-for="(g, i) in groups" :key="g.provider" class="rounded-md border" :aria-label="`${g.provider} models`">
|
||||
<div class="bg-muted/40 flex h-8 items-center gap-2 px-3 text-sm">
|
||||
<button
|
||||
type="button"
|
||||
class="text-muted-foreground hover:text-foreground flex size-5 shrink-0 items-center justify-center rounded disabled:opacity-40"
|
||||
:aria-expanded="isOpen(g.provider, i, g.rows.length)"
|
||||
:aria-label="`${isOpen(g.provider, i, g.rows.length) ? 'Collapse' : 'Expand'} ${g.provider} models`"
|
||||
:disabled="g.rows.length === 0"
|
||||
@click="toggle(g.provider, isOpen(g.provider, i, g.rows.length))"
|
||||
>
|
||||
<span aria-hidden="true" class="inline-block transition-transform" :class="isOpen(g.provider, i, g.rows.length) ? 'rotate-90' : ''">›</span>
|
||||
</button>
|
||||
<button type="button" class="hover:underline min-w-0 truncate font-mono font-medium" :aria-label="`Open provider ${g.provider}`" @click="nav.openPanel('provider', g.provider)">
|
||||
{{ g.provider }}
|
||||
</button>
|
||||
<StatusDot :tone="BREAKER_TONE[breakerStatus(g.provider)]" size="md" class="shrink-0" />
|
||||
<span v-if="breakerStatus(g.provider) !== 'closed'" class="text-muted-foreground shrink-0 text-xs">{{ breakerStatus(g.provider) }}</span>
|
||||
<span class="text-muted-foreground ml-auto shrink-0 font-mono text-xs tabular-nums">{{ g.rows.length.toLocaleString('en-US') }} models</span>
|
||||
<span class="text-muted-foreground hidden shrink-0 font-mono text-xs tabular-nums sm:inline">{{ formatCompactCount(g.requests) }} req</span>
|
||||
</div>
|
||||
<div v-if="isOpen(g.provider, i, g.rows.length)" class="flex flex-col gap-2 p-1">
|
||||
<WbTable
|
||||
:columns="columns"
|
||||
:rows="rowsOf(g)"
|
||||
row-key="id"
|
||||
:active-key="activeModel"
|
||||
:label="`${g.provider} models`"
|
||||
@row-activate="(row: Row) => nav.openPanel('model', row.id)"
|
||||
>
|
||||
<template #cell-name="{ row }">
|
||||
<span class="wb-model" :title="(row as Row).id"><span class="wb-model-name">{{ (row as Row).name }}</span></span>
|
||||
</template>
|
||||
<template #cell-kind="{ value }">
|
||||
<span :class="value ? '' : 'text-muted-foreground'">{{ value || '—' }}</span>
|
||||
</template>
|
||||
<template #cell-context="{ value }">{{ value === null ? '—' : formatContextWindow(value as number) }}</template>
|
||||
<template #cell-price="{ row }">
|
||||
<Badge :tone="(row as Row).price === 'unpriced' ? 'warning' : 'neutral'" variant="outline" size="sm" :title="(row as Row).priceTitle">{{ (row as Row).price === 'none' ? '—' : (row as Row).price }}</Badge>
|
||||
</template>
|
||||
<template #cell-requests="{ value }">{{ formatCompactCount(value as number) }}</template>
|
||||
<template #cell-health="{ row }">
|
||||
<span v-if="(row as Row).health === null" class="text-muted-foreground">—</span>
|
||||
<span v-else class="inline-flex items-center justify-end gap-1.5">
|
||||
<StatusDot v-if="(row as Row).healthTone" :tone="(row as Row).healthTone!" size="md" />
|
||||
{{ (row as Row).health }}%
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-routers="{ value }">
|
||||
<span v-if="(value as string[]).length === 0" class="text-muted-foreground">—</span>
|
||||
<span v-else class="flex items-center gap-1" :title="(value as string[]).join(', ')">
|
||||
<Badge v-for="r in (value as string[]).slice(0, ROUTER_BADGES)" :key="r" tone="info" variant="outline" size="sm" class="max-w-44 truncate font-mono">{{ r }}</Badge>
|
||||
<span v-if="(value as string[]).length > ROUTER_BADGES" class="text-muted-foreground text-xs">+{{ (value as string[]).length - ROUTER_BADGES }}</span>
|
||||
</span>
|
||||
</template>
|
||||
</WbTable>
|
||||
<div v-if="g.rows.length > PAGE_SIZE" class="flex items-center justify-between gap-2 px-2 pb-1">
|
||||
<span class="text-muted-foreground text-xs">{{ g.rows.length.toLocaleString('en-US') }} models</span>
|
||||
<Pagination :page="pageOf(g.provider, g.rows.length)" :total="g.rows.length" :page-size="PAGE_SIZE" variant="compact" size="sm" @update:page="pages.set(g.provider, $event)" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</StateView>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ModelPanel v-if="openSel?.kind === 'model'" :id="openSel.id" @close="nav.closePanel()" />
|
||||
<ProviderPanel v-else-if="openSel?.kind === 'provider'" :id="openSel.id" @close="nav.closePanel()" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
<script setup lang="ts">
|
||||
import { Badge, Button, DescriptionItem, DescriptionList, Sparkline } from '@perfect-design/ui'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
|
||||
import ModelMetaForm from '@/components/forms/ModelMetaForm.vue'
|
||||
import PricingForm from '@/components/forms/PricingForm.vue'
|
||||
import { adminFetch, isAuthRejection, messageOf } from '@/lib/api'
|
||||
import { formatCompactCount, formatContextWindow, formatLatencyMs, formatModelCostHover } from '@/lib/format'
|
||||
import { priceStatus } from '@/lib/models-view'
|
||||
import { formatSel } from '@/lib/panel-selection'
|
||||
import { providerRateStatus, providerSuccessRate } from '@/lib/provider-rate'
|
||||
import { seriesUrl } from '@/lib/range'
|
||||
import { routersByModel } from '@/lib/router-index'
|
||||
import { useFiltersStore } from '@/stores/filters'
|
||||
import { useModelsStore } from '@/stores/models'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
import type { AdminSeriesResponse } 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 MIN_SPARK_POINTS = 2
|
||||
const SPARK_WIDTH = 440
|
||||
const SPARK_HEIGHT = 40
|
||||
const PRICE_SOURCE_NOTE: Record<string, string> = {
|
||||
override: 'pricing override in config',
|
||||
builtin: 'built-in price table',
|
||||
litellm: 'LiteLLM price table',
|
||||
free: 'configured free (modelMeta.free)',
|
||||
unpriced: 'no pricing rule matched, billed as $0',
|
||||
}
|
||||
type Snippet = 'meta' | 'price' | null
|
||||
|
||||
const props = defineProps<{ id: string }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const filters = useFiltersStore()
|
||||
const models = useModelsStore()
|
||||
const nav = useNavStore()
|
||||
|
||||
const row = computed(() => models.rows.find((r) => r.id === props.id))
|
||||
const routers = computed(() => {
|
||||
const r = row.value
|
||||
if (!r) return []
|
||||
const index = routersByModel(models.routers)
|
||||
return [...new Set([...(r.routers ?? []), ...(index.get(r.id) ?? [])])].sort()
|
||||
})
|
||||
const status = computed(() => (row.value ? priceStatus(row.value) : 'none'))
|
||||
const priced = computed(() => row.value?.inputPerMTokUsd !== undefined && row.value?.outputPerMTokUsd !== undefined)
|
||||
const successRate = computed(() => (row.value ? providerSuccessRate(row.value.attempts, row.value.failures) : null))
|
||||
|
||||
// --- Usage over the range ----------------------------------------------------------
|
||||
|
||||
const points = ref<number[]>([])
|
||||
const seriesLoading = ref(true)
|
||||
const seriesError = ref('')
|
||||
let reqId = 0
|
||||
|
||||
async function loadSeries(): Promise<void> {
|
||||
const id = ++reqId
|
||||
seriesLoading.value = true
|
||||
try {
|
||||
const res = await adminFetch<AdminSeriesResponse>(seriesUrl({ scope: [`model:${props.id}`], metric: 'req', window: filters.window, span: filters.span }))
|
||||
if (id !== reqId) return
|
||||
points.value = res.series.find((s) => s.scope === `model:${props.id}`)?.points ?? []
|
||||
seriesError.value = ''
|
||||
} catch (err) {
|
||||
if (id !== reqId || isAuthRejection(err)) return
|
||||
points.value = []
|
||||
seriesError.value = messageOf(err)
|
||||
} finally {
|
||||
if (id === reqId) seriesLoading.value = false
|
||||
}
|
||||
}
|
||||
const total = computed(() => points.value.reduce((a, v) => a + v, 0))
|
||||
const sparkState = computed<ViewState>(() => {
|
||||
if (seriesLoading.value && points.value.length === 0) return 'loading'
|
||||
if (seriesError.value) return 'error'
|
||||
return points.value.length >= MIN_SPARK_POINTS && total.value > 0 ? 'ready' : 'empty'
|
||||
})
|
||||
|
||||
watch(() => [props.id, filters.range], () => void loadSeries())
|
||||
onMounted(() => void loadSeries())
|
||||
|
||||
// --- Snippets ------------------------------------------------------------------------
|
||||
|
||||
const snippet = ref<Snippet>(null)
|
||||
watch(() => props.id, () => (snippet.value = null))
|
||||
|
||||
const usd = (v: number): string => `$${v.toFixed(2)}`
|
||||
|
||||
function openRouter(name: string): void {
|
||||
nav.goTo('routers', { sel: formatSel('router', name) }, { replace: false })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DetailPanel kind="model" :id="id" :title="id" @close="emit('close')">
|
||||
<div class="flex flex-col divide-y px-1 pb-4" data-testid="model-panel">
|
||||
<div v-if="!row" class="text-muted-foreground py-3 text-sm">This model is no longer in the catalog.</div>
|
||||
<template v-else>
|
||||
<PanelSection title="Meta">
|
||||
<DescriptionList variant="inline" size="sm" density="compact">
|
||||
<DescriptionItem term="Provider">
|
||||
<button type="button" class="hover:underline font-mono" @click="nav.openPanel('provider', row.providerName)">{{ row.providerName }}</button>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Model"><span class="font-mono break-all">{{ row.model }}</span></DescriptionItem>
|
||||
<DescriptionItem term="Kind">{{ row.kind || '—' }}</DescriptionItem>
|
||||
<DescriptionItem v-if="row.endpoint" term="Type">endpoint path, not a routable model</DescriptionItem>
|
||||
<DescriptionItem term="Context window">
|
||||
<span class="font-mono tabular-nums">{{ row.contextTokens !== undefined ? formatContextWindow(row.contextTokens) : '—' }}</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Aliases">
|
||||
<span v-if="row.aliases.length === 0" class="text-muted-foreground">none</span>
|
||||
<span v-else class="flex flex-wrap justify-end gap-1">
|
||||
<Badge v-for="a in row.aliases" :key="a" tone="neutral" variant="outline" size="sm" class="font-mono">{{ a }}</Badge>
|
||||
</span>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Price">
|
||||
<DescriptionList variant="inline" size="sm" density="compact">
|
||||
<DescriptionItem term="Source">
|
||||
<span class="flex flex-col items-end text-right">
|
||||
<Badge :tone="status === 'unpriced' ? 'warning' : 'neutral'" variant="outline" size="sm">{{ row.priceSource }}</Badge>
|
||||
<span class="text-muted-foreground text-xs">{{ PRICE_SOURCE_NOTE[row.priceSource] }}</span>
|
||||
</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Input per MTok">
|
||||
<span class="font-mono tabular-nums">{{ priced ? usd(row.inputPerMTokUsd as number) : '—' }}</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Output per MTok">
|
||||
<span class="font-mono tabular-nums">{{ priced ? usd(row.outputPerMTokUsd as number) : '—' }}</span>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
<p v-if="priced" class="text-muted-foreground m-0 text-xs">{{ formatModelCostHover(row.inputPerMTokUsd as number, row.outputPerMTokUsd as number) }}</p>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Usage in range">
|
||||
<DescriptionList variant="inline" size="sm" density="compact">
|
||||
<DescriptionItem term="Requests"><span class="font-mono tabular-nums">{{ formatCompactCount(row.requests) }}</span></DescriptionItem>
|
||||
<DescriptionItem term="Tokens in / out">
|
||||
<span class="font-mono tabular-nums">{{ formatCompactCount(row.tokensIn) }} / {{ formatCompactCount(row.tokensOut) }}</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Latency p50 / p95">
|
||||
<span class="font-mono tabular-nums">{{ row.p50Ms !== undefined ? formatLatencyMs(row.p50Ms) : '—' }} / {{ row.p95Ms !== undefined ? formatLatencyMs(row.p95Ms) : '—' }}</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Success rate">
|
||||
<span class="font-mono tabular-nums">{{ successRate === null ? '—' : `${Math.round(successRate * 1000) / 10}% (${providerRateStatus(successRate)})` }}</span>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
<StateView :state="sparkState" empty-title="No traffic in this range" :error-message="seriesError" :rows="1" @retry="loadSeries()">
|
||||
<Sparkline :data="points" variant="area" :width="SPARK_WIDTH" :height="SPARK_HEIGHT" class="h-10 w-full" label="Requests per bucket over the selected range" />
|
||||
</StateView>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Routers">
|
||||
<p v-if="routers.length === 0" class="text-muted-foreground m-0 text-sm">No smart router targets this model.</p>
|
||||
<ul v-else class="m-0 flex list-none flex-col p-0" aria-label="Routers using this model">
|
||||
<li v-for="r in routers" :key="r" class="flex h-8 items-center">
|
||||
<button type="button" class="hover:bg-accent w-full truncate rounded px-2 text-left font-mono text-sm" @click="openRouter(r)">{{ r }}</button>
|
||||
</li>
|
||||
</ul>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Change model settings">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<Button variant="outline" size="sm" :aria-expanded="snippet === 'meta'" @click="snippet = snippet === 'meta' ? null : 'meta'">
|
||||
{{ snippet === 'meta' ? 'Hide metadata snippet' : 'Generate metadata snippet' }}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" :aria-expanded="snippet === 'price'" @click="snippet = snippet === 'price' ? null : 'price'">
|
||||
{{ snippet === 'price' ? 'Hide price snippet' : 'Generate price override snippet' }}
|
||||
</Button>
|
||||
</div>
|
||||
<ModelMetaForm v-if="snippet === 'meta'" :preset-model-id="id" />
|
||||
<PricingForm v-else-if="snippet === 'price'" :preset-model-id="id" />
|
||||
</PanelSection>
|
||||
</template>
|
||||
</div>
|
||||
</DetailPanel>
|
||||
</template>
|
||||
@@ -0,0 +1,115 @@
|
||||
<script setup lang="ts">
|
||||
import { Button, DescriptionItem, DescriptionList, StatusBadge } from '@perfect-design/ui'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
import { copyText } from '@/lib/clipboard'
|
||||
import { formatAgo, formatCompactCount, formatLatencyMs, formatUntil } from '@/lib/format'
|
||||
import { breakerRows, providerRateStatus, providerSuccessRate } from '@/lib/provider-rate'
|
||||
import { useCopyFeedback } from '@/composables/useCopyFeedback'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useModelsStore } from '@/stores/models'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
import DetailPanel from '@/widgets/DetailPanel.vue'
|
||||
import PanelSection from '@/widgets/PanelSection.vue'
|
||||
|
||||
const MODEL_ROWS = 12
|
||||
const STATE_TONE = { closed: 'success', open: 'danger', 'half-open': 'warning', degraded: 'warning' } as const
|
||||
|
||||
const props = defineProps<{ id: string }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const dashboard = useDashboardStore()
|
||||
const models = useModelsStore()
|
||||
const nav = useNavStore()
|
||||
const copy = useCopyFeedback()
|
||||
const urlEl = ref<HTMLElement | null>(null)
|
||||
|
||||
const provider = computed(() => dashboard.overview?.providers.find((p) => p.name === props.id))
|
||||
const breaker = computed(() => breakerRows(dashboard.overview).find((b) => b.provider === props.id))
|
||||
const status = computed(() => (breaker.value?.degraded ? 'degraded' : (breaker.value?.state ?? 'closed')))
|
||||
const until = computed(() => formatUntil(breaker.value?.openUntil))
|
||||
|
||||
const lastDiscovery = computed(() => formatAgo(provider.value?.lastRefresh).trim().slice(1, -1) || '—')
|
||||
const perf = computed(() => models.providerPerf.find((r) => r.id === props.id))
|
||||
const successRate = computed(() => providerSuccessRate(provider.value?.attemptsDay ?? 0, provider.value?.failuresDay ?? 0))
|
||||
|
||||
const providerModels = computed(() =>
|
||||
models.rows.filter((r) => r.providerName === props.id).sort((a, b) => b.requests - a.requests || a.id.localeCompare(b.id)),
|
||||
)
|
||||
const shownModels = computed(() => providerModels.value.slice(0, MODEL_ROWS))
|
||||
const hiddenModels = computed(() => providerModels.value.length - shownModels.value.length)
|
||||
|
||||
async function copyUrl(): Promise<void> {
|
||||
copy.set(await copyText(provider.value?.baseUrl ?? '', urlEl.value ?? undefined))
|
||||
}
|
||||
const COPY_LABEL = { idle: 'Copy', copied: 'Copied', selected: 'Selected', failed: 'Copy failed' } as const
|
||||
|
||||
function showAll(): void {
|
||||
nav.goTo('models', { provider: props.id })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DetailPanel kind="provider" :id="id" :title="id" @close="emit('close')">
|
||||
<div class="flex flex-col divide-y px-1 pb-4" data-testid="provider-panel">
|
||||
<div v-if="!provider" class="text-muted-foreground py-3 text-sm">This provider is not configured.</div>
|
||||
<template v-else>
|
||||
<PanelSection title="Health">
|
||||
<DescriptionList variant="inline" size="sm" density="compact">
|
||||
<DescriptionItem term="Breaker">
|
||||
<StatusBadge :status="status" :tones="STATE_TONE" size="sm" />
|
||||
</DescriptionItem>
|
||||
<DescriptionItem v-if="until" term="Next probe"><span class="font-mono tabular-nums">{{ until }}</span></DescriptionItem>
|
||||
<DescriptionItem term="Success today">
|
||||
<span class="font-mono tabular-nums">
|
||||
{{ successRate === null ? 'no traffic' : `${Math.round(successRate * 1000) / 10}% (${providerRateStatus(successRate)})` }}
|
||||
</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Attempts / failures">
|
||||
<span class="font-mono tabular-nums">{{ formatCompactCount(provider.attemptsDay) }} / {{ formatCompactCount(provider.failuresDay) }}</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Last discovery">{{ provider.discoveryEnabled ? lastDiscovery : 'discovery off' }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Last error">
|
||||
<p v-if="provider.lastErr" class="text-destructive m-0 text-sm break-words whitespace-pre-wrap" data-testid="provider-last-err">{{ provider.lastErr }}</p>
|
||||
<p v-else class="text-muted-foreground m-0 text-sm">No error recorded.</p>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Latency (time to first byte)">
|
||||
<DescriptionList v-if="perf?.ttfbP50Ms !== undefined || perf?.ttfbP95Ms !== undefined" variant="inline" size="sm" density="compact">
|
||||
<DescriptionItem term="p50"><span class="font-mono tabular-nums">{{ perf?.ttfbP50Ms !== undefined ? formatLatencyMs(perf.ttfbP50Ms) : '—' }}</span></DescriptionItem>
|
||||
<DescriptionItem term="p95"><span class="font-mono tabular-nums">{{ perf?.ttfbP95Ms !== undefined ? formatLatencyMs(perf.ttfbP95Ms) : '—' }}</span></DescriptionItem>
|
||||
</DescriptionList>
|
||||
<p v-else-if="!models.latencyEnabled" class="text-muted-foreground m-0 text-sm">Latency stats are off. Enable admin.stats.latency to record them.</p>
|
||||
<p v-else class="text-muted-foreground m-0 text-sm">No latency samples for this provider in the range.</p>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Models">
|
||||
<p v-if="providerModels.length === 0" class="text-muted-foreground m-0 text-sm">No models listed for this provider.</p>
|
||||
<template v-else>
|
||||
<ul class="m-0 flex list-none flex-col p-0" aria-label="Provider models">
|
||||
<li v-for="m in shownModels" :key="m.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="m.id" @click="nav.openPanel('model', m.id)">
|
||||
<span class="min-w-0 truncate">{{ m.model }}</span>
|
||||
<span class="shrink-0 font-mono text-xs tabular-nums">{{ formatCompactCount(m.requests) }} req</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="hiddenModels > 0">
|
||||
<Button variant="outline" size="sm" @click="showAll">Show all {{ providerModels.length.toLocaleString('en-US') }} in the table</Button>
|
||||
</div>
|
||||
</template>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Base URL">
|
||||
<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">{{ provider.baseUrl }}</code>
|
||||
<Button variant="outline" size="sm" class="shrink-0" :aria-label="`Copy base URL of ${id}`" @click="copyUrl">{{ COPY_LABEL[copy.state.value] }}</Button>
|
||||
</div>
|
||||
</PanelSection>
|
||||
</template>
|
||||
</div>
|
||||
</DetailPanel>
|
||||
</template>
|
||||
Reference in New Issue
Block a user