refactor(webui): extract repeated dashboard elements into shared components

Markup and helpers that were copied between pages now live in one
place:
- ChartCard, StatDisabledAlert, StatItem, DetailField, BudgetRatioBars,
  LabeledSelect, TargetPicker and LoadStateView components
- lib/scope.ts, lib/columns.ts and lib/chart-palette.ts
- messageOf, isAuthRejection, and the USD to micro-USD conversion
  helpers
- one monthly cost projection, one date formatter, and the
  useCopyFeedback composable

Behaviour is unchanged. Before and after screenshots of every page
match at 390 and 1440 px. Empty-state text now comes from the shared
EmptyState component, and the user run-out date uses the short date
format. admin_assets_gen.go is regenerated.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
This commit is contained in:
2026-09-24 06:04:46 +01:00
parent ce39b8eb37
commit 2608e01c50
67 changed files with 2008 additions and 1136 deletions
+26 -1
View File
@@ -8,7 +8,7 @@
import { createPinia, setActivePinia } from 'pinia'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { AdminApiError, adminFetch } from './api'
import { AdminApiError, adminFetch, isAuthRejection, messageOf } from './api'
import { useAuthStore } from '@/stores/auth'
function jsonResponse(status: number, body: unknown): Response {
@@ -76,3 +76,28 @@ describe('adminFetch', () => {
expect(auth.error).toBe('invalid key, or not an admin')
})
})
describe('messageOf', () => {
it('returns an Error instance\'s own message', () => {
expect(messageOf(new Error('boom'))).toBe('boom')
})
it('stringifies a non-Error thrown value', () => {
expect(messageOf('plain string')).toBe('plain string')
expect(messageOf(404)).toBe('404')
expect(messageOf(null)).toBe('null')
})
})
describe('isAuthRejection', () => {
it('is true for an AdminApiError with status 401 or 403', () => {
expect(isAuthRejection(new AdminApiError('nope', 401))).toBe(true)
expect(isAuthRejection(new AdminApiError('nope', 403))).toBe(true)
})
it('is false for any other AdminApiError status or a non-AdminApiError value', () => {
expect(isAuthRejection(new AdminApiError('server error', 500))).toBe(false)
expect(isAuthRejection(new Error('plain'))).toBe(false)
expect(isAuthRejection('nope')).toBe(false)
})
})
+23
View File
@@ -61,3 +61,26 @@ export async function adminFetch<T>(path: string): Promise<T> {
}
return (await resp.json()) as T
}
/**
* messageOf (reuse-audit.md F4 step 1) extracts a human-readable message
* from a caught value of unknown shape: an Error's own `.message`, or the
* stringified value otherwise (a thrown string, object, etc.). The ONE
* shared implementation — every Pinia store's fetch action and every
* component with a local latest-request-wins fetch used to hand-roll this
* same ternary in its `catch` block.
*/
export function messageOf(err: unknown): string {
return err instanceof Error ? err.message : String(err)
}
/**
* isAuthRejection (reuse-audit.md F4 step 1) reports whether a caught
* value is an AdminApiError for a 401/403 — i.e. adminFetch has already
* rejected the stored key (authStore.reject) for this failure, so the
* caller's own `catch` block should return early instead of also setting
* its local `error` state with the same rejection.
*/
export function isAuthRejection(err: unknown): boolean {
return err instanceof AdminApiError && (err.status === 401 || err.status === 403)
}
+27
View File
@@ -0,0 +1,27 @@
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
@@ -0,0 +1,49 @@
// 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]!
}
+75
View File
@@ -0,0 +1,75 @@
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
@@ -0,0 +1,87 @@
// 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),
]
}
+8 -12
View File
@@ -2,26 +2,22 @@ import type { ColumnDef } from '@tanstack/vue-table'
import { h } from 'vue'
import { Badge } from '@/components/ui/badge'
import { EVENT_KIND_LABEL, eventKindVariant } from '@/lib/events-filter'
import { EMPTY_CELL } from '@/lib/columns'
import { eventKindVariant, kindLabel } from '@/lib/events-filter'
import { formatTimestamp } from '@/lib/format'
import type { AdminEventKind, AdminEventView } from '@/types/api'
/** kindLabel falls back to the raw kind string for a version-skewed server build emitting a kind EVENT_KIND_LABEL does not know — same "still render it" convention AdminEventView.kind's own `| string` union documents. */
function kindLabel(kind: string): string {
return EVENT_KIND_LABEL[kind as AdminEventKind] ?? kind
}
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 '—'
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(' → ') : '—'
return parts.length ? parts.join(' → ') : EMPTY_CELL
}
/**
@@ -63,7 +59,7 @@ export function eventsColumns(): ColumnDef<AdminEventView, unknown>[] {
accessorFn: (e) => e.user ?? e.group ?? '',
cell: ({ row }) => {
const text = scopeText(row.original)
return h('span', { class: text === '—' ? 'text-muted-foreground' : undefined }, text)
return h('span', { class: text === EMPTY_CELL ? 'text-muted-foreground' : undefined }, text)
},
},
{
@@ -73,7 +69,7 @@ export function eventsColumns(): ColumnDef<AdminEventView, unknown>[] {
accessorFn: (e) => `${e.model ?? ''} ${e.provider ?? ''}`,
cell: ({ row }) => {
const text = targetText(row.original)
return h('span', { class: text === '—' ? 'text-muted-foreground' : 'font-mono text-xs' }, text)
return h('span', { class: text === EMPTY_CELL ? 'text-muted-foreground' : 'font-mono text-xs' }, text)
},
},
{
@@ -88,7 +84,7 @@ export function eventsColumns(): ColumnDef<AdminEventView, unknown>[] {
meta: { align: 'right' },
accessorFn: (e) => e.status ?? 0,
cell: ({ row }) =>
h('span', { class: 'tabular-nums' }, row.original.status !== undefined ? String(row.original.status) : '—'),
h('span', { class: 'tabular-nums' }, row.original.status !== undefined ? String(row.original.status) : EMPTY_CELL),
},
{
id: 'message',
+13 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { eventKindVariant, EVENT_KIND_LABEL, EVENT_KINDS, filterEvents } from './events-filter'
import { eventKindVariant, EVENT_KIND_LABEL, EVENT_KINDS, filterEvents, kindLabel } from './events-filter'
import type { AdminEventView } from '@/types/api'
function event(overrides: Partial<AdminEventView> = {}): AdminEventView {
@@ -40,6 +40,18 @@ describe('EVENT_KINDS', () => {
})
})
describe('kindLabel', () => {
it('renders the known display label for every AdminEventKind', () => {
for (const kind of EVENT_KINDS) {
expect(kindLabel(kind)).toBe(EVENT_KIND_LABEL[kind])
}
})
it('falls back to the raw kind string for a kind this build does not recognize', () => {
expect(kindLabel('some_future_kind')).toBe('some_future_kind')
})
})
describe('eventKindVariant', () => {
it.each([
['rate_limit', 'destructive'],
+12
View File
@@ -26,6 +26,18 @@ export const EVENT_KIND_LABEL: Record<AdminEventKind, string> = {
* there first).
*/
export const EVENT_KINDS = Object.keys(EVENT_KIND_LABEL) as AdminEventKind[]
/**
* kindLabel (reuse-audit.md F13) renders one event's kind as display text,
* falling back to the raw kind string for a kind EVENT_KIND_LABEL does not
* know (a server newer than this webui build) — same forward-compat
* convention AdminEventView.kind's own `| string` union documents. The ONE
* shared implementation: lib/events-columns.ts's Events-tab column and
* HomePage.vue's "Latest events" card used to each hand-roll an identical
* copy of this exact ternary.
*/
export function kindLabel(kind: string): string {
return EVENT_KIND_LABEL[kind as AdminEventKind] ?? kind
}
/**
* eventKindVariant maps a kind to the shadcn-vue Badge variant its row
+33 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { headroom, MIN_PROJECTION_FRACTION, monthProgress, projectMonthEnd } from './forecast'
import { headroom, MIN_PROJECTION_FRACTION, monthCostProjection, monthProgress, NOT_ENOUGH_DATA, projectMonthEnd } from './forecast'
describe('monthProgress', () => {
it('reads 0 at the first instant of a UTC month', () => {
@@ -105,3 +105,35 @@ describe('headroom', () => {
expect(headroom(5_000_000, 5)).toEqual({ limitMicros: 5_000_000, remainingMicros: 0, willExceed: false })
})
})
describe('monthCostProjection', () => {
const halfMonth = new Date('2026-04-16T00:00:00Z') // Apr 1 -> May 1 UTC, elapsed 15/30 = 0.5
it('returns micros: null, willExceed: false too early in the month to project (NOT_ENOUGH_DATA is the caller\'s own display text)', () => {
const tooEarly = new Date('2026-04-01T00:00:00Z')
expect(monthCostProjection({ costPerMonthMicroUsd: 1_000_000 }, tooEarly)).toEqual({ micros: null, willExceed: false })
})
it('projects month-end cost and reports willExceed false when no limit is configured', () => {
expect(monthCostProjection({ costPerMonthMicroUsd: 15_000_000 }, halfMonth)).toEqual({ micros: 30_000_000, willExceed: false })
})
it('reports willExceed false when the projection stays under the entry\'s own configured limit', () => {
expect(monthCostProjection({ costPerMonthMicroUsd: 15_000_000, limits: { costPerMonthUSD: 100 } }, halfMonth)).toEqual({
micros: 30_000_000,
willExceed: false,
})
})
it('reports willExceed true when the projection crosses the entry\'s own configured limit', () => {
expect(monthCostProjection({ costPerMonthMicroUsd: 15_000_000, limits: { costPerMonthUSD: 10 } }, halfMonth)).toEqual({
micros: 30_000_000,
willExceed: true,
})
})
})
describe('NOT_ENOUGH_DATA', () => {
it('is a non-empty display string', () => {
expect(NOT_ENOUGH_DATA).toBeTruthy()
})
})
+39 -6
View File
@@ -15,11 +15,14 @@
// with the figure actually being projected on the last/first day of a
// month in any timezone west or east of UTC.
// MICROS_PER_USD (P11 review fix, DRY): imported from lib/usage-bars.ts,
// the one shared definition — this module used to declare its own
// identical copy, one of three (usage-bars.ts, usage-columns.ts) the
// coordinator's review flagged.
import { MICROS_PER_USD } from '@/lib/usage-bars'
// usdToMicros (P11 review fix, DRY; reuse-audit.md F8): imported from
// lib/usage-bars.ts, which re-exports lib/format.ts's own one shared
// definition — this module used to declare its own identical MICROS_PER_USD
// copy, one of three (usage-bars.ts, usage-columns.ts) an earlier review
// flagged, then hand-rolled `Math.round(x * MICROS_PER_USD)` here even
// after that consolidation (F8's own gap) instead of calling the shared
// conversion function.
import { usdToMicros } from '@/lib/usage-bars'
/**
* MIN_PROJECTION_FRACTION is the smallest elapsed-month fraction
@@ -100,7 +103,37 @@ export function headroom(projectedMicros: number | null, limitUsd: number | unde
if (projectedMicros === null || limitUsd === undefined || limitUsd <= 0) {
return { limitMicros: null, remainingMicros: null, willExceed: false }
}
const limitMicros = Math.round(limitUsd * MICROS_PER_USD)
const limitMicros = usdToMicros(limitUsd)
const remainingMicros = limitMicros - projectedMicros
return { limitMicros, remainingMicros, willExceed: remainingMicros < 0 }
}
/** NOT_ENOUGH_DATA (reuse-audit.md F7) is the ONE "too early in the month to project" message — projectMonthEnd's own null case, shown wherever a projected/run-out figure has nothing to report yet. */
export const NOT_ENOUGH_DATA = 'not enough data yet'
/** WILL_EXCEED_TITLE (reuse-audit.md F7) is the ONE tooltip text for a projection that crosses its own configured limit (headroom's own willExceed). */
export const WILL_EXCEED_TITLE = 'Projected to exceed the configured cost/month limit'
/** MonthCostProjection is monthCostProjection's own result: the projected month-end micro-USD total (null below MIN_PROJECTION_FRACTION, projectMonthEnd's own convention), and whether it crosses the entry's own configured cost/month limit. */
export interface MonthCostProjection {
micros: number | null
willExceed: boolean
}
/**
* monthCostProjection projects one usage entry's month-end cost
* (projectMonthEnd) and checks it against that SAME entry's own configured
* cost/month limit (headroom) in one call — the ONE per-row month-end
* projection every table/detail-grid/CSV export in this panel used to
* re-derive separately (ConsumerDirectory.vue's groupCostProjection,
* lib/usage-columns.ts's costMonthProjColumn, lib/usage-csv.ts's own CSV
* row), each pairing projectMonthEnd + headroom by hand. Takes only the
* two fields it actually reads, not a full AdminUsageEntryView, so a
* caller building one from a narrower shape (or a test) never needs to
* fill in fields this has no use for.
*/
export function monthCostProjection(entry: { costPerMonthMicroUsd: number; limits?: { costPerMonthUSD?: number } }, now: Date): MonthCostProjection {
const projected = projectMonthEnd(entry.costPerMonthMicroUsd, monthProgress(now))
if (projected === null) return { micros: null, willExceed: false }
return { micros: projected, willExceed: headroom(projected, entry.limits?.costPerMonthUSD).willExceed }
}
+37 -1
View File
@@ -18,9 +18,45 @@ export function routableModelId(providerName: string, modelId: string): string {
return `${providerName}/${modelId}`
}
/**
* MICROS_PER_USD converts a plain USD amount (e.g. a LimitsConfig cost
* limit, `costPerDayUSD: 5`) into the micro-USD unit AdminUsageEntryView's
* own cost fields already use — matching metrics.go's usdToMicros(round)
* convention (ground truth, dashboard-plan.md section 0).
*
* reuse-audit.md F8: the ONE definition (moved here from lib/usage-bars.ts,
* which re-exports it for every existing import site) — usdToMicros/
* microsToUsd below are the ONE place a USD<->micro-USD conversion happens,
* replacing the hand-rolled `Math.round(usd * 1_000_000)` / `micros /
* 1_000_000` copies that used to bypass this constant.
*/
export const MICROS_PER_USD = 1_000_000
/** usdToMicros converts a plain USD amount to micro-USD, rounded to the nearest whole micro-USD (metrics.go's own usdToMicros(round) convention). */
export function usdToMicros(usd: number): number {
return Math.round(usd * MICROS_PER_USD)
}
/** microsToUsd converts a micro-USD integer back to a plain USD float — the exact inverse of usdToMicros, modulo usdToMicros' own rounding. */
export function microsToUsd(micros: number): number {
return micros / MICROS_PER_USD
}
/** formatCost renders a micro-USD integer (adminUsageEntryView's convention) as "$1.2345". */
export function formatCost(micros: number): string {
return `$${(micros / 1_000_000).toFixed(4)}`
return `$${microsToUsd(micros).toFixed(4)}`
}
/**
* formatShortDate renders a Date as a compact "Oct 15" label (month/day
* only, no time-of-day) — reuse-audit.md F13: the ONE run-out-date format,
* replacing BurnDownChart.vue's and UserDetail.vue's two disagreeing
* formats (a short date vs. a full formatTimestamp). A PROJECTED date (a
* run-out estimate) should never imply false time-of-day precision, so
* this intentionally omits it.
*/
export function formatShortDate(d: Date): string {
return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
}
/** formatExactInt renders a raw integer count with thousands separators ("1,234,567") — the precise value CompactNumber.vue and the usage chart's tooltip carry alongside a compact rendering, never lost. */
+2 -2
View File
@@ -9,7 +9,7 @@
// boundaries for the same two underlying concepts (a used/limit ratio,
// a success rate) the rest of this panel already colors consistently.
import { providerRateStatus, providerSuccessRate } from '@/lib/provider-rate'
import { MICROS_PER_USD, ratioTier } from '@/lib/usage-bars'
import { ratioTier, usdToMicros } from '@/lib/usage-bars'
import type { AdminGroupView, AdminProviderView } from '@/types/api'
/** KpiTier is KpiTile.vue's own three-color scale — 'ok' (normal), 'warn' (approaching a limit / minor degradation), 'critical' (over a limit / severe degradation). */
@@ -27,7 +27,7 @@ export function sumGroupBudgetMicros(groups: AdminGroupView[]): number {
let total = 0
for (const group of groups) {
const limitUsd = group.limits?.costPerMonthUSD
if (limitUsd && limitUsd > 0) total += Math.round(limitUsd * MICROS_PER_USD)
if (limitUsd && limitUsd > 0) total += usdToMicros(limitUsd)
}
return total
}
+14 -51
View File
@@ -1,10 +1,10 @@
import type { ColumnDef } from '@tanstack/vue-table'
import { h } from 'vue'
import CompactNumber from '@/components/CompactNumber.vue'
import EntityLink from '@/components/EntityLink.vue'
import ModelChip from '@/components/ModelChip.vue'
import { Badge } from '@/components/ui/badge'
import { EMPTY_CELL, optionalColumn, usageMetricColumns } from '@/lib/columns'
import { formatContextWindow, formatCost, formatLatencyMs, formatModelCostHover } from '@/lib/format'
import { formatErrorRatePercent, providerErrorRate } from '@/lib/provider-rate'
import type { AdminCatalogResponse, AdminPerfResponse, AdminUsageModelsResponse, PriceSource } from '@/types/api'
@@ -117,7 +117,7 @@ function priceCell(row: ModelCatalogRow) {
// 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 ? formatModelCostHover(row.inputPerMTokUsd as number, row.outputPerMTokUsd as number) : '—'),
h('span', {}, known ? formatModelCostHover(row.inputPerMTokUsd as number, row.outputPerMTokUsd as number) : EMPTY_CELL),
h(Badge, { as: 'span', variant: 'outline', class: 'font-normal' }, () => PRICE_SOURCE_LABEL[source]),
])
}
@@ -162,18 +162,7 @@ export function modelCatalogColumns(): ColumnDef<ModelCatalogRow, unknown>[] {
h(EntityLink, { label: row.original.id, kind: 'model', id: row.original.id }),
]),
},
{
id: 'context',
header: 'Context',
meta: { align: 'right' },
accessorFn: (r) => r.contextTokens ?? 0,
cell: ({ row }) =>
h(
'span',
{ class: 'tabular-nums' },
row.original.contextTokens !== undefined ? formatContextWindow(row.original.contextTokens) : '—',
),
},
optionalColumn<ModelCatalogRow>('context', 'Context', (r) => r.contextTokens, formatContextWindow),
{
id: 'price',
header: 'Price',
@@ -191,7 +180,7 @@ export function modelCatalogColumns(): ColumnDef<ModelCatalogRow, unknown>[] {
{ as: 'span', variant: 'secondary', class: 'font-normal', title: "':free' suffix model — display-only, billing follows the Price column's own source" },
() => 'free',
)
: h('span', { class: 'text-muted-foreground' }, '—'),
: h('span', { class: 'text-muted-foreground' }, EMPTY_CELL),
},
{
id: 'aliases',
@@ -200,7 +189,7 @@ export function modelCatalogColumns(): ColumnDef<ModelCatalogRow, unknown>[] {
accessorFn: (r) => r.aliases.join(', '),
cell: ({ row }) => {
const aliases = row.original.aliases
if (aliases.length === 0) return h('span', { class: 'text-muted-foreground' }, '—')
if (aliases.length === 0) return h('span', { class: 'text-muted-foreground' }, EMPTY_CELL)
return h(
'div',
{ class: 'flex flex-wrap gap-1' },
@@ -208,27 +197,13 @@ export function modelCatalogColumns(): ColumnDef<ModelCatalogRow, unknown>[] {
)
},
},
{
id: 'requests',
header: 'Requests',
meta: { align: 'right' },
accessorFn: (r) => r.requests,
cell: ({ row }) => h(CompactNumber, { value: row.original.requests }),
},
{
id: 'tokensIn',
header: 'Tokens in',
meta: { align: 'right' },
accessorFn: (r) => r.tokensIn,
cell: ({ row }) => h(CompactNumber, { value: row.original.tokensIn }),
},
{
id: 'tokensOut',
header: 'Tokens out',
meta: { align: 'right' },
accessorFn: (r) => r.tokensOut,
cell: ({ row }) => h(CompactNumber, { value: row.original.tokensOut }),
},
// 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 !== 'cost'),
{
id: 'cost',
header: 'Cost',
@@ -242,20 +217,8 @@ export function modelCatalogColumns(): ColumnDef<ModelCatalogRow, unknown>[] {
return formatCost(r.costMicroUsd)
},
},
{
id: 'p50',
header: 'p50',
meta: { align: 'right' },
accessorFn: (r) => r.p50Ms ?? -1,
cell: ({ row }) => h('span', { class: 'tabular-nums' }, row.original.p50Ms !== undefined ? formatLatencyMs(row.original.p50Ms) : '—'),
},
{
id: 'p95',
header: 'p95',
meta: { align: 'right' },
accessorFn: (r) => r.p95Ms ?? -1,
cell: ({ row }) => h('span', { class: 'tabular-nums' }, row.original.p95Ms !== undefined ? formatLatencyMs(row.original.p95Ms) : '—'),
},
optionalColumn<ModelCatalogRow>('p50', 'p50', (r) => r.p50Ms, formatLatencyMs, { sortSentinel: -1 }),
optionalColumn<ModelCatalogRow>('p95', 'p95', (r) => r.p95Ms, formatLatencyMs, { sortSentinel: -1 }),
{
id: 'errorRate',
header: 'Error rate',
+4
View File
@@ -177,4 +177,8 @@ describe('formatErrorRatePercent', () => {
it('does not clamp a rate above 1 (should not occur with real counters, but is not silently capped)', () => {
expect(formatErrorRatePercent(1.8)).toBe('180%')
})
it('renders null as the caller-supplied nullLabel instead of the "no data" default', () => {
expect(formatErrorRatePercent(null, 'no traffic')).toBe('no traffic')
})
})
+7 -4
View File
@@ -118,13 +118,16 @@ export function providerErrorRate(attempts: number, failures: number): number |
* formatRatePercent above (a SUCCESS rate must never overstate itself as
* 100%; an ERROR rate must never round down to a misleadingly clean 0%).
* `null` (no traffic to compute a rate from — providerErrorRate's own
* "nothing to report" case) renders as "no data", never "0%". Not clamped
* to 100%: a rate above 1 should not occur with real counters, but this
* "nothing to report" case) renders as `nullLabel` (default "no data"),
* never "0%" — reuse-audit.md F13: the `nullLabel` param lets HomePage.vue's
* fleet-wide reading pass "no traffic" instead of hand-rolling an identical
* copy of this function with a different null wording. Not clamped to
* 100%: a rate above 1 should not occur with real counters, but this
* function reports whatever the caller computed rather than silently
* capping it (lib/series.ts's own ratioSeries makes the identical choice).
*/
export function formatErrorRatePercent(rate: number | null): string {
if (rate === null) return 'no data'
export function formatErrorRatePercent(rate: number | null, nullLabel = 'no data'): string {
if (rate === null) return nullLabel
if (rate <= 0) return '0%'
return `${Math.ceil(rate * 100)}%`
}
+114
View File
@@ -0,0 +1,114 @@
import { describe, expect, it } from 'vitest'
import { drilldownLevel, makeScope, parseScope, scopeBudgetLimits, scopeId } from './scope'
import type { AdminGroupView, AdminUsageEntryView } from '@/types/api'
function group(overrides: Partial<AdminGroupView> = {}): AdminGroupView {
return { name: 'eng', memberCount: 1, ...overrides }
}
function user(overrides: Partial<AdminUsageEntryView> = {}): AdminUsageEntryView {
return {
kind: 'user',
id: 'alice',
requestsPerMinute: 0,
requestsPerDay: 0,
tokensInPerDay: 0,
tokensOutPerDay: 0,
tokensInPerMonth: 0,
tokensOutPerMonth: 0,
costPerDayMicroUsd: 0,
costPerMonthMicroUsd: 0,
rejectionsPerDay: 0,
...overrides,
}
}
describe('parseScope', () => {
it.each([
['group:eng', { kind: 'group', id: 'eng' }],
['user:alice', { kind: 'user', id: 'alice' }],
['model:gpt-4', { kind: 'model', id: 'gpt-4' }],
['provider:openai', { kind: 'provider', id: 'openai' }],
] as const)('splits %s into its kind and id', (input, expected) => {
expect(parseScope(input)).toEqual(expected)
})
it('returns null for a string with no recognized "kind:" prefix', () => {
expect(parseScope('all')).toBeNull()
expect(parseScope('total')).toBeNull()
expect(parseScope('')).toBeNull()
})
it('splits only on the FIRST colon, keeping the rest of the id intact', () => {
expect(parseScope('model:openai/gpt-4:latest')).toEqual({ kind: 'model', id: 'openai/gpt-4:latest' })
})
})
describe('scopeId', () => {
it('strips the "kind:" prefix', () => {
expect(scopeId('group:eng')).toBe('eng')
expect(scopeId('provider:openai')).toBe('openai')
})
it('returns the string unchanged when it carries no recognized prefix', () => {
expect(scopeId('all')).toBe('all')
expect(scopeId('total')).toBe('total')
})
})
describe('makeScope', () => {
it('is parseScope\'s own inverse', () => {
expect(makeScope('group', 'eng')).toBe('group:eng')
expect(parseScope(makeScope('user', 'alice'))).toEqual({ kind: 'user', id: 'alice' })
})
})
describe('drilldownLevel', () => {
it('reads "" as the group level', () => {
expect(drilldownLevel('')).toEqual({ kind: 'group' })
})
it('reads "group:x" as the user level, naming the parent group', () => {
expect(drilldownLevel('group:eng')).toEqual({ kind: 'user', group: 'eng' })
})
it('reads "user:x" as the usermodel level, naming the user', () => {
expect(drilldownLevel('user:alice')).toEqual({ kind: 'usermodel', user: 'alice' })
})
it('reads any other non-empty string as the usermodel level verbatim (defensive fallback)', () => {
expect(drilldownLevel('alice')).toEqual({ kind: 'usermodel', user: 'alice' })
})
})
describe('scopeBudgetLimits', () => {
const groups = [group({ name: 'eng', limits: { costPerMonthUSD: 100 } }), group({ name: 'ops', limits: { costPerMonthUSD: 50 } })]
const users = [user({ id: 'alice', limits: { costPerMonthUSD: 10 } })]
it('sums every configured group\'s own budget for "all" (or any other unscoped root string)', () => {
expect(scopeBudgetLimits('all', groups, users)).toEqual({ costPerMonthUSD: 150 })
expect(scopeBudgetLimits('total', groups, users)).toEqual({ costPerMonthUSD: 150 })
})
it('returns undefined for the fleet-wide sum when no group has a budget configured', () => {
expect(scopeBudgetLimits('all', [group({ limits: undefined })], [])).toBeUndefined()
})
it('resolves a group scope to that one group\'s own limits', () => {
expect(scopeBudgetLimits('group:eng', groups, users)).toEqual({ costPerMonthUSD: 100 })
})
it('resolves a user scope to that one user\'s own limits', () => {
expect(scopeBudgetLimits('user:alice', groups, users)).toEqual({ costPerMonthUSD: 10 })
})
it('returns undefined for a group/user scope this fleet does not actually have', () => {
expect(scopeBudgetLimits('group:nope', groups, users)).toBeUndefined()
expect(scopeBudgetLimits('user:nope', groups, users)).toBeUndefined()
})
it('returns undefined for a provider scope (no single group/user limit applies)', () => {
expect(scopeBudgetLimits('provider:openai', groups, users)).toBeUndefined()
})
})
+91
View File
@@ -0,0 +1,91 @@
// reuse-audit.md F5: scope-string parsing (the `group:`/`user:`/`model:`/
// `provider:` prefix convention shared by stores/filters.ts's global scope
// filter, AttributionDrilldown's `drill` breadcrumb, and every per-series
// `scope` string an /admin/api/usage/* or /admin/api/events response
// carries) used to be reimplemented at every call site: a prefix strip
// three different ways, `drilldownLevel` duplicated verbatim, and a
// scope-to-budget lookup written out twice more. Kept pure and out of any
// component/store the same way lib/series.ts and lib/kpi.ts keep their own
// math out of theirs — vitest's node-environment config exercises every
// function here directly, no component mount required.
import { sumGroupBudgetMicros } from '@/lib/kpi'
import { microsToUsd } from '@/lib/usage-bars'
import type { AdminGroupView, AdminUsageEntryView, LimitsConfig } from '@/types/api'
/** ScopeKind is every prefix a "kind:id" scope string can carry across this panel — not every caller accepts every kind (a Spend burn-down scope never carries 'provider', a Reliability series scope never carries 'group'/'user'), but the prefix syntax itself is the same everywhere. */
export type ScopeKind = 'group' | 'user' | 'model' | 'provider'
export interface ParsedScope {
kind: ScopeKind
id: string
}
/**
* parseScope splits a "kind:id" scope string into its parts. Returns null
* for a string with no recognized "kind:" prefix — a caller's own root/
* unscoped sentinel ('all', 'total', or AttributionDrilldown's drill ''),
* which only that caller knows how to interpret, so this never guesses at
* one.
*/
export function parseScope(scope: string): ParsedScope | null {
for (const kind of ['group', 'user', 'model', 'provider'] as const) {
const prefix = `${kind}:`
if (scope.startsWith(prefix)) return { kind, id: scope.slice(prefix.length) }
}
return null
}
/** scopeId strips a scope string's own "kind:" prefix, or returns it unchanged when it carries none (the caller's own root sentinel, or an id that was never prefixed to begin with). */
export function scopeId(scope: string): string {
return parseScope(scope)?.id ?? scope
}
/** makeScope builds a "kind:id" scope string — parseScope's own inverse. */
export function makeScope(kind: ScopeKind, id: string): string {
return `${kind}:${id}`
}
/** DrilldownLevel is AttributionDrilldown's current GET /admin/api/usage/totals request shape, derived from its `drill` breadcrumb state. */
export type DrilldownLevel = { kind: 'group' } | { kind: 'user'; group: string } | { kind: 'usermodel'; user: string }
/**
* drilldownLevel derives AttributionDrilldown's current level from its
* `drill` breadcrumb state: '' is the top (every group listed), a
* `group:{name}` drill shows that group's own users, anything else is
* read as a `user:{name}` drill showing that user's own per-model
* breakdown — the ONE definition (moved from stores/spend.ts, which used
* to duplicate AttributionDrilldown.vue's own identical copy verbatim).
*/
export function drilldownLevel(drill: string): DrilldownLevel {
if (drill === '') return { kind: 'group' }
const parsed = parseScope(drill)
if (parsed?.kind === 'group') return { kind: 'user', group: parsed.id }
return { kind: 'usermodel', user: parsed?.kind === 'user' ? parsed.id : drill }
}
/**
* scopeBudgetLimits resolves the configured cost/month LimitsConfig for a
* `filters.scope`-shaped string (redesign-plan.md section 3.1:
* `scope=all|group:x|user:x|provider:x`) from the already-polled dashboard
* overview/usage data — no second network round trip. `'all'` (or any
* unscoped/root string parseScope does not recognize a `group:`/`user:`
* prefix on) resolves to the FLEET-WIDE sum of every configured group's
* own budget (Q2/DECISIONS: lib/kpi.ts's sumGroupBudgetMicros — the ONE
* fleet-budget definition, replacing SpendPage.vue's own inline recompute
* of the identical sum), `undefined` when that total is 0 ("no budget
* set", never a fabricated zero-dollar budget). `group:`/`user:` resolve
* to that one group's/user's own configured limits (undefined if the
* scope names a group/user this fleet does not actually have); a
* `provider:` scope (or any other unrecognized prefix) has no single
* group/user limit to report and also resolves to undefined.
*/
export function scopeBudgetLimits(scope: string, groups: AdminGroupView[], users: AdminUsageEntryView[]): LimitsConfig | undefined {
const parsed = parseScope(scope)
if (!parsed) {
const totalMicros = sumGroupBudgetMicros(groups)
return totalMicros > 0 ? { costPerMonthUSD: microsToUsd(totalMicros) } : undefined
}
if (parsed.kind === 'group') return groups.find((g) => g.name === parsed.id)?.limits
if (parsed.kind === 'user') return users.find((u) => u.id === parsed.id)?.limits
return undefined
}
+4 -1
View File
@@ -11,6 +11,8 @@
// keep their own math out of theirs — vitest's node-environment config
// exercises every function here directly, no component mount required.
import { parseScope } from '@/lib/scope'
/** One AdminSeriesResponse series entry: a scope id and its bucket-aligned points (types/api.ts: AdminSeriesResponse['series'][number]). */
export interface Series {
scope: string
@@ -86,7 +88,8 @@ export function other(totalPoints: number[], charted: Series[]): number[] {
export function sumByProvider(series: Series[]): Series[] {
const byProvider = new Map<string, number[]>()
for (const s of series) {
const id = s.scope.startsWith('model:') ? s.scope.slice('model:'.length) : s.scope
const parsed = parseScope(s.scope)
const id = parsed?.kind === 'model' ? parsed.id : s.scope
const slash = id.indexOf('/')
const provider = slash === -1 ? id : id.slice(0, slash)
const acc = byProvider.get(provider) ?? new Array<number>(s.points.length).fill(0)
+18
View File
@@ -10,6 +10,7 @@ import {
isValidNonNegativeInt,
isValidUserName,
modelMetaSnippet,
parseList,
pricingSnippet,
userGrantJsonFragment,
userJsonLine,
@@ -17,6 +18,23 @@ import {
validatePersonalGrant,
} from './snippets'
describe('parseList', () => {
it('splits on commas and trims whitespace', () => {
expect(parseList('anthropic, openai , gx10')).toEqual(['anthropic', 'openai', 'gx10'])
})
it('drops empty entries (blank field, trailing comma, doubled comma)', () => {
expect(parseList('')).toEqual([])
expect(parseList('anthropic,')).toEqual(['anthropic'])
expect(parseList('anthropic,,openai')).toEqual(['anthropic', 'openai'])
expect(parseList(' ')).toEqual([])
})
it('de-duplicates, keeping first-seen order', () => {
expect(parseList('anthropic, openai, anthropic')).toEqual(['anthropic', 'openai'])
})
})
// Golden strings below are checked against the REAL production shapes in
// home-cluster/kubernetes/namespaces/traefik/base/llmgateway/middleware.yaml
// and users-configmap.yaml (read this session) — structure and field order
+14
View File
@@ -28,6 +28,20 @@ export const NAME_PATTERN = /^[a-zA-Z0-9._-]+$/
export function isValidName(name: string): boolean {
return NAME_PATTERN.test(name)
}
/**
* parseList (reuse-audit.md F12) splits a comma-separated form field into
* trimmed, non-empty, de-duplicated entries — the ONE shared parser
* GrantForm.vue's and UserForm.vue's own two identical copies (providers/
* models/mcpServers/agents, extraGroups) each hand-rolled.
*/
export function parseList(raw: string): string[] {
const seen = new Set<string>()
for (const part of raw.split(',')) {
const trimmed = part.trim()
if (trimmed) seen.add(trimmed)
}
return Array.from(seen)
}
/**
* isValidUserName mirrors auth.go's own buildEntry check (~955-975,
+5 -33
View File
@@ -1,33 +1,11 @@
import type { ColumnDef } from '@tanstack/vue-table'
import { h } from 'vue'
import CompactNumber from '@/components/CompactNumber.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'
/**
* numericColumn builds one right-aligned, sortable request-counter
* column, rendered via CompactNumber (SI-style, exact value on title/
* aria-label — usage-columns.ts's own numericColumn applies the
* identical treatment). Mirrors usage-columns.ts's own helper of the
* same name and purpose, but without that one's storeDown '?' masking: a
* target's counters carry no storeDown flag (limiter.targetUsage,
* limits.go — a target scope has no limit to protect from a
* misleadingly-confident zero, unlike a limited user/group scope), so
* there is nothing to mask here. accessorFn (and therefore sorting)
* always reads the true raw number.
*/
function numericColumn(id: string, header: string, read: (t: AdminTargetView) => number): ColumnDef<AdminTargetView, unknown> {
return {
id,
header,
accessorFn: read,
meta: { align: 'right' },
cell: ({ row }) => h(CompactNumber, { value: read(row.original) }),
}
}
// --- target health (feat/target-health) ---
//
// Mirrors ProviderHealthPanel.vue's own healthBadgeVariant/healthBadgeLabel
@@ -181,9 +159,9 @@ export function targetColumns(onSelect?: (target: AdminTargetView) => void): Col
)
},
},
numericColumn('reqMin', 'req/min', (t) => t.counters.requestsPerMinute),
numericColumn('reqDay', 'req/day', (t) => t.counters.requestsPerDay),
numericColumn('reqMonth', 'req/month', (t) => t.counters.requestsPerMonth),
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),
]
}
@@ -336,12 +314,6 @@ export function targetCallerColumns(showTarget: boolean): ColumnDef<TargetCaller
return h('span', { class: 'font-medium' }, caller || row.original.id)
},
})
columns.push({
id: 'requests',
header: 'Requests',
meta: { align: 'right' },
accessorFn: (row) => row.values.req ?? 0,
cell: ({ row }) => h(CompactNumber, { value: row.original.values.req ?? 0 }),
})
columns.push(compactColumn<TargetCallerRow>('requests', 'Requests', (row) => row.values.req ?? 0))
return columns
}
+12 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { BAR_AMBER_THRESHOLD, BAR_RED_THRESHOLD, budgetRatios, ratioTier } from './usage-bars'
import { BAR_AMBER_THRESHOLD, BAR_RED_THRESHOLD, budgetRatios, budgetValueText, ratioTier } from './usage-bars'
import type { AdminUsageEntryView } from '@/types/api'
function testEntry(overrides: Partial<AdminUsageEntryView> = {}): AdminUsageEntryView {
@@ -121,6 +121,17 @@ describe('budgetRatios', () => {
})
})
describe('budgetValueText', () => {
it('formats a cost-kind ratio (id starting "cost") through formatCost, both sides', () => {
expect(budgetValueText({ id: 'costMonth', used: 1_500_000, limit: 5_000_000, ratio: 0.3 })).toBe('$1.5000 / $5.0000')
})
it('formats every other kind through formatExactInt, both sides', () => {
expect(budgetValueText({ id: 'reqMin', used: 42, limit: 100, ratio: 0.42 })).toBe('42 / 100')
expect(budgetValueText({ id: 'tokDay', used: 1_500, limit: 2_000, ratio: 0.75 })).toBe('1,500 / 2,000')
})
})
// estimatedRunOutDate was removed (P2 item 14 — it disagreed with
// lib/burndown.ts's runOutDate on an already-exceeded budget and on day 1
// of the month; UserDetail.vue and BurnDownChart.vue now both call the
+30 -14
View File
@@ -38,19 +38,21 @@ export interface BudgetRatio {
}
/**
* MICROS_PER_USD converts a LimitsConfig cost limit (plain USD, e.g.
* `costPerDayUSD: 5`) into the same micro-USD unit AdminUsageEntryView's
* own cost fields already use — matching metrics.go's usdToMicros(round)
* convention (ground truth, dashboard-plan.md section 0).
*
* P11 review fix (DRY): this constant used to be declared independently
* three times (here, lib/forecast.ts, lib/usage-columns.ts) — this is now
* the ONE definition; lib/forecast.ts imports it, and lib/usage-columns.ts
* no longer needs its own copy at all (it now reads limits through
* budgetRatios below instead of re-deriving them — see numericColumn's own
* doc comment there).
* usdToMicros / microsToUsd (reuse-audit.md F8): moved to lib/format.ts
* (formatCost's own home — an "odd home" here, the audit's words, for
* conversions every cost-limit needs), re-exported here so every existing
* `from '@/lib/usage-bars'` import site (lib/forecast.ts, lib/kpi.ts, lib/
* usage-csv.ts, lib/scope.ts, stores/spend.ts, pages/HomePage.vue,
* components/UserDetail.vue) keeps working unchanged. P11 review fix
* (DRY) history: the underlying MICROS_PER_USD constant used to be
* declared independently three times (here, lib/forecast.ts, lib/usage-
* columns.ts) before the first consolidation onto this file; F8 is the
* second consolidation, onto lib/format.ts. MICROS_PER_USD itself is not
* re-exported here — nothing imports it from this module, only from lib/
* format.ts directly.
*/
export const MICROS_PER_USD = 1_000_000
export { usdToMicros, microsToUsd } from '@/lib/format'
import { formatCost, formatExactInt, usdToMicros } from '@/lib/format'
/**
* BUDGET_RATIO_LABEL (P10) names each BudgetRatio id in accurate,
@@ -122,11 +124,11 @@ export function budgetRatios(entry: AdminUsageEntryView): BudgetRatio[] {
// the rounded value, makes both paths agree with Go: a limit that rounds
// to 0 micro-USD is skipped, exactly like an unconfigured one.
if (limits.costPerDayUSD) {
const limitMicros = Math.round(limits.costPerDayUSD * MICROS_PER_USD)
const limitMicros = usdToMicros(limits.costPerDayUSD)
if (limitMicros > 0) out.push(ratioOf('costDay', entry.costPerDayMicroUsd, limitMicros))
}
if (limits.costPerMonthUSD) {
const limitMicros = Math.round(limits.costPerMonthUSD * MICROS_PER_USD)
const limitMicros = usdToMicros(limits.costPerMonthUSD)
if (limitMicros > 0) out.push(ratioOf('costMonth', entry.costPerMonthMicroUsd, limitMicros))
}
return out
@@ -137,3 +139,17 @@ export function budgetRatios(entry: AdminUsageEntryView): BudgetRatio[] {
// ONE run-out projection in this codebase — it used to disagree with this
// one on an already-exceeded budget (null here vs `now` there) and on day
// 1 of the month (clamped/overstated here vs null there).
/**
* budgetValueText (reuse-audit.md F7) renders one BudgetRatio's "used /
* limit" detail text (UsageBar's aria-valuetext/title) — a cost-kind ratio
* (id starting "cost") formats both sides through formatCost (dollars),
* every other kind (requests, tokens) through formatExactInt (a plain
* thousands-grouped integer) — the ONE definition, replacing
* ConsumerDirectory.vue's and UserDetail.vue's own two copies (which had
* drifted onto two different signatures for the identical logic).
*/
export function budgetValueText(ratio: BudgetRatio): string {
if (ratio.id.startsWith('cost')) return `${formatCost(ratio.used)} / ${formatCost(ratio.limit)}`
return `${formatExactInt(ratio.used)} / ${formatExactInt(ratio.limit)}`
}
+17 -16
View File
@@ -4,7 +4,8 @@ import { h } from 'vue'
import CompactNumber from '@/components/CompactNumber.vue'
import EntityLink from '@/components/EntityLink.vue'
import UsageBar from '@/components/UsageBar.vue'
import { headroom, monthProgress, projectMonthEnd } from '@/lib/forecast'
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'
@@ -115,17 +116,19 @@ function rejDayColumn(): ColumnDef<AdminUsageEntryView, unknown> {
* 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.
* 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. elapsedFraction is computed ONCE per usageColumns() call
* (not per row) since every row projects against the identical point in
* the current UTC month.
* pin it instead.
*/
function costMonthProjColumn(elapsedFraction: number): ColumnDef<AdminUsageEntryView, unknown> {
function costMonthProjColumn(now: Date): ColumnDef<AdminUsageEntryView, unknown> {
return {
id: 'costMonthProj',
header: 'cost/month (proj.)',
@@ -133,19 +136,18 @@ function costMonthProjColumn(elapsedFraction: number): ColumnDef<AdminUsageEntry
// 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) => projectMonthEnd(entry.costPerMonthMicroUsd, elapsedFraction) ?? 0,
accessorFn: (entry) => monthCostProjection(entry, now).micros ?? 0,
cell: ({ row }) => {
if (row.original.storeDown) return '?'
const projected = projectMonthEnd(row.original.costPerMonthMicroUsd, elapsedFraction)
if (projected === null) return h('span', { class: 'text-muted-foreground' }, 'not enough data yet')
const result = headroom(projected, row.original.limits?.costPerMonthUSD)
const projection = monthCostProjection(row.original, now)
if (projection.micros === null) return h('span', { class: 'text-muted-foreground' }, NOT_ENOUGH_DATA)
return h(
'span',
{
class: result.willExceed ? 'text-destructive' : undefined,
title: result.willExceed ? 'Projected to exceed the configured cost/month limit' : undefined,
class: projection.willExceed ? 'text-destructive' : undefined,
title: projection.willExceed ? WILL_EXCEED_TITLE : undefined,
},
formatCost(projected),
formatCost(projection.micros),
)
},
}
@@ -170,7 +172,7 @@ function sourceColumn(sourceValue: (entry: AdminUsageEntryView) => string | unde
id: 'source',
header: 'Source',
accessorFn: (entry) => sourceValue(entry) ?? '',
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, sourceValue(row.original) ?? '—'),
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, sourceValue(row.original) ?? EMPTY_CELL),
}
}
@@ -217,7 +219,6 @@ export function usageColumns(
now: Date = new Date(),
sourceValue?: (entry: AdminUsageEntryView) => string | undefined,
): ColumnDef<AdminUsageEntryView, unknown>[] {
const elapsedFraction = monthProgress(now)
const columns: ColumnDef<AdminUsageEntryView, unknown>[] = [
{
id: 'id',
@@ -266,7 +267,7 @@ export function usageColumns(
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(elapsedFraction),
costMonthProjColumn(now),
lastSeenColumn(now),
)
return columns
+10 -7
View File
@@ -4,9 +4,9 @@
// formula-injection neutralisation) behavior is defined in exactly one
// place (that module's own doc comment).
import { toCsv } from '@/lib/csv'
import { monthProgress, projectMonthEnd } from '@/lib/forecast'
import { monthCostProjection, NOT_ENOUGH_DATA } from '@/lib/forecast'
import { formatLimits } from '@/lib/format'
import { MICROS_PER_USD } from '@/lib/usage-bars'
import { microsToUsd } from '@/lib/usage-bars'
import type { AdminUsageEntryView } from '@/types/api'
/** UsageCsvKind picks the second column's label — "Group" for a Users export (each row's own group membership), "Members" for a Groups export (each row's member count) — mirroring usage-columns.ts's own usageColumns(idLabel, secondaryColumnLabel, ...) call sites in UsageTable.vue/ConsumerDirectory.vue exactly. */
@@ -30,7 +30,7 @@ const USAGE_CSV_SECONDARY_LABEL: Record<UsageCsvKind, string> = {
* 1 micro-USD = $0.000001.
*/
function csvCostUsd(micros: number): string {
return (micros / MICROS_PER_USD).toFixed(6)
return microsToUsd(micros).toFixed(6)
}
/**
@@ -63,7 +63,11 @@ function csvCostUsd(micros: number): string {
* `now` (F7, default the real current time) is threaded in rather than
* read via `new Date()` inside this module — the same "caller can pin it
* under test" convention costMonthProjColumn/CostForecastCard already
* follow.
* follow. The projected month-end cost column reuses lib/forecast.ts's
* own monthCostProjection (the same helper costMonthProjColumn and
* ConsumerDirectory.vue's groupCostProjection call) rather than pairing
* projectMonthEnd by hand — this export only reads its `.micros`, never
* `.willExceed` (a CSV cell has no styling to apply).
*/
export function usageCsv(
entries: AdminUsageEntryView[],
@@ -71,7 +75,6 @@ export function usageCsv(
secondaryValue: (entry: AdminUsageEntryView) => string,
now: Date = new Date(),
): string {
const elapsedFraction = monthProgress(now)
const headers = [
'Name',
USAGE_CSV_SECONDARY_LABEL[kind],
@@ -90,7 +93,7 @@ export function usageCsv(
]
const rows = entries.map((entry) => {
const masked = entry.storeDown
const projected = masked ? null : projectMonthEnd(entry.costPerMonthMicroUsd, elapsedFraction)
const projected = masked ? null : monthCostProjection(entry, now).micros
return [
entry.id,
secondaryValue(entry),
@@ -104,7 +107,7 @@ export function usageCsv(
masked ? '?' : entry.tokensOutPerMonth,
masked ? '?' : csvCostUsd(entry.costPerDayMicroUsd),
masked ? '?' : csvCostUsd(entry.costPerMonthMicroUsd),
masked ? '?' : projected === null ? 'not enough data yet' : csvCostUsd(projected),
masked ? '?' : projected === null ? NOT_ENOUGH_DATA : csvCostUsd(projected),
// Never masked — lastSeen is its own SET-based counter family
// (redesign-plan.md section 1.2), independent of the INCRBY usage
// counters `storeDown` actually guards (see usage-columns.ts's