diff --git a/webui/src/lib/chart-labels.spec.ts b/webui/src/lib/chart-labels.spec.ts new file mode 100644 index 0000000..55b59c8 --- /dev/null +++ b/webui/src/lib/chart-labels.spec.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' + +import { thinLabels } from './chart-labels' + +const nums = (n: number) => Array.from({ length: n }, (_, i) => String(i)) + +describe('thinLabels', () => { + it('keeps every label when within max', () => { + expect(thinLabels(nums(6))).toEqual(nums(6)) + }) + + it('keeps every Nth label and blanks the rest', () => { + // 10 labels, max 6 -> N = 2 + expect(thinLabels(nums(10))).toEqual(['0', '', '2', '', '4', '', '6', '', '8', '9']) + }) + + it('always keeps the last label', () => { + const out = thinLabels(nums(25), 6) + expect(out.at(-1)).toBe('24') + expect(out).toHaveLength(25) + }) + + it('keeps the output length and handles empty input', () => { + expect(thinLabels([])).toEqual([]) + expect(thinLabels(['a'])).toEqual(['a']) + }) +}) diff --git a/webui/src/lib/chart-labels.ts b/webui/src/lib/chart-labels.ts new file mode 100644 index 0000000..764c833 --- /dev/null +++ b/webui/src/lib/chart-labels.ts @@ -0,0 +1,6 @@ +/** thinLabels blanks every label except every Nth (N = ceil(len / max)), always keeping the last, so long axes stay legible. */ +export function thinLabels(labels: string[], max = 6): string[] { + const step = Math.max(1, Math.ceil(labels.length / Math.max(1, max))) + const last = labels.length - 1 + return labels.map((label, i) => (i % step === 0 || i === last ? label : '')) +} diff --git a/webui/src/lib/range.ts b/webui/src/lib/range.ts index c7b2a3c..22f77c4 100644 --- a/webui/src/lib/range.ts +++ b/webui/src/lib/range.ts @@ -78,6 +78,7 @@ export function comparison(range: RangeKey): ComparisonResult { /** Spans from which GET /usage/models?detail=1 answers 400 "range too large" (observed on the live API: 48h and 30d fail, 24h and 14d pass). */ const DETAIL_REJECTED_FROM_SPAN: Partial> = { hour: 48, day: 30 } +/** Pre-flight optimisation only (avoids a failed request); the retry-on-400 in stores/spend.ts fetchModelsRanking is the real guard for any range the backend rejects. */ /** modelDetailSupported is false for ranges where asking for per-model detail is known to fail, so callers skip the doomed request. */ export function modelDetailSupported(window: HistoryWindow, span: number): boolean { const limit = DETAIL_REJECTED_FROM_SPAN[window] diff --git a/webui/src/lib/usage-csv.spec.ts b/webui/src/lib/usage-csv.spec.ts index 0ed90c3..715ff2d 100644 --- a/webui/src/lib/usage-csv.spec.ts +++ b/webui/src/lib/usage-csv.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { usageCsv } from './usage-csv' +import { breakdownCsv, usageCsv } from './usage-csv' import type { AdminUsageEntryView } from '@/types/api' function testEntry(overrides: Partial = {}): AdminUsageEntryView { @@ -93,3 +93,14 @@ describe('usageCsv', () => { // modelRankingCsv/modelDetailCsv (and their own describe blocks here) // were removed with the functions themselves (P3 item 25, dead code) — // see usage-csv.ts's own doc comment. + +describe('breakdownCsv', () => { + it('exports id, selected metric and share', () => { + const csv = breakdownCsv('user', 'req', [{ id: 'alice', value: 9, share: 0.75 }, { id: 'bob', value: 3, share: null }]) + expect(csv.trim().split(/\r?\n/)).toEqual(['user,req,share', 'alice,9,0.75', 'bob,3,']) + }) + + it('labels the cost column with its unit', () => { + expect(breakdownCsv('group', 'cost', []).split(/\r?\n/)[0]).toBe('group,cost (micro-USD),share') + }) +}) diff --git a/webui/src/lib/usage-csv.ts b/webui/src/lib/usage-csv.ts index e084645..37ed98a 100644 --- a/webui/src/lib/usage-csv.ts +++ b/webui/src/lib/usage-csv.ts @@ -125,3 +125,15 @@ export function usageCsv( // redesigned shell — grep confirms only this file and its own now-deleted // spec section ever referenced them. The redesigned Models page // (ModelCatalogTable.vue) has no CSV export of its own. + +export interface BreakdownCsvRow { + id: string + value: number + share: number | null +} + +/** breakdownCsv exports exactly what a Usage breakdown table shows: id, the range-selected metric (raw; cost stays micro-USD) and its share. */ +export function breakdownCsv(idHeader: string, metric: string, rows: BreakdownCsvRow[]): string { + const metricHeader = metric === 'cost' ? 'cost (micro-USD)' : metric + return toCsv([idHeader, metricHeader, 'share'], rows.map((r) => [r.id, r.value, r.share === null ? '' : r.share])) +} diff --git a/webui/src/pages/UsagePage.vue b/webui/src/pages/UsagePage.vue index 0c50202..c3e6009 100644 --- a/webui/src/pages/UsagePage.vue +++ b/webui/src/pages/UsagePage.vue @@ -6,7 +6,7 @@ import { useEntityLinks } from '@/composables/useEntityLinks' import { useNow } from '@/composables/useNow' import { budgetLineVisible, cumulative, runOutDate } from '@/lib/burndown' import { cacheSavingsStatus } from '@/lib/cache-savings' -import { toCsv } from '@/lib/csv' +import { thinLabels } from '@/lib/chart-labels' import { costAvoidedMicros, freeRows, pickReferenceModel } from '@/lib/cost-avoided' import { downloadText } from '@/lib/download' import type { DownloadOutcome } from '@/lib/download' @@ -22,7 +22,7 @@ import { deltaOf, sumPoints } from '@/lib/overview-metrics' import type { ChartLine } from '@/lib/overview-metrics' import { parseScope, scopeBudgetLimits, scopeId, scopeMtdMicros } from '@/lib/scope' import { seriesToStacked } from '@/lib/series' -import { usageCsv } from '@/lib/usage-csv' +import { breakdownCsv } from '@/lib/usage-csv' import { wbColumns } from '@/lib/wb-columns' import { useCatalogStore } from '@/stores/catalog' import { useDashboardStore } from '@/stores/dashboard' @@ -32,6 +32,7 @@ import { isSpendMetric, SPEND_METRIC_LABEL, SPEND_METRICS, useSpendStore } from import { USERS_RANGE_TOO_LARGE, useUsageUsersStore } from '@/stores/usage-users' import type { HistoryMetric } from '@/types/api' import ModelName from '@/widgets/ModelName.vue' +import ShareCell from '@/widgets/ShareCell.vue' import StateView from '@/widgets/StateView.vue' import type { ViewState } from '@/widgets/StateView.vue' import WbTable from '@/widgets/WbTable.vue' @@ -163,6 +164,8 @@ interface BreakdownRow { name: string value: number share: number | null + /** Set for a zero-valued model row with detail: what to show instead of a zero cost. */ + zeroText: string | null } const columns = computed(() => @@ -173,17 +176,22 @@ const columns = computed(() => ]), ) -const sourceRows = computed<{ id: string; value: number }[]>(() => { - if (by.value === 'model') return spend.modelRanking.map((m) => ({ id: m.id, value: m.value })) +const sourceRows = computed<{ id: string; value: number; free?: boolean }[]>(() => { + if (by.value === 'model') return spend.modelRanking.map((m) => ({ id: m.id, value: m.value, free: m.free })) if (by.value === 'group') return spend.drilldownRows.map((r) => ({ id: r.id, value: r.values[metric.value] ?? 0 })) return users.rows }) +function zeroText(r: { value: number; free?: boolean }): string | null { + if (by.value !== 'model' || !spend.detailAvailable || r.value !== 0) return null + return r.free && metric.value === 'cost' ? 'free' : '—' +} + const tableRows = computed(() => { const rows = sourceRows.value.filter((r) => r.value > 0 || by.value === 'model').sort((a, b) => b.value - a.value) const sum = rows.reduce((acc, r) => acc + r.value, 0) const total = filters.scope === 'all' && totalInRange.value > 0 ? totalInRange.value : sum - return rows.map((r) => ({ id: r.id, name: r.id, value: r.value, share: total > 0 ? Math.min(1, r.value / total) : null })) + return rows.map((r) => ({ id: r.id, name: r.id, value: r.value, share: total > 0 ? Math.min(1, r.value / total) : null, zeroText: zeroText(r) })) }) const tablePage = ref(1) @@ -221,7 +229,7 @@ const limits = computed(() => scopeBudgetLimits(filters.scope, dashboard.overvie const projected = computed(() => projectMonthEnd(mtdMicros.value, monthProgress(now.value))) const room = computed(() => headroom(projected.value, limits.value?.costPerMonthUSD)) -const burnLabels = computed(() => spend.burndownBuckets.map((b) => formatBucketLabel(b, 'day'))) +const burnLabels = computed(() => thinLabels(spend.burndownBuckets.map((b) => formatBucketLabel(b, 'day')))) const burnSpent = computed(() => cumulative(spend.burndownPoints)) const burnTotal = computed(() => burnSpent.value.at(-1) ?? 0) const burnLines = computed(() => { @@ -275,7 +283,7 @@ const healthColumns = computed(() => { key: 'id', header: 'Model', kind: 'text', sortable: false }, { key: 'priceSource', header: 'Source', kind: 'status', sortable: false }, { key: 'inputPerMTokUsd', header: 'Price in / out per MTok', kind: 'text', sortable: false }, - ...(spend.detailAvailable + ...(spend.pricingDetailAvailable ? [ { key: 'requests', header: 'Requests', kind: 'number' as const, sortable: false }, { key: 'costMicroUsd', header: 'Cost', kind: 'number' as const, sortable: false }, @@ -311,14 +319,8 @@ const feedback = ref(null) const FEEDBACK_LABEL: Record = { downloaded: 'Downloaded', copied: 'Copied', selected: 'Selected', failed: 'Export failed' } let feedbackTimer: ReturnType | undefined -function groupMemberCount(id: string): string { - return String((dashboard.usage?.users ?? []).filter((u) => (u.groups ?? (u.groupName === undefined ? [] : [u.groupName])).includes(id)).length) -} - function buildCsv(): string { - if (by.value === 'group') return usageCsv(dashboard.usage?.groups ?? [], 'groups', (e) => groupMemberCount(e.id), now.value) - if (by.value === 'user') return usageCsv(dashboard.usage?.users ?? [], 'users', (e) => (e.groups ?? (e.groupName === undefined ? [] : [e.groupName])).join(', '), now.value) - return toCsv(['model', metric.value, 'share'], tableRows.value.map((r) => [r.id, r.value, r.share ?? ''])) + return breakdownCsv(by.value, metric.value, tableRows.value) } async function exportCsv(): Promise { @@ -428,7 +430,11 @@ const money = (micros: number | null): string | null => (micros === null ? null - + +
{{ tableRows.length.toLocaleString('en-US') }} rows @@ -506,7 +512,7 @@ const money = (micros: number | null): string | null => (micros === null ? null -

{{ DETAIL_NOTICE }}

+

{{ DETAIL_NOTICE }}

(micros === null ? null - +
{{ healthRows.length.toLocaleString('en-US') }} models diff --git a/webui/src/stores/spend.spec.ts b/webui/src/stores/spend.spec.ts index af60288..9adfd89 100644 --- a/webui/src/stores/spend.spec.ts +++ b/webui/src/stores/spend.spec.ts @@ -752,6 +752,33 @@ describe('useSpendStore detail fallback', () => { expect(spend.rankingError).toBe('') }) + it('falls back on a 400 for a range not on the known-rejected list (day/14)', async () => { + const urls: string[] = [] + mockedAdminFetch.mockImplementation((async (path: string) => { + urls.push(path) + if (path.includes('detail=1')) throw tooLarge() + return { ...rankingWith(['a/one']), detail: false, models: [{ id: 'a/one', value: 5 }] } + }) as typeof adminFetch) + useFiltersStore().setFilters({ range: '14d' }) + const spend = useSpendStore() + await spend.fetchModelRanking() + expect(urls).toHaveLength(2) + expect(spend.detailAvailable).toBe(false) + expect(spend.rankingError).toBe('') + }) + + it('keeps the two ranking flags independent', async () => { + mockedAdminFetch.mockImplementation((async (path: string) => { + if (path.includes('metric=req') && path.includes('detail=1')) throw tooLarge() + return { ...rankingWith(['a/one']), models: [{ id: 'a/one', value: 5 }] } + }) as typeof adminFetch) + const spend = useSpendStore() + await spend.fetchModelRanking() + await spend.fetchPricingHealthRanking() + expect(spend.pricingDetailAvailable).toBe(false) + expect(spend.detailAvailable).toBe(true) + }) + it('does the same for the pricing-health ranking', async () => { mockedAdminFetch.mockImplementation((async (path: string) => { if (path.includes('detail=1')) throw tooLarge() @@ -761,7 +788,7 @@ describe('useSpendStore detail fallback', () => { await spend.fetchPricingHealthRanking() expect(spend.pricingHealthRanking).toHaveLength(1) expect(spend.pricingHealthError).toBe('') - expect(spend.detailAvailable).toBe(false) + expect(spend.pricingDetailAvailable).toBe(false) }) it('keeps surfacing non-400 failures', async () => { diff --git a/webui/src/stores/spend.ts b/webui/src/stores/spend.ts index 5a317db..0092eef 100644 --- a/webui/src/stores/spend.ts +++ b/webui/src/stores/spend.ts @@ -130,8 +130,10 @@ export const useSpendStore = defineStore('spend', { * longer discards a row specifically BECAUSE it is unpriced. */ pricingHealthRanking: [] as AdminUsageModelsResponse['models'], - /** False when the server refused `detail=1` for this range (400 range too large) and the rankings fell back to value-only rows, so per-model tokens, cost and free flags are absent. */ + /** False when the server refused `detail=1` for this range (400 range too large) and the model ranking fell back to value-only rows, so per-model tokens, cost and free flags are absent. */ detailAvailable: true, + /** Same as detailAvailable, for the pricing-health ranking. */ + pricingDetailAvailable: true, // --- burn-down (BurnDownChart) --- burndownBuckets: [] as string[], @@ -348,7 +350,7 @@ export const useSpendStore = defineStore('spend', { const { res, detail } = await fetchModelsRanking('req', filters.window, filters.span) if (requestId !== this.pricingHealthReqId) return this.pricingHealthRanking = res.models - this.detailAvailable = detail + this.pricingDetailAvailable = detail this.pricingHealthError = '' this.pricingHealthLoaded = true } catch (err) {