fix(admin-ui): page-level loading, stale and form fixes

Fetch the consumers list on the user detail page so admin and grant data show on a deep link.
Gate Recent errors, the Spend total and the forecast card on load state instead of showing zeros.
Show a stale notice on top lists when a refresh fails.
Clear the target name when the target kind changes.
Ignore out-of-order config responses.
Wrap long group names and event messages, and announce projected budget overruns to screen readers.
Regenerate admin_assets_gen.go.
This commit is contained in:
2026-11-08 02:04:23 +00:00
parent fcfb298077
commit 05a7c114f5
10 changed files with 158 additions and 78 deletions
+68 -68
View File
File diff suppressed because one or more lines are too long
+3 -2
View File
@@ -335,11 +335,11 @@ function groupsCsv(): string {
<Accordion v-if="sortedGroupRows.length" v-model="expandedGroupValues" type="multiple" class="rounded-md border px-3">
<AccordionItem v-for="row in sortedGroupRows" :key="row.original.id" :value="row.original.id">
<div class="flex items-center gap-2">
<span class="shrink-0 py-2.5 font-medium">{{ row.original.id }}</span>
<span class="min-w-0 break-all py-2.5 font-medium">{{ row.original.id }}</span>
<AccordionTrigger header-class="flex-1">
<span class="sr-only">Group {{ row.original.id }} details</span>
<span class="flex flex-1 flex-wrap items-center gap-x-4 gap-y-1 pr-2 text-left">
<span class="text-xs text-muted-foreground tabular-nums">{{ memberCountOf(row.original) || '0' }} members</span>
<span class="text-xs text-muted-foreground tabular-nums">{{ dashboard.overview ? memberCountOf(row.original) || '0' : '?' }} members</span>
<span class="text-xs text-muted-foreground tabular-nums">
<template v-if="row.original.storeDown">?</template>
<CompactNumber v-else :value="row.original.requestsPerDay" /> req/day
@@ -433,6 +433,7 @@ function groupsCsv(): string {
:title="!row.original.storeDown && groupCostProjection(row.original, now).willExceed ? WILL_EXCEED_TITLE : undefined"
>
{{ row.original.storeDown ? '?' : groupCostProjection(row.original, now).text }}
<span v-if="!row.original.storeDown && groupCostProjection(row.original, now).willExceed" class="sr-only">(will exceed limit)</span>
</DetailField>
</dl>
<BudgetRatioBars v-if="budgetRatios(row.original).length" class="mb-3" :ratios="budgetRatios(row.original)" />
+4
View File
@@ -5,8 +5,10 @@ import EmptyState from '@/components/EmptyState.vue'
import EntityLink from '@/components/EntityLink.vue'
import ErrorState from '@/components/ErrorState.vue'
import SkeletonList from '@/components/SkeletonList.vue'
import StaleNotice from '@/components/StaleNotice.vue'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { loadState } from '@/lib/load-state'
import { staleNotice } from '@/lib/stale-notice'
/** One TopList.vue row — an entity id/label, its formatted value, and which EntityLink.vue target it opens. */
export interface TopListItem {
@@ -81,6 +83,7 @@ const props = withDefaults(
)
const state = computed(() => loadState({ loading: props.loading, hasData: props.loaded, error: props.error ?? '' }))
const staleMessage = computed(() => staleNotice(props.loaded, props.error ?? '', null))
</script>
<template>
@@ -90,6 +93,7 @@ const state = computed(() => loadState({ loading: props.loading, hasData: props.
<slot name="controls" />
</CardHeader>
<CardContent>
<StaleNotice :message="notice ? null : staleMessage" class="mb-3" />
<EmptyState v-if="notice" :title="notice" :description="noticeDescription" />
<SkeletonList v-else-if="state === 'skeleton'" :rows="5" />
<ErrorState v-else-if="state === 'error'" :message="error ?? ''" :on-retry="onRetry" />
+7 -3
View File
@@ -67,6 +67,7 @@ function loadDetail(): Promise<void> {
onMounted(() => {
void loadDetail()
void events.refresh()
void consumers.ensureConsumers()
})
// featuresUserModelStats is included alongside userId/range: on a deep
// link or reload (#consumers?user=x), this component mounts and fires
@@ -119,7 +120,7 @@ const reqState = computed(() => loadState({ loading: detail.value?.loading ?? fa
const costState = computed(() => loadState({ loading: detail.value?.loading ?? false, hasData: detail.value?.costSeries != null, error: detail.value?.costError ?? '' }))
/** showUserModelHint mirrors AttributionDrilldown.vue's own convention (Spend page): the hint shows when the client's own feature flag reads off, OR the usermodel call itself came back 404 (stores/consumers.ts's modelTotalsUnavailable) — the second case catches a stale/not-yet-loaded overview on a deep link or reload, where featuresUserModelStats can read true for a moment while the server still says otherwise. */
const showUserModelHint = computed(() => !featuresUserModelStats.value || detail.value?.modelTotalsUnavailable === true)
const showUserModelHint = computed(() => (dashboard.overview !== null && !featuresUserModelStats.value) || detail.value?.modelTotalsUnavailable === true)
/** modelRows ranks usermodel totals by cost desc (falling back to req when cost is absent from the requested metrics) — a small, page-local sort since this table has no other consumer that would justify a shared column/sort helper. */
const modelRows = computed(() => {
@@ -144,6 +145,7 @@ const modelState = computed(() => loadState({ loading: detail.value?.loading ??
/** recentErrors filters the shared Events store (WP-F, read-only import) down to this user — the newest 10, matching the store's own newest-first order. */
const recentErrors = computed(() => events.events.filter((e) => e.user === props.userId).slice(0, 10))
const recentErrorsState = computed(() => loadState({ loading: events.refreshing, hasData: events.lastUpdated !== null, error: events.error }))
const ratios = computed(() => (entry.value ? budgetRatios(entry.value) : []))
@@ -266,13 +268,15 @@ const runOutDate = computed(() => {
<CardTitle>Recent errors</CardTitle>
</CardHeader>
<CardContent>
<ul v-if="recentErrors.length" class="flex flex-col gap-2 text-sm">
<SkeletonTable v-if="recentErrorsState === 'skeleton'" :rows="2" :cols="2" />
<ErrorState v-else-if="recentErrorsState === 'error'" :message="events.error" :on-retry="events.refresh" />
<ul v-else-if="recentErrors.length" class="flex flex-col gap-2 text-sm">
<li v-for="(event, index) in recentErrors" :key="index" class="border-b pb-2 last:border-0 last:pb-0">
<p class="flex flex-wrap items-center gap-2">
<Badge variant="secondary">{{ event.kind }}</Badge>
<span class="text-muted-foreground">{{ formatTimestamp(event.time) }}</span>
</p>
<p class="text-muted-foreground">{{ event.message }}</p>
<p class="break-words text-muted-foreground">{{ event.message }}</p>
</li>
</ul>
<EmptyState v-else title="No recent errors in the current event window." />
@@ -57,6 +57,7 @@ function onNameUpdate(value: unknown): void {
<SelectItem v-for="name in targetNames" :key="name" :value="name">{{ name }}</SelectItem>
</SelectContent>
</Select>
<p v-if="targetNames.length === 0" class="text-xs text-muted-foreground">No {{ targetKind === 'group' ? 'groups' : 'users' }} loaded yet.</p>
</div>
</div>
</template>
@@ -45,3 +45,13 @@ describe('useTargetPicker', () => {
expect(picker.snippetLabel.value).toBe('Merge into alice’s users.json line')
})
})
describe('useTargetPicker kind switch', () => {
it('clears targetName when targetKind changes so a stale name cannot leak across kinds', () => {
const picker = useTargetPicker(() => ['admins'], () => ['alice'])
picker.targetName.value = 'admins'
picker.targetKind.value = 'user'
expect(picker.targetName.value).toBe('')
expect(picker.nameValid.value).toBe(false)
})
})
+3 -1
View File
@@ -1,4 +1,4 @@
import { computed, ref, type ComputedRef, type Ref } from 'vue'
import { computed, ref, watch, type ComputedRef, type Ref } from 'vue'
import { isValidName, isValidUserName } from '@/lib/snippets'
@@ -30,6 +30,8 @@ export function useTargetPicker(groupNames: () => string[], userNames: () => str
const targetKind = ref<GrantTargetKind>('group')
const targetName = ref('')
watch(targetKind, () => (targetName.value = ''), { flush: 'sync' })
const targetNames = computed(() => (targetKind.value === 'group' ? groupNames() : userNames()))
const nameValid = computed(() => (targetKind.value === 'group' ? isValidName(targetName.value.trim()) : isValidUserName(targetName.value)))
+2 -2
View File
@@ -219,7 +219,7 @@ function retryPricingHealthTable(): Promise<void> {
</div>
<div class="text-right">
<p class="text-xs font-medium text-muted-foreground">{{ SPEND_METRIC_LABEL[metric] }} in range</p>
<p class="text-2xl font-semibold tabular-nums">{{ valueFormatter(totalInRange) }}</p>
<p class="text-2xl font-semibold tabular-nums">{{ breakdownState === 'ready' ? valueFormatter(totalInRange) : '—' }}</p>
</div>
</div>
<p v-if="byDisabled" class="text-sm text-muted-foreground">
@@ -285,7 +285,7 @@ function retryPricingHealthTable(): Promise<void> {
:error="spend.burndownError"
:on-retry="spend.refresh"
/>
<CostForecastCard v-if="forecastAvailable" :mtd-micros="scopeMtdMicros" :limits="scopeLimits" :now="now" />
<CostForecastCard v-if="forecastAvailable && dashboard.usage" :mtd-micros="scopeMtdMicros" :limits="scopeLimits" :now="now" />
</div>
<CostAvoidedCard
+52
View File
@@ -0,0 +1,52 @@
import { createPinia, setActivePinia } from 'pinia'
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('@/lib/api', async () => {
const actual = await vi.importActual<typeof import('@/lib/api')>('@/lib/api')
return { ...actual, adminFetch: vi.fn() }
})
import { adminFetch } from '@/lib/api'
import { useAuthStore } from '@/stores/auth'
import { useConfigStore } from '@/stores/config'
import type { AdminConfigResponse } from '@/types/api'
const mocked = vi.mocked(adminFetch)
const cfg = (tag: string) => ({ tag }) as unknown as AdminConfigResponse
function deferred<T>() {
let resolve!: (v: T) => void
const promise = new Promise<T>((r) => (resolve = r))
return { promise, resolve }
}
describe('useConfigStore.fetchConfig', () => {
beforeEach(() => {
setActivePinia(createPinia())
mocked.mockReset()
useAuthStore().submit('k')
})
it('keeps the newest response when an older request settles last', async () => {
const older = deferred<AdminConfigResponse>()
const newer = deferred<AdminConfigResponse>()
mocked.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise)
const store = useConfigStore()
const first = store.fetchConfig()
const second = store.fetchConfig()
newer.resolve(cfg('new'))
await second
older.resolve(cfg('old'))
await first
expect(store.data).toEqual(cfg('new'))
expect(store.loading).toBe(false)
})
it('records the error message on failure', async () => {
mocked.mockRejectedValue(new Error('boom'))
const store = useConfigStore()
await store.fetchConfig()
expect(store.error).toBe('boom')
expect(store.loading).toBe(false)
})
})
+8 -2
View File
@@ -19,20 +19,26 @@ export const useConfigStore = defineStore('config', {
data: null as AdminConfigResponse | null,
loading: false,
error: '',
/** Latest-request-wins guard: only the newest fetch may write state. */
reqId: 0,
}),
actions: {
async fetchConfig(): Promise<void> {
const auth = useAuthStore()
if (!auth.isAuthenticated) return
const requestId = ++this.reqId
this.loading = true
try {
this.data = await adminFetch<AdminConfigResponse>('/admin/api/config')
const res = await adminFetch<AdminConfigResponse>('/admin/api/config')
if (requestId !== this.reqId) return
this.data = res
this.error = ''
} catch (err) {
if (requestId !== this.reqId) return
if (isAuthRejection(err)) return
this.error = messageOf(err)
} finally {
this.loading = false
if (requestId === this.reqId) this.loading = false
}
},
/** ensureConfig fetches only when there is no data yet — ConfigPage.vue's own onMounted call. */