fix(admin-ui): cap user detail cache, gate breakdown on ranking, restore single chevron

The per-user detail cache grew without limit and now keeps the 20 most recently fetched users. Spend refresh built the breakdown from a stale ranking after the ranking failed or was superseded, and now skips that step. The FontAwesome stylesheet overrode Tailwind hidden and showed two accordion chevrons, so it now loads in a low cascade layer.
This commit is contained in:
2026-11-08 02:35:06 +00:00
parent 8c5e4fbcda
commit 3e1750ddb9
8 changed files with 121 additions and 40 deletions
+32 -32
View File
File diff suppressed because one or more lines are too long
+2
View File
@@ -1,4 +1,6 @@
@import "tailwindcss";
/* Layered below utilities so Tailwind classes such as `hidden` still win over the FontAwesome icon display rule. */
@import "@fortawesome/fontawesome-svg-core/styles.css" layer(base);
@import "tw-animate-css";
@import "shadcn-vue/tailwind.css";
+10
View File
@@ -0,0 +1,10 @@
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
describe('main.css', () => {
// Unlayered FontAwesome CSS sets `display` on every icon and beats Tailwind's `hidden`, so both chevrons of an accordion trigger showed.
it('imports the FontAwesome stylesheet inside a cascade layer', () => {
const css = readFileSync(new URL('./main.css', import.meta.url), 'utf8')
expect(css).toMatch(/@import\s+"@fortawesome\/fontawesome-svg-core\/styles\.css"\s+layer\(/)
})
})
-1
View File
@@ -1,5 +1,4 @@
import { config } from '@fortawesome/fontawesome-svg-core'
import '@fortawesome/fontawesome-svg-core/styles.css'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { createPinia } from 'pinia'
import { createApp } from 'vue'
+17 -1
View File
@@ -12,7 +12,7 @@ vi.mock('@/lib/api', async () => {
import { AdminApiError, adminFetch } from '@/lib/api'
import { useAuthStore } from '@/stores/auth'
import { useConsumersStore } from '@/stores/consumers'
import { evictOldestDetails, useConsumersStore } from '@/stores/consumers'
import type { AdminConsumersResponse, AdminSeriesResponse, AdminTotalsResponse } from '@/types/api'
const mockedAdminFetch = vi.mocked(adminFetch)
@@ -318,3 +318,19 @@ describe('useConsumersStore.fetchUserDetail', () => {
await inFlight
})
})
describe('evictOldestDetails', () => {
const entry = (fetchedAt: number | null, loading = false) =>
({ loading, fetchedAt, reqId: 1, window: 'day', span: 7 }) as unknown as import('@/stores/consumers').UserDetailState
it.each([
{ name: 'under cap keeps all', cap: 5, keep: 'a', loadingId: '', want: ['a', 'b', 'c'] },
{ name: 'drops oldest beyond cap', cap: 2, keep: 'c', loadingId: '', want: ['b', 'c'] },
{ name: 'never drops the kept user', cap: 1, keep: 'a', loadingId: '', want: ['a'] },
{ name: 'never drops a loading entry', cap: 1, keep: 'c', loadingId: 'a', want: ['a', 'c'] },
])('$name', ({ cap, keep, loadingId, want }) => {
const detail = { a: entry(1, loadingId === 'a'), b: entry(2), c: entry(3) }
evictOldestDetails(detail, keep, cap)
expect(Object.keys(detail).sort()).toEqual(want)
})
})
+17
View File
@@ -43,6 +43,22 @@ export interface UserDetailState {
span: number | null
}
/** MAX_CACHED_USER_DETAILS caps how many opened users' detail the store keeps in memory. */
export const MAX_CACHED_USER_DETAILS = 20
/** evictOldestDetails drops the least recently fetched entries beyond the cap, never the kept user and never one still loading. */
export function evictOldestDetails(detail: Record<string, UserDetailState>, keep: string, cap: number): void {
const ids = Object.keys(detail)
let excess = ids.length - cap
if (excess <= 0) return
const candidates = ids.filter((id) => id !== keep && !detail[id]?.loading).sort((a, b) => (detail[a]?.fetchedAt ?? 0) - (detail[b]?.fetchedAt ?? 0))
for (const id of candidates) {
if (excess <= 0) break
delete detail[id]
excess--
}
}
function emptyDetail(): UserDetailState {
return {
loading: false,
@@ -168,6 +184,7 @@ export const useConsumersStore = defineStore('consumers', {
costError: rangeChanged ? '' : existing.costError,
modelError: rangeChanged ? '' : existing.modelError,
}
evictOldestDetails(this.detail, userId, MAX_CACHED_USER_DETAILS)
const clamped = dayOrMonthWindow(window, span)
const [reqResult, costResult, modelResult] = await Promise.allSettled([
+29 -1
View File
@@ -677,7 +677,7 @@ describe('useSpendStore: pricingHealthLoaded / drilldownLoaded', () => {
describe('useSpendStore.refresh: overlapping calls', () => {
it('an earlier refresh finishing after a newer one has started does not clear loading', async () => {
const spend = useSpendStore()
vi.spyOn(spend, 'fetchModelRanking').mockResolvedValue(undefined)
vi.spyOn(spend, 'fetchModelRanking').mockResolvedValue(true)
const pending: (() => void)[] = []
const controlled = (): Promise<void> => new Promise((resolve) => pending.push(resolve))
@@ -704,3 +704,31 @@ describe('useSpendStore.refresh: overlapping calls', () => {
expect(spend.loading).toBe(false)
})
})
describe('useSpendStore.refresh: breakdown depends on the ranking', () => {
it('keeps the previous breakdown when the ranking fails and the breakdown needs it', async () => {
const spend = useSpendStore()
spend.by = 'model'
spend.breakdown = [{ scope: 'model:old', points: [1, 2] }]
mockedAdminFetch.mockImplementation((async (path: string) => {
if (path.startsWith('/admin/api/usage/models')) throw new AdminApiError('boom', 500)
if (path.startsWith('/admin/api/usage/series')) return seriesFor(['total'], 0)
return { kind: 'group', window: 'day', span: 2, offset: 0, metrics: [], rows: [] }
}) as typeof adminFetch)
await spend.refresh()
expect(spend.rankingError).not.toBe('')
expect(spend.breakdown).toEqual([{ scope: 'model:old', points: [1, 2] }])
})
it('still builds a group breakdown when the ranking fails', async () => {
const spend = useSpendStore()
spend.by = 'group'
mockedAdminFetch.mockImplementation((async (path: string) => {
if (path.startsWith('/admin/api/usage/models')) throw new AdminApiError('boom', 500)
if (path.startsWith('/admin/api/usage/series')) return seriesFor(['total', 'group:a'], 5)
return { kind: 'group', window: 'day', span: 2, offset: 0, metrics: [], rows: [{ id: 'a' }] }
}) as typeof adminFetch)
await spend.refresh()
expect(spend.breakdown.map((s) => s.scope)).toContain('group:a')
})
})
+14 -5
View File
@@ -292,7 +292,7 @@ export const useSpendStore = defineStore('spend', {
this.loading = true
try {
await Promise.all([
this.fetchModelRanking().then(() => this.fetchBreakdown()),
this.fetchModelRanking().then((applied) => (applied || !this.breakdownNeedsRanking() ? this.fetchBreakdown() : undefined)),
this.fetchPricingHealthRanking(),
this.fetchBurndown(),
this.fetchDrilldown(),
@@ -301,23 +301,32 @@ export const useSpendStore = defineStore('spend', {
if (requestId === this.refreshReqId) this.loading = false
}
},
async fetchModelRanking(): Promise<void> {
/** breakdownNeedsRanking is true when the current breakdown is built from the model ranking: model and provider breakdowns, and any provider scope. Group and single group/user scopes do not read it. */
breakdownNeedsRanking(): boolean {
const filters = useFiltersStore()
if (filters.scope === 'all') return this.by !== 'group'
return !(filters.scope.startsWith('group:') || filters.scope.startsWith('user:'))
},
/** Resolves true only when this call's ranking was applied: a failed or superseded fetch resolves false, so refresh() does not build a breakdown from a stale ranking. */
async fetchModelRanking(): Promise<boolean> {
const filters = useFiltersStore()
const requestId = ++this.rankingReqId
try {
const res = await adminFetch<AdminUsageModelsResponse>(
`/admin/api/usage/models?metric=${this.metric}&window=${filters.window}&span=${filters.span}&limit=${MODEL_RANKING_LIMIT}&detail=1`,
)
if (requestId !== this.rankingReqId) return
if (requestId !== this.rankingReqId) return false
this.modelRanking = res.models
this.rankingError = ''
return true
} catch (err) {
if (requestId !== this.rankingReqId) return
if (isAuthRejection(err)) return
if (requestId !== this.rankingReqId) return false
if (isAuthRejection(err)) return false
// Own field, never folded into breakdownError — see this store's
// own doc comment on rankingError (verify-ui-states-3.md
// pre-existing fix).
this.rankingError = messageOf(err)
return false
}
},
/** fetchPricingHealthRanking is pricingHealthRanking's own fetch — always metric=req, independent of `this.metric` (see that field's own doc comment, P3 item 21). Runs in parallel with fetchModelRanking in refresh(), not chained after it: neither depends on the other's result. */