feat(webui): routers page

This commit is contained in:
2026-11-25 11:52:37 +00:00
parent 7b660363e7
commit b9ca05be66
6 changed files with 552 additions and 3 deletions
+125
View File
@@ -0,0 +1,125 @@
import { describe, expect, it } from 'vitest'
import { routerPanelModel } from '@/lib/router-panel'
import type { AdminRouterView } from '@/types/api'
function view(over: Partial<AdminRouterView> = {}): AdminRouterView {
return {
name: 'smartrouter/uni',
defaultTier: 'low',
shadowEnabled: false,
classifier: 'v2',
riskZ: 128,
firstByteTimeout: '40s',
selection: 'ordered',
calibration: { mode: 'off', delta: [], maxLower: 0, maxRaise: 0, freeze: false },
saturationDowngrade: false,
downgradeBand: 100,
downgraded: 0,
timeoutFallback: true,
fellBack: 2,
tiers: [
{ name: 'low', models: ['uni/a'], minScore: 0 },
{ name: 'mid', models: ['uni/b'], minScore: 150 },
{ name: 'top', models: ['uni/c', 'uni/d'], minScore: 350 },
],
keywordRules: [],
maxAttempts: 4,
contextEscalation: true,
contextTokens: 524288,
stats: {
scope: 'shared',
requests: 3,
tiers: [
{ name: 'low', count: 1 },
{ name: 'mid', count: 1 },
{ name: 'top', count: 1 },
],
reasons: [{ name: 'score', count: 3 }],
escalations: [],
shadow: [],
outcomes: [{ tier: 'low', reason: 'score', outcome: 'ok', count: 3 }],
},
...over,
}
}
describe('routerPanelModel', () => {
it('shadow null when stats.shadow empty', () => {
expect(routerPanelModel(view()).shadow).toBeNull()
expect(routerPanelModel(view({ stats: undefined })).shadow).toBeNull()
})
it('builds a live-by-shadow matrix in tier order when stats.shadow has cells', () => {
const m = routerPanelModel(
view({
stats: {
...view().stats!,
shadow: [
{ live: 'top', shadow: 'low', count: 4 },
{ live: 'low', shadow: 'low', count: 9 },
{ live: 'low', shadow: 'mid', count: 2 },
],
},
}),
)
expect(m.shadow).toEqual({ rows: ['low', 'mid', 'top'], cols: ['low', 'mid', 'top'], values: [[9, 2, 0], [0, 0, 0], [4, 0, 0]] })
})
it('split percentages sum to 100', () => {
const counts = [1, 1, 1]
const m = routerPanelModel(view({ stats: { ...view().stats!, tiers: counts.map((count, i) => ({ name: ['low', 'mid', 'top'][i], count })) } }))
expect(m.split.map((s) => s.pct).reduce((a, b) => a + b, 0)).toBe(100)
expect(m.split.map((s) => s.name)).toEqual(['low', 'mid', 'top'])
})
it('split is all zero without traffic and keeps unseen tiers', () => {
const m = routerPanelModel(view({ stats: undefined }))
expect(m.split).toEqual([
{ name: 'low', count: 0, pct: 0 },
{ name: 'mid', count: 0, pct: 0 },
{ name: 'top', count: 0, pct: 0 },
])
})
it('settings include firstByteTimeout and timeoutFallback', () => {
const m = routerPanelModel(view())
const byKey = Object.fromEntries(m.settings.map((s) => [s.key, s.value]))
expect(byKey.firstByteTimeout).toBe('40s')
expect(byKey.timeoutFallback).toBe('on')
expect(byKey.contextTokens).toBe('524288')
})
it('shows unset optional settings as a dash, never undefined', () => {
const m = routerPanelModel(view({ firstByteTimeout: undefined, contextTokens: undefined, timeoutFallback: false }))
const byKey = Object.fromEntries(m.settings.map((s) => [s.key, s.value]))
expect(byKey.firstByteTimeout).toBe('—')
expect(byKey.timeoutFallback).toBe('off')
expect(m.settings.every((s) => !/undefined|NaN/.test(s.value))).toBe(true)
})
it('totals outcomes in a fixed order and drops empty ones', () => {
const m = routerPanelModel(
view({
stats: {
...view().stats!,
outcomes: [
{ tier: 'low', reason: 'score', outcome: 'bad', count: 2 },
{ tier: 'low', reason: 'score', outcome: 'ok', count: 5 },
{ tier: 'mid', reason: 'bump', outcome: 'ok', count: 3 },
],
},
}),
)
expect(m.outcomes).toEqual([
{ outcome: 'ok', count: 8, pct: 80 },
{ outcome: 'bad', count: 2, pct: 20 },
])
})
it('lists tiers with models, default flag and request count', () => {
const m = routerPanelModel(view())
expect(m.tiers[2]).toEqual({ name: 'top', minScore: 350, models: ['uni/c', 'uni/d'], isDefault: false, count: 1 })
expect(m.tiers[0].isDefault).toBe(true)
})
})
+117
View File
@@ -0,0 +1,117 @@
import type { AdminRouterView } from '@/types/api'
const UNSET = '—'
const WHOLE = 100
const OUTCOME_ORDER = ['ok', 'slow', 'bad', 'escalated', 'error'] as const
export interface RouterTierModel {
name: string
minScore: number
models: string[]
isDefault: boolean
count: number
}
export interface RouterSplit {
name: string
count: number
pct: number
}
export interface RouterOutcome {
outcome: string
count: number
pct: number
}
export interface RouterSetting {
key: string
label: string
value: string
}
export interface RouterShadow {
rows: string[]
cols: string[]
values: number[][]
}
export interface RouterPanelModel {
tiers: RouterTierModel[]
split: RouterSplit[]
reasons: Array<{ name: string; count: number }>
outcomes: RouterOutcome[]
shadow: RouterShadow | null
settings: RouterSetting[]
}
/** Whole-number percentages that sum to exactly 100 (largest remainder); all zero without traffic. */
function percentages(counts: number[]): number[] {
const total = counts.reduce((a, b) => a + b, 0)
if (total <= 0) return counts.map(() => 0)
const exact = counts.map((c) => (c * WHOLE) / total)
const pct = exact.map(Math.floor)
let left = WHOLE - pct.reduce((a, b) => a + b, 0)
const byRemainder = exact.map((e, i) => ({ i, r: e - pct[i] })).sort((a, b) => b.r - a.r || a.i - b.i)
for (const { i } of byRemainder) {
if (left-- <= 0) break
pct[i]++
}
return pct
}
const onOff = (v: boolean): string => (v ? 'on' : 'off')
function settings(v: AdminRouterView): RouterSetting[] {
const s = (key: string, label: string, value: string | number | undefined): RouterSetting => ({ key, label, value: value === undefined || value === '' ? UNSET : String(value) })
return [
s('classifier', 'Classifier', v.classifier),
s('shadowClassifier', 'Shadow classifier', v.shadowClassifier),
s('riskZ', 'Risk margin (σ/100)', v.riskZ),
s('selection', 'Selection', v.selection),
s('defaultTier', 'Default tier', v.defaultTier),
s('toolsMinTier', 'Tools floor tier', v.toolsMinTier),
s('maxAttempts', 'Max attempts', v.maxAttempts),
s('firstByteTimeout', 'First-byte timeout', v.firstByteTimeout),
s('timeoutFallback', 'Timeout fallback', onOff(v.timeoutFallback)),
s('fellBack', 'Fell back', v.fellBack),
s('saturationDowngrade', 'Saturation downgrade', onOff(v.saturationDowngrade)),
s('downgraded', 'Downgraded', v.downgraded),
s('contextEscalation', 'Context escalation', onOff(v.contextEscalation)),
s('contextTokens', 'Advertised context (tokens)', v.contextTokens),
s('calibration', 'Calibration', v.calibration.mode),
]
}
function shadow(v: AdminRouterView, order: string[]): RouterShadow | null {
const cells = v.stats?.shadow ?? []
if (cells.length === 0) return null
const seen = new Set(order)
for (const c of cells) for (const n of [c.live, c.shadow]) if (!seen.has(n)) seen.add(n)
const names = [...seen]
const values = names.map(() => names.map(() => 0))
for (const c of cells) values[names.indexOf(c.live)][names.indexOf(c.shadow)] += c.count
return { rows: names, cols: names, values }
}
/** Derived view of one smart router for the panel: tiers, tier split, reasons, outcomes, shadow matrix and settings rows. */
export function routerPanelModel(view: AdminRouterView): RouterPanelModel {
const stats = view.stats
const counts = new Map((stats?.tiers ?? []).map((t) => [t.name, t.count]))
const order = view.tiers.map((t) => t.name)
for (const name of counts.keys()) if (!order.includes(name)) order.push(name)
const splitCounts = order.map((n) => counts.get(n) ?? 0)
const pct = percentages(splitCounts)
const split = order.map((name, i) => ({ name, count: splitCounts[i], pct: pct[i] }))
const totals = new Map<string, number>()
for (const o of stats?.outcomes ?? []) totals.set(o.outcome, (totals.get(o.outcome) ?? 0) + o.count)
const kinds = [...OUTCOME_ORDER, ...[...totals.keys()].filter((k) => !(OUTCOME_ORDER as readonly string[]).includes(k))].filter((k) => (totals.get(k) ?? 0) > 0)
const outcomePct = percentages(kinds.map((k) => totals.get(k) ?? 0))
const outcomes = kinds.map((outcome, i) => ({ outcome, count: totals.get(outcome) ?? 0, pct: outcomePct[i] }))
return {
tiers: view.tiers.map((t) => ({ name: t.name, minScore: t.minScore, models: t.models, isDefault: t.name === view.defaultTier, count: counts.get(t.name) ?? 0 })),
split,
reasons: [...(stats?.reasons ?? [])].sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)),
outcomes,
shadow: shadow(view, order),
settings: settings(view),
}
}