mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
refactor(webui): extract repeated dashboard elements into shared components
Markup and helpers that were copied between pages now live in one place: - ChartCard, StatDisabledAlert, StatItem, DetailField, BudgetRatioBars, LabeledSelect, TargetPicker and LoadStateView components - lib/scope.ts, lib/columns.ts and lib/chart-palette.ts - messageOf, isAuthRejection, and the USD to micro-USD conversion helpers - one monthly cost projection, one date formatter, and the useCopyFeedback composable Behaviour is unchanged. Before and after screenshots of every page match at 390 and 1440 px. Empty-state text now comes from the shared EmptyState component, and the user run-out date uses the short date format. admin_assets_gen.go is regenerated. Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
This commit is contained in:
@@ -11,13 +11,12 @@ import EmptyState from '@/components/EmptyState.vue'
|
||||
import EntityLink from '@/components/EntityLink.vue'
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import SkeletonTable from '@/components/SkeletonTable.vue'
|
||||
import StatDisabledAlert from '@/components/StatDisabledAlert.vue'
|
||||
import TryLongerRangeButton from '@/components/TryLongerRangeButton.vue'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { formatCost } from '@/lib/format'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
import { drilldownLevel, makeScope } from '@/lib/scope'
|
||||
import { SPEND_METRIC_LABEL } from '@/stores/spend'
|
||||
import type { AdminTotalsResponse, HistoryMetric, HistoryWindow } from '@/types/api'
|
||||
|
||||
@@ -70,15 +69,7 @@ const props = defineProps<{
|
||||
|
||||
const emit = defineEmits<{ 'update:drill': [value: string] }>()
|
||||
|
||||
const nav = useNavStore()
|
||||
|
||||
type Level = { kind: 'group' } | { kind: 'user'; group: string } | { kind: 'usermodel'; user: string }
|
||||
|
||||
const level = computed<Level>(() => {
|
||||
if (props.drill === '') return { kind: 'group' }
|
||||
if (props.drill.startsWith('group:')) return { kind: 'user', group: props.drill.slice('group:'.length) }
|
||||
return { kind: 'usermodel', user: props.drill.slice('user:'.length) }
|
||||
})
|
||||
const level = computed(() => drilldownLevel(props.drill))
|
||||
|
||||
/**
|
||||
* parentGroupLabel is a BEST-EFFORT breadcrumb label for the group a
|
||||
@@ -97,15 +88,15 @@ function goToGroups(): void {
|
||||
emit('update:drill', '')
|
||||
}
|
||||
function goToParentGroup(): void {
|
||||
if (parentGroupLabel.value) emit('update:drill', `group:${parentGroupLabel.value}`)
|
||||
if (parentGroupLabel.value) emit('update:drill', makeScope('group', parentGroupLabel.value))
|
||||
}
|
||||
function onRowClick(id: string): void {
|
||||
const l = level.value
|
||||
if (l.kind === 'group') {
|
||||
emit('update:drill', `group:${id}`)
|
||||
emit('update:drill', makeScope('group', id))
|
||||
} else if (l.kind === 'user' && props.userModelStatsEnabled) {
|
||||
parentGroupLabel.value = l.group
|
||||
emit('update:drill', `user:${id}`)
|
||||
emit('update:drill', makeScope('user', id))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,13 +180,12 @@ const noTrafficInRange = computed<boolean>(() => !showUserModelHint.value && pro
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-3">
|
||||
<ClampedRangeNotice v-if="level.kind === 'usermodel'" :window="window" :span="span" />
|
||||
<Alert v-if="showUserModelHint" variant="warn">
|
||||
<AlertTitle>Per-user-model statistics are off</AlertTitle>
|
||||
<AlertDescription class="flex flex-wrap items-center gap-2">
|
||||
<span>Enable <code class="font-mono text-xs">admin.stats.userModel</code> in the middleware config to see per-model attribution for this user.</span>
|
||||
<Button type="button" variant="outline" size="sm" @click="nav.goTo('config')">Open Config</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<StatDisabledAlert
|
||||
v-if="showUserModelHint"
|
||||
title="Per-user-model statistics are off"
|
||||
config-key="admin.stats.userModel"
|
||||
purpose="to see per-model attribution for this user."
|
||||
/>
|
||||
<SkeletonTable v-else-if="state === 'skeleton'" :rows="5" :cols="metrics.length + 1" />
|
||||
<ErrorState v-else-if="state === 'error'" :message="error" :on-retry="onRetry" />
|
||||
<EmptyState v-else-if="noTrafficInRange" title="No traffic in this range.">
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<script setup lang="ts">
|
||||
import UsageBar from '@/components/UsageBar.vue'
|
||||
import { BUDGET_RATIO_LABEL, budgetValueText } from '@/lib/usage-bars'
|
||||
import type { BudgetRatio } from '@/lib/usage-bars'
|
||||
|
||||
/**
|
||||
* BudgetRatioBars (reuse-audit.md F7) is the ONE budget-ratio bar row —
|
||||
* one labelled UsageBar per configured limit — UserDetail.vue's Headroom
|
||||
* card and ConsumerDirectory.vue's group accordion both hand-rolled: a
|
||||
* label (BUDGET_RATIO_LABEL) beside each lib/usage-bars.ts budgetRatios()
|
||||
* entry, its UsageBar sized to that ratio, and its "used / limit" text
|
||||
* (the shared budgetValueText).
|
||||
*/
|
||||
defineProps<{
|
||||
ratios: BudgetRatio[]
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-wrap items-center gap-x-4 gap-y-1.5">
|
||||
<span v-for="ratio in ratios" :key="ratio.id" class="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
{{ BUDGET_RATIO_LABEL[ratio.id] }}
|
||||
<UsageBar :ratio="ratio.ratio" :label="BUDGET_RATIO_LABEL[ratio.id]" :value-text="budgetValueText(ratio)" />
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,13 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import SkeletonChart from '@/components/SkeletonChart.vue'
|
||||
import ChartCard from '@/components/ChartCard.vue'
|
||||
import StatItem from '@/components/StatItem.vue'
|
||||
import TimeSeriesChart from '@/components/TimeSeriesChart.vue'
|
||||
import type { TimeSeriesDataset } from '@/components/TimeSeriesChart.vue'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { cumulative, runOutDate } from '@/lib/burndown'
|
||||
import { formatBucketLabel, formatCost } from '@/lib/format'
|
||||
import { NOT_ENOUGH_DATA } from '@/lib/forecast'
|
||||
import { formatBucketLabel, formatCost, formatShortDate } from '@/lib/format'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
|
||||
/**
|
||||
@@ -64,43 +64,34 @@ const willExceed = computed<boolean>(() => props.budgetMicros !== null && spentM
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Burn-down</CardTitle>
|
||||
<CardDescription>Cumulative spend this UTC calendar month against the configured budget.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<SkeletonChart v-if="state === 'skeleton'" />
|
||||
<ErrorState v-else-if="state === 'error'" :message="error ?? ''" :on-retry="onRetry" />
|
||||
<template v-else>
|
||||
<div class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-3">
|
||||
<div>
|
||||
<p class="text-muted-foreground">Spent so far</p>
|
||||
<p class="text-lg font-semibold tabular-nums" :class="willExceed ? 'text-destructive' : undefined">
|
||||
{{ formatCost(spentMicros) }}
|
||||
</p>
|
||||
</div>
|
||||
<div v-if="budgetMicros !== null">
|
||||
<p class="text-muted-foreground">Budget</p>
|
||||
<p class="text-lg font-semibold tabular-nums">{{ formatCost(budgetMicros) }}</p>
|
||||
</div>
|
||||
<div v-if="budgetMicros !== null">
|
||||
<p class="text-muted-foreground">Projected run-out</p>
|
||||
<p v-if="runOut === null" class="text-sm text-muted-foreground">not enough data yet</p>
|
||||
<p v-else class="text-lg font-semibold tabular-nums" :class="willExceed ? 'text-destructive' : undefined">
|
||||
{{ runOut.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="budgetMicros === null" class="text-sm text-muted-foreground">No budget configured for this scope.</p>
|
||||
<TimeSeriesChart
|
||||
:labels="labels"
|
||||
:datasets="datasets"
|
||||
:comparison-datasets="comparisonDatasets"
|
||||
:value-formatter="formatCost"
|
||||
ariaLabel="Cumulative spend this month against the configured budget"
|
||||
/>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<ChartCard
|
||||
title="Burn-down"
|
||||
description="Cumulative spend this UTC calendar month against the configured budget."
|
||||
:state="state"
|
||||
:error="error ?? ''"
|
||||
:on-retry="onRetry"
|
||||
>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-3">
|
||||
<StatItem label="Spent so far" :tone="willExceed ? 'destructive' : 'default'">{{ formatCost(spentMicros) }}</StatItem>
|
||||
<StatItem v-if="budgetMicros !== null" label="Budget">{{ formatCost(budgetMicros) }}</StatItem>
|
||||
<StatItem
|
||||
v-if="budgetMicros !== null"
|
||||
label="Projected run-out"
|
||||
:tone="willExceed ? 'destructive' : 'default'"
|
||||
:hint="runOut === null ? NOT_ENOUGH_DATA : undefined"
|
||||
>
|
||||
{{ runOut === null ? '' : formatShortDate(runOut) }}
|
||||
</StatItem>
|
||||
</div>
|
||||
<p v-if="budgetMicros === null" class="text-sm text-muted-foreground">No budget configured for this scope.</p>
|
||||
<TimeSeriesChart
|
||||
:labels="labels"
|
||||
:datasets="datasets"
|
||||
:comparison-datasets="comparisonDatasets"
|
||||
:value-formatter="formatCost"
|
||||
ariaLabel="Cumulative spend this month against the configured budget"
|
||||
/>
|
||||
</div>
|
||||
</ChartCard>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
<script setup lang="ts">
|
||||
import EmptyState from '@/components/EmptyState.vue'
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import SkeletonChart from '@/components/SkeletonChart.vue'
|
||||
import TimeSeriesChart from '@/components/TimeSeriesChart.vue'
|
||||
import type { TimeSeriesComparisonDataset, TimeSeriesDataset } from '@/components/TimeSeriesChart.vue'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { formatExactInt } from '@/lib/format'
|
||||
import type { LoadState } from '@/lib/load-state'
|
||||
|
||||
/**
|
||||
* ChartCard (reuse-audit.md F1) is the ONE `Card > CardHeader(Title,
|
||||
* Description?) > CardContent > skeleton|error|(empty)|chart` shell every
|
||||
* time-series chart card in this panel used to hand-roll — ReliabilityPage
|
||||
* (5 real chart cards + 4 skeleton-only loading cards), UserDetail
|
||||
* (requests/cost), SpendPage (breakdown), BurnDownChart. `state` drives the
|
||||
* skeleton/error/ready branch (lib/load-state.ts's LoadState — the SAME
|
||||
* precedence every other card in this panel already follows); `error` and
|
||||
* `onRetry` forward straight to ErrorState. The default slot overrides the
|
||||
* ready-state body for a chart that needs more than a bare TimeSeriesChart
|
||||
* (BurnDownChart's own stat row above its chart) — omitted, this renders
|
||||
* TimeSeriesChart directly from `labels`/`datasets`/etc. `#header-extra`
|
||||
* adds header content beyond title/description (e.g. a per-card control)
|
||||
* without needing the caller to rebuild CardHeader itself.
|
||||
*
|
||||
* `showEmpty` (default false, opt-in) is the ONLY thing that turns
|
||||
* `state === 'empty'` into a distinct EmptyState render instead of falling
|
||||
* through to the ready branch (the default slot, or the bare
|
||||
* TimeSeriesChart). None of today's call sites had an "empty" concept
|
||||
* before this component existed — they always rendered their chart (or,
|
||||
* for BurnDownChart, its stat row above the chart) for any non-skeleton,
|
||||
* non-error state, even with zero data points. Defaulting `showEmpty` to
|
||||
* false keeps that exact behaviour; a future card that genuinely wants
|
||||
* "No data for this range." text can opt in per-instance.
|
||||
*
|
||||
* `bare` (true) skips the Card/CardHeader/CardTitle chrome entirely,
|
||||
* rendering only the state-branch content — SpendPage's breakdown chart
|
||||
* has its own bespoke header (Tabs, a metric Select, a running total) and,
|
||||
* today, no Card wrapper at all around the chart; forcing one on would be
|
||||
* a visible layout change this refactor must not make (behaviour-
|
||||
* preserving rule), so `bare` lets it reuse the skeleton/error/ready
|
||||
* branch without the surrounding card border/padding.
|
||||
*/
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
title?: string
|
||||
description?: string
|
||||
state: LoadState
|
||||
error?: string
|
||||
onRetry?: () => void | Promise<void>
|
||||
emptyTitle?: string
|
||||
emptyDescription?: string
|
||||
/** Opt-in: renders EmptyState instead of the ready branch when `state === 'empty'` — see this component's own doc comment. Defaults to false (behaviour-preserving: 'empty' falls through to ready everywhere until a caller explicitly asks for the distinct empty render). */
|
||||
showEmpty?: boolean
|
||||
bare?: boolean
|
||||
/** Omit when this ChartCard is only ever used in a non-'ready' state (e.g. one of the 4 skeleton-only loading cards below) — never read outside the 'ready' branch. */
|
||||
labels?: string[]
|
||||
datasets?: TimeSeriesDataset[]
|
||||
comparisonDatasets?: TimeSeriesComparisonDataset[]
|
||||
stacked?: boolean
|
||||
valueFormatter?: (value: number) => string
|
||||
/** Required whenever `state` can reach 'ready' with the default TimeSeriesChart body (TimeSeriesChart's own ariaLabel doc comment: no safe generic default) — optional here only so a skeleton-only ChartCard is not forced to pass a meaningless placeholder. */
|
||||
ariaLabel?: string
|
||||
}>(),
|
||||
{
|
||||
description: undefined,
|
||||
error: '',
|
||||
onRetry: undefined,
|
||||
emptyTitle: 'No data for this range.',
|
||||
emptyDescription: undefined,
|
||||
showEmpty: false,
|
||||
bare: false,
|
||||
labels: () => [],
|
||||
datasets: () => [],
|
||||
comparisonDatasets: () => [],
|
||||
stacked: false,
|
||||
valueFormatter: formatExactInt,
|
||||
ariaLabel: '',
|
||||
},
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-if="bare">
|
||||
<SkeletonChart v-if="state === 'skeleton'" />
|
||||
<ErrorState v-else-if="state === 'error'" :message="error" :on-retry="onRetry" />
|
||||
<EmptyState v-else-if="state === 'empty' && showEmpty" :title="emptyTitle" :description="emptyDescription" />
|
||||
<slot v-else>
|
||||
<TimeSeriesChart
|
||||
:labels="labels"
|
||||
:datasets="datasets"
|
||||
:comparison-datasets="comparisonDatasets"
|
||||
:stacked="stacked"
|
||||
:value-formatter="valueFormatter"
|
||||
:ariaLabel="ariaLabel"
|
||||
/>
|
||||
</slot>
|
||||
</template>
|
||||
<Card v-else>
|
||||
<CardHeader>
|
||||
<CardTitle>{{ title }}</CardTitle>
|
||||
<CardDescription v-if="description">{{ description }}</CardDescription>
|
||||
<slot name="header-extra" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<SkeletonChart v-if="state === 'skeleton'" />
|
||||
<ErrorState v-else-if="state === 'error'" :message="error" :on-retry="onRetry" />
|
||||
<EmptyState v-else-if="state === 'empty' && showEmpty" :title="emptyTitle" :description="emptyDescription" />
|
||||
<slot v-else>
|
||||
<TimeSeriesChart
|
||||
:labels="labels"
|
||||
:datasets="datasets"
|
||||
:comparison-datasets="comparisonDatasets"
|
||||
:stacked="stacked"
|
||||
:value-formatter="valueFormatter"
|
||||
:ariaLabel="ariaLabel"
|
||||
/>
|
||||
</slot>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -3,30 +3,32 @@ import type { SortingState } from '@tanstack/vue-table'
|
||||
import { getCoreRowModel, getSortedRowModel, useVueTable } from '@tanstack/vue-table'
|
||||
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
|
||||
|
||||
import BudgetRatioBars from '@/components/BudgetRatioBars.vue'
|
||||
import CompactNumber from '@/components/CompactNumber.vue'
|
||||
import CostForecastCard from '@/components/CostForecastCard.vue'
|
||||
import CsvExportButton from '@/components/CsvExportButton.vue'
|
||||
import DetailField from '@/components/DetailField.vue'
|
||||
import EmptyState from '@/components/EmptyState.vue'
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import LoadStateView from '@/components/LoadStateView.vue'
|
||||
import ModelChip from '@/components/ModelChip.vue'
|
||||
import SearchInput from '@/components/SearchInput.vue'
|
||||
import SkeletonList from '@/components/SkeletonList.vue'
|
||||
import SkeletonTable from '@/components/SkeletonTable.vue'
|
||||
import SortHeaderButton from '@/components/SortHeaderButton.vue'
|
||||
import StatItem from '@/components/StatItem.vue'
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { valueUpdater } from '@/components/ui/table'
|
||||
import UsageBar from '@/components/UsageBar.vue'
|
||||
import UsageTable from '@/components/UsageTable.vue'
|
||||
import { useNow } from '@/composables/useNow'
|
||||
import { useSearchQuery } from '@/composables/useSearchQuery'
|
||||
import { headroom, monthProgress, projectMonthEnd } from '@/lib/forecast'
|
||||
import { formatCost, formatExactInt, formatLimits } from '@/lib/format'
|
||||
import { monthCostProjection, NOT_ENOUGH_DATA, WILL_EXCEED_TITLE } from '@/lib/forecast'
|
||||
import { formatCost, formatLimits } from '@/lib/format'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { type ExpandState, clearExpandOverrides, computeExpandedItems, toggleItemExpand } from '@/lib/search-expand'
|
||||
import { BUDGET_RATIO_LABEL, type BudgetRatio, budgetRatios } from '@/lib/usage-bars'
|
||||
import { budgetRatios } from '@/lib/usage-bars'
|
||||
import { usageColumns } from '@/lib/usage-columns'
|
||||
import { usageCsv } from '@/lib/usage-csv'
|
||||
import { groupMatches, groupNameMatches, matchingMembersOfGroup, membersOfGroup, userMatches } from '@/lib/usage-search'
|
||||
@@ -227,19 +229,30 @@ function isGlobPattern(entry: string): boolean {
|
||||
return /[*?[]/.test(entry)
|
||||
}
|
||||
|
||||
/** budgetValueText renders one BudgetRatio's "used / limit" detail text (UsageBar's aria-valuetext/title). */
|
||||
function budgetValueText(ratio: BudgetRatio): string {
|
||||
if (ratio.id.startsWith('cost')) return `${formatCost(ratio.used)} / ${formatCost(ratio.limit)}`
|
||||
return `${formatExactInt(ratio.used)} / ${formatExactInt(ratio.limit)}`
|
||||
}
|
||||
|
||||
/** groupCostProjection mirrors usage-columns.ts's own costMonthProjColumn math for one group row. */
|
||||
/** groupCostProjection renders lib/forecast.ts's shared monthCostProjection (reuse-audit.md F7) for one group row as display text. */
|
||||
function groupCostProjection(entry: AdminUsageEntryView, now: Date): { text: string; willExceed: boolean } {
|
||||
const elapsedFraction = monthProgress(now)
|
||||
const projected = projectMonthEnd(entry.costPerMonthMicroUsd, elapsedFraction)
|
||||
if (projected === null) return { text: 'not enough data yet', willExceed: false }
|
||||
return { text: formatCost(projected), willExceed: headroom(projected, entry.limits?.costPerMonthUSD).willExceed }
|
||||
const projection = monthCostProjection(entry, now)
|
||||
return { text: projection.micros === null ? NOT_ENOUGH_DATA : formatCost(projection.micros), willExceed: projection.willExceed }
|
||||
}
|
||||
/**
|
||||
* GROUP_DETAIL_FIELDS (reuse-audit.md F6) drives the group accordion's 4
|
||||
* uniform "storeDown ? '?' : <CompactNumber>" detail fields with one
|
||||
* v-for instead of four hand-rolled DetailField copies — the same label/
|
||||
* accessor pairs lib/usage-columns.ts's own numericColumn calls already
|
||||
* name for these exact ids (tokInDay, tokOutDay, tokInMonth, tokOutMonth).
|
||||
* req/min and rejected/day are rendered explicitly, ahead of this v-for,
|
||||
* to keep the HEAD field order (rejected/day also needs its own
|
||||
* conditional destructive-tone class). Not the ColumnDef objects
|
||||
* themselves: a TanStack ColumnDef's `cell` needs a full CellContext
|
||||
* (row/column/table) to render, which this plain `dl` grid — driven by
|
||||
* `row.original` alone, no table instance — has no reason to construct.
|
||||
*/
|
||||
const GROUP_DETAIL_FIELDS: { label: string; read: (entry: AdminUsageEntryView) => number }[] = [
|
||||
{ label: 'tokIn/day', read: (e) => e.tokensInPerDay },
|
||||
{ label: 'tokOut/day', read: (e) => e.tokensOutPerDay },
|
||||
{ label: 'tokIn/month', read: (e) => e.tokensInPerMonth },
|
||||
{ label: 'tokOut/month', read: (e) => e.tokensOutPerMonth },
|
||||
]
|
||||
|
||||
// --- CSV export ---
|
||||
const usersColumns = computed(() => usageColumns('Name', 'Group', groupNameOf, now.value, sourceOf))
|
||||
@@ -289,28 +302,13 @@ function groupsCsv(): string {
|
||||
<CardDescription>Usage summed across every user and group combined.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-5">
|
||||
<div>
|
||||
<p class="text-muted-foreground">Requests/day</p>
|
||||
<p class="text-lg font-semibold tabular-nums"><CompactNumber :value="usage.total.requestsPerDay" /></p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-muted-foreground">Rejected/day</p>
|
||||
<p class="text-lg font-semibold tabular-nums" :class="usage.total.rejectionsPerDay > 0 ? 'text-destructive' : undefined">
|
||||
<CompactNumber :value="usage.total.rejectionsPerDay" />
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-muted-foreground">Tokens in/day</p>
|
||||
<p class="text-lg font-semibold tabular-nums"><CompactNumber :value="usage.total.tokensInPerDay" /></p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-muted-foreground">Tokens out/day</p>
|
||||
<p class="text-lg font-semibold tabular-nums"><CompactNumber :value="usage.total.tokensOutPerDay" /></p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-muted-foreground">Cost/day</p>
|
||||
<p class="text-lg font-semibold tabular-nums">{{ formatCost(usage.total.costPerDayMicroUsd) }}</p>
|
||||
</div>
|
||||
<StatItem label="Requests/day"><CompactNumber :value="usage.total.requestsPerDay" /></StatItem>
|
||||
<StatItem label="Rejected/day" :tone="usage.total.rejectionsPerDay > 0 ? 'destructive' : 'default'">
|
||||
<CompactNumber :value="usage.total.rejectionsPerDay" />
|
||||
</StatItem>
|
||||
<StatItem label="Tokens in/day"><CompactNumber :value="usage.total.tokensInPerDay" /></StatItem>
|
||||
<StatItem label="Tokens out/day"><CompactNumber :value="usage.total.tokensOutPerDay" /></StatItem>
|
||||
<StatItem label="Cost/day">{{ formatCost(usage.total.costPerDayMicroUsd) }}</StatItem>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -354,145 +352,90 @@ function groupsCsv(): string {
|
||||
</div>
|
||||
<AccordionContent>
|
||||
<dl class="mb-3 grid grid-cols-2 gap-x-6 gap-y-1.5 text-sm sm:grid-cols-4">
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground" :title="GLOB_HINT">Providers</dt>
|
||||
<dd>
|
||||
<div v-if="row.original.providers?.length" class="flex flex-wrap gap-1.5">
|
||||
<Badge
|
||||
v-for="providerName in row.original.providers"
|
||||
:key="providerName"
|
||||
as="span"
|
||||
variant="secondary"
|
||||
class="max-w-full truncate font-mono font-normal"
|
||||
:title="providerName"
|
||||
>
|
||||
{{ providerName }}
|
||||
</Badge>
|
||||
</div>
|
||||
<span v-else class="text-muted-foreground">All providers</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground" :title="GLOB_HINT">Models</dt>
|
||||
<dd>
|
||||
<div v-if="row.original.models?.length" class="flex flex-wrap gap-1.5">
|
||||
<template v-for="modelId in row.original.models" :key="modelId">
|
||||
<ModelChip v-if="!isGlobPattern(modelId)" :id="modelId" />
|
||||
<Badge v-else as="span" variant="secondary" class="max-w-full truncate font-mono font-normal" :title="modelId">{{ modelId }}</Badge>
|
||||
</template>
|
||||
</div>
|
||||
<span v-else class="text-muted-foreground">All models</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground" :title="GLOB_HINT">MCP servers</dt>
|
||||
<dd>
|
||||
<div v-if="row.original.mcpServers?.length" class="flex flex-wrap gap-1.5">
|
||||
<Badge
|
||||
v-for="serverName in row.original.mcpServers"
|
||||
:key="serverName"
|
||||
as="span"
|
||||
variant="secondary"
|
||||
class="max-w-full truncate font-mono font-normal"
|
||||
:title="serverName"
|
||||
>
|
||||
{{ serverName }}
|
||||
</Badge>
|
||||
</div>
|
||||
<span v-else class="text-muted-foreground">All MCP servers</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground" :title="GLOB_HINT">Agents</dt>
|
||||
<dd>
|
||||
<div v-if="row.original.agents?.length" class="flex flex-wrap gap-1.5">
|
||||
<Badge
|
||||
v-for="agentName in row.original.agents"
|
||||
:key="agentName"
|
||||
as="span"
|
||||
variant="secondary"
|
||||
class="max-w-full truncate font-mono font-normal"
|
||||
:title="agentName"
|
||||
>
|
||||
{{ agentName }}
|
||||
</Badge>
|
||||
</div>
|
||||
<span v-else class="text-muted-foreground">All agents</span>
|
||||
</dd>
|
||||
</div>
|
||||
<DetailField label="Providers" :label-title="GLOB_HINT">
|
||||
<div v-if="row.original.providers?.length" class="flex flex-wrap gap-1.5">
|
||||
<Badge
|
||||
v-for="providerName in row.original.providers"
|
||||
:key="providerName"
|
||||
as="span"
|
||||
variant="secondary"
|
||||
class="max-w-full truncate font-mono font-normal"
|
||||
:title="providerName"
|
||||
>
|
||||
{{ providerName }}
|
||||
</Badge>
|
||||
</div>
|
||||
<span v-else class="text-muted-foreground">All providers</span>
|
||||
</DetailField>
|
||||
<DetailField label="Models" :label-title="GLOB_HINT">
|
||||
<div v-if="row.original.models?.length" class="flex flex-wrap gap-1.5">
|
||||
<template v-for="modelId in row.original.models" :key="modelId">
|
||||
<ModelChip v-if="!isGlobPattern(modelId)" :id="modelId" />
|
||||
<Badge v-else as="span" variant="secondary" class="max-w-full truncate font-mono font-normal" :title="modelId">{{ modelId }}</Badge>
|
||||
</template>
|
||||
</div>
|
||||
<span v-else class="text-muted-foreground">All models</span>
|
||||
</DetailField>
|
||||
<DetailField label="MCP servers" :label-title="GLOB_HINT">
|
||||
<div v-if="row.original.mcpServers?.length" class="flex flex-wrap gap-1.5">
|
||||
<Badge
|
||||
v-for="serverName in row.original.mcpServers"
|
||||
:key="serverName"
|
||||
as="span"
|
||||
variant="secondary"
|
||||
class="max-w-full truncate font-mono font-normal"
|
||||
:title="serverName"
|
||||
>
|
||||
{{ serverName }}
|
||||
</Badge>
|
||||
</div>
|
||||
<span v-else class="text-muted-foreground">All MCP servers</span>
|
||||
</DetailField>
|
||||
<DetailField label="Agents" :label-title="GLOB_HINT">
|
||||
<div v-if="row.original.agents?.length" class="flex flex-wrap gap-1.5">
|
||||
<Badge
|
||||
v-for="agentName in row.original.agents"
|
||||
:key="agentName"
|
||||
as="span"
|
||||
variant="secondary"
|
||||
class="max-w-full truncate font-mono font-normal"
|
||||
:title="agentName"
|
||||
>
|
||||
{{ agentName }}
|
||||
</Badge>
|
||||
</div>
|
||||
<span v-else class="text-muted-foreground">All agents</span>
|
||||
</DetailField>
|
||||
</dl>
|
||||
<dl class="mb-3 grid grid-cols-2 gap-x-6 gap-y-1.5 text-sm sm:grid-cols-4">
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground">Limits</dt>
|
||||
<dd>{{ formatLimits(row.original.limits) }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground">req/min</dt>
|
||||
<dd class="tabular-nums">
|
||||
<template v-if="row.original.storeDown">?</template>
|
||||
<CompactNumber v-else :value="row.original.requestsPerMinute" />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground">rejected/day</dt>
|
||||
<dd class="tabular-nums" :class="!row.original.storeDown && row.original.rejectionsPerDay > 0 ? 'text-destructive' : undefined">
|
||||
<template v-if="row.original.storeDown">?</template>
|
||||
<CompactNumber v-else :value="row.original.rejectionsPerDay" />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground">tokIn/day</dt>
|
||||
<dd class="tabular-nums">
|
||||
<template v-if="row.original.storeDown">?</template>
|
||||
<CompactNumber v-else :value="row.original.tokensInPerDay" />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground">tokOut/day</dt>
|
||||
<dd class="tabular-nums">
|
||||
<template v-if="row.original.storeDown">?</template>
|
||||
<CompactNumber v-else :value="row.original.tokensOutPerDay" />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground">tokIn/month</dt>
|
||||
<dd class="tabular-nums">
|
||||
<template v-if="row.original.storeDown">?</template>
|
||||
<CompactNumber v-else :value="row.original.tokensInPerMonth" />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground">tokOut/month</dt>
|
||||
<dd class="tabular-nums">
|
||||
<template v-if="row.original.storeDown">?</template>
|
||||
<CompactNumber v-else :value="row.original.tokensOutPerMonth" />
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground">cost/month</dt>
|
||||
<dd class="tabular-nums">{{ row.original.storeDown ? '?' : formatCost(row.original.costPerMonthMicroUsd) }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground">cost/month (proj.)</dt>
|
||||
<dd
|
||||
class="tabular-nums"
|
||||
:class="!row.original.storeDown && groupCostProjection(row.original, now).willExceed ? 'text-destructive' : undefined"
|
||||
:title="!row.original.storeDown && groupCostProjection(row.original, now).willExceed ? 'Projected to exceed the configured cost/month limit' : undefined"
|
||||
>
|
||||
{{ row.original.storeDown ? '?' : groupCostProjection(row.original, now).text }}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div v-if="budgetRatios(row.original).length" class="mb-3 flex flex-wrap items-center gap-x-4 gap-y-1.5">
|
||||
<span
|
||||
v-for="ratio in budgetRatios(row.original)"
|
||||
:key="ratio.id"
|
||||
class="inline-flex items-center gap-1.5 text-xs text-muted-foreground"
|
||||
<DetailField label="Limits">{{ formatLimits(row.original.limits) }}</DetailField>
|
||||
<DetailField label="req/min" numeric>
|
||||
<template v-if="row.original.storeDown">?</template>
|
||||
<CompactNumber v-else :value="row.original.requestsPerMinute" />
|
||||
</DetailField>
|
||||
<DetailField
|
||||
label="rejected/day"
|
||||
numeric
|
||||
:class="!row.original.storeDown && row.original.rejectionsPerDay > 0 ? 'text-destructive' : undefined"
|
||||
>
|
||||
{{ BUDGET_RATIO_LABEL[ratio.id] }}
|
||||
<UsageBar :ratio="ratio.ratio" :label="BUDGET_RATIO_LABEL[ratio.id]" :value-text="budgetValueText(ratio)" />
|
||||
</span>
|
||||
</div>
|
||||
<template v-if="row.original.storeDown">?</template>
|
||||
<CompactNumber v-else :value="row.original.rejectionsPerDay" />
|
||||
</DetailField>
|
||||
<DetailField v-for="field in GROUP_DETAIL_FIELDS" :key="field.label" :label="field.label" numeric>
|
||||
<template v-if="row.original.storeDown">?</template>
|
||||
<CompactNumber v-else :value="field.read(row.original)" />
|
||||
</DetailField>
|
||||
<DetailField label="cost/month" numeric>{{ row.original.storeDown ? '?' : formatCost(row.original.costPerMonthMicroUsd) }}</DetailField>
|
||||
<DetailField
|
||||
label="cost/month (proj.)"
|
||||
numeric
|
||||
:class="!row.original.storeDown && groupCostProjection(row.original, now).willExceed ? 'text-destructive' : undefined"
|
||||
:title="!row.original.storeDown && groupCostProjection(row.original, now).willExceed ? WILL_EXCEED_TITLE : undefined"
|
||||
>
|
||||
{{ row.original.storeDown ? '?' : groupCostProjection(row.original, now).text }}
|
||||
</DetailField>
|
||||
</dl>
|
||||
<BudgetRatioBars v-if="budgetRatios(row.original).length" class="mb-3" :ratios="budgetRatios(row.original)" />
|
||||
<p class="mb-1.5 text-xs font-medium text-muted-foreground">Members</p>
|
||||
<UsageTable
|
||||
id-label="Name"
|
||||
@@ -508,7 +451,7 @@ function groupsCsv(): string {
|
||||
<EmptyState v-else-if="noGroupsConfigured" title="No groups configured." description="Grant a group access from the Config page's change helper.">
|
||||
<Button type="button" variant="outline" size="sm" @click="nav.goTo('config', { helper: 'grant' })">Open change helper</Button>
|
||||
</EmptyState>
|
||||
<p v-else class="py-6 text-center text-sm text-muted-foreground">{{ groupsEmptyMessage }}</p>
|
||||
<EmptyState v-else :title="groupsEmptyMessage" />
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -524,19 +467,18 @@ function groupsCsv(): string {
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<SkeletonTable v-if="dashboardLoadState === 'skeleton'" :rows="5" :cols="5" />
|
||||
<ErrorState v-else-if="dashboardLoadState === 'error'" :message="dashboard.error" :on-retry="dashboard.refresh" />
|
||||
<UsageTable
|
||||
v-else
|
||||
id-label="Name"
|
||||
secondary-column-label="Group"
|
||||
:entries="filteredUsers"
|
||||
:secondary-value="groupNameOf"
|
||||
:empty-message="usersEmptyMessage"
|
||||
:now="now"
|
||||
:source-value="sourceOf"
|
||||
v-model:sorting="usersSorting"
|
||||
/>
|
||||
<LoadStateView :state="dashboardLoadState" :error="dashboard.error" :on-retry="dashboard.refresh" skeleton="table" :rows="5" :cols="5">
|
||||
<UsageTable
|
||||
id-label="Name"
|
||||
secondary-column-label="Group"
|
||||
:entries="filteredUsers"
|
||||
:secondary-value="groupNameOf"
|
||||
:empty-message="usersEmptyMessage"
|
||||
:now="now"
|
||||
:source-value="sourceOf"
|
||||
v-model:sorting="usersSorting"
|
||||
/>
|
||||
</LoadStateView>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import LabeledSelect from '@/components/LabeledSelect.vue'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { costAvoidedMicros, freeRows, pickReferenceModel } from '@/lib/cost-avoided'
|
||||
import { formatCost } from '@/lib/format'
|
||||
import type { AdminCatalogModel, AdminUsageModelEntry } from '@/types/api'
|
||||
@@ -81,6 +81,8 @@ const priceableOptions = computed<{ id: string; requests: number }[]>(() => {
|
||||
return out.sort((a, b) => b.requests - a.requests)
|
||||
})
|
||||
|
||||
const referenceOptions = computed(() => priceableOptions.value.map((opt) => ({ value: opt.id, label: opt.id })))
|
||||
|
||||
const defaultReference = computed<string | null>(() => pickReferenceModel(props.models, props.catalog))
|
||||
const effectiveReference = computed<string | null>(() => props.refModel || defaultReference.value)
|
||||
const referenceCatalog = computed<AdminCatalogModel | undefined>(() =>
|
||||
@@ -111,17 +113,15 @@ function onReferenceUpdate(value: unknown): void {
|
||||
<CardTitle>Cost avoided</CardTitle>
|
||||
<CardDescription>What free-tier traffic in range would have cost at a real model's own rates.</CardDescription>
|
||||
</div>
|
||||
<div v-if="priceableOptions.length > 0" class="flex flex-col gap-1">
|
||||
<label id="cost-avoided-ref-label" class="text-xs font-medium text-muted-foreground">Reference model</label>
|
||||
<Select :model-value="effectiveReference ?? undefined" @update:model-value="onReferenceUpdate">
|
||||
<SelectTrigger aria-labelledby="cost-avoided-ref-label" class="w-56">
|
||||
<SelectValue placeholder="Pick a reference model" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="opt in priceableOptions" :key="opt.id" :value="opt.id">{{ opt.id }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<LabeledSelect
|
||||
v-if="priceableOptions.length > 0"
|
||||
label="Reference model"
|
||||
:model-value="effectiveReference ?? ''"
|
||||
:options="referenceOptions"
|
||||
placeholder="Pick a reference model"
|
||||
trigger-class="w-56"
|
||||
@update:model-value="onReferenceUpdate"
|
||||
/>
|
||||
</CardHeader>
|
||||
<CardContent class="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import StatItem from '@/components/StatItem.vue'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { headroom, monthProgress, projectMonthEnd } from '@/lib/forecast'
|
||||
import { headroom, monthProgress, NOT_ENOUGH_DATA, projectMonthEnd, WILL_EXCEED_TITLE } from '@/lib/forecast'
|
||||
import { formatCost } from '@/lib/format'
|
||||
import type { LimitsConfig } from '@/types/api'
|
||||
|
||||
@@ -53,26 +54,16 @@ const forecast = computed(() => headroom(projectedMicros.value, props.limits?.co
|
||||
<CardDescription>Projected month-end spend, extrapolated from month-to-date usage (UTC calendar month).</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-3">
|
||||
<div>
|
||||
<p class="text-muted-foreground">Month to date</p>
|
||||
<p class="text-lg font-semibold tabular-nums">{{ formatCost(mtdMicros) }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-muted-foreground">Projected month-end</p>
|
||||
<p v-if="projectedMicros === null" class="text-sm text-muted-foreground">not enough data yet</p>
|
||||
<p
|
||||
v-else
|
||||
class="text-lg font-semibold tabular-nums"
|
||||
:class="forecast.willExceed ? 'text-destructive' : undefined"
|
||||
:title="forecast.willExceed ? 'Projected to exceed the configured cost/month limit' : undefined"
|
||||
>
|
||||
{{ formatCost(projectedMicros) }}
|
||||
</p>
|
||||
</div>
|
||||
<div v-if="forecast.limitMicros !== null">
|
||||
<p class="text-muted-foreground">Limit</p>
|
||||
<p class="text-lg font-semibold tabular-nums">{{ formatCost(forecast.limitMicros) }}</p>
|
||||
</div>
|
||||
<StatItem label="Month to date">{{ formatCost(mtdMicros) }}</StatItem>
|
||||
<StatItem
|
||||
label="Projected month-end"
|
||||
:tone="forecast.willExceed ? 'destructive' : 'default'"
|
||||
:title="forecast.willExceed ? WILL_EXCEED_TITLE : undefined"
|
||||
:hint="projectedMicros === null ? NOT_ENOUGH_DATA : undefined"
|
||||
>
|
||||
{{ projectedMicros === null ? '' : formatCost(projectedMicros) }}
|
||||
</StatItem>
|
||||
<StatItem v-if="forecast.limitMicros !== null" label="Limit">{{ formatCost(forecast.limitMicros) }}</StatItem>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* DetailField (reuse-audit.md F6) is the ONE `dt`/`dd` detail-field pair
|
||||
* every accordion/expanded-row detail grid in this panel used to hand-
|
||||
* roll: a small muted `dt` label (`labelTitle` for a hint on the LABEL
|
||||
* itself, e.g. the glob-pattern hint on a group's Providers/Models/MCP
|
||||
* servers/Agents fields) and a `dd` for the value (default slot) —
|
||||
* `numeric` adds `tabular-nums` to the `dd` for a figure that should align
|
||||
* in a monospaced-digit grid. `inheritAttrs: false` + `v-bind="$attrs"` on
|
||||
* the `dd` (not the root `div`) forwards any other attribute a caller
|
||||
* passes straight onto the VALUE element — a conditional `class` (e.g. a
|
||||
* destructive rejected-count) or `title` (e.g. a "projected to exceed"
|
||||
* tooltip) lands on the same element it did before this extraction, never
|
||||
* on the label.
|
||||
*/
|
||||
defineOptions({ inheritAttrs: false })
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
label: string
|
||||
labelTitle?: string
|
||||
numeric?: boolean
|
||||
}>(),
|
||||
{ labelTitle: undefined, numeric: false },
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground" :title="labelTitle">{{ label }}</dt>
|
||||
<dd v-bind="$attrs" :class="numeric ? 'tabular-nums' : undefined">
|
||||
<slot />
|
||||
</dd>
|
||||
</div>
|
||||
</template>
|
||||
@@ -2,9 +2,9 @@
|
||||
import { faArrowRightArrowLeft } from '@fortawesome/free-solid-svg-icons'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
import LabeledSelect from '@/components/LabeledSelect.vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { SCOPE_PATTERN } from '@/lib/hash-state'
|
||||
import { RANGE_KEYS } from '@/lib/range'
|
||||
import type { RangeKey } from '@/lib/range'
|
||||
@@ -21,6 +21,7 @@ const RANGE_LABEL: Record<RangeKey, string> = {
|
||||
'6mo': 'Last 6 months',
|
||||
'12mo': 'Last 12 months',
|
||||
}
|
||||
const RANGE_OPTIONS = RANGE_KEYS.map((key) => ({ value: key, label: RANGE_LABEL[key] }))
|
||||
|
||||
/**
|
||||
* GlobalFilterBar (redesign-plan.md section 3.1) is the shell's one
|
||||
@@ -94,17 +95,7 @@ function commitScope(): void {
|
||||
|
||||
<template>
|
||||
<div class="flex flex-wrap items-end gap-3">
|
||||
<div class="flex flex-col gap-1">
|
||||
<label id="global-filter-range-label" class="text-xs font-medium text-muted-foreground">Range</label>
|
||||
<Select :model-value="filters.range" @update:model-value="onRangeUpdate">
|
||||
<SelectTrigger aria-labelledby="global-filter-range-label" class="w-36">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="key in RANGE_KEYS" :key="key" :value="key">{{ RANGE_LABEL[key] }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<LabeledSelect label="Range" :model-value="filters.range" :options="RANGE_OPTIONS" trigger-class="w-36" @update:model-value="onRangeUpdate" />
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, useId } from 'vue'
|
||||
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
|
||||
export interface LabeledSelectOption {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
/**
|
||||
* LabeledSelect (reuse-audit.md F11) is the ONE "label above a Select,
|
||||
* wired via aria-labelledby" block this panel used to hand-roll at every
|
||||
* filter/target picker (GlobalFilterBar's Range, CostAvoidedCard's
|
||||
* reference model, SpendPage's Metric, ReliabilityPage's Provider,
|
||||
* UserForm's Primary group). `allLabel`, when set, injects an "All X"
|
||||
* option and maps it to/from `modelValue === ''` internally — Radix/
|
||||
* reka-ui Select items cannot hold an empty-string value themselves
|
||||
* (EventsView.vue's/ReliabilityPage.vue's own identical ALL_KINDS/
|
||||
* ALL_PROVIDERS_OPTION doc comments), so every "All" filter used to
|
||||
* re-implement this same sentinel swap at its own template boundary.
|
||||
* Omit `allLabel` for a plain required-selection picker with no "All"
|
||||
* concept (UserForm's Primary group, CostAvoidedCard's reference model).
|
||||
*/
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
label: string
|
||||
modelValue: string
|
||||
options: LabeledSelectOption[]
|
||||
allLabel?: string
|
||||
placeholder?: string
|
||||
triggerClass?: string
|
||||
}>(),
|
||||
{ allLabel: undefined, placeholder: undefined, triggerClass: undefined },
|
||||
)
|
||||
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: string] }>()
|
||||
|
||||
/** ALL_SENTINEL is LabeledSelect's own internal Select-only stand-in for modelValue === '' — never exposed to a caller, which only ever sees '' itself via v-model. */
|
||||
const ALL_SENTINEL = '__all__'
|
||||
|
||||
const labelId = `labeled-select-${useId()}`
|
||||
|
||||
const selectValue = computed(() => (props.modelValue === '' && props.allLabel !== undefined ? ALL_SENTINEL : props.modelValue))
|
||||
|
||||
function onUpdate(value: unknown): void {
|
||||
if (typeof value !== 'string') return
|
||||
emit('update:modelValue', value === ALL_SENTINEL ? '' : value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-1">
|
||||
<label :id="labelId" class="text-xs font-medium text-muted-foreground">{{ label }}</label>
|
||||
<Select :model-value="selectValue" @update:model-value="onUpdate">
|
||||
<SelectTrigger :aria-labelledby="labelId" :class="triggerClass">
|
||||
<SelectValue :placeholder="placeholder" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-if="allLabel !== undefined" :value="ALL_SENTINEL">{{ allLabel }}</SelectItem>
|
||||
<SelectItem v-for="opt in options" :key="opt.value" :value="opt.value">{{ opt.label }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,68 @@
|
||||
<script setup lang="ts">
|
||||
import type { IconDefinition } from '@fortawesome/free-solid-svg-icons'
|
||||
|
||||
import EmptyState from '@/components/EmptyState.vue'
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import SkeletonChart from '@/components/SkeletonChart.vue'
|
||||
import SkeletonList from '@/components/SkeletonList.vue'
|
||||
import SkeletonTable from '@/components/SkeletonTable.vue'
|
||||
import type { LoadState } from '@/lib/load-state'
|
||||
|
||||
/**
|
||||
* LoadStateView (reuse-audit.md F2) is the ONE skeleton/error/(empty)/ready
|
||||
* state branch for a list/table card with no Card wrapper of its own
|
||||
* opinions (ChartCard.vue is this same idea for a chart card) — TargetCallers,
|
||||
* HomePage's Latest-events card, and PricingHealthTable each used to
|
||||
* hand-roll this identical `v-if="state==='skeleton'" / v-else-if=
|
||||
* "state==='error'" / v-else-if="<own empty boolean>" / v-else` chain.
|
||||
* `state` decides skeleton/error/ready; the 'empty' branch is opt-in only —
|
||||
* it renders when the caller passes `empty: true` explicitly, never merely
|
||||
* because `state === 'empty'`. Every pre-existing call site already derived
|
||||
* its own "nothing to show" from its own data length (e.g. a settled fetch
|
||||
* that came back with zero rows), exactly like their old hand-rolled
|
||||
* chains did — `state === 'empty'` alone (no data ever loaded, not
|
||||
* loading, no error) must fall through to the ready branch (`v-else`), so
|
||||
* a caller that reaches this component only for its own
|
||||
* table/list-with-empty-message body (e.g. UsageTable, DataTable) keeps
|
||||
* rendering that body — and that body's own empty-message — unchanged,
|
||||
* instead of losing it to a generic "Nothing to show." here. `#empty`
|
||||
* overrides the default EmptyState entirely (TryLongerRangeButton, a
|
||||
* custom icon) when a plain title/description is not enough.
|
||||
*/
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
state: LoadState
|
||||
error?: string
|
||||
onRetry?: () => void | Promise<void>
|
||||
skeleton: 'table' | 'list' | 'chart'
|
||||
rows?: number
|
||||
cols?: number
|
||||
/** The ONLY switch for the empty branch — see this component's own doc comment. `state === 'empty'` alone never triggers it. */
|
||||
empty?: boolean
|
||||
emptyIcon?: IconDefinition
|
||||
emptyTitle?: string
|
||||
emptyDescription?: string
|
||||
}>(),
|
||||
{
|
||||
error: '',
|
||||
onRetry: undefined,
|
||||
rows: 5,
|
||||
cols: 4,
|
||||
empty: false,
|
||||
emptyIcon: undefined,
|
||||
emptyTitle: 'Nothing to show.',
|
||||
emptyDescription: undefined,
|
||||
},
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<SkeletonTable v-if="state === 'skeleton' && skeleton === 'table'" :rows="rows" :cols="cols" />
|
||||
<SkeletonList v-else-if="state === 'skeleton' && skeleton === 'list'" :rows="rows" />
|
||||
<SkeletonChart v-else-if="state === 'skeleton'" />
|
||||
<ErrorState v-else-if="state === 'error'" :message="error" :on-retry="onRetry" />
|
||||
<slot v-else-if="empty" name="empty">
|
||||
<EmptyState :icon="emptyIcon" :title="emptyTitle" :description="emptyDescription" />
|
||||
</slot>
|
||||
<slot v-else />
|
||||
</template>
|
||||
@@ -6,14 +6,12 @@ import EmptyState from '@/components/EmptyState.vue'
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import SearchInput from '@/components/SearchInput.vue'
|
||||
import SkeletonTable from '@/components/SkeletonTable.vue'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import StatDisabledAlert from '@/components/StatDisabledAlert.vue'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { filterModelRows } from '@/lib/model-filter'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { modelCatalogColumns } from '@/lib/model-table-columns'
|
||||
import type { ModelCatalogRow } from '@/lib/model-table-columns'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
/**
|
||||
* ModelCatalogTable (redesign-plan.md section 3.4, Models & providers
|
||||
@@ -41,8 +39,6 @@ const props = defineProps<{
|
||||
|
||||
const emit = defineEmits<{ 'update:query': [value: string] }>()
|
||||
|
||||
const nav = useNavStore()
|
||||
|
||||
const filtered = computed<ModelCatalogRow[]>(() => filterModelRows(props.rows, props.query))
|
||||
|
||||
const columns = modelCatalogColumns()
|
||||
@@ -82,13 +78,12 @@ const emptyMessage = computed<string>(() => {
|
||||
/>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-3">
|
||||
<Alert v-if="!latencyEnabled" variant="warn">
|
||||
<AlertTitle>Latency statistics are off</AlertTitle>
|
||||
<AlertDescription class="flex flex-wrap items-center gap-2">
|
||||
<span>Enable <code>admin.stats.latency</code> in the middleware config to see fleet p50/p95.</span>
|
||||
<Button type="button" variant="outline" size="sm" @click="nav.goTo('config')">Open Config</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<StatDisabledAlert
|
||||
v-if="!latencyEnabled"
|
||||
title="Latency statistics are off"
|
||||
config-key="admin.stats.latency"
|
||||
purpose="to see fleet p50/p95."
|
||||
/>
|
||||
<SkeletonTable v-if="catalogLoadState === 'skeleton'" :rows="5" :cols="columns.length" />
|
||||
<ErrorState v-else-if="catalogLoadState === 'error'" :message="error ?? ''" :on-retry="onRetry" />
|
||||
<EmptyState v-else-if="catalogLoadState === 'empty'" title="No models configured." />
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { faCheck, faCopy, faTriangleExclamation } from '@fortawesome/free-solid-svg-icons'
|
||||
import { computed, onUnmounted, ref, useTemplateRef } from 'vue'
|
||||
import { computed, useTemplateRef } from 'vue'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { useCopyFeedback } from '@/composables/useCopyFeedback'
|
||||
import { copyText } from '@/lib/clipboard'
|
||||
import { formatContextWindow, formatModelCostHover } from '@/lib/format'
|
||||
import { useToastsStore } from '@/stores/toasts'
|
||||
@@ -50,17 +51,9 @@ const props = defineProps<{
|
||||
}>()
|
||||
|
||||
const labelRef = useTemplateRef<HTMLElement>('label')
|
||||
const state = ref<'idle' | 'copied' | 'selected' | 'failed'>('idle')
|
||||
let resetTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const { state, set: setCopyFeedback } = useCopyFeedback()
|
||||
const toasts = useToastsStore()
|
||||
|
||||
function scheduleReset(): void {
|
||||
clearTimeout(resetTimer)
|
||||
resetTimer = setTimeout(() => {
|
||||
state.value = 'idle'
|
||||
}, 1500)
|
||||
}
|
||||
|
||||
async function onClick(): Promise<void> {
|
||||
const result = await copyText(props.id, labelRef.value ?? undefined)
|
||||
// 'failed' (neither the Clipboard API nor the selection fallback
|
||||
@@ -71,9 +64,8 @@ async function onClick(): Promise<void> {
|
||||
// feedback right at the click target (the icon swap plus this same
|
||||
// title/aria-label text), so a success toast on top would double-notify
|
||||
// for something the reader is already looking straight at.
|
||||
state.value = result
|
||||
setCopyFeedback(result)
|
||||
if (result === 'failed') toasts.push({ kind: 'error', message: `Could not copy ${props.id}.` })
|
||||
scheduleReset()
|
||||
}
|
||||
|
||||
const icon = {
|
||||
@@ -119,10 +111,6 @@ const title = computed(() => {
|
||||
const base = baseTitle.value[state.value]
|
||||
return metaDetail.value ? `${base} · ${metaDetail.value}` : base
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
clearTimeout(resetTimer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -2,18 +2,17 @@
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import { computed, h } from 'vue'
|
||||
|
||||
import CompactNumber from '@/components/CompactNumber.vue'
|
||||
import CsvExportButton from '@/components/CsvExportButton.vue'
|
||||
import DataTable from '@/components/DataTable.vue'
|
||||
import EmptyState from '@/components/EmptyState.vue'
|
||||
import EntityLink from '@/components/EntityLink.vue'
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import SkeletonTable from '@/components/SkeletonTable.vue'
|
||||
import LoadStateView from '@/components/LoadStateView.vue'
|
||||
import TryLongerRangeButton from '@/components/TryLongerRangeButton.vue'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { EMPTY_CELL, optionalColumn, usageMetricColumns } from '@/lib/columns'
|
||||
import { toCsv } from '@/lib/csv'
|
||||
import { formatContextWindow, formatCost, formatModelCostHover } from '@/lib/format'
|
||||
import { formatContextWindow, formatModelCostHover } from '@/lib/format'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { joinPricingHealth, pricingHealthOrder } from '@/lib/pricing-health'
|
||||
import type { PricingHealthRow } from '@/lib/pricing-health'
|
||||
@@ -73,10 +72,14 @@ function sourceCell(row: PricingHealthRow) {
|
||||
}
|
||||
|
||||
function priceCell(row: PricingHealthRow) {
|
||||
if (row.inputPerMTokUsd === undefined || row.outputPerMTokUsd === undefined) return h('span', { class: 'text-muted-foreground' }, '—')
|
||||
if (row.inputPerMTokUsd === undefined || row.outputPerMTokUsd === undefined) return h('span', { class: 'text-muted-foreground' }, EMPTY_CELL)
|
||||
return h('span', {}, formatModelCostHover(row.inputPerMTokUsd, row.outputPerMTokUsd))
|
||||
}
|
||||
|
||||
// reuse-audit.md F9: context/requests/tokensIn/tokensOut/cost are the
|
||||
// identical shape lib/model-table-columns.ts's own modelCatalogColumns
|
||||
// builds for ModelCatalogRow — shared via lib/columns.ts's generic
|
||||
// factories rather than a second hand-rolled copy for this row type.
|
||||
const columns: ColumnDef<PricingHealthRow, unknown>[] = [
|
||||
{
|
||||
id: 'id',
|
||||
@@ -96,41 +99,8 @@ const columns: ColumnDef<PricingHealthRow, unknown>[] = [
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => priceCell(row.original),
|
||||
},
|
||||
{
|
||||
id: 'context',
|
||||
header: 'Context',
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (r) => r.contextTokens ?? 0,
|
||||
cell: ({ row }) => h('span', { class: 'tabular-nums' }, row.original.contextTokens !== undefined ? formatContextWindow(row.original.contextTokens) : '—'),
|
||||
},
|
||||
{
|
||||
id: 'requests',
|
||||
header: 'Requests',
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (r) => r.requests,
|
||||
cell: ({ row }) => h(CompactNumber, { value: row.original.requests }),
|
||||
},
|
||||
{
|
||||
id: 'tokensIn',
|
||||
header: 'Tokens in',
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (r) => r.tokensIn,
|
||||
cell: ({ row }) => h(CompactNumber, { value: row.original.tokensIn }),
|
||||
},
|
||||
{
|
||||
id: 'tokensOut',
|
||||
header: 'Tokens out',
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (r) => r.tokensOut,
|
||||
cell: ({ row }) => h(CompactNumber, { value: row.original.tokensOut }),
|
||||
},
|
||||
{
|
||||
id: 'cost',
|
||||
header: 'Cost',
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (r) => r.costMicroUsd,
|
||||
cell: ({ row }) => formatCost(row.original.costMicroUsd),
|
||||
},
|
||||
optionalColumn<PricingHealthRow>('context', 'Context', (r) => r.contextTokens, formatContextWindow),
|
||||
...usageMetricColumns<PricingHealthRow>(),
|
||||
]
|
||||
|
||||
/**
|
||||
@@ -171,17 +141,17 @@ function pricingHealthCsv(): string {
|
||||
<CardDescription>Every model served in range, joined with its billing price source.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-3">
|
||||
<SkeletonTable v-if="state === 'skeleton'" :rows="5" :cols="columns.length" />
|
||||
<ErrorState v-else-if="state === 'error'" :message="error" :on-retry="onRetry" />
|
||||
<EmptyState v-else-if="rows.length === 0" title="No traffic in this range.">
|
||||
<TryLongerRangeButton />
|
||||
</EmptyState>
|
||||
<template v-else>
|
||||
<LoadStateView :state="state" :error="error" :on-retry="onRetry" skeleton="table" :rows="5" :cols="columns.length" :empty="rows.length === 0">
|
||||
<template #empty>
|
||||
<EmptyState title="No traffic in this range.">
|
||||
<TryLongerRangeButton />
|
||||
</EmptyState>
|
||||
</template>
|
||||
<DataTable :columns="columns" :data="rows" empty-message="none" />
|
||||
<div class="flex justify-end">
|
||||
<CsvExportButton filename="pricing-health.csv" :build="pricingHealthCsv" />
|
||||
</div>
|
||||
</template>
|
||||
</LoadStateView>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
@@ -8,16 +8,17 @@ import {
|
||||
import { computed, h, reactive, watch } from 'vue'
|
||||
|
||||
import DataTable from '@/components/DataTable.vue'
|
||||
import DetailField from '@/components/DetailField.vue'
|
||||
import EmptyState from '@/components/EmptyState.vue'
|
||||
import EntityLink from '@/components/EntityLink.vue'
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import ModelChip from '@/components/ModelChip.vue'
|
||||
import ProviderRateBadge from '@/components/ProviderRateBadge.vue'
|
||||
import SearchInput from '@/components/SearchInput.vue'
|
||||
import SkeletonList from '@/components/SkeletonList.vue'
|
||||
import StatDisabledAlert from '@/components/StatDisabledAlert.vue'
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
@@ -356,22 +357,20 @@ const aliasEmptyMessage = computed(() =>
|
||||
<SearchInput v-model="modelQuery" placeholder="Search models or aliases..." class="mt-2 max-w-sm" />
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-3">
|
||||
<Alert v-if="!models.latencyEnabled" variant="warn">
|
||||
<AlertTitle>Latency statistics are off</AlertTitle>
|
||||
<AlertDescription class="flex flex-wrap items-center gap-2">
|
||||
<span>Enable <code>admin.stats.latency</code> in the middleware config to see fleet p50/p95.</span>
|
||||
<Button type="button" variant="outline" size="sm" @click="nav.goTo('config')">Open Config</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<StatDisabledAlert
|
||||
v-if="!models.latencyEnabled"
|
||||
title="Latency statistics are off"
|
||||
config-key="admin.stats.latency"
|
||||
purpose="to see fleet p50/p95."
|
||||
/>
|
||||
<SkeletonList v-if="providersLoadState === 'skeleton'" :rows="3" />
|
||||
<ErrorState v-else-if="providersLoadState === 'error'" :message="dashboard.error" :on-retry="dashboard.refresh" />
|
||||
<p v-else-if="!overview?.providers.length" class="py-6 text-center text-sm text-muted-foreground">none</p>
|
||||
<p
|
||||
<EmptyState v-else-if="!overview?.providers.length" title="No providers configured." />
|
||||
<EmptyState
|
||||
v-else-if="hasQuery && filteredProviders.length === 0"
|
||||
class="py-6 text-center text-sm text-muted-foreground"
|
||||
>
|
||||
no providers match "{{ modelQuery }}"
|
||||
</p>
|
||||
title="No matches."
|
||||
:description='`No providers match "${modelQuery}".`'
|
||||
/>
|
||||
<template v-else>
|
||||
<p class="text-xs text-muted-foreground">{{ perReplicaCaveat() }} Fleet p50/p95/timeouts/failovers below are fleet-wide, not per-replica.</p>
|
||||
<Accordion v-model="expandedProviderValues" type="multiple" class="rounded-md border px-3">
|
||||
@@ -488,22 +487,12 @@ const aliasEmptyMessage = computed(() =>
|
||||
</div>
|
||||
<AccordionContent>
|
||||
<dl class="mb-3 grid grid-cols-2 gap-x-6 gap-y-1.5 text-sm sm:grid-cols-3">
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground">Base URL</dt>
|
||||
<dd class="break-all">{{ p.baseUrl }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted-foreground">Last refresh</dt>
|
||||
<dd>{{ refreshDetailLabel(p.discoveryEnabled, p.lastRefresh) }}</dd>
|
||||
</div>
|
||||
<div v-if="p.healthState !== 'closed'">
|
||||
<dt class="text-xs text-muted-foreground">Discovery health</dt>
|
||||
<dd :class="healthDetailClass(p.healthState)">{{ healthBadgeLabel(p) }}</dd>
|
||||
</div>
|
||||
<div v-if="p.lastErr">
|
||||
<dt class="text-xs text-muted-foreground">Last error</dt>
|
||||
<dd class="text-destructive">{{ p.lastErr }}</dd>
|
||||
</div>
|
||||
<DetailField label="Base URL" class="break-all">{{ p.baseUrl }}</DetailField>
|
||||
<DetailField label="Last refresh">{{ refreshDetailLabel(p.discoveryEnabled, p.lastRefresh) }}</DetailField>
|
||||
<DetailField v-if="p.healthState !== 'closed'" label="Discovery health" :class="healthDetailClass(p.healthState)">
|
||||
{{ healthBadgeLabel(p) }}
|
||||
</DetailField>
|
||||
<DetailField v-if="p.lastErr" label="Last error" class="text-destructive">{{ p.lastErr }}</DetailField>
|
||||
</dl>
|
||||
<div v-if="visibleModels(p).length" class="flex flex-wrap gap-1.5">
|
||||
<span v-for="m in visibleModels(p)" :key="m" class="inline-flex min-w-0 max-w-full items-center gap-1">
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { faCheck, faCopy, faTriangleExclamation } from '@fortawesome/free-solid-svg-icons'
|
||||
import { onUnmounted, ref, useTemplateRef } from 'vue'
|
||||
import { useTemplateRef } from 'vue'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useCopyFeedback } from '@/composables/useCopyFeedback'
|
||||
import { copyText } from '@/lib/clipboard'
|
||||
import { useToastsStore } from '@/stores/toasts'
|
||||
|
||||
@@ -21,21 +22,17 @@ const props = defineProps<{
|
||||
}>()
|
||||
|
||||
const preRef = useTemplateRef<HTMLElement>('pre')
|
||||
const state = ref<'idle' | 'copied' | 'selected' | 'failed'>('idle')
|
||||
let resetTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const { state, set: setCopyFeedback } = useCopyFeedback()
|
||||
const toasts = useToastsStore()
|
||||
|
||||
async function onCopy(): Promise<void> {
|
||||
state.value = await copyText(props.text, preRef.value ?? undefined)
|
||||
const result = await copyText(props.text, preRef.value ?? undefined)
|
||||
setCopyFeedback(result)
|
||||
// Only a FAILURE also gets a toast (states-plan.md item 3) — see
|
||||
// ModelChip.vue's own identical doc comment: 'copied'/'selected'
|
||||
// already have clear inline feedback (the button's own icon/label
|
||||
// swap right below), so a success toast would double-notify.
|
||||
if (state.value === 'failed') toasts.push({ kind: 'error', message: 'Could not copy the snippet.' })
|
||||
clearTimeout(resetTimer)
|
||||
resetTimer = setTimeout(() => {
|
||||
state.value = 'idle'
|
||||
}, 1500)
|
||||
if (result === 'failed') toasts.push({ kind: 'error', message: 'Could not copy the snippet.' })
|
||||
}
|
||||
|
||||
const BUTTON_LABEL: Record<typeof state.value, string> = {
|
||||
@@ -44,8 +41,6 @@ const BUTTON_LABEL: Record<typeof state.value, string> = {
|
||||
selected: 'Selected — press ⌘/Ctrl+C',
|
||||
failed: 'Copy failed',
|
||||
}
|
||||
|
||||
onUnmounted(() => clearTimeout(resetTimer))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<script setup lang="ts">
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
/**
|
||||
* StatDisabledAlert (reuse-audit.md F3) is the ONE shared "a fleet
|
||||
* statistic is switched off in the middleware config" hint: a warn Alert
|
||||
* with a config-key `<code>` reference and an "Open Config" button that
|
||||
* navigates to the Config page. Replaces the 5 hand-rolled copies in
|
||||
* ProviderHealthPanel, ModelCatalogTable, ReliabilityPage,
|
||||
* AttributionDrilldown and UserDetail — those differed only in title,
|
||||
* config key and trailing purpose text (some dynamic, e.g. naming the
|
||||
* selected provider), which is exactly what these three props carry.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
/** e.g. "Latency statistics are off" or "Per-user-model statistics are off" */
|
||||
title: string
|
||||
/** dotted config key shown as inline code, e.g. "admin.stats.latency" */
|
||||
configKey: string
|
||||
/** trailing sentence after "Enable <code>{configKey}</code> in the middleware config ", e.g. "to see fleet p50/p95." */
|
||||
purpose: string
|
||||
}>()
|
||||
|
||||
const nav = useNavStore()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Alert variant="warn">
|
||||
<AlertTitle>{{ props.title }}</AlertTitle>
|
||||
<AlertDescription class="flex flex-wrap items-center gap-2">
|
||||
<span>Enable <code class="font-mono text-xs">{{ props.configKey }}</code> in the middleware config {{ props.purpose }}</span>
|
||||
<Button type="button" variant="outline" size="sm" @click="nav.goTo('config')">Open Config</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</template>
|
||||
@@ -0,0 +1,39 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* StatItem (reuse-audit.md F6) is the ONE label-over-value stat cell every
|
||||
* "Total"/overview grid in this panel used to hand-roll: a muted label,
|
||||
* then either the value (default slot, rendered `text-lg font-semibold
|
||||
* tabular-nums`, optionally tinted by `tone`) or, when `hint` is set, a
|
||||
* small muted substitute line instead of a value — the "not enough data
|
||||
* yet"/"pick a reference model" case every month-projection or run-out
|
||||
* figure in this panel shows before it has enough data to report one.
|
||||
*/
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
label: string
|
||||
tone?: 'default' | 'destructive' | 'accent' | 'muted'
|
||||
/** Shown as the value paragraph's `title` attribute — e.g. "Projected to exceed the configured cost/month limit." */
|
||||
title?: string
|
||||
/** A small muted line shown INSTEAD of the (default-slot) value — e.g. "not enough data yet". Omit to render the value normally. */
|
||||
hint?: string
|
||||
}>(),
|
||||
{ tone: 'default', title: undefined, hint: undefined },
|
||||
)
|
||||
|
||||
const TONE_CLASS: Record<'default' | 'destructive' | 'accent' | 'muted', string | undefined> = {
|
||||
default: undefined,
|
||||
destructive: 'text-destructive',
|
||||
accent: 'text-chart-requests',
|
||||
muted: 'text-muted-foreground',
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<p class="text-muted-foreground">{{ label }}</p>
|
||||
<p v-if="hint" class="text-sm text-muted-foreground">{{ hint }}</p>
|
||||
<p v-else class="text-lg font-semibold tabular-nums" :class="TONE_CLASS[tone]" :title="title">
|
||||
<slot />
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -3,10 +3,9 @@ import { computed, ref, watch } from 'vue'
|
||||
|
||||
import ClampedRangeNotice from '@/components/ClampedRangeNotice.vue'
|
||||
import DataTable from '@/components/DataTable.vue'
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import SkeletonTable from '@/components/SkeletonTable.vue'
|
||||
import LoadStateView from '@/components/LoadStateView.vue'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { adminFetch } from '@/lib/api'
|
||||
import { adminFetch, messageOf } from '@/lib/api'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { dayOrMonthWindow, totalsUrl } from '@/lib/range'
|
||||
import { targetCallerColumns } from '@/lib/target-columns'
|
||||
@@ -72,7 +71,7 @@ async function load(): Promise<void> {
|
||||
loadedOk.value = true
|
||||
} catch (err) {
|
||||
if (requestId !== reqId) return
|
||||
error.value = err instanceof Error ? err.message : String(err)
|
||||
error.value = messageOf(err)
|
||||
} finally {
|
||||
if (requestId === reqId) loading.value = false
|
||||
}
|
||||
@@ -98,9 +97,9 @@ const callersLoadState = computed(() => loadState({ loading: loading.value, hasD
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-3">
|
||||
<ClampedRangeNotice :window="filters.window" :span="filters.span" />
|
||||
<SkeletonTable v-if="callersLoadState === 'skeleton'" :rows="5" :cols="columns.length" />
|
||||
<ErrorState v-else-if="callersLoadState === 'error'" :message="error" :on-retry="load" />
|
||||
<DataTable v-else :columns="columns" :data="rows" empty-message="no callers recorded in this window" />
|
||||
<LoadStateView :state="callersLoadState" :error="error" :on-retry="load" skeleton="table" :rows="5" :cols="columns.length">
|
||||
<DataTable :columns="columns" :data="rows" empty-message="no callers recorded in this window" />
|
||||
</LoadStateView>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
@@ -2,31 +2,30 @@
|
||||
import { faArrowLeft } from '@fortawesome/free-solid-svg-icons'
|
||||
import { computed, onMounted, onUnmounted, watch } from 'vue'
|
||||
|
||||
import BudgetRatioBars from '@/components/BudgetRatioBars.vue'
|
||||
import ChartCard from '@/components/ChartCard.vue'
|
||||
import ClampedRangeNotice from '@/components/ClampedRangeNotice.vue'
|
||||
import CompactNumber from '@/components/CompactNumber.vue'
|
||||
import EmptyState from '@/components/EmptyState.vue'
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import ModelChip from '@/components/ModelChip.vue'
|
||||
import SkeletonChart from '@/components/SkeletonChart.vue'
|
||||
import SkeletonTable from '@/components/SkeletonTable.vue'
|
||||
import TimeSeriesChart from '@/components/TimeSeriesChart.vue'
|
||||
import StatDisabledAlert from '@/components/StatDisabledAlert.vue'
|
||||
import StatItem from '@/components/StatItem.vue'
|
||||
import TryLongerRangeButton from '@/components/TryLongerRangeButton.vue'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import UsageBar from '@/components/UsageBar.vue'
|
||||
import { useNow } from '@/composables/useNow'
|
||||
import { runOutDate as computeRunOutDate } from '@/lib/burndown'
|
||||
import { formatBucketLabel, formatCost, formatExactInt, formatLimits, formatTimestamp } from '@/lib/format'
|
||||
import { formatBucketLabel, formatCost, formatLimits, formatShortDate, formatTimestamp } from '@/lib/format'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { BUDGET_RATIO_LABEL, budgetRatios } from '@/lib/usage-bars'
|
||||
import { budgetRatios, usdToMicros } from '@/lib/usage-bars'
|
||||
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'
|
||||
|
||||
/**
|
||||
* UserDetail (redesign-plan.md section 3.4) is the Consumers page's
|
||||
@@ -42,7 +41,6 @@ const dashboard = useDashboardStore()
|
||||
const consumers = useConsumersStore()
|
||||
const events = useEventsStore()
|
||||
const filters = useFiltersStore()
|
||||
const nav = useNavStore()
|
||||
const { now, start: startClock, stop: stopClock } = useNow()
|
||||
onMounted(startClock)
|
||||
onUnmounted(stopClock)
|
||||
@@ -149,11 +147,6 @@ const recentErrors = computed(() => events.events.filter((e) => e.user === props
|
||||
|
||||
const ratios = computed(() => (entry.value ? budgetRatios(entry.value) : []))
|
||||
|
||||
function budgetValueText(id: string, used: number, limit: number): string {
|
||||
if (id.startsWith('cost')) return `${formatCost(used)} / ${formatCost(limit)}`
|
||||
return `${formatExactInt(used)} / ${formatExactInt(limit)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* runOutDate reuses lib/burndown.ts's own runOutDate — the SAME function
|
||||
* BurnDownChart.vue projects the Spend page's burn-down line with — rather
|
||||
@@ -163,7 +156,7 @@ function budgetValueText(id: string, used: number, limit: number): string {
|
||||
const runOutDate = computed(() => {
|
||||
const limitUsd = entry.value?.limits?.costPerMonthUSD
|
||||
if (!entry.value || !limitUsd) return null
|
||||
return computeRunOutDate(entry.value.costPerMonthMicroUsd, Math.round(limitUsd * 1_000_000), now.value)
|
||||
return computeRunOutDate(entry.value.costPerMonthMicroUsd, usdToMicros(limitUsd), now.value)
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -191,18 +184,9 @@ const runOutDate = computed(() => {
|
||||
No usage scope for this user yet — it appears after their first request.
|
||||
</CardContent>
|
||||
<CardContent v-else class="grid grid-cols-2 gap-4 text-sm sm:grid-cols-4">
|
||||
<div>
|
||||
<p class="text-muted-foreground">Requests/day</p>
|
||||
<p class="text-lg font-semibold tabular-nums"><CompactNumber :value="entry.requestsPerDay" /></p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-muted-foreground">Cost/day</p>
|
||||
<p class="text-lg font-semibold tabular-nums">{{ formatCost(entry.costPerDayMicroUsd) }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-muted-foreground">Cost/month</p>
|
||||
<p class="text-lg font-semibold tabular-nums">{{ formatCost(entry.costPerMonthMicroUsd) }}</p>
|
||||
</div>
|
||||
<StatItem label="Requests/day"><CompactNumber :value="entry.requestsPerDay" /></StatItem>
|
||||
<StatItem label="Cost/day">{{ formatCost(entry.costPerDayMicroUsd) }}</StatItem>
|
||||
<StatItem label="Cost/month">{{ formatCost(entry.costPerMonthMicroUsd) }}</StatItem>
|
||||
<div>
|
||||
<p class="text-muted-foreground">Limits</p>
|
||||
<p class="text-sm">{{ formatLimits(entry.limits) }}</p>
|
||||
@@ -213,41 +197,33 @@ const runOutDate = computed(() => {
|
||||
<Card v-if="entry && ratios.length">
|
||||
<CardHeader>
|
||||
<CardTitle>Headroom</CardTitle>
|
||||
<CardDescription v-if="runOutDate">At the current pace, cost/month runs out around {{ formatTimestamp(runOutDate.toISOString()) }}.</CardDescription>
|
||||
<CardDescription v-if="runOutDate">At the current pace, cost/month runs out around {{ formatShortDate(runOutDate) }}.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-wrap items-center gap-x-4 gap-y-1.5">
|
||||
<span v-for="ratio in ratios" :key="ratio.id" class="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
{{ BUDGET_RATIO_LABEL[ratio.id] }}
|
||||
<UsageBar
|
||||
:ratio="ratio.ratio"
|
||||
:label="BUDGET_RATIO_LABEL[ratio.id]"
|
||||
:value-text="budgetValueText(ratio.id, ratio.used, ratio.limit)"
|
||||
/>
|
||||
</span>
|
||||
<CardContent>
|
||||
<BudgetRatioBars :ratios="ratios" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Requests over time</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<SkeletonChart v-if="reqState === 'skeleton'" />
|
||||
<ErrorState v-else-if="reqState === 'error'" :message="detail?.reqError ?? ''" :on-retry="loadDetail" />
|
||||
<TimeSeriesChart v-else :labels="reqLabels" :datasets="reqDatasets" :ariaLabel="`Requests over time for ${userId}`" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
<ChartCard
|
||||
title="Requests over time"
|
||||
:state="reqState"
|
||||
:error="detail?.reqError ?? ''"
|
||||
:on-retry="loadDetail"
|
||||
:labels="reqLabels"
|
||||
:datasets="reqDatasets"
|
||||
:aria-label="`Requests over time for ${userId}`"
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Cost over time</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<SkeletonChart v-if="costState === 'skeleton'" />
|
||||
<ErrorState v-else-if="costState === 'error'" :message="detail?.costError ?? ''" :on-retry="loadDetail" />
|
||||
<TimeSeriesChart v-else :labels="costLabels" :datasets="costDatasets" :value-formatter="formatCost" :ariaLabel="`Cost over time for ${userId}`" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
<ChartCard
|
||||
title="Cost over time"
|
||||
:state="costState"
|
||||
:error="detail?.costError ?? ''"
|
||||
:on-retry="loadDetail"
|
||||
:labels="costLabels"
|
||||
:datasets="costDatasets"
|
||||
:value-formatter="formatCost"
|
||||
:aria-label="`Cost over time for ${userId}`"
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -255,13 +231,12 @@ const runOutDate = computed(() => {
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-3">
|
||||
<ClampedRangeNotice :window="filters.window" :span="filters.span" />
|
||||
<Alert v-if="showUserModelHint" variant="warn">
|
||||
<AlertTitle>Per-user-model statistics are off</AlertTitle>
|
||||
<AlertDescription class="flex flex-wrap items-center gap-2">
|
||||
<span>Enable <code class="font-mono text-xs">admin.stats.userModel</code> in the middleware config to see a per-model breakdown for this user.</span>
|
||||
<Button type="button" variant="outline" size="sm" @click="nav.goTo('config')">Open Config</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<StatDisabledAlert
|
||||
v-if="showUserModelHint"
|
||||
title="Per-user-model statistics are off"
|
||||
config-key="admin.stats.userModel"
|
||||
purpose="to see a per-model breakdown for this user."
|
||||
/>
|
||||
<SkeletonTable v-else-if="modelState === 'skeleton'" :rows="3" :cols="3" />
|
||||
<ErrorState v-else-if="modelState === 'error'" :message="detail?.modelError ?? ''" :on-retry="loadDetail" />
|
||||
<EmptyState v-else-if="!modelRows.length" title="No traffic in this range.">
|
||||
@@ -300,7 +275,7 @@ const runOutDate = computed(() => {
|
||||
<p class="text-muted-foreground">{{ event.message }}</p>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="py-6 text-center text-sm text-muted-foreground">none in the current event window</p>
|
||||
<EmptyState v-else title="No recent errors in the current event window." />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
import TargetPicker from '@/components/forms/TargetPicker.vue'
|
||||
import SnippetBlock from '@/components/SnippetBlock.vue'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { groupGrantSnippet, isValidName, isValidUserName, userGrantJsonFragment, validatePersonalGrant } from '@/lib/snippets'
|
||||
import { useTargetPicker } from '@/composables/useTargetPicker'
|
||||
import { groupGrantSnippet, parseList, userGrantJsonFragment, validatePersonalGrant } from '@/lib/snippets'
|
||||
|
||||
/**
|
||||
* GrantForm (ChangeHelper, redesign-plan.md section 3.4) builds a group's
|
||||
@@ -23,35 +24,20 @@ const props = defineProps<{
|
||||
userNames: string[]
|
||||
}>()
|
||||
|
||||
const targetKind = ref<'group' | 'user'>('group')
|
||||
const targetName = ref('')
|
||||
const { targetKind, targetName, targetNames, nameValid, snippetLabel } = useTargetPicker(
|
||||
() => props.groupNames,
|
||||
() => props.userNames,
|
||||
)
|
||||
const providersRaw = ref('')
|
||||
const modelsRaw = ref('')
|
||||
const mcpServersRaw = ref('')
|
||||
const agentsRaw = ref('')
|
||||
|
||||
/** parseList splits a comma-separated field into trimmed, non-empty, de-duplicated entries — the one shared parser every list field below uses. */
|
||||
function parseList(raw: string): string[] {
|
||||
const seen = new Set<string>()
|
||||
for (const part of raw.split(',')) {
|
||||
const trimmed = part.trim()
|
||||
if (trimmed) seen.add(trimmed)
|
||||
}
|
||||
return Array.from(seen)
|
||||
}
|
||||
|
||||
const providers = computed(() => parseList(providersRaw.value))
|
||||
const models = computed(() => parseList(modelsRaw.value))
|
||||
const mcpServers = computed(() => parseList(mcpServersRaw.value))
|
||||
const agents = computed(() => parseList(agentsRaw.value))
|
||||
|
||||
const targetNames = computed(() => (targetKind.value === 'group' ? props.groupNames : props.userNames))
|
||||
// A group name follows NAME_PATTERN (auth.go's configNamePattern — a
|
||||
// route-path-segment safety rule); a user name only needs to be
|
||||
// non-empty (auth.go's buildEntry, no character restriction at all —
|
||||
// P3 item 27). isValidUserName, not isValidName, for targetKind === 'user'.
|
||||
const nameValid = computed(() => (targetKind.value === 'group' ? isValidName(targetName.value.trim()) : isValidUserName(targetName.value)))
|
||||
|
||||
// validatePersonalGrant is a USER-ONLY rule (lib/snippets.ts's own doc
|
||||
// comment) — a group's own `providers: []` legitimately means "every
|
||||
// provider" and Go applies it with no such check at group-construction
|
||||
@@ -81,27 +67,14 @@ const snippet = computed<string | null>(() => {
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div class="flex flex-col gap-1">
|
||||
<label id="grant-target-kind-label" class="text-xs font-medium text-muted-foreground">Target</label>
|
||||
<Select :model-value="targetKind" @update:model-value="(v) => (targetKind = v as 'group' | 'user')">
|
||||
<SelectTrigger aria-labelledby="grant-target-kind-label"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="group">Group</SelectItem>
|
||||
<SelectItem value="user">User (personal grant, existing users.json entry)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<label id="grant-target-name-label" class="text-xs font-medium text-muted-foreground">{{ targetKind === 'group' ? 'Group name' : 'User name' }}</label>
|
||||
<Select :model-value="targetName" @update:model-value="(v) => (targetName = String(v))">
|
||||
<SelectTrigger aria-labelledby="grant-target-name-label"><SelectValue placeholder="Select…" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="name in targetNames" :key="name" :value="name">{{ name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<TargetPicker
|
||||
:target-kind="targetKind"
|
||||
:target-name="targetName"
|
||||
:target-names="targetNames"
|
||||
user-option-label="User (personal grant, existing users.json entry)"
|
||||
@update:target-kind="targetKind = $event"
|
||||
@update:target-name="targetName = $event"
|
||||
/>
|
||||
|
||||
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div class="flex flex-col gap-1">
|
||||
@@ -128,11 +101,7 @@ const snippet = computed<string | null>(() => {
|
||||
<AlertDescription>{{ grantError }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<SnippetBlock
|
||||
v-if="snippet"
|
||||
:label="targetKind === 'group' ? 'Paste into middleware.yaml' : `Merge into ${targetName}’s users.json line`"
|
||||
:text="snippet"
|
||||
/>
|
||||
<SnippetBlock v-if="snippet" :label="snippetLabel" :text="snippet" />
|
||||
<p v-else class="text-sm text-muted-foreground">Pick a target and at least one list to build a snippet.</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import { computed, reactive } from 'vue'
|
||||
|
||||
import TargetPicker from '@/components/forms/TargetPicker.vue'
|
||||
import SnippetBlock from '@/components/SnippetBlock.vue'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { groupLimitsSnippet, isValidName, isValidNonNegative, isValidNonNegativeInt, isValidUserName, userLimitsJsonFragment } from '@/lib/snippets'
|
||||
import { useTargetPicker } from '@/composables/useTargetPicker'
|
||||
import { groupLimitsSnippet, isValidNonNegative, isValidNonNegativeInt, userLimitsJsonFragment } from '@/lib/snippets'
|
||||
import type { LimitsConfig } from '@/types/api'
|
||||
|
||||
/**
|
||||
@@ -22,8 +23,10 @@ const props = defineProps<{
|
||||
userNames: string[]
|
||||
}>()
|
||||
|
||||
const targetKind = ref<'group' | 'user'>('group')
|
||||
const targetName = ref('')
|
||||
const { targetKind, targetName, targetNames, nameValid, snippetLabel } = useTargetPicker(
|
||||
() => props.groupNames,
|
||||
() => props.userNames,
|
||||
)
|
||||
|
||||
/** 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<keyof LimitsConfig>(['requestsPerMinute', 'requestsPerDay', 'tokensPerDay', 'tokensPerMonth'])
|
||||
@@ -51,8 +54,6 @@ const raw = reactive<Record<keyof LimitsConfig, string>>({
|
||||
costPerMonthUSD: '',
|
||||
})
|
||||
|
||||
const targetNames = computed(() => (targetKind.value === 'group' ? props.groupNames : props.userNames))
|
||||
|
||||
/** invalidFields lists every field whose entered text is non-empty but fails its own domain check (fieldValid above) — surfaced individually rather than one generic "invalid input" message, so the operator can see exactly which field to fix. Split by INTEGER_FIELDS so the error text is accurate for both: a fraction is invalid for requestsPerMinute etc. but perfectly valid for costPerDayUSD/costPerMonthUSD. */
|
||||
const invalidFields = computed(() =>
|
||||
FIELDS.filter(({ key }) => raw[key].trim() !== '' && !fieldValid(key, Number(raw[key]))).map((f) => f.label),
|
||||
@@ -73,12 +74,6 @@ const limits = computed<LimitsConfig>(() => {
|
||||
return out
|
||||
})
|
||||
|
||||
// A group name follows NAME_PATTERN (auth.go's configNamePattern — a
|
||||
// route-path-segment safety rule); a user name only needs to be
|
||||
// non-empty (auth.go's buildEntry, no character restriction at all —
|
||||
// P3 item 27). isValidUserName, not isValidName, for targetKind === 'user'.
|
||||
const nameValid = computed(() => (targetKind.value === 'group' ? isValidName(targetName.value.trim()) : isValidUserName(targetName.value)))
|
||||
|
||||
const snippet = computed<string | null>(() => {
|
||||
if (!nameValid.value || invalidFields.value.length > 0) return null
|
||||
if (Object.keys(limits.value).length === 0) return null
|
||||
@@ -90,27 +85,14 @@ const snippet = computed<string | null>(() => {
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div class="flex flex-col gap-1">
|
||||
<label id="limits-target-kind-label" class="text-xs font-medium text-muted-foreground">Target</label>
|
||||
<Select :model-value="targetKind" @update:model-value="(v) => (targetKind = v as 'group' | 'user')">
|
||||
<SelectTrigger aria-labelledby="limits-target-kind-label"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="group">Group</SelectItem>
|
||||
<SelectItem value="user">User (existing users.json entry)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<label id="limits-target-name-label" class="text-xs font-medium text-muted-foreground">{{ targetKind === 'group' ? 'Group name' : 'User name' }}</label>
|
||||
<Select :model-value="targetName" @update:model-value="(v) => (targetName = String(v))">
|
||||
<SelectTrigger aria-labelledby="limits-target-name-label"><SelectValue placeholder="Select…" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="name in targetNames" :key="name" :value="name">{{ name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<TargetPicker
|
||||
:target-kind="targetKind"
|
||||
:target-name="targetName"
|
||||
:target-names="targetNames"
|
||||
user-option-label="User (existing users.json entry)"
|
||||
@update:target-kind="targetKind = $event"
|
||||
@update:target-name="targetName = $event"
|
||||
/>
|
||||
|
||||
<div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
<div v-for="field in FIELDS" :key="field.key" class="flex flex-col gap-1">
|
||||
@@ -133,11 +115,7 @@ const snippet = computed<string | null>(() => {
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<SnippetBlock
|
||||
v-if="snippet"
|
||||
:label="targetKind === 'group' ? 'Paste into middleware.yaml' : `Merge into ${targetName}’s users.json line`"
|
||||
:text="snippet"
|
||||
/>
|
||||
<SnippetBlock v-if="snippet" :label="snippetLabel" :text="snippet" />
|
||||
<p v-else class="text-sm text-muted-foreground">Pick a target and at least one limit to build a snippet.</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
<script setup lang="ts">
|
||||
import { useId } from 'vue'
|
||||
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import type { GrantTargetKind } from '@/composables/useTargetPicker'
|
||||
|
||||
/**
|
||||
* TargetPicker (reuse-audit.md F12) is the "Target kind, then Group or
|
||||
* User name" two-Select block GrantForm.vue and LimitsForm.vue each
|
||||
* hand-rolled — pairs with the composables/useTargetPicker.ts composable,
|
||||
* which owns the state/validation this component only renders.
|
||||
* `userOptionLabel` stays a prop rather than a hardcoded string: GrantForm
|
||||
* ("User (personal grant, existing users.json entry)") and LimitsForm
|
||||
* ("User (existing users.json entry)") word the "user" option differently,
|
||||
* and unifying that wording is outside this refactor's scope.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
targetKind: GrantTargetKind
|
||||
targetName: string
|
||||
targetNames: string[]
|
||||
userOptionLabel: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:targetKind': [value: GrantTargetKind]
|
||||
'update:targetName': [value: string]
|
||||
}>()
|
||||
|
||||
const kindLabelId = `target-picker-kind-${useId()}`
|
||||
const nameLabelId = `target-picker-name-${useId()}`
|
||||
|
||||
function onKindUpdate(value: unknown): void {
|
||||
if (value === 'group' || value === 'user') emit('update:targetKind', value)
|
||||
}
|
||||
function onNameUpdate(value: unknown): void {
|
||||
emit('update:targetName', String(value))
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div class="flex flex-col gap-1">
|
||||
<label :id="kindLabelId" class="text-xs font-medium text-muted-foreground">Target</label>
|
||||
<Select :model-value="targetKind" @update:model-value="onKindUpdate">
|
||||
<SelectTrigger :aria-labelledby="kindLabelId"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="group">Group</SelectItem>
|
||||
<SelectItem value="user">{{ props.userOptionLabel }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<label :id="nameLabelId" class="text-xs font-medium text-muted-foreground">{{ targetKind === 'group' ? 'Group name' : 'User name' }}</label>
|
||||
<Select :model-value="targetName" @update:model-value="onNameUpdate">
|
||||
<SelectTrigger :aria-labelledby="nameLabelId"><SelectValue placeholder="Select…" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="name in targetNames" :key="name" :value="name">{{ name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,12 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
import LabeledSelect from '@/components/LabeledSelect.vue'
|
||||
import SnippetBlock from '@/components/SnippetBlock.vue'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { API_KEY_PLACEHOLDER, generateApiKey, isValidUserName, userJsonLine, validatePersonalGrant } from '@/lib/snippets'
|
||||
import { API_KEY_PLACEHOLDER, generateApiKey, isValidUserName, parseList, userJsonLine, validatePersonalGrant } from '@/lib/snippets'
|
||||
import { useToastsStore } from '@/stores/toasts'
|
||||
|
||||
/**
|
||||
@@ -21,6 +21,8 @@ import { useToastsStore } from '@/stores/toasts'
|
||||
*/
|
||||
const props = defineProps<{ groupNames: string[] }>()
|
||||
|
||||
const groupOptions = computed(() => props.groupNames.map((g) => ({ value: g, label: g })))
|
||||
|
||||
const name = ref('')
|
||||
const apiKey = ref(API_KEY_PLACEHOLDER)
|
||||
const primaryGroup = ref('')
|
||||
@@ -51,15 +53,6 @@ function generate(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function parseList(raw: string): string[] {
|
||||
const seen = new Set<string>()
|
||||
for (const part of raw.split(',')) {
|
||||
const trimmed = part.trim()
|
||||
if (trimmed) seen.add(trimmed)
|
||||
}
|
||||
return Array.from(seen)
|
||||
}
|
||||
|
||||
const extraGroups = computed(() => parseList(extraGroupsRaw.value))
|
||||
const providers = computed(() => parseList(providersRaw.value))
|
||||
const models = computed(() => parseList(modelsRaw.value))
|
||||
@@ -91,15 +84,13 @@ const snippet = computed<string | null>(() => {
|
||||
<label for="user-name" class="text-xs font-medium text-muted-foreground">Name</label>
|
||||
<Input id="user-name" v-model="name" placeholder="alice" />
|
||||
</div>
|
||||
<div class="flex flex-col gap-1">
|
||||
<label id="user-group-label" class="text-xs font-medium text-muted-foreground">Primary group</label>
|
||||
<Select :model-value="primaryGroup" @update:model-value="(v) => (primaryGroup = String(v))">
|
||||
<SelectTrigger aria-labelledby="user-group-label"><SelectValue placeholder="Select…" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="g in props.groupNames" :key="g" :value="g">{{ g }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<LabeledSelect
|
||||
label="Primary group"
|
||||
:model-value="primaryGroup"
|
||||
:options="groupOptions"
|
||||
placeholder="Select…"
|
||||
@update:model-value="primaryGroup = $event"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
|
||||
Reference in New Issue
Block a user