mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
feat(webui): make the dashboard responsive and add loading and empty states
Every tab row scrolls sideways instead of being clipped by its card. On phones this hid tabs, such as the Config change helper's last forms at 360-390px. The login button has a larger touch target, and long names are truncated with a tooltip. Loading and empty states: - Skeletons show only while a selection has no data yet, never over data already on screen during a refresh. - Empty states name the next step to take. - Error states offer a Retry button that shows progress, and each card keeps its own error. - Toasts confirm copies and key generation, and report background failures once per streak through polite and assertive live regions. Other changes: - The access matrix switches between Models, MCP servers and Agents, and says "none configured" only once its data has loaded. - Home ranks the top 5 users by cost, requests or tokens. It requests only the needed metrics and warns before a range exceeds the server's key cap. - MCP and agent deep links accept a bare target name. admin_assets_gen.go is regenerated. Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
This commit is contained in:
@@ -1,6 +1,14 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { buildAccessMatrix, providerAccessCell, targetAccessCell } from './access-matrix'
|
||||
import {
|
||||
buildAccessMatrix,
|
||||
MATRIX_KIND_LABEL,
|
||||
MATRIX_KINDS,
|
||||
matrixColumnsState,
|
||||
parseMatrixKind,
|
||||
providerAccessCell,
|
||||
targetAccessCell,
|
||||
} from './access-matrix'
|
||||
import type { AdminConsumerGroup, AdminTargetView } from '@/types/api'
|
||||
|
||||
function group(overrides: Partial<AdminConsumerGroup> = {}): AdminConsumerGroup {
|
||||
@@ -99,3 +107,58 @@ describe('buildAccessMatrix', () => {
|
||||
expect(buildAccessMatrix([], ['anthropic'], [], [])).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('MATRIX_KINDS', () => {
|
||||
it('orders the three kinds models, mcp, agents', () => {
|
||||
expect(MATRIX_KINDS).toEqual(['models', 'mcp', 'agents'])
|
||||
})
|
||||
|
||||
it('labels every kind', () => {
|
||||
expect(MATRIX_KIND_LABEL).toEqual({ models: 'Models', mcp: 'MCP servers', agents: 'Agents' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseMatrixKind', () => {
|
||||
it('parses each valid kind', () => {
|
||||
expect(parseMatrixKind('models')).toBe('models')
|
||||
expect(parseMatrixKind('mcp')).toBe('mcp')
|
||||
expect(parseMatrixKind('agents')).toBe('agents')
|
||||
})
|
||||
|
||||
it('falls back to models for an unknown value', () => {
|
||||
expect(parseMatrixKind('bogus')).toBe('models')
|
||||
})
|
||||
|
||||
it('falls back to models when undefined', () => {
|
||||
expect(parseMatrixKind(undefined)).toBe('models')
|
||||
})
|
||||
})
|
||||
|
||||
describe('matrixColumnsState', () => {
|
||||
it('is "loading" when the source has not loaded yet and there is no dashboard error', () => {
|
||||
expect(matrixColumnsState(false, 0, '')).toBe('loading')
|
||||
})
|
||||
|
||||
it('is "error" when the source has not loaded and dashboard.error is set', () => {
|
||||
expect(matrixColumnsState(false, 0, 'overview: fetch failed')).toBe('error')
|
||||
})
|
||||
|
||||
// Bug this helper fixes: a not-yet-loaded source maps to 0 columns via
|
||||
// `?? []`, indistinguishable from a genuinely empty, loaded source by
|
||||
// column count alone — so columnCount must never override sourceLoaded.
|
||||
it('is "loading", not "empty", when the source has not loaded even though columnCount is 0', () => {
|
||||
expect(matrixColumnsState(false, 0, '')).not.toBe('empty')
|
||||
})
|
||||
|
||||
it('is "empty" when the source has loaded with zero columns', () => {
|
||||
expect(matrixColumnsState(true, 0, '')).toBe('empty')
|
||||
})
|
||||
|
||||
it('is "empty" when the source has loaded with zero columns even if a stale dashboard.error lingers', () => {
|
||||
expect(matrixColumnsState(true, 0, 'usage: fetch failed')).toBe('empty')
|
||||
})
|
||||
|
||||
it('is "ready" when the source has loaded with at least one column', () => {
|
||||
expect(matrixColumnsState(true, 3, '')).toBe('ready')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -63,6 +63,35 @@ export function targetAccessCell(group: AdminConsumerGroup, target: Pick<AdminTa
|
||||
return { allowed: target.access.includes(group.name) }
|
||||
}
|
||||
|
||||
/**
|
||||
* MatrixKind is AccessMatrix.vue's own view switch: which one column
|
||||
* group the table currently renders (P4 three-view split — the old
|
||||
* matrix mixed providers, MCP servers, and agents in one wide table,
|
||||
* which was hard to scan). `'models'` is the default.
|
||||
*/
|
||||
export type MatrixKind = 'models' | 'mcp' | 'agents'
|
||||
|
||||
/** MATRIX_KINDS is the ordered list AccessMatrix.vue's Tabs render from — this array's order IS the tab order. */
|
||||
export const MATRIX_KINDS: MatrixKind[] = ['models', 'mcp', 'agents']
|
||||
|
||||
/** MATRIX_KIND_LABEL is each kind's tab/column-group label. */
|
||||
export const MATRIX_KIND_LABEL: Record<MatrixKind, string> = {
|
||||
models: 'Models',
|
||||
mcp: 'MCP servers',
|
||||
agents: 'Agents',
|
||||
}
|
||||
|
||||
/**
|
||||
* parseMatrixKind reads the `matrix` hash page param (ConsumersPage.vue,
|
||||
* mirroring its own `view` param's parsing) into a MatrixKind — unknown
|
||||
* or absent values (a stale/hand-edited link, or the clean default hash
|
||||
* with no `matrix` param at all) fall back to `'models'` rather than
|
||||
* throwing.
|
||||
*/
|
||||
export function parseMatrixKind(raw: string | undefined): MatrixKind {
|
||||
return (MATRIX_KINDS as readonly string[]).includes(raw ?? '') ? (raw as MatrixKind) : 'models'
|
||||
}
|
||||
|
||||
/** AccessMatrixRow is one group's full row: its own provider/MCP-server/agent cells, each keyed by that column's own name — AccessMatrix.vue iterates `providerNames`/`mcpServers`/`agents` (the caller's own column order) and looks up each cell by name rather than relying on object key iteration order. */
|
||||
export interface AccessMatrixRow {
|
||||
group: string
|
||||
@@ -92,3 +121,33 @@ export function buildAccessMatrix(
|
||||
agents: Object.fromEntries(agents.map((target) => [target.name, targetAccessCell(group, target)])),
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* MatrixColumnsState is what AccessMatrix.vue's CardContent renders in
|
||||
* place of a table for the CURRENTLY SELECTED kind's own columns —
|
||||
* distinct from the separate consumers.error/consumers.loading/
|
||||
* rows.length===0 branches ahead of it in the template, which are about
|
||||
* GROUPS (rows, stores/consumers.ts), a different store entirely.
|
||||
*/
|
||||
export type MatrixColumnsState = 'loading' | 'error' | 'empty' | 'ready'
|
||||
|
||||
/**
|
||||
* matrixColumnsState decides which of the four states above the current
|
||||
* kind's own column source is in. `sourceLoaded` must be whether the
|
||||
* RAW dashboard field is non-null (`dashboard.overview !== null` for
|
||||
* 'models', `dashboard.targets !== null` for 'mcp'/'agents') — NOT
|
||||
* whether the derived column list (which maps a null source to `[]`) is
|
||||
* empty, since those two are indistinguishable by column count alone.
|
||||
* Previously AccessMatrix.vue read `columns.length === 0` on its own to
|
||||
* decide whether to show "No providers configured." etc — true both
|
||||
* while the source had not loaded yet (or had just failed) AND once it
|
||||
* had genuinely loaded with zero columns, so a page still on its first
|
||||
* fetch, or whose fetch had just failed, showed "no MCP servers
|
||||
* configured" as a confirmed fact about the fleet rather than "still
|
||||
* loading" or the real error. `dashboardError` (dashboard.ts's own
|
||||
* `error` field) is read only in the 'error' state.
|
||||
*/
|
||||
export function matrixColumnsState(sourceLoaded: boolean, columnCount: number, dashboardError: string): MatrixColumnsState {
|
||||
if (!sourceLoaded) return dashboardError ? 'error' : 'loading'
|
||||
return columnCount === 0 ? 'empty' : 'ready'
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { loadState } from './load-state'
|
||||
|
||||
describe('loadState', () => {
|
||||
it('is "ready" when there is data, no error, not loading', () => {
|
||||
expect(loadState({ loading: false, hasData: true, error: '' })).toBe('ready')
|
||||
})
|
||||
|
||||
it('is "ready" when there is data even if loading is true (a background refresh in flight)', () => {
|
||||
expect(loadState({ loading: true, hasData: true, error: '' })).toBe('ready')
|
||||
})
|
||||
|
||||
// states-plan.md item 1: a background refresh failure must never blank
|
||||
// already-rendered data into an error state — that surfaces via a
|
||||
// toast instead (stores/toasts.ts), not by switching away from 'ready'.
|
||||
it('is "ready" when there is data even if a background refresh just failed (error set)', () => {
|
||||
expect(loadState({ loading: false, hasData: true, error: 'usage: fetch failed' })).toBe('ready')
|
||||
})
|
||||
|
||||
it('is "error" when there is no data and an error is set', () => {
|
||||
expect(loadState({ loading: false, hasData: false, error: 'overview: fetch failed' })).toBe('error')
|
||||
})
|
||||
|
||||
it('is "error" even while loading, when there is no data and an error is set (a retry already in flight)', () => {
|
||||
expect(loadState({ loading: true, hasData: false, error: 'overview: fetch failed' })).toBe('error')
|
||||
})
|
||||
|
||||
it('is "skeleton" when there is no data, no error, and loading is true', () => {
|
||||
expect(loadState({ loading: true, hasData: false, error: '' })).toBe('skeleton')
|
||||
})
|
||||
|
||||
it('is "empty" when there is no data, no error, and not loading', () => {
|
||||
expect(loadState({ loading: false, hasData: false, error: '' })).toBe('empty')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* LoadState is the four states any data-driven view in this panel
|
||||
* renders in place of its real content — the single vocabulary
|
||||
* EmptyState.vue/ErrorState.vue/the Skeleton* components all key off of,
|
||||
* so every page decides "skeleton vs error vs empty vs ready" the same
|
||||
* way instead of each growing its own ad-hoc v-if chain.
|
||||
*/
|
||||
export type LoadState = 'skeleton' | 'error' | 'empty' | 'ready'
|
||||
|
||||
/** LoadStateInput is loadState's own three signals — every store in this panel already exposes something that maps onto these (a `loading`/`lastUpdated` flag, a data field's null-ness or length, an `error` string). */
|
||||
export interface LoadStateInput {
|
||||
/** Whether a fetch for the CURRENT selection is in flight (or has never yet completed) — a background refresh of data already on screen does not count (see hasData's own precedence below). */
|
||||
loading: boolean
|
||||
/** Whether there is currently displayable data for the CURRENT selection — false right after a filter/selection change clears the previous selection's data, not just on a cold first load. */
|
||||
hasData: boolean
|
||||
/** The store's current error message, '' when there is none. */
|
||||
error: string
|
||||
}
|
||||
|
||||
/**
|
||||
* loadState decides which of the four LoadState values a view should
|
||||
* render, from the three signals above. Precedence, highest first:
|
||||
*
|
||||
* 1. 'ready' whenever `hasData` is true — even alongside a non-empty
|
||||
* `error` (a background poll just failed but the PREVIOUS successful
|
||||
* result is still on screen): states-plan.md item 1's own rule is
|
||||
* that a background refresh must never replace rendered data with a
|
||||
* skeleton, and a background failure must never blank it into an
|
||||
* error state either — that case surfaces via a toast instead
|
||||
* (stores/toasts.ts), not by this helper switching states.
|
||||
* 2. 'error' when there is no data and `error` is set — the first fetch
|
||||
* for this selection failed outright, nothing to show underneath it.
|
||||
* 3. 'skeleton' when there is no data, no error, and `loading` is true —
|
||||
* first load, or a filter/selection change that cleared the previous
|
||||
* selection's own data and kicked off a fresh fetch.
|
||||
* 4. 'empty' otherwise — not loading, no error, genuinely no data.
|
||||
*/
|
||||
export function loadState({ loading, hasData, error }: LoadStateInput): LoadState {
|
||||
if (hasData) return 'ready'
|
||||
if (error) return 'error'
|
||||
if (loading) return 'skeleton'
|
||||
return 'empty'
|
||||
}
|
||||
@@ -3,8 +3,8 @@ import { describe, expect, it } from 'vitest'
|
||||
|
||||
import CompactNumber from '@/components/CompactNumber.vue'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { composeTargetId, parseTargetCallerId, targetCallerColumns, targetColumns } from './target-columns'
|
||||
import type { AdminTargetHealthView, AdminTargetView, AdminTotalsResponse } from '@/types/api'
|
||||
import { composeTargetId, parseTargetCallerId, resolveTargetRef, targetCallerColumns, targetColumns } from './target-columns'
|
||||
import type { AdminTargetHealthView, AdminTargetsResponse, AdminTargetView, AdminTotalsResponse } from '@/types/api'
|
||||
|
||||
/**
|
||||
* Target health rendering (feat/target-health): mirrors usage-columns.
|
||||
@@ -276,3 +276,77 @@ describe('targetCallerColumns', () => {
|
||||
expect(isVNode(rendered) && rendered.props?.value).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
// --- resolveTargetRef (P2 item: a hand-typed #targets?target=demo-mcp
|
||||
// 400ed — parseTargetRef, stats_read.go, only accepts "mcp/{name}"/
|
||||
// "agent/{name}") ---
|
||||
|
||||
function namedTarget(name: string): AdminTargetView {
|
||||
return {
|
||||
name,
|
||||
url: 'https://example.com/mcp',
|
||||
counters: { requestsPerMinute: 0, requestsPerDay: 0, requestsPerMonth: 0 },
|
||||
health: { state: 'unknown', consecutiveFailures: 0 },
|
||||
}
|
||||
}
|
||||
|
||||
function targets(mcpNames: string[], agentNames: string[]): Pick<AdminTargetsResponse, 'mcpServers' | 'agents'> {
|
||||
return { mcpServers: mcpNames.map(namedTarget), agents: agentNames.map(namedTarget) }
|
||||
}
|
||||
|
||||
describe('resolveTargetRef', () => {
|
||||
it('passes an already-prefixed "mcp/{name}" ref through unchanged, without needing targets loaded', () => {
|
||||
expect(resolveTargetRef('mcp/fetch', null)).toEqual({ kind: 'ref', ref: 'mcp/fetch', name: 'fetch' })
|
||||
})
|
||||
|
||||
it('passes an already-prefixed "agent/{name}" ref through unchanged', () => {
|
||||
expect(resolveTargetRef('agent/agentkit', targets([], ['agentkit']))).toEqual({
|
||||
kind: 'ref',
|
||||
ref: 'agent/agentkit',
|
||||
name: 'agentkit',
|
||||
})
|
||||
})
|
||||
|
||||
it('round-trips a name that itself contains a slash, matching stats_read.go\'s Cut-on-first-slash', () => {
|
||||
expect(resolveTargetRef('mcp/team/fetch', null)).toEqual({ kind: 'ref', ref: 'mcp/team/fetch', name: 'team/fetch' })
|
||||
})
|
||||
|
||||
it('is "pending" for a bare name while dashboard.targets has not loaded yet (null)', () => {
|
||||
expect(resolveTargetRef('demo-mcp', null)).toEqual({ kind: 'pending' })
|
||||
})
|
||||
|
||||
it('resolves a bare name found only in mcpServers', () => {
|
||||
expect(resolveTargetRef('demo-mcp', targets(['demo-mcp'], []))).toEqual({
|
||||
kind: 'ref',
|
||||
ref: 'mcp/demo-mcp',
|
||||
name: 'demo-mcp',
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves a bare name found only in agents', () => {
|
||||
expect(resolveTargetRef('agentkit', targets([], ['agentkit']))).toEqual({
|
||||
kind: 'ref',
|
||||
ref: 'agent/agentkit',
|
||||
name: 'agentkit',
|
||||
})
|
||||
})
|
||||
|
||||
it('shows a notice for a bare name found in neither list (unknown)', () => {
|
||||
const result = resolveTargetRef('nope', targets(['demo-mcp'], ['agentkit']))
|
||||
expect(result.kind).toBe('notice')
|
||||
expect(result.kind === 'notice' && result.message).toContain('No MCP server or agent named "nope"')
|
||||
})
|
||||
|
||||
it('shows a notice for a bare name found in BOTH lists (ambiguous) rather than guessing', () => {
|
||||
const result = resolveTargetRef('shared', targets(['shared'], ['shared']))
|
||||
expect(result.kind).toBe('notice')
|
||||
expect(result.kind === 'notice' && result.message).toContain('matches both an MCP server and an agent')
|
||||
})
|
||||
|
||||
it('rejects an unknown prefix as a bare name, not a ref (e.g. "http/foo" is looked up, not passed through)', () => {
|
||||
expect(resolveTargetRef('http/foo', targets([], []))).toEqual({
|
||||
kind: 'notice',
|
||||
message: 'No MCP server or agent named "http/foo" is configured.',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,7 +4,7 @@ import { h } from 'vue'
|
||||
import CompactNumber from '@/components/CompactNumber.vue'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { formatElapsedAgo, formatLatencyMs } from '@/lib/format'
|
||||
import type { AdminTargetHealthView, AdminTargetView, AdminTotalsResponse } from '@/types/api'
|
||||
import type { AdminTargetHealthView, AdminTargetsResponse, AdminTargetView, AdminTotalsResponse } from '@/types/api'
|
||||
|
||||
/**
|
||||
* numericColumn builds one right-aligned, sortable request-counter
|
||||
@@ -210,6 +210,68 @@ export function composeTargetId(kind: TargetKind, name: string): string {
|
||||
return `${kind}/${name}`
|
||||
}
|
||||
|
||||
/**
|
||||
* TargetRefResolution is TargetsPage.vue's own read of the `target` hash
|
||||
* param, normalized for GET /admin/api/usage/totals?kind=targetcaller&
|
||||
* target= (admin.go's parseTargetRef: only "mcp/{name}" or "agent/{name}"
|
||||
* is valid — a bare name 400s):
|
||||
* - 'ref': `ref` is a valid "mcp/{name}"/"agent/{name}" composite,
|
||||
* safe to pass straight to TargetCallers.vue; `name` is the bare
|
||||
* name alone, for a nicer fallback label than the full composite.
|
||||
* - 'pending': `raw` was a bare name and dashboard.targets has not
|
||||
* loaded yet (still null) — there is nothing to resolve against
|
||||
* yet, so the caller shows neither a table nor a notice.
|
||||
* - 'notice': `raw` could not be resolved to exactly one target —
|
||||
* either no configured MCP server or agent has that name, or (rarer)
|
||||
* BOTH an MCP server and an agent share it, so guessing either one
|
||||
* would risk showing the wrong caller breakdown. `message` is ready
|
||||
* to render as-is.
|
||||
*/
|
||||
export type TargetRefResolution =
|
||||
| { kind: 'ref'; ref: string; name: string }
|
||||
| { kind: 'pending' }
|
||||
| { kind: 'notice'; message: string }
|
||||
|
||||
/** parsePrefixedTargetRef reads a "mcp/{name}"/"agent/{name}" composite — mirrors stats_read.go's own parseTargetRef (Cut on the FIRST "/", so a name containing further slashes still round-trips) — or null for anything else (a bare name, an unknown prefix, or an empty name). */
|
||||
function parsePrefixedTargetRef(raw: string): { kind: TargetKind; name: string } | null {
|
||||
const cut = raw.indexOf('/')
|
||||
if (cut === -1) return null
|
||||
const prefix = raw.slice(0, cut)
|
||||
const name = raw.slice(cut + 1)
|
||||
if (name === '' || (prefix !== 'mcp' && prefix !== 'agent')) return null
|
||||
return { kind: prefix, name }
|
||||
}
|
||||
|
||||
/**
|
||||
* resolveTargetRef normalizes TargetsPage.vue's `target` hash param
|
||||
* (P2 item: a hand-typed `#targets?target=demo-mcp` 400ed — the backend
|
||||
* only accepts the prefixed composite form, never a bare name) into a
|
||||
* TargetRefResolution: an already-prefixed `raw` ("mcp/x"/"agent/x")
|
||||
* passes through unchanged (server-side existence is not checked here —
|
||||
* an unknown target under a valid prefix just returns zero rows,
|
||||
* TargetCallers.vue's own existing "no callers recorded" empty state,
|
||||
* not an error); a bare name is looked up in `targets.mcpServers` first,
|
||||
* then `targets.agents` — resolved only when it matches EXACTLY ONE of
|
||||
* the two lists, otherwise 'notice' ('unknown' for neither, 'ambiguous'
|
||||
* for both, since silently guessing which kind the reader meant could
|
||||
* show the wrong target's callers).
|
||||
*/
|
||||
export function resolveTargetRef(raw: string, targets: Pick<AdminTargetsResponse, 'mcpServers' | 'agents'> | null): TargetRefResolution {
|
||||
const prefixed = parsePrefixedTargetRef(raw)
|
||||
if (prefixed) return { kind: 'ref', ref: composeTargetId(prefixed.kind, prefixed.name), name: prefixed.name }
|
||||
|
||||
if (targets === null) return { kind: 'pending' }
|
||||
|
||||
const inMcp = targets.mcpServers.some((t) => t.name === raw)
|
||||
const inAgents = targets.agents.some((t) => t.name === raw)
|
||||
if (inMcp && inAgents) {
|
||||
return { kind: 'notice', message: `"${raw}" matches both an MCP server and an agent — use "mcp/${raw}" or "agent/${raw}" to pick one.` }
|
||||
}
|
||||
if (inMcp) return { kind: 'ref', ref: composeTargetId('mcp', raw), name: raw }
|
||||
if (inAgents) return { kind: 'ref', ref: composeTargetId('agent', raw), name: raw }
|
||||
return { kind: 'notice', message: `No MCP server or agent named "${raw}" is configured.` }
|
||||
}
|
||||
|
||||
/**
|
||||
* ParsedTargetCallerId is one targetcaller row's `id`
|
||||
* ("mcp/fetch/alice" — AdminTotalsResponse's own doc comment) split into
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
ADMIN_MAX_KEYS_PER_REQUEST,
|
||||
DEFAULT_TOP_USERS_MODE,
|
||||
parseTopUsersMode,
|
||||
rankTopUsers,
|
||||
TOP_USERS_METRICS_BY_MODE,
|
||||
TOP_USERS_MODE_LABEL,
|
||||
TOP_USERS_MODES,
|
||||
topUsersCapCheckResult,
|
||||
topUsersCapExceeded,
|
||||
topUsersTotalsUrl,
|
||||
} from './top-users'
|
||||
import type { AdminTotalsResponse } from '@/types/api'
|
||||
|
||||
function row(id: string, values: Partial<Record<'req' | 'tokin' | 'tokout' | 'cost', number>>): AdminTotalsResponse['rows'][number] {
|
||||
return { id, values: { req: 0, tokin: 0, tokout: 0, cost: 0, ...values } }
|
||||
}
|
||||
|
||||
describe('TOP_USERS_METRICS_BY_MODE', () => {
|
||||
it('requests only the metric(s) each mode ranks by', () => {
|
||||
expect(TOP_USERS_METRICS_BY_MODE.cost).toEqual(['cost'])
|
||||
expect(TOP_USERS_METRICS_BY_MODE.req).toEqual(['req'])
|
||||
expect(TOP_USERS_METRICS_BY_MODE.tokens).toEqual(['tokin', 'tokout'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('topUsersTotalsUrl', () => {
|
||||
it('builds the cost-mode query string with metrics=cost', () => {
|
||||
expect(topUsersTotalsUrl('day', 7, 'cost')).toBe('/admin/api/usage/totals?kind=user&window=day&span=7&offset=0&metrics=cost&limit=1000')
|
||||
})
|
||||
|
||||
it('builds the req-mode query string with metrics=req', () => {
|
||||
expect(topUsersTotalsUrl('hour', 24, 'req')).toBe('/admin/api/usage/totals?kind=user&window=hour&span=24&offset=0&metrics=req&limit=1000')
|
||||
})
|
||||
|
||||
it('builds the tokens-mode query string with metrics=tokin,tokout', () => {
|
||||
expect(topUsersTotalsUrl('month', 12, 'tokens')).toBe(
|
||||
'/admin/api/usage/totals?kind=user&window=month&span=12&offset=0&metrics=tokin%2Ctokout&limit=1000',
|
||||
)
|
||||
})
|
||||
|
||||
it('honours an explicit limit override', () => {
|
||||
expect(topUsersTotalsUrl('day', 7, 'cost', 50)).toBe('/admin/api/usage/totals?kind=user&window=day&span=7&offset=0&metrics=cost&limit=50')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ADMIN_MAX_KEYS_PER_REQUEST', () => {
|
||||
it('mirrors the server constant (stats_read.go: adminMaxKeysPerRequest)', () => {
|
||||
expect(ADMIN_MAX_KEYS_PER_REQUEST).toBe(64000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('topUsersCapExceeded', () => {
|
||||
it('mirrors stats_read.go:573 exactly: len(ids)*len(metrics)*span > cap', () => {
|
||||
// 1000 users * 1 metric * 48h span = 48000, under the 64000 cap.
|
||||
expect(topUsersCapExceeded(1000, 1, 48)).toBe(false)
|
||||
// 1334 users * 1 metric * 48h span = 64032, over the cap.
|
||||
expect(topUsersCapExceeded(1334, 1, 48)).toBe(true)
|
||||
})
|
||||
|
||||
it('is false at exactly the cap (strict >, not >=, matching the server)', () => {
|
||||
expect(topUsersCapExceeded(64000, 1, 1)).toBe(false)
|
||||
expect(topUsersCapExceeded(64001, 1, 1)).toBe(true)
|
||||
})
|
||||
|
||||
it('scales with metrics count — tokens mode (2 metrics) trips sooner than cost/req (1 metric)', () => {
|
||||
expect(topUsersCapExceeded(700, 1, 48)).toBe(false)
|
||||
expect(topUsersCapExceeded(700, 2, 48)).toBe(true)
|
||||
})
|
||||
|
||||
it('is false for zero users, metrics, or span', () => {
|
||||
expect(topUsersCapExceeded(0, 1, 48)).toBe(false)
|
||||
expect(topUsersCapExceeded(500, 0, 48)).toBe(false)
|
||||
expect(topUsersCapExceeded(500, 1, 0)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
// verify-ui-states-2.md #4: HomePage.vue's own configuredUserCount is now
|
||||
// an EXACT count (dashboard.usage.users.length), but is null before that
|
||||
// store has ever loaded — topUsersCapCheckResult is the wrapper that
|
||||
// decides what to do with that null case (skip the predictive check
|
||||
// entirely, rather than treating null as 0 or guessing).
|
||||
describe('topUsersCapCheckResult', () => {
|
||||
it('skips the predictive check (returns false) when configuredUserCount is null', () => {
|
||||
// Would trip the cap if it were treated as any real number here.
|
||||
expect(topUsersCapCheckResult(null, 2, 48)).toBe(false)
|
||||
})
|
||||
|
||||
it('delegates to topUsersCapExceeded once configuredUserCount is a real number', () => {
|
||||
expect(topUsersCapCheckResult(1334, 1, 48)).toBe(true)
|
||||
expect(topUsersCapCheckResult(1000, 1, 48)).toBe(false)
|
||||
})
|
||||
|
||||
it('is false for a genuinely zero configured user count', () => {
|
||||
expect(topUsersCapCheckResult(0, 2, 48)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseTopUsersMode', () => {
|
||||
it('parses each valid mode', () => {
|
||||
expect(parseTopUsersMode('cost')).toBe('cost')
|
||||
expect(parseTopUsersMode('req')).toBe('req')
|
||||
expect(parseTopUsersMode('tokens')).toBe('tokens')
|
||||
})
|
||||
|
||||
it('falls back to cost for an unknown value', () => {
|
||||
expect(parseTopUsersMode('bogus')).toBe('cost')
|
||||
})
|
||||
|
||||
it('falls back to cost when undefined', () => {
|
||||
expect(parseTopUsersMode(undefined)).toBe(DEFAULT_TOP_USERS_MODE)
|
||||
})
|
||||
})
|
||||
|
||||
describe('TOP_USERS_MODES / TOP_USERS_MODE_LABEL', () => {
|
||||
it('orders the three modes cost, req, tokens', () => {
|
||||
expect(TOP_USERS_MODES).toEqual(['cost', 'req', 'tokens'])
|
||||
})
|
||||
|
||||
it('labels every mode', () => {
|
||||
expect(TOP_USERS_MODE_LABEL).toEqual({ cost: 'Cost', req: 'Requests', tokens: 'Tokens' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('rankTopUsers', () => {
|
||||
it('ranks by cost descending', () => {
|
||||
const rows = [row('alice', { cost: 5 }), row('bob', { cost: 20 }), row('carl', { cost: 10 })]
|
||||
expect(rankTopUsers(rows, 'cost')).toEqual([
|
||||
{ id: 'bob', value: 20 },
|
||||
{ id: 'carl', value: 10 },
|
||||
{ id: 'alice', value: 5 },
|
||||
])
|
||||
})
|
||||
|
||||
it('ranks by requests descending', () => {
|
||||
const rows = [row('alice', { req: 5, cost: 999 }), row('bob', { req: 20, cost: 1 })]
|
||||
expect(rankTopUsers(rows, 'req')).toEqual([
|
||||
{ id: 'bob', value: 20 },
|
||||
{ id: 'alice', value: 5 },
|
||||
])
|
||||
})
|
||||
|
||||
it('ranks by tokens as tokin+tokout summed, descending', () => {
|
||||
const rows = [row('alice', { tokin: 100, tokout: 50 }), row('bob', { tokin: 10, tokout: 10 })]
|
||||
expect(rankTopUsers(rows, 'tokens')).toEqual([
|
||||
{ id: 'alice', value: 150 },
|
||||
{ id: 'bob', value: 20 },
|
||||
])
|
||||
})
|
||||
|
||||
it('breaks ties by id ascending', () => {
|
||||
const rows = [row('zed', { cost: 10 }), row('amy', { cost: 10 })]
|
||||
expect(rankTopUsers(rows, 'cost')).toEqual([
|
||||
{ id: 'amy', value: 10 },
|
||||
{ id: 'zed', value: 10 },
|
||||
])
|
||||
})
|
||||
|
||||
it('excludes zero rows for the CURRENT mode only', () => {
|
||||
// bob has requests but $0 cost (free-model-only traffic): out of the
|
||||
// cost ranking, but present in the requests ranking.
|
||||
const rows = [row('alice', { cost: 5, req: 1 }), row('bob', { cost: 0, req: 9 })]
|
||||
expect(rankTopUsers(rows, 'cost')).toEqual([{ id: 'alice', value: 5 }])
|
||||
expect(rankTopUsers(rows, 'req')).toEqual([
|
||||
{ id: 'bob', value: 9 },
|
||||
{ id: 'alice', value: 1 },
|
||||
])
|
||||
})
|
||||
|
||||
it('truncates to the limit (default 5)', () => {
|
||||
const rows = Array.from({ length: 8 }, (_, i) => row(`user${i}`, { cost: 8 - i }))
|
||||
expect(rankTopUsers(rows, 'cost')).toHaveLength(5)
|
||||
expect(rankTopUsers(rows, 'cost')[0]).toEqual({ id: 'user0', value: 8 })
|
||||
})
|
||||
|
||||
it('honours a custom limit', () => {
|
||||
const rows = [row('a', { cost: 3 }), row('b', { cost: 2 }), row('c', { cost: 1 })]
|
||||
expect(rankTopUsers(rows, 'cost', 2)).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('returns an empty array when every row is zero for the mode', () => {
|
||||
const rows = [row('alice', { cost: 0 }), row('bob', { cost: 0 })]
|
||||
expect(rankTopUsers(rows, 'cost')).toEqual([])
|
||||
})
|
||||
|
||||
it('returns an empty array for no rows', () => {
|
||||
expect(rankTopUsers([], 'cost')).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,175 @@
|
||||
import type { AdminTotalsResponse, HistoryWindow } from '@/types/api'
|
||||
|
||||
/**
|
||||
* TOP_USERS_MODES is HomePage.vue's "top users" card Tabs switch (Cost |
|
||||
* Requests | Tokens) — the values match the `top` hash param verbatim
|
||||
* ('req'/'tokens'; 'cost' is the default and is never written to the
|
||||
* hash at all, mirroring lib/access-matrix.ts's MATRIX_KINDS/`matrix`
|
||||
* param convention), so no separate internal-vs-URL name mapping exists.
|
||||
*/
|
||||
export const TOP_USERS_MODES = ['cost', 'req', 'tokens'] as const
|
||||
|
||||
export type TopUsersMode = (typeof TOP_USERS_MODES)[number]
|
||||
|
||||
export const DEFAULT_TOP_USERS_MODE: TopUsersMode = 'cost'
|
||||
|
||||
/** TOP_USERS_MODE_LABEL is each mode's Tabs label and the source for the card's "Top 5 users by …" title. */
|
||||
export const TOP_USERS_MODE_LABEL: Record<TopUsersMode, string> = {
|
||||
cost: 'Cost',
|
||||
req: 'Requests',
|
||||
tokens: 'Tokens',
|
||||
}
|
||||
|
||||
/**
|
||||
* ADMIN_MAX_KEYS_PER_REQUEST mirrors the server's own adminMaxKeysPerRequest
|
||||
* (stats_read.go:28, `const adminMaxKeysPerRequest = 64000`) — GET
|
||||
* /admin/api/usage/totals?kind=user rejects with 400 the moment
|
||||
* `len(ids) * len(metrics) * span` exceeds this, where `ids` is EVERY
|
||||
* configured user (stats_read.go:566-576: built from `g.auth.snapshot()`'s
|
||||
* userSummaries, not filtered to users with recent traffic). `dashboard.
|
||||
* usage.users` (admin.go's own userSummaries, already polled every 5s) IS
|
||||
* an exact, free source for this count — HomePage.vue's own
|
||||
* configuredUserCount reads it directly (verify-ui-states-2.md #4; an
|
||||
* earlier revision of this comment wrongly claimed no such source
|
||||
* existed and used a per-group memberCount sum instead, which over-counts
|
||||
* a user who belongs to more than one group). topUsersCapExceeded below
|
||||
* re-implements that same inequality for topUsersCapCheckResult's
|
||||
* best-effort predictive check.
|
||||
*/
|
||||
export const ADMIN_MAX_KEYS_PER_REQUEST = 64000
|
||||
|
||||
/**
|
||||
* TOP_USERS_METRICS_BY_MODE (P1 fix, verify-ui-states.md #1) — each mode
|
||||
* requests ONLY the metric(s) it ranks by, not all four unconditionally: a
|
||||
* fetch this card used to always shape as `metrics=req,tokin,tokout,cost`
|
||||
* (4 metrics) now costs 1 metric (cost/req) or 2 (tokens, summed
|
||||
* client-side by rankTopUsers below) against the server's own
|
||||
* len(ids)*len(metrics)*span cap — up to 4x more configured users before a
|
||||
* fleet trips adminMaxKeysPerRequest on the coarsest (hour, span 48) global
|
||||
* range. This is the ONLY lever this card has over that cap: `ids` is
|
||||
* fixed by server-side config, and the `limit` query param (below) is
|
||||
* applied AFTER the cap check, over already-fetched rows (buildTotalsRows,
|
||||
* stats_read.go:453-480) — it does not, and cannot, reduce the read cost
|
||||
* the cap guards.
|
||||
*/
|
||||
export const TOP_USERS_METRICS_BY_MODE: Record<TopUsersMode, readonly string[]> = {
|
||||
cost: ['cost'],
|
||||
req: ['req'],
|
||||
tokens: ['tokin', 'tokout'],
|
||||
}
|
||||
|
||||
/**
|
||||
* parseTopUsersMode reads the `top` hash param into a TopUsersMode —
|
||||
* unknown or absent values fall back to 'cost' rather than throwing,
|
||||
* mirroring lib/access-matrix.ts's parseMatrixKind.
|
||||
*/
|
||||
export function parseTopUsersMode(raw: string | undefined): TopUsersMode {
|
||||
return (TOP_USERS_MODES as readonly string[]).includes(raw ?? '') ? (raw as TopUsersMode) : DEFAULT_TOP_USERS_MODE
|
||||
}
|
||||
|
||||
/**
|
||||
* TOP_USERS_FETCH_LIMIT (1000, the server's own adminTotalsMaxLimit,
|
||||
* stats_read.go) is headroom for CLIENT-SIDE re-ranking, not a cap-safety
|
||||
* lever (see TOP_USERS_METRICS_BY_MODE's own doc comment — `limit` is
|
||||
* applied after the cap check, over already-fetched rows). It matters only
|
||||
* for 'tokens' mode: the server sorts by metrics[0] ('tokin') descending
|
||||
* and truncates to `limit` BEFORE this card re-ranks by tokin+tokout
|
||||
* summed (rankTopUsers below) — a `limit` too small could truncate away a
|
||||
* user with a large tokout but a middling tokin before the client ever
|
||||
* gets a chance to re-rank them in. 1000 keeps that reordering effect
|
||||
* practically unreachable for any real fleet.
|
||||
*/
|
||||
export const TOP_USERS_FETCH_LIMIT = 1000
|
||||
|
||||
/** TOP_USERS_RANK_LIMIT is how many rows rankTopUsers keeps after ranking — the card's own "top 5". */
|
||||
export const TOP_USERS_RANK_LIMIT = 5
|
||||
|
||||
/**
|
||||
* topUsersTotalsUrl builds HomePage.vue's "top users" query string for one
|
||||
* mode: GET /admin/api/usage/totals?kind=user&window=<window>&span=<span>&
|
||||
* offset=0&metrics=<mode's own metrics>&limit=<limit>. Built directly (not
|
||||
* via lib/range.ts's totalsUrl) because totalsUrl's own `offset` convention
|
||||
* deliberately OMITS the param when 0 (server default, seriesUrl/totalsUrl's
|
||||
* shared doc comment, lib/range.spec.ts's own "omits offset when 0" test) —
|
||||
* this card's own fixed shape always writes `offset=0` explicitly, so it
|
||||
* cannot reuse that builder without changing totalsUrl's behavior for every
|
||||
* other caller.
|
||||
*/
|
||||
export function topUsersTotalsUrl(window: HistoryWindow, span: number, mode: TopUsersMode, limit: number = TOP_USERS_FETCH_LIMIT): string {
|
||||
const q = new URLSearchParams()
|
||||
q.set('kind', 'user')
|
||||
q.set('window', window)
|
||||
q.set('span', String(span))
|
||||
q.set('offset', '0')
|
||||
q.set('metrics', TOP_USERS_METRICS_BY_MODE[mode].join(','))
|
||||
q.set('limit', String(limit))
|
||||
return `/admin/api/usage/totals?${q.toString()}`
|
||||
}
|
||||
|
||||
/**
|
||||
* topUsersCapExceeded mirrors the server's own kind=user cap check
|
||||
* (stats_read.go:573: `len(ids)*len(metrics)*span > adminMaxKeysPerRequest`)
|
||||
* so HomePage.vue can decide, BEFORE firing a request, whether it would
|
||||
* come back 400 — `userCount` is the caller's own count of every
|
||||
* CONFIGURED user (HomePage.vue's configuredUserCount, an EXACT count as
|
||||
* of verify-ui-states-2.md #4, not an estimate). Deliberately a plain,
|
||||
* easily-tested predicate over three numbers rather than something that
|
||||
* reaches into a store itself.
|
||||
*/
|
||||
export function topUsersCapExceeded(userCount: number, metricsCount: number, span: number): boolean {
|
||||
return userCount * metricsCount * span > ADMIN_MAX_KEYS_PER_REQUEST
|
||||
}
|
||||
|
||||
/**
|
||||
* topUsersCapCheckResult (verify-ui-states-2.md #4) wraps topUsersCapExceeded
|
||||
* for HomePage.vue's actual call site: `configuredUserCount` is null before
|
||||
* dashboard.usage has ever loaded (a cold mount, or a load failure) — the
|
||||
* predictive check is skipped entirely in that case (returns false, so
|
||||
* fetchTopUsers fires the request) rather than guessing at a count, and the
|
||||
* server's own real 400 (fetchTopUsers's own catch, matched on "range too
|
||||
* large") still covers whatever this happens to miss once usage loads late.
|
||||
*/
|
||||
export function topUsersCapCheckResult(configuredUserCount: number | null, metricsCount: number, span: number): boolean {
|
||||
if (configuredUserCount === null) return false
|
||||
return topUsersCapExceeded(configuredUserCount, metricsCount, span)
|
||||
}
|
||||
|
||||
/** One ranked "top users" row — the id plus the single numeric value the current mode ranked it by (already summed for 'tokens'). HomePage.vue formats `value` itself (formatCost for 'cost', formatCompactCount for 'req'/'tokens') — this stays a plain number so the sort/tiebreak logic below never depends on a formatted string. */
|
||||
export interface RankedTopUser {
|
||||
id: string
|
||||
value: number
|
||||
}
|
||||
|
||||
/** topUserValue reads the single metric (or metric sum) `mode` ranks by out of one totals row — 'tokens' sums tokin+tokout, matching TOP_USERS_METRICS_BY_MODE's own request shape; a metric absent from `values` (should not happen given TOP_USERS_METRICS_BY_MODE, but Record<string, number> guarantees no key) reads as 0. */
|
||||
function topUserValue(row: { values: Record<string, number> }, mode: TopUsersMode): number {
|
||||
switch (mode) {
|
||||
case 'cost':
|
||||
return row.values.cost ?? 0
|
||||
case 'req':
|
||||
return row.values.req ?? 0
|
||||
case 'tokens':
|
||||
return (row.values.tokin ?? 0) + (row.values.tokout ?? 0)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* rankTopUsers ranks ONE fetched totals response client-side for `mode` —
|
||||
* Cost/Requests/Tokens each sort by their own value descending, ties broken
|
||||
* by id ascending; a row whose CURRENT MODE's value is 0 is excluded (a
|
||||
* user with requests but $0 cost, e.g. free-model-only traffic, drops out
|
||||
* of the Cost ranking but stays in the Requests one) — distinct from the
|
||||
* server's own all-metrics-zero drop (stats_read.go's buildTotalsRows),
|
||||
* which this re-implements for the one metric set actually requested
|
||||
* rather than relying on it.
|
||||
*/
|
||||
export function rankTopUsers(
|
||||
rows: AdminTotalsResponse['rows'],
|
||||
mode: TopUsersMode,
|
||||
limit: number = TOP_USERS_RANK_LIMIT,
|
||||
): RankedTopUser[] {
|
||||
return rows
|
||||
.map((row): RankedTopUser => ({ id: row.id, value: topUserValue(row, mode) }))
|
||||
.filter((row) => row.value > 0)
|
||||
.sort((a, b) => (b.value !== a.value ? b.value - a.value : a.id.localeCompare(b.id)))
|
||||
.slice(0, limit)
|
||||
}
|
||||
Reference in New Issue
Block a user