feat(admin-ui): alias labels, active-provider legends, denser tables and readable money

Label configured model aliases with an alias badge wherever a model id shows.
List only providers with traffic in the window in provider chart legends.
Page long tables, show a scroll shadow on wide ones and drop the duplicate model link.
Show costs with thousands separators and magnitude-scaled decimals on cards and chart axes.
Use whole-number ticks for count charts and replace all-zero charts with a message.
Back off polling after failures.
Keep the CSV status region from widening the page on phones.
Regenerate admin_assets_gen.go.
This commit is contained in:
2026-11-08 02:22:22 +00:00
parent 05a7c114f5
commit 758d7c7020
37 changed files with 468 additions and 147 deletions
+18
View File
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest'
import { aliasNameSet } from './alias'
import type { AdminAliasView } from '@/types/api'
const view = (alias: string): AdminAliasView => ({ alias, target: 'openai/gpt-5', modelMeta: {} })
describe('aliasNameSet', () => {
it.each<{ name: string; input: AdminAliasView[] | undefined; has: string[]; hasNot: string[] }>([
{ name: 'undefined', input: undefined, has: [], hasNot: ['x'] },
{ name: 'empty', input: [], has: [], hasNot: ['x'] },
{ name: 'two aliases', input: [view('fast'), view('smart')], has: ['fast', 'smart'], hasNot: ['openai/gpt-5', 'Fast', ''] },
])('$name', ({ input, has, hasNot }) => {
const set = aliasNameSet(input)
for (const h of has) expect(set.has(h)).toBe(true)
for (const h of hasNot.filter((x) => !has.includes(x))) expect(set.has(h)).toBe(false)
})
})
+6
View File
@@ -0,0 +1,6 @@
import type { AdminAliasView } from '@/types/api'
/** aliasNameSet indexes configured alias names (exact match, as a client sends them) for O(1) lookups. */
export function aliasNameSet(aliases: readonly AdminAliasView[] | undefined): Set<string> {
return new Set((aliases ?? []).map((a) => a.alias))
}
+17 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { formatBucketLabel, formatCompactCount, formatContextWindow, formatElapsedAgo, formatLatencyMs, formatModelCostHover, formatUntil, refreshDetailLabel, refreshLabel, ZERO_TIME } from './format'
import { formatBucketLabel, formatCompactCount, formatContextWindow, formatCostAxis, formatCostDisplay, formatElapsedAgo, formatLatencyMs, formatModelCostHover, formatUntil, refreshDetailLabel, refreshLabel, ZERO_TIME } from './format'
describe('refreshLabel', () => {
it('reads "discovery off" when discovery is disabled, regardless of lastRefresh', () => {
@@ -269,3 +269,19 @@ describe('rounding boundaries', () => {
expect(formatLatencyMs(ms)).toBe(want)
})
})
describe('cost display formatters', () => {
it.each([
{ name: 'zero', micros: 0, display: '$0.0000', axis: '$0' },
{ name: 'sub-cent keeps precision', micros: 1_234, display: '$0.0012', axis: '$0.0012' },
{ name: 'under a dollar', micros: 500_000, display: '$0.5000', axis: '$0.5' },
{ name: 'a few dollars', micros: 2_688_800, display: '$2.69', axis: '$2.69' },
{ name: 'hundreds', micros: 999_000_000, display: '$999.00', axis: '$999' },
{ name: 'thousands', micros: 1_500_000_000, display: '$1,500', axis: '$1,500' },
{ name: 'negative', micros: -2_000_000, display: '-$2.00', axis: '-$2' },
{ name: 'NaN', micros: NaN, display: '—', axis: '—' },
])('$name', ({ micros, display, axis }) => {
expect(formatCostDisplay(micros)).toBe(display)
expect(formatCostAxis(micros)).toBe(axis)
})
})
+31
View File
@@ -47,6 +47,37 @@ export function formatCost(micros: number): string {
return `$${microsToUsd(micros).toFixed(4)}`
}
/** Thresholds in micro-USD: 4 decimals under $1 (per-request costs are tiny), cents under $1000, whole dollars above. */
const COST_DISPLAY_CENTS_FROM_MICROS = 1_000_000
const COST_DISPLAY_WHOLE_FROM_MICROS = 1_000_000_000
function costFractionDigits(absMicros: number): number {
if (absMicros < COST_DISPLAY_CENTS_FROM_MICROS) return 4
return absMicros < COST_DISPLAY_WHOLE_FROM_MICROS ? 2 : 0
}
function formatUsdAmount(micros: number, minDigits: (max: number) => number): string {
if (!Number.isFinite(micros)) return '—'
const abs = Math.abs(micros)
const max = costFractionDigits(abs)
const text = microsToUsd(abs).toLocaleString('en-US', { minimumFractionDigits: minDigits(max), maximumFractionDigits: max })
return `${micros < 0 ? '-' : ''}$${text}`
}
/**
* formatCostDisplay renders micro-USD for cards, headings and tooltips with thousands separators and magnitude-scaled
* decimals. Tables and CSV keep formatCost's fixed 4 decimals. Rounding error is at most 0.5% from $1 up
* (formal/Gateway/Ui/Cost.lean rel_err_ge1).
*/
export function formatCostDisplay(micros: number): string {
return formatUsdAmount(micros, (max) => max)
}
/** formatCostAxis is formatCostDisplay without trailing zeros ("$0", "$0.5", "$1,600"), for chart ticks. */
export function formatCostAxis(micros: number): string {
return formatUsdAmount(micros, () => 0)
}
/**
* formatShortDate renders a Date as a compact "Oct 15" label (month/day
* only, no time-of-day) — reuse-audit.md F13: the ONE run-out-date format,
+14 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { loadState } from './load-state'
import { emptyWhenAllZero, loadState } from './load-state'
describe('loadState', () => {
it('is "ready" when there is data, no error, not loading', () => {
@@ -34,3 +34,16 @@ describe('loadState', () => {
expect(loadState({ loading: false, hasData: false, error: '' })).toBe('empty')
})
})
describe('emptyWhenAllZero', () => {
const zero = [{ data: [0, 0, null] }]
it.each([
{ name: 'ready + all zero', state: 'ready', series: zero, want: 'empty' },
{ name: 'ready + no series', state: 'ready', series: [], want: 'empty' },
{ name: 'ready + traffic', state: 'ready', series: [{ data: [0, 2] }], want: 'ready' },
{ name: 'skeleton passes through', state: 'skeleton', series: zero, want: 'skeleton' },
{ name: 'error passes through', state: 'error', series: zero, want: 'error' },
] as const)('$name', ({ state, series, want }) => {
expect(emptyWhenAllZero(state, series)).toBe(want)
})
})
+7
View File
@@ -41,3 +41,10 @@ export function loadState({ loading, hasData, error }: LoadStateInput): LoadStat
if (loading) return 'skeleton'
return 'empty'
}
/** emptyWhenAllZero turns a 'ready' chart state into 'empty' when no series has a non-zero point, so an all-zero chart is replaced by a short message. Other states pass through (formal/Gateway/Ui/EmptyChart.lean). */
export function emptyWhenAllZero(state: LoadState, series: readonly { data: readonly (number | null)[] }[]): LoadState {
if (state !== 'ready') return state
const hasTraffic = series.some((s) => s.data.some((v) => v !== null && v !== 0))
return hasTraffic ? state : 'empty'
}
+4 -9
View File
@@ -2,7 +2,6 @@ import type { VNode } from 'vue'
import { isVNode } from 'vue'
import { describe, expect, it } from 'vitest'
import EntityLink from '@/components/EntityLink.vue'
import ModelChip from '@/components/ModelChip.vue'
import { Badge } from '@/components/ui/badge'
import { buildModelCatalogRows, modelCatalogColumns } from './model-table-columns'
@@ -126,15 +125,11 @@ describe('buildModelCatalogRows', () => {
describe('modelCatalogColumns: id column', () => {
const col = modelCatalogColumns().find((c) => c.id === 'id')
it('cell renders a ModelChip and an EntityLink pointed at kind "model"', () => {
// This table lives on the Models page, so a link back to it would repeat the chip's own text.
it('cell renders one ModelChip and no self-link', () => {
const rendered = cellOf(col)({ row: { original: testRow({ id: 'anthropic/claude' }) } }) as VNode
const children = rendered.children as VNode[]
const chip = children.find((c) => c.type === ModelChip)
const link = children.find((c) => c.type === EntityLink)
expect(chip?.props?.id).toBe('anthropic/claude')
expect(link?.props?.kind).toBe('model')
expect(link?.props?.id).toBe('anthropic/claude')
expect(link?.props?.label).toBe('anthropic/claude')
expect(rendered.type).toBe(ModelChip)
expect(rendered.props?.id).toBe('anthropic/claude')
})
})
+6 -10
View File
@@ -1,7 +1,6 @@
import type { ColumnDef } from '@tanstack/vue-table'
import { h } from 'vue'
import EntityLink from '@/components/EntityLink.vue'
import ModelChip from '@/components/ModelChip.vue'
import { Badge } from '@/components/ui/badge'
import { EMPTY_CELL, optionalColumn, usageMetricColumns } from '@/lib/columns'
@@ -152,15 +151,12 @@ export function modelCatalogColumns(): ColumnDef<ModelCatalogRow, unknown>[] {
header: 'Model',
accessorFn: (r) => r.id,
cell: ({ row }) =>
h('span', { class: 'inline-flex flex-wrap items-center gap-1.5' }, [
h(ModelChip, {
id: row.original.id,
contextTokens: row.original.contextTokens,
inputPerMTokUsd: row.original.inputPerMTokUsd,
outputPerMTokUsd: row.original.outputPerMTokUsd,
}),
h(EntityLink, { label: row.original.id, kind: 'model', id: row.original.id }),
]),
h(ModelChip, {
id: row.original.id,
contextTokens: row.original.contextTokens,
inputPerMTokUsd: row.original.inputPerMTokUsd,
outputPerMTokUsd: row.original.outputPerMTokUsd,
}),
},
optionalColumn<ModelCatalogRow>('context', 'Context', (r) => r.contextTokens, formatContextWindow),
{
+28
View File
@@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest'
import { pageWindow } from './paging'
describe('pageWindow', () => {
it.each([
{ name: 'empty', total: 0, size: 25, idx: 0, want: { index: 0, count: 1, from: 0, to: 0 } },
{ name: 'fits one page', total: 25, size: 25, idx: 0, want: { index: 0, count: 1, from: 0, to: 25 } },
{ name: 'first page', total: 31, size: 25, idx: 0, want: { index: 0, count: 2, from: 0, to: 25 } },
{ name: 'last partial page', total: 31, size: 25, idx: 1, want: { index: 1, count: 2, from: 25, to: 31 } },
{ name: 'index past the end clamps', total: 31, size: 25, idx: 9, want: { index: 1, count: 2, from: 25, to: 31 } },
{ name: 'negative index clamps', total: 31, size: 25, idx: -3, want: { index: 0, count: 2, from: 0, to: 25 } },
{ name: 'filter shrank the data', total: 3, size: 25, idx: 4, want: { index: 0, count: 1, from: 0, to: 3 } },
{ name: 'zero page size is treated as 1', total: 2, size: 0, idx: 1, want: { index: 1, count: 2, from: 1, to: 2 } },
])('$name', ({ total, size, idx, want }) => {
expect(pageWindow(total, size, idx)).toEqual(want)
})
it('every reachable page of a non-empty table shows at least one row', () => {
for (let total = 1; total < 80; total++) {
for (let idx = 0; idx < 6; idx++) {
const w = pageWindow(total, 25, idx)
expect(w.to).toBeGreaterThan(w.from)
expect(w.to).toBeLessThanOrEqual(total)
}
}
})
})
+18
View File
@@ -0,0 +1,18 @@
export interface PageWindow {
/** Zero-based page index, clamped into range. */
index: number
count: number
/** Zero-based start offset, inclusive. */
from: number
/** Zero-based end offset, exclusive. */
to: number
}
/** pageWindow clamps `index` into [0, count-1] and returns the row range for it (formal/Gateway/Ui/Paging.lean). */
export function pageWindow(total: number, pageSize: number, index: number): PageWindow {
const size = Math.max(1, Math.floor(pageSize))
const count = Math.max(1, Math.ceil(total / size))
const clamped = Math.min(Math.max(0, Math.floor(index)), count - 1)
const from = clamped * size
return { index: clamped, count, from, to: Math.min(total, from + size) }
}
+35 -1
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createVisibilityPoller, type VisibilityDocumentLike } from './polling'
import { backoffSkips, createVisibilityPoller, type VisibilityDocumentLike } from './polling'
/**
* createFakeDoc builds a minimal VisibilityDocumentLike test double: a
@@ -222,3 +222,37 @@ describe('createVisibilityPoller', () => {
poller.stop()
})
})
describe('poll backoff', () => {
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())
it.each([
{ failures: 0, want: 0 },
{ failures: 1, want: 1 },
{ failures: 2, want: 3 },
{ failures: 3, want: 7 },
{ failures: 50, want: 7 },
])('backoffSkips($failures) = $want', ({ failures, want }) => {
expect(backoffSkips(failures)).toBe(want)
})
it('skips ticks after a failed poll and resets after a success', async () => {
const tick = vi.fn<() => Promise<boolean>>().mockResolvedValue(true)
const poller = createVisibilityPoller({ intervalMs: 1000, tick, doc: undefined })
poller.start()
await vi.advanceTimersByTimeAsync(0)
expect(tick).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1000) // skipped (1 skip after 1 failure)
expect(tick).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1000)
expect(tick).toHaveBeenCalledTimes(2)
tick.mockResolvedValue(false)
await vi.advanceTimersByTimeAsync(3000) // 2 failures -> 3 skips, then a call
await vi.advanceTimersByTimeAsync(1000)
expect(tick).toHaveBeenCalledTimes(3)
await vi.advanceTimersByTimeAsync(1000) // healthy again: every tick
expect(tick).toHaveBeenCalledTimes(4)
poller.stop()
})
})
+37 -5
View File
@@ -26,12 +26,12 @@ export interface VisibilityPollerOptions {
/** How often `tick` fires while the page is visible. */
intervalMs: number
/**
* The store's own refresh step. Never awaited here — a caller that
* The store's own refresh step. May return a promise resolving `true` when the poll failed: consecutive failures then skip ticks (see backoffSkips) so a down gateway is not hit every interval. Never awaited here — a caller that
* needs its own in-flight guard (history.ts keeps its "skip a tick
* while the previous fetch is still in flight" rule) builds that into
* `tick` itself, same as before this module existed.
*/
tick: () => void
tick: () => void | Promise<boolean | void>
/**
* The document to watch for visibility changes. Defaults to the real
* `document` global when one exists. In a non-browser context (vitest's
@@ -57,8 +57,40 @@ function resolveDoc(doc: VisibilityDocumentLike | undefined): VisibilityDocument
return typeof document === 'undefined' ? undefined : (document as unknown as VisibilityDocumentLike)
}
export function createVisibilityPoller({ intervalMs, tick, doc }: VisibilityPollerOptions): VisibilityPoller {
/** Most ticks skipped between attempts while failing: 2^3 - 1, so a down gateway is retried at least every 8 intervals. */
const MAX_BACKOFF_EXPONENT = 3
/** backoffSkips is how many ticks to skip after `failures` consecutive failed polls; 0 while healthy. */
export function backoffSkips(failures: number): number {
return 2 ** Math.min(failures, MAX_BACKOFF_EXPONENT) - 1
}
export function createVisibilityPoller({ intervalMs, tick: rawTick, doc }: VisibilityPollerOptions): VisibilityPoller {
const target = resolveDoc(doc)
let failures = 0
let skipsLeft = 0
/** run fires the store's tick and, when it reports failure, schedules the backoff. `force` (start, tab becoming visible) bypasses pending skips. */
function run(force: boolean): void {
if (!force && skipsLeft > 0) {
skipsLeft--
return
}
const result = rawTick()
if (result instanceof Promise) {
void result.then(
(failed) => {
failures = failed === true ? failures + 1 : 0
skipsLeft = backoffSkips(failures)
},
() => {
failures++
skipsLeft = backoffSkips(failures)
},
)
}
}
const tick = (): void => run(false)
let timer: ReturnType<typeof setInterval> | undefined
// P13 review fix: `timer !== undefined` alone used to double as start()'s
// idempotency guard, but a poller that STARTS while the page is hidden
@@ -89,7 +121,7 @@ export function createVisibilityPoller({ intervalMs, tick, doc }: VisibilityPoll
if (target.hidden) {
clearTimer()
} else {
tick()
run(true)
scheduleTimer()
}
}
@@ -107,7 +139,7 @@ export function createVisibilityPoller({ intervalMs, tick, doc }: VisibilityPoll
if (started) return
started = true
if (!target?.hidden) {
tick()
run(true)
scheduleTimer()
}
target?.addEventListener('visibilitychange', onVisibilityChange)
+27 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { other, ratioSeries, stackTopN, sumByProvider } from './series'
import { activeScopes, activeSeries, other, ratioSeries, stackTopN, sumByProvider } from './series'
describe('stackTopN', () => {
it('returns the n series with the largest total, descending', () => {
@@ -129,3 +129,29 @@ describe('ratioSeries', () => {
expect(ratioSeries([], [])).toEqual([])
})
})
describe('activeSeries / activeScopes', () => {
const series = [
{ scope: 'provider:a', points: [0, 3, 0] },
{ scope: 'provider:idle', points: [0, 0, 0] },
{ scope: 'provider:empty', points: [] },
{ scope: 'provider:b', points: [1, 0, 0] },
]
it('drops series with no traffic and keeps order', () => {
expect(activeSeries(series).map((s) => s.scope)).toEqual(['provider:a', 'provider:b'])
})
it('keeps the chart-wide total unchanged (Lean Gateway.Ui.Active.total_preserved)', () => {
const total = (ss: { points: number[] }[]) => ss.reduce((acc, s) => acc + s.points.reduce((x, y) => x + y, 0), 0)
expect(total(activeSeries(series))).toBe(total(series))
})
it('returns an empty list for no input', () => {
expect(activeSeries([])).toEqual([])
})
it('activeScopes names only providers with traffic', () => {
expect([...activeScopes(series)].sort()).toEqual(['provider:a', 'provider:b'])
})
})
+11 -1
View File
@@ -97,7 +97,17 @@ export function sumByProvider(series: Series[]): Series[] {
byProvider.set(provider, acc)
}
const grouped = Array.from(byProvider.entries()).map(([scope, points]) => ({ scope, points }))
return grouped.sort((a, b) => sumSeries(b.points) - sumSeries(a.points))
return activeSeries(grouped).sort((a, b) => sumSeries(b.points) - sumSeries(a.points))
}
/** activeSeries drops series whose points sum to zero, so a legend lists only entities that had traffic in the window. The chart-wide total is unchanged. */
export function activeSeries<T extends { points: readonly (number | null)[] }>(series: T[]): T[] {
return series.filter((s) => sumSeries(s.points.map((p) => p ?? 0)) > 0)
}
/** activeScopes is the set of scope ids that had any traffic in `series`. */
export function activeScopes(series: Series[]): Set<string> {
return new Set(activeSeries(series).map((s) => s.scope))
}
/**