refactor(webui): remove shadcn-vue, chart.js and replaced components

Delete 89 files that no live entry imports, drop chart.js, vue-chartjs,
@tanstack/vue-table and the FontAwesome runtime, and replace the Vue
FontAwesome wrapper with a small SVG component.

Limit Tailwind source scanning to the perfect-design components the app
bundles. Add the bundle gate script and spec: gzip JS+CSS of dist/assets
must stay at or below 324300 bytes.
This commit is contained in:
2026-11-25 11:52:38 +00:00
parent 945621a3c5
commit e1f1a60d4d
105 changed files with 156 additions and 9470 deletions
+10
View File
@@ -0,0 +1,10 @@
import { describe, expect, it } from 'vitest'
import { hasDist, LIMIT, totalGzip } from '../../scripts/bundle-size.mjs'
// Needs a prior `npm run build`; skipped when dist/ is absent.
describe.skipIf(!hasDist())('bundle gate', () => {
it('keeps gzip JS+CSS within the size limit', () => {
expect(totalGzip()).toBeLessThanOrEqual(LIMIT)
})
})
-27
View File
@@ -1,27 +0,0 @@
import { describe, expect, it } from 'vitest'
import { BREAKDOWN_PALETTE, CHART_SERIES_COLORS, seriesColor } from './chart-palette'
describe('BREAKDOWN_PALETTE', () => {
it('starts with the same four colors as CHART_SERIES_COLORS, in the same order', () => {
expect(BREAKDOWN_PALETTE.slice(0, 4)).toEqual(CHART_SERIES_COLORS)
})
it('has 8 entries total', () => {
expect(BREAKDOWN_PALETTE).toHaveLength(8)
})
})
describe('seriesColor', () => {
it('cycles through the default palette (CHART_SERIES_COLORS) by index', () => {
expect(seriesColor(0)).toBe(CHART_SERIES_COLORS[0])
expect(seriesColor(CHART_SERIES_COLORS.length)).toBe(CHART_SERIES_COLORS[0])
expect(seriesColor(CHART_SERIES_COLORS.length + 1)).toBe(CHART_SERIES_COLORS[1])
})
it('cycles through an explicitly passed palette (e.g. BREAKDOWN_PALETTE) instead', () => {
expect(seriesColor(0, BREAKDOWN_PALETTE)).toBe(BREAKDOWN_PALETTE[0])
expect(seriesColor(7, BREAKDOWN_PALETTE)).toBe(BREAKDOWN_PALETTE[7])
expect(seriesColor(8, BREAKDOWN_PALETTE)).toBe(BREAKDOWN_PALETTE[0])
})
})
-49
View File
@@ -1,49 +0,0 @@
// reuse-audit.md F13: the ONE chart colour palette module. Two call sites
// used to each own a palette + its own cycling function — stores/
// reliability.ts's RELIABILITY_SERIES_COLORS (a UI concern that had drifted
// into a Pinia store) and pages/SpendPage.vue's BREAKDOWN_PALETTE (the
// identical first four colours, plus four more) — this module is their one
// shared home.
/**
* CHART_SERIES_COLORS cycles through main.css's four existing --chart-*
* tokens (assets/main.css is owned by WP-E — this module does not add a
* fifth) — used to colour the Reliability page's per-provider error-rate/
* timeout/failover overlay charts. With more than four configured
* providers, colors repeat — a known, documented limitation rather than a
* silent one.
*/
export const CHART_SERIES_COLORS = ['--chart-requests', '--chart-tokens-in', '--chart-tokens-out', '--chart-cost'] as const
/**
* BREAKDOWN_PALETTE cycles a colorblind-safe (Okabe & Ito, 2008) 8-color
* qualitative set across the Spend page's breakdown chart's per-model/
* provider/group series. The first four reuse CHART_SERIES_COLORS (already
* that same palette's requests/tokens-in/tokens-out/cost members); the
* remaining four (--chart-series-a..d) extend it, defined alongside them in
* assets/main.css — main.css's original four tokens were sized for four
* FIXED semantic metrics, not an open-ended breakdown series count, so this
* page needed four more, but every chart color token lives in the one
* design-tokens file (Tailwind-only rule), never a component-local <style>
* block. Beyond 8 series (e.g. a fleet with more than 8 configured groups)
* colors repeat — an accepted qualitative-palette limit, not a bug: legend
* labels remain the disambiguator past that point, the same tradeoff any
* categorical chart palette makes once it runs out of distinguishable hues.
*/
export const BREAKDOWN_PALETTE = [
...CHART_SERIES_COLORS,
'--chart-series-a',
'--chart-series-b',
'--chart-series-c',
'--chart-series-d',
] as const
/**
* seriesColor picks one entry from `palette` by index, cycling — defaults
* to CHART_SERIES_COLORS (the Reliability page's 4-color set); pass
* BREAKDOWN_PALETTE for the Spend page's 8-color breakdown chart, or any
* other palette a future chart needs.
*/
export function seriesColor(index: number, palette: readonly string[] = CHART_SERIES_COLORS): string {
return palette[index % palette.length]!
}
-18
View File
@@ -1,18 +0,0 @@
import { CategoryScale, Chart, Filler, Legend, LinearScale, LineController, LineElement, PointElement, Tooltip } from 'chart.js'
// Registered once at module load (ES module caching makes this a true
// singleton regardless of how many components import it) — only the
// chart pieces this panel actually uses, not chart.js's full
// auto-registry, to keep the baked-in bundle lean. TimeSeriesChart.vue
// (redesign-plan.md section 3.4) is the only chart component in this
// panel, and it only ever imports `Line` from vue-chartjs (never `Bar`) —
// so this registers exactly Line's own pieces, plus `Filler`:
// TimeSeriesChart.vue sets `fill: props.stacked` on every stacked
// dataset, and without Filler registered chart.js silently ignores that
// option — a stacked area chart drew UNFILLED lines at cumulative
// heights, so a reader saw the top line at the height of the whole total
// rather than its own value (P2). A `BarController`/`BarElement`
// registration used to sit here too; it was dead — grep confirms no
// component imports vue-chartjs's `Bar`.
Chart.register(CategoryScale, LinearScale, Legend, Tooltip, LineController, LineElement, PointElement, Filler)
-75
View File
@@ -1,75 +0,0 @@
import { describe, expect, it } from 'vitest'
import { compactColumn, costColumn, EMPTY_CELL, optionalColumn, usageMetricColumns } from './columns'
interface Row {
requests: number
tokensIn: number
tokensOut: number
costMicroUsd: number
latencyMs?: number
}
describe('EMPTY_CELL', () => {
it('is the em dash', () => {
expect(EMPTY_CELL).toBe('—')
})
})
describe('compactColumn', () => {
it('carries the given id/header and right-aligns', () => {
const col = compactColumn<Row>('requests', 'Requests', (r) => r.requests)
expect(col.id).toBe('requests')
expect(col.header).toBe('Requests')
expect(col.meta).toEqual({ align: 'right' })
})
it('accessorFn reads the given field via the read function', () => {
const col = compactColumn<Row>('requests', 'Requests', (r) => r.requests) as unknown as { accessorFn: (r: Row) => number }
expect(col.accessorFn({ requests: 42, tokensIn: 0, tokensOut: 0, costMicroUsd: 0 })).toBe(42)
})
})
describe('costColumn', () => {
it('accessorFn reads the given field, unformatted', () => {
const col = costColumn<Row>('cost', 'Cost', (r) => r.costMicroUsd) as unknown as { accessorFn: (r: Row) => number }
expect(col.accessorFn({ requests: 0, tokensIn: 0, tokensOut: 0, costMicroUsd: 1_500_000 })).toBe(1_500_000)
})
})
describe('optionalColumn', () => {
it('accessorFn falls back to the default sentinel (0) for an undefined value', () => {
const col = optionalColumn<Row>('latency', 'Latency', (r) => r.latencyMs, String) as unknown as { accessorFn: (r: Row) => number }
expect(col.accessorFn({ requests: 0, tokensIn: 0, tokensOut: 0, costMicroUsd: 0 })).toBe(0)
})
it('accessorFn falls back to a caller-supplied sortSentinel for an undefined value', () => {
const col = optionalColumn<Row>('latency', 'Latency', (r) => r.latencyMs, String, { sortSentinel: -1 }) as unknown as {
accessorFn: (r: Row) => number
}
expect(col.accessorFn({ requests: 0, tokensIn: 0, tokensOut: 0, costMicroUsd: 0 })).toBe(-1)
})
it('accessorFn reads the real value when defined, ignoring the sentinel', () => {
const col = optionalColumn<Row>('latency', 'Latency', (r) => r.latencyMs, String, { sortSentinel: -1 }) as unknown as {
accessorFn: (r: Row) => number
}
expect(col.accessorFn({ requests: 0, tokensIn: 0, tokensOut: 0, costMicroUsd: 0, latencyMs: 120 })).toBe(120)
})
})
describe('usageMetricColumns', () => {
it('builds exactly requests/tokensIn/tokensOut/cost, in that order', () => {
const columns = usageMetricColumns<Row>()
expect(columns.map((c) => c.id)).toEqual(['requests', 'tokensIn', 'tokensOut', 'cost'])
})
it('each column\'s accessorFn reads its own field', () => {
const row: Row = { requests: 1, tokensIn: 2, tokensOut: 3, costMicroUsd: 4 }
const columns = usageMetricColumns<Row>() as unknown as { id: string; accessorFn: (r: Row) => number }[]
expect(columns.find((c) => c.id === 'requests')?.accessorFn(row)).toBe(1)
expect(columns.find((c) => c.id === 'tokensIn')?.accessorFn(row)).toBe(2)
expect(columns.find((c) => c.id === 'tokensOut')?.accessorFn(row)).toBe(3)
expect(columns.find((c) => c.id === 'cost')?.accessorFn(row)).toBe(4)
})
})
-87
View File
@@ -1,87 +0,0 @@
// reuse-audit.md F9: generic TanStack ColumnDef factories for the numeric-
// metric columns that repeat across every usage-shaped table in this panel
// (lib/model-table-columns.ts, components/PricingHealthTable.vue, lib/
// target-columns.ts) — a right-aligned, sortable count column rendered via
// CompactNumber, a right-aligned cost column rendered via formatCost, and
// an "undefined reads as a placeholder" optional numeric column (p50/p95,
// context window). Each factory is generic over the row type `T`: the
// duplication these replace was never about the ROW SHAPE (every caller
// already has its own row interface), only about the identical id/header/
// accessor/cell wiring built on top of it.
import type { ColumnDef } from '@tanstack/vue-table'
import { h } from 'vue'
import CompactNumber from '@/components/CompactNumber.vue'
import { formatCost } from '@/lib/format'
/** EMPTY_CELL is the ONE "no value to show" placeholder every table cell in this panel renders instead of a blank — model-table-columns.ts, PricingHealthTable.vue, usage-columns.ts, and events-columns.ts each used to redeclare the same '—' literal. */
export const EMPTY_CELL = '—'
/** compactColumn builds one right-aligned, sortable numeric column rendered via CompactNumber (SI-style, exact value on title/aria-label) — the plain case with no storeDown masking or budget-bar overlay (usage-columns.ts's own richer numericColumn keeps those, see its own doc comment for why it is not built on this one). */
export function compactColumn<T>(id: string, header: string, read: (row: T) => number): ColumnDef<T, unknown> {
return {
id,
header,
meta: { align: 'right' },
accessorFn: (r) => read(r),
cell: ({ row }) => h(CompactNumber, { value: read(row.original) }),
}
}
/** costColumn builds one right-aligned, sortable micro-USD column rendered via formatCost — the plain case (a caller with its own special-case cell, e.g. model-table-columns.ts's free-priced-model badge, keeps its own hand-written column instead). */
export function costColumn<T>(id: string, header: string, read: (row: T) => number): ColumnDef<T, unknown> {
return {
id,
header,
meta: { align: 'right' },
accessorFn: (r) => read(r),
cell: ({ row }) => formatCost(read(row.original)),
}
}
/**
* optionalColumn builds one right-aligned, sortable column for a value
* that may be undefined (no observations yet, a feature switched off) —
* EMPTY_CELL for the cell, `sortSentinel` (default 0) for the accessor so
* an "undefined" row still sorts somewhere deterministic (p50/p95 pass -1,
* so "no data" sorts below a genuine 0ms reading rather than tying with
* it; context window's own 0 default is fine as-is, nothing sorts below a
* real context size of 0).
*/
export function optionalColumn<T>(
id: string,
header: string,
read: (row: T) => number | undefined,
format: (n: number) => string,
opts?: { sortSentinel?: number },
): ColumnDef<T, unknown> {
const sentinel = opts?.sortSentinel ?? 0
return {
id,
header,
meta: { align: 'right' },
accessorFn: (r) => read(r) ?? sentinel,
cell: ({ row }) => {
const value = read(row.original)
return h('span', { class: 'tabular-nums' }, value !== undefined ? format(value) : EMPTY_CELL)
},
}
}
/** UsageMetricRow is the field set usageMetricColumns reads — every row shape in this panel that carries per-model/per-scope requests/tokens/cost (ModelCatalogRow, PricingHealthRow) already has exactly these four fields under these exact names. */
export interface UsageMetricRow {
requests: number
tokensIn: number
tokensOut: number
costMicroUsd: number
}
/** usageMetricColumns builds the requests/tokensIn/tokensOut/cost column set every usage-ranked model table in this panel repeats (reuse-audit.md F9) — a caller with its own special-case cost cell (e.g. a free-priced-model badge) omits 'cost' here and appends its own instead. */
export function usageMetricColumns<T extends UsageMetricRow>(): ColumnDef<T, unknown>[] {
return [
compactColumn<T>('requests', 'Requests', (r) => r.requests),
compactColumn<T>('tokensIn', 'Tokens in', (r) => r.tokensIn),
compactColumn<T>('tokensOut', 'Tokens out', (r) => r.tokensOut),
costColumn<T>('cost', 'Cost', (r) => r.costMicroUsd),
]
}
-97
View File
@@ -1,97 +0,0 @@
import type { ColumnDef } from '@tanstack/vue-table'
import { h } from 'vue'
import { Badge } from '@/components/ui/badge'
import { EMPTY_CELL } from '@/lib/columns'
import { eventKindVariant, kindLabel } from '@/lib/events-filter'
import { formatTimestamp } from '@/lib/format'
import type { AdminEventView } from '@/types/api'
/** scopeText renders one event's user/group — a user-scoped event never carries a group and vice versa (AdminEventView's own doc comment), so at most one of the two is ever present; an event with neither (a total/all-scope event, e.g. a capacity rejection recorded user-less — DECISIONS Q4) renders an em dash. */
function scopeText(e: AdminEventView): string {
if (e.user) return `user:${e.user}`
if (e.group) return `group:${e.group}`
return EMPTY_CELL
}
/** targetText renders one event's model/provider pair — joined when both are known (an upstream/timeout event names both), just the one that is known otherwise, and an em dash when neither applies (a rate_limit/budget event never carries either). */
function targetText(e: AdminEventView): string {
const parts = [e.model, e.provider].filter((v): v is string => Boolean(v))
return parts.length ? parts.join(' → ') : EMPTY_CELL
}
/**
* eventsColumns builds the Events tab's DataTable ColumnDef set
* (admin.go/events.go: gatewayEvent — F3). Mirrors target-columns.ts's own
* shape: a Badge for the classified `kind` column (eventKindVariant), plain
* muted text for everything free-form (route/message), an em dash for a
* field this row does not carry rather than a blank cell.
*/
export function eventsColumns(): ColumnDef<AdminEventView, unknown>[] {
return [
{
id: 'time',
header: 'Time',
accessorFn: (e) => e.time,
cell: ({ row }) => h('span', { class: 'text-muted-foreground tabular-nums' }, formatTimestamp(row.original.time)),
},
{
id: 'kind',
header: 'Kind',
accessorFn: (e) => e.kind,
cell: ({ row }) =>
h(
Badge,
{ as: 'span', variant: eventKindVariant(row.original.kind), class: 'font-normal' },
() => kindLabel(row.original.kind),
),
},
{
id: 'route',
header: 'Route',
accessorFn: (e) => e.route,
cell: ({ row }) => h('span', { class: 'font-mono text-xs' }, row.original.route),
},
{
id: 'scope',
header: 'User / group',
enableSorting: false,
accessorFn: (e) => e.user ?? e.group ?? '',
cell: ({ row }) => {
const text = scopeText(row.original)
return h('span', { class: text === EMPTY_CELL ? 'text-muted-foreground' : undefined }, text)
},
},
{
id: 'target',
header: 'Model / provider',
enableSorting: false,
accessorFn: (e) => `${e.model ?? ''} ${e.provider ?? ''}`,
cell: ({ row }) => {
const text = targetText(row.original)
return h('span', { class: text === EMPTY_CELL ? 'text-muted-foreground' : 'font-mono text-xs' }, text)
},
},
{
id: 'replica',
header: 'Replica',
accessorFn: (e) => e.replica,
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, row.original.replica),
},
{
id: 'status',
header: 'Status',
meta: { align: 'right' },
accessorFn: (e) => e.status ?? 0,
cell: ({ row }) =>
h('span', { class: 'tabular-nums' }, row.original.status !== undefined ? String(row.original.status) : EMPTY_CELL),
},
{
id: 'message',
header: 'Message',
enableSorting: false,
accessorFn: (e) => e.message,
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, row.original.message),
},
]
}
+1 -166
View File
@@ -1,40 +1,8 @@
import type { VNode } from 'vue'
import { isVNode } from 'vue'
import { describe, expect, it } from 'vitest'
import ModelChip from '@/components/ModelChip.vue'
import { Badge } from '@/components/ui/badge'
import { buildModelCatalogRows, modelCatalogColumns } from './model-table-columns'
import type { ModelCatalogRow } from './model-table-columns'
import { buildModelCatalogRows } from './model-table-columns'
import type { AdminCatalogResponse, AdminPerfResponse, AdminUsageModelsResponse } from '@/types/api'
function testRow(overrides: Partial<ModelCatalogRow> = {}): ModelCatalogRow {
return {
id: 'openai/gpt-5',
model: 'gpt-5',
providerName: 'openai',
kind: '',
endpoint: false,
priceSource: 'builtin',
aliases: [],
requests: 0,
tokensIn: 0,
tokensOut: 0,
costMicroUsd: 0,
attempts: 0,
failures: 0,
...overrides,
}
}
function accessorFnOf(col: unknown): (row: ModelCatalogRow, index: number) => unknown {
return (col as { accessorFn: (row: ModelCatalogRow, index: number) => unknown }).accessorFn
}
function cellOf(col: unknown): (ctx: { row: { original: ModelCatalogRow } }) => unknown {
return (col as { cell: (ctx: { row: { original: ModelCatalogRow } }) => unknown }).cell
}
describe('buildModelCatalogRows', () => {
function catalog(): AdminCatalogResponse {
return {
@@ -124,139 +92,6 @@ describe('buildModelCatalogRows', () => {
})
})
describe('modelCatalogColumns: id column', () => {
const col = modelCatalogColumns().find((c) => c.id === 'id')
// 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
expect(rendered.type).toBe(ModelChip)
expect(rendered.props?.id).toBe('anthropic/claude')
})
})
describe('modelCatalogColumns: price column', () => {
const col = modelCatalogColumns().find((c) => c.id === 'price')
it('renders a destructive "unpriced" Badge for priceSource "unpriced"', () => {
const rendered = cellOf(col)({ row: { original: testRow({ priceSource: 'unpriced' }) } }) as VNode
expect(rendered.type).toBe(Badge)
expect(rendered.props?.variant).toBe('destructive')
})
it('renders a "free" Badge for priceSource "free"', () => {
const rendered = cellOf(col)({ row: { original: testRow({ priceSource: 'free' }) } }) as VNode
expect(rendered.type).toBe(Badge)
const slot = (rendered.children as { default: () => string }).default
expect(slot()).toBe('free')
})
it('renders the formatted price plus a source Badge for override/builtin/litellm', () => {
const rendered = cellOf(col)({
row: { original: testRow({ priceSource: 'litellm', inputPerMTokUsd: 1, outputPerMTokUsd: 2 }) },
}) as VNode
const children = rendered.children as VNode[]
expect((children[0] as VNode).children).toBe('$1.00 / $2.00')
const badge = children[1] as VNode
expect(badge.type).toBe(Badge)
expect((badge.children as { default: () => string }).default()).toBe('litellm')
})
it('renders an em dash placeholder for a priced source with unknown per-token cost (version skew)', () => {
const rendered = cellOf(col)({ row: { original: testRow({ priceSource: 'override' }) } }) as VNode
const children = rendered.children as VNode[]
expect((children[0] as VNode).children).toBe('—')
})
it('sorts unpriced first, then ascending by input price', () => {
const accessor = accessorFnOf(col)
const rows = [
testRow({ id: 'a', priceSource: 'builtin', inputPerMTokUsd: 5 }),
testRow({ id: 'b', priceSource: 'unpriced' }),
testRow({ id: 'c', priceSource: 'builtin', inputPerMTokUsd: 1 }),
]
const sorted = [...rows].sort((x, y) => (accessor(x, 0) as number) - (accessor(y, 0) as number))
expect(sorted.map((r) => r.id)).toEqual(['b', 'c', 'a'])
})
})
describe('modelCatalogColumns: ":free" suffix flag', () => {
const col = modelCatalogColumns().find((c) => c.id === 'price')
const priced = { priceSource: 'litellm', inputPerMTokUsd: 1, outputPerMTokUsd: 2 } as const
it('has no separate free column', () => {
expect(modelCatalogColumns().some((c) => c.id === 'free')).toBe(false)
})
it.each([
{ displayFree: true, children: 3 },
{ displayFree: false, children: 2 },
{ displayFree: undefined, children: 2 },
])('displayFree=$displayFree renders $children price-cell children', ({ displayFree, children }) => {
const rendered = cellOf(col)({ row: { original: testRow({ ...priced, displayFree }) } }) as VNode
expect((rendered.children as VNode[]).length).toBe(children)
})
})
describe('modelCatalogColumns: aliases column', () => {
const col = modelCatalogColumns().find((c) => c.id === 'aliases')
it('renders an em dash for an empty alias list', () => {
const rendered = cellOf(col)({ row: { original: testRow({ aliases: [] }) } })
expect(isVNode(rendered) && rendered.children).toBe('—')
})
it('renders one Badge per alias', () => {
const rendered = cellOf(col)({ row: { original: testRow({ aliases: ['a', 'b'] }) } }) as VNode
const children = rendered.children as VNode[]
expect(children).toHaveLength(2)
expect(children.every((c) => c.type === Badge)).toBe(true)
})
})
describe('modelCatalogColumns: cost column', () => {
const col = modelCatalogColumns().find((c) => c.id === 'cost')
it('renders a "free" Badge for a zero-cost free/displayFree row instead of $0.0000', () => {
const rendered = cellOf(col)({ row: { original: testRow({ priceSource: 'free', costMicroUsd: 0 }) } }) as VNode
expect(rendered.type).toBe(Badge)
const rendered2 = cellOf(col)({ row: { original: testRow({ displayFree: true, costMicroUsd: 0 }) } }) as VNode
expect(rendered2.type).toBe(Badge)
})
it('renders the real formatted cost when non-zero, even if free', () => {
const rendered = cellOf(col)({ row: { original: testRow({ priceSource: 'free', costMicroUsd: 1_234_500 }) } })
expect(rendered).toBe('$1.2345')
})
it('renders plain formatCost for a priced, non-free row', () => {
const rendered = cellOf(col)({ row: { original: testRow({ costMicroUsd: 2_000_000 }) } })
expect(rendered).toBe('$2.0000')
})
})
describe('modelCatalogColumns: p50/p95/error rate columns', () => {
it('p50/p95 render an em dash when undefined, formatted latency otherwise', () => {
const p50 = modelCatalogColumns().find((c) => c.id === 'p50')
const p95 = modelCatalogColumns().find((c) => c.id === 'p95')
expect(cellOf(p50)({ row: { original: testRow() } })).toMatchObject({ children: '—' })
expect(cellOf(p95)({ row: { original: testRow({ p95Ms: 1500 }) } })).toMatchObject({ children: '1.5s' })
})
it('error rate renders "no data" for zero attempts, a ceiled percent otherwise', () => {
const col = modelCatalogColumns().find((c) => c.id === 'errorRate')
expect(cellOf(col)({ row: { original: testRow({ attempts: 0, failures: 0 }) } })).toMatchObject({ children: 'no data' })
expect(cellOf(col)({ row: { original: testRow({ attempts: 100, failures: 1 }) } })).toMatchObject({ children: '1%' })
})
it('error rate sorts a no-traffic row (-1) below every real rate', () => {
const col = modelCatalogColumns().find((c) => c.id === 'errorRate')
const accessor = accessorFnOf(col)
expect(accessor(testRow({ attempts: 0, failures: 0 }), 0)).toBe(-1)
expect(accessor(testRow({ attempts: 10, failures: 0 }), 0)).toBe(0)
})
})
describe('buildModelCatalogRows: router targets', () => {
it('carries a model routers list and defaults to empty', () => {
const catalog = {
-165
View File
@@ -1,12 +1,3 @@
import type { ColumnDef } from '@tanstack/vue-table'
import { h } from 'vue'
import ModelChip from '@/components/ModelChip.vue'
import { Badge } from '@/components/ui/badge'
import CompactNumber from '@/components/CompactNumber.vue'
import { EMPTY_CELL, optionalColumn, usageMetricColumns } from '@/lib/columns'
import { formatCost, formatLatencyMs, formatModelCostHover, formatModelPriceShort } from '@/lib/format'
import { formatErrorRatePercent, providerErrorRate } from '@/lib/provider-rate'
import type { AdminCatalogResponse, AdminPerfResponse, AdminUsageModelsResponse, PriceSource } from '@/types/api'
/**
@@ -102,159 +93,3 @@ export function buildModelCatalogRows(
}
return rows
}
/** PRICE_SOURCE_LABEL is the price-source Badge's visible text for the three "priced by a rule" sources — 'free'/'unpriced' get their own dedicated badge treatment in priceCell below, never this generic label. */
const PRICE_SOURCE_LABEL: Record<Extract<PriceSource, 'override' | 'builtin' | 'litellm'>, string> = {
override: 'override',
builtin: 'builtin',
litellm: 'litellm',
}
const FREE_SUFFIX_TITLE = "':free' suffix model — display-only, billing follows the price source"
function priceCell(row: ModelCatalogRow) {
if (row.endpoint) return h('span', { class: 'text-muted-foreground' }, EMPTY_CELL)
if (row.priceSource === 'unpriced') {
return h(
Badge,
{ as: 'span', variant: 'destructive', class: 'font-normal', title: 'No pricing rule matched — billed as $0.' },
() => 'unpriced',
)
}
if (row.priceSource === 'free') {
return h(Badge, { as: 'span', variant: 'secondary', class: 'font-normal', title: 'Configured free (modelMeta.free) — priced at $0.' }, () => 'free')
}
const known = row.inputPerMTokUsd !== undefined && row.outputPerMTokUsd !== undefined
// Narrowed to a local BEFORE the h() callback below — TS control-flow
// narrowing on `row.priceSource` (from the two early returns above)
// does not cross a closure boundary, so the callback itself still sees
// the full PriceSource union unless the already-narrowed value is
// captured into its own variable first.
const source = row.priceSource as Exclude<PriceSource, 'unpriced' | 'free'>
return h('span', { class: 'inline-flex flex-wrap items-center gap-1.5' }, [
h(
'span',
known ? { class: 'tabular-nums', title: formatModelCostHover(row.inputPerMTokUsd as number, row.outputPerMTokUsd as number) } : {},
known ? formatModelPriceShort(row.inputPerMTokUsd as number, row.outputPerMTokUsd as number) : EMPTY_CELL,
),
h(Badge, { as: 'span', variant: 'outline', class: 'font-normal' }, () => PRICE_SOURCE_LABEL[source]),
...(row.displayFree ? [h(Badge, { as: 'span', variant: 'secondary', class: 'font-normal', title: FREE_SUFFIX_TITLE }, () => ':free')] : []),
])
}
/**
* priceSortValue orders unpriced first (nothing to report, worth an
* operator's attention), then by ascending input price — accessorFn's
* numeric return, not the rendered text, is what DataTable actually sorts
* on.
*/
function priceSortValue(row: ModelCatalogRow): number {
if (row.endpoint) return 0
if (row.priceSource === 'unpriced') return -1
return row.inputPerMTokUsd ?? 0
}
/**
* modelCatalogColumns builds the Models page's catalog table (redesign-
* plan.md section 3.4): id, context, price + source badge (plus a ':free' badge for
* the suffix flag, distinct from the 'free' priceSource badge), aliases,
* req/tokens/cost for the current global range, p50/p95, and error rate.
* p50/p95 read "—" whenever undefined, regardless of WHY (no observations
* yet, or admin.stats.latency off entirely) — ModelCatalogTable.vue itself
* carries the admin.stats.latency hint at the table level (task
* instruction: "handle latencyEnabled=false with a hint naming
* admin.stats.latency"), not repeated on every row.
*/
export function modelCatalogColumns(): ColumnDef<ModelCatalogRow, unknown>[] {
return [
{
id: 'id',
header: 'Model',
accessorFn: (r) => r.id,
cell: ({ row }) =>
h(ModelChip, {
id: row.original.id,
contextTokens: row.original.contextTokens,
inputPerMTokUsd: row.original.inputPerMTokUsd,
outputPerMTokUsd: row.original.outputPerMTokUsd,
}),
},
{
id: 'price',
header: 'Price $/MTok',
accessorFn: (r) => priceSortValue(r),
cell: ({ row }) => priceCell(row.original),
},
{
id: 'aliases',
header: 'Aliases',
enableSorting: false,
accessorFn: (r) => r.aliases.join(', '),
cell: ({ row }) => {
const aliases = row.original.aliases
if (aliases.length === 0) return h('span', { class: 'text-muted-foreground' }, EMPTY_CELL)
return h(
'div',
{ class: 'flex flex-wrap gap-1' },
aliases.map((a) => h(Badge, { key: a, as: 'span', variant: 'outline', class: 'font-mono font-normal' }, () => a)),
)
},
},
{
id: 'routers',
header: 'Routers',
enableSorting: false,
accessorFn: (r) => (r.routers ?? []).join(', '),
cell: ({ row }) => {
const routers = row.original.routers ?? []
if (routers.length === 0) return h('span', { class: 'text-muted-foreground' }, EMPTY_CELL)
return h(
'div',
{ class: 'flex flex-wrap gap-1' },
routers.map((r) => h(Badge, { key: r, as: 'span', variant: 'secondary', class: 'font-mono font-normal', title: 'Smart router target' }, () => r)),
)
},
},
// reuse-audit.md F9: requests/tokensIn/tokensOut share the shared
// usageMetricColumns factory; 'cost' stays hand-written below since
// this table's cost cell has an extra free-priced-model badge case
// usageMetricColumns' own plain costColumn does not (and should not —
// PricingHealthTable.vue's identical-shaped cost column has no such
// badge) carry.
...usageMetricColumns<ModelCatalogRow>().filter((c) => c.id === 'requests'),
{
id: 'tokens',
header: 'Tokens',
meta: { align: 'right' },
accessorFn: (r) => r.tokensIn + r.tokensOut,
cell: ({ row }) =>
h('span', { class: 'inline-flex items-center gap-1 whitespace-nowrap', title: 'input / output tokens' }, [
h(CompactNumber, { value: row.original.tokensIn }),
h('span', { class: 'text-muted-foreground' }, '/'),
h(CompactNumber, { value: row.original.tokensOut }),
]),
},
{
id: 'cost',
header: 'Cost',
meta: { align: 'right' },
accessorFn: (r) => r.costMicroUsd,
cell: ({ row }) => {
const r = row.original
if ((r.priceSource === 'free' || r.displayFree) && r.costMicroUsd === 0) {
return h(Badge, { as: 'span', variant: 'secondary', class: 'font-normal', title: 'priced at $0 per token' }, () => 'free')
}
return formatCost(r.costMicroUsd)
},
},
optionalColumn<ModelCatalogRow>('p50', 'p50', (r) => r.p50Ms, formatLatencyMs, { sortSentinel: -1 }),
optionalColumn<ModelCatalogRow>('p95', 'p95', (r) => r.p95Ms, formatLatencyMs, { sortSentinel: -1 }),
{
id: 'errorRate',
header: 'Errors',
meta: { align: 'right' },
accessorFn: (r) => providerErrorRate(r.attempts, r.failures) ?? -1,
cell: ({ row }) => h('span', { class: 'tabular-nums' }, formatErrorRatePercent(providerErrorRate(row.original.attempts, row.original.failures))),
},
]
}
-31
View File
@@ -1,31 +0,0 @@
import { describe, expect, it } from 'vitest'
import { providerSections } from '@/lib/provider-sections'
describe('providerSections', () => {
it('returns one untitled section when no kinds or endpoints are set', () => {
expect(providerSections({ models: ['a', 'b'] })).toEqual([{ title: '', models: ['a', 'b'], endpoints: [] }])
})
it('groups models and endpoints by kind, plain models first', () => {
const got = providerSections({
models: ['chat', 'rerank', 'embed'],
kinds: { rerank: 'reranking', embed: 'embedding', '/v1/decide': 'decision' },
endpoints: ['/v1/decide'],
})
expect(got).toEqual([
{ title: '', models: ['chat'], endpoints: [] },
{ title: 'decision', models: [], endpoints: ['/v1/decide'] },
{ title: 'embedding', models: ['embed'], endpoints: [] },
{ title: 'reranking', models: ['rerank'], endpoints: [] },
])
})
it('files an endpoint without a kind under "endpoints"', () => {
const got = providerSections({ models: ['chat'], endpoints: ['/v1/other'] })
expect(got).toEqual([
{ title: '', models: ['chat'], endpoints: [] },
{ title: 'endpoints', models: [], endpoints: ['/v1/other'] },
])
})
})
-40
View File
@@ -1,40 +0,0 @@
export interface ProviderSection {
/** Sub-section heading; '' for the untitled plain-model section. */
title: string
models: string[]
endpoints: string[]
}
export interface ProviderSectionInput {
models: string[]
kinds?: Record<string, string>
endpoints?: string[]
}
/** Heading for an endpoint with no configured kind. */
export const ENDPOINT_KIND = 'endpoints'
/**
* providerSections splits one provider's rows into sub-sections by kind:
* the plain (no-kind) models first, then one section per kind, sorted.
* A provider with no kinds and no endpoints yields one untitled section,
* so an unconfigured provider renders exactly as the flat list did.
*/
export function providerSections(p: ProviderSectionInput): ProviderSection[] {
const kinds = p.kinds ?? {}
const endpoints = p.endpoints ?? []
if (endpoints.length === 0 && Object.keys(kinds).length === 0) return [{ title: '', models: p.models, endpoints: [] }]
const byTitle = new Map<string, ProviderSection>()
const section = (title: string): ProviderSection => {
let s = byTitle.get(title)
if (!s) {
s = { title, models: [], endpoints: [] }
byTitle.set(title, s)
}
return s
}
for (const m of p.models) section(kinds[m] ?? '').models.push(m)
for (const e of endpoints) section(kinds[e] ?? ENDPOINT_KIND).endpoints.push(e)
return [...byTitle.values()].sort((a, b) => (a.title === '' ? -1 : b.title === '' ? 1 : a.title.localeCompare(b.title)))
}
-151
View File
@@ -1,151 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
type ExpandState,
clearExpandOverrides,
computeExpandedItems,
toggleItemExpand,
} from './search-expand'
/** newState is a fresh ExpandState — every test starts from an empty, un-searched panel. */
function newState(): ExpandState {
return { manuallyExpanded: new Set(), manuallyCollapsed: new Set() }
}
describe('computeExpandedItems', () => {
it('returns manuallyExpanded verbatim when there is no active query', () => {
const state = newState()
state.manuallyExpanded.add('openai')
expect(computeExpandedItems(state, false, ['openai', 'anthropic'])).toEqual(new Set(['openai']))
})
it('auto-expands every matching id while a query is active', () => {
const state = newState()
expect(computeExpandedItems(state, true, ['openai', 'anthropic'])).toEqual(new Set(['openai', 'anthropic']))
})
it('unions manuallyExpanded with matches while a query is active', () => {
const state = newState()
state.manuallyExpanded.add('gemini') // manually opened before the search started, does not match it
expect(computeExpandedItems(state, true, ['openai'])).toEqual(new Set(['gemini', 'openai']))
})
it('suppresses an auto-match the user explicitly collapsed', () => {
const state = newState()
state.manuallyCollapsed.add('openai')
expect(computeExpandedItems(state, true, ['openai', 'anthropic'])).toEqual(new Set(['anthropic']))
})
})
describe('toggleItemExpand', () => {
it('opening (currentlyExpanded=false) adds to manuallyExpanded and clears any collapse override', () => {
const state = newState()
state.manuallyCollapsed.add('openai')
toggleItemExpand(state, 'openai', false)
expect(state.manuallyExpanded.has('openai')).toBe(true)
expect(state.manuallyCollapsed.has('openai')).toBe(false)
})
it('closing (currentlyExpanded=true) removes from manuallyExpanded and adds a collapse override', () => {
const state = newState()
state.manuallyExpanded.add('openai')
toggleItemExpand(state, 'openai', true)
expect(state.manuallyExpanded.has('openai')).toBe(false)
expect(state.manuallyCollapsed.has('openai')).toBe(true)
})
})
describe('clearExpandOverrides', () => {
it('drops manuallyCollapsed but leaves manuallyExpanded untouched', () => {
const state = newState()
state.manuallyExpanded.add('openai')
state.manuallyCollapsed.add('anthropic')
clearExpandOverrides(state)
expect(state.manuallyCollapsed.size).toBe(0)
expect(state.manuallyExpanded.has('openai')).toBe(true)
})
})
describe('the review-flagged sequence: an auto-matched (never manually opened) item, clicked closed', () => {
it('never enters manuallyExpanded, and stays collapsed after the query clears', () => {
const state = newState()
const matches = ['openai']
// 1. Search starts matching "openai" — it shows via auto-expand only,
// manuallyExpanded is still empty.
let expanded = computeExpandedItems(state, true, matches)
expect(expanded.has('openai')).toBe(true)
expect(state.manuallyExpanded.has('openai')).toBe(false)
// 2. User clicks it closed while it's only auto-expanded. The RAW bug
// this module exists to fix: reading manuallyExpanded.has('openai')
// directly (false) would have ADDED it to manuallyExpanded instead
// of suppressing the auto-expand. toggleItemExpand takes the
// EFFECTIVE current state (expanded.has('openai') === true) instead.
toggleItemExpand(state, 'openai', expanded.has('openai'))
expect(state.manuallyExpanded.has('openai')).toBe(false)
expect(state.manuallyCollapsed.has('openai')).toBe(true)
// 3. Still searching: the override suppresses the auto-expand.
expanded = computeExpandedItems(state, true, matches)
expect(expanded.has('openai')).toBe(false)
// 4. Query clears: a stale override must never carry into a later,
// unrelated search.
clearExpandOverrides(state)
expanded = computeExpandedItems(state, false, [])
expect(expanded.has('openai')).toBe(false)
})
})
describe('an item manually opened before search, still matches, clicked closed during search', () => {
it("the user's in-search click wins, and it stays closed after the query clears too", () => {
const state = newState()
state.manuallyExpanded.add('openai') // opened before any search existed
const matches = ['openai']
let expanded = computeExpandedItems(state, true, matches)
expect(expanded.has('openai')).toBe(true)
toggleItemExpand(state, 'openai', expanded.has('openai'))
expect(state.manuallyExpanded.has('openai')).toBe(false)
expect(state.manuallyCollapsed.has('openai')).toBe(true)
clearExpandOverrides(state)
expanded = computeExpandedItems(state, false, [])
expect(expanded.has('openai')).toBe(false)
})
})
// This module is domain-agnostic on what an "id" represents — it started as
// ProviderHealthPanel.vue's provider names, but ConsumerDirectory.vue also
// feeds it group ids (see that component's own doc comment: matchingIds
// there is every group that matches ONLY via a member, never via its own
// name). These two cases exist to pin that the module behaves identically
// for that second domain, not because anything here differs by id shape.
describe('generic ids (Usage group ids, not just Providers provider names)', () => {
it('auto-expands and can be collapsed/overridden identically for a group id', () => {
const state = newState()
const matches = ['team-a']
let expanded = computeExpandedItems(state, true, matches)
expect(expanded.has('team-a')).toBe(true)
toggleItemExpand(state, 'team-a', expanded.has('team-a'))
expect(state.manuallyExpanded.has('team-a')).toBe(false)
expect(state.manuallyCollapsed.has('team-a')).toBe(true)
expanded = computeExpandedItems(state, true, matches)
expect(expanded.has('team-a')).toBe(false)
clearExpandOverrides(state)
expanded = computeExpandedItems(state, false, [])
expect(expanded.has('team-a')).toBe(false)
})
it('a group id manually opened stays open when the query clears', () => {
const state = newState()
state.manuallyExpanded.add('team-a')
expect(computeExpandedItems(state, false, [])).toEqual(new Set(['team-a']))
})
})
-96
View File
@@ -1,96 +0,0 @@
/**
* Pure expand/collapse state for a search-filterable shadcn-vue Accordion —
* shared by ProviderHealthPanel.vue (providers) and ConsumerDirectory.vue
* (groups), and generalized (originally provider-expand.ts) so both
* consume ONE tested implementation instead of two copies of the same
* logic (vue.md: "if you've written it twice, you owe an abstraction").
* Extracted out of the component so the exact toggle sequence a review
* flagged (see toggleItemExpand's own comment) is tested in isolation,
* without mounting Vue — see search-expand.spec.ts (vitest), which
* exercises this module directly, including the full flagged sequence.
*
* Two sets track state, keyed on each accordion item's own string id (a
* provider name on the Models page, a group id on the Consumers page —
* this module has no opinion on what the id means or on what counts as a
* "match"; callers decide that and pass the resulting id list in):
* - manuallyExpanded: items the user explicitly opened, independent of any
* search query. This is the state a cleared search returns to.
* - manuallyCollapsed: items the user explicitly closed WHILE a search
* query was auto-expanding them. Only ever consulted while a query is
* active (computeExpandedItems below) — once the query clears, effective
* state is manuallyExpanded alone, so entries here become inert.
* clearExpandOverrides drops them anyway, so a stale collapse from one
* search session cannot silently suppress a match in an unrelated later
* one.
*/
export interface ExpandState {
manuallyExpanded: Set<string>
manuallyCollapsed: Set<string>
}
/**
* computeExpandedItems returns the effective set of expanded item ids:
* manuallyExpanded verbatim when no query is active; with a query active,
* manuallyExpanded plus every id in matchingIds that is not in
* manuallyCollapsed (auto-expand every match, unless the user explicitly
* closed that one). The caller decides what "matching" means for its own
* view, and this module has no opinion on it either way —
* ProviderHealthPanel.vue passes every provider that itself matched at
* all (every match there implies at least one matching model, so every
* match auto-expands); ConsumerDirectory.vue instead passes only the
* subset of its own matches that matched via a member rather than via
* the group's own name (see that component's own doc comment for why it
* draws that narrower distinction).
*/
export function computeExpandedItems(state: ExpandState, hasQuery: boolean, matchingIds: string[]): Set<string> {
if (!hasQuery) return new Set(state.manuallyExpanded)
const expanded = new Set(state.manuallyExpanded)
for (const id of matchingIds) {
if (!state.manuallyCollapsed.has(id)) expanded.add(id)
}
return expanded
}
/**
* toggleItemExpand mutates state for one item, given whether it is
* CURRENTLY effectively expanded (computeExpandedItems' own result for
* that id — the caller passes this, rather than the function re-deriving
* it, so callers stay in charge of what "current" means for their own
* render).
*
* This is the exact fix for a review-flagged bug: the original
* implementation toggled manuallyExpanded.has(id) directly — the RAW
* manual flag, not the effective (possibly auto-expanded) one. Clicking a
* row that was only auto-expanded (matching the search, never manually
* opened) read manuallyExpanded.has(id) as false and ADDED it to
* manuallyExpanded — invisible immediately (it was already showing via
* auto-expand), but wrongly left it expanded after the query cleared,
* since manuallyExpanded now contained an item the user never actually
* chose to open. Toggling against the EFFECTIVE state fixes this in both
* directions:
* - Expanded only via auto-match, clicked to close: manuallyExpanded never
* gains the entry (nothing to remove); manuallyCollapsed gains it,
* suppressing the auto-expand for as long as the query stays active.
* Clearing the query drops back to manuallyExpanded, which never had it
* — correctly collapsed.
* - Expanded via a manual open from BEFORE a search started, still
* matches, clicked to close during the search: manuallyExpanded loses it
* (the user's own most recent action wins) and manuallyCollapsed gains
* it, so it also stays closed after the query clears — treating the
* in-search click as the user's current intent, not the older,
* pre-search one.
*/
export function toggleItemExpand(state: ExpandState, id: string, currentlyExpanded: boolean): void {
if (currentlyExpanded) {
state.manuallyExpanded.delete(id)
state.manuallyCollapsed.add(id)
} else {
state.manuallyCollapsed.delete(id)
state.manuallyExpanded.add(id)
}
}
/** clearExpandOverrides drops every manuallyCollapsed entry — called when the search query becomes empty, so a suppression from one search session never carries into an unrelated later one (manuallyCollapsed is otherwise never consulted outside an active query anyway; this only matters for a FUTURE query). */
export function clearExpandOverrides(state: ExpandState): void {
state.manuallyCollapsed.clear()
}
-33
View File
@@ -1,33 +0,0 @@
import { describe, expect, it } from 'vitest'
import { loadState } from './load-state'
import { staleNotice } from './stale-notice'
const at = new Date('2026-11-08T10:11:12Z')
describe('staleNotice', () => {
it.each([
{ name: 'no data, error', hasData: false, error: 'boom', want: null },
{ name: 'data, no error', hasData: true, error: '', want: null },
{ name: 'no data, no error', hasData: false, error: '', want: null },
])('is null: $name', ({ hasData, error, want }) => {
expect(staleNotice(hasData, error, at)).toBe(want)
})
it('names the error and the data age when data is shown and refresh fails', () => {
const msg = staleNotice(true, 'HTTP 503', at)
expect(msg).toContain('HTTP 503')
expect(msg).toContain(at.toLocaleTimeString())
})
it('omits the age when lastUpdated is unknown', () => {
expect(staleNotice(true, 'x', null)).toBe('Refresh failing: x.')
})
// Lean gate Gateway.Ui.Stale.no_silent_stale: ready + error always has a notice.
it.each([true, false])('never silent when ready with error (loading=%s)', (loading) => {
const state = loadState({ loading, hasData: true, error: 'e' })
expect(state).toBe('ready')
expect(staleNotice(true, 'e', at)).not.toBeNull()
})
})
-6
View File
@@ -1,6 +0,0 @@
/** staleNotice returns the text for a "showing old data" banner, or null. Shown only when data is on screen and the latest refresh failed. */
export function staleNotice(hasData: boolean, error: string, lastUpdated: Date | null): string | null {
if (!hasData || !error) return null
const at = lastUpdated ? ` Data from ${lastUpdated.toLocaleTimeString()}.` : ''
return `Refresh failing: ${error}.${at}`
}
+2 -253
View File
@@ -1,213 +1,7 @@
import { isVNode } from 'vue'
import { describe, expect, it } from 'vitest'
import CompactNumber from '@/components/CompactNumber.vue'
import { Badge } from '@/components/ui/badge'
import { composeTargetId, parseTargetCallerId, resolveTargetRef, targetCallerColumns, targetColumns } from './target-columns'
import type { AdminTargetHealthView, AdminTargetsResponse, AdminTargetView, AdminTotalsResponse } from '@/types/api'
/**
* Target health rendering (feat/target-health): mirrors usage-columns.
* spec.ts's own approach of exercising a ColumnDef's `cell` renderer
* directly (no component mount needed — vite.config.ts's `test` block
* runs vitest in the 'node' environment with no @vue/test-utils/jsdom in
* this package, so there is no existing "mount a .vue view" pattern to
* follow here; the health column's rendering logic lives entirely in this
* plain TanStack ColumnDef, exactly like usage-columns.ts's own cells, so
* the identical direct-call approach gives full coverage without either).
*/
function testTarget(health: AdminTargetHealthView): AdminTargetView {
return {
name: 'my-server',
url: 'https://mcp.example.com',
counters: { requestsPerMinute: 0, requestsPerDay: 0, requestsPerMonth: 0 },
health,
}
}
function healthCellOf(target: AdminTargetView): unknown {
const col = targetColumns().find((c) => c.id === 'health')
const cell = col?.cell as (ctx: { row: { original: AdminTargetView } }) => unknown
return cell({ row: { original: target } })
}
describe('targetColumns: health column', () => {
it('renders a destructive Badge for unhealthy, with a relative-time label and lastError in the title', () => {
const health: AdminTargetHealthView = {
state: 'unhealthy',
lastCheck: new Date(Date.now() - 42_000).toISOString(),
lastError: 'connection refused',
consecutiveFailures: 3,
source: 'probe',
}
const rendered = healthCellOf(testTarget(health))
expect(isVNode(rendered)).toBe(true)
const vnode = rendered as { type: unknown; props?: Record<string, unknown>; children?: unknown }
expect(vnode.type).toBe(Badge)
expect(vnode.props?.variant).toBe('destructive')
expect(vnode.props?.title).toBe('3 consecutive failures via probe: connection refused')
const slot = (vnode.children as { default: () => string }).default
expect(slot()).toMatch(/^unhealthy \(\d+s ago\)$/)
})
it('falls back to a bare "unhealthy" label when lastCheck is missing (version-skew defensive case)', () => {
const health: AdminTargetHealthView = { state: 'unhealthy', consecutiveFailures: 1 }
const rendered = healthCellOf(testTarget(health))
const vnode = rendered as { props?: Record<string, unknown>; children?: { default: () => string } }
expect(vnode.children?.default()).toBe('unhealthy')
// Singular "failure", no "via <source>", no lastError.
expect(vnode.props?.title).toBe('1 consecutive failure')
})
it('renders an outline Badge labeled "unknown" with a fixed explanatory title', () => {
const health: AdminTargetHealthView = { state: 'unknown', consecutiveFailures: 0 }
const rendered = healthCellOf(testTarget(health))
const vnode = rendered as { type: unknown; props?: Record<string, unknown>; children?: { default: () => string } }
expect(vnode.type).toBe(Badge)
expect(vnode.props?.variant).toBe('outline')
expect(vnode.props?.title).toBe('not observed yet — no traffic and probes disabled or not yet run')
expect(vnode.children?.default()).toBe('unknown')
})
it('renders no Badge for healthy — plain muted text with latency, and relative time + source in the title', () => {
const health: AdminTargetHealthView = {
state: 'healthy',
lastCheck: new Date(Date.now() - 5_000).toISOString(),
consecutiveFailures: 0,
latencyMs: 12,
source: 'traffic',
}
const rendered = healthCellOf(testTarget(health))
expect(isVNode(rendered)).toBe(true)
const vnode = rendered as { type: unknown; props?: Record<string, unknown>; children?: unknown }
expect(vnode.type).toBe('span')
expect(vnode.props?.class).toBe('text-muted-foreground')
// formatLatencyMs (lib/format.ts), not a raw "${latencyMs} ms" — no
// space, matching every other latency reading in this panel.
expect(vnode.children).toBe('healthy · 12ms')
expect(vnode.props?.title).toMatch(/^\d+s ago via traffic$/)
})
it('renders the healthy latency suffix in seconds via formatLatencyMs once above 1000ms', () => {
const health: AdminTargetHealthView = { state: 'healthy', consecutiveFailures: 0, latencyMs: 1500 }
const rendered = healthCellOf(testTarget(health))
const vnode = rendered as { children?: unknown }
expect(vnode.children).toBe('healthy · 1.5s')
})
it('omits the latency suffix for healthy when latencyMs is unknown', () => {
const health: AdminTargetHealthView = { state: 'healthy', consecutiveFailures: 0 }
const rendered = healthCellOf(testTarget(health))
const vnode = rendered as { children?: unknown; props?: Record<string, unknown> }
expect(vnode.children).toBe('healthy')
// Neither lastCheck nor source known — nothing to show in the title.
expect(vnode.props?.title).toBe('')
})
it('the health column is not sortable — three semantic states have no meaningful alphabetical order', () => {
const col = targetColumns().find((c) => c.id === 'health')
expect(col?.enableSorting).toBe(false)
})
// F4/F7 (feat/target-health review): "unknown" also covers a target
// that HAS been observed but has never succeeded, still below
// failureThreshold — that case carries real failure detail even
// though the label stays "unknown".
it('surfaces failure detail in the unknown badge title for a target observed but never succeeded', () => {
const health: AdminTargetHealthView = {
state: 'unknown',
consecutiveFailures: 2,
source: 'probe',
lastError: 'dial tcp: connection refused',
}
const rendered = healthCellOf(testTarget(health))
const vnode = rendered as { type: unknown; props?: Record<string, unknown>; children?: { default: () => string } }
expect(vnode.type).toBe(Badge)
expect(vnode.props?.variant).toBe('outline')
expect(vnode.props?.title).toBe('2 failures so far via probe: dial tcp: connection refused')
expect(vnode.children?.default()).toBe('unknown')
})
it('singular "failure" and no "via <source>"/lastError when only consecutiveFailures is known', () => {
const health: AdminTargetHealthView = { state: 'unknown', consecutiveFailures: 1 }
const rendered = healthCellOf(testTarget(health))
const vnode = rendered as { props?: Record<string, unknown> }
expect(vnode.props?.title).toBe('1 failure so far')
})
it('falls back to the outline "unknown" badge for any state other than healthy/unhealthy', () => {
// Defensive: healthCell's own state check is an explicit
// state === 'healthy' branch with "unknown" as the fallback for
// everything else — not the reverse — so a value this version of
// the webui does not recognize renders as "unknown", never as a
// silently-wrong "healthy".
const health = { state: 'something-future-versions-might-add', consecutiveFailures: 0 } as unknown as AdminTargetHealthView
const rendered = healthCellOf(testTarget(health))
const vnode = rendered as { type: unknown; props?: Record<string, unknown>; children?: { default: () => string } }
expect(vnode.type).toBe(Badge)
expect(vnode.props?.variant).toBe('outline')
expect(vnode.children?.default()).toBe('unknown')
})
})
function accessCellOf(access: AdminTargetView['access']): unknown {
const col = targetColumns().find((c) => c.id === 'access')
const cell = col?.cell as (ctx: { row: { original: AdminTargetView } }) => unknown
return cell({ row: { original: { ...testTarget({ state: 'unknown', consecutiveFailures: 0 }), access } } })
}
describe('targetColumns: access column', () => {
it('renders "All groups" for null and absent access', () => {
for (const access of [null, undefined]) {
const node = accessCellOf(access)
expect(isVNode(node) && node.children).toBe('All groups')
}
})
it('renders "No groups" for an empty access list, not "All groups"', () => {
const node = accessCellOf([])
expect(isVNode(node) && node.children).toBe('No groups')
})
it('renders one Badge per group for a non-empty access list', () => {
const node = accessCellOf(['a', 'b'])
expect(isVNode(node)).toBe(true)
const children = (node as { children: unknown[] }).children
expect(children).toHaveLength(2)
expect(children.every((c) => isVNode(c) && c.type === Badge)).toBe(true)
})
})
describe('targetColumns: name column selection', () => {
it('renders plain text with no onSelect (default, backward-compatible)', () => {
const col = targetColumns().find((c) => c.id === 'name')
const cell = col?.cell as (ctx: { row: { original: AdminTargetView } }) => unknown
const rendered = cell({ row: { original: testTarget({ state: 'unknown', consecutiveFailures: 0 }) } })
expect(isVNode(rendered) && rendered.type).toBe('span')
})
it('renders a clickable button that invokes onSelect with the row when given', () => {
const selected: AdminTargetView[] = []
const col = targetColumns((t) => selected.push(t)).find((c) => c.id === 'name')
const cell = col?.cell as (ctx: { row: { original: AdminTargetView } }) => unknown
const target = testTarget({ state: 'unknown', consecutiveFailures: 0 })
const rendered = cell({ row: { original: target } })
expect(isVNode(rendered) && rendered.type).toBe('button')
const onClick = (rendered as { props?: Record<string, unknown> }).props?.onClick as (e: MouseEvent) => void
onClick({ stopPropagation: () => {} } as MouseEvent)
expect(selected).toEqual([target])
})
})
import { composeTargetId, parseTargetCallerId, resolveTargetRef } from './target-columns'
import type { AdminTargetsResponse, AdminTargetView } from '@/types/api'
describe('composeTargetId', () => {
it('joins kind and name with a slash', () => {
expect(composeTargetId('mcp', 'fetch')).toBe('mcp/fetch')
@@ -232,51 +26,6 @@ describe('parseTargetCallerId', () => {
expect(parseTargetCallerId('mcp/fetch')).toEqual({ kind: 'mcp', target: 'fetch', caller: '' })
})
})
// dayOrMonthWindow moved to lib/range.ts (P2 item 2: a SHARED clamp used
// by stores/consumers.ts, stores/spend.ts, AND this module's own
// TargetCallers.vue — see range.spec.ts's own describe('dayOrMonthWindow').
describe('targetCallerColumns', () => {
function row(id: string, req: number): AdminTotalsResponse['rows'][number] {
return { id, values: { req } }
}
it('omits the Target column when showTarget is false', () => {
const columns = targetCallerColumns(false)
expect(columns.find((c) => c.id === 'target')).toBeUndefined()
expect(columns.map((c) => c.id)).toEqual(['caller', 'requests'])
})
it('includes the Target column, rendering "kind/target", when showTarget is true', () => {
const columns = targetCallerColumns(true)
const col = columns.find((c) => c.id === 'target')
expect(col).toBeDefined()
const cell = col?.cell as (ctx: { row: { original: AdminTotalsResponse['rows'][number] } }) => unknown
const rendered = cell({ row: { original: row('mcp/fetch/alice', 3) } })
expect(isVNode(rendered) && rendered.children).toBe('mcp/fetch')
})
it('caller column reads the parsed caller name, falling back to the raw id', () => {
const columns = targetCallerColumns(false)
const col = columns.find((c) => c.id === 'caller') as unknown as {
accessorFn: (r: AdminTotalsResponse['rows'][number], i: number) => unknown
}
const accessor = col.accessorFn
expect(accessor(row('mcp/fetch/alice', 3), 0)).toBe('alice')
expect(accessor(row('malformed', 3), 0)).toBe('malformed')
})
it('requests column renders a CompactNumber reading values.req, defaulting to 0', () => {
const columns = targetCallerColumns(false)
const col = columns.find((c) => c.id === 'requests')
const cell = col?.cell as (ctx: { row: { original: AdminTotalsResponse['rows'][number] } }) => unknown
const rendered = cell({ row: { original: { id: 'mcp/fetch/alice', values: {} } } })
expect(isVNode(rendered) && rendered.type).toBe(CompactNumber)
expect(isVNode(rendered) && rendered.props?.value).toBe(0)
})
})
// --- resolveTargetRef (P2 item: a hand-typed #targets?target=demo-mcp
// 400ed — parseTargetRef, stats_read.go, only accepts "mcp/{name}"/
// "agent/{name}") ---
+1 -216
View File
@@ -1,180 +1,4 @@
import type { ColumnDef } from '@tanstack/vue-table'
import { h } from 'vue'
import { Badge } from '@/components/ui/badge'
import { compactColumn } from '@/lib/columns'
import { formatElapsedAgo, formatLatencyMs } from '@/lib/format'
import type { AdminTargetHealthView, AdminTargetsResponse, AdminTargetView, AdminTotalsResponse } from '@/types/api'
// --- target health (feat/target-health) ---
//
// Mirrors ProviderHealthPanel.vue's own healthBadgeVariant/healthBadgeLabel
// convention for the discovery circuit breaker: a Badge only for the two
// states worth flagging (unhealthy, unknown); the common healthy case
// renders no badge at all, just muted inline text — the same "nothing to
// show reads as no badge" idiom every health/rate indicator in this panel
// already follows (see AdminTargetHealthView's own doc comment, api.ts,
// for what each field means).
const UNKNOWN_HEALTH_TITLE = 'not observed yet — no traffic and probes disabled or not yet run'
/** unhealthyLabel keeps the Badge's own visible text short — "unhealthy (Ns ago)" when lastCheck is known, plain "unhealthy" otherwise (defensive: a version-skewed server response omitting lastCheck on an unhealthy row). */
function unhealthyLabel(health: AdminTargetHealthView): string {
const ago = formatElapsedAgo(health.lastCheck)
return ago ? `unhealthy (${ago})` : 'unhealthy'
}
/** unhealthyTitle carries the detail the short label leaves out — consecutiveFailures, source, and lastError (when present) — e.g. "3 consecutive failures via probe: connection refused". */
function unhealthyTitle(health: AdminTargetHealthView): string {
const failWord = health.consecutiveFailures === 1 ? 'failure' : 'failures'
const sourcePart = health.source ? ` via ${health.source}` : ''
const base = `${health.consecutiveFailures} consecutive ${failWord}${sourcePart}`
return health.lastError ? `${base}: ${health.lastError}` : base
}
/** healthyTitle is the muted "healthy" text's hover detail — "Ns ago via probe/traffic" — omitting whichever half (relative time, source) the response does not carry. */
function healthyTitle(health: AdminTargetHealthView): string {
const ago = formatElapsedAgo(health.lastCheck)
if (!ago) return health.source ? `via ${health.source}` : ''
return health.source ? `${ago} via ${health.source}` : ago
}
/**
* unknownTitle renders the "unknown" badge's hover detail. F4
* (feat/target-health) reads "unknown" two different ways — see
* AdminTargetHealthView's own doc comment (types/api.ts): never observed
* at all, which gets the generic UNKNOWN_HEALTH_TITLE, or observed but
* never yet succeeded (still below failureThreshold), which carries real
* failure detail (consecutiveFailures/source/lastError) even though the
* label stays "unknown" — this surfaces that detail instead of the
* generic message, mirroring unhealthyTitle's own conditional shape.
*/
function unknownTitle(health: AdminTargetHealthView): string {
if (health.consecutiveFailures <= 0 && !health.lastError) return UNKNOWN_HEALTH_TITLE
const failWord = health.consecutiveFailures === 1 ? 'failure' : 'failures'
const sourcePart = health.source ? ` via ${health.source}` : ''
const base = `${health.consecutiveFailures} ${failWord} so far${sourcePart}`
return health.lastError ? `${base}: ${health.lastError}` : base
}
/**
* healthCell renders one row's health column: destructive Badge for
* unhealthy, muted plain text (plus " · " and formatLatencyMs when
* latencyMs is known) for the explicit healthy case, and an outline
* "unknown" Badge as the FALLBACK for everything else — not the reverse
* — so a state value this webui build does not recognize renders as
* "unknown" rather than silently reading as healthy.
*/
function healthCell(health: AdminTargetHealthView) {
if (health.state === 'unhealthy') {
return h(
Badge,
{ as: 'span', variant: 'destructive', class: 'font-normal', title: unhealthyTitle(health) },
() => unhealthyLabel(health),
)
}
if (health.state === 'healthy') {
const latencyPart = health.latencyMs !== undefined ? ` · ${formatLatencyMs(health.latencyMs)}` : ''
return h('span', { class: 'text-muted-foreground', title: healthyTitle(health) }, `healthy${latencyPart}`)
}
return h(Badge, { as: 'span', variant: 'outline', class: 'font-normal', title: unknownTitle(health) }, () => 'unknown')
}
/**
* targetColumns builds the shared TanStack `ColumnDef` set both the MCP
* servers and the Agents DataTable in TargetsView.vue use (admin.go:
* adminTargetView — the two tables share one identical row shape). name is
* plain text (not the ModelChip copy treatment — a target name is not a
* routable model id) UNLESS `onSelect` is given, in which case it renders
* as a real `<button>` (same structural convention as EntityLink.vue: a
* click opens that target's own caller breakdown, TargetCallers.vue,
* rather than navigating away — redesign-plan.md section 3.4's
* "TargetCallers.vue expander"). url is muted and truncated with a title
* attribute for the full value; health is the Badge/muted-text pair
* healthCell above builds (feat/target-health); access renders as a
* Badge per allowed group, or a muted "All groups" when unrestricted —
* the exact idiom ConsumerDirectory.vue's own group Access block already
* established (Providers/Models/MCP servers/Agents dt/dd pairs there).
*/
export function targetColumns(onSelect?: (target: AdminTargetView) => void): ColumnDef<AdminTargetView, unknown>[] {
return [
{
id: 'name',
header: 'Name',
accessorFn: (t) => t.name,
cell: ({ row }) => {
if (!onSelect) return h('span', { class: 'font-medium' }, row.original.name)
return h(
'button',
{
type: 'button',
class:
'cursor-pointer rounded-sm font-medium hover:text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',
title: `View ${row.original.name}'s callers`,
onClick: (event: MouseEvent) => {
event.stopPropagation()
onSelect(row.original)
},
},
row.original.name,
)
},
},
{
id: 'url',
header: 'URL',
accessorFn: (t) => t.url,
cell: ({ row }) =>
h(
'span',
{ class: 'block max-w-xs truncate text-muted-foreground', title: row.original.url },
row.original.url,
),
},
{
id: 'health',
header: 'Health',
// No natural sort order across three semantic states (healthy/
// unhealthy/unknown) — plain alphabetical would put "healthy" and
// "unhealthy" beside each other for the wrong reason. Same call the
// access column below makes for its own non-primitive shape.
enableSorting: false,
accessorFn: (t) => t.health.state,
cell: ({ row }) => healthCell(row.original.health),
},
{
id: 'access',
header: 'Access',
enableSorting: false,
accessorFn: (t) => (t.access ?? []).join(', '),
cell: ({ row }) => {
const access = row.original.access
// null/absent = every group; [] = no group (admin.go adminTargetView.Access).
if (access == null) return h('span', { class: 'text-muted-foreground' }, 'All groups')
if (access.length === 0) return h('span', { class: 'text-muted-foreground' }, 'No groups')
return h(
'div',
{ class: 'flex flex-wrap gap-1.5' },
access.map((name) => h(Badge, { key: name, as: 'span', variant: 'secondary', class: 'font-mono font-normal' }, () => name)),
)
},
},
compactColumn<AdminTargetView>('reqMin', 'req/min', (t) => t.counters.requestsPerMinute),
compactColumn<AdminTargetView>('reqDay', 'req/day', (t) => t.counters.requestsPerDay),
compactColumn<AdminTargetView>('reqMonth', 'req/month', (t) => t.counters.requestsPerMonth),
]
}
// --- target x caller (redesign-plan.md section 3.4's "TargetCallers.vue
// expander" + "top callers" card) ---
//
// GET /admin/api/usage/totals?kind=targetcaller (redesign-plan.md section
// 1.3.v) has no dedicated row type in types/api.ts — AdminTotalsResponse
// inlines its row shape rather than naming it, so `TargetCallerRow` is
// derived from that response's own `rows` element type here (single source
// of truth: a future field added to the inline shape needs no second edit
// in this file).
type TargetCallerRow = AdminTotalsResponse['rows'][number]
import type { AdminTargetsResponse } from '@/types/api'
export type TargetKind = 'mcp' | 'agent'
@@ -278,42 +102,3 @@ export function parseTargetCallerId(id: string): ParsedTargetCallerId {
if (second === -1) return { kind, target: rest, caller: '' }
return { kind, target: rest.slice(0, second), caller: rest.slice(second + 1) }
}
/**
* targetCallerColumns builds the shared TanStack `ColumnDef` set
* TargetCallers.vue's DataTable uses for both its modes: a single
* target's own caller breakdown (`showTarget: false` — the panel's own
* heading already names the target) and the fleet-wide "top callers" card
* (`showTarget: true` — each row's own target is not implied by anything
* else on screen). `requests` is the only metric the server returns for
* this kind (contract: "targetcaller req only"), so there is no metric
* picker here, unlike model-table-columns.ts's multi-metric table.
*/
export function targetCallerColumns(showTarget: boolean): ColumnDef<TargetCallerRow, unknown>[] {
const columns: ColumnDef<TargetCallerRow, unknown>[] = []
if (showTarget) {
columns.push({
id: 'target',
header: 'Target',
accessorFn: (row) => {
const p = parseTargetCallerId(row.id)
return `${p.kind}/${p.target}`
},
cell: ({ row }) => {
const p = parseTargetCallerId(row.original.id)
return h('span', { class: 'font-mono text-xs text-muted-foreground' }, `${p.kind}/${p.target}`)
},
})
}
columns.push({
id: 'caller',
header: 'Caller',
accessorFn: (row) => parseTargetCallerId(row.id).caller || row.id,
cell: ({ row }) => {
const caller = parseTargetCallerId(row.original.id).caller
return h('span', { class: 'font-medium' }, caller || row.original.id)
},
})
columns.push(compactColumn<TargetCallerRow>('requests', 'Requests', (row) => row.values.req ?? 0))
return columns
}
-323
View File
@@ -1,323 +0,0 @@
import type { VNode } from 'vue'
import { isVNode } from 'vue'
import { describe, expect, it } from 'vitest'
import EntityLink from '@/components/EntityLink.vue'
import { usageColumns } from './usage-columns'
import type { AdminUsageEntryView } from '@/types/api'
/**
* Compact-number rendering (feature v0.23 addendum) must land ONLY in
* each numeric column's cell renderer, never in its accessorFn — the
* accessorFn is what getSortedRowModel actually sorts by, so a compacted
* STRING there ("15.0M") would sort lexicographically instead of
* numerically. These tests exercise the ColumnDef objects directly
* (no table mount needed) to pin that separation.
*/
function testEntry(overrides: Partial<AdminUsageEntryView> = {}): AdminUsageEntryView {
return {
kind: 'user',
id: 'alice',
requestsPerMinute: 5,
requestsPerDay: 15_000_000,
tokensInPerDay: 999,
tokensOutPerDay: 0,
tokensInPerMonth: 0,
tokensOutPerMonth: 0,
costPerDayMicroUsd: 1_234_500,
costPerMonthMicroUsd: 0,
rejectionsPerDay: 0,
...overrides,
}
}
/**
* accessorFnOf narrows a plain `ColumnDef` (a union of accessor/display
* column shapes TypeScript does not narrow automatically) down to the
* `accessorFn` every numericColumn-built column in this test file
* actually carries — a thin, test-local cast, not a production type.
*/
function accessorFnOf(col: unknown): (row: AdminUsageEntryView, index: number) => unknown {
return (col as { accessorFn: (row: AdminUsageEntryView, index: number) => unknown }).accessorFn
}
function cellOf(col: unknown): (ctx: { row: { original: AdminUsageEntryView } }) => unknown {
return (col as { cell: (ctx: { row: { original: AdminUsageEntryView } }) => unknown }).cell
}
describe('usageColumns: sorting stays on raw numeric values', () => {
const columns = usageColumns('Name', 'Group', () => 'g')
it('a count column (reqDay) accessorFn returns the raw number, not a compact string', () => {
const col = columns.find((c) => c.id === 'reqDay')
expect(accessorFnOf(col)(testEntry(), 0)).toBe(15_000_000)
})
it('a count column cell renders a CompactNumber vnode, not the raw number as text, when no limit is configured', () => {
const col = columns.find((c) => c.id === 'reqDay')
const rendered = cellOf(col)({ row: { original: testEntry() } })
expect(isVNode(rendered)).toBe(true)
})
it('a cost column cell still renders plain formatted text (compact:false), not a CompactNumber vnode, when no limit is configured', () => {
const col = columns.find((c) => c.id === 'costDay')
const rendered = cellOf(col)({ row: { original: testEntry() } })
expect(isVNode(rendered)).toBe(false)
expect(rendered).toBe('$1.2345')
})
it('a storeDown row still masks every count cell as "?" regardless of compact rendering', () => {
const col = columns.find((c) => c.id === 'tokInDay')
const rendered = cellOf(col)({ row: { original: testEntry({ storeDown: true }) } })
expect(rendered).toBe('?')
})
// Review finding: TanStack's getAutoSortingFn only inspects rows 11+
// (RowSorting.js's own `flatRows.slice(10)`) to auto-detect numeric vs.
// string sorting, so a Groups table with 10 or fewer rows silently fell
// back to `basic` (plain string a > b comparison), sorting "10" before "9".
// An explicit sortingFn sidesteps that row-count-dependent auto-detection
// entirely.
it('the secondary (Members/Group) column declares an explicit sortingFn, not left to row-count-dependent auto-detection', () => {
const col = columns.find((c) => c.id === 'secondary')
expect((col as { sortingFn?: string }).sortingFn).toBe('alphanumeric')
})
it('sorting a set of entries by reqDay orders numerically, not lexicographically (the bug this separation prevents)', () => {
const col = columns.find((c) => c.id === 'reqDay')
const accessor = accessorFnOf(col)
const entries = [testEntry({ id: 'a', requestsPerDay: 15_000_000 }), testEntry({ id: 'b', requestsPerDay: 999 }), testEntry({ id: 'c', requestsPerDay: 12_000 })]
const sorted = [...entries].sort((x, y) => (accessor(x, 0) as number) - (accessor(y, 0) as number))
expect(sorted.map((e) => e.id)).toEqual(['b', 'c', 'a'])
// A lexicographic sort on the COMPACT TEXT would instead order
// "1,000+" digits, "12k", "15.0M" as strings ("12k" < "15.0M" <
// "999" alphabetically) — the wrong order, which is exactly why
// accessorFn must stay numeric.
})
})
// F1 (usage-vs-limit bars): a column built with limitOf renders a UsageBar
// beside its number ONLY when the row's own limit is actually configured
// and the row is not storeDown — no fabricated bar for an unlimited scope.
describe('usageColumns: F1 usage-vs-limit bars', () => {
const columns = usageColumns('Name', 'Group', () => 'g')
it('reqDay renders a bare CompactNumber vnode, no bar, when the row has no limit configured', () => {
const col = columns.find((c) => c.id === 'reqDay')
const rendered = cellOf(col)({ row: { original: testEntry() } }) as VNode
expect(rendered.type).not.toBe('span')
})
it('reqDay wraps the number with a UsageBar when the row has that limit configured', () => {
const col = columns.find((c) => c.id === 'reqDay')
const entry = testEntry({ limits: { requestsPerDay: 100 }, requestsPerDay: 40 })
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
expect(isVNode(rendered)).toBe(true)
expect(rendered.type).toBe('span')
const children = rendered.children as VNode[]
expect(children).toHaveLength(2)
expect(children[1].props?.ratio).toBeCloseTo(0.4)
})
it('the token-day columns measure the bar against the COMBINED in+out total, not each column\'s own individual count', () => {
const col = columns.find((c) => c.id === 'tokInDay')
const entry = testEntry({ limits: { tokensPerDay: 1000 }, tokensInPerDay: 300, tokensOutPerDay: 400 })
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
const children = rendered.children as VNode[]
expect(children[1].props?.ratio).toBeCloseTo(0.7)
})
it('a cost column converts its USD limit to micro-USD before computing the ratio', () => {
const col = columns.find((c) => c.id === 'costDay')
const entry = testEntry({ limits: { costPerDayUSD: 1 }, costPerDayMicroUsd: 250_000 })
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
const children = rendered.children as VNode[]
expect(children[1].props?.ratio).toBeCloseTo(0.25)
})
it('renders no bar for a storeDown row even when a limit is configured', () => {
const col = columns.find((c) => c.id === 'reqDay')
const entry = testEntry({ limits: { requestsPerDay: 100 }, storeDown: true })
expect(cellOf(col)({ row: { original: entry } })).toBe('?')
})
// P10 review fix: the token columns' bar must announce the COMBINED
// in+out measurement it actually shows, not the column's own single-
// direction header text — a screen-reader user has no other column
// beside it to infer that from, unlike a sighted reader.
it('the tokIn/day column\'s bar label spells out "tokens (in+out)/day", not the column header "tokIn/day"', () => {
const col = columns.find((c) => c.id === 'tokInDay')
const entry = testEntry({ limits: { tokensPerDay: 1000 }, tokensInPerDay: 300, tokensOutPerDay: 400 })
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
const children = rendered.children as VNode[]
expect(children[1].props?.label).toBe('tokens (in+out)/day')
})
it('the tokOut/month column\'s bar label spells out "tokens (in+out)/month"', () => {
const col = columns.find((c) => c.id === 'tokOutMonth')
const entry = testEntry({ limits: { tokensPerMonth: 1000 }, tokensInPerMonth: 300, tokensOutPerMonth: 400 })
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
const children = rendered.children as VNode[]
expect(children[1].props?.label).toBe('tokens (in+out)/month')
})
it('the req/day column\'s bar label is "req/day" (matches its own header — no in+out ambiguity there)', () => {
const col = columns.find((c) => c.id === 'reqDay')
const entry = testEntry({ limits: { requestsPerDay: 100 }, requestsPerDay: 40 })
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
const children = rendered.children as VNode[]
expect(children[1].props?.label).toBe('req/day')
})
// P11 review fix: numericColumn now reuses budgetRatios (lib/usage-bars.ts)
// instead of its own dropped limitOf/usdLimitMicros — a cost limit that
// rounds to 0 micro-USD is skipped (no bar, no Infinity/NaN ratio),
// exactly like Go, rather than the column's old independent conversion
// disagreeing with budgetRatios about it.
it('costDay renders no bar (skips, does not divide by 0) when the configured limit rounds to 0 micro-USD', () => {
const col = columns.find((c) => c.id === 'costDay')
const entry = testEntry({ limits: { costPerDayUSD: 0.0000001 }, costPerDayMicroUsd: 5 })
const rendered = cellOf(col)({ row: { original: entry } })
expect(isVNode(rendered)).toBe(false) // plain formatted text, not a UsageBar-wrapping span
})
})
// F6 (EntityLink id cell): the id column renders an EntityLink pointed at
// Consumers?user={id}, never a plain span — the click-through-to-detail
// affordance every Users/Members row gets.
describe('usageColumns: F6 id cell is an EntityLink', () => {
const columns = usageColumns('Name', 'Group', () => 'g')
const col = columns.find((c) => c.id === 'id')
it('renders an EntityLink vnode, not a plain span', () => {
const rendered = cellOf(col)({ row: { original: testEntry({ id: 'alice', kind: 'user' }) } }) as VNode
expect(rendered.type).toBe(EntityLink)
})
it('builds kind "user" and the row id, with the label matching', () => {
const rendered = cellOf(col)({ row: { original: testEntry({ id: 'alice', kind: 'user' }) } }) as VNode
expect(rendered.props?.kind).toBe('user')
expect(rendered.props?.id).toBe('alice')
expect(rendered.props?.label).toBe('alice')
})
it('is not masked by storeDown — the link stays clickable even for a row with stale/unknown counters', () => {
const rendered = cellOf(col)({ row: { original: testEntry({ id: 'alice', kind: 'user', storeDown: true }) } }) as VNode
expect(rendered.type).toBe(EntityLink)
})
})
describe('usageColumns: last seen column', () => {
const now = new Date(Date.UTC(2026, 3, 16, 12, 0, 0))
const columns = usageColumns('Name', 'Group', () => 'g', now)
const col = columns.find((c) => c.id === 'lastSeen')
it('accessorFn reads the raw unix-seconds value, defaulting to 0 when unset', () => {
expect(accessorFnOf(col)(testEntry(), 0)).toBe(0)
expect(accessorFnOf(col)(testEntry({ lastSeen: 123 }), 0)).toBe(123)
})
it('cell renders "never" when unset', () => {
expect(cellOf(col)({ row: { original: testEntry() } })).toBe('never')
})
it('cell renders a relative-time label when set', () => {
const seconds = Math.floor(now.getTime() / 1000) - 300
expect(cellOf(col)({ row: { original: testEntry({ lastSeen: seconds }) } })).toBe('5m ago')
})
it('is NOT masked by storeDown — lastSeen is its own counter family, independent of the usage counters storeDown guards', () => {
const seconds = Math.floor(now.getTime() / 1000) - 300
expect(cellOf(col)({ row: { original: testEntry({ lastSeen: seconds, storeDown: true }) } })).toBe('5m ago')
})
})
describe('usageColumns: optional source column', () => {
it('is absent when no sourceValue is passed', () => {
const columns = usageColumns('Name', 'Group', () => 'g')
expect(columns.find((c) => c.id === 'source')).toBeUndefined()
})
it('is inserted right after the secondary column when sourceValue is passed', () => {
const columns = usageColumns('Name', 'Group', () => 'g', new Date(), (e) => (e.id === 'alice' ? 'inline' : undefined))
const ids = columns.map((c) => c.id)
expect(ids.indexOf('source')).toBe(ids.indexOf('secondary') + 1)
})
it('renders the resolved source text', () => {
const columns = usageColumns('Name', 'Group', () => 'g', new Date(), (e) => (e.id === 'alice' ? 'inline' : undefined))
const col = columns.find((c) => c.id === 'source')
const rendered = cellOf(col)({ row: { original: testEntry({ id: 'alice' }) } }) as VNode
expect(rendered.children).toBe('inline')
})
it('renders an em dash when the lookup returns undefined (no matching /consumers entry)', () => {
const columns = usageColumns('Name', 'Group', () => 'g', new Date(), () => undefined)
const col = columns.find((c) => c.id === 'source')
const rendered = cellOf(col)({ row: { original: testEntry({ id: 'bob' }) } }) as VNode
expect(rendered.children).toBe('—')
})
})
// F4 (rejected/day column): destructive tint applies only once the count
// is actually positive — a healthy scope (0 rejections) renders plain,
// matching every other "nothing to show reads as no flag" indicator in
// this panel (ProviderHealthPanel.vue's badges).
describe('usageColumns: F4 rejected/day column', () => {
const columns = usageColumns('Name', 'Group', () => 'g')
const col = columns.find((c) => c.id === 'rejDay')
it('accessorFn reads the raw rejectionsPerDay number', () => {
expect(accessorFnOf(col)(testEntry({ rejectionsPerDay: 12 }), 0)).toBe(12)
})
it('renders no destructive class when rejectionsPerDay is 0', () => {
const rendered = cellOf(col)({ row: { original: testEntry({ rejectionsPerDay: 0 }) } }) as VNode
expect(rendered.props?.class).toBeUndefined()
})
it('renders a destructive class when rejectionsPerDay is positive', () => {
const rendered = cellOf(col)({ row: { original: testEntry({ rejectionsPerDay: 3 }) } }) as VNode
expect(rendered.props?.class).toBe('text-destructive')
})
it('masks as "?" for a storeDown row', () => {
expect(cellOf(col)({ row: { original: testEntry({ storeDown: true }) } })).toBe('?')
})
})
// F7 (cost forecast per row): costMonthProjColumn extrapolates each row's
// own costPerMonthMicroUsd against the SAME `now` every row in one
// usageColumns() call shares — passed in explicitly so this stays
// deterministic under test (coordinator brief: "now passed as prop for
// determinism").
describe('usageColumns: F7 cost/month (proj.) column', () => {
// Fixed at exactly the midpoint of a UTC 30-day month (April 2026) so
// elapsedFraction is a clean 0.5 — projectMonthEnd(mtd, 0.5) == mtd*2.
const now = new Date(Date.UTC(2026, 3, 16, 0, 0, 0))
const columns = usageColumns('Name', 'Group', () => 'g', now)
const col = columns.find((c) => c.id === 'costMonthProj')
it('renders the projected month-end cost, formatted', () => {
const entry = testEntry({ costPerMonthMicroUsd: 5_000_000 })
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
expect(rendered.children).toBe('$10.0000')
})
it('renders a destructive class + title when the projection exceeds the configured cost/month limit', () => {
const entry = testEntry({ costPerMonthMicroUsd: 5_000_000, limits: { costPerMonthUSD: 8 } })
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
expect(rendered.props?.class).toBe('text-destructive')
expect(rendered.props?.title).toMatch(/exceed/)
})
it('renders no destructive class when the projection stays under the limit', () => {
const entry = testEntry({ costPerMonthMicroUsd: 5_000_000, limits: { costPerMonthUSD: 20 } })
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
expect(rendered.props?.class).toBeUndefined()
})
it('masks as "?" for a storeDown row', () => {
expect(cellOf(col)({ row: { original: testEntry({ storeDown: true }) } })).toBe('?')
})
})
-274
View File
@@ -1,274 +0,0 @@
import type { ColumnDef } from '@tanstack/vue-table'
import { h } from 'vue'
import CompactNumber from '@/components/CompactNumber.vue'
import EntityLink from '@/components/EntityLink.vue'
import UsageBar from '@/components/UsageBar.vue'
import { EMPTY_CELL } from '@/lib/columns'
import { monthCostProjection, NOT_ENOUGH_DATA, WILL_EXCEED_TITLE } from '@/lib/forecast'
import { formatCost, formatExactInt, formatLimits } from '@/lib/format'
import { formatLastSeen } from '@/lib/last-seen'
import { BUDGET_RATIO_LABEL, budgetRatios } from '@/lib/usage-bars'
import type { AdminUsageEntryView } from '@/types/api'
/**
* numericColumn builds one right-aligned, sortable numeric column that
* reads '?' instead of a stale number while the entry's own scope has a
* down store — DataTable.vue's cell renderer, not the accessor, does this
* check, so sorting itself still uses the entry's real underlying value
* (a storeDown row sorts by its last-known number, same as the rest of
* the table; only the DISPLAYED text is masked). Mirrors the pre-DataTable
* UsageTable.vue template's own `entry.storeDown ? '?' : ...` convention.
*
* compact (default true) renders the value through CompactNumber (SI-
* style, with the exact figure on title/aria-label) instead of the plain
* `format`/String path — used for every raw token/request COUNT column
* below; the two cost columns pass compact:false, since formatCost
* already shows full precision and compacting a dollar figure is not
* this feature's concern. The accessorFn (and therefore sorting) always
* reads the true raw number either way — only the cell's rendered text
* changes.
*
* F1 (usage-vs-limit bars): `budgetId` optionally names WHICH
* lib/usage-bars.ts BudgetRatio this column illustrates (one of
* budgetRatios' own ids — "reqMin", "reqDay", "tokDay", "tokMonth",
* "costDay", "costMonth"). When the row is not storeDown and
* budgetRatios(row) actually contains that id (i.e. the scope has that
* limit configured), the cell renders a UsageBar beside the number.
*
* P11 review fix (DRY + correctness): this used to take its own
* `limitOf`/`usedOf` accessor pair and re-derive the USD->micro-USD
* conversion locally (a dropped usdLimitMicros helper) — a second,
* independent implementation of exactly what budgetRatios already computes,
* and one that disagreed with it: budgetRatios gated on the RAW USD value
* being truthy before rounding (a limit rounding to 0 micro-USD produced an
* Infinity/NaN ratio there), while this column's own usdLimitMicros rounded
* first — the two could show a bar in one place, mask it in the other, for
* the identical scope. Reusing budgetRatios here (now fixed to round-then-
* skip, matching Go — see that module's own doc comment) makes both paths
* agree by construction: there is only one ratio computation left, not two.
*
* BUDGET_RATIO_LABEL[budgetId] (P10 review fix), not the column's own
* `header`, backs the bar's accessible label: the token columns'
* "tokDay"/"tokMonth" ratio combines BOTH directions
* (budgetRatios' own doc comment), so the bar's aria-label spells out
* "tokens (in+out)/day" — the column HEADER stays "tokIn/day"/"tokOut/day"
* (that identity is real and worth keeping visually), but a screen-reader
* user hearing just "tokIn/day, 1,500 / 2,000" beside a cell showing 500
* has no other cue that the meter measures the combined total, not that
* column's own count.
*/
function numericColumn(
id: string,
header: string,
read: (entry: AdminUsageEntryView) => number,
format: (n: number) => string = String,
compact = true,
budgetId?: string,
): ColumnDef<AdminUsageEntryView, unknown> {
return {
id,
header,
accessorFn: read,
meta: { align: 'right' },
cell: ({ row }) => {
if (row.original.storeDown) return '?'
const value = read(row.original)
const valueNode = compact ? h(CompactNumber, { value }) : format(value)
if (!budgetId) return valueNode
const ratio = budgetRatios(row.original).find((r) => r.id === budgetId)
if (!ratio) return valueNode
const valueText = compact
? `${formatExactInt(ratio.used)} / ${formatExactInt(ratio.limit)}`
: `${format(ratio.used)} / ${format(ratio.limit)}`
return h('span', { class: 'inline-flex items-center justify-end gap-1.5' }, [
valueNode,
h(UsageBar, { ratio: ratio.ratio, label: BUDGET_RATIO_LABEL[budgetId] ?? header, valueText }),
])
},
}
}
/**
* rejDayColumn (F4) renders rejectionsPerDay — fleet-wide requests denied
* by a limit check today (types/api.ts's own doc comment). Not built via
* numericColumn: it needs a destructive tint whenever the count is
* positive at all (coordinator brief: "destructive tint when > 0"),
* independent of any configured limit/bar — a rejection count itself IS
* the signal, there is nothing to compare it against.
*/
function rejDayColumn(): ColumnDef<AdminUsageEntryView, unknown> {
return {
id: 'rejDay',
header: 'rejected/day',
accessorFn: (entry) => entry.rejectionsPerDay,
meta: { align: 'right' },
cell: ({ row }) => {
if (row.original.storeDown) return '?'
const value = row.original.rejectionsPerDay
return h(CompactNumber, { value, class: value > 0 ? 'text-destructive' : undefined })
},
}
}
/**
* costMonthProjColumn (F7) renders lib/forecast.ts's projected month-end
* cost for each row, extrapolated from that row's own costPerMonthMicroUsd
* — the same math CostForecastCard.vue applies to the Total entry, here
* applied per user/group so an operator can see WHICH scope is on track
* to blow its own cost/month limit, not just the fleet-wide total. Reuses
* lib/forecast.ts's own monthCostProjection (F7's one projection+headroom
* pairing) rather than calling projectMonthEnd/headroom separately here —
* the same helper ConsumerDirectory.vue's groupCostProjection and lib/
* usage-csv.ts's own CSV row call.
*
* `now` is threaded in from the caller (coordinator brief: "now passed as
* prop for determinism") rather than read via `new Date()` inside this
* module — usageColumns() takes it as an optional parameter, defaulting
* to the real current time for every production call site, so a test can
* pin it instead.
*/
function costMonthProjColumn(now: Date): ColumnDef<AdminUsageEntryView, unknown> {
return {
id: 'costMonthProj',
header: 'cost/month (proj.)',
meta: { align: 'right' },
// Sorting: a not-enough-data-yet row (null projection) has no real
// figure to compare — it sorts as if projected to 0, the smallest
// possible spend, rather than being excluded from sorting entirely.
accessorFn: (entry) => monthCostProjection(entry, now).micros ?? 0,
cell: ({ row }) => {
if (row.original.storeDown) return '?'
const projection = monthCostProjection(row.original, now)
if (projection.micros === null) return h('span', { class: 'text-muted-foreground' }, NOT_ENOUGH_DATA)
return h(
'span',
{
class: projection.willExceed ? 'text-destructive' : undefined,
title: projection.willExceed ? WILL_EXCEED_TITLE : undefined,
},
formatCost(projection.micros),
)
},
}
}
/**
* sourceColumn (Consumers redesign, redesign-plan.md section 3.4) renders
* a user's directory source — 'inline' (defined directly in the plugin
* config) or 'file' (loaded from users.file, admin.go: adminConsumerUser.
* Source) — via the caller-supplied `sourceValue` lookup (ConsumerDirectory.
* vue joins this row's id against the /admin/api/consumers response, which
* this module has no fetch access to itself). Only ever added when a
* caller passes `sourceValue` to usageColumns (see its own doc comment) —
* a group row (no such concept) and the headless Groups sort toolbar never
* get this column at all. `sourceValue` returning undefined (a group's
* nested member row whose name has no matching /consumers entry yet, e.g.
* mid-fetch) renders an em dash rather than blank, so the column never
* looks like a rendering bug.
*/
function sourceColumn(sourceValue: (entry: AdminUsageEntryView) => string | undefined): ColumnDef<AdminUsageEntryView, unknown> {
return {
id: 'source',
header: 'Source',
accessorFn: (entry) => sourceValue(entry) ?? '',
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, sourceValue(row.original) ?? EMPTY_CELL),
}
}
/**
* lastSeenColumn (Consumers redesign) renders AdminUsageEntryView.lastSeen
* via lib/last-seen.ts's formatLastSeen — added unconditionally (unlike
* sourceColumn above): lastSeen is a fleet-wide counter written for BOTH
* user and group scopes (redesign-plan.md section 1.2's last-seen family:
* "user + every group scope"), so it is meaningful in every context
* usageColumns() is used in, not just the flat Users table. A storeDown
* row is NOT masked as "?" here (unlike every numericColumn) — lastSeen is
* its own separate counter family (a SET, not the same INCRBY scope
* counters storeDown actually guards), so a down usage store does not
* make this value stale/unknown the way it does for req/tok/cost.
*/
function lastSeenColumn(now: Date): ColumnDef<AdminUsageEntryView, unknown> {
return {
id: 'lastSeen',
header: 'Last seen',
accessorFn: (entry) => entry.lastSeen ?? 0,
cell: ({ row }) => formatLastSeen(row.original.lastSeen, now),
}
}
/**
* usageColumns builds the shared TanStack `ColumnDef` set for one
* AdminUsageEntryView table. Used by UsageTable.vue (the flat Users list,
* and — reused unmodified — a group's nested member-user list inside
* ConsumerDirectory.vue's Groups accordion) and, headlessly (no `<Table>`
* render, see that component's own doc comment for why), by its Groups
* sort bar, so both surfaces sort by the exact same column semantics.
* idLabel/secondaryColumnLabel name the first two columns; secondaryValue
* reads the second column's per-row value (a user's group name, or a
* group's member count). `now` (F7) defaults to the real current time —
* see costMonthProjColumn's own doc comment for why a caller can override
* it. `sourceValue`, when supplied, inserts sourceColumn right after the
* secondary column — ConsumerDirectory.vue's flat Users table is the only
* caller that passes it (see sourceColumn's own doc comment).
*/
export function usageColumns(
idLabel: string,
secondaryColumnLabel: string,
secondaryValue: (entry: AdminUsageEntryView) => string,
now: Date = new Date(),
sourceValue?: (entry: AdminUsageEntryView) => string | undefined,
): ColumnDef<AdminUsageEntryView, unknown>[] {
const columns: ColumnDef<AdminUsageEntryView, unknown>[] = [
{
id: 'id',
header: idLabel,
accessorFn: (entry) => entry.id,
// EntityLink (redesign-plan.md section 3.5, replacing ScopeLink):
// this column only ever renders 'user' kind entries in practice —
// UsageTable.vue's own doc comment ("users, or a group's member
// users") — so it links straight to Consumers?user={id}, opening
// that row's own UserDetail, rather than a Charts scope jump.
cell: ({ row }) => h(EntityLink, { class: 'font-medium', label: row.original.id, kind: 'user', id: row.original.id }),
},
{
id: 'secondary',
header: secondaryColumnLabel,
accessorFn: secondaryValue,
// 'alphanumeric' (not the default auto-detected sortingFn): this
// column's value is a plain string everywhere EXCEPT the Groups
// toolbar, where ConsumerDirectory.vue passes memberCountOf — a
// numeric count rendered as a string. TanStack's getAutoSortingFn
// only inspects rows 11+ (flatRows.slice(10)) to decide numeric vs
// basic, so a groups table with 10 or fewer rows silently fell back
// to `basic` (plain a > b string comparison), sorting "10" before
// "9". 'alphanumeric' handles both cases correctly regardless of row
// count: numeric substrings compare numerically, and it degrades
// gracefully for the plain-text group-name case (secondaryValue on
// the Users table).
sortingFn: 'alphanumeric',
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, secondaryValue(row.original)),
},
]
if (sourceValue) columns.push(sourceColumn(sourceValue))
columns.push(
{
id: 'limits',
header: 'Limits',
accessorFn: (entry) => formatLimits(entry.limits),
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, formatLimits(row.original.limits)),
},
numericColumn('reqMin', 'req/min', (e) => e.requestsPerMinute, String, true, 'reqMin'),
numericColumn('reqDay', 'req/day', (e) => e.requestsPerDay, String, true, 'reqDay'),
rejDayColumn(),
numericColumn('tokInDay', 'tokIn/day', (e) => e.tokensInPerDay, String, true, 'tokDay'),
numericColumn('tokOutDay', 'tokOut/day', (e) => e.tokensOutPerDay, String, true, 'tokDay'),
numericColumn('tokInMonth', 'tokIn/month', (e) => e.tokensInPerMonth, String, true, 'tokMonth'),
numericColumn('tokOutMonth', 'tokOut/month', (e) => e.tokensOutPerMonth, String, true, 'tokMonth'),
numericColumn('costDay', 'cost/day', (e) => e.costPerDayMicroUsd, formatCost, false, 'costDay'),
numericColumn('costMonth', 'cost/month', (e) => e.costPerMonthMicroUsd, formatCost, false, 'costMonth'),
costMonthProjColumn(now),
lastSeenColumn(now),
)
return columns
}
-104
View File
@@ -1,104 +0,0 @@
import { describe, expect, it } from 'vitest'
import { groupMatches, groupNameMatches, matchingMembersOfGroup, membersOfGroup, userMatches } from './usage-search'
import type { AdminUsageEntryView } from '@/types/api'
/** entry builds a minimal AdminUsageEntryView — only id/groupName/groups matter to this module, the rest are never read. */
function entry(id: string, groupName?: string, groups?: string[]): AdminUsageEntryView {
return {
kind: groupName === undefined ? 'group' : 'user',
id,
groupName,
groups,
requestsPerMinute: 0,
requestsPerDay: 0,
tokensInPerDay: 0,
tokensOutPerDay: 0,
tokensInPerMonth: 0,
tokensOutPerMonth: 0,
costPerDayMicroUsd: 0,
costPerMonthMicroUsd: 0,
rejectionsPerDay: 0,
}
}
const alice = entry('alice', 'team-a')
const bob = entry('bob', 'team-a')
const carol = entry('carol', 'team-b')
const teamA = entry('team-a')
const teamB = entry('team-b')
const users = [alice, bob, carol]
describe('userMatches', () => {
it('matches a case-insensitive substring of the id (query pre-lowercased by the caller)', () => {
expect(userMatches(alice, 'lic')).toBe(true)
})
it('does not match an unrelated query', () => {
expect(userMatches(alice, 'zzz')).toBe(false)
})
})
describe('groupNameMatches', () => {
it('matches on the group id alone, ignoring members entirely', () => {
expect(groupNameMatches(teamA, 'team-a')).toBe(true)
})
it('does not match a query that only a member would match', () => {
expect(groupNameMatches(teamA, 'alice')).toBe(false)
})
})
describe('membersOfGroup', () => {
it('joins users to a group on groupName === group.id', () => {
expect(membersOfGroup(teamA, users)).toEqual([alice, bob])
expect(membersOfGroup(teamB, users)).toEqual([carol])
})
// Multi-group support (review finding 4): a user's full membership lives
// in `groups` (admin.go's adminUsageEntryView.Groups); groupName alone
// only ever carries the FIRST one. Before this fix, membersOfGroup's
// `groupName === group.id` join silently dropped a multi-group user from
// every group but their first.
it('joins a multi-group user into EVERY one of their member groups via `groups`, not just groupName', () => {
const dave = entry('dave', 'team-a', ['team-a', 'team-b'])
const roster = [alice, bob, carol, dave]
expect(membersOfGroup(teamA, roster)).toEqual([alice, bob, dave])
expect(membersOfGroup(teamB, roster)).toEqual([carol, dave])
})
it('falls back to [groupName] when `groups` is absent (a single-group user, or a fixture predating the field)', () => {
expect(membersOfGroup(teamA, users)).toEqual([alice, bob])
})
})
describe('matchingMembersOfGroup', () => {
it('returns only the group members that themselves match query', () => {
expect(matchingMembersOfGroup(teamA, users, 'alice')).toEqual([alice])
})
it('returns an empty array when no member matches', () => {
expect(matchingMembersOfGroup(teamA, users, 'zzz')).toEqual([])
})
})
describe('groupMatches', () => {
it('matches via the group’s own name, with no matching member', () => {
expect(groupMatches(teamA, users, 'team-a')).toBe(true)
})
it('matches via a member, with no name match', () => {
expect(groupMatches(teamA, users, 'alice')).toBe(true)
})
it('does not match when neither the name nor any member matches', () => {
expect(groupMatches(teamA, users, 'zzz')).toBe(false)
})
it('a group with no members only matches by name', () => {
const lonely = entry('lonely-group')
expect(groupMatches(lonely, users, 'lonely')).toBe(true)
expect(groupMatches(lonely, users, 'alice')).toBe(false)
})
})
-68
View File
@@ -1,68 +0,0 @@
import type { AdminUsageEntryView } from '@/types/api'
/**
* Shared matching helpers for the "Filter users or groups" search
* ConsumerDirectory.vue offers (operator directive: identical semantics,
* ONE implementation — no second copy of this logic; extracted here
* rather than left inline specifically because the pre-redesign Usage
* AND Charts tabs both needed the identical matching rules before this
* module existed).
*
* Every `query` parameter here is expected to already be trimmed and
* lowercased by the caller, mirroring ProviderHealthPanel.vue's own
* normalizedQuery convention (modelMatches/aliasMatches there never
* re-normalize either) — these functions stay pure string/array
* operations, with the caller owning the single source of truth for "is a
* query active at all".
*/
/** userMatches: a user matches when its own id (display name) contains query. */
export function userMatches(user: Pick<AdminUsageEntryView, 'id'>, query: string): boolean {
return user.id.toLowerCase().includes(query)
}
/** groupNameMatches: a group matches by its own id (display name) alone, ignoring its members. */
export function groupNameMatches(group: Pick<AdminUsageEntryView, 'id'>, query: string): boolean {
return group.id.toLowerCase().includes(query)
}
/**
* membersOfGroup: group's own member user rows, joined on group.id being
* one of the user's own member groups — a user's row carries its full
* membership in `groups` (admin.go's adminUsageEntryView.Groups, multi-group
* support) and falls back to the single-group `groupName` for a user
* predating that field (or a mock/fixture that only sets groupName). Never
* `groupName` alone: a multi-group user would otherwise silently drop out
* of every group but their first. This is a plain client-side join against
* the already-polled GET /admin/api/usage response, no extra fetch.
* ConsumerDirectory.vue calls this directly (replacing the pre-redesign
* Usage tab's own former local membersOf helper); matchingMembersOfGroup
* below builds on it too, which is how ConsumerDirectory.vue's own
* groupMatches call ends up depending on this same join — indirectly,
* through matchingMembersOfGroup — without calling membersOfGroup itself.
*/
export function membersOfGroup(group: Pick<AdminUsageEntryView, 'id'>, users: AdminUsageEntryView[]): AdminUsageEntryView[] {
return users.filter((u) => (u.groups ?? [u.groupName]).includes(group.id))
}
/** matchingMembersOfGroup: group's own members that themselves match query. */
export function matchingMembersOfGroup(
group: Pick<AdminUsageEntryView, 'id'>,
users: AdminUsageEntryView[],
query: string,
): AdminUsageEntryView[] {
return membersOfGroup(group, users).filter((u) => userMatches(u, query))
}
/**
* groupMatches: a group matches if its own name contains query OR it has
* at least one matching member (binding search semantics). Callers that
* need to distinguish WHICH of the two reasons a group matched — to decide
* whether to show all of its members or only the matching ones — use
* groupNameMatches and matchingMembersOfGroup directly instead (see
* ConsumerDirectory.vue's own memberOnlyMatchIds doc comment for that
* distinction).
*/
export function groupMatches(group: Pick<AdminUsageEntryView, 'id'>, users: AdminUsageEntryView[], query: string): boolean {
return groupNameMatches(group, query) || matchingMembersOfGroup(group, users, query).length > 0
}