mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
feat(webui): users page
This commit is contained in:
+1
-1
@@ -47,7 +47,7 @@ const PAGES: Record<PageId, Component> = {
|
||||
overview: lazyPage(() => import('@/pages/OverviewPage.vue')),
|
||||
usage: lazyPage(() => import('@/pages/UsagePage.vue')),
|
||||
reliability: lazyPage(() => import('@/pages/ReliabilityPage.vue')),
|
||||
users: lazyPage(() => import('@/pages/ConsumersPage.vue')),
|
||||
users: lazyPage(() => import('@/pages/UsersPage.vue')),
|
||||
models: lazyPage(() => import('@/pages/ModelsPage.vue')),
|
||||
routers: lazyPage(() => import('@/pages/ModelsPage.vue')),
|
||||
targets: lazyPage(() => import('@/pages/TargetsPage.vue')),
|
||||
|
||||
@@ -21,6 +21,9 @@ import type { LimitKey, LimitsConfig } from '@/types/api'
|
||||
const props = defineProps<{
|
||||
groupNames: string[]
|
||||
userNames: string[]
|
||||
/** Pre-selects the target (a detail panel opens the form for its own entity). */
|
||||
presetKind?: 'group' | 'user'
|
||||
presetName?: string
|
||||
}>()
|
||||
|
||||
const { targetKind, targetName, targetNames, nameValid, snippetLabel } = useTargetPicker(
|
||||
@@ -28,6 +31,11 @@ const { targetKind, targetName, targetNames, nameValid, snippetLabel } = useTarg
|
||||
() => props.userNames,
|
||||
)
|
||||
|
||||
if (props.presetName) {
|
||||
targetKind.value = props.presetKind ?? 'user'
|
||||
targetName.value = props.presetName
|
||||
}
|
||||
|
||||
/** INTEGER_FIELDS is every LimitsConfig field Go decodes as `int64` (llmgateway.go) — requestsPerMinute/requestsPerDay/tokensPerDay/tokensPerMonth reject a fractional value like "1.5" at json.Unmarshal outright (P2 item 12), unlike costPerDayUSD/costPerMonthUSD, which are `float64`. */
|
||||
const INTEGER_FIELDS = new Set<LimitKey>(['requestsPerMinute', 'requestsPerDay', 'tokensPerMinute', 'tokensPerDay', 'tokensPerMonth'])
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { effectiveLimitRows, isHot, meterModel, primaryLimit } from '@/lib/meters'
|
||||
import type { LimitsConfig } from '@/types/api'
|
||||
|
||||
const PACING = { startPct: 80, maxDelay: '10s' }
|
||||
const LIMITS: LimitsConfig = { requestsPerMinute: 30, requestsPerDay: 3000, tokensPerMinute: 1_200_000, pacing: PACING }
|
||||
const ENTRY = { requestsPerMinute: 27, requestsPerDay: 1500, tokensPerMinute: 900_000 }
|
||||
|
||||
describe('meterModel', () => {
|
||||
it('requests meter has pacing marker at startPct and limit marker', () => {
|
||||
const m = meterModel(ENTRY, LIMITS).find((x) => x.label === 'Requests/min')
|
||||
expect(m).toEqual({
|
||||
label: 'Requests/min',
|
||||
value: 27,
|
||||
max: 30,
|
||||
markers: [
|
||||
{ value: 24, label: 'pacing 80%', tone: 'warning' },
|
||||
{ value: 30, label: 'limit', tone: 'danger' },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('absent tokensPerMinute shows limit only', () => {
|
||||
const m = meterModel({ requestsPerMinute: 1, requestsPerDay: 2 }, LIMITS).find((x) => x.label === 'Tokens/min')
|
||||
expect(m).toEqual({ label: 'Tokens/min', value: 0, max: 1_200_000, markers: [{ value: 1_200_000, label: 'limit', tone: 'danger' }] })
|
||||
})
|
||||
|
||||
it('no limits -> []', () => {
|
||||
expect(meterModel(ENTRY, undefined)).toEqual([])
|
||||
expect(meterModel(ENTRY, {})).toEqual([])
|
||||
})
|
||||
|
||||
it('day meter carries the limit only, never pacing', () => {
|
||||
const m = meterModel(ENTRY, LIMITS).find((x) => x.label === 'Requests/day')
|
||||
expect(m?.markers).toEqual([{ value: 3000, label: 'limit', tone: 'danger' }])
|
||||
})
|
||||
|
||||
it('without pacing the minute meters have only the limit marker', () => {
|
||||
const m = meterModel(ENTRY, { requestsPerMinute: 30 })
|
||||
expect(m).toHaveLength(1)
|
||||
expect(m[0]?.markers).toEqual([{ value: 30, label: 'limit', tone: 'danger' }])
|
||||
})
|
||||
|
||||
it('lists the meters in a fixed order', () => {
|
||||
expect(meterModel(ENTRY, LIMITS).map((m) => m.label)).toEqual(['Requests/min', 'Requests/day', 'Tokens/min'])
|
||||
})
|
||||
|
||||
it('treats a zero limit as unset', () => {
|
||||
expect(meterModel(ENTRY, { requestsPerMinute: 0, requestsPerDay: 0 })).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('isHot', () => {
|
||||
it('is hot once a minute meter reaches the pacing threshold', () => {
|
||||
expect(isHot({ requestsPerMinute: 24, requestsPerDay: 0 }, LIMITS)).toBe(true)
|
||||
expect(isHot({ requestsPerMinute: 23, requestsPerDay: 0 }, LIMITS)).toBe(false)
|
||||
})
|
||||
it('reads live tokens too', () => {
|
||||
expect(isHot({ requestsPerMinute: 0, requestsPerDay: 0, tokensPerMinute: 1_000_000 }, LIMITS)).toBe(true)
|
||||
})
|
||||
it('falls back to 80% without pacing and is false without limits', () => {
|
||||
expect(isHot({ requestsPerMinute: 8, requestsPerDay: 0 }, { requestsPerMinute: 10 })).toBe(true)
|
||||
expect(isHot({ requestsPerMinute: 7, requestsPerDay: 0 }, { requestsPerMinute: 10 })).toBe(false)
|
||||
expect(isHot({ requestsPerMinute: 99, requestsPerDay: 0 }, undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('primaryLimit', () => {
|
||||
it('prefers requests/min, then tokens/min, then requests/day', () => {
|
||||
expect(primaryLimit(LIMITS)).toEqual({ limit: 30, unit: 'min' })
|
||||
expect(primaryLimit({ tokensPerMinute: 5 })).toEqual({ limit: 5, unit: 'tok/min' })
|
||||
expect(primaryLimit({ requestsPerDay: 9 })).toEqual({ limit: 9, unit: 'day' })
|
||||
expect(primaryLimit(undefined)).toEqual({ limit: null, unit: '' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('effectiveLimitRows', () => {
|
||||
it('labels each limit with where it came from', () => {
|
||||
const rows = effectiveLimitRows(LIMITS, { requestsPerMinute: 'memberLimits:friends', requestsPerDay: 'user' })
|
||||
expect(rows.find((r) => r.label === 'Requests/min')).toMatchObject({ value: '30', source: 'group friends (per member)' })
|
||||
expect(rows.find((r) => r.label === 'Requests/day')).toMatchObject({ value: '3,000', source: 'user' })
|
||||
expect(rows.find((r) => r.label === 'Pacing')).toMatchObject({ value: 'from 80%, up to 10s delay' })
|
||||
})
|
||||
it('returns no rows without limits', () => {
|
||||
expect(effectiveLimitRows(undefined, undefined)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
import { formatCompactCount } from '@/lib/format'
|
||||
import type { AdminUsageEntryView, LimitSources, LimitsConfig } from '@/types/api'
|
||||
|
||||
/** Pacing starts here when a scope sets no pacing block; matches the budget bars' amber tier. */
|
||||
const DEFAULT_HOT_FRACTION = 0.8
|
||||
const PERCENT = 100
|
||||
|
||||
export interface MeterMarker {
|
||||
value: number
|
||||
label: string
|
||||
tone: 'warning' | 'danger'
|
||||
}
|
||||
|
||||
export interface Meter {
|
||||
label: string
|
||||
value: number
|
||||
max: number
|
||||
markers: MeterMarker[]
|
||||
}
|
||||
|
||||
type LiveEntry = Pick<AdminUsageEntryView, 'requestsPerMinute' | 'requestsPerDay' | 'tokensPerMinute'>
|
||||
|
||||
const has = (n: number | undefined): n is number => typeof n === 'number' && Number.isFinite(n) && n > 0
|
||||
|
||||
function limitMarker(limit: number): MeterMarker {
|
||||
return { value: limit, label: 'limit', tone: 'danger' }
|
||||
}
|
||||
|
||||
function pacingMarker(limit: number, limits: LimitsConfig): MeterMarker | null {
|
||||
const pct = limits.pacing?.startPct
|
||||
return has(pct) ? { value: (limit * pct) / PERCENT, label: `pacing ${pct}%`, tone: 'warning' } : null
|
||||
}
|
||||
|
||||
function minuteMarkers(limit: number, limits: LimitsConfig, live: boolean): MeterMarker[] {
|
||||
const pacing = live ? pacingMarker(limit, limits) : null
|
||||
return pacing ? [pacing, limitMarker(limit)] : [limitMarker(limit)]
|
||||
}
|
||||
|
||||
/** meterModel builds one meter per set limit; pacing applies to minute meters only, and needs a live reading. */
|
||||
export function meterModel(entry: LiveEntry, limits: LimitsConfig | undefined): Meter[] {
|
||||
if (!limits) return []
|
||||
const out: Meter[] = []
|
||||
if (has(limits.requestsPerMinute)) {
|
||||
out.push({ label: 'Requests/min', value: entry.requestsPerMinute, max: limits.requestsPerMinute, markers: minuteMarkers(limits.requestsPerMinute, limits, true) })
|
||||
}
|
||||
if (has(limits.requestsPerDay)) {
|
||||
out.push({ label: 'Requests/day', value: entry.requestsPerDay, max: limits.requestsPerDay, markers: [limitMarker(limits.requestsPerDay)] })
|
||||
}
|
||||
if (has(limits.tokensPerMinute)) {
|
||||
const live = entry.tokensPerMinute !== undefined
|
||||
out.push({ label: 'Tokens/min', value: entry.tokensPerMinute ?? 0, max: limits.tokensPerMinute, markers: minuteMarkers(limits.tokensPerMinute, limits, live) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** isHot reports a minute meter at or past the pacing start (80% when pacing is unset). */
|
||||
export function isHot(entry: LiveEntry, limits: LimitsConfig | undefined): boolean {
|
||||
if (!limits) return false
|
||||
const threshold = has(limits.pacing?.startPct) ? (limits.pacing as { startPct: number }).startPct / PERCENT : DEFAULT_HOT_FRACTION
|
||||
return meterModel(entry, limits)
|
||||
.filter((m) => m.label.endsWith('/min'))
|
||||
.some((m) => m.value / m.max >= threshold)
|
||||
}
|
||||
|
||||
/** primaryLimit picks the single limit a table cell shows. */
|
||||
export function primaryLimit(limits: LimitsConfig | undefined): { limit: number | null; unit: string } {
|
||||
if (has(limits?.requestsPerMinute)) return { limit: limits.requestsPerMinute, unit: 'min' }
|
||||
if (has(limits?.tokensPerMinute)) return { limit: limits.tokensPerMinute, unit: 'tok/min' }
|
||||
if (has(limits?.requestsPerDay)) return { limit: limits.requestsPerDay, unit: 'day' }
|
||||
return { limit: null, unit: '' }
|
||||
}
|
||||
|
||||
export interface LimitRow {
|
||||
key: string
|
||||
label: string
|
||||
value: string
|
||||
source: string
|
||||
}
|
||||
|
||||
const LIMIT_FIELDS: Array<{ key: Exclude<keyof LimitsConfig, 'pacing'>; label: string; usd?: boolean }> = [
|
||||
{ key: 'requestsPerMinute', label: 'Requests/min' },
|
||||
{ key: 'requestsPerDay', label: 'Requests/day' },
|
||||
{ key: 'tokensPerMinute', label: 'Tokens/min' },
|
||||
{ key: 'tokensPerDay', label: 'Tokens/day' },
|
||||
{ key: 'tokensPerMonth', label: 'Tokens/month' },
|
||||
{ key: 'costPerDayUSD', label: 'Cost/day', usd: true },
|
||||
{ key: 'costPerMonthUSD', label: 'Cost/month', usd: true },
|
||||
]
|
||||
|
||||
const MEMBER_PREFIX = 'memberLimits:'
|
||||
|
||||
function sourceLabel(source: string | undefined): string {
|
||||
if (!source) return ''
|
||||
return source.startsWith(MEMBER_PREFIX) ? `group ${source.slice(MEMBER_PREFIX.length)} (per member)` : source
|
||||
}
|
||||
|
||||
/** effectiveLimitRows lists each set limit with the config layer it came from. */
|
||||
export function effectiveLimitRows(limits: LimitsConfig | undefined, sources: LimitSources | undefined): LimitRow[] {
|
||||
if (!limits) return []
|
||||
const rows: LimitRow[] = []
|
||||
for (const f of LIMIT_FIELDS) {
|
||||
const v = limits[f.key]
|
||||
if (has(v)) rows.push({ key: f.key, label: f.label, value: f.usd ? `$${v}` : formatCompactCount(v), source: sourceLabel(sources?.[f.key]) })
|
||||
}
|
||||
if (limits.pacing) {
|
||||
rows.push({ key: 'pacing', label: 'Pacing', value: `from ${limits.pacing.startPct}%, up to ${limits.pacing.maxDelay} delay`, source: sourceLabel(sources?.pacing) })
|
||||
}
|
||||
return rows
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
<script setup lang="ts">
|
||||
import { Card, CardAction, CardContent, CardHeader, CardTitle, Pagination, SegmentedControl } from '@perfect-design/ui'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
|
||||
import { useNow } from '@/composables/useNow'
|
||||
import { formatCompactCount } from '@/lib/format'
|
||||
import { formatLastSeen } from '@/lib/last-seen'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { isHot, primaryLimit } from '@/lib/meters'
|
||||
import { pageWindow } from '@/lib/paging'
|
||||
import { resolveSel } from '@/lib/panel-selection'
|
||||
import { wbColumns } from '@/lib/wb-columns'
|
||||
import GroupPanel from '@/panels/GroupPanel.vue'
|
||||
import UserPanel from '@/panels/UserPanel.vue'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
import type { AdminUsageEntryView } from '@/types/api'
|
||||
import LimitBadge from '@/widgets/LimitBadge.vue'
|
||||
import StateView from '@/widgets/StateView.vue'
|
||||
import type { ViewState } from '@/widgets/StateView.vue'
|
||||
import WbTable from '@/widgets/WbTable.vue'
|
||||
|
||||
const PAGE_SIZE = 12
|
||||
type Tab = 'users' | 'groups'
|
||||
const TAB_OPTIONS = [
|
||||
{ value: 'users', label: 'Users' },
|
||||
{ value: 'groups', label: 'Groups' },
|
||||
]
|
||||
|
||||
interface Row {
|
||||
id: string
|
||||
name: string
|
||||
group: string
|
||||
members: number
|
||||
lastSeen: string
|
||||
requests: number
|
||||
tokens: number
|
||||
share: number | null
|
||||
limit: number | null
|
||||
limitUnit: string
|
||||
hot: boolean
|
||||
}
|
||||
|
||||
const dashboard = useDashboardStore()
|
||||
const nav = useNavStore()
|
||||
const { now, start: startClock, stop: stopClock } = useNow()
|
||||
|
||||
const usage = computed(() => dashboard.usage)
|
||||
const tab = computed<Tab>(() => (nav.params.tab === 'groups' ? 'groups' : 'users'))
|
||||
|
||||
function pick(next: unknown): void {
|
||||
if (next !== 'users' && next !== 'groups') return
|
||||
const { tab: _tab, ...rest } = nav.params
|
||||
nav.goTo('users', next === 'groups' ? { ...rest, tab: 'groups' } : rest)
|
||||
}
|
||||
|
||||
const memberCounts = computed(() => new Map((dashboard.overview?.groups ?? []).map((g) => [g.name, g.memberCount])))
|
||||
// Fleet total can lag the per-scope counters, so never let a share exceed the visible sum.
|
||||
const totalRequests = computed(() => Math.max(usage.value?.total.requestsPerDay ?? 0, (usage.value?.users ?? []).reduce((a, u) => a + u.requestsPerDay, 0)))
|
||||
|
||||
function toRow(e: AdminUsageEntryView): Row {
|
||||
const { limit, unit } = primaryLimit(e.limits)
|
||||
return {
|
||||
id: e.id,
|
||||
name: e.id,
|
||||
group: (e.groups ?? (e.groupName ? [e.groupName] : [])).join(', ') || '—',
|
||||
members: memberCounts.value.get(e.id) ?? 0,
|
||||
lastSeen: formatLastSeen(e.lastSeen, now.value),
|
||||
requests: e.requestsPerDay,
|
||||
tokens: e.tokensInPerDay + e.tokensOutPerDay,
|
||||
share: totalRequests.value > 0 ? Math.min(1, e.requestsPerDay / totalRequests.value) : null,
|
||||
limit,
|
||||
limitUnit: unit,
|
||||
hot: isHot(e, e.limits),
|
||||
}
|
||||
}
|
||||
|
||||
const byRequests = (a: Row, b: Row): number => b.requests - a.requests || a.name.localeCompare(b.name)
|
||||
const userRows = computed<Row[]>(() => (usage.value?.users ?? []).map(toRow).sort(byRequests))
|
||||
const groupRows = computed<Row[]>(() => (usage.value?.groups ?? []).map(toRow).sort(byRequests))
|
||||
const rows = computed(() => (tab.value === 'users' ? userRows.value : groupRows.value))
|
||||
|
||||
const userColumns = wbColumns<Row>([
|
||||
{ key: 'name', header: 'Name', kind: 'text' },
|
||||
{ key: 'group', header: 'Group', kind: 'text' },
|
||||
{ key: 'lastSeen', header: 'Last seen', kind: 'time', sortable: false },
|
||||
{ key: 'requests', header: 'Req/day', kind: 'number' },
|
||||
{ key: 'tokens', header: 'Tokens/day', kind: 'number' },
|
||||
{ key: 'share', header: 'Share', kind: 'share' },
|
||||
{ key: 'limit', header: 'Limit', kind: 'limit', sortable: false },
|
||||
])
|
||||
const groupColumns = wbColumns<Row>([
|
||||
{ key: 'name', header: 'Name', kind: 'text' },
|
||||
{ key: 'members', header: 'Members', kind: 'number' },
|
||||
{ key: 'requests', header: 'Req/day', kind: 'number' },
|
||||
{ key: 'tokens', header: 'Tokens/day', kind: 'number' },
|
||||
{ key: 'share', header: 'Share', kind: 'share' },
|
||||
{ key: 'limit', header: 'Limit', kind: 'limit', sortable: false },
|
||||
])
|
||||
const columns = computed(() => (tab.value === 'users' ? userColumns : groupColumns))
|
||||
|
||||
const page = ref(1)
|
||||
watch(tab, () => (page.value = 1))
|
||||
const window_ = computed(() => pageWindow(rows.value.length, PAGE_SIZE, page.value - 1))
|
||||
const paged = computed(() => rows.value.slice(window_.value.from, window_.value.to))
|
||||
|
||||
const state = computed<ViewState>(() => {
|
||||
const s = loadState({ loading: dashboard.lastUpdated === null, hasData: usage.value !== null, error: dashboard.error })
|
||||
if (s === 'skeleton') return 'loading'
|
||||
if (s === 'error') return 'error'
|
||||
return rows.value.length === 0 ? 'empty' : 'ready'
|
||||
})
|
||||
const emptyTitle = computed(() => (tab.value === 'users' ? 'No users configured' : 'No groups configured'))
|
||||
|
||||
const selection = computed(() => nav.selection)
|
||||
const activeKey = computed(() => (selection.value?.kind === (tab.value === 'users' ? 'user' : 'group') ? selection.value.id : null))
|
||||
|
||||
function exists(kind: string, id: string): boolean {
|
||||
if (kind === 'user') return (usage.value?.users ?? []).some((u) => u.id === id)
|
||||
if (kind === 'group') return (usage.value?.groups ?? []).some((g) => g.id === id)
|
||||
return false
|
||||
}
|
||||
// An unknown or foreign sel is dropped in place once usage has loaded.
|
||||
watch(
|
||||
[selection, usage],
|
||||
([sel, u]) => {
|
||||
if (!sel || !u) return
|
||||
if (resolveSel(sel, (k, id) => exists(k, id)) === null) nav.closePanel()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
const openSel = computed(() => (usage.value ? resolveSel(selection.value, (k, id) => exists(k, id)) : null))
|
||||
|
||||
function open(row: Row): void {
|
||||
nav.openPanel(tab.value === 'users' ? 'user' : 'group', row.id)
|
||||
}
|
||||
|
||||
onMounted(startClock)
|
||||
onUnmounted(stopClock)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<Card size="sm">
|
||||
<CardHeader class="items-center">
|
||||
<CardTitle>{{ tab === 'users' ? 'Users' : 'Groups' }}</CardTitle>
|
||||
<CardAction class="self-center">
|
||||
<SegmentedControl :model-value="tab" :options="TAB_OPTIONS" size="sm" aria-label="Users or groups" @update:model-value="pick" />
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-2">
|
||||
<StateView :state="state" :empty-title="emptyTitle" :error-message="dashboard.error" :updated-at="dashboard.lastUpdated ?? undefined" @retry="dashboard.refresh()">
|
||||
<WbTable
|
||||
class="wb-clip"
|
||||
:columns="columns"
|
||||
:rows="paged"
|
||||
row-key="id"
|
||||
:active-key="activeKey"
|
||||
:label="tab === 'users' ? 'Users' : 'Groups'"
|
||||
@row-activate="open"
|
||||
>
|
||||
<template #cell-members="{ value }">{{ formatCompactCount(value as number) }}</template>
|
||||
<template #cell-requests="{ value }">{{ formatCompactCount(value as number) }}</template>
|
||||
<template #cell-tokens="{ value }">{{ formatCompactCount(value as number) }}</template>
|
||||
<template #cell-limit="{ row }">
|
||||
<LimitBadge :limit="(row as Row).limit" :unit="(row as Row).limitUnit" :hot="(row as Row).hot" />
|
||||
</template>
|
||||
</WbTable>
|
||||
<div v-if="rows.length > PAGE_SIZE" class="flex items-center justify-between gap-2">
|
||||
<span class="text-muted-foreground text-xs">{{ rows.length.toLocaleString('en-US') }} {{ tab }}</span>
|
||||
<Pagination v-model:page="page" :total="rows.length" :page-size="PAGE_SIZE" variant="compact" size="sm" />
|
||||
</div>
|
||||
</StateView>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<UserPanel v-if="openSel?.kind === 'user'" :id="openSel.id" @close="nav.closePanel()" />
|
||||
<GroupPanel v-else-if="openSel?.kind === 'group'" :id="openSel.id" @close="nav.closePanel()" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,92 @@
|
||||
<script setup lang="ts">
|
||||
import { DescriptionItem, DescriptionList } from '@perfect-design/ui'
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { formatCompactCount, formatCostDisplay } from '@/lib/format'
|
||||
import { effectiveLimitRows, meterModel } from '@/lib/meters'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
import DetailPanel from '@/widgets/DetailPanel.vue'
|
||||
import MeterBar from '@/widgets/MeterBar.vue'
|
||||
import PanelSection from '@/widgets/PanelSection.vue'
|
||||
|
||||
const MEMBER_ROWS = 12
|
||||
|
||||
const props = defineProps<{ id: string }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const dashboard = useDashboardStore()
|
||||
const nav = useNavStore()
|
||||
|
||||
const entry = computed(() => dashboard.usage?.groups.find((g) => g.id === props.id))
|
||||
const members = computed(() =>
|
||||
(dashboard.usage?.users ?? [])
|
||||
.filter((u) => (u.groups ?? [u.groupName]).includes(props.id))
|
||||
.sort((a, b) => b.requestsPerDay - a.requestsPerDay || a.id.localeCompare(b.id)),
|
||||
)
|
||||
const memberCount = computed(() => dashboard.overview?.groups.find((g) => g.name === props.id)?.memberCount ?? members.value.length)
|
||||
const shownMembers = computed(() => members.value.slice(0, MEMBER_ROWS))
|
||||
|
||||
const meters = computed(() => (entry.value ? meterModel(entry.value, entry.value.limits) : []))
|
||||
const aggregateRows = computed(() => effectiveLimitRows(entry.value?.limits, undefined))
|
||||
const memberRows = computed(() => effectiveLimitRows(entry.value?.memberLimits, undefined))
|
||||
|
||||
const usageRows = computed(() => {
|
||||
const e = entry.value
|
||||
if (!e) return []
|
||||
return [
|
||||
{ term: 'Requests/min', value: formatCompactCount(e.requestsPerMinute) },
|
||||
{ term: 'Requests/day', value: formatCompactCount(e.requestsPerDay) },
|
||||
{ term: 'Tokens/day', value: formatCompactCount(e.tokensInPerDay + e.tokensOutPerDay) },
|
||||
{ term: 'Rejected/day', value: formatCompactCount(e.rejectionsPerDay) },
|
||||
{ term: 'Cost/day', value: formatCostDisplay(e.costPerDayMicroUsd) },
|
||||
{ term: 'Cost/month', value: formatCostDisplay(e.costPerMonthMicroUsd) },
|
||||
]
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DetailPanel kind="group" :id="id" :title="id" @close="emit('close')">
|
||||
<div class="flex flex-col divide-y px-1 pb-4" data-testid="group-panel">
|
||||
<div v-if="!entry" class="text-muted-foreground py-3 text-sm">This group has no usage data yet.</div>
|
||||
<template v-else>
|
||||
<PanelSection title="Usage">
|
||||
<DescriptionList variant="inline" size="sm" density="compact">
|
||||
<DescriptionItem term="Members"><span class="font-mono tabular-nums">{{ formatCompactCount(memberCount) }}</span></DescriptionItem>
|
||||
<DescriptionItem v-for="r in usageRows" :key="r.term" :term="r.term"><span class="font-mono tabular-nums">{{ r.value }}</span></DescriptionItem>
|
||||
</DescriptionList>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Aggregate limits">
|
||||
<div v-if="meters.length" class="flex flex-col gap-3">
|
||||
<MeterBar v-for="m in meters" :key="m.label" :meter="m" />
|
||||
</div>
|
||||
<p v-else class="text-muted-foreground m-0 text-sm">No aggregate limits. Members are limited individually.</p>
|
||||
<DescriptionList v-if="aggregateRows.length" variant="inline" size="sm" density="compact">
|
||||
<DescriptionItem v-for="r in aggregateRows" :key="r.key" :term="r.label"><span class="font-mono tabular-nums">{{ r.value }}</span></DescriptionItem>
|
||||
</DescriptionList>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Per-member limits">
|
||||
<DescriptionList v-if="memberRows.length" variant="inline" size="sm" density="compact">
|
||||
<DescriptionItem v-for="r in memberRows" :key="r.key" :term="r.label"><span class="font-mono tabular-nums">{{ r.value }}</span></DescriptionItem>
|
||||
</DescriptionList>
|
||||
<p v-else class="text-muted-foreground m-0 text-sm">No per-member limits.</p>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection :title="`Members (${members.length.toLocaleString('en-US')})`">
|
||||
<ul v-if="shownMembers.length" class="m-0 flex list-none flex-col p-0" aria-label="Group members">
|
||||
<li v-for="u in shownMembers" :key="u.id">
|
||||
<button type="button" class="hover:bg-accent flex h-8 w-full items-center justify-between gap-3 rounded-md px-2 text-left text-sm" @click="nav.openPanel('user', u.id)">
|
||||
<span class="min-w-0 truncate">{{ u.id }}</span>
|
||||
<span class="shrink-0 text-right font-mono text-xs tabular-nums">{{ formatCompactCount(u.requestsPerDay) }} req/day</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="text-muted-foreground m-0 text-sm">No members.</p>
|
||||
<p v-if="members.length > MEMBER_ROWS" class="text-muted-foreground m-0 px-2 text-xs">Top {{ MEMBER_ROWS }} by requests. {{ (members.length - MEMBER_ROWS).toLocaleString('en-US') }} more on the Users tab.</p>
|
||||
</PanelSection>
|
||||
</template>
|
||||
</div>
|
||||
</DetailPanel>
|
||||
</template>
|
||||
@@ -0,0 +1,219 @@
|
||||
<script setup lang="ts">
|
||||
import { Badge, Button, DescriptionItem, DescriptionList, StatusDot } from '@perfect-design/ui'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
|
||||
import LimitsForm from '@/components/forms/LimitsForm.vue'
|
||||
import { useNow } from '@/composables/useNow'
|
||||
import { providerAccessCell } from '@/lib/access-matrix'
|
||||
import { kindLabel } from '@/lib/events-filter'
|
||||
import { formatCompactCount } from '@/lib/format'
|
||||
import { formatLastSeen } from '@/lib/last-seen'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { effectiveLimitRows, meterModel } from '@/lib/meters'
|
||||
import { useConsumersStore } from '@/stores/consumers'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useEventsStore } from '@/stores/events'
|
||||
import { useFiltersStore } from '@/stores/filters'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
import DetailPanel from '@/widgets/DetailPanel.vue'
|
||||
import MeterBar from '@/widgets/MeterBar.vue'
|
||||
import ModelName from '@/widgets/ModelName.vue'
|
||||
import PanelSection from '@/widgets/PanelSection.vue'
|
||||
import StateView from '@/widgets/StateView.vue'
|
||||
import type { ViewState } from '@/widgets/StateView.vue'
|
||||
|
||||
const EVENT_ROWS = 8
|
||||
const THROTTLE_KINDS: ReadonlySet<string> = new Set(['rate_limit', 'paced'])
|
||||
|
||||
const props = defineProps<{ id: string }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const dashboard = useDashboardStore()
|
||||
const consumers = useConsumersStore()
|
||||
const events = useEventsStore()
|
||||
const filters = useFiltersStore()
|
||||
const nav = useNavStore()
|
||||
const { now, start: startClock, stop: stopClock } = useNow()
|
||||
|
||||
const entry = computed(() => dashboard.usage?.users.find((u) => u.id === props.id))
|
||||
const consumer = computed(() => consumers.data?.users.find((u) => u.name === props.id))
|
||||
const groups = computed(() => entry.value?.groups ?? (entry.value?.groupName ? [entry.value.groupName] : []))
|
||||
|
||||
// --- Meters + effective limits ---------------------------------------------
|
||||
|
||||
const meters = computed(() => (entry.value ? meterModel(entry.value, entry.value.limits) : []))
|
||||
const limitRows = computed(() => effectiveLimitRows(entry.value?.limits, entry.value?.limitSources))
|
||||
const exempt = computed(() => entry.value?.exemptRequestsPerMonth ?? 0)
|
||||
|
||||
// --- Models used ------------------------------------------------------------
|
||||
|
||||
const userModelStats = computed(() => dashboard.overview?.features.userModelStats ?? false)
|
||||
const detail = computed(() => consumers.detail[props.id])
|
||||
const modelRows = computed(() =>
|
||||
[...(detail.value?.modelTotals?.rows ?? [])].sort((a, b) => (b.values.req ?? 0) - (a.values.req ?? 0)),
|
||||
)
|
||||
const modelsState = computed<ViewState>(() => {
|
||||
if (dashboard.overview !== null && (!userModelStats.value || detail.value?.modelTotalsUnavailable)) return 'empty'
|
||||
const s = loadState({ loading: detail.value?.loading ?? true, hasData: detail.value?.modelTotals != null, error: detail.value?.modelError ?? '' })
|
||||
if (s === 'skeleton') return 'loading'
|
||||
if (s === 'error') return 'error'
|
||||
return modelRows.value.length === 0 ? 'empty' : 'ready'
|
||||
})
|
||||
const modelsEmptyTitle = computed(() => (userModelStats.value ? 'No model traffic in this range' : 'Per-user model statistics are off'))
|
||||
const modelsEmptyDescription = computed(() => (userModelStats.value ? undefined : 'Enable admin.stats.userModel to see which models this user calls.'))
|
||||
|
||||
function loadModels(): Promise<void> {
|
||||
return consumers.fetchUserDetail(props.id, filters.window, filters.span, userModelStats.value)
|
||||
}
|
||||
|
||||
// --- Throttle events --------------------------------------------------------
|
||||
|
||||
const throttled = computed(() => events.events.filter((e) => e.user === props.id && THROTTLE_KINDS.has(e.kind)).slice(0, EVENT_ROWS))
|
||||
const eventsState = computed<ViewState>(() => {
|
||||
const s = loadState({ loading: events.refreshing, hasData: events.lastUpdated !== null, error: events.error })
|
||||
if (s === 'skeleton') return 'loading'
|
||||
if (s === 'error') return 'error'
|
||||
return throttled.value.length === 0 ? 'empty' : 'ready'
|
||||
})
|
||||
const EVENT_TONE: Record<string, 'warning' | 'info'> = { rate_limit: 'warning', paced: 'info' }
|
||||
|
||||
function clock(iso: string): string {
|
||||
const d = new Date(iso)
|
||||
return Number.isNaN(d.getTime()) ? '' : d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
|
||||
}
|
||||
|
||||
// --- Access ----------------------------------------------------------------
|
||||
|
||||
const groupRows = computed(() => (consumers.data?.groups ?? []).filter((g) => groups.value.includes(g.name)))
|
||||
const providers = computed(() => {
|
||||
const out = new Map<string, string>()
|
||||
for (const g of groupRows.value) {
|
||||
for (const p of g.allowedProviders) {
|
||||
const cell = providerAccessCell(g, p)
|
||||
if (!out.has(p) || (cell.detail && !out.get(p))) out.set(p, cell.detail ?? '')
|
||||
}
|
||||
}
|
||||
return [...out].map(([name, detail]) => ({ name, detail })).sort((a, b) => a.name.localeCompare(b.name))
|
||||
})
|
||||
const accessState = computed<ViewState>(() => (consumers.data ? 'ready' : consumers.error ? 'error' : 'loading'))
|
||||
|
||||
// --- Snippet -----------------------------------------------------------------
|
||||
|
||||
const snippetOpen = ref(false)
|
||||
const groupNames = computed(() => (consumers.data?.groups ?? []).map((g) => g.name))
|
||||
const userNames = computed(() => (consumers.data?.users ?? []).map((u) => u.name))
|
||||
|
||||
watch([() => props.id, () => filters.range, userModelStats], () => void loadModels())
|
||||
watch(() => props.id, () => (snippetOpen.value = false))
|
||||
onMounted(() => {
|
||||
startClock()
|
||||
events.startPolling()
|
||||
void consumers.ensureConsumers()
|
||||
void loadModels()
|
||||
})
|
||||
onUnmounted(() => {
|
||||
stopClock()
|
||||
events.stopPolling()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DetailPanel kind="user" :id="id" :title="id" @close="emit('close')">
|
||||
<div class="flex flex-col divide-y px-1 pb-4" data-testid="user-panel">
|
||||
<div v-if="!entry" class="text-muted-foreground py-3 text-sm">No usage scope for this user yet. It appears after their first request.</div>
|
||||
<template v-else>
|
||||
<div class="flex flex-wrap items-center gap-2 pb-3 text-sm">
|
||||
<Badge v-if="consumer?.admin" tone="danger" size="sm">admin</Badge>
|
||||
<Badge v-if="consumer?.source" tone="neutral" variant="outline" size="sm">{{ consumer.source }}</Badge>
|
||||
<button
|
||||
v-for="g in groups"
|
||||
:key="g"
|
||||
type="button"
|
||||
class="hover:bg-accent rounded-md border px-2 py-0.5 text-xs"
|
||||
@click="nav.openPanel('group', g)"
|
||||
>
|
||||
{{ g }}
|
||||
</button>
|
||||
<span class="text-muted-foreground ml-auto text-xs">last seen {{ formatLastSeen(entry.lastSeen, now) }}</span>
|
||||
</div>
|
||||
|
||||
<PanelSection title="Meters">
|
||||
<div v-if="meters.length" class="flex flex-col gap-3">
|
||||
<MeterBar v-for="m in meters" :key="m.label" :meter="m" />
|
||||
</div>
|
||||
<p v-else class="text-muted-foreground m-0 text-sm">No limits apply to this user.</p>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Effective limits">
|
||||
<DescriptionList v-if="limitRows.length || exempt" variant="inline" size="sm" density="compact">
|
||||
<DescriptionItem v-for="r in limitRows" :key="r.key" :term="r.label">
|
||||
<span class="font-mono tabular-nums">{{ r.value }}</span>
|
||||
<span v-if="r.source" class="text-muted-foreground"> · {{ r.source }}</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem v-if="exempt" term="Exempt requests/month">
|
||||
<span class="font-mono tabular-nums">{{ formatCompactCount(exempt) }}</span>
|
||||
<span class="text-muted-foreground"> · limitExemptKinds</span>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
<p v-else class="text-muted-foreground m-0 text-sm">No limits set.</p>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Models used">
|
||||
<StateView :state="modelsState" :empty-title="modelsEmptyTitle" :empty-description="modelsEmptyDescription" :error-message="detail?.modelError" :rows="3" @retry="loadModels()">
|
||||
<ul class="m-0 flex list-none flex-col p-0" aria-label="Models used">
|
||||
<li v-for="m in modelRows" :key="m.id" class="flex h-8 items-center justify-between gap-3 px-2 text-sm">
|
||||
<ModelName :id="m.id" class="min-w-0" />
|
||||
<span class="shrink-0 text-right font-mono text-xs tabular-nums">{{ formatCompactCount(m.values.req ?? 0) }} req</span>
|
||||
</li>
|
||||
</ul>
|
||||
</StateView>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Recent rate-limit and paced events">
|
||||
<StateView :state="eventsState" empty-title="No recent throttling" :error-message="events.error" :rows="2" @retry="events.refresh()">
|
||||
<ul class="m-0 flex list-none flex-col p-0" aria-label="Recent throttle events">
|
||||
<li v-for="(e, i) in throttled" :key="`${e.time}-${i}`" class="flex h-8 items-center gap-2 px-2 text-sm" :title="e.message">
|
||||
<StatusDot class="shrink-0" :tone="EVENT_TONE[e.kind] ?? 'neutral'" size="md" />
|
||||
<span class="text-muted-foreground shrink-0 font-mono text-xs">{{ clock(e.time) }}</span>
|
||||
<span class="text-muted-foreground shrink-0">{{ kindLabel(e.kind) }}</span>
|
||||
<span class="min-w-0 flex-1 truncate">{{ e.model || e.provider || e.route }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</StateView>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Access">
|
||||
<StateView :state="accessState" :error-message="consumers.error" :rows="2" @retry="consumers.fetchConsumers()">
|
||||
<DescriptionList variant="stacked" size="sm" density="compact">
|
||||
<DescriptionItem term="Providers">
|
||||
<span v-if="providers.length === 0" class="text-muted-foreground">None granted by group</span>
|
||||
<span v-else class="flex flex-wrap gap-1">
|
||||
<Badge v-for="p in providers" :key="p.name" tone="neutral" variant="outline" size="sm" class="font-mono">{{ p.name }}<template v-if="p.detail"> · {{ p.detail }}</template></Badge>
|
||||
</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem v-if="consumer?.providers?.length" term="Personal providers">
|
||||
<span class="flex flex-wrap gap-1">
|
||||
<Badge v-for="p in consumer.providers" :key="p" tone="neutral" variant="outline" size="sm" class="font-mono">{{ p }}</Badge>
|
||||
</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem v-if="consumer?.models?.length" term="Personal models">
|
||||
<span class="flex flex-col gap-1">
|
||||
<ModelName v-for="m in consumer.models" :id="m" :key="m" />
|
||||
</span>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</StateView>
|
||||
</PanelSection>
|
||||
|
||||
<PanelSection title="Change limits">
|
||||
<div>
|
||||
<Button variant="outline" size="sm" :aria-expanded="snippetOpen" @click="snippetOpen = !snippetOpen">
|
||||
{{ snippetOpen ? 'Hide limits snippet' : 'Generate limits snippet' }}
|
||||
</Button>
|
||||
</div>
|
||||
<LimitsForm v-if="snippetOpen" :group-names="groupNames" :user-names="userNames" preset-kind="user" :preset-name="id" />
|
||||
</PanelSection>
|
||||
</template>
|
||||
</div>
|
||||
</DetailPanel>
|
||||
</template>
|
||||
@@ -0,0 +1,27 @@
|
||||
<script setup lang="ts">
|
||||
import { StatBar } from '@perfect-design/ui'
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { formatCompactCount } from '@/lib/format'
|
||||
import type { Meter } from '@/lib/meters'
|
||||
|
||||
const props = defineProps<{ meter: Meter }>()
|
||||
|
||||
function fmt(n: number): string {
|
||||
return Number.isInteger(n) || n >= 10 ? formatCompactCount(Math.round(n)) : String(Number(n.toFixed(1)))
|
||||
}
|
||||
|
||||
const pacing = computed(() => props.meter.markers.find((m) => m.tone === 'warning'))
|
||||
const warnAt = computed(() => (pacing.value ? pacing.value.value / props.meter.max : 0.8))
|
||||
const valueText = computed(() => `${fmt(props.meter.value)} / ${fmt(props.meter.max)}`)
|
||||
const markers = computed(() => props.meter.markers.map((m) => ({ ...m, valueText: fmt(m.value) })))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-1" data-testid="meter">
|
||||
<StatBar :label="meter.label" :value="meter.value" :max="meter.max" :value-text="valueText" tone="auto" :warn-at="warnAt" :danger-at="1" size="md" :markers="markers" />
|
||||
<p class="text-muted-foreground m-0 flex flex-wrap gap-x-4 text-xs">
|
||||
<span v-for="m in markers" :key="m.label" data-testid="meter-marker">{{ m.label }} <span class="font-mono tabular-nums">{{ m.valueText }}</span></span>
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{ title: string }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="flex flex-col gap-2 py-3" :aria-label="title">
|
||||
<h3 class="text-muted-foreground m-0 text-xs font-medium tracking-wide uppercase">{{ title }}</h3>
|
||||
<slot />
|
||||
</section>
|
||||
</template>
|
||||
Reference in New Issue
Block a user