fix(admin-ui): stale-data notice, request timeout and dedupe, hash and format edge cases

Show a persistent notice when a refresh fails while old data is on screen.
Add retry to the Targets and Access Matrix error states.
Give tables names, skeletons a status role and CSV export a live region.
Abort admin requests after 15 seconds and share concurrent identical GETs.
Show a reload prompt when a lazy page chunk fails to load.
Ignore prototype keys in the location hash.
Stop formatContextWindow emitting 1000k, round latency before the 1s cutoff,
and treat NaN as not enough data in the month projection.
Regenerate admin_assets_gen.go.
This commit is contained in:
2026-11-08 01:59:34 +00:00
parent 5f5efa5a8d
commit fcfb298077
31 changed files with 421 additions and 180 deletions
+146 -146
View File
File diff suppressed because one or more lines are too long
+16 -8
View File
@@ -6,6 +6,7 @@ import { computed, defineAsyncComponent, onMounted } from 'vue'
import AuthGate from '@/components/AuthGate.vue'
import ConfigWarningsBanner from '@/components/ConfigWarningsBanner.vue'
import PageLoadError from '@/components/PageLoadError.vue'
import GlobalFilterBar from '@/components/GlobalFilterBar.vue'
import SidebarNav from '@/components/SidebarNav.vue'
import ToastViewport from '@/components/ToastViewport.vue'
@@ -43,14 +44,18 @@ useHashState()
* on first load, generalizing the same reasoning the old shell already
* applied to its one chart-heavy tab.
*/
function lazyPage(loader: () => Promise<Component>): Component {
return defineAsyncComponent({ loader, errorComponent: PageLoadError, timeout: 30_000 })
}
const PAGES: Record<PageId, Component> = {
home: defineAsyncComponent(() => import('@/pages/HomePage.vue')),
spend: defineAsyncComponent(() => import('@/pages/SpendPage.vue')),
consumers: defineAsyncComponent(() => import('@/pages/ConsumersPage.vue')),
models: defineAsyncComponent(() => import('@/pages/ModelsPage.vue')),
reliability: defineAsyncComponent(() => import('@/pages/ReliabilityPage.vue')),
config: defineAsyncComponent(() => import('@/pages/ConfigPage.vue')),
targets: defineAsyncComponent(() => import('@/pages/TargetsPage.vue')),
home: lazyPage(() => import('@/pages/HomePage.vue')),
spend: lazyPage(() => import('@/pages/SpendPage.vue')),
consumers: lazyPage(() => import('@/pages/ConsumersPage.vue')),
models: lazyPage(() => import('@/pages/ModelsPage.vue')),
reliability: lazyPage(() => import('@/pages/ReliabilityPage.vue')),
config: lazyPage(() => import('@/pages/ConfigPage.vue')),
targets: lazyPage(() => import('@/pages/TargetsPage.vue')),
}
const currentPage = computed<Component>(() => PAGES[nav.page])
@@ -68,7 +73,10 @@ const currentPage = computed<Component>(() => PAGES[nav.page])
// neither of this function's two `if` branches fires, and the template
// renders the Skeleton for that state instead of ever reading statusText.
const statusText = computed<string>(() => {
if (dashboard.error) return `refresh failed: ${dashboard.error}`
if (dashboard.error) {
const age = dashboard.lastUpdated ? ` · data from ${dashboard.lastUpdated.toLocaleTimeString()}` : ''
return `refresh failed: ${dashboard.error}${age}`
}
const replica = dashboard.overview?.replica
const updated = dashboard.lastUpdated?.toLocaleTimeString() ?? ''
return `last updated ${updated}${replica ? ` · replica ${replica}` : ''}`
+1 -1
View File
@@ -174,7 +174,7 @@ function cellIconClass(cell: AccessCell): string {
</EmptyState>
</CardContent>
<CardContent v-else-if="columnsState === 'error'">
<ErrorState :message="dashboard.error" />
<ErrorState :message="dashboard.error" :on-retry="dashboard.refresh" />
</CardContent>
<CardContent v-else-if="columnsState === 'loading'">
<SkeletonTable :rows="rows.length" :cols="4" />
@@ -191,7 +191,7 @@ const noTrafficInRange = computed<boolean>(() => !showUserModelHint.value && pro
<EmptyState v-else-if="noTrafficInRange" title="No traffic in this range.">
<TryLongerRangeButton />
</EmptyState>
<DataTable v-else :columns="columns" :data="rows" empty-message="none" />
<DataTable v-else :columns="columns" :data="rows" empty-message="No models recorded for this user in this range." label="Per-model attribution" />
</CardContent>
</Card>
</template>
+1
View File
@@ -91,5 +91,6 @@ onBeforeUnmount(() => {
/>
<FontAwesomeIcon v-else :icon="faFileCsv" class="size-3.5" aria-hidden="true" />
<span :class="isFailure ? 'text-destructive' : undefined">{{ label }}</span>
<span class="sr-only" role="status">{{ feedback ? label : '' }}</span>
</Button>
</template>
+4 -2
View File
@@ -38,6 +38,8 @@ const props = defineProps<{
rowClass?: (row: TData) => string | undefined
/** Shown in the empty-state row when data is empty. */
emptyMessage?: string
/** Accessible name for the table (aria-label). */
label?: string
/**
* Optional CONTROLLED sort state (P6, `v-model:sorting`). Omitted (the
* default) keeps every existing call site's original UNCONTROLLED
@@ -88,7 +90,7 @@ function ariaSort(dir: false | 'asc' | 'desc'): 'ascending' | 'descending' | und
</script>
<template>
<Table>
<Table :aria-label="label">
<TableHeader>
<TableRow v-for="headerGroup in table.getHeaderGroups()" :key="headerGroup.id">
<TableHead
@@ -104,7 +106,7 @@ function ariaSort(dir: false | 'asc' | 'desc'): 'ascending' | 'descending' | und
</TableHeader>
<TableBody>
<TableEmpty v-if="table.getRowModel().rows.length === 0" :colspan="columns.length" class="text-muted-foreground">
{{ emptyMessage ?? 'none' }}
{{ emptyMessage ?? 'No rows to show.' }}
</TableEmpty>
<TableRow v-for="row in table.getRowModel().rows" :key="row.id" :class="rowClass?.(row.original)">
<TableCell
+5 -1
View File
@@ -7,6 +7,7 @@ import DataTable from '@/components/DataTable.vue'
import EmptyState from '@/components/EmptyState.vue'
import ErrorState from '@/components/ErrorState.vue'
import SearchInput from '@/components/SearchInput.vue'
import StaleNotice from '@/components/StaleNotice.vue'
import SkeletonTable from '@/components/SkeletonTable.vue'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
@@ -15,6 +16,7 @@ import { useSearchQuery } from '@/composables/useSearchQuery'
import { eventsColumns } from '@/lib/events-columns'
import { EVENT_KIND_LABEL, EVENT_KINDS, filterEvents } from '@/lib/events-filter'
import { loadState } from '@/lib/load-state'
import { staleNotice } from '@/lib/stale-notice'
import { useEventsStore } from '@/stores/events'
// This component backs the new "Events" tab (App.vue, F3) — GET
@@ -68,6 +70,7 @@ const columns = eventsColumns()
* skeleton or error here).
*/
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))
/**
* noEventsRecorded is the GENUINE "nothing has ever happened" case
@@ -148,6 +151,7 @@ onUnmounted(() => {
</div>
</CardHeader>
<CardContent>
<StaleNotice :message="staleMessage" class="mb-3" />
<SkeletonTable v-if="eventsLoadState === 'skeleton'" :rows="5" :cols="columns.length" />
<ErrorState v-else-if="eventsLoadState === 'error'" :message="events.error" :on-retry="events.refresh" />
<EmptyState
@@ -156,7 +160,7 @@ onUnmounted(() => {
title="No failures recorded."
description="Rate-limit, budget, and upstream events will show up here as they happen."
/>
<DataTable v-else :columns="columns" :data="filteredEvents" :empty-message="emptyMessage" />
<DataTable v-else label="Events" :columns="columns" :data="filteredEvents" :empty-message="emptyMessage" />
</CardContent>
</Card>
</div>
+1 -1
View File
@@ -87,7 +87,7 @@ const emptyMessage = computed<string>(() => {
<SkeletonTable v-if="catalogLoadState === 'skeleton'" :rows="5" :cols="columns.length" />
<ErrorState v-else-if="catalogLoadState === 'error'" :message="error ?? ''" :on-retry="onRetry" />
<EmptyState v-else-if="catalogLoadState === 'empty'" title="No models configured." />
<DataTable v-else :columns="columns" :data="filtered" :empty-message="emptyMessage" />
<DataTable v-else label="Model catalog" :columns="columns" :data="filtered" :empty-message="emptyMessage" />
</CardContent>
</Card>
</template>
+21
View File
@@ -0,0 +1,21 @@
<script setup lang="ts">
import { faArrowRotateRight, faTriangleExclamation } from '@fortawesome/free-solid-svg-icons'
import { Button } from '@/components/ui/button'
function reload(): void {
window.location.reload()
}
</script>
<template>
<div role="alert" class="flex flex-col items-center gap-2 px-4 py-16 text-center">
<FontAwesomeIcon :icon="faTriangleExclamation" class="size-6 text-destructive" aria-hidden="true" />
<p class="text-sm font-medium text-destructive">This page failed to load.</p>
<p class="max-w-md text-sm text-muted-foreground">The gateway may have been updated since this tab opened. Reload to fetch the current version.</p>
<Button type="button" variant="outline" size="sm" class="mt-1" @click="reload">
<FontAwesomeIcon :icon="faArrowRotateRight" class="size-3.5" aria-hidden="true" />
Reload
</Button>
</div>
</template>
+1 -1
View File
@@ -147,7 +147,7 @@ function pricingHealthCsv(): string {
<TryLongerRangeButton />
</EmptyState>
</template>
<DataTable :columns="columns" :data="rows" empty-message="none" />
<DataTable :columns="columns" :data="rows" empty-message="No priced models in this range." label="Pricing health" />
<div class="flex justify-end">
<CsvExportButton filename="pricing-health.csv" :build="pricingHealthCsv" />
</div>
+1 -1
View File
@@ -531,7 +531,7 @@ const aliasEmptyMessage = computed(() =>
<CardDescription>Operator-defined alias &rarr; target model mappings.</CardDescription>
</CardHeader>
<CardContent>
<DataTable :columns="aliasColumns" :data="filteredAliases" :empty-message="aliasEmptyMessage" />
<DataTable label="Model aliases" :columns="aliasColumns" :data="filteredAliases" :empty-message="aliasEmptyMessage" />
</CardContent>
</Card>
+1 -1
View File
@@ -12,7 +12,7 @@ import { Skeleton } from '@/components/ui/skeleton'
</script>
<template>
<div class="h-72 w-full">
<div class="h-72 w-full" role="status" aria-busy="true" aria-label="Loading chart">
<Skeleton class="h-full w-full" />
</div>
</template>
+2 -1
View File
@@ -14,10 +14,11 @@ withDefaults(defineProps<{ rows?: number; cols?: number }>(), { rows: 5, cols: 4
</script>
<template>
<Table>
<Table role="status" aria-busy="true" aria-label="Loading">
<TableHeader>
<TableRow>
<TableHead v-for="c in cols" :key="c">
<span class="sr-only">Loading</span>
<Skeleton class="h-4 w-16" />
</TableHead>
</TableRow>
+14
View File
@@ -0,0 +1,14 @@
<script setup lang="ts">
import { faTriangleExclamation } from '@fortawesome/free-solid-svg-icons'
import { Alert, AlertDescription } from '@/components/ui/alert'
defineProps<{ message: string | null }>()
</script>
<template>
<Alert v-if="message" variant="warn" role="status">
<FontAwesomeIcon :icon="faTriangleExclamation" aria-hidden="true" />
<AlertDescription>{{ message }}</AlertDescription>
</Alert>
</template>
+1 -1
View File
@@ -98,7 +98,7 @@ const callersLoadState = computed(() => loadState({ loading: loading.value, hasD
<CardContent class="flex flex-col gap-3">
<ClampedRangeNotice :window="filters.window" :span="filters.span" />
<LoadStateView :state="callersLoadState" :error="error" :on-retry="load" skeleton="table" :rows="5" :cols="columns.length">
<DataTable :columns="columns" :data="rows" empty-message="no callers recorded in this window" />
<DataTable :columns="columns" :data="rows" label="Callers" empty-message="no callers recorded in this window" />
</LoadStateView>
</CardContent>
</Card>
+4 -4
View File
@@ -126,8 +126,8 @@ const agentColumns = targetColumns(onSelect('agent'))
</CardHeader>
<CardContent>
<SkeletonTable v-if="targetsLoadState === 'skeleton'" :rows="3" :cols="mcpColumns.length" />
<ErrorState v-else-if="targetsLoadState === 'error'" :message="dashboard.error" />
<DataTable v-else :columns="mcpColumns" :data="filteredMCPServers" :empty-message="mcpEmptyMessage" />
<ErrorState v-else-if="targetsLoadState === 'error'" :message="dashboard.error" :on-retry="dashboard.refresh" />
<DataTable v-else label="MCP servers" :columns="mcpColumns" :data="filteredMCPServers" :empty-message="mcpEmptyMessage" />
</CardContent>
</Card>
@@ -141,8 +141,8 @@ const agentColumns = targetColumns(onSelect('agent'))
</CardHeader>
<CardContent>
<SkeletonTable v-if="targetsLoadState === 'skeleton'" :rows="3" :cols="agentColumns.length" />
<ErrorState v-else-if="targetsLoadState === 'error'" :message="dashboard.error" />
<DataTable v-else :columns="agentColumns" :data="filteredAgents" :empty-message="agentsEmptyMessage" />
<ErrorState v-else-if="targetsLoadState === 'error'" :message="dashboard.error" :on-retry="dashboard.refresh" />
<DataTable v-else label="Agents" :columns="agentColumns" :data="filteredAgents" :empty-message="agentsEmptyMessage" />
</CardContent>
</Card>
</template>
+1
View File
@@ -39,6 +39,7 @@ const columns = computed(() =>
<template>
<DataTable
label="Usage"
:columns="columns"
:data="entries"
:empty-message="emptyMessage"
+3 -1
View File
@@ -2,6 +2,8 @@
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
defineOptions({ inheritAttrs: false })
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
@@ -9,7 +11,7 @@ const props = defineProps<{
<template>
<div data-slot="table-container" class="relative w-full overflow-x-auto">
<table data-slot="table" :class="cn('w-full caption-bottom text-sm', props.class)">
<table data-slot="table" v-bind="$attrs" :class="cn('w-full caption-bottom text-sm', props.class)">
<slot />
</table>
</div>
+75
View File
@@ -101,3 +101,78 @@ describe('isAuthRejection', () => {
expect(isAuthRejection('nope')).toBe(false)
})
})
describe('adminFetch resilience', () => {
beforeEach(() => {
setActivePinia(createPinia())
useAuthStore().submit('test-admin-key')
vi.stubGlobal('fetch', vi.fn())
})
it('passes an abort signal so a hung request cannot block polling forever', async () => {
vi.mocked(fetch).mockResolvedValue(jsonResponse(200, {}))
await adminFetch('/admin/api/overview')
const init = vi.mocked(fetch).mock.calls[0][1]
expect(init?.signal).toBeInstanceOf(AbortSignal)
})
it('turns a timeout into an AdminApiError naming the path', async () => {
vi.mocked(fetch).mockRejectedValue(new DOMException('timed out', 'TimeoutError'))
await expect(adminFetch('/admin/api/overview')).rejects.toMatchObject({
name: 'AdminApiError',
message: expect.stringContaining('/admin/api/overview'),
})
})
it('turns a 200 with a non-JSON body into an AdminApiError, not a raw SyntaxError', async () => {
vi.mocked(fetch).mockResolvedValue({
ok: true,
status: 200,
json: () => Promise.reject(new SyntaxError('Unexpected token <')),
} as Response)
await expect(adminFetch('/admin/api/overview')).rejects.toBeInstanceOf(AdminApiError)
})
it('rethrows network errors unchanged', async () => {
vi.mocked(fetch).mockRejectedValue(new TypeError('Failed to fetch'))
await expect(adminFetch('/admin/api/overview')).rejects.toThrow('Failed to fetch')
})
})
describe('adminFetch in-flight dedupe', () => {
beforeEach(() => {
setActivePinia(createPinia())
useAuthStore().submit('test-admin-key')
vi.stubGlobal('fetch', vi.fn())
})
it('shares one request between concurrent calls for the same path', async () => {
vi.mocked(fetch).mockResolvedValue(jsonResponse(200, { n: 1 }))
const [a, b] = await Promise.all([adminFetch('/admin/api/x'), adminFetch('/admin/api/x')])
expect(fetch).toHaveBeenCalledTimes(1)
expect(a).toEqual({ n: 1 })
expect(b).toEqual({ n: 1 })
})
it('does not share between different paths', async () => {
vi.mocked(fetch).mockResolvedValue(jsonResponse(200, {}))
await Promise.all([adminFetch('/admin/api/x'), adminFetch('/admin/api/y')])
expect(fetch).toHaveBeenCalledTimes(2)
})
it('issues a fresh request once the first settles, including after failure', async () => {
vi.mocked(fetch).mockRejectedValueOnce(new TypeError('down')).mockResolvedValue(jsonResponse(200, { ok: true }))
await expect(adminFetch('/admin/api/x')).rejects.toThrow('down')
await expect(adminFetch('/admin/api/x')).resolves.toEqual({ ok: true })
expect(fetch).toHaveBeenCalledTimes(2)
})
it('does not share across different admin keys', async () => {
vi.mocked(fetch).mockResolvedValue(jsonResponse(200, {}))
const first = adminFetch('/admin/api/x')
useAuthStore().submit('other-key')
const second = adminFetch('/admin/api/x')
await Promise.all([first, second])
expect(fetch).toHaveBeenCalledTimes(2)
})
})
+31 -4
View File
@@ -1,5 +1,11 @@
import { useAuthStore } from '@/stores/auth'
/** Upper bound on one admin request; a hung socket would otherwise pin a store's in-flight guard and freeze polling. */
const ADMIN_FETCH_TIMEOUT_MS = 15_000
/** Concurrent GETs for the same key and path share one request (spend.ts asks twice for the default metric). */
const inFlight = new Map<string, Promise<unknown>>()
/** AdminApiError carries the HTTP status alongside the message, so callers
* can tell an auth failure (already handled by adminFetch itself) apart
* from any other fetch failure without re-parsing the message string. */
@@ -41,12 +47,29 @@ async function serverErrorMessage(resp: Response, path: string): Promise<string>
* poll timer should not spam the status line with "unauthorized" on every
* tick once the gate is already showing) can catch and check `status`.
*/
export async function adminFetch<T>(path: string): Promise<T> {
export function adminFetch<T>(path: string): Promise<T> {
const key = useAuthStore().apiKey
const flightKey = `${key}\0${path}`
const existing = inFlight.get(flightKey)
if (existing) return existing as Promise<T>
const request = doAdminFetch<T>(path, key).finally(() => inFlight.delete(flightKey))
inFlight.set(flightKey, request)
return request
}
async function doAdminFetch<T>(path: string, key: string): Promise<T> {
const auth = useAuthStore()
const key = auth.apiKey
const headers: HeadersInit = key ? { 'x-api-key': key } : {}
const resp = await fetch(path, { credentials: 'same-origin', headers })
let resp: Response
try {
resp = await fetch(path, { credentials: 'same-origin', headers, signal: AbortSignal.timeout(ADMIN_FETCH_TIMEOUT_MS) })
} catch (err) {
if (err instanceof DOMException && err.name === 'TimeoutError') {
throw new AdminApiError(`${path}: no response after ${ADMIN_FETCH_TIMEOUT_MS / 1000}s`, 0)
}
throw err
}
if (!resp.ok) {
const message = await serverErrorMessage(resp, path)
@@ -59,7 +82,11 @@ export async function adminFetch<T>(path: string): Promise<T> {
}
throw new AdminApiError(message, resp.status)
}
return (await resp.json()) as T
try {
return (await resp.json()) as T
} catch {
throw new AdminApiError(`${path}: response was not valid JSON`, resp.status)
}
}
/**
+6
View File
@@ -137,3 +137,9 @@ describe('NOT_ENOUGH_DATA', () => {
expect(NOT_ENOUGH_DATA).toBeTruthy()
})
})
describe('projectMonthEnd non-finite input', () => {
it.each([NaN, Infinity * 0, -1])('returns null for elapsedFraction %s', (f) => {
expect(projectMonthEnd(5, f)).toBeNull()
})
})
+1 -1
View File
@@ -70,7 +70,7 @@ export function monthProgress(now: Date): number {
* infinite figure for the first sliver of a month.
*/
export function projectMonthEnd(mtdMicros: number, elapsedFraction: number): number | null {
if (elapsedFraction < MIN_PROJECTION_FRACTION) return null
if (!(elapsedFraction >= MIN_PROJECTION_FRACTION)) return null
return Math.round(mtdMicros / elapsedFraction)
}
+19
View File
@@ -250,3 +250,22 @@ describe('formatElapsedAgo', () => {
expect(formatElapsedAgo(iso)).toMatch(/^\d+s ago$/)
})
})
describe('rounding boundaries', () => {
it.each([
{ name: 'k rounding never reaches 1000k', tokens: 999_999, want: '1M' },
{ name: 'just under the cutoff stays k', tokens: 999_499, want: '999k' },
{ name: 'cutoff moves to M', tokens: 999_500, want: '1M' },
])('formatContextWindow: $name', ({ tokens, want }) => {
expect(formatContextWindow(tokens)).toBe(want)
})
it.each([
{ name: 'rounds before the second cutoff', ms: 999.6, want: '1.0s' },
{ name: 'plain ms', ms: 120, want: '120ms' },
{ name: 'NaN', ms: NaN, want: '—' },
{ name: 'Infinity', ms: Infinity, want: '—' },
])('formatLatencyMs: $name', ({ ms, want }) => {
expect(formatLatencyMs(ms)).toBe(want)
})
})
+5 -2
View File
@@ -162,7 +162,8 @@ export function formatContextWindow(tokens: number): string {
return `${Math.round(tokens / (1024 * 1024))}M`
}
if (tokens < 1_000_000) return `${Math.round(tokens / 1_000)}k`
// 999_500+ would round to "1000k"; the M branch renders it as "1M".
if (tokens < 999_500) return `${Math.round(tokens / 1_000)}k`
return `${Math.round(tokens / 1_000_000)}M`
}
@@ -195,7 +196,9 @@ export function formatModelCostHover(inputUsd: number, outputUsd: number): strin
* crossed, just a plain rounded reading.
*/
export function formatLatencyMs(ms: number): string {
if (ms < 1000) return `${Math.round(ms)}ms`
if (!Number.isFinite(ms)) return '—'
const rounded = Math.round(ms)
if (rounded < 1000) return `${rounded}ms`
return `${(ms / 1000).toFixed(1)}s`
}
+9
View File
@@ -130,3 +130,12 @@ describe('parsePageParams', () => {
expect(parsePageParams(new URLSearchParams())).toEqual({})
})
})
describe('parseHashState prototype keys', () => {
it.each(['constructor', 'toString', '__proto__', 'hasOwnProperty'])('#%s falls back to the default page', (key) => {
const state = parseHashState(`#${key}?range=7d`)
expect(typeof state.page).toBe('string')
expect(PAGE_IDS).toContain(state.page)
expect(state.query.get('range')).toBe('7d')
})
})
+1 -1
View File
@@ -53,7 +53,7 @@ export function parseHashState(hash: string): HashState {
if (isPageId(pagePart)) return { page: pagePart, query: new URLSearchParams(queryPart) }
const legacy = LEGACY_PAGE_MAP[pagePart]
const legacy = Object.hasOwn(LEGACY_PAGE_MAP, pagePart) ? LEGACY_PAGE_MAP[pagePart] : undefined
if (legacy) return { page: legacy, query: new URLSearchParams() }
return { page: DEFAULT_PAGE, query: new URLSearchParams(queryPart) }
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest'
import { loadState } from './load-state'
import { staleNotice } from './stale-notice'
const at = new Date('2026-11-08T10:11:12Z')
describe('staleNotice', () => {
it.each([
{ name: 'no data, error', hasData: false, error: 'boom', want: null },
{ name: 'data, no error', hasData: true, error: '', want: null },
{ name: 'no data, no error', hasData: false, error: '', want: null },
])('is null: $name', ({ hasData, error, want }) => {
expect(staleNotice(hasData, error, at)).toBe(want)
})
it('names the error and the data age when data is shown and refresh fails', () => {
const msg = staleNotice(true, 'HTTP 503', at)
expect(msg).toContain('HTTP 503')
expect(msg).toContain(at.toLocaleTimeString())
})
it('omits the age when lastUpdated is unknown', () => {
expect(staleNotice(true, 'x', null)).toBe('Refresh failing: x.')
})
// Lean gate Gateway.Ui.Stale.no_silent_stale: ready + error always has a notice.
it.each([true, false])('never silent when ready with error (loading=%s)', (loading) => {
const state = loadState({ loading, hasData: true, error: 'e' })
expect(state).toBe('ready')
expect(staleNotice(true, 'e', at)).not.toBeNull()
})
})
+6
View File
@@ -0,0 +1,6 @@
/** staleNotice returns the text for a "showing old data" banner, or null. Shown only when data is on screen and the latest refresh failed. */
export function staleNotice(hasData: boolean, error: string, lastUpdated: Date | null): string | null {
if (!hasData || !error) return null
const at = lastUpdated ? ` Data from ${lastUpdated.toLocaleTimeString()}.` : ''
return `Refresh failing: ${error}.${at}`
}
+8 -1
View File
@@ -4,8 +4,15 @@ import { createApp } from 'vue'
import App from '@/App.vue'
import '@/assets/main.css'
import { messageOf } from '@/lib/api'
import { useToastsStore } from '@/stores/toasts'
const app = createApp(App)
app.use(createPinia())
const pinia = createPinia()
app.use(pinia)
app.config.errorHandler = (err) => {
console.error(err)
useToastsStore(pinia).push({ kind: 'error', message: `Unexpected error: ${messageOf(err)}` })
}
app.component('FontAwesomeIcon', FontAwesomeIcon)
app.mount('#app')
+1 -1
View File
@@ -496,7 +496,7 @@ onUnmounted(() => {
>
<span class="flex min-w-0 items-center gap-2">
<Badge :variant="eventKindVariant(event.kind)" class="shrink-0 font-normal">{{ kindLabel(event.kind) }}</Badge>
<span class="min-w-0 truncate text-muted-foreground">{{ event.message }}</span>
<span class="min-w-0 truncate text-muted-foreground" :title="event.message">{{ event.message }}</span>
</span>
<span class="shrink-0 tabular-nums text-muted-foreground">{{ formatTimestamp(event.time) }}</span>
</li>
+2
View File
@@ -7,6 +7,7 @@ vi.mock('@/lib/api', async () => {
})
import { adminFetch, AdminApiError } from '@/lib/api'
import { clearStoredKey } from '@/lib/key-storage'
import { useAuthStore } from '@/stores/auth'
import { useCatalogStore } from '@/stores/catalog'
import type { AdminCatalogResponse } from '@/types/api'
@@ -39,6 +40,7 @@ describe('useCatalogStore.fetch', () => {
})
it('is a no-op while unauthenticated', async () => {
clearStoredKey()
setActivePinia(createPinia())
const catalog = useCatalogStore()
await catalog.fetch()