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

Label configured model aliases with an alias badge wherever a model id shows.
List only providers with traffic in the window in provider chart legends.
Page long tables, show a scroll shadow on wide ones and drop the duplicate model link.
Show costs with thousands separators and magnitude-scaled decimals on cards and chart axes.
Use whole-number ticks for count charts and replace all-zero charts with a message.
Back off polling after failures.
Keep the CSV status region from widening the page on phones.
Regenerate admin_assets_gen.go.
This commit is contained in:
2026-11-08 02:22:22 +00:00
parent 05a7c114f5
commit 758d7c7020
37 changed files with 468 additions and 147 deletions
+70 -70
View File
File diff suppressed because one or more lines are too long
+9
View File
@@ -218,3 +218,12 @@
font-variant-numeric: tabular-nums;
}
}
/* Horizontal scroll cue: a soft shadow on whichever edge still has hidden content. */
@utility scroll-shadow-x {
background:
linear-gradient(to right, var(--card) 30%, transparent) 0 0 / 2.5rem 100% no-repeat local,
linear-gradient(to left, var(--card) 30%, transparent) 100% 0 / 2.5rem 100% no-repeat local,
radial-gradient(farthest-side at 0 50%, oklch(0 0 0 / 0.22), transparent) 0 0 / 0.6rem 100% no-repeat scroll,
radial-gradient(farthest-side at 100% 50%, oklch(0 0 0 / 0.22), transparent) 100% 0 / 0.6rem 100% no-repeat scroll;
}
+7
View File
@@ -0,0 +1,7 @@
<script setup lang="ts">
import { Badge } from '@/components/ui/badge'
</script>
<template>
<Badge as="span" variant="outline" class="shrink-0 px-1.5 py-0 text-[10px] font-medium uppercase tracking-wide" title="Model alias defined in the gateway config">alias</Badge>
</template>
+5 -4
View File
@@ -7,7 +7,7 @@ import TimeSeriesChart from '@/components/TimeSeriesChart.vue'
import type { TimeSeriesDataset } from '@/components/TimeSeriesChart.vue'
import { cumulative, runOutDate } from '@/lib/burndown'
import { NOT_ENOUGH_DATA } from '@/lib/forecast'
import { formatBucketLabel, formatCost, formatShortDate } from '@/lib/format'
import { formatBucketLabel, formatCostAxis, formatCostDisplay, formatShortDate } from '@/lib/format'
import { loadState } from '@/lib/load-state'
/**
@@ -73,8 +73,8 @@ const willExceed = computed<boolean>(() => props.budgetMicros !== null && spentM
>
<div class="flex flex-col gap-4">
<div class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-3">
<StatItem label="Spent so far" :tone="willExceed ? 'destructive' : 'default'">{{ formatCost(spentMicros) }}</StatItem>
<StatItem v-if="budgetMicros !== null" label="Budget">{{ formatCost(budgetMicros) }}</StatItem>
<StatItem label="Spent so far" :tone="willExceed ? 'destructive' : 'default'">{{ formatCostDisplay(spentMicros) }}</StatItem>
<StatItem v-if="budgetMicros !== null" label="Budget">{{ formatCostDisplay(budgetMicros) }}</StatItem>
<StatItem
v-if="budgetMicros !== null"
label="Projected run-out"
@@ -89,7 +89,8 @@ const willExceed = computed<boolean>(() => props.budgetMicros !== null && spentM
:labels="labels"
:datasets="datasets"
:comparison-datasets="comparisonDatasets"
:value-formatter="formatCost"
:value-formatter="formatCostDisplay"
:axis-formatter="formatCostAxis"
ariaLabel="Cumulative spend this month against the configured budget"
/>
</div>
+3
View File
@@ -59,6 +59,7 @@ const props = withDefaults(
comparisonDatasets?: TimeSeriesComparisonDataset[]
stacked?: boolean
valueFormatter?: (value: number) => string
axisFormatter?: (value: number) => string
/** Required whenever `state` can reach 'ready' with the default TimeSeriesChart body (TimeSeriesChart's own ariaLabel doc comment: no safe generic default) — optional here only so a skeleton-only ChartCard is not forced to pass a meaningless placeholder. */
ariaLabel?: string
}>(),
@@ -92,6 +93,7 @@ const props = withDefaults(
:comparison-datasets="comparisonDatasets"
:stacked="stacked"
:value-formatter="valueFormatter"
:axis-formatter="axisFormatter"
:ariaLabel="ariaLabel"
/>
</slot>
@@ -113,6 +115,7 @@ const props = withDefaults(
:comparison-datasets="comparisonDatasets"
:stacked="stacked"
:value-formatter="valueFormatter"
:axis-formatter="axisFormatter"
:ariaLabel="ariaLabel"
/>
</slot>
+12 -7
View File
@@ -25,7 +25,7 @@ import UsageTable from '@/components/UsageTable.vue'
import { useNow } from '@/composables/useNow'
import { useSearchQuery } from '@/composables/useSearchQuery'
import { monthCostProjection, NOT_ENOUGH_DATA, WILL_EXCEED_TITLE } from '@/lib/forecast'
import { formatCost, formatLimits } from '@/lib/format'
import { formatCostDisplay, formatLimits } from '@/lib/format'
import { loadState } from '@/lib/load-state'
import { type ExpandState, clearExpandOverrides, computeExpandedItems, toggleItemExpand } from '@/lib/search-expand'
import { budgetRatios } from '@/lib/usage-bars'
@@ -49,6 +49,9 @@ import type { AdminUsageEntryView } from '@/types/api'
* Source column (inline/file, GET /admin/api/consumers) on the flat Users
* table only.
*/
/** Rows per page in the flat Users table: keeps a 30+ user fleet scannable. */
const USERS_PAGE_SIZE = 25
const dashboard = useDashboardStore()
const consumers = useConsumersStore()
const nav = useNavStore()
@@ -232,7 +235,7 @@ function isGlobPattern(entry: string): boolean {
/** groupCostProjection renders lib/forecast.ts's shared monthCostProjection (reuse-audit.md F7) for one group row as display text. */
function groupCostProjection(entry: AdminUsageEntryView, now: Date): { text: string; willExceed: boolean } {
const projection = monthCostProjection(entry, now)
return { text: projection.micros === null ? NOT_ENOUGH_DATA : formatCost(projection.micros), willExceed: projection.willExceed }
return { text: projection.micros === null ? NOT_ENOUGH_DATA : formatCostDisplay(projection.micros), willExceed: projection.willExceed }
}
/**
* GROUP_DETAIL_FIELDS (reuse-audit.md F6) drives the group accordion's 4
@@ -308,7 +311,7 @@ function groupsCsv(): string {
</StatItem>
<StatItem label="Tokens in/day"><CompactNumber :value="usage.total.tokensInPerDay" /></StatItem>
<StatItem label="Tokens out/day"><CompactNumber :value="usage.total.tokensOutPerDay" /></StatItem>
<StatItem label="Cost/day">{{ formatCost(usage.total.costPerDayMicroUsd) }}</StatItem>
<StatItem label="Cost/day">{{ formatCostDisplay(usage.total.costPerDayMicroUsd) }}</StatItem>
</CardContent>
</Card>
@@ -328,7 +331,8 @@ function groupsCsv(): string {
<SkeletonList v-if="dashboardLoadState === 'skeleton'" :rows="3" />
<ErrorState v-else-if="dashboardLoadState === 'error'" :message="dashboard.error" :on-retry="dashboard.refresh" />
<template v-else>
<div v-if="sortedGroupRows.length" class="mb-3 flex flex-wrap gap-x-4 gap-y-1 text-xs font-medium text-muted-foreground">
<div v-if="sortedGroupRows.length" class="mb-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs font-medium text-muted-foreground">
<span>Sort groups by</span>
<SortHeaderButton v-for="header in toolbarHeaders" :key="header.id" :header="header" />
</div>
@@ -345,7 +349,7 @@ function groupsCsv(): string {
<CompactNumber v-else :value="row.original.requestsPerDay" /> req/day
</span>
<span class="text-xs text-muted-foreground tabular-nums">
{{ row.original.storeDown ? '?' : formatCost(row.original.costPerDayMicroUsd) }}/day
{{ row.original.storeDown ? '?' : formatCostDisplay(row.original.costPerDayMicroUsd) }}/day
</span>
</span>
</AccordionTrigger>
@@ -425,7 +429,7 @@ function groupsCsv(): string {
<template v-if="row.original.storeDown">?</template>
<CompactNumber v-else :value="field.read(row.original)" />
</DetailField>
<DetailField label="cost/month" numeric>{{ row.original.storeDown ? '?' : formatCost(row.original.costPerMonthMicroUsd) }}</DetailField>
<DetailField label="cost/month" numeric>{{ row.original.storeDown ? '?' : formatCostDisplay(row.original.costPerMonthMicroUsd) }}</DetailField>
<DetailField
label="cost/month (proj.)"
numeric
@@ -462,7 +466,7 @@ function groupsCsv(): string {
<div class="flex items-start justify-between gap-2">
<div>
<CardTitle>Users</CardTitle>
<CardDescription v-if="consumers.data?.usersFile">File-backed users load from {{ consumers.data.usersFile }}.</CardDescription>
<CardDescription v-if="consumers.data?.usersFile" class="max-w-full truncate" :title="consumers.data.usersFile">File-backed users load from {{ consumers.data.usersFile }}.</CardDescription>
</div>
<CsvExportButton filename="consumers-users.csv" :build="usersCsv" />
</div>
@@ -470,6 +474,7 @@ function groupsCsv(): string {
<CardContent>
<LoadStateView :state="dashboardLoadState" :error="dashboard.error" :on-retry="dashboard.refresh" skeleton="table" :rows="5" :cols="5">
<UsageTable
:page-size="USERS_PAGE_SIZE"
id-label="Name"
secondary-column-label="Group"
:entries="filteredUsers"
+3 -3
View File
@@ -4,7 +4,7 @@ import { computed } from 'vue'
import LabeledSelect from '@/components/LabeledSelect.vue'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { costAvoidedMicros, freeRows, pickReferenceModel } from '@/lib/cost-avoided'
import { formatCost } from '@/lib/format'
import { formatCostDisplay } from '@/lib/format'
import type { AdminCatalogModel, AdminUsageModelEntry } from '@/types/api'
/**
@@ -129,12 +129,12 @@ function onReferenceUpdate(value: unknown): void {
<p v-if="avoidedMicros === null" class="text-sm text-muted-foreground">
{{ priceableOptions.length === 0 ? 'No priced model served in range to compare against.' : 'Pick a reference model above.' }}
</p>
<p v-else class="text-lg font-semibold tabular-nums text-chart-requests">{{ formatCost(avoidedMicros) }}</p>
<p v-else class="text-lg font-semibold tabular-nums text-chart-requests">{{ formatCostDisplay(avoidedMicros) }}</p>
</div>
<div v-if="cacheStatsEnabled">
<p class="text-muted-foreground">Cache savings</p>
<p v-if="!cacheSavingsAvailable" class="text-lg font-semibold tabular-nums text-muted-foreground">n/a</p>
<p v-else class="text-lg font-semibold tabular-nums text-chart-requests">{{ formatCost(cacheSavedMicros) }}</p>
<p v-else class="text-lg font-semibold tabular-nums text-chart-requests">{{ formatCostDisplay(cacheSavedMicros) }}</p>
<p v-if="cacheSavingsNote" class="text-xs text-status-warn">{{ cacheSavingsNote }}</p>
</div>
</CardContent>
+4 -4
View File
@@ -4,7 +4,7 @@ import { computed } from 'vue'
import StatItem from '@/components/StatItem.vue'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { headroom, monthProgress, NOT_ENOUGH_DATA, projectMonthEnd, WILL_EXCEED_TITLE } from '@/lib/forecast'
import { formatCost } from '@/lib/format'
import { formatCostDisplay } from '@/lib/format'
import type { LimitsConfig } from '@/types/api'
/**
@@ -54,16 +54,16 @@ const forecast = computed(() => headroom(projectedMicros.value, props.limits?.co
<CardDescription>Projected month-end spend, extrapolated from month-to-date usage (UTC calendar month).</CardDescription>
</CardHeader>
<CardContent class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-3">
<StatItem label="Month to date">{{ formatCost(mtdMicros) }}</StatItem>
<StatItem label="Month to date">{{ formatCostDisplay(mtdMicros) }}</StatItem>
<StatItem
label="Projected month-end"
:tone="forecast.willExceed ? 'destructive' : 'default'"
:title="forecast.willExceed ? WILL_EXCEED_TITLE : undefined"
:hint="projectedMicros === null ? NOT_ENOUGH_DATA : undefined"
>
{{ projectedMicros === null ? '' : formatCost(projectedMicros) }}
{{ projectedMicros === null ? '' : formatCostDisplay(projectedMicros) }}
</StatItem>
<StatItem v-if="forecast.limitMicros !== null" label="Limit">{{ formatCost(forecast.limitMicros) }}</StatItem>
<StatItem v-if="forecast.limitMicros !== null" label="Limit">{{ formatCostDisplay(forecast.limitMicros) }}</StatItem>
</CardContent>
</Card>
</template>
+1 -1
View File
@@ -81,7 +81,7 @@ onBeforeUnmount(() => {
</script>
<template>
<Button type="button" variant="outline" size="sm" :disabled="exporting" @click="onClick">
<Button type="button" variant="outline" size="sm" class="relative" :disabled="exporting" @click="onClick">
<FontAwesomeIcon v-if="feedback === 'failed'" :icon="faCircleXmark" class="size-3.5 text-destructive" aria-hidden="true" />
<FontAwesomeIcon
v-else-if="feedback"
+23 -2
View File
@@ -1,9 +1,11 @@
<script setup lang="ts" generic="TData">
import type { ColumnDef, SortingState } from '@tanstack/vue-table'
import { FlexRender, getCoreRowModel, getSortedRowModel, useVueTable } from '@tanstack/vue-table'
import { ref } from 'vue'
import { computed, ref } from 'vue'
import SortHeaderButton from '@/components/SortHeaderButton.vue'
import { Button } from '@/components/ui/button'
import { pageWindow } from '@/lib/paging'
import {
Table,
TableBody,
@@ -40,6 +42,8 @@ const props = defineProps<{
emptyMessage?: string
/** Accessible name for the table (aria-label). */
label?: string
/** Rows per page; omit to show every row. A pager appears only when the data exceeds one page. */
pageSize?: number
/**
* Optional CONTROLLED sort state (P6, `v-model:sorting`). Omitted (the
* default) keeps every existing call site's original UNCONTROLLED
@@ -59,6 +63,8 @@ const emit = defineEmits<{ 'update:sorting': [value: SortingState] }>()
/** internalSorting is read only when props.sorting is undefined (uncontrolled mode) — see the `sorting` prop's own doc comment above. */
const internalSorting = ref<SortingState>([])
const pageIndex = ref(0)
const table = useVueTable({
get data() {
return props.data
@@ -81,6 +87,11 @@ const table = useVueTable({
},
})
const allRows = computed(() => table.getRowModel().rows)
const pg = computed(() => pageWindow(allRows.value.length, props.pageSize ?? Math.max(1, allRows.value.length), pageIndex.value))
const paged = computed(() => props.pageSize !== undefined && allRows.value.length > props.pageSize)
const visibleRows = computed(() => (paged.value ? allRows.value.slice(pg.value.from, pg.value.to) : allRows.value))
/** ariaSort maps a column's current sort direction to the `aria-sort` value native to a real <th> — set only on the sorted column, per spec. */
function ariaSort(dir: false | 'asc' | 'desc'): 'ascending' | 'descending' | undefined {
if (dir === 'asc') return 'ascending'
@@ -90,6 +101,7 @@ function ariaSort(dir: false | 'asc' | 'desc'): 'ascending' | 'descending' | und
</script>
<template>
<div>
<Table :aria-label="label">
<TableHeader>
<TableRow v-for="headerGroup in table.getHeaderGroups()" :key="headerGroup.id">
@@ -108,7 +120,7 @@ function ariaSort(dir: false | 'asc' | 'desc'): 'ascending' | 'descending' | und
<TableEmpty v-if="table.getRowModel().rows.length === 0" :colspan="columns.length" class="text-muted-foreground">
{{ emptyMessage ?? 'No rows to show.' }}
</TableEmpty>
<TableRow v-for="row in table.getRowModel().rows" :key="row.id" :class="rowClass?.(row.original)">
<TableRow v-for="row in visibleRows" :key="row.id" :class="rowClass?.(row.original)">
<TableCell
v-for="cell in row.getVisibleCells()"
:key="cell.id"
@@ -119,4 +131,13 @@ function ariaSort(dir: false | 'asc' | 'desc'): 'ascending' | 'descending' | und
</TableRow>
</TableBody>
</Table>
<nav v-if="paged" class="flex items-center justify-between gap-2 pt-3 text-xs text-muted-foreground" aria-label="Table pages">
<span aria-live="polite">Rows {{ pg.from + 1 }}–{{ pg.to }} of {{ allRows.length }}</span>
<span class="flex items-center gap-2">
<Button type="button" variant="outline" size="sm" :disabled="pg.index === 0" @click="pageIndex = pg.index - 1">Previous</Button>
<span class="tabular-nums">Page {{ pg.index + 1 }} / {{ pg.count }}</span>
<Button type="button" variant="outline" size="sm" :disabled="pg.index >= pg.count - 1" @click="pageIndex = pg.index + 1">Next</Button>
</span>
</nav>
</div>
</template>
+4
View File
@@ -1,6 +1,8 @@
<script setup lang="ts">
import { faArrowUpRightFromSquare } from '@fortawesome/free-solid-svg-icons'
import AliasBadge from '@/components/AliasBadge.vue'
import { useAliasNames } from '@/composables/useAliasNames'
import { useNavStore } from '@/stores/nav'
/**
@@ -43,6 +45,7 @@ const props = defineProps<{
}>()
const nav = useNavStore()
const { isAlias } = useAliasNames()
const TARGET: Record<'user' | 'model', { page: 'consumers' | 'models'; paramKey: 'user' | 'model'; noun: string }> = {
user: { page: 'consumers', paramKey: 'user', noun: 'Consumers' },
@@ -65,6 +68,7 @@ function onClick(event: MouseEvent): void {
@click="onClick"
>
<span class="min-w-0" :class="labelClass">{{ label }}</span>
<AliasBadge v-if="kind === 'model' && isAlias(id)" />
<FontAwesomeIcon :icon="faArrowUpRightFromSquare" class="size-3 shrink-0" aria-hidden="true" />
</button>
</template>
+4 -1
View File
@@ -69,6 +69,9 @@ const columns = eventsColumns()
* states-plan.md item 3 — so content is never wiped/replaced by a
* skeleton or error here).
*/
/** Rows per page in the Events table. */
const EVENTS_PAGE_SIZE = 50
const eventsLoadState = computed(() => loadState({ loading: events.refreshing, hasData: events.lastUpdated !== null, error: events.error }))
const staleMessage = computed(() => staleNotice(events.lastUpdated !== null, events.error, events.lastUpdated))
@@ -160,7 +163,7 @@ onUnmounted(() => {
title="No failures recorded."
description="Rate-limit, budget, and upstream events will show up here as they happen."
/>
<DataTable v-else label="Events" :columns="columns" :data="filteredEvents" :empty-message="emptyMessage" />
<DataTable v-else label="Events" :page-size="EVENTS_PAGE_SIZE" :columns="columns" :data="filteredEvents" :empty-message="emptyMessage" />
</CardContent>
</Card>
</div>
+4
View File
@@ -2,7 +2,9 @@
import { faCheck, faCopy, faTriangleExclamation } from '@fortawesome/free-solid-svg-icons'
import { computed, useTemplateRef } from 'vue'
import AliasBadge from '@/components/AliasBadge.vue'
import { Badge } from '@/components/ui/badge'
import { useAliasNames } from '@/composables/useAliasNames'
import { useCopyFeedback } from '@/composables/useCopyFeedback'
import { copyText } from '@/lib/clipboard'
import { formatContextWindow, formatModelCostHover } from '@/lib/format'
@@ -50,6 +52,7 @@ const props = defineProps<{
outputPerMTokUsd?: number
}>()
const { isAlias } = useAliasNames()
const labelRef = useTemplateRef<HTMLElement>('label')
const { state, set: setCopyFeedback } = useCopyFeedback()
const toasts = useToastsStore()
@@ -125,6 +128,7 @@ const title = computed(() => {
@click="onClick"
>
<span ref="label" class="min-w-0 truncate select-text">{{ id }}</span>
<AliasBadge v-if="isAlias(id)" />
<FontAwesomeIcon :icon="icon[state]" class="size-2.5 shrink-0" aria-hidden="true" />
</Badge>
</template>
+8 -1
View File
@@ -58,6 +58,8 @@ const props = withDefaults(
stacked?: boolean
/** Formats a raw value for the tooltip and y-axis ticks — defaults to formatExactInt (lib/format.ts). Cost callers pass formatCost, a ratio series a percent formatter, and so on. */
valueFormatter?: (value: number) => string
/** Y-axis tick formatter when the tooltip formatter is too wordy for a tick (cost: "$1,600" not "$1,600.00"); defaults to valueFormatter. */
axisFormatter?: (value: number) => string
/**
* ariaLabel is this chart's accessible name (P3 item 16) — a bare
* `<canvas>` has no text alternative at all for a screen reader, so
@@ -158,7 +160,12 @@ const chartOptions = computed<ChartOptions<'line'>>(() => ({
stacked: props.stacked,
beginAtZero: true,
grid: { color: border.value },
ticks: { color: mutedForeground.value, callback: (value) => props.valueFormatter(Number(value)) },
// Counts are whole numbers: no 0.1-step ticks on a chart whose largest value is 1.
ticks: {
color: mutedForeground.value,
precision: props.valueFormatter === formatExactInt ? 0 : undefined,
callback: (value) => (props.axisFormatter ?? props.valueFormatter)(Number(value)),
},
},
},
plugins: {
+3
View File
@@ -28,6 +28,8 @@ const props = defineProps<{
sorting?: SortingState
/** Optional per-row source lookup ('inline'/'file'/undefined), forwarded to usage-columns.ts's usageColumns — see that module's sourceColumn doc comment. Omitted everywhere except ConsumerDirectory.vue's flat Users table. */
sourceValue?: (entry: AdminUsageEntryView) => string | undefined
/** Forwarded to DataTable: rows per page for large user lists. */
pageSize?: number
}>()
const emit = defineEmits<{ 'update:sorting': [value: SortingState] }>()
@@ -40,6 +42,7 @@ const columns = computed(() =>
<template>
<DataTable
label="Usage"
:page-size="pageSize"
:columns="columns"
:data="entries"
:empty-message="emptyMessage"
+6 -5
View File
@@ -19,7 +19,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { useNow } from '@/composables/useNow'
import { runOutDate as computeRunOutDate } from '@/lib/burndown'
import { formatBucketLabel, formatCost, formatLimits, formatShortDate, formatTimestamp } from '@/lib/format'
import { formatBucketLabel, formatCostAxis, formatCostDisplay, formatLimits, formatShortDate, formatTimestamp } from '@/lib/format'
import { loadState } from '@/lib/load-state'
import { budgetRatios, usdToMicros } from '@/lib/usage-bars'
import { useConsumersStore } from '@/stores/consumers'
@@ -187,8 +187,8 @@ const runOutDate = computed(() => {
</CardContent>
<CardContent v-else class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-4">
<StatItem label="Requests/day"><CompactNumber :value="entry.requestsPerDay" /></StatItem>
<StatItem label="Cost/day">{{ formatCost(entry.costPerDayMicroUsd) }}</StatItem>
<StatItem label="Cost/month">{{ formatCost(entry.costPerMonthMicroUsd) }}</StatItem>
<StatItem label="Cost/day">{{ formatCostDisplay(entry.costPerDayMicroUsd) }}</StatItem>
<StatItem label="Cost/month">{{ formatCostDisplay(entry.costPerMonthMicroUsd) }}</StatItem>
<div>
<p class="text-muted-foreground">Limits</p>
<p class="text-sm">{{ formatLimits(entry.limits) }}</p>
@@ -223,7 +223,8 @@ const runOutDate = computed(() => {
:on-retry="loadDetail"
:labels="costLabels"
:datasets="costDatasets"
:value-formatter="formatCost"
:value-formatter="formatCostDisplay"
:axis-formatter="formatCostAxis"
:aria-label="`Cost over time for ${userId}`"
/>
@@ -256,7 +257,7 @@ const runOutDate = computed(() => {
<TableRow v-for="row in modelRows" :key="row.id">
<TableCell><ModelChip :id="row.id" /></TableCell>
<TableCell class="text-right tabular-nums"><CompactNumber :value="row.values.req ?? 0" /></TableCell>
<TableCell class="text-right tabular-nums">{{ formatCost(row.values.cost ?? 0) }}</TableCell>
<TableCell class="text-right tabular-nums">{{ formatCostDisplay(row.values.cost ?? 0) }}</TableCell>
</TableRow>
</TableBody>
</Table>
+1 -1
View File
@@ -10,7 +10,7 @@ const props = defineProps<{
</script>
<template>
<div data-slot="table-container" class="relative w-full overflow-x-auto">
<div data-slot="table-container" class="scroll-shadow-x relative w-full overflow-x-auto">
<table data-slot="table" v-bind="$attrs" :class="cn('w-full caption-bottom text-sm', props.class)">
<slot />
</table>
+11
View File
@@ -0,0 +1,11 @@
import { computed } from 'vue'
import { aliasNameSet } from '@/lib/alias'
import { useDashboardStore } from '@/stores/dashboard'
/** useAliasNames exposes isAlias(id): true when id is a configured model alias (from the polled overview). */
export function useAliasNames() {
const dashboard = useDashboardStore()
const names = computed(() => aliasNameSet(dashboard.overview?.aliases))
return { isAlias: (id: string): boolean => names.value.has(id) }
}
+18
View File
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest'
import { aliasNameSet } from './alias'
import type { AdminAliasView } from '@/types/api'
const view = (alias: string): AdminAliasView => ({ alias, target: 'openai/gpt-5', modelMeta: {} })
describe('aliasNameSet', () => {
it.each<{ name: string; input: AdminAliasView[] | undefined; has: string[]; hasNot: string[] }>([
{ name: 'undefined', input: undefined, has: [], hasNot: ['x'] },
{ name: 'empty', input: [], has: [], hasNot: ['x'] },
{ name: 'two aliases', input: [view('fast'), view('smart')], has: ['fast', 'smart'], hasNot: ['openai/gpt-5', 'Fast', ''] },
])('$name', ({ input, has, hasNot }) => {
const set = aliasNameSet(input)
for (const h of has) expect(set.has(h)).toBe(true)
for (const h of hasNot.filter((x) => !has.includes(x))) expect(set.has(h)).toBe(false)
})
})
+6
View File
@@ -0,0 +1,6 @@
import type { AdminAliasView } from '@/types/api'
/** aliasNameSet indexes configured alias names (exact match, as a client sends them) for O(1) lookups. */
export function aliasNameSet(aliases: readonly AdminAliasView[] | undefined): Set<string> {
return new Set((aliases ?? []).map((a) => a.alias))
}
+17 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { formatBucketLabel, formatCompactCount, formatContextWindow, formatElapsedAgo, formatLatencyMs, formatModelCostHover, formatUntil, refreshDetailLabel, refreshLabel, ZERO_TIME } from './format'
import { formatBucketLabel, formatCompactCount, formatContextWindow, formatCostAxis, formatCostDisplay, formatElapsedAgo, formatLatencyMs, formatModelCostHover, formatUntil, refreshDetailLabel, refreshLabel, ZERO_TIME } from './format'
describe('refreshLabel', () => {
it('reads "discovery off" when discovery is disabled, regardless of lastRefresh', () => {
@@ -269,3 +269,19 @@ describe('rounding boundaries', () => {
expect(formatLatencyMs(ms)).toBe(want)
})
})
describe('cost display formatters', () => {
it.each([
{ name: 'zero', micros: 0, display: '$0.0000', axis: '$0' },
{ name: 'sub-cent keeps precision', micros: 1_234, display: '$0.0012', axis: '$0.0012' },
{ name: 'under a dollar', micros: 500_000, display: '$0.5000', axis: '$0.5' },
{ name: 'a few dollars', micros: 2_688_800, display: '$2.69', axis: '$2.69' },
{ name: 'hundreds', micros: 999_000_000, display: '$999.00', axis: '$999' },
{ name: 'thousands', micros: 1_500_000_000, display: '$1,500', axis: '$1,500' },
{ name: 'negative', micros: -2_000_000, display: '-$2.00', axis: '-$2' },
{ name: 'NaN', micros: NaN, display: '—', axis: '—' },
])('$name', ({ micros, display, axis }) => {
expect(formatCostDisplay(micros)).toBe(display)
expect(formatCostAxis(micros)).toBe(axis)
})
})
+31
View File
@@ -47,6 +47,37 @@ export function formatCost(micros: number): string {
return `$${microsToUsd(micros).toFixed(4)}`
}
/** Thresholds in micro-USD: 4 decimals under $1 (per-request costs are tiny), cents under $1000, whole dollars above. */
const COST_DISPLAY_CENTS_FROM_MICROS = 1_000_000
const COST_DISPLAY_WHOLE_FROM_MICROS = 1_000_000_000
function costFractionDigits(absMicros: number): number {
if (absMicros < COST_DISPLAY_CENTS_FROM_MICROS) return 4
return absMicros < COST_DISPLAY_WHOLE_FROM_MICROS ? 2 : 0
}
function formatUsdAmount(micros: number, minDigits: (max: number) => number): string {
if (!Number.isFinite(micros)) return '—'
const abs = Math.abs(micros)
const max = costFractionDigits(abs)
const text = microsToUsd(abs).toLocaleString('en-US', { minimumFractionDigits: minDigits(max), maximumFractionDigits: max })
return `${micros < 0 ? '-' : ''}$${text}`
}
/**
* formatCostDisplay renders micro-USD for cards, headings and tooltips with thousands separators and magnitude-scaled
* decimals. Tables and CSV keep formatCost's fixed 4 decimals. Rounding error is at most 0.5% from $1 up
* (formal/Gateway/Ui/Cost.lean rel_err_ge1).
*/
export function formatCostDisplay(micros: number): string {
return formatUsdAmount(micros, (max) => max)
}
/** formatCostAxis is formatCostDisplay without trailing zeros ("$0", "$0.5", "$1,600"), for chart ticks. */
export function formatCostAxis(micros: number): string {
return formatUsdAmount(micros, () => 0)
}
/**
* formatShortDate renders a Date as a compact "Oct 15" label (month/day
* only, no time-of-day) — reuse-audit.md F13: the ONE run-out-date format,
+14 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { loadState } from './load-state'
import { emptyWhenAllZero, loadState } from './load-state'
describe('loadState', () => {
it('is "ready" when there is data, no error, not loading', () => {
@@ -34,3 +34,16 @@ describe('loadState', () => {
expect(loadState({ loading: false, hasData: false, error: '' })).toBe('empty')
})
})
describe('emptyWhenAllZero', () => {
const zero = [{ data: [0, 0, null] }]
it.each([
{ name: 'ready + all zero', state: 'ready', series: zero, want: 'empty' },
{ name: 'ready + no series', state: 'ready', series: [], want: 'empty' },
{ name: 'ready + traffic', state: 'ready', series: [{ data: [0, 2] }], want: 'ready' },
{ name: 'skeleton passes through', state: 'skeleton', series: zero, want: 'skeleton' },
{ name: 'error passes through', state: 'error', series: zero, want: 'error' },
] as const)('$name', ({ state, series, want }) => {
expect(emptyWhenAllZero(state, series)).toBe(want)
})
})
+7
View File
@@ -41,3 +41,10 @@ export function loadState({ loading, hasData, error }: LoadStateInput): LoadStat
if (loading) return 'skeleton'
return 'empty'
}
/** emptyWhenAllZero turns a 'ready' chart state into 'empty' when no series has a non-zero point, so an all-zero chart is replaced by a short message. Other states pass through (formal/Gateway/Ui/EmptyChart.lean). */
export function emptyWhenAllZero(state: LoadState, series: readonly { data: readonly (number | null)[] }[]): LoadState {
if (state !== 'ready') return state
const hasTraffic = series.some((s) => s.data.some((v) => v !== null && v !== 0))
return hasTraffic ? state : 'empty'
}
+4 -9
View File
@@ -2,7 +2,6 @@ import type { VNode } from 'vue'
import { isVNode } from 'vue'
import { describe, expect, it } from 'vitest'
import EntityLink from '@/components/EntityLink.vue'
import ModelChip from '@/components/ModelChip.vue'
import { Badge } from '@/components/ui/badge'
import { buildModelCatalogRows, modelCatalogColumns } from './model-table-columns'
@@ -126,15 +125,11 @@ describe('buildModelCatalogRows', () => {
describe('modelCatalogColumns: id column', () => {
const col = modelCatalogColumns().find((c) => c.id === 'id')
it('cell renders a ModelChip and an EntityLink pointed at kind "model"', () => {
// This table lives on the Models page, so a link back to it would repeat the chip's own text.
it('cell renders one ModelChip and no self-link', () => {
const rendered = cellOf(col)({ row: { original: testRow({ id: 'anthropic/claude' }) } }) as VNode
const children = rendered.children as VNode[]
const chip = children.find((c) => c.type === ModelChip)
const link = children.find((c) => c.type === EntityLink)
expect(chip?.props?.id).toBe('anthropic/claude')
expect(link?.props?.kind).toBe('model')
expect(link?.props?.id).toBe('anthropic/claude')
expect(link?.props?.label).toBe('anthropic/claude')
expect(rendered.type).toBe(ModelChip)
expect(rendered.props?.id).toBe('anthropic/claude')
})
})
+6 -10
View File
@@ -1,7 +1,6 @@
import type { ColumnDef } from '@tanstack/vue-table'
import { h } from 'vue'
import EntityLink from '@/components/EntityLink.vue'
import ModelChip from '@/components/ModelChip.vue'
import { Badge } from '@/components/ui/badge'
import { EMPTY_CELL, optionalColumn, usageMetricColumns } from '@/lib/columns'
@@ -152,15 +151,12 @@ export function modelCatalogColumns(): ColumnDef<ModelCatalogRow, unknown>[] {
header: 'Model',
accessorFn: (r) => r.id,
cell: ({ row }) =>
h('span', { class: 'inline-flex flex-wrap items-center gap-1.5' }, [
h(ModelChip, {
id: row.original.id,
contextTokens: row.original.contextTokens,
inputPerMTokUsd: row.original.inputPerMTokUsd,
outputPerMTokUsd: row.original.outputPerMTokUsd,
}),
h(EntityLink, { label: row.original.id, kind: 'model', id: row.original.id }),
]),
h(ModelChip, {
id: row.original.id,
contextTokens: row.original.contextTokens,
inputPerMTokUsd: row.original.inputPerMTokUsd,
outputPerMTokUsd: row.original.outputPerMTokUsd,
}),
},
optionalColumn<ModelCatalogRow>('context', 'Context', (r) => r.contextTokens, formatContextWindow),
{
+28
View File
@@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest'
import { pageWindow } from './paging'
describe('pageWindow', () => {
it.each([
{ name: 'empty', total: 0, size: 25, idx: 0, want: { index: 0, count: 1, from: 0, to: 0 } },
{ name: 'fits one page', total: 25, size: 25, idx: 0, want: { index: 0, count: 1, from: 0, to: 25 } },
{ name: 'first page', total: 31, size: 25, idx: 0, want: { index: 0, count: 2, from: 0, to: 25 } },
{ name: 'last partial page', total: 31, size: 25, idx: 1, want: { index: 1, count: 2, from: 25, to: 31 } },
{ name: 'index past the end clamps', total: 31, size: 25, idx: 9, want: { index: 1, count: 2, from: 25, to: 31 } },
{ name: 'negative index clamps', total: 31, size: 25, idx: -3, want: { index: 0, count: 2, from: 0, to: 25 } },
{ name: 'filter shrank the data', total: 3, size: 25, idx: 4, want: { index: 0, count: 1, from: 0, to: 3 } },
{ name: 'zero page size is treated as 1', total: 2, size: 0, idx: 1, want: { index: 1, count: 2, from: 1, to: 2 } },
])('$name', ({ total, size, idx, want }) => {
expect(pageWindow(total, size, idx)).toEqual(want)
})
it('every reachable page of a non-empty table shows at least one row', () => {
for (let total = 1; total < 80; total++) {
for (let idx = 0; idx < 6; idx++) {
const w = pageWindow(total, 25, idx)
expect(w.to).toBeGreaterThan(w.from)
expect(w.to).toBeLessThanOrEqual(total)
}
}
})
})
+18
View File
@@ -0,0 +1,18 @@
export interface PageWindow {
/** Zero-based page index, clamped into range. */
index: number
count: number
/** Zero-based start offset, inclusive. */
from: number
/** Zero-based end offset, exclusive. */
to: number
}
/** pageWindow clamps `index` into [0, count-1] and returns the row range for it (formal/Gateway/Ui/Paging.lean). */
export function pageWindow(total: number, pageSize: number, index: number): PageWindow {
const size = Math.max(1, Math.floor(pageSize))
const count = Math.max(1, Math.ceil(total / size))
const clamped = Math.min(Math.max(0, Math.floor(index)), count - 1)
const from = clamped * size
return { index: clamped, count, from, to: Math.min(total, from + size) }
}
+35 -1
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createVisibilityPoller, type VisibilityDocumentLike } from './polling'
import { backoffSkips, createVisibilityPoller, type VisibilityDocumentLike } from './polling'
/**
* createFakeDoc builds a minimal VisibilityDocumentLike test double: a
@@ -222,3 +222,37 @@ describe('createVisibilityPoller', () => {
poller.stop()
})
})
describe('poll backoff', () => {
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())
it.each([
{ failures: 0, want: 0 },
{ failures: 1, want: 1 },
{ failures: 2, want: 3 },
{ failures: 3, want: 7 },
{ failures: 50, want: 7 },
])('backoffSkips($failures) = $want', ({ failures, want }) => {
expect(backoffSkips(failures)).toBe(want)
})
it('skips ticks after a failed poll and resets after a success', async () => {
const tick = vi.fn<() => Promise<boolean>>().mockResolvedValue(true)
const poller = createVisibilityPoller({ intervalMs: 1000, tick, doc: undefined })
poller.start()
await vi.advanceTimersByTimeAsync(0)
expect(tick).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1000) // skipped (1 skip after 1 failure)
expect(tick).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1000)
expect(tick).toHaveBeenCalledTimes(2)
tick.mockResolvedValue(false)
await vi.advanceTimersByTimeAsync(3000) // 2 failures -> 3 skips, then a call
await vi.advanceTimersByTimeAsync(1000)
expect(tick).toHaveBeenCalledTimes(3)
await vi.advanceTimersByTimeAsync(1000) // healthy again: every tick
expect(tick).toHaveBeenCalledTimes(4)
poller.stop()
})
})
+37 -5
View File
@@ -26,12 +26,12 @@ export interface VisibilityPollerOptions {
/** How often `tick` fires while the page is visible. */
intervalMs: number
/**
* The store's own refresh step. Never awaited here — a caller that
* The store's own refresh step. May return a promise resolving `true` when the poll failed: consecutive failures then skip ticks (see backoffSkips) so a down gateway is not hit every interval. Never awaited here — a caller that
* needs its own in-flight guard (history.ts keeps its "skip a tick
* while the previous fetch is still in flight" rule) builds that into
* `tick` itself, same as before this module existed.
*/
tick: () => void
tick: () => void | Promise<boolean | void>
/**
* The document to watch for visibility changes. Defaults to the real
* `document` global when one exists. In a non-browser context (vitest's
@@ -57,8 +57,40 @@ function resolveDoc(doc: VisibilityDocumentLike | undefined): VisibilityDocument
return typeof document === 'undefined' ? undefined : (document as unknown as VisibilityDocumentLike)
}
export function createVisibilityPoller({ intervalMs, tick, doc }: VisibilityPollerOptions): VisibilityPoller {
/** Most ticks skipped between attempts while failing: 2^3 - 1, so a down gateway is retried at least every 8 intervals. */
const MAX_BACKOFF_EXPONENT = 3
/** backoffSkips is how many ticks to skip after `failures` consecutive failed polls; 0 while healthy. */
export function backoffSkips(failures: number): number {
return 2 ** Math.min(failures, MAX_BACKOFF_EXPONENT) - 1
}
export function createVisibilityPoller({ intervalMs, tick: rawTick, doc }: VisibilityPollerOptions): VisibilityPoller {
const target = resolveDoc(doc)
let failures = 0
let skipsLeft = 0
/** run fires the store's tick and, when it reports failure, schedules the backoff. `force` (start, tab becoming visible) bypasses pending skips. */
function run(force: boolean): void {
if (!force && skipsLeft > 0) {
skipsLeft--
return
}
const result = rawTick()
if (result instanceof Promise) {
void result.then(
(failed) => {
failures = failed === true ? failures + 1 : 0
skipsLeft = backoffSkips(failures)
},
() => {
failures++
skipsLeft = backoffSkips(failures)
},
)
}
}
const tick = (): void => run(false)
let timer: ReturnType<typeof setInterval> | undefined
// P13 review fix: `timer !== undefined` alone used to double as start()'s
// idempotency guard, but a poller that STARTS while the page is hidden
@@ -89,7 +121,7 @@ export function createVisibilityPoller({ intervalMs, tick, doc }: VisibilityPoll
if (target.hidden) {
clearTimer()
} else {
tick()
run(true)
scheduleTimer()
}
}
@@ -107,7 +139,7 @@ export function createVisibilityPoller({ intervalMs, tick, doc }: VisibilityPoll
if (started) return
started = true
if (!target?.hidden) {
tick()
run(true)
scheduleTimer()
}
target?.addEventListener('visibilitychange', onVisibilityChange)
+27 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { other, ratioSeries, stackTopN, sumByProvider } from './series'
import { activeScopes, activeSeries, other, ratioSeries, stackTopN, sumByProvider } from './series'
describe('stackTopN', () => {
it('returns the n series with the largest total, descending', () => {
@@ -129,3 +129,29 @@ describe('ratioSeries', () => {
expect(ratioSeries([], [])).toEqual([])
})
})
describe('activeSeries / activeScopes', () => {
const series = [
{ scope: 'provider:a', points: [0, 3, 0] },
{ scope: 'provider:idle', points: [0, 0, 0] },
{ scope: 'provider:empty', points: [] },
{ scope: 'provider:b', points: [1, 0, 0] },
]
it('drops series with no traffic and keeps order', () => {
expect(activeSeries(series).map((s) => s.scope)).toEqual(['provider:a', 'provider:b'])
})
it('keeps the chart-wide total unchanged (Lean Gateway.Ui.Active.total_preserved)', () => {
const total = (ss: { points: number[] }[]) => ss.reduce((acc, s) => acc + s.points.reduce((x, y) => x + y, 0), 0)
expect(total(activeSeries(series))).toBe(total(series))
})
it('returns an empty list for no input', () => {
expect(activeSeries([])).toEqual([])
})
it('activeScopes names only providers with traffic', () => {
expect([...activeScopes(series)].sort()).toEqual(['provider:a', 'provider:b'])
})
})
+11 -1
View File
@@ -97,7 +97,17 @@ export function sumByProvider(series: Series[]): Series[] {
byProvider.set(provider, acc)
}
const grouped = Array.from(byProvider.entries()).map(([scope, points]) => ({ scope, points }))
return grouped.sort((a, b) => sumSeries(b.points) - sumSeries(a.points))
return activeSeries(grouped).sort((a, b) => sumSeries(b.points) - sumSeries(a.points))
}
/** activeSeries drops series whose points sum to zero, so a legend lists only entities that had traffic in the window. The chart-wide total is unchanged. */
export function activeSeries<T extends { points: readonly (number | null)[] }>(series: T[]): T[] {
return series.filter((s) => sumSeries(s.points.map((p) => p ?? 0)) > 0)
}
/** activeScopes is the set of scope ids that had any traffic in `series`. */
export function activeScopes(series: Series[]): Set<string> {
return new Set(activeSeries(series).map((s) => s.scope))
}
/**
+8 -8
View File
@@ -13,7 +13,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { AdminApiError, adminFetch, messageOf } from '@/lib/api'
import { eventKindVariant, kindLabel } from '@/lib/events-filter'
import { formatCompactCount, formatCost, formatTimestamp } from '@/lib/format'
import { formatCompactCount, formatCostDisplay, formatTimestamp } from '@/lib/format'
import { headroom, monthProgress, NOT_ENOUGH_DATA, projectMonthEnd } from '@/lib/forecast'
import {
budgetRatio,
@@ -75,8 +75,8 @@ const spendMtdMicros = computed<number>(() => dashboard.usage?.total.costPerMont
const budgetMicros = computed<number>(() => sumGroupBudgetMicros(dashboard.overview?.groups ?? []))
const spendTier = computed(() => budgetTier(budgetRatio(spendMtdMicros.value, budgetMicros.value)))
const spendDelta = computed<string>(() => {
const today = `${formatCost(spendTodayMicros.value)} today`
return budgetMicros.value > 0 ? `${today} · budget ${formatCost(budgetMicros.value)}/mo` : `${today} · no budget set`
const today = `${formatCostDisplay(spendTodayMicros.value)} today`
return budgetMicros.value > 0 ? `${today} · budget ${formatCostDisplay(budgetMicros.value)}/mo` : `${today} · no budget set`
})
// --- Projected month-end (lib/forecast.ts) ------------------------------
@@ -86,7 +86,7 @@ const projectedHeadroom = computed(() =>
headroom(projectedMicros.value, budgetMicros.value > 0 ? microsToUsd(budgetMicros.value) : undefined),
)
const projectedValue = computed<string>(() =>
projectedMicros.value === null ? NOT_ENOUGH_DATA : formatCost(projectedMicros.value),
projectedMicros.value === null ? NOT_ENOUGH_DATA : formatCostDisplay(projectedMicros.value),
)
const projectedTier = computed(() => (projectedHeadroom.value.willExceed ? 'critical' : 'ok'))
const projectedDelta = computed<string | undefined>(() => {
@@ -244,9 +244,9 @@ const topUsersLoaded = computed<boolean>(() => topUsersCache.has(topUsersMode.va
let topUsersReqId = 0
let topModelsReqId = 0
/** formatTopUserValue applies the existing formatter each mode's unit calls for — formatCost (already 2-decimal-cents-safe) for money, formatCompactCount for raw counts/token sums. */
/** formatTopUserValue applies the existing formatter each mode's unit calls for — formatCostDisplay (already 2-decimal-cents-safe) for money, formatCompactCount for raw counts/token sums. */
function formatTopUserValue(mode: TopUsersMode, value: number): string {
return mode === 'cost' ? formatCost(value) : formatCompactCount(value)
return mode === 'cost' ? formatCostDisplay(value) : formatCompactCount(value)
}
const topUsers = computed<TopListItem[]>(() =>
@@ -321,7 +321,7 @@ async function fetchTopModels(): Promise<void> {
topModels.value = res.models.map((m) => ({
id: m.id,
label: m.id,
value: formatCost(m.value),
value: formatCostDisplay(m.value),
kind: 'model' as const,
}))
topModelsError.value = ''
@@ -407,7 +407,7 @@ onUnmounted(() => {
<ErrorState :message="dashboard.error" :on-retry="dashboard.refresh" />
</div>
<template v-else>
<KpiTile label="Spend (MTD)" :value="formatCost(spendMtdMicros)" :delta="spendDelta" :tier="spendTier" :to="{ page: 'spend' }" />
<KpiTile label="Spend (MTD)" :value="formatCostDisplay(spendMtdMicros)" :delta="spendDelta" :tier="spendTier" :to="{ page: 'spend' }" />
<KpiTile
label="Projected month-end"
:value="projectedValue"
+11 -3
View File
@@ -15,7 +15,7 @@ import { Alert, AlertDescription } from '@/components/ui/alert'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { seriesColor } from '@/lib/chart-palette'
import { formatBucketLabel } from '@/lib/format'
import { loadState } from '@/lib/load-state'
import { emptyWhenAllZero, loadState } from '@/lib/load-state'
import type { LoadState } from '@/lib/load-state'
import { formatErrorRatePercent } from '@/lib/provider-rate'
import { scopeId } from '@/lib/scope'
@@ -201,6 +201,10 @@ const reliabilityState = computed<LoadState>(() => {
if (dashboardLoadState.value !== 'ready') return dashboardLoadState.value
return loadState({ loading: reliability.loading, hasData: reliability.buckets.length > 0, error: reliability.error })
})
/** Count charts with nothing to plot show a message instead of an empty 0-1 axis. */
const timeoutState = computed<LoadState>(() => emptyWhenAllZero(reliabilityState.value, timeoutDatasets.value))
const failoverState = computed<LoadState>(() => emptyWhenAllZero(reliabilityState.value, failoverDatasets.value))
/** providerPerfState mirrors reliabilityState for the "Selected provider performance" chart pair — reliability.fetchProviderPerf runs independently of fetch() (its own doc comment), so it needs its own loading/error signal, only reachable once providerPerfAvailable is already true. */
const providerPerfState = computed(() =>
loadState({ loading: reliability.providerPerfLoading, hasData: reliability.providerPerfPoints.length > 0, error: reliability.providerPerfError }),
@@ -367,7 +371,9 @@ onMounted(() => void reliability.fetch())
<ChartCard
title="Timeouts by provider"
:state="reliabilityState"
:state="timeoutState"
show-empty
empty-title="No timeouts in this range.""
:error="reliability.error"
:on-retry="reliability.fetch"
:labels="bucketLabels"
@@ -378,7 +384,9 @@ onMounted(() => void reliability.fetch())
<ChartCard
title="Failovers by provider"
:description="noFailoverConfigured ? 'This deployment has no failover chains configured.' : undefined"
:state="reliabilityState"
:state="failoverState"
show-empty
empty-title="No failovers in this range."
:error="reliability.error"
:on-retry="reliability.fetch"
:labels="bucketLabels"
+5 -3
View File
@@ -13,7 +13,7 @@ import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useNow } from '@/composables/useNow'
import { cacheSavingsStatus } from '@/lib/cache-savings'
import { BREAKDOWN_PALETTE, seriesColor } from '@/lib/chart-palette'
import { formatBucketLabel, formatCompactCount, formatCost } from '@/lib/format'
import { formatBucketLabel, formatCompactCount, formatCostAxis, formatCostDisplay } from '@/lib/format'
import { loadState } from '@/lib/load-state'
import { parseScope, scopeBudgetLimits, scopeId } from '@/lib/scope'
import { useCatalogStore } from '@/stores/catalog'
@@ -133,7 +133,8 @@ const comparisonDatasets = computed<TimeSeriesComparisonDataset[]>(() =>
spend.comparisonPoints ? [{ label: 'Total', data: spend.comparisonPoints, color: '--foreground', labelSuffix: ' (previous period)' }] : [],
)
const valueFormatter = computed<(value: number) => string>(() => (metric.value === 'cost' ? formatCost : formatCompactCount))
const valueFormatter = computed<(value: number) => string>(() => (metric.value === 'cost' ? formatCostDisplay : formatCompactCount))
const axisFormatter = computed<(value: number) => string>(() => (metric.value === 'cost' ? formatCostAxis : formatCompactCount))
const totalInRange = computed<number>(() => spend.totalPoints.reduce((a, b) => a + b, 0))
@@ -264,6 +265,7 @@ function retryPricingHealthTable(): Promise<void> {
:comparison-datasets="comparisonDatasets"
stacked
:value-formatter="valueFormatter"
:axis-formatter="axisFormatter"
:aria-label="`${SPEND_METRIC_LABEL[metric]} breakdown ${SPEND_BY_LABEL[by].toLowerCase()} over time`"
/>
<!-- verify-ui-states-3.md NEW-1: a background refetch failure (poll
@@ -274,7 +276,7 @@ function retryPricingHealthTable(): Promise<void> {
labels/formatter with no indication anything had gone wrong. -->
<p v-if="spend.breakdownError && breakdownState === 'ready'" class="text-sm break-words text-destructive">{{ spend.breakdownError }}</p>
<div class="grid grid-cols-1 gap-4 lg:grid-cols-2">
<div class="grid grid-cols-1 items-start gap-4 lg:grid-cols-2">
<BurnDownChart
v-if="spend.burndownAvailable"
:buckets="spend.burndownBuckets"
+1 -1
View File
@@ -131,7 +131,7 @@ export const useDashboardStore = defineStore('dashboard', {
*/
startPolling(): void {
if (this.poller) return
this.poller = createVisibilityPoller({ intervalMs: POLL_MS, tick: () => void this.refresh() })
this.poller = createVisibilityPoller({ intervalMs: POLL_MS, tick: () => this.refresh().then(() => this.error !== '') })
this.poller.start()
},
// P11 review fix: a stopPolling action mirroring events.ts's own
+6 -4
View File
@@ -2,7 +2,7 @@ import { defineStore } from 'pinia'
import { adminFetch, isAuthRejection, messageOf } from '@/lib/api'
import { seriesUrl } from '@/lib/range'
import { ratioSeries } from '@/lib/series'
import { activeScopes, ratioSeries } from '@/lib/series'
import { useDashboardStore } from '@/stores/dashboard'
import { useFiltersStore } from '@/stores/filters'
import type { AdminPerfResponse, AdminPerfRow, AdminSeriesResponse, HistoryWindow } from '@/types/api'
@@ -155,9 +155,11 @@ export const useReliabilityStore = defineStore('reliability', {
this.buckets = attemptRes.buckets
this.windowUsed = window
this.errorRate = errorRateSeries(attemptRes, failRes)
this.timeouts = timeoutRes.series
this.failovers = foverRes.series
// A provider with no attempts in the window is idle, not healthy: keep it out of every legend.
const active = activeScopes(attemptRes.series)
this.errorRate = errorRateSeries(attemptRes, failRes).filter((s) => active.has(s.scope))
this.timeouts = timeoutRes.series.filter((s) => active.has(s.scope))
this.failovers = foverRes.series.filter((s) => active.has(s.scope))
this.rejections = rejRes.series[0]?.points ?? []
this.unpriced = r402Res.series[0]?.points ?? []
this.lastUpdated = new Date()