mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
refactor(webui): remove shadcn-vue, chart.js and replaced components
Delete 89 files that no live entry imports, drop chart.js, vue-chartjs, @tanstack/vue-table and the FontAwesome runtime, and replace the Vue FontAwesome wrapper with a small SVG component. Limit Tailwind source scanning to the perfect-design components the app bundles. Add the bundle gate script and spec: gzip JS+CSS of dist/assets must stay at or below 324300 bytes.
This commit is contained in:
Generated
+1
-88
@@ -8,14 +8,10 @@
|
||||
"name": "webui",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@fortawesome/fontawesome-svg-core": "^7.3.1",
|
||||
"@fortawesome/free-brands-svg-icons": "^7.3.1",
|
||||
"@fortawesome/free-solid-svg-icons": "^7.3.1",
|
||||
"@fortawesome/vue-fontawesome": "^3.3.3",
|
||||
"@perfect-design/ui": "https://github.com/lukaszraczylo/perfect-design/releases/download/v0.4.0/perfect-design-ui-0.4.0.tgz",
|
||||
"@tanstack/vue-table": "^8.21.3",
|
||||
"@vueuse/core": "^14.4.0",
|
||||
"chart.js": "^4.5.1",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"pinia": "^4.0.3",
|
||||
@@ -23,8 +19,7 @@
|
||||
"shadcn-vue": "^2.8.2",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"vue": "^3.5.40",
|
||||
"vue-chartjs": "^5.3.4"
|
||||
"vue": "^3.5.40"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "^4.14.1",
|
||||
@@ -696,18 +691,6 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/@fortawesome/fontawesome-svg-core": {
|
||||
"version": "7.3.1",
|
||||
"resolved": "https://npm.fontawesome.com/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-7.3.1.tgz",
|
||||
"integrity": "sha512-BoxVN3PKnMbgStHhjoaky/oWdxHomDqmBVA24IA3KEmssFGeI7u9YT/BJceOjIum/t6TpPa/vcMKaVYQeIQ/3Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@fortawesome/fontawesome-common-types": "7.3.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/@fortawesome/free-brands-svg-icons": {
|
||||
"version": "7.3.1",
|
||||
"resolved": "https://npm.fontawesome.com/@fortawesome/free-brands-svg-icons/-/free-brands-svg-icons-7.3.1.tgz",
|
||||
@@ -732,16 +715,6 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/@fortawesome/vue-fontawesome": {
|
||||
"version": "3.3.3",
|
||||
"resolved": "https://npm.fontawesome.com/@fortawesome/vue-fontawesome/-/vue-fontawesome-3.3.3.tgz",
|
||||
"integrity": "sha512-Jbjze98gGcVBSdkscLbnDlHECumMAFVWDarMtycctn9qL3p92ApnV36VW4PwVrcm9IWrHnnE6ZL9x7MXStSCfA==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@fortawesome/fontawesome-svg-core": "~1 || ~6 || ~7",
|
||||
"vue": ">= 3.0.0 < 4"
|
||||
}
|
||||
},
|
||||
"node_modules/@hono/node-server": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.1.tgz",
|
||||
@@ -892,12 +865,6 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@kurkle/color": {
|
||||
"version": "0.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz",
|
||||
"integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/sdk": {
|
||||
"version": "1.30.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz",
|
||||
@@ -1890,19 +1857,6 @@
|
||||
"vite": "^5.2.0 || ^6 || ^7 || ^8"
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/table-core": {
|
||||
"version": "8.21.3",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/table-core/-/table-core-8.21.3.tgz",
|
||||
"integrity": "sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/virtual-core": {
|
||||
"version": "3.17.8",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.17.8.tgz",
|
||||
@@ -1913,25 +1867,6 @@
|
||||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/vue-table": {
|
||||
"version": "8.21.3",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/vue-table/-/vue-table-8.21.3.tgz",
|
||||
"integrity": "sha512-rusRyd77c5tDPloPskctMyPLFEQUeBzxdQ+2Eow4F7gDPlPOB1UnnhzfpdvqZ8ZyX2rRNGmqNnQWm87OI2OQPw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@tanstack/table-core": "8.21.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": ">=3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/vue-virtual": {
|
||||
"version": "3.13.36",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/vue-virtual/-/vue-virtual-3.13.36.tgz",
|
||||
@@ -2863,18 +2798,6 @@
|
||||
"url": "https://github.com/chalk/chalk?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/chart.js": {
|
||||
"version": "4.5.1",
|
||||
"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz",
|
||||
"integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@kurkle/color": "^0.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"pnpm": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/chokidar": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz",
|
||||
@@ -7228,16 +7151,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vue-chartjs": {
|
||||
"version": "5.3.4",
|
||||
"resolved": "https://registry.npmjs.org/vue-chartjs/-/vue-chartjs-5.3.4.tgz",
|
||||
"integrity": "sha512-x3Fqob8RQvrTdssfi9ecsCzEkFOd8JPmNwSkSQzdfKj/uBsRJs/Y88cZcZIEcPsTVfMGwMo4MOoihoDG2DoE/g==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"chart.js": "^4.1.1",
|
||||
"vue": "^3.0.0-0 || ^2.7.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vue-eslint-parser": {
|
||||
"version": "10.4.1",
|
||||
"resolved": "https://registry.npmjs.org/vue-eslint-parser/-/vue-eslint-parser-10.4.1.tgz",
|
||||
|
||||
+1
-6
@@ -12,14 +12,10 @@
|
||||
"test:visual": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fortawesome/fontawesome-svg-core": "^7.3.1",
|
||||
"@fortawesome/free-brands-svg-icons": "^7.3.1",
|
||||
"@fortawesome/free-solid-svg-icons": "^7.3.1",
|
||||
"@fortawesome/vue-fontawesome": "^3.3.3",
|
||||
"@perfect-design/ui": "https://github.com/lukaszraczylo/perfect-design/releases/download/v0.4.0/perfect-design-ui-0.4.0.tgz",
|
||||
"@tanstack/vue-table": "^8.21.3",
|
||||
"@vueuse/core": "^14.4.0",
|
||||
"chart.js": "^4.5.1",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"pinia": "^4.0.3",
|
||||
@@ -27,8 +23,7 @@
|
||||
"shadcn-vue": "^2.8.2",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"vue": "^3.5.40",
|
||||
"vue-chartjs": "^5.3.4"
|
||||
"vue": "^3.5.40"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "^4.14.1",
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
export const LIMIT: number
|
||||
export const DIST: string
|
||||
export function hasDist(): boolean
|
||||
export function measure(dir?: string): { file: string; gzip: number }[]
|
||||
export function totalGzip(dir?: string): number
|
||||
@@ -0,0 +1,32 @@
|
||||
// Gate scope: gzip (level 9) of every .js and .css in dist/assets, lazy chunks included.
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { gzipSync } from 'node:zlib'
|
||||
|
||||
export const LIMIT = 324300
|
||||
export const DIST = fileURLToPath(new URL('../dist/assets', import.meta.url))
|
||||
|
||||
export const hasDist = () => existsSync(DIST)
|
||||
|
||||
export function totalGzip(dir = DIST) {
|
||||
return measure(dir).reduce((n, r) => n + r.gzip, 0)
|
||||
}
|
||||
|
||||
export function measure(dir = DIST) {
|
||||
return readdirSync(dir)
|
||||
.filter((f) => /\.(js|css)$/.test(f))
|
||||
.map((f) => ({ file: f, gzip: gzipSync(readFileSync(join(dir, f)), { level: 9 }).length }))
|
||||
.sort((a, b) => b.gzip - a.gzip)
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
const rows = measure()
|
||||
const total = totalGzip()
|
||||
for (const r of rows.slice(0, 10)) console.log(`${String(r.gzip).padStart(8)} ${r.file}`)
|
||||
console.log(`total gzip JS+CSS: ${total} B (limit ${LIMIT}); ${rows.length} files`)
|
||||
if (total > LIMIT) {
|
||||
console.error('bundle gate FAILED')
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,68 @@
|
||||
@import "tailwindcss";
|
||||
/* Layered below utilities so Tailwind classes such as `hidden` still win over the FontAwesome icon display rule. */
|
||||
@import "@fortawesome/fontawesome-svg-core/styles.css" layer(base);
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn-vue/tailwind.css";
|
||||
@import "@perfect-design/ui/theme.css";
|
||||
@import "@perfect-design/ui/packs.css";
|
||||
@source "../../node_modules/@perfect-design/ui/dist";
|
||||
/* Tailwind scans only the perfect-design components this app bundles; scanning all of dist adds ~15 KB gzip of unused utilities. Add a component's directory here when a new one is imported. */
|
||||
@source "../../node_modules/@perfect-design/ui/dist/lib/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Card";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/CodeViewer";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DataTable";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DescriptionList";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Heatmap";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/KpiTile";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/LineChart";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Sparkline";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatBar";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatGroup";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Table";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/YamlViewer";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/_chart";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/_shared";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/Callout";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/EmptyState";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/ErrorState";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/LoadingState";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/OfflineIndicator";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/StaleNotice";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/ToastItem";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/Toaster";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Checkbox";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/CheckboxCard";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Combobox";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/DateInput";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Field";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/FilterBar";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Input";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/InputGroup";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Label";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/NativeSelect";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/NumberInput";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/SearchInput";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/SegmentedControl";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/TimeInput";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/layout/AppShell";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/layout/ConfigProvider";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/layout/Container";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/NavLink";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/Pagination";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/SidebarNav";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/ThemeToggle";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Command";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Dialog";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Popover";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Sheet";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Badge";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Button";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Icon";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Kbd";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Spinner";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusBadge";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusDot";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/RelativeTime/**/*.js";
|
||||
|
||||
/*
|
||||
* The base palette (background, primary, border, radius, ...) now comes from
|
||||
@@ -220,3 +277,15 @@
|
||||
.wb-model-provider::after { content: '/'; }
|
||||
.wb-model-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
@media (min-width: 640px) { .wb-table td.wb-text:has(.wb-model) { width: 100%; max-width: 0; overflow: hidden; } }
|
||||
|
||||
/* FaIcon.vue's box; layered below utilities so classes such as `hidden` still win. */
|
||||
@layer base {
|
||||
.svg-inline--fa {
|
||||
box-sizing: content-box;
|
||||
display: inline-block;
|
||||
height: 1em;
|
||||
overflow: visible;
|
||||
vertical-align: -0.125em;
|
||||
width: 1.25em;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { faCheck, faTriangleExclamation, faXmark } from '@fortawesome/free-solid-svg-icons'
|
||||
import { computed, onMounted } from 'vue'
|
||||
|
||||
import EmptyState from '@/components/EmptyState.vue'
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import SkeletonTable from '@/components/SkeletonTable.vue'
|
||||
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 { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { buildAccessMatrix, MATRIX_KIND_LABEL, MATRIX_KINDS, matrixColumnsState } from '@/lib/access-matrix'
|
||||
import type { AccessCell, MatrixKind } from '@/lib/access-matrix'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { useConsumersStore } from '@/stores/consumers'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
/**
|
||||
* AccessMatrix (redesign-plan.md section 3.4; P4 three-view split) is the
|
||||
* Consumers page's `view=matrix` alternative to ConsumerDirectory: rows
|
||||
* are groups, columns are ONE of three kinds at a time — providers
|
||||
* (allowed check + "n/m models", from GET /admin/api/consumers'
|
||||
* AllowedProviders/modelAccess), MCP servers, or agents (both from GET
|
||||
* /admin/api/targets' own `access` list) — switched by a Tabs control in
|
||||
* the card header, CONTROLLED via the `kind` prop/`update:kind` emit the
|
||||
* same way AttributionDrilldown.vue's `drill` prop works: this component
|
||||
* owns no navigation state itself, ConsumersPage.vue keeps `kind` in
|
||||
* nav.params (lib/access-matrix.ts's own `matrix` hash param) so a
|
||||
* reload or shared link restores the same view. Pure data shaping lives
|
||||
* in lib/access-matrix.ts; this component only fetches, lays out the
|
||||
* selected kind's columns, and renders.
|
||||
*/
|
||||
const props = defineProps<{ kind: MatrixKind }>()
|
||||
const emit = defineEmits<{ 'update:kind': [kind: MatrixKind] }>()
|
||||
|
||||
const consumers = useConsumersStore()
|
||||
const dashboard = useDashboardStore()
|
||||
const nav = useNavStore()
|
||||
|
||||
onMounted(() => {
|
||||
void consumers.ensureConsumers()
|
||||
})
|
||||
|
||||
const providerNames = computed(() => (dashboard.overview?.providers ?? []).map((p) => p.name))
|
||||
const mcpServers = computed(() => dashboard.targets?.mcpServers ?? [])
|
||||
const agents = computed(() => dashboard.targets?.agents ?? [])
|
||||
|
||||
/** MatrixSection is the AccessMatrixRow key each kind reads its cells from. */
|
||||
type MatrixSection = 'providers' | 'mcpServers' | 'agents'
|
||||
|
||||
/** KIND_SECTION maps the page-facing MatrixKind to the row-shape key buildAccessMatrix produced it under (lib/access-matrix.ts's own AccessMatrixRow). */
|
||||
const KIND_SECTION: Record<MatrixKind, MatrixSection> = {
|
||||
models: 'providers',
|
||||
mcp: 'mcpServers',
|
||||
agents: 'agents',
|
||||
}
|
||||
|
||||
/** KIND_DESCRIPTION is the CardDescription text for the currently selected kind. */
|
||||
const KIND_DESCRIPTION: Record<MatrixKind, string> = {
|
||||
models: "Which groups can reach which providers, and how many of each provider's models.",
|
||||
mcp: 'Which groups can reach which MCP servers.',
|
||||
agents: 'Which groups can reach which agents.',
|
||||
}
|
||||
|
||||
/** KIND_EMPTY_MESSAGE is shown instead of a table with zero columns — distinct from the "no groups configured" state below, since groups can exist while this kind's own column list is empty (e.g. no MCP servers configured at all). */
|
||||
const KIND_EMPTY_MESSAGE: Record<MatrixKind, string> = {
|
||||
models: 'No providers configured.',
|
||||
mcp: 'No MCP servers configured.',
|
||||
agents: 'No agents configured.',
|
||||
}
|
||||
|
||||
/** MatrixColumn is one header/cell column of the currently selected kind — no more "(MCP)"/"(agent)" label suffix, since the Tabs control already says which kind is showing. */
|
||||
interface MatrixColumn {
|
||||
key: string
|
||||
label: string
|
||||
section: MatrixSection
|
||||
}
|
||||
|
||||
const columns = computed<MatrixColumn[]>(() => {
|
||||
const section = KIND_SECTION[props.kind]
|
||||
if (props.kind === 'models') return providerNames.value.map((name): MatrixColumn => ({ key: name, label: name, section }))
|
||||
const targets = props.kind === 'mcp' ? mcpServers.value : agents.value
|
||||
return targets.map((t): MatrixColumn => ({ key: t.name, label: t.name, section }))
|
||||
})
|
||||
|
||||
const rows = computed(() => buildAccessMatrix(consumers.data?.groups ?? [], providerNames.value, mcpServers.value, agents.value))
|
||||
|
||||
/** sourceLoaded is whether the CURRENT kind's own raw dashboard field has loaded at least once — dashboard.overview for 'models', dashboard.targets for 'mcp'/'agents' — read straight off the store rather than the derived `columns` list, which maps a not-yet-loaded source to `[]` indistinguishably from a genuinely empty one (lib/access-matrix.ts's matrixColumnsState doc comment). */
|
||||
const sourceLoaded = computed(() => (props.kind === 'models' ? dashboard.overview !== null : dashboard.targets !== null))
|
||||
|
||||
/** columnsState is the current kind's own loading/error/empty/ready state (lib/access-matrix.ts's matrixColumnsState) — drives which CardContent branch renders below, independent of the groups-only groupsLoadState/noGroupsConfigured checks above it. */
|
||||
const columnsState = computed(() => matrixColumnsState(sourceLoaded.value, columns.value.length, dashboard.error))
|
||||
|
||||
/**
|
||||
* groupsLoadState (lib/load-state.ts) replaces the old bare
|
||||
* `consumers.error`/`consumers.loading` checks — those used to show the
|
||||
* error text UNCONDITIONALLY whenever consumers.error was set, even with
|
||||
* perfectly good stale group rows already in `rows` from a PRIOR
|
||||
* successful fetch (fetchConsumers, stores/consumers.ts, never clears
|
||||
* `data` on a failed refetch) — states-plan.md item 1's own "never wipe
|
||||
* rendered data on a background failure" rule, the same class of bug
|
||||
* this states pass fixes everywhere else. 'ready' once consumers.data has
|
||||
* loaded at least once, even with zero groups — `noGroupsConfigured`
|
||||
* below is the separate "loaded, but genuinely nothing configured" case.
|
||||
*/
|
||||
const groupsLoadState = computed(() => loadState({ loading: consumers.loading, hasData: consumers.data !== null, error: consumers.error }))
|
||||
|
||||
/** noGroupsConfigured (states-plan.md item 2: "Consumers: 'No groups configured' + hint to the Config page change helper") is true only once groups have genuinely loaded with none configured — not while still loading or errored (groupsLoadState handles those first, see the template below). */
|
||||
const noGroupsConfigured = computed(() => groupsLoadState.value === 'ready' && rows.value.length === 0)
|
||||
|
||||
const EMPTY_CELL: AccessCell = { allowed: false }
|
||||
|
||||
function cellFor(row: (typeof rows.value)[number], column: MatrixColumn): AccessCell {
|
||||
return row[column.section][column.key] ?? EMPTY_CELL
|
||||
}
|
||||
|
||||
/** setKind forwards a Tabs selection as `update:kind`, guarding the `unknown` reka-ui hands back down to a real MatrixKind (mirrors ConsumersPage.vue's own setView / ChangeHelper.vue's setHelper). */
|
||||
function setKind(next: unknown): void {
|
||||
if (typeof next !== 'string' || !(MATRIX_KINDS as readonly string[]).includes(next)) return
|
||||
emit('update:kind', next as MatrixKind)
|
||||
}
|
||||
|
||||
/**
|
||||
* cellSrText is the ONLY accessible text a screen reader announces for
|
||||
* one cell — the visible icon is aria-hidden and the visible detail span
|
||||
* is aria-hidden too (P3 item 18: it used to be read TWICE, once as
|
||||
* plain visible text and again inside this string). A zero-model cell
|
||||
* (`zero`) gets its own wording rather than the plain "Allowed, 0/5
|
||||
* models" reading, which sounds identical to "Allowed, 5/5 models" to a
|
||||
* screen reader user skimming past the number.
|
||||
*/
|
||||
function cellSrText(cell: AccessCell): string {
|
||||
if (!cell.allowed) return 'Not allowed'
|
||||
if (cell.zero) return `Allowed, but ${cell.detail} reachable — the model grant matches none of this provider's models`
|
||||
return cell.detail ? `Allowed, ${cell.detail}` : 'Allowed'
|
||||
}
|
||||
|
||||
/** cellIcon picks the FontAwesome icon for a cell's three visual states: not allowed (X), allowed-but-zero-usable-models (warning triangle — P3 item 18: this used to render an identical green check to a genuinely unrestricted cell), and ordinarily allowed (check). */
|
||||
function cellIcon(cell: AccessCell) {
|
||||
if (!cell.allowed) return faXmark
|
||||
if (cell.zero) return faTriangleExclamation
|
||||
return faCheck
|
||||
}
|
||||
|
||||
/** cellIconClass colors cellIcon's three states distinctly — not-allowed and zero-but-allowed must never share the "everything is fine" green. */
|
||||
function cellIconClass(cell: AccessCell): string {
|
||||
if (!cell.allowed) return 'text-muted-foreground/40'
|
||||
if (cell.zero) return 'text-status-warn'
|
||||
return 'text-chart-requests'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Access matrix</CardTitle>
|
||||
<CardDescription>{{ KIND_DESCRIPTION[props.kind] }}</CardDescription>
|
||||
<Tabs :model-value="props.kind" @update:model-value="setKind">
|
||||
<TabsList>
|
||||
<TabsTrigger v-for="k in MATRIX_KINDS" :key="k" :value="k">{{ MATRIX_KIND_LABEL[k] }}</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</CardHeader>
|
||||
<CardContent v-if="groupsLoadState === 'error'">
|
||||
<ErrorState :message="consumers.error" :on-retry="consumers.fetchConsumers" />
|
||||
</CardContent>
|
||||
<CardContent v-else-if="groupsLoadState === 'skeleton'">
|
||||
<SkeletonTable :rows="4" :cols="4" />
|
||||
</CardContent>
|
||||
<CardContent v-else-if="noGroupsConfigured">
|
||||
<EmptyState 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>
|
||||
</CardContent>
|
||||
<CardContent v-else-if="columnsState === 'error'">
|
||||
<ErrorState :message="dashboard.error" :on-retry="dashboard.refresh" />
|
||||
</CardContent>
|
||||
<CardContent v-else-if="columnsState === 'loading'">
|
||||
<SkeletonTable :rows="rows.length" :cols="4" />
|
||||
</CardContent>
|
||||
<CardContent v-else-if="columnsState === 'empty'">
|
||||
<EmptyState :title="KIND_EMPTY_MESSAGE[props.kind]" />
|
||||
</CardContent>
|
||||
<CardContent v-else class="overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Group</TableHead>
|
||||
<TableHead v-for="column in columns" :key="column.key">{{ column.label }}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="row in rows" :key="row.group">
|
||||
<TableHead scope="row" class="font-medium">{{ row.group }}</TableHead>
|
||||
<TableCell v-for="column in columns" :key="column.key" class="text-center" :title="cellFor(row, column).detail">
|
||||
<FontAwesomeIcon :icon="cellIcon(cellFor(row, column))" :class="cellIconClass(cellFor(row, column))" class="size-3.5" aria-hidden="true" />
|
||||
<span v-if="cellFor(row, column).detail" aria-hidden="true" class="ml-1 text-xs text-muted-foreground">{{ cellFor(row, column).detail }}</span>
|
||||
<span class="sr-only">{{ cellSrText(cellFor(row, column)) }}</span>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -1,197 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import { faChevronRight } from '@fortawesome/free-solid-svg-icons'
|
||||
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
|
||||
import { computed, h, ref } from 'vue'
|
||||
|
||||
import ClampedRangeNotice from '@/components/ClampedRangeNotice.vue'
|
||||
import CompactNumber from '@/components/CompactNumber.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 StatDisabledAlert from '@/components/StatDisabledAlert.vue'
|
||||
import TryLongerRangeButton from '@/components/TryLongerRangeButton.vue'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { formatCost } from '@/lib/format'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { drilldownLevel, makeScope } from '@/lib/scope'
|
||||
import { SPEND_METRIC_LABEL } from '@/stores/spend'
|
||||
import type { AdminTotalsResponse, HistoryMetric, HistoryWindow } from '@/types/api'
|
||||
|
||||
/** DrilldownRow is one GET /admin/api/usage/totals row (types/api.ts's AdminTotalsResponse.rows entry). */
|
||||
type DrilldownRow = AdminTotalsResponse['rows'][number]
|
||||
|
||||
/**
|
||||
* AttributionDrilldown (redesign-plan.md section 3.4) descends group ->
|
||||
* users (GET /admin/api/usage/totals?kind=user&group=) -> models (kind=
|
||||
* usermodel, only when AdminFeaturesView.userModelStats — the config's
|
||||
* admin.stats.userModel), breadcrumbs tracked in the `drill` page param
|
||||
* (section 3.1). This component owns no fetch itself — CONTROLLED, like
|
||||
* CostAvoidedCard.vue's own `ref` prop — stores/spend.ts's fetchDrilldown
|
||||
* reads `drill` and supplies `rows`/`metrics`/`disabled`; every click here
|
||||
* only emits `update:drill`, letting SpendPage.vue keep it in nav.params
|
||||
* (so a reload or shared link restores the same drilldown position).
|
||||
*
|
||||
* `userModelStatsEnabled` gates whether a USER row is clickable at all
|
||||
* (redesign-plan.md's own "only when features.userModelStats, else hint
|
||||
* naming the config key") — checked client-side from the already-polled
|
||||
* overview response, before ever firing a request that would only come
|
||||
* back 404. `disabled` (from the store, a REAL 404) is the fallback for
|
||||
* the deep-link case: a reader who lands directly on `drill=user:x` via a
|
||||
* restored hash before this prop has had a chance to gate the click.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
rows: DrilldownRow[]
|
||||
metrics: string[]
|
||||
drill: string
|
||||
disabled: boolean
|
||||
userModelStatsEnabled: boolean
|
||||
/** The global filters store's current window/span (N3 fix) — ClampedRangeNotice's own props, forwarded so this stays a controlled, props-driven component rather than reaching into stores/filters.ts itself. */
|
||||
window: HistoryWindow
|
||||
span: number
|
||||
/** spend.drilldownLoading (verify-ui-states.md #3 fix) — this card had no loading/error input at all: `spend.drilldownRows` starts as [], so the very first Spend load, and any failed drilldown fetch, rendered the identical "No traffic in this range." a genuinely empty group/user/model list gets. */
|
||||
loading: boolean
|
||||
/**
|
||||
* spend.drilldownLoaded (verify-ui-states-2.md #2 fix) — "has a fetch
|
||||
* completed for the current window/span/drill selection", not
|
||||
* `rows.length > 0`: the 60s poll flips `loading` true on every tick, and
|
||||
* a genuinely empty level (e.g. a group with no users) used to flash a
|
||||
* skeleton back on for each tick. `noTrafficInRange` below still checks
|
||||
* `rows.length` directly for EmptyState vs. the real table.
|
||||
*/
|
||||
loaded: boolean
|
||||
error: string
|
||||
/** Renders ErrorState's own "Retry" button — SpendPage.vue's own spend.fetchDrilldown. */
|
||||
onRetry?: () => void | Promise<void>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:drill': [value: string] }>()
|
||||
|
||||
const level = computed(() => drilldownLevel(props.drill))
|
||||
|
||||
/**
|
||||
* parentGroupLabel is a BEST-EFFORT breadcrumb label for the group a
|
||||
* drilled-into user belongs to — the `drill` param itself only ever
|
||||
* encodes the current LEAF selection (`user:{id}`, redesign-plan.md
|
||||
* section 3.1's own `drill=group:x|user:x` shape has no room for a
|
||||
* compound path), so this is tracked as local component state, set at
|
||||
* the moment a user row is clicked FROM the user-list level. A reader who
|
||||
* lands directly on `drill=user:x` via a restored hash sees no middle
|
||||
* breadcrumb segment — an acceptable, honest degradation (nothing else
|
||||
* available in `drill` records it) rather than a fabricated group name.
|
||||
*/
|
||||
const parentGroupLabel = ref('')
|
||||
|
||||
function goToGroups(): void {
|
||||
emit('update:drill', '')
|
||||
}
|
||||
function goToParentGroup(): void {
|
||||
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', makeScope('group', id))
|
||||
} else if (l.kind === 'user' && props.userModelStatsEnabled) {
|
||||
parentGroupLabel.value = l.group
|
||||
emit('update:drill', makeScope('user', id))
|
||||
}
|
||||
}
|
||||
|
||||
const idColumnLabel = computed<string>(() => (level.value.kind === 'group' ? 'Group' : level.value.kind === 'user' ? 'User' : 'Model'))
|
||||
|
||||
/** Row id is clickable to drill further at the group level always, and at the user level only when userModelStatsEnabled — the leaf (usermodel) level renders the model id as an EntityLink to the Models page instead, since there is nowhere further to drill. */
|
||||
function idCell(row: DrilldownRow) {
|
||||
const l = level.value
|
||||
if (l.kind === 'usermodel') return h(EntityLink, { label: row.id, kind: 'model', id: row.id })
|
||||
const clickable = l.kind === 'group' || props.userModelStatsEnabled
|
||||
if (!clickable) return h('span', {}, row.id)
|
||||
return h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class:
|
||||
'inline-flex cursor-pointer items-center gap-1 rounded-sm hover:text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',
|
||||
onClick: () => onRowClick(row.id),
|
||||
},
|
||||
[row.id, h(FontAwesomeIcon, { icon: faChevronRight, class: 'size-3', 'aria-hidden': 'true' })],
|
||||
)
|
||||
}
|
||||
|
||||
const columns = computed<ColumnDef<DrilldownRow, unknown>[]>(() => [
|
||||
{ id: 'id', header: idColumnLabel.value, accessorFn: (r) => r.id, cell: ({ row }) => idCell(row.original) },
|
||||
...props.metrics.map(
|
||||
(metric): ColumnDef<DrilldownRow, unknown> => ({
|
||||
id: metric,
|
||||
header: SPEND_METRIC_LABEL[metric as HistoryMetric] ?? metric,
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (r) => r.values[metric] ?? 0,
|
||||
cell: ({ row }) => {
|
||||
const value = row.original.values[metric] ?? 0
|
||||
return metric === 'cost' ? formatCost(value) : h(CompactNumber, { value })
|
||||
},
|
||||
}),
|
||||
),
|
||||
])
|
||||
|
||||
const showUserModelHint = computed<boolean>(() => level.value.kind === 'user' && (!props.userModelStatsEnabled || props.disabled))
|
||||
|
||||
const state = computed(() => loadState({ loading: props.loading, hasData: props.loaded, error: props.error }))
|
||||
|
||||
/**
|
||||
* noTrafficInRange (states-plan.md item 2: "Spend/Models/Home lists: 'No
|
||||
* traffic in this range'") is the genuine "nothing to show" case — gated
|
||||
* directly on `rows.length === 0` (verify-ui-states-2.md #2 fix; `state`
|
||||
* no longer distinguishes empty from non-empty once `loaded` is true, see
|
||||
* this component's own `loaded` prop doc comment), the same way
|
||||
* UserDetail.vue's own "Models used" table checks `!modelRows.length`. The
|
||||
* template below still checks `state === 'skeleton'`/`'error'` FIRST, so a
|
||||
* first/failed fetch never reaches this branch. Never true alongside
|
||||
* showUserModelHint, which takes precedence in the template below (that
|
||||
* state has its own, more specific copy).
|
||||
*/
|
||||
const noTrafficInRange = computed<boolean>(() => !showUserModelHint.value && props.rows.length === 0)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Attribution</CardTitle>
|
||||
<CardDescription>Drill from groups into users into the models they used.</CardDescription>
|
||||
<nav aria-label="Breadcrumb" class="flex flex-wrap items-center gap-1.5 text-sm text-muted-foreground">
|
||||
<button type="button" class="hover:text-foreground hover:underline" :disabled="level.kind === 'group'" @click="goToGroups">
|
||||
All groups
|
||||
</button>
|
||||
<template v-if="level.kind === 'user'">
|
||||
<FontAwesomeIcon :icon="faChevronRight" class="size-3" aria-hidden="true" />
|
||||
<span class="font-medium text-foreground">{{ level.group }}</span>
|
||||
</template>
|
||||
<template v-if="level.kind === 'usermodel'">
|
||||
<FontAwesomeIcon :icon="faChevronRight" class="size-3" aria-hidden="true" />
|
||||
<button v-if="parentGroupLabel" type="button" class="hover:text-foreground hover:underline" @click="goToParentGroup">
|
||||
{{ parentGroupLabel }}
|
||||
</button>
|
||||
<FontAwesomeIcon :icon="faChevronRight" class="size-3" aria-hidden="true" />
|
||||
<span class="font-medium text-foreground">{{ level.user }}</span>
|
||||
</template>
|
||||
</nav>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-3">
|
||||
<ClampedRangeNotice v-if="level.kind === 'usermodel'" :window="window" :span="span" />
|
||||
<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.">
|
||||
<TryLongerRangeButton />
|
||||
</EmptyState>
|
||||
<DataTable v-else :columns="columns" :data="rows" empty-message="No models recorded for this user in this range." label="Per-model attribution" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -1,26 +0,0 @@
|
||||
<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,101 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from '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 { BUDGET_LINE_MAX_RATIO, budgetLineVisible, cumulative, runOutDate } from '@/lib/burndown'
|
||||
import { NOT_ENOUGH_DATA } from '@/lib/forecast'
|
||||
import { formatBucketLabel, formatCostAxis, formatCostDisplay, formatShortDate } from '@/lib/format'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
|
||||
/**
|
||||
* BurnDownChart (redesign-plan.md section 3.4) renders the current UTC
|
||||
* calendar month's cumulative spend against its configured budget: a
|
||||
* solid line (lib/burndown.ts's `cumulative`, run over the store's own raw
|
||||
* per-day points — see stores/spend.ts's own doc comment on why the
|
||||
* running-sum step lives here rather than in the store) plus, when a
|
||||
* budget is configured, a dashed reference line at that flat limit
|
||||
* (TimeSeriesChart's own `comparisonDatasets` — a budget ceiling is
|
||||
* exactly the "reference overlay, not a component of the current total"
|
||||
* that prop already documents) and the projected run-out date
|
||||
* (lib/burndown.ts's runOutDate, MTD average daily rate).
|
||||
*
|
||||
* `now` is a required prop, not read from `new Date()` internally —
|
||||
* CostForecastCard.vue's own doc comment explains why a component-local
|
||||
* default silently freezes at first mount (Vue caches a prop default
|
||||
* once per instance): the caller passes the SAME shared clock
|
||||
* (composables/useNow.ts) every other time-dependent read on the page
|
||||
* shares.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
/** Day-window bucket keys, oldest first (limits.go's "20060102" format — lib/format.ts's formatBucketLabel). */
|
||||
buckets: string[]
|
||||
/** Raw (not cumulative) per-day cost in micro-USD, index-aligned with `buckets`. */
|
||||
points: number[]
|
||||
/** The scope's configured cost/month budget in micro-USD, or null when none is configured. */
|
||||
budgetMicros: number | null
|
||||
now: Date
|
||||
/** spend.burndownLoading (verify-ui-states.md #7 fix, Spend page gap) — this card had no loading/error input at all before: `buckets` starts as [], so the very first Spend load, and any failed burn-down fetch, rendered a flat all-zero chart with no indication either was happening. */
|
||||
loading?: boolean
|
||||
error?: string
|
||||
/** Renders ErrorState's own "Retry" button — SpendPage.vue's own spend.refresh (fetchBurndown has no standalone public retry of its own). */
|
||||
onRetry?: () => void | Promise<void>
|
||||
}>()
|
||||
|
||||
const state = computed(() => loadState({ loading: props.loading ?? false, hasData: props.buckets.length > 0, error: props.error ?? '' }))
|
||||
|
||||
const labels = computed<string[]>(() => props.buckets.map((b) => formatBucketLabel(b, 'day')))
|
||||
const cumulativePoints = computed<number[]>(() => cumulative(props.points))
|
||||
const spentMicros = computed<number>(() => cumulativePoints.value.at(-1) ?? 0)
|
||||
|
||||
const datasets = computed<TimeSeriesDataset[]>(() => [{ label: 'Spent (MTD)', data: cumulativePoints.value, color: '--chart-cost' }])
|
||||
|
||||
const comparisonDatasets = computed<TimeSeriesDataset[]>(() => {
|
||||
if (props.budgetMicros === null || !budgetLineVisible(spentMicros.value, props.budgetMicros)) return []
|
||||
const flat = new Array<number>(cumulativePoints.value.length).fill(props.budgetMicros)
|
||||
return [{ label: 'Budget', data: flat, color: '--destructive' }]
|
||||
})
|
||||
|
||||
const runOut = computed<Date | null>(() => (props.budgetMicros === null ? null : runOutDate(spentMicros.value, props.budgetMicros, props.now)))
|
||||
|
||||
const willExceed = computed<boolean>(() => props.budgetMicros !== null && spentMicros.value >= props.budgetMicros)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<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'">{{ formatCostDisplay(spentMicros) }}</StatItem>
|
||||
<StatItem v-if="budgetMicros !== null" label="Budget">{{ formatCostDisplay(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>
|
||||
<p v-else-if="comparisonDatasets.length === 0" class="text-sm text-muted-foreground">
|
||||
Budget line hidden: it is more than {{ BUDGET_LINE_MAX_RATIO }}× current spend and would flatten the curve.
|
||||
</p>
|
||||
<TimeSeriesChart
|
||||
:labels="labels"
|
||||
:datasets="datasets"
|
||||
:comparison-datasets="comparisonDatasets"
|
||||
:value-formatter="formatCostDisplay"
|
||||
:axis-formatter="formatCostAxis"
|
||||
ariaLabel="Cumulative spend this month against the configured budget"
|
||||
/>
|
||||
</div>
|
||||
</ChartCard>
|
||||
</template>
|
||||
@@ -1,55 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import GrantForm from '@/components/forms/GrantForm.vue'
|
||||
import LimitsForm from '@/components/forms/LimitsForm.vue'
|
||||
import ModelMetaForm from '@/components/forms/ModelMetaForm.vue'
|
||||
import PricingForm from '@/components/forms/PricingForm.vue'
|
||||
import RouterForm from '@/components/forms/RouterForm.vue'
|
||||
import UserForm from '@/components/forms/UserForm.vue'
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { HELPER_IDS, HELPER_LABEL } from '@/lib/helper-forms'
|
||||
import type { HelperId } from '@/lib/helper-forms'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
/**
|
||||
* ChangeHelper (redesign-plan.md section 3.4) is the Config page's
|
||||
* snippet-building surface: six forms (LimitsForm, GrantForm,
|
||||
* PricingForm, ModelMetaForm, RouterForm, UserForm), each producing a paste-ready
|
||||
* YAML/users.json fragment via lib/snippets.ts, switched by the page's own
|
||||
* `helper` hash param so a shared link opens the same tab.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
groupNames: string[]
|
||||
userNames: string[]
|
||||
}>()
|
||||
|
||||
const nav = useNavStore()
|
||||
|
||||
const helper = computed<HelperId>(() => {
|
||||
const value = nav.params.helper
|
||||
return (HELPER_IDS as readonly string[]).includes(value ?? '') ? (value as HelperId) : 'limits'
|
||||
})
|
||||
|
||||
function setHelper(next: unknown): void {
|
||||
if (typeof next !== 'string' || !(HELPER_IDS as readonly string[]).includes(next)) return
|
||||
nav.goTo('config', { ...nav.params, helper: next })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<Tabs :model-value="helper" @update:model-value="setHelper">
|
||||
<TabsList>
|
||||
<TabsTrigger v-for="id in HELPER_IDS" :key="id" :value="id">{{ HELPER_LABEL[id] }}</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
|
||||
<LimitsForm v-if="helper === 'limits'" :group-names="props.groupNames" :user-names="props.userNames" />
|
||||
<GrantForm v-else-if="helper === 'grant'" :group-names="props.groupNames" :user-names="props.userNames" />
|
||||
<PricingForm v-else-if="helper === 'pricing'" />
|
||||
<ModelMetaForm v-else-if="helper === 'model'" />
|
||||
<RouterForm v-else-if="helper === 'router'" />
|
||||
<UserForm v-else :group-names="props.groupNames" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,124 +0,0 @@
|
||||
<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
|
||||
axisFormatter?: (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"
|
||||
:axis-formatter="axisFormatter"
|
||||
: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"
|
||||
:axis-formatter="axisFormatter"
|
||||
:ariaLabel="ariaLabel"
|
||||
/>
|
||||
</slot>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -1,38 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { dayOrMonthClampNotice } from '@/lib/range'
|
||||
import type { HistoryWindow } from '@/types/api'
|
||||
|
||||
/**
|
||||
* ClampedRangeNotice (N3 fix, verify-redesign-final.md) is the ONE shared
|
||||
* "this view silently clamped your range" banner for every day/month-only
|
||||
* endpoint reached through lib/range.ts's dayOrMonthWindow:
|
||||
* - UserDetail.vue's "Models used" table (usermodel totals)
|
||||
* - AttributionDrilldown.vue's usermodel level (the Spend drilldown)
|
||||
* - TargetCallers.vue (targetcaller totals)
|
||||
* An hour-resolution global range (24h/48h) has no day/month equivalent
|
||||
* for any of these — dayOrMonthWindow silently substitutes a fixed
|
||||
* 7-day day-window instead, and this renders nothing (dayOrMonthClampNotice
|
||||
* returns null) unless that substitution actually happened, so a
|
||||
* day/month-window reader never sees a spurious banner.
|
||||
*
|
||||
* Distinct from ReliabilityPage.vue's own inline month-clamp Alert — a
|
||||
* DIFFERENT clamp (hour/day -> a fixed 30-day window, stores/
|
||||
* reliability.ts's hourOrDayWindow) that stays its own local computed,
|
||||
* not this component.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
window: HistoryWindow
|
||||
span: number
|
||||
}>()
|
||||
|
||||
const note = computed<string | null>(() => dayOrMonthClampNotice(props.window, props.span))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Alert v-if="note" variant="warn">
|
||||
<AlertDescription>{{ note }}</AlertDescription>
|
||||
</Alert>
|
||||
</template>
|
||||
@@ -1,37 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import SnippetBlock from '@/components/SnippetBlock.vue'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { emitYamlDocument, toYamlValue } from '@/lib/yaml-emit'
|
||||
import type { YamlValue } from '@/lib/yaml-emit'
|
||||
|
||||
/**
|
||||
* ConfigTree (redesign-plan.md section 3.4) renders GET /admin/api/config's
|
||||
* already-redacted `config` (admin_config.go's redactConfig — every
|
||||
* apiKey/password literal replaced with "[redacted]", an "env:NAME"/
|
||||
* "file:/path" indirection kept, every baseUrl/url stripped of userinfo)
|
||||
* as read-only YAML via lib/yaml-emit.ts's generic recursive renderer —
|
||||
* safe to render as-is, never re-sanitized client-side (types/api.ts's
|
||||
* AdminConfigResponse doc comment).
|
||||
*/
|
||||
const props = defineProps<{
|
||||
config: Record<string, unknown>
|
||||
warnings: string[]
|
||||
}>()
|
||||
|
||||
const yamlText = computed(() => {
|
||||
const value = toYamlValue(props.config) as Record<string, YamlValue | undefined>
|
||||
return emitYamlDocument(value)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<Alert v-for="(warning, index) in warnings" :key="index" variant="warn">
|
||||
<AlertTitle>Config warning</AlertTitle>
|
||||
<AlertDescription>{{ warning }}</AlertDescription>
|
||||
</Alert>
|
||||
<SnippetBlock label="Redacted running config (read-only)" :text="yamlText" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,492 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
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 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 UsageTable from '@/components/UsageTable.vue'
|
||||
import { useNow } from '@/composables/useNow'
|
||||
import { useSearchQuery } from '@/composables/useSearchQuery'
|
||||
import { monthCostProjection, NOT_ENOUGH_DATA, WILL_EXCEED_TITLE } from '@/lib/forecast'
|
||||
import { formatCostDisplay, formatLimits } from '@/lib/format'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { type ExpandState, clearExpandOverrides, computeExpandedItems, toggleItemExpand } from '@/lib/search-expand'
|
||||
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'
|
||||
import { useConsumersStore } from '@/stores/consumers'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
import type { AdminUsageEntryView } from '@/types/api'
|
||||
|
||||
/**
|
||||
* ConsumerDirectory (redesign-plan.md section 3.4) is the Consumers page's
|
||||
* default view: the Users/Groups usage-and-access directory that used to
|
||||
* be UsageView.vue's whole tab, moved here verbatim (the Groups accordion
|
||||
* + its access block included, per the coordinator's own instruction) with
|
||||
* three redesign-era changes: nav.usageQuery -> the page's own `q` hash
|
||||
* param (stores/nav.ts no longer special-cases a search string), the id
|
||||
* cell's ScopeLink -> EntityLink (usage-columns.ts, opens this row's own
|
||||
* UserDetail instead of jumping to the old flat Charts tab), and a new
|
||||
* Source column (inline/file, GET /admin/api/consumers) on the flat Users
|
||||
* table only.
|
||||
*/
|
||||
/** Rows per page in the flat Users table: keeps a 30+ user fleet scannable. */
|
||||
const USERS_PAGE_SIZE = 25
|
||||
|
||||
const dashboard = useDashboardStore()
|
||||
const consumers = useConsumersStore()
|
||||
const nav = useNavStore()
|
||||
const usage = computed(() => dashboard.usage)
|
||||
|
||||
/**
|
||||
* dashboardLoadState (verify-ui-states.md #3) gates the Groups/Users
|
||||
* cards' own skeleton/error — `hasData` is "has GET /admin/api/usage EVER
|
||||
* landed", not "are there any groups/users": a fleet with genuinely zero
|
||||
* groups/users still reads 'ready' and falls through to the EXISTING
|
||||
* noGroupsConfigured/usersEmptyMessage copy below, unchanged. Mirrors
|
||||
* HomePage.vue's own identical kpiTilesState convention (verify-ui-states-2.
|
||||
* md #11: this comment named the old kpiTilesLoading identifier, since
|
||||
* renamed) — both read the same polled dashboard store. Previously
|
||||
* `noGroupsConfigured`/
|
||||
* `usersEmptyMessage` read `usage.value?.groups/users.length ?? 0 === 0`
|
||||
* directly, which was ALSO true before the first successful fetch (or
|
||||
* after a failed one) — "No groups/users configured" rendered as a false
|
||||
* fleet fact while the real state was "not loaded yet" or "failed".
|
||||
*/
|
||||
const dashboardLoadState = computed(() => loadState({ loading: !dashboard.lastUpdated, hasData: usage.value !== null, error: dashboard.error }))
|
||||
|
||||
onMounted(() => {
|
||||
void consumers.ensureConsumers()
|
||||
})
|
||||
|
||||
// The one shared reactive clock every time-dependent read on this page uses
|
||||
// (P1, composables/useNow.ts's own doc comment) — CostForecastCard's own
|
||||
// elapsedFraction, usageColumns()'s `now` parameter (both the real Users/
|
||||
// Members <table>s below and the headless Groups toolbar's groupColumns),
|
||||
// and groupCostProjection all read THIS ref, never their own `new Date()`.
|
||||
const { now, start: startClock, stop: stopClock } = useNow()
|
||||
onMounted(startClock)
|
||||
onUnmounted(stopClock)
|
||||
|
||||
/** memberCounts maps a group name to its member count — only the Overview response carries it. */
|
||||
const memberCounts = computed<Record<string, number>>(() => {
|
||||
const out: Record<string, number> = {}
|
||||
for (const g of dashboard.overview?.groups ?? []) out[g.name] = g.memberCount
|
||||
return out
|
||||
})
|
||||
|
||||
/** groupNameOf renders a user's FULL group membership (multi-group support — entry.groups ?? [entry.groupName], never groupName alone, see AdminUsageEntryView.groups' own doc comment), comma-joined for the Group column. */
|
||||
function groupNameOf(entry: AdminUsageEntryView): string {
|
||||
return (entry.groups ?? (entry.groupName === undefined ? [] : [entry.groupName])).join(', ')
|
||||
}
|
||||
function memberCountOf(entry: AdminUsageEntryView): string {
|
||||
const count = memberCounts.value[entry.id]
|
||||
return count === undefined ? '' : String(count)
|
||||
}
|
||||
|
||||
/** sourceOf (Consumers redesign) joins a usage entry's id against GET /admin/api/consumers' own users list — 'inline' or 'file' (admin.go: adminConsumerUser.Source), undefined until that on-demand fetch resolves or for an id it has no match for (a group row never has one). Passed to usage-columns.ts's usageColumns() as `sourceValue` — see that module's sourceColumn doc comment. */
|
||||
function sourceOf(entry: AdminUsageEntryView): string | undefined {
|
||||
return consumers.data?.users.find((u) => u.name === entry.id)?.source
|
||||
}
|
||||
|
||||
// --- user/group search filter (operator feature) ---
|
||||
// Matching logic lives in lib/usage-search.ts. Bound to nav.params.q so
|
||||
// the search text round-trips through the URL hash (#consumers?q=...,
|
||||
// lib/hash-state.ts) — stores/nav.ts's own `params` is opaque, so this
|
||||
// page owns interpreting/writing its own `q` key directly, rather than
|
||||
// the old nav.usageQuery special case.
|
||||
const usageQuery = computed<string>({
|
||||
get: () => nav.params.q ?? '',
|
||||
set: (value) => nav.goTo('users', { ...nav.params, q: value }),
|
||||
})
|
||||
const { query: userQuery, normalized: normalizedQuery, hasQuery } = useSearchQuery(usageQuery)
|
||||
|
||||
/** filteredGroups is every group matching the query — own name OR a matching member (lib/usage-search.ts's groupMatches) — or every group when there is no query. */
|
||||
const filteredGroups = computed<AdminUsageEntryView[]>(() => {
|
||||
const all = usage.value?.groups ?? []
|
||||
if (!hasQuery.value) return all
|
||||
const users = usage.value?.users ?? []
|
||||
return all.filter((g) => groupMatches(g, users, normalizedQuery.value))
|
||||
})
|
||||
|
||||
/** memberOnlyMatchIds is filteredGroups narrowed to groups that matched ONLY via a member, never via their own name — the auto-expand target set (search-expand.ts's computeExpandedItems `matchingIds`). A group's own name is already legible on its collapsed trigger row, so only a member-only match needs auto-expansion to reveal what matched. */
|
||||
const memberOnlyMatchIds = computed<string[]>(() => {
|
||||
if (!hasQuery.value) return []
|
||||
return filteredGroups.value.filter((g) => !groupNameMatches(g, normalizedQuery.value)).map((g) => g.id)
|
||||
})
|
||||
|
||||
/** visibleMembers: a group matched by its OWN name shows every member; a group that matched only via a member shows only the matching ones. */
|
||||
function visibleMembers(group: AdminUsageEntryView): AdminUsageEntryView[] {
|
||||
const users = usage.value?.users ?? []
|
||||
if (!hasQuery.value || groupNameMatches(group, normalizedQuery.value)) return membersOfGroup(group, users)
|
||||
return matchingMembersOfGroup(group, users, normalizedQuery.value)
|
||||
}
|
||||
|
||||
const groupsEmptyMessage = computed(() =>
|
||||
!usage.value?.groups.length ? 'none configured' : hasQuery.value ? `no groups match "${userQuery.value}"` : 'none',
|
||||
)
|
||||
|
||||
/** noGroupsConfigured (states-plan.md item 2: "Consumers: 'No groups configured' + hint to the Config page change helper") — mirrors AccessMatrix.vue's identical own noGroupsConfigured, the Access matrix view's own copy of this same "Consumers" page fact. Only true when genuinely nothing is configured, never while a search query merely matches none (groupsEmptyMessage's own "no groups match" case keeps its plain inline text — a filter producing zero rows is a routine interaction, not a fleet-configuration fact worth the same visual weight). */
|
||||
const noGroupsConfigured = computed(() => (usage.value?.groups.length ?? 0) === 0 && !hasQuery.value)
|
||||
|
||||
/** filteredUsers is every user matching the query directly, PLUS every member of a group that matched by NAME. */
|
||||
const filteredUsers = computed<AdminUsageEntryView[]>(() => {
|
||||
const all = usage.value?.users ?? []
|
||||
if (!hasQuery.value) return all
|
||||
const groups = usage.value?.groups ?? []
|
||||
const nameMatchedGroupIds = new Set(groups.filter((g) => groupNameMatches(g, normalizedQuery.value)).map((g) => g.id))
|
||||
return all.filter(
|
||||
(u) => userMatches(u, normalizedQuery.value) || (u.groups ?? [u.groupName]).some((g) => g !== undefined && nameMatchedGroupIds.has(g)),
|
||||
)
|
||||
})
|
||||
const usersEmptyMessage = computed(() =>
|
||||
!usage.value?.users.length ? 'none configured' : hasQuery.value ? `no users match "${userQuery.value}"` : 'none',
|
||||
)
|
||||
|
||||
// --- Groups accordion ---
|
||||
//
|
||||
// Groups render as a shadcn-vue Accordion — expanding a group shows its
|
||||
// member users' own usage rows below it. "Sortable groups usage" is
|
||||
// implemented headlessly: the SAME usageColumns() defs the real <table>-
|
||||
// based UsageTable uses drive a second, unrendered useVueTable instance
|
||||
// here purely for its getSortedRowModel() — sortedGroupRows below. The
|
||||
// small button toolbar under the Groups heading toggles that sort using
|
||||
// the identical SortHeaderButton DataTable.vue's real <th>s use.
|
||||
const groupColumns = computed(() => usageColumns('Name', 'Members', memberCountOf, now.value))
|
||||
const groupSorting = ref<SortingState>([])
|
||||
const groupsTable = useVueTable({
|
||||
get data() {
|
||||
return filteredGroups.value
|
||||
},
|
||||
get columns() {
|
||||
return groupColumns.value
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
onSortingChange: (updater) => valueUpdater(updater, groupSorting),
|
||||
state: {
|
||||
get sorting() {
|
||||
return groupSorting.value
|
||||
},
|
||||
},
|
||||
})
|
||||
const sortedGroupRows = computed(() => groupsTable.getRowModel().rows)
|
||||
|
||||
/** TOOLBAR_COLUMN_IDS restricts the toolbar to exactly the fields each trigger row displays (Name, Members, req/day, cost/day) — the full stat set stays available inside each expanded item's own detail grid, just not as a sort key here. */
|
||||
const TOOLBAR_COLUMN_IDS = new Set(['id', 'secondary', 'reqDay', 'costDay'])
|
||||
const toolbarHeaders = computed(() => groupsTable.getHeaderGroups()[0].headers.filter((header) => TOOLBAR_COLUMN_IDS.has(header.column.id)))
|
||||
|
||||
/** Which groups are open — driven by the shared tested lib/search-expand.ts state. */
|
||||
const groupExpandState: ExpandState = reactive({
|
||||
manuallyExpanded: new Set<string>(),
|
||||
manuallyCollapsed: new Set<string>(),
|
||||
})
|
||||
const expandedGroups = computed<Set<string>>(() => computeExpandedItems(groupExpandState, hasQuery.value, memberOnlyMatchIds.value))
|
||||
function toggleGroup(id: string): void {
|
||||
toggleItemExpand(groupExpandState, id, expandedGroups.value.has(id))
|
||||
}
|
||||
const expandedGroupValues = computed<string[]>({
|
||||
get: () => Array.from(expandedGroups.value),
|
||||
set: (newValues) => {
|
||||
const next = new Set(newValues)
|
||||
for (const id of expandedGroups.value) {
|
||||
if (!next.has(id)) toggleGroup(id)
|
||||
}
|
||||
for (const id of next) {
|
||||
if (!expandedGroups.value.has(id)) toggleGroup(id)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
// A stale manuallyCollapsed suppression from one search must never
|
||||
// silently carry into a later, unrelated one — see ExpandState's own doc
|
||||
// comment.
|
||||
watch(userQuery, (value) => {
|
||||
if (value.trim() === '') clearExpandOverrides(groupExpandState)
|
||||
})
|
||||
|
||||
// --- Access block (moved from UsageView.vue, unchanged) ---
|
||||
const GLOB_HINT = 'Glob pattern — matches like a shell wildcard (*, ?, [...])'
|
||||
|
||||
/** isGlobPattern reports whether one configured models entry is a glob pattern rather than a literal model id — the same special characters path.Match recognizes (auth.go's matchesGlob). */
|
||||
function isGlobPattern(entry: string): boolean {
|
||||
return /[*?[]/.test(entry)
|
||||
}
|
||||
|
||||
/** 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 projection = monthCostProjection(entry, now)
|
||||
return { text: projection.micros === null ? NOT_ENOUGH_DATA : formatCostDisplay(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))
|
||||
const usersSorting = ref<SortingState>([])
|
||||
const usersTable = useVueTable({
|
||||
get data() {
|
||||
return filteredUsers.value
|
||||
},
|
||||
get columns() {
|
||||
return usersColumns.value
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
onSortingChange: (updater) => valueUpdater(updater, usersSorting),
|
||||
state: {
|
||||
get sorting() {
|
||||
return usersSorting.value
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
function usersCsv(): string {
|
||||
return usageCsv(
|
||||
usersTable.getRowModel().rows.map((row) => row.original),
|
||||
'users',
|
||||
groupNameOf,
|
||||
now.value,
|
||||
)
|
||||
}
|
||||
function groupsCsv(): string {
|
||||
return usageCsv(
|
||||
sortedGroupRows.value.map((row) => row.original),
|
||||
'groups',
|
||||
memberCountOf,
|
||||
now.value,
|
||||
)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<SearchInput v-model="userQuery" placeholder="Filter users or groups" class="max-w-sm" />
|
||||
|
||||
<Card v-if="usage">
|
||||
<CardHeader>
|
||||
<CardTitle>Total</CardTitle>
|
||||
<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">
|
||||
<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">{{ formatCostDisplay(usage.total.costPerDayMicroUsd) }}</StatItem>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<CostForecastCard v-if="usage" :mtd-micros="usage.total.costPerMonthMicroUsd" :limits="usage.total.limits" :now="now" />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<CardTitle>Groups</CardTitle>
|
||||
<CardDescription>Expand a group to see its member users' own usage.</CardDescription>
|
||||
</div>
|
||||
<CsvExportButton filename="consumers-groups.csv" :build="groupsCsv" />
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<SkeletonList v-if="dashboardLoadState === 'skeleton'" :rows="3" />
|
||||
<ErrorState v-else-if="dashboardLoadState === 'error'" :message="dashboard.error" :on-retry="dashboard.refresh" />
|
||||
<template v-else>
|
||||
<div v-if="sortedGroupRows.length" class="mb-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs font-medium text-muted-foreground">
|
||||
<span>Sort groups by</span>
|
||||
<SortHeaderButton v-for="header in toolbarHeaders" :key="header.id" :header="header" />
|
||||
</div>
|
||||
|
||||
<Accordion v-if="sortedGroupRows.length" v-model="expandedGroupValues" type="multiple" class="rounded-md border px-3">
|
||||
<AccordionItem v-for="row in sortedGroupRows" :key="row.original.id" :value="row.original.id">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="min-w-0 break-all py-2.5 font-medium">{{ row.original.id }}</span>
|
||||
<AccordionTrigger header-class="flex-1">
|
||||
<span class="sr-only">Group {{ row.original.id }} details</span>
|
||||
<span class="flex flex-1 flex-wrap items-center gap-x-4 gap-y-1 pr-2 text-left">
|
||||
<span class="text-xs text-muted-foreground tabular-nums">{{ dashboard.overview ? memberCountOf(row.original) || '0' : '?' }} members</span>
|
||||
<span class="text-xs text-muted-foreground tabular-nums">
|
||||
<template v-if="row.original.storeDown">?</template>
|
||||
<CompactNumber v-else :value="row.original.requestsPerDay" /> req/day
|
||||
</span>
|
||||
<span class="text-xs text-muted-foreground tabular-nums">
|
||||
{{ row.original.storeDown ? '?' : formatCostDisplay(row.original.costPerDayMicroUsd) }}/day
|
||||
</span>
|
||||
</span>
|
||||
</AccordionTrigger>
|
||||
</div>
|
||||
<AccordionContent>
|
||||
<dl class="mb-3 grid grid-cols-2 gap-x-6 gap-y-1.5 text-sm sm:grid-cols-4">
|
||||
<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">
|
||||
<DetailField label="Limits">{{ formatLimits(row.original.limits, row.original.limitSources) }}</DetailField>
|
||||
<DetailField v-if="row.original.memberLimits" label="Member limits">{{ formatLimits(row.original.memberLimits) }}</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"
|
||||
>
|
||||
<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 ? '?' : formatCostDisplay(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 }}
|
||||
<span v-if="!row.original.storeDown && groupCostProjection(row.original, now).willExceed" class="sr-only">(will exceed limit)</span>
|
||||
</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"
|
||||
secondary-column-label="Group"
|
||||
:entries="visibleMembers(row.original)"
|
||||
:secondary-value="groupNameOf"
|
||||
:now="now"
|
||||
:source-value="sourceOf"
|
||||
/>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
<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>
|
||||
<EmptyState v-else :title="groupsEmptyMessage" />
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<CardTitle>Users</CardTitle>
|
||||
<CardDescription v-if="consumers.data?.usersFile" class="max-w-full truncate" :title="consumers.data.usersFile">File-backed users load from {{ consumers.data.usersFile }}.</CardDescription>
|
||||
</div>
|
||||
<CsvExportButton filename="consumers-users.csv" :build="usersCsv" />
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadStateView :state="dashboardLoadState" :error="dashboard.error" :on-retry="dashboard.refresh" skeleton="table" :rows="5" :cols="5">
|
||||
<UsageTable
|
||||
:page-size="USERS_PAGE_SIZE"
|
||||
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>
|
||||
</template>
|
||||
@@ -1,142 +0,0 @@
|
||||
<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 { costAvoidedMicros, freeRows, pickReferenceModel } from '@/lib/cost-avoided'
|
||||
import { formatCostDisplay } from '@/lib/format'
|
||||
import type { AdminCatalogModel, AdminUsageModelEntry } from '@/types/api'
|
||||
|
||||
/**
|
||||
* CostAvoidedCard (redesign-plan.md section 3.4) reports what the fleet's
|
||||
* free-tier traffic in range WOULD have cost against a real, priced
|
||||
* reference model — lib/cost-avoided.ts's own doc comment has the unit
|
||||
* derivation. The reference model defaults to the most-requested priced
|
||||
* model actually served in range (pickReferenceModel) but is always
|
||||
* reader-overridable via the picker below; `ref` is a CONTROLLED prop
|
||||
* (this card owns no picker state itself), mirroring DataTable.vue's own
|
||||
* `sorting`/`update:sorting` convention — SpendPage.vue keeps the current
|
||||
* choice in the `ref` page param (redesign-plan.md section 3.1) so a
|
||||
* reload or shared link restores the same comparison.
|
||||
*
|
||||
* Cache savings (redesign-plan.md section 3.4: "cache savings (sum csave)
|
||||
* shown alongside when enabled") render as a second figure beside the
|
||||
* cost-avoided one, only when `cacheStatsEnabled` — a genuinely different
|
||||
* saving (a repeat request served from cache, never re-billed at all) that
|
||||
* would otherwise be easy to conflate with "served by a free model".
|
||||
*
|
||||
* N2 fix (verify-redesign-final.md): the figure is not always summable.
|
||||
* `cacheSavingsAvailable` (lib/cache-savings.ts's own doc comment has the
|
||||
* full backend grounding) is false for an hour-window range — the
|
||||
* backend never writes a per-hour cache-savings bucket at all, so
|
||||
* `m.cacheSavedMicroUsd` is undefined on every row and summing it would
|
||||
* silently render a fabricated "$0.00" rather than "no data for this
|
||||
* range". The card renders "n/a" instead whenever it is false.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
/** The model ranking (GET /admin/api/usage/models, detail=1) — every free row feeds costAvoidedMicros; every catalog-priced row is a candidate reference model. */
|
||||
models: AdminUsageModelEntry[]
|
||||
catalog: Map<string, AdminCatalogModel>
|
||||
/**
|
||||
* The reader's explicit reference-model override (the `ref` page param),
|
||||
* or '' for "use the default". Named `refModel`, not `ref` — `ref` is a
|
||||
* reserved Vue template attribute (component template refs); a prop
|
||||
* literally named `ref` can never be set from a parent's template via
|
||||
* `:ref="..."`, since Vue always intercepts that binding for its own
|
||||
* template-ref mechanism instead of passing it through as a prop.
|
||||
*/
|
||||
refModel: string
|
||||
/** AdminFeaturesView.cacheStats — gates the cache-savings figure. */
|
||||
cacheStatsEnabled: boolean
|
||||
/**
|
||||
* cacheSavingsAvailable (N2 fix, lib/cache-savings.ts's own
|
||||
* cacheSavingsStatus) — false for an hour-window range, where the
|
||||
* backend has no per-hour cache-savings bucket at all. The card
|
||||
* renders "n/a" instead of a figure when this is false, never a
|
||||
* fabricated "$0.00". SpendPage.vue computes this from the current
|
||||
* global range (it owns the filters store; this card stays a pure,
|
||||
* props-driven component).
|
||||
*/
|
||||
cacheSavingsAvailable: boolean
|
||||
/**
|
||||
* cacheSavingsNote (N2 fix) — a caveat to show ALONGSIDE an available
|
||||
* figure (currently only the month-window "35-day retention" note,
|
||||
* lib/cache-savings.ts), or the reason text when
|
||||
* `cacheSavingsAvailable` is false. Null when the figure is available
|
||||
* and exact (day-window ranges).
|
||||
*/
|
||||
cacheSavingsNote?: string | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:refModel': [value: string] }>()
|
||||
|
||||
/** priceableOptions is the picker's own list: every served model whose catalog entry is genuinely priced (excludes free/unpriced — comparing free traffic against another $0 model is meaningless, the same filter pickReferenceModel itself applies), sorted by descending requests so the most relevant choices sit at the top. */
|
||||
const priceableOptions = computed<{ id: string; requests: number }[]>(() => {
|
||||
const out: { id: string; requests: number }[] = []
|
||||
for (const m of props.models) {
|
||||
const cat = props.catalog.get(m.id)
|
||||
if (!cat || cat.priceSource === 'free' || cat.priceSource === 'unpriced') continue
|
||||
out.push({ id: m.id, requests: m.requests ?? 0 })
|
||||
}
|
||||
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>(() =>
|
||||
effectiveReference.value ? props.catalog.get(effectiveReference.value) : undefined,
|
||||
)
|
||||
|
||||
const avoidedMicros = computed<number | null>(() => {
|
||||
const cat = referenceCatalog.value
|
||||
if (!cat || cat.inputPerMTokUsd === undefined || cat.outputPerMTokUsd === undefined) return null
|
||||
return costAvoidedMicros(freeRows(props.models), cat.inputPerMTokUsd, cat.outputPerMTokUsd)
|
||||
})
|
||||
|
||||
const cacheSavedMicros = computed<number>(() => {
|
||||
let total = 0
|
||||
for (const m of props.models) total += m.cacheSavedMicroUsd ?? 0
|
||||
return total
|
||||
})
|
||||
|
||||
function onReferenceUpdate(value: unknown): void {
|
||||
if (typeof value === 'string') emit('update:refModel', value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
<CardHeader class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div>
|
||||
<CardTitle>Cost avoided</CardTitle>
|
||||
<CardDescription>What free-tier traffic in range would have cost at a real model's own rates.</CardDescription>
|
||||
</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>
|
||||
<p class="text-muted-foreground">Cost avoided (free-tier traffic)</p>
|
||||
<p v-if="avoidedMicros === null" class="text-sm text-muted-foreground">
|
||||
{{ priceableOptions.length === 0 ? 'No priced model served in range to compare against.' : 'Pick a reference model above.' }}
|
||||
</p>
|
||||
<p v-else class="text-lg font-semibold tabular-nums text-chart-requests">{{ formatCostDisplay(avoidedMicros) }}</p>
|
||||
</div>
|
||||
<div v-if="cacheStatsEnabled">
|
||||
<p class="text-muted-foreground">Cache savings</p>
|
||||
<p v-if="!cacheSavingsAvailable" class="text-lg font-semibold tabular-nums text-muted-foreground">n/a</p>
|
||||
<p v-else class="text-lg font-semibold tabular-nums text-chart-requests">{{ formatCostDisplay(cacheSavedMicros) }}</p>
|
||||
<p v-if="cacheSavingsNote" class="text-xs text-status-warn">{{ cacheSavingsNote }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -1,69 +0,0 @@
|
||||
<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, NOT_ENOUGH_DATA, projectMonthEnd, WILL_EXCEED_TITLE } from '@/lib/forecast'
|
||||
import { formatCostDisplay } from '@/lib/format'
|
||||
import type { LimitsConfig } from '@/types/api'
|
||||
|
||||
/**
|
||||
* CostForecastCard renders a fleet- or scope-wide cost projection — F7,
|
||||
* originally the pre-redesign Usage tab's own card, now used by both
|
||||
* SpendPage.vue (the global range's own scope, under the burn-down chart)
|
||||
* and ConsumerDirectory.vue (fleet-wide, under the Total row). All math is
|
||||
* delegated to lib/forecast.ts's pure functions; this component only
|
||||
* formats and lays the result out.
|
||||
*
|
||||
* `now` is a REQUIRED prop, not read from `new Date()` inside this
|
||||
* component (coordinator brief: "now passed as prop for determinism") —
|
||||
* every caller supplies it from its OWN composables/useNow.ts instance,
|
||||
* keeping every `Date.now()`-flavored read in this feature at the
|
||||
* boundary rather than buried inside a component, same discipline
|
||||
* lib/forecast.ts's own functions already follow by taking
|
||||
* `now`/`elapsedFraction` as plain arguments.
|
||||
*
|
||||
* P1 review fix: this used to be optional with a `withDefaults(...,
|
||||
* { now: () => new Date() })` default. Vue caches a prop's default value
|
||||
* ONCE per component instance (propsDefaults) — the very first time it is
|
||||
* read, not on every render — so a caller that omitted `now` froze this
|
||||
* card's projection at whatever instant it happened to mount, never
|
||||
* advancing again for as long as the page stayed open. `now` is now
|
||||
* required: every caller passes the ONE shared reactive clock its own
|
||||
* useNow() call returns, so there is no default left to accidentally
|
||||
* freeze.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
/** usage.total.costPerMonthMicroUsd — fleet-wide month-to-date spend. */
|
||||
mtdMicros: number
|
||||
/** usage.total.limits — costPerMonthUSD is the only field this card reads. */
|
||||
limits?: LimitsConfig
|
||||
/** The shared reactive clock (composables/useNow.ts) — never defaulted here, see this comment block above. */
|
||||
now: Date
|
||||
}>()
|
||||
|
||||
const elapsedFraction = computed(() => monthProgress(props.now))
|
||||
const projectedMicros = computed(() => projectMonthEnd(props.mtdMicros, elapsedFraction.value))
|
||||
const forecast = computed(() => headroom(projectedMicros.value, props.limits?.costPerMonthUSD))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Cost forecast</CardTitle>
|
||||
<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">
|
||||
<StatItem label="Month to date">{{ formatCostDisplay(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 ? '' : formatCostDisplay(projectedMicros) }}
|
||||
</StatItem>
|
||||
<StatItem v-if="forecast.limitMicros !== null" label="Limit">{{ formatCostDisplay(forecast.limitMicros) }}</StatItem>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -1,96 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { faCircleCheck, faCircleXmark, faFileCsv } from '@fortawesome/free-solid-svg-icons'
|
||||
import { computed, onBeforeUnmount, ref } from 'vue'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { downloadText, type DownloadOutcome } from '@/lib/download'
|
||||
|
||||
/**
|
||||
* CsvExportButton is the one "Export CSV" control every table export in
|
||||
* this panel uses (F8) — ConsumerDirectory.vue's Users/Groups exports
|
||||
* (lib/usage-csv.ts's usageCsv) and PricingHealthTable.vue's own
|
||||
* pricing-health export each build their own CSV text and pass it
|
||||
* through the same `build` prop — one export affordance, not a copy per
|
||||
* table (vue.md: "if you've written it twice, you owe an abstraction").
|
||||
*
|
||||
* `build` is called fresh on every click, never memoized — an export
|
||||
* always reflects whatever rows are CURRENTLY visible (filtered + sorted)
|
||||
* at click time, matching the coordinator brief ("exports filtered+sorted
|
||||
* rows"), never a stale snapshot captured at mount.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
/** The downloaded file's name, e.g. "usage-users.csv". */
|
||||
filename: string
|
||||
/** Builds the CSV text (lib/csv.ts's toCsv, via usage-csv.ts) on demand. */
|
||||
build: () => string
|
||||
}>()
|
||||
|
||||
/**
|
||||
* exporting guards a rapid double-click from firing two downloads (or two
|
||||
* copyText fallback prompts) back to back — downloadText (lib/download.ts)
|
||||
* is async only because its clipboard fallback is, so this window is
|
||||
* normally imperceptibly short, but a real one regardless.
|
||||
*/
|
||||
const exporting = ref(false)
|
||||
|
||||
/** P5 review fix: downloadText's own return value used to be discarded entirely — a failed export (or a silent clipboard/selection fallback) looked identical to a successful one. `feedback` holds the most recent outcome; the label/icon below reflect it for FEEDBACK_MS, then the button reverts to its normal resting state. */
|
||||
const feedback = ref<DownloadOutcome | null>(null)
|
||||
const FEEDBACK_MS = 2500
|
||||
let feedbackTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const FEEDBACK_LABEL: Record<DownloadOutcome, string> = {
|
||||
downloaded: 'Downloaded',
|
||||
copied: 'Copied',
|
||||
selected: 'Selected — press ⌘/Ctrl+C',
|
||||
failed: 'Export failed',
|
||||
}
|
||||
|
||||
const label = computed(() => (feedback.value ? FEEDBACK_LABEL[feedback.value] : 'Export CSV'))
|
||||
const isFailure = computed(() => feedback.value === 'failed')
|
||||
|
||||
function clearFeedbackAfterDelay(): void {
|
||||
if (feedbackTimer !== undefined) clearTimeout(feedbackTimer)
|
||||
feedbackTimer = setTimeout(() => {
|
||||
feedback.value = null
|
||||
feedbackTimer = undefined
|
||||
}, FEEDBACK_MS)
|
||||
}
|
||||
|
||||
async function onClick(): Promise<void> {
|
||||
if (exporting.value) return
|
||||
exporting.value = true
|
||||
try {
|
||||
// Inline feedback ONLY (verify-ui-states.md #9 fix) — this used to
|
||||
// ALSO push a toast on failure, on top of the button's own "Export
|
||||
// failed" label/icon swap right at the click target: two
|
||||
// notifications for the one event, exactly the double-notify
|
||||
// states-plan.md item 3 says to avoid ("keep one, don't
|
||||
// double-notify"). The inline state is immediate, contextual, and
|
||||
// already dismisses itself after FEEDBACK_MS — a toast added nothing
|
||||
// a reader watching the button they just clicked wouldn't already see.
|
||||
feedback.value = await downloadText(props.filename, props.build())
|
||||
clearFeedbackAfterDelay()
|
||||
} finally {
|
||||
exporting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (feedbackTimer !== undefined) clearTimeout(feedbackTimer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Button type="button" variant="outline" size="sm" class="relative" :disabled="exporting" @click="onClick">
|
||||
<FontAwesomeIcon v-if="feedback === 'failed'" :icon="faCircleXmark" class="size-3.5 text-destructive" aria-hidden="true" />
|
||||
<FontAwesomeIcon
|
||||
v-else-if="feedback"
|
||||
:icon="faCircleCheck"
|
||||
class="size-3.5 text-chart-requests"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<FontAwesomeIcon v-else :icon="faFileCsv" class="size-3.5" aria-hidden="true" />
|
||||
<span :class="isFailure ? 'text-destructive' : undefined">{{ label }}</span>
|
||||
<span class="sr-only" role="status">{{ feedback ? label : '' }}</span>
|
||||
</Button>
|
||||
</template>
|
||||
@@ -1,143 +0,0 @@
|
||||
<script setup lang="ts" generic="TData">
|
||||
import type { ColumnDef, SortingState } from '@tanstack/vue-table'
|
||||
import { FlexRender, getCoreRowModel, getSortedRowModel, useVueTable } from '@tanstack/vue-table'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
import SortHeaderButton from '@/components/SortHeaderButton.vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { pageWindow } from '@/lib/paging'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableEmpty,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
|
||||
/**
|
||||
* DataTable is the shared sortable-table shape every real tabular surface
|
||||
* in the panel uses (users usage, a group's nested member-user rows,
|
||||
* aliases) — the shadcn-vue DataTable pattern
|
||||
* (shadcn-vue.com/docs/components/data-table: useVueTable +
|
||||
* getSortedRowModel + FlexRender), factored into one reusable component
|
||||
* instead of re-writing the same table setup and sortable-header-button
|
||||
* boilerplate at every call site (vue.md: "if you've written it twice,
|
||||
* you owe an abstraction"). Each column stays a plain TanStack
|
||||
* `ColumnDef` — a string `header` label plus an optional custom `cell`
|
||||
* renderer — and this component supplies the uniform
|
||||
* clickable-header-with-asc/desc-icon chrome for every column that does
|
||||
* not explicitly set `enableSorting: false`. `meta: { align: 'right' }`
|
||||
* (declared in ui/table/utils.ts) right-aligns a numeric column's header
|
||||
* button and cell content with tabular-nums, matching this panel's
|
||||
* existing numeric-column convention.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
columns: ColumnDef<TData, unknown>[]
|
||||
data: TData[]
|
||||
/** Extra classes for one row, keyed by its own data (e.g. a destructive tint for a storeDown entry). */
|
||||
rowClass?: (row: TData) => string | undefined
|
||||
/** Shown in the empty-state row when data is empty. */
|
||||
emptyMessage?: string
|
||||
/** Accessible name for the table (aria-label). */
|
||||
label?: string
|
||||
/** Rows per page; omit to show every row. A pager appears only when the data exceeds one page. */
|
||||
pageSize?: number
|
||||
/**
|
||||
* Optional CONTROLLED sort state (P6, `v-model:sorting`). Omitted (the
|
||||
* default) keeps every existing call site's original UNCONTROLLED
|
||||
* behavior unchanged — this component owns `internalSorting` itself and
|
||||
* a caller has no way to read the current sort. Passed, a caller (e.g.
|
||||
* ConsumerDirectory.vue's Users export, which needs to export rows in
|
||||
* the table's own current sort order — the plan's own "exports
|
||||
* filtered+sorted rows" requirement) instead owns the ref: every header
|
||||
* click emits `update:sorting` with the new state rather than mutating
|
||||
* anything locally here.
|
||||
*/
|
||||
sorting?: SortingState
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:sorting': [value: SortingState] }>()
|
||||
|
||||
/** internalSorting is read only when props.sorting is undefined (uncontrolled mode) — see the `sorting` prop's own doc comment above. */
|
||||
const internalSorting = ref<SortingState>([])
|
||||
|
||||
const pageIndex = ref(0)
|
||||
|
||||
const table = useVueTable({
|
||||
get data() {
|
||||
return props.data
|
||||
},
|
||||
get columns() {
|
||||
return props.columns
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
onSortingChange: (updater) => {
|
||||
const current = props.sorting ?? internalSorting.value
|
||||
const next = typeof updater === 'function' ? updater(current) : updater
|
||||
if (props.sorting !== undefined) emit('update:sorting', next)
|
||||
else internalSorting.value = next
|
||||
},
|
||||
state: {
|
||||
get sorting() {
|
||||
return props.sorting ?? internalSorting.value
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const allRows = computed(() => table.getRowModel().rows)
|
||||
const pg = computed(() => pageWindow(allRows.value.length, props.pageSize ?? Math.max(1, allRows.value.length), pageIndex.value))
|
||||
const paged = computed(() => props.pageSize !== undefined && allRows.value.length > props.pageSize)
|
||||
const visibleRows = computed(() => (paged.value ? allRows.value.slice(pg.value.from, pg.value.to) : allRows.value))
|
||||
|
||||
/** ariaSort maps a column's current sort direction to the `aria-sort` value native to a real <th> — set only on the sorted column, per spec. */
|
||||
function ariaSort(dir: false | 'asc' | 'desc'): 'ascending' | 'descending' | undefined {
|
||||
if (dir === 'asc') return 'ascending'
|
||||
if (dir === 'desc') return 'descending'
|
||||
return undefined
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<Table :aria-label="label">
|
||||
<TableHeader>
|
||||
<TableRow v-for="headerGroup in table.getHeaderGroups()" :key="headerGroup.id">
|
||||
<TableHead
|
||||
v-for="header in headerGroup.headers"
|
||||
:key="header.id"
|
||||
:class="header.column.columnDef.meta?.align === 'right' ? 'text-right' : undefined"
|
||||
:aria-sort="header.column.getCanSort() ? (ariaSort(header.column.getIsSorted()) ?? 'none') : undefined"
|
||||
>
|
||||
<SortHeaderButton v-if="header.column.getCanSort()" :header="header" class="-mx-1.5" />
|
||||
<FlexRender v-else-if="!header.isPlaceholder" :render="header.column.columnDef.header" :props="header.getContext()" />
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableEmpty v-if="table.getRowModel().rows.length === 0" :colspan="columns.length" class="text-muted-foreground">
|
||||
{{ emptyMessage ?? 'No rows to show.' }}
|
||||
</TableEmpty>
|
||||
<TableRow v-for="row in visibleRows" :key="row.id" :class="rowClass?.(row.original)">
|
||||
<TableCell
|
||||
v-for="cell in row.getVisibleCells()"
|
||||
:key="cell.id"
|
||||
:class="cell.column.columnDef.meta?.align === 'right' ? 'text-right tabular-nums' : undefined"
|
||||
>
|
||||
<FlexRender :render="cell.column.columnDef.cell" :props="cell.getContext()" />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
<nav v-if="paged" class="flex items-center justify-between gap-2 pt-3 text-xs text-muted-foreground" aria-label="Table pages">
|
||||
<span aria-live="polite">Rows {{ pg.from + 1 }}–{{ pg.to }} of {{ allRows.length }}</span>
|
||||
<span class="flex items-center gap-2">
|
||||
<Button type="button" variant="outline" size="sm" :disabled="pg.index === 0" @click="pageIndex = pg.index - 1">Previous</Button>
|
||||
<span class="tabular-nums">Page {{ pg.index + 1 }} / {{ pg.count }}</span>
|
||||
<Button type="button" variant="outline" size="sm" :disabled="pg.index >= pg.count - 1" @click="pageIndex = pg.index + 1">Next</Button>
|
||||
</span>
|
||||
</nav>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,35 +0,0 @@
|
||||
<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>
|
||||
@@ -1,35 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { faInbox } from '@fortawesome/free-solid-svg-icons'
|
||||
import type { IconDefinition } from '@fortawesome/free-solid-svg-icons'
|
||||
|
||||
/**
|
||||
* EmptyState is the ONE shared "nothing to show, and that's expected"
|
||||
* placeholder every table/list/card in this panel uses instead of an
|
||||
* ad-hoc "no X configured"/"no traffic" text line (states-plan.md item
|
||||
* 2) — an icon, a short title, a one-line description, and an optional
|
||||
* action (a button/link via the default slot, e.g. "Try a longer range"
|
||||
* or a link to the Config page's change helper). `role="status"` — this
|
||||
* is informational, not an error, so it is announced politely
|
||||
* (aria-live="polite" semantics), matching ErrorState.vue's own
|
||||
* `role="alert"` counterpart for the destructive case.
|
||||
*/
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
icon?: IconDefinition
|
||||
title: string
|
||||
description?: string
|
||||
}>(),
|
||||
{ icon: () => faInbox },
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div role="status" class="flex flex-col items-center gap-2 px-4 py-8 text-center">
|
||||
<FontAwesomeIcon :icon="icon" class="size-6 text-muted-foreground/60" aria-hidden="true" />
|
||||
<p class="text-sm font-medium text-foreground">{{ title }}</p>
|
||||
<p v-if="description" class="max-w-sm text-sm text-muted-foreground">{{ description }}</p>
|
||||
<div v-if="$slots.default" class="mt-1">
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,74 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { faArrowUpRightFromSquare } from '@fortawesome/free-solid-svg-icons'
|
||||
|
||||
import AliasBadge from '@/components/AliasBadge.vue'
|
||||
import { useAliasNames } from '@/composables/useAliasNames'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
/**
|
||||
* EntityLink (redesign-plan.md section 3.5) is the redesigned shell's own
|
||||
* navigation link for an entity id: a user id opens Consumers pre-filtered
|
||||
* to that user (lib/usage-columns.ts's id cell, UserDetail.vue), a model
|
||||
* id opens Models pre-filtered to that model (lib/model-table-columns.ts's
|
||||
* id cell) — nav.goTo rather than a bare href, so it stays inside the
|
||||
* SPA's own hash-routed shell. It replaced ScopeLink.vue (deleted, section
|
||||
* 3.5) once every one of that component's own call sites had switched
|
||||
* over.
|
||||
*
|
||||
* Structural note carried over from ScopeLink.vue: a real
|
||||
* `<button type="button">`, always rendered as a SIBLING of whatever
|
||||
* interactive element it sits beside (a table cell, an accordion header),
|
||||
* never nested inside one — the HTML button content model forbids a
|
||||
* focusable descendant, and nesting one breaks both keyboard operation
|
||||
* and how assistive technology exposes it.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
/** The visible + accessible label, e.g. a user id or model id. */
|
||||
label: string
|
||||
/** Which page this id opens — 'user' -> Consumers, 'model' -> Models. */
|
||||
kind: 'user' | 'model'
|
||||
/** The raw entity id (never pre-formatted as "kind:id" — this component builds nav.goTo's own params itself). */
|
||||
id: string
|
||||
/**
|
||||
* Applied to the inner label `<span>`, never the root `<button>`
|
||||
* (verify-ui-states.md #10 fix). A caller that used to pass `truncate`
|
||||
* through the root's own fallthrough `class` got a hard clip with no
|
||||
* "…" and the trailing icon clipped away too: `text-overflow: ellipsis`
|
||||
* only renders on the element whose own overflow is hidden, and
|
||||
* `min-width: auto` on an inline-flex child ignores the parent's
|
||||
* shrunk width — the label never actually shrank enough to overflow.
|
||||
* Passing `truncate` here instead lets the label span (which also gets
|
||||
* `min-w-0` unconditionally, see the template) genuinely truncate with
|
||||
* an ellipsis while the icon (`shrink-0`) stays fully visible.
|
||||
*/
|
||||
labelClass?: string
|
||||
}>()
|
||||
|
||||
const nav = useNavStore()
|
||||
const { isAlias } = useAliasNames()
|
||||
|
||||
const TARGET: Record<'user' | 'model', { page: 'users' | 'models'; paramKey: 'user' | 'model'; noun: string }> = {
|
||||
user: { page: 'users', paramKey: 'user', noun: 'Consumers' },
|
||||
model: { page: 'models', paramKey: 'model', noun: 'Models' },
|
||||
}
|
||||
|
||||
function onClick(event: MouseEvent): void {
|
||||
event.stopPropagation()
|
||||
const target = TARGET[props.kind]
|
||||
nav.goTo(target.page, { [target.paramKey]: props.id })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
type="button"
|
||||
:aria-label="`View ${label} in ${TARGET[kind].noun}`"
|
||||
:title="`View ${label} in ${TARGET[kind].noun}`"
|
||||
class="inline-flex min-w-0 cursor-pointer items-center gap-1 rounded-sm text-inherit hover:text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
|
||||
@click="onClick"
|
||||
>
|
||||
<span class="min-w-0" :class="labelClass">{{ label }}</span>
|
||||
<AliasBadge v-if="kind === 'model' && isAlias(id)" />
|
||||
<FontAwesomeIcon :icon="faArrowUpRightFromSquare" class="size-3 shrink-0" aria-hidden="true" />
|
||||
</button>
|
||||
</template>
|
||||
@@ -1,65 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { faArrowRotateRight, faTriangleExclamation } from '@fortawesome/free-solid-svg-icons'
|
||||
import { ref } from 'vue'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
/**
|
||||
* ErrorState is EmptyState.vue's destructive counterpart (states-plan.md
|
||||
* item 2) — a fetch for the CURRENT selection failed and there is no
|
||||
* data underneath it to fall back to (lib/load-state.ts's loadState:
|
||||
* 'error', not 'ready' — a background refresh failure while data is
|
||||
* ALREADY shown never reaches this component, it surfaces via a toast
|
||||
* instead, stores/toasts.ts). `message` is the server/network error
|
||||
* string already surfaced by lib/api.ts's AdminApiError, shown verbatim
|
||||
* — never re-worded, so what the reader sees matches what actually
|
||||
* failed. `onRetry`, when given, renders a "Retry" button calling the
|
||||
* store's own refresh/ensure action; omitted for a view with no single
|
||||
* refresh action to re-run (rare — most stores in this panel expose
|
||||
* one). `role="alert"` announces this assertively, unlike EmptyState's
|
||||
* polite `role="status"`.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
message: string
|
||||
onRetry?: () => void | Promise<void>
|
||||
}>()
|
||||
|
||||
/**
|
||||
* retrying (verify-ui-states.md #6 lows: "Retry shows progress (disabled +
|
||||
* spinner/text) while retrying") is LOCAL, not read off the caller's own
|
||||
* store loading flag — several call sites' `onRetry` (consumers.
|
||||
* fetchConsumers, events.refresh) do not clear their store's `error`
|
||||
* before re-fetching, so `loadState` would stay 'error' with no in-flight
|
||||
* signal at all if this depended on that. Tracking the retry promise here
|
||||
* instead works for every caller uniformly, and disabling the button while
|
||||
* it is in flight also closes the "repeated clicks fire parallel requests"
|
||||
* gap those same actions have no guard against.
|
||||
*/
|
||||
const retrying = ref(false)
|
||||
|
||||
async function onRetryClick(): Promise<void> {
|
||||
if (!props.onRetry || retrying.value) return
|
||||
retrying.value = true
|
||||
try {
|
||||
await props.onRetry()
|
||||
} finally {
|
||||
retrying.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div role="alert" class="flex flex-col items-center gap-2 px-4 py-8 text-center">
|
||||
<FontAwesomeIcon :icon="faTriangleExclamation" class="size-6 text-destructive" aria-hidden="true" />
|
||||
<p class="max-w-full break-words text-sm font-medium text-destructive">{{ message }}</p>
|
||||
<Button v-if="onRetry" type="button" variant="outline" size="sm" class="mt-1" :disabled="retrying" @click="onRetryClick">
|
||||
<FontAwesomeIcon
|
||||
:icon="faArrowRotateRight"
|
||||
class="size-3.5"
|
||||
:class="retrying ? 'animate-spin motion-reduce:animate-none' : undefined"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{{ retrying ? 'Retrying…' : 'Retry' }}
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,170 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { faCircleCheck, faTriangleExclamation } from '@fortawesome/free-solid-svg-icons'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { computed, onMounted, onUnmounted } from 'vue'
|
||||
|
||||
import DataTable from '@/components/DataTable.vue'
|
||||
import EmptyState from '@/components/EmptyState.vue'
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import SearchInput from '@/components/SearchInput.vue'
|
||||
import StaleNotice from '@/components/StaleNotice.vue'
|
||||
import SkeletonTable from '@/components/SkeletonTable.vue'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { useSearchQuery } from '@/composables/useSearchQuery'
|
||||
import { eventsColumns } from '@/lib/events-columns'
|
||||
import { EVENT_KIND_LABEL, EVENT_KINDS, filterEvents } from '@/lib/events-filter'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { staleNotice } from '@/lib/stale-notice'
|
||||
import { useEventsStore } from '@/stores/events'
|
||||
|
||||
// This component backs the new "Events" tab (App.vue, F3) — GET
|
||||
// /admin/api/events (admin.go/events.go: adminEventsResponse). Polled only
|
||||
// while this view is mounted (onMounted/onUnmounted below), unlike the
|
||||
// Providers/Usage/Targets dashboard poll which runs for the app's whole
|
||||
// session — see stores/events.ts's own doc comment.
|
||||
const events = useEventsStore()
|
||||
|
||||
const ALL_KINDS = 'all'
|
||||
|
||||
// kindFilter/userFilter live on the store, not as local refs (F9,
|
||||
// hash-state): composables/useHashState.ts reads/writes them directly so
|
||||
// this filter round-trips through the URL hash. userFilter binds through
|
||||
// useSearchQuery's own external-ref option — see useSearchQuery.ts's own
|
||||
// doc comment for the other current external-ref caller
|
||||
// (ConsumerDirectory.vue).
|
||||
const { kindFilter, userFilter } = storeToRefs(events)
|
||||
const { normalized: normalizedUserQuery } = useSearchQuery(userFilter)
|
||||
|
||||
/** kindSelectValue adapts store's '' ("every kind") to the Select's own ALL_KINDS sentinel — Radix Select items cannot use an empty-string value. */
|
||||
const kindSelectValue = computed(() => (kindFilter.value === '' ? ALL_KINDS : kindFilter.value))
|
||||
|
||||
const filteredEvents = computed(() =>
|
||||
filterEvents(events.events, {
|
||||
kind: kindFilter.value,
|
||||
user: normalizedUserQuery.value,
|
||||
}),
|
||||
)
|
||||
|
||||
function onKindChange(value: unknown): void {
|
||||
if (typeof value !== 'string') return
|
||||
events.setKindFilter(value === ALL_KINDS ? '' : value)
|
||||
}
|
||||
|
||||
const columns = eventsColumns()
|
||||
|
||||
/**
|
||||
* eventsLoadState (lib/load-state.ts) replaces the old lone
|
||||
* `!events.lastUpdated` check this view used everywhere: 'skeleton' for
|
||||
* the first fetch, 'error' when that first fetch itself failed (P9's own
|
||||
* false-negative bug — an initial-load FAILURE used to render the exact
|
||||
* same "loading…" text as a genuine in-flight load, forever, since
|
||||
* events.error was never even read here), 'ready' once there is a
|
||||
* successful fetch to show (an EMPTY events list after a successful
|
||||
* fetch is still 'ready' — DataTable's own emptyMessage below renders
|
||||
* the real "no events recorded" row, not this card-level state). A
|
||||
* LATER background-poll failure, with events already on screen, stays
|
||||
* 'ready' too (stores/events.ts's own toast covers that case instead —
|
||||
* states-plan.md item 3 — so content is never wiped/replaced by a
|
||||
* skeleton or error here).
|
||||
*/
|
||||
/** Rows per page in the Events table. */
|
||||
const EVENTS_PAGE_SIZE = 50
|
||||
|
||||
const eventsLoadState = computed(() => loadState({ loading: events.refreshing, hasData: events.lastUpdated !== null, error: events.error }))
|
||||
const staleMessage = computed(() => staleNotice(events.lastUpdated !== null, events.error, events.lastUpdated))
|
||||
|
||||
/**
|
||||
* noEventsRecorded is the GENUINE "nothing has ever happened" case
|
||||
* (states-plan.md item 2: "Events/Reliability: 'No failures recorded'
|
||||
* (positive tone, success icon)") — renders EmptyState instead of an
|
||||
* empty DataTable row, since a clean fleet is worth a reassuring visual,
|
||||
* not just quiet table text. Distinct from "nothing matches the active
|
||||
* filter" below, which stays a plain inline DataTable row: a filter
|
||||
* producing zero rows is a routine, low-stakes interaction, not a
|
||||
* fleet-health signal worth the same visual weight.
|
||||
*
|
||||
* The copy below deliberately does NOT say "in this range" (verify-ui-
|
||||
* states.md #11 fix): the events store fetches the last EVENTS_LIMIT
|
||||
* events (stores/events.ts: GET /admin/api/events?limit=200), unscoped by
|
||||
* the global range filter — "in this range" would misleadingly imply a
|
||||
* narrower window filtered this list down to zero.
|
||||
*/
|
||||
const noEventsRecorded = computed(() => events.events.length === 0)
|
||||
|
||||
/** emptyMessage is DataTable's own inline empty-row text for the "some events exist, but the active filter matches none" case — only ever rendered while noEventsRecorded is false (see the template below). */
|
||||
const emptyMessage = computed(() => {
|
||||
if (kindFilter.value !== '' || normalizedUserQuery.value) return 'no events match the current filter'
|
||||
return 'none'
|
||||
})
|
||||
|
||||
/**
|
||||
* sourceCaption states plainly whether the list below is fleet-wide or
|
||||
* this-replica-only — the Events view must never present a replica-only
|
||||
* fallback as if it were the fleet-wide picture. Only rendered while
|
||||
* eventsLoadState is 'ready' (see the template below), so this never
|
||||
* reads the store's pristine initial source/replica/capacity values.
|
||||
*/
|
||||
const sourceCaption = computed(() => {
|
||||
if (events.source === 'redis') return 'Fleet-wide, across every replica'
|
||||
return `This replica only (${events.replica || 'unknown'}) — Redis is unreachable or unconfigured`
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
events.startPolling()
|
||||
})
|
||||
onUnmounted(() => {
|
||||
events.stopPolling()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<Alert v-if="events.degraded" variant="destructive">
|
||||
<FontAwesomeIcon :icon="faTriangleExclamation" class="size-4" aria-hidden="true" />
|
||||
<AlertTitle>Fleet-wide event log unavailable</AlertTitle>
|
||||
<AlertDescription>
|
||||
Redis is configured but could not be read — showing this replica's own in-memory events only, which may miss
|
||||
events recorded by other replicas.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Card>
|
||||
<CardHeader class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<CardTitle>Events</CardTitle>
|
||||
<!-- Only rendered once there is a real fetch to describe (eventsLoadState 'ready') — 'skeleton'/'error' show nothing here, the CardContent body below already signals which of those it is. -->
|
||||
<CardDescription v-if="eventsLoadState === 'ready'">
|
||||
{{ sourceCaption }} — rate limit, budget, and upstream events, newest first (capacity
|
||||
{{ events.capacity }}).
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<SearchInput v-model="userFilter" placeholder="Filter by user or group" class="w-56" />
|
||||
<Select :model-value="kindSelectValue" @update:model-value="onKindChange">
|
||||
<SelectTrigger class="w-44" aria-label="Filter by kind">
|
||||
<SelectValue placeholder="Kind" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem :value="ALL_KINDS">All kinds</SelectItem>
|
||||
<SelectItem v-for="k in EVENT_KINDS" :key="k" :value="k">{{ EVENT_KIND_LABEL[k] }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<StaleNotice :message="staleMessage" class="mb-3" />
|
||||
<SkeletonTable v-if="eventsLoadState === 'skeleton'" :rows="5" :cols="columns.length" />
|
||||
<ErrorState v-else-if="eventsLoadState === 'error'" :message="events.error" :on-retry="events.refresh" />
|
||||
<EmptyState
|
||||
v-else-if="noEventsRecorded"
|
||||
:icon="faCircleCheck"
|
||||
title="No failures recorded."
|
||||
description="Rate-limit, budget, and upstream events will show up here as they happen."
|
||||
/>
|
||||
<DataTable v-else label="Events" :page-size="EVENTS_PAGE_SIZE" :columns="columns" :data="filteredEvents" :empty-message="emptyMessage" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import type { IconDefinition } from '@fortawesome/free-solid-svg-icons'
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps<{ icon: IconDefinition }>()
|
||||
|
||||
const view = computed(() => {
|
||||
const [width, height, , , path] = props.icon.icon
|
||||
return { box: `0 0 ${width} ${height}`, path: Array.isArray(path) ? path.join('') : path }
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<svg
|
||||
:class="['svg-inline--fa', `fa-${icon.iconName}`]"
|
||||
:data-prefix="icon.prefix"
|
||||
:data-icon="icon.iconName"
|
||||
role="img"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
:viewBox="view.box"
|
||||
>
|
||||
<path fill="currentColor" :d="view.path" />
|
||||
</svg>
|
||||
</template>
|
||||
@@ -1,70 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import type { KpiTier } from '@/lib/kpi'
|
||||
import type { PageId } from '@/lib/pages'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
/**
|
||||
* KpiTile (redesign-plan.md section 3.4) is the Home page's one KPI-tile
|
||||
* shape: a label, a headline value, an optional delta/detail line, and a
|
||||
* tier (lib/kpi.ts) that colors the value text — 'ok' (default
|
||||
* foreground), 'warn' (--status-warn), 'critical' (--destructive), the
|
||||
* same two semantic tokens the rest of this panel's badges/bars already
|
||||
* use, never a fourth ad-hoc color.
|
||||
*
|
||||
* Optionally a link: when `to` is set, the whole tile becomes a real
|
||||
* `<button>` that calls nav.goTo(to.page, to.params) — a budget tile
|
||||
* jumps to Spend, an open-breakers tile jumps to Reliability, and so on.
|
||||
* Without `to`, it renders as a plain, non-interactive Card (a tile with
|
||||
* nowhere useful to send the reader, e.g. "requests/min", stays inert
|
||||
* rather than a button that does nothing).
|
||||
*/
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
label: string
|
||||
value: string
|
||||
delta?: string
|
||||
tier?: KpiTier
|
||||
to?: { page: PageId; params?: Record<string, string> }
|
||||
}>(),
|
||||
{ tier: 'ok' },
|
||||
)
|
||||
|
||||
const nav = useNavStore()
|
||||
|
||||
const valueClass = computed<string>(() => {
|
||||
switch (props.tier) {
|
||||
case 'warn':
|
||||
return 'text-status-warn'
|
||||
case 'critical':
|
||||
return 'text-destructive'
|
||||
default:
|
||||
return 'text-foreground'
|
||||
}
|
||||
})
|
||||
|
||||
function onClick(): void {
|
||||
if (!props.to) return
|
||||
nav.goTo(props.to.page, props.to.params ?? {})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<component
|
||||
:is="to ? 'button' : 'div'"
|
||||
:type="to ? 'button' : undefined"
|
||||
class="block w-full rounded-xl text-left"
|
||||
:class="to ? 'cursor-pointer transition-colors hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50' : undefined"
|
||||
@click="onClick"
|
||||
>
|
||||
<Card>
|
||||
<CardContent class="flex flex-col gap-1 px-4 py-3">
|
||||
<span class="text-xs font-medium text-muted-foreground">{{ label }}</span>
|
||||
<span class="text-2xl font-semibold tracking-tight tabular-nums" :class="valueClass">{{ value }}</span>
|
||||
<span v-if="delta" class="text-xs text-muted-foreground">{{ delta }}</span>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</component>
|
||||
</template>
|
||||
@@ -1,68 +0,0 @@
|
||||
<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>
|
||||
@@ -1,133 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import DataTable from '@/components/DataTable.vue'
|
||||
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 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'
|
||||
|
||||
/**
|
||||
* ModelCatalogTable (redesign-plan.md section 3.4, Models & providers
|
||||
* page) is the catalog-driven table: every configured model (not just
|
||||
* ones with observed traffic), joined with the current range's ranking
|
||||
* and fleet performance — ModelCatalogRow's own doc comment
|
||||
* (lib/model-table-columns.ts) has the full join contract.
|
||||
*
|
||||
* `query` is a controlled v-model, not owned locally: ModelsPage.vue keeps
|
||||
* it so the Models page's own `q` hash param (redesign-plan.md section
|
||||
* 3.1) round-trips through the URL, the same controlled-component
|
||||
* convention SearchInput.vue itself already documents.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
rows: ModelCatalogRow[]
|
||||
query: string
|
||||
/** GET /admin/api/performance's own latencyEnabled (AdminPerfResponse) — false means admin.stats.latency is off, so p50/p95 read "—" for every row, not "no traffic yet". */
|
||||
latencyEnabled: boolean
|
||||
loading: boolean
|
||||
/** models.error (verify-ui-states.md #3 fix) — ModelsPage.vue's own current-fetch error, '' when there is none. Previously this component always passed error: '' into loadState below, so a fetch that failed with no rows yet rendered "No models configured." (a false fleet fact) instead of ErrorState. */
|
||||
error?: string
|
||||
/** Renders ErrorState's own "Retry" button — ModelsPage.vue's own models.fetch. */
|
||||
onRetry?: () => void | Promise<void>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:query': [value: string] }>()
|
||||
|
||||
const filtered = computed<ModelCatalogRow[]>(() => filterModelRows(props.rows, props.query))
|
||||
|
||||
const columns = modelCatalogColumns()
|
||||
|
||||
interface CatalogSection {
|
||||
key: string
|
||||
/** '' for the ungrouped (no-kind) rows. */
|
||||
title: string
|
||||
rows: ModelCatalogRow[]
|
||||
}
|
||||
|
||||
/**
|
||||
* sections splits the filtered rows into one table per (provider, kind): a
|
||||
* provider's plain models first, then one sub-section per kind, sorted.
|
||||
* With no kind set anywhere this is a single untitled section, so an
|
||||
* unconfigured catalog renders exactly as the flat table did.
|
||||
*/
|
||||
const sections = computed<CatalogSection[]>(() => {
|
||||
if (!filtered.value.some((r) => r.kind)) return [{ key: 'all', title: '', rows: filtered.value }]
|
||||
const providers: string[] = []
|
||||
const byKey = new Map<string, CatalogSection>()
|
||||
for (const r of filtered.value) {
|
||||
if (!providers.includes(r.providerName)) providers.push(r.providerName)
|
||||
const key = `${r.providerName}\u0000${r.kind}`
|
||||
let sec = byKey.get(key)
|
||||
if (!sec) {
|
||||
sec = { key, title: r.kind ? `${r.providerName} · ${r.kind}` : r.providerName, rows: [] }
|
||||
byKey.set(key, sec)
|
||||
}
|
||||
sec.rows.push(r)
|
||||
}
|
||||
const kindsOf = (provider: string): string[] =>
|
||||
[...byKey.values()]
|
||||
.filter((sec) => sec.rows[0].providerName === provider)
|
||||
.map((sec) => sec.rows[0].kind)
|
||||
.sort((a, b) => (a === '' ? -1 : b === '' ? 1 : a.localeCompare(b)))
|
||||
return providers.flatMap((p) => kindsOf(p).map((k) => byKey.get(`${p}\u0000${k}`) as CatalogSection))
|
||||
})
|
||||
|
||||
/**
|
||||
* catalogLoadState (lib/load-state.ts, verify-ui-states.md #3 fix) now
|
||||
* reads the REAL `error` prop, not a hardcoded ''. A not-yet-loaded (or
|
||||
* failed) catalog used to render "No models configured." — a false fleet
|
||||
* fact — for BOTH "still fetching" and "the fetch failed with zero rows"
|
||||
* cases alike, since `error: ''` meant loadState could only ever resolve
|
||||
* to 'skeleton' or 'empty', never 'error'. ModelsPage.vue's own top-level
|
||||
* `models.error` paragraph stays alongside this (it also covers a
|
||||
* background refresh failure while rows are already on screen, which
|
||||
* never reaches this component's own ErrorState — loadState's 'ready'
|
||||
* precedence keeps existing rows on screen through that case).
|
||||
*/
|
||||
const catalogLoadState = computed(() => loadState({ loading: props.loading, hasData: props.rows.length > 0, error: props.error ?? '' }))
|
||||
|
||||
const emptyMessage = computed<string>(() => {
|
||||
if (props.query.trim()) return `no models match "${props.query}"`
|
||||
return 'none'
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Model catalog</CardTitle>
|
||||
<CardDescription>
|
||||
Every configured model: price source, per-model usage for the current range, fleet p50/p95, and error rate.
|
||||
</CardDescription>
|
||||
<SearchInput
|
||||
:model-value="query"
|
||||
placeholder="Search models or aliases..."
|
||||
class="mt-2 max-w-sm"
|
||||
@update:model-value="emit('update:query', $event)"
|
||||
/>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-3">
|
||||
<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." />
|
||||
<template v-else>
|
||||
<section v-for="sec in sections" :key="sec.key" class="flex flex-col gap-2">
|
||||
<h3 v-if="sec.title" class="text-sm font-medium text-muted-foreground">{{ sec.title }}</h3>
|
||||
<DataTable :label="sec.title ? `Model catalog: ${sec.title}` : 'Model catalog'" :columns="columns" :data="sec.rows" :empty-message="emptyMessage" />
|
||||
</section>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -1,157 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import { computed, h } from '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 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, formatModelCostHover } from '@/lib/format'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { joinPricingHealth, pricingHealthOrder } from '@/lib/pricing-health'
|
||||
import type { PricingHealthRow } from '@/lib/pricing-health'
|
||||
import type { AdminCatalogModel, AdminUsageModelEntry, PriceSource } from '@/types/api'
|
||||
|
||||
/**
|
||||
* PricingHealthTable (redesign-plan.md section 3.4) lists every model
|
||||
* actually served in the current range, joined with its catalog entry
|
||||
* (lib/pricing-health.ts's joinPricingHealth), unpriced first with a
|
||||
* destructive badge (pricingHealthOrder) — the row an operator most needs
|
||||
* to act on (a served model billing at $0 because no pricing rule
|
||||
* matched) is always the first thing they see, before any manual sort.
|
||||
*
|
||||
* `loading`/`error` (verify-ui-states.md #3/#7 fix): this card had NO
|
||||
* loading or error input at all before — `spend.pricingHealthRanking` /
|
||||
* `catalog.modelsById` both start empty, so the very first Spend load, and
|
||||
* any failed Spend/catalog fetch, rendered the identical "No traffic in
|
||||
* this range." a genuinely empty fleet gets, with no way to tell the three
|
||||
* apart.
|
||||
*
|
||||
* `loaded` (verify-ui-states-2.md #2 fix): `hasData` below is "has a fetch
|
||||
* completed for the current range" (spend.pricingHealthLoaded), not
|
||||
* `rows.length > 0` — the 60s poll (stores/spend.ts's own refresh())
|
||||
* flips `loading` true on every tick, and a genuinely empty pricing-health
|
||||
* table used to flash a skeleton back on for each of those ticks. The
|
||||
* template below still checks `rows.length` directly for EmptyState vs.
|
||||
* the real table, the same way UserDetail.vue's own "Models used" table
|
||||
* does.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
models: AdminUsageModelEntry[]
|
||||
catalog: Map<string, AdminCatalogModel>
|
||||
loading: boolean
|
||||
loaded: boolean
|
||||
error: string
|
||||
/** Renders ErrorState's own "Retry" button — SpendPage.vue's own spend.fetchPricingHealthRanking. */
|
||||
onRetry?: () => void | Promise<void>
|
||||
}>()
|
||||
|
||||
const rows = computed<PricingHealthRow[]>(() => pricingHealthOrder(joinPricingHealth(props.models, props.catalog)))
|
||||
|
||||
const state = computed(() => loadState({ loading: props.loading, hasData: props.loaded, error: props.error }))
|
||||
|
||||
const unpricedCount = computed<number>(() => rows.value.filter((r) => r.priceSource === 'unpriced').length)
|
||||
|
||||
/** SOURCE_BADGE_VARIANT mirrors lib/model-table-columns.ts's own priceCell badge treatment (WP-F, ModelCatalogTable.vue) so the two tables read consistently: destructive for unpriced (needs attention), secondary for a deliberate free model, outline for an explicit rule. */
|
||||
const SOURCE_BADGE_VARIANT: Record<PriceSource, 'destructive' | 'secondary' | 'outline'> = {
|
||||
unpriced: 'destructive',
|
||||
free: 'secondary',
|
||||
override: 'outline',
|
||||
builtin: 'outline',
|
||||
litellm: 'outline',
|
||||
}
|
||||
|
||||
function sourceCell(row: PricingHealthRow) {
|
||||
return h(Badge, { as: 'span', variant: SOURCE_BADGE_VARIANT[row.priceSource], class: 'font-normal' }, () => row.priceSource)
|
||||
}
|
||||
|
||||
function priceCell(row: PricingHealthRow) {
|
||||
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',
|
||||
header: 'Model',
|
||||
accessorFn: (r) => r.id,
|
||||
cell: ({ row }) => h(EntityLink, { label: row.original.id, kind: 'model', id: row.original.id }),
|
||||
},
|
||||
{
|
||||
id: 'source',
|
||||
header: 'Source',
|
||||
accessorFn: (r) => r.priceSource,
|
||||
cell: ({ row }) => sourceCell(row.original),
|
||||
},
|
||||
{
|
||||
id: 'price',
|
||||
header: 'Price',
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => priceCell(row.original),
|
||||
},
|
||||
optionalColumn<PricingHealthRow>('context', 'Context', (r) => r.contextTokens, formatContextWindow),
|
||||
...usageMetricColumns<PricingHealthRow>(),
|
||||
]
|
||||
|
||||
/**
|
||||
* pricingHealthCsv exports exactly the rows on screen (unpriced-first
|
||||
* order, or whatever the reader has since re-sorted to — DataTable's own
|
||||
* `data` prop is passed through unmodified) as raw, unformatted values
|
||||
* (CsvExportButton.vue's own doc comment: "always reflects whatever rows
|
||||
* are CURRENTLY visible... never a stale snapshot") — costMicroUsd stays
|
||||
* micro-USD, not a pre-formatted "$X.XXXX" string, so the export re-opens
|
||||
* cleanly as a spreadsheet numeric column.
|
||||
*/
|
||||
function pricingHealthCsv(): string {
|
||||
return toCsv(
|
||||
['id', 'priceSource', 'displayFree', 'requests', 'tokensIn', 'tokensOut', 'costMicroUsd', 'contextTokens', 'inputPerMTokUsd', 'outputPerMTokUsd'],
|
||||
rows.value.map((r) => [
|
||||
r.id,
|
||||
r.priceSource,
|
||||
r.displayFree,
|
||||
r.requests,
|
||||
r.tokensIn,
|
||||
r.tokensOut,
|
||||
r.costMicroUsd,
|
||||
r.contextTokens ?? '',
|
||||
r.inputPerMTokUsd ?? '',
|
||||
r.outputPerMTokUsd ?? '',
|
||||
]),
|
||||
)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2">
|
||||
Pricing health
|
||||
<Badge v-if="unpricedCount > 0" variant="destructive" class="font-normal">{{ unpricedCount }} unpriced</Badge>
|
||||
</CardTitle>
|
||||
<CardDescription>Every model served in range, joined with its billing price source.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-3">
|
||||
<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="No priced models in this range." label="Pricing health" />
|
||||
<div class="flex justify-end">
|
||||
<CsvExportButton filename="pricing-health.csv" :build="pricingHealthCsv" />
|
||||
</div>
|
||||
</LoadStateView>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -1,563 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import {
|
||||
faCircleCheck,
|
||||
faCircleXmark,
|
||||
faTriangleExclamation,
|
||||
} from '@fortawesome/free-solid-svg-icons'
|
||||
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 { providerSections } from '@/lib/provider-sections'
|
||||
import type { ProviderSection } from '@/lib/provider-sections'
|
||||
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 { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { useSearchQuery } from '@/composables/useSearchQuery'
|
||||
import { formatAgo, formatContextWindow, formatLatencyMs, formatUntil, refreshDetailLabel, refreshLabel, routableModelId } from '@/lib/format'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { isModelDegraded } from '@/lib/provider-rate'
|
||||
import { type ExpandState, clearExpandOverrides, computeExpandedItems, toggleItemExpand } from '@/lib/search-expand'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useModelsStore } from '@/stores/models'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
import type {
|
||||
AdminAliasView,
|
||||
AdminLatencyView,
|
||||
AdminModelMetaView,
|
||||
AdminModelRateView,
|
||||
AdminPerfRow,
|
||||
AdminProvenanceView,
|
||||
AdminProviderView,
|
||||
} from '@/types/api'
|
||||
|
||||
/**
|
||||
* ProviderHealthPanel (redesign-plan.md section 3.4, Models & providers
|
||||
* page) is ProvidersView.vue's own Providers accordion + aliases table,
|
||||
* moved here verbatim, PLUS fleet-wide performance (p50/p95, timeouts,
|
||||
* failovers — GET /admin/api/performance?kind=provider, read from
|
||||
* useModelsStore, which the Models page's own onMounted fetches once for
|
||||
* the whole page, shared with ModelCatalogTable.vue). The per-replica
|
||||
* discovery/latency/provenance badges below are UNCHANGED from
|
||||
* ProvidersView.vue — still sourced from the SAME 5s dashboard poll
|
||||
* (GET /admin/api/overview), still per-replica/in-process (see each
|
||||
* badge's own doc comment for why that never averages across replicas).
|
||||
*/
|
||||
const dashboard = useDashboardStore()
|
||||
const models = useModelsStore()
|
||||
const overview = computed(() => dashboard.overview)
|
||||
const nav = useNavStore()
|
||||
|
||||
/**
|
||||
* goToProviderModels navigates to the Models catalog table, pre-filtered
|
||||
* (via its own `q` search) to this provider's own models — the redesign's
|
||||
* replacement for the pre-redesign nav.goToModels (stores/nav.ts no
|
||||
* longer has a per-page goTo* method at all, see that store's own doc
|
||||
* comment; every navigation goes through the single goTo(page, params)).
|
||||
*/
|
||||
function goToProviderModels(providerName: string): void {
|
||||
nav.goTo('models', { q: `${providerName}/` })
|
||||
}
|
||||
|
||||
// --- provider expand/collapse (shadcn-vue Accordion) — unchanged from ProvidersView.vue ---
|
||||
const expandState: ExpandState = reactive({
|
||||
manuallyExpanded: new Set<string>(),
|
||||
manuallyCollapsed: new Set<string>(),
|
||||
})
|
||||
|
||||
// --- model/alias search filter (operator feature) — unchanged from ProvidersView.vue ---
|
||||
const { query: modelQuery, normalized: normalizedQuery, hasQuery } = useSearchQuery()
|
||||
|
||||
function modelMatches(providerName: string, modelId: string): boolean {
|
||||
return routableModelId(providerName, modelId).toLowerCase().includes(normalizedQuery.value)
|
||||
}
|
||||
function providerMatches(p: AdminProviderView): boolean {
|
||||
return p.models.some((m) => modelMatches(p.name, m))
|
||||
}
|
||||
function aliasMatches(a: AdminAliasView): boolean {
|
||||
return a.alias.toLowerCase().includes(normalizedQuery.value) || a.target.toLowerCase().includes(normalizedQuery.value)
|
||||
}
|
||||
|
||||
/**
|
||||
* providersLoadState (live-preview fix, same class of bug as
|
||||
* lib/access-matrix.ts's matrixColumnsState / TargetsView.vue's
|
||||
* targetsLoadState) — `overview` maps a not-yet-loaded dashboard.overview
|
||||
* straight to `[]` via `?? []` below, which the template used to render as
|
||||
* a confirmed "none" (no providers configured at all) before the 5s
|
||||
* dashboard poll's first response had even landed. `loading: true` mirrors
|
||||
* those same two call sites' own idiom: it is only ever consulted once
|
||||
* `hasData` (dashboard.overview !== null) is already false, so there is
|
||||
* nothing else to fall back to but a skeleton or the dashboard's own error.
|
||||
*/
|
||||
const providersLoadState = computed(() => loadState({ loading: true, hasData: overview.value !== null, error: dashboard.error }))
|
||||
|
||||
const filteredProviders = computed<AdminProviderView[]>(() => {
|
||||
const all = overview.value?.providers ?? []
|
||||
return hasQuery.value ? all.filter(providerMatches) : all
|
||||
})
|
||||
const filteredAliases = computed<AdminAliasView[]>(() => {
|
||||
const all = overview.value?.aliases ?? []
|
||||
return hasQuery.value ? all.filter(aliasMatches) : all
|
||||
})
|
||||
|
||||
const expandedProviders = computed<Set<string>>(() =>
|
||||
computeExpandedItems(
|
||||
expandState,
|
||||
hasQuery.value,
|
||||
filteredProviders.value.map((p) => p.name),
|
||||
),
|
||||
)
|
||||
|
||||
function toggleProvider(name: string): void {
|
||||
toggleItemExpand(expandState, name, expandedProviders.value.has(name))
|
||||
}
|
||||
|
||||
const expandedProviderValues = computed<string[]>({
|
||||
get: () => Array.from(expandedProviders.value),
|
||||
set: (newValues) => {
|
||||
const next = new Set(newValues)
|
||||
for (const name of expandedProviders.value) {
|
||||
if (!next.has(name)) toggleProvider(name)
|
||||
}
|
||||
for (const name of next) {
|
||||
if (!expandedProviders.value.has(name)) toggleProvider(name)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
watch(modelQuery, (value) => {
|
||||
if (value.trim() === '') clearExpandOverrides(expandState)
|
||||
})
|
||||
|
||||
function visibleModels(p: AdminProviderView): string[] {
|
||||
return hasQuery.value ? p.models.filter((m) => modelMatches(p.name, m)) : p.models
|
||||
}
|
||||
|
||||
function visibleSections(p: AdminProviderView): ProviderSection[] {
|
||||
const sections = providerSections({ models: visibleModels(p), kinds: p.kinds, endpoints: p.endpoints })
|
||||
if (!hasQuery.value) return sections.filter((s) => s.models.length > 0 || s.endpoints.length > 0)
|
||||
return sections
|
||||
.map((s) => ({ ...s, endpoints: s.endpoints.filter((e) => modelMatches(p.name, e)) }))
|
||||
.filter((s) => s.models.length > 0 || s.endpoints.length > 0)
|
||||
}
|
||||
|
||||
const ZERO_MODEL_RATE: AdminModelRateView = { attemptsDay: 0, failuresDay: 0 }
|
||||
|
||||
function modelRateFor(p: AdminProviderView, model: string): AdminModelRateView {
|
||||
return p.modelRates?.[model] ?? ZERO_MODEL_RATE
|
||||
}
|
||||
|
||||
function modelIsDegraded(p: AdminProviderView, model: string): boolean {
|
||||
const r = modelRateFor(p, model)
|
||||
return isModelDegraded(r.attemptsDay, r.failuresDay)
|
||||
}
|
||||
|
||||
const ZERO_MODEL_META: AdminModelMetaView = {}
|
||||
|
||||
function modelMetaFor(p: AdminProviderView, model: string): AdminModelMetaView {
|
||||
return p.modelMeta?.[model] ?? ZERO_MODEL_META
|
||||
}
|
||||
|
||||
// --- discovery circuit breaker (feat/provider-health) — unchanged from ProvidersView.vue ---
|
||||
|
||||
function healthBadgeVariant(state: AdminProviderView['healthState']): 'destructive' | 'secondary' | undefined {
|
||||
switch (state) {
|
||||
case 'open':
|
||||
return 'destructive'
|
||||
case 'half-open':
|
||||
return 'secondary'
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function healthBadgeLabel(p: AdminProviderView): string {
|
||||
const until = formatUntil(p.openUntil)
|
||||
return until ? `${p.healthState} (${until})` : p.healthState
|
||||
}
|
||||
|
||||
function healthDetailClass(state: AdminProviderView['healthState']): string {
|
||||
return state === 'open' ? 'text-destructive' : 'text-muted-foreground'
|
||||
}
|
||||
|
||||
// --- per-replica upstream latency (feat: instrument upstream latency) — unchanged from ProvidersView.vue ---
|
||||
|
||||
function streamingLatency(p: AdminProviderView): AdminLatencyView | undefined {
|
||||
return p.latency?.streaming
|
||||
}
|
||||
function nonStreamingLatency(p: AdminProviderView): AdminLatencyView | undefined {
|
||||
return p.latency?.['non-streaming']
|
||||
}
|
||||
|
||||
function latencyObservationCount(v: AdminLatencyView): string {
|
||||
if (v.count === undefined) return 'no observations counted'
|
||||
return `${v.count} ${v.count === 1 ? 'observation' : 'observations'} on this replica`
|
||||
}
|
||||
|
||||
function perReplicaCaveat(): string {
|
||||
const replica = overview.value?.replica
|
||||
const who = replica ? `replica ${replica}` : 'this replica'
|
||||
return `Per-replica (${who}), in-process only — not a fleet-wide average across this deployment’s replicas.`
|
||||
}
|
||||
|
||||
function streamingLatencyTitle(v: AdminLatencyView): string {
|
||||
return `Average time to first byte, the load-sensitive reading for streaming traffic. ${latencyObservationCount(v)}. ${perReplicaCaveat()}`
|
||||
}
|
||||
|
||||
function nonStreamingLatencyTitle(v: AdminLatencyView): string {
|
||||
return `Average total response time, including generation — not a load-sensitive signal like streaming ttfb, since this provider buffers the whole completion before sending anything. ${latencyObservationCount(v)}. ${perReplicaCaveat()}`
|
||||
}
|
||||
|
||||
// --- usage provenance (feat: expose token-accounting provenance) — unchanged from ProvidersView.vue ---
|
||||
|
||||
function estimatedProvenance(p: AdminProviderView): AdminProvenanceView | undefined {
|
||||
return p.provenance?.estimated
|
||||
}
|
||||
function unbilledProvenance(p: AdminProviderView): AdminProvenanceView | undefined {
|
||||
return p.provenance?.unbilled
|
||||
}
|
||||
|
||||
function estimatedProvenanceTitle(v: AdminProvenanceView): string {
|
||||
const plural = v.requests === 1 ? '' : 's'
|
||||
return `${v.requests} non-streaming response${plural} carried no usage from the provider — prompt tokens were estimated from request body size instead (${v.tokens} tokens billed from the estimate), completion billed as zero. ${perReplicaCaveat()}`
|
||||
}
|
||||
|
||||
function unbilledProvenanceTitle(v: AdminProvenanceView): string {
|
||||
const plural = v.requests === 1 ? '' : 's'
|
||||
return `${v.requests} streaming response${plural} carried no usage from the provider — the request was counted but zero tokens were billed. If this keeps happening, this provider may be serving completions entirely free against every budget. ${perReplicaCaveat()}`
|
||||
}
|
||||
|
||||
// --- fleet-wide performance (NEW: GET /admin/api/performance?kind=provider) ---
|
||||
//
|
||||
// Fleet-wide (Redis-backed via the latency histogram counters, WP-A), UNLIKE
|
||||
// every badge above this point in the file — a provider's own p50/p95
|
||||
// here is the SAME reading regardless which replica answered the poll,
|
||||
// the opposite of the per-replica caveat every latency/provenance badge
|
||||
// above carries. timeouts/failovers are always populated (they do not
|
||||
// need admin.stats.latency — only the percentile fields do, AdminPerfRow's
|
||||
// own doc comment); a provider with zero of either renders no badge at
|
||||
// all, mirroring every other "nothing to show" convention in this file.
|
||||
|
||||
function providerPerfFor(name: string): AdminPerfRow | undefined {
|
||||
return models.providerPerf.find((r) => r.id === name)
|
||||
}
|
||||
|
||||
function fleetLatencyTitle(kind: 'p50' | 'p95'): string {
|
||||
const { window, span } = models.perfWindow
|
||||
return `Fleet-wide (every replica combined) ${kind === 'p50' ? 'median' : '95th percentile'} response time, over the last ${span} ${window}${span === 1 ? '' : 's'}.`
|
||||
}
|
||||
|
||||
function fleetCountTitle(kind: 'timeouts' | 'failovers'): string {
|
||||
const { window, span } = models.perfWindow
|
||||
const noun = kind === 'timeouts' ? 'requests that exceeded the deadline' : "requests failed away from this provider to another candidate"
|
||||
return `${noun}, fleet-wide, over the last ${span} ${window}${span === 1 ? '' : 's'}.`
|
||||
}
|
||||
|
||||
// --- model aliases (sortable DataTable) — unchanged from ProvidersView.vue ---
|
||||
const aliasColumns: ColumnDef<AdminAliasView, unknown>[] = [
|
||||
{
|
||||
id: 'alias',
|
||||
header: 'Alias',
|
||||
accessorFn: (a) => a.alias,
|
||||
cell: ({ row }) =>
|
||||
h(ModelChip, {
|
||||
id: row.original.alias,
|
||||
contextTokens: row.original.modelMeta?.contextTokens,
|
||||
inputPerMTokUsd: row.original.modelMeta?.inputPerMTokUsd,
|
||||
outputPerMTokUsd: row.original.modelMeta?.outputPerMTokUsd,
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'target',
|
||||
header: 'Target',
|
||||
accessorFn: (a) => a.target,
|
||||
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, row.original.target),
|
||||
},
|
||||
]
|
||||
const aliasEmptyMessage = computed(() =>
|
||||
!overview.value?.aliases.length ? 'none configured' : hasQuery.value ? `no aliases match "${modelQuery.value}"` : 'none',
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<div class="grid gap-4 sm:grid-cols-3">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2 text-sm font-medium text-muted-foreground">
|
||||
<FontAwesomeIcon
|
||||
:icon="overview?.redis.configured ? faCircleCheck : faCircleXmark"
|
||||
:class="overview?.redis.configured ? 'text-chart-requests' : 'text-muted-foreground'"
|
||||
class="size-3.5"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
Redis
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-1 text-sm">
|
||||
<p class="font-medium">{{ overview?.redis.configured ? 'Configured' : 'Not configured' }}</p>
|
||||
<p v-if="overview?.redis.lastErr" class="flex items-start gap-1.5 text-destructive">
|
||||
<FontAwesomeIcon :icon="faTriangleExclamation" class="mt-0.5 size-3.5 shrink-0" aria-hidden="true" />
|
||||
<span>{{ overview.redis.lastErr }}{{ formatAgo(overview.redis.lastErrAt) }}</span>
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2 text-sm font-medium text-muted-foreground">
|
||||
<FontAwesomeIcon
|
||||
:icon="overview?.cache.enabled ? faCircleCheck : faCircleXmark"
|
||||
:class="overview?.cache.enabled ? 'text-chart-requests' : 'text-muted-foreground'"
|
||||
class="size-3.5"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
Response cache
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="text-sm">
|
||||
<p class="font-medium">{{ overview?.cache.enabled ? 'Enabled' : 'Disabled' }}</p>
|
||||
<p v-if="overview?.cache.enabled" class="text-muted-foreground">ttl {{ overview.cache.ttl }}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2 text-sm font-medium text-muted-foreground">
|
||||
<FontAwesomeIcon
|
||||
:icon="overview?.retry.enabled ? faCircleCheck : faCircleXmark"
|
||||
:class="overview?.retry.enabled ? 'text-chart-requests' : 'text-muted-foreground'"
|
||||
class="size-3.5"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
Retry
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="text-sm">
|
||||
<p class="font-medium">{{ overview?.retry.enabled ? 'Enabled' : 'Disabled' }}</p>
|
||||
<p v-if="overview?.retry.enabled" class="text-muted-foreground">
|
||||
attempts {{ overview.retry.attempts }}, backoff {{ overview.retry.backoff }}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Providers</CardTitle>
|
||||
<CardDescription>
|
||||
Every configured upstream, its last discovery refresh, and fleet-wide performance. Search filters providers and
|
||||
aliases by model id.
|
||||
</CardDescription>
|
||||
<SearchInput v-model="modelQuery" placeholder="Search models or aliases..." class="mt-2 max-w-sm" />
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-3">
|
||||
<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" />
|
||||
<EmptyState v-else-if="!overview?.providers.length" title="No providers configured." />
|
||||
<EmptyState
|
||||
v-else-if="hasQuery && filteredProviders.length === 0"
|
||||
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">
|
||||
<AccordionItem v-for="p in filteredProviders" :key="p.name" :value="p.name">
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 cursor-pointer rounded-sm py-2.5 font-medium hover:text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
|
||||
:aria-label="`View ${p.name}'s models in the Models table`"
|
||||
:title="`View ${p.name}'s models in the Models table`"
|
||||
@click="goToProviderModels(p.name)"
|
||||
>{{ p.name }}</button>
|
||||
<AccordionTrigger header-class="flex-1">
|
||||
<span class="sr-only">Provider {{ p.name }} details</span>
|
||||
<span class="flex flex-1 flex-wrap items-center gap-x-3 gap-y-1 pr-2 text-left">
|
||||
<Badge as="span" variant="secondary" class="font-normal">{{ p.type }}</Badge>
|
||||
<span class="text-xs text-muted-foreground tabular-nums">{{ p.modelCount }} models</span>
|
||||
<ProviderRateBadge
|
||||
:attempts-day="p.attemptsDay"
|
||||
:failures-day="p.failuresDay"
|
||||
:attempts-minute="p.attemptsMinute"
|
||||
:failures-minute="p.failuresMinute"
|
||||
/>
|
||||
<Badge
|
||||
v-if="p.healthState !== 'closed'"
|
||||
as="span"
|
||||
:variant="healthBadgeVariant(p.healthState)"
|
||||
class="font-normal"
|
||||
:title="p.healthState === 'open' ? 'discovery is backing off after repeated failures' : 'a discovery probe is deciding whether to recover'"
|
||||
>
|
||||
{{ healthBadgeLabel(p) }}
|
||||
</Badge>
|
||||
<Badge
|
||||
v-if="streamingLatency(p)?.avgTtfbMs !== undefined"
|
||||
as="span"
|
||||
variant="outline"
|
||||
class="font-normal tabular-nums"
|
||||
:title="streamingLatencyTitle(streamingLatency(p) as AdminLatencyView)"
|
||||
>
|
||||
streaming ttfb {{ formatLatencyMs(streamingLatency(p)!.avgTtfbMs as number) }}
|
||||
</Badge>
|
||||
<Badge
|
||||
v-if="nonStreamingLatency(p)?.avgDurationMs !== undefined"
|
||||
as="span"
|
||||
variant="outline"
|
||||
class="font-normal tabular-nums"
|
||||
:title="nonStreamingLatencyTitle(nonStreamingLatency(p) as AdminLatencyView)"
|
||||
>
|
||||
non-streaming avg {{ formatLatencyMs(nonStreamingLatency(p)!.avgDurationMs as number) }}
|
||||
</Badge>
|
||||
<Badge
|
||||
v-if="providerPerfFor(p.name)?.p50Ms !== undefined"
|
||||
as="span"
|
||||
variant="outline"
|
||||
class="font-normal tabular-nums"
|
||||
:title="fleetLatencyTitle('p50')"
|
||||
>
|
||||
fleet p50 {{ formatLatencyMs(providerPerfFor(p.name)!.p50Ms as number) }}
|
||||
</Badge>
|
||||
<Badge
|
||||
v-if="providerPerfFor(p.name)?.p95Ms !== undefined"
|
||||
as="span"
|
||||
variant="outline"
|
||||
class="font-normal tabular-nums"
|
||||
:title="fleetLatencyTitle('p95')"
|
||||
>
|
||||
fleet p95 {{ formatLatencyMs(providerPerfFor(p.name)!.p95Ms as number) }}
|
||||
</Badge>
|
||||
<Badge
|
||||
v-if="(providerPerfFor(p.name)?.timeouts ?? 0) > 0"
|
||||
as="span"
|
||||
variant="secondary"
|
||||
class="font-normal tabular-nums"
|
||||
:title="fleetCountTitle('timeouts')"
|
||||
>
|
||||
{{ providerPerfFor(p.name)!.timeouts }} timeouts
|
||||
</Badge>
|
||||
<Badge
|
||||
v-if="(providerPerfFor(p.name)?.failovers ?? 0) > 0"
|
||||
as="span"
|
||||
variant="secondary"
|
||||
class="font-normal tabular-nums"
|
||||
:title="fleetCountTitle('failovers')"
|
||||
>
|
||||
{{ providerPerfFor(p.name)!.failovers }} failovers
|
||||
</Badge>
|
||||
<Badge
|
||||
v-if="estimatedProvenance(p)"
|
||||
as="span"
|
||||
variant="secondary"
|
||||
class="font-normal tabular-nums"
|
||||
:title="estimatedProvenanceTitle(estimatedProvenance(p) as AdminProvenanceView)"
|
||||
>
|
||||
estimated {{ estimatedProvenance(p)!.requests }}
|
||||
</Badge>
|
||||
<Badge
|
||||
v-if="unbilledProvenance(p)"
|
||||
as="span"
|
||||
variant="destructive"
|
||||
class="font-normal tabular-nums"
|
||||
:title="unbilledProvenanceTitle(unbilledProvenance(p) as AdminProvenanceView)"
|
||||
>
|
||||
unbilled {{ unbilledProvenance(p)!.requests }}
|
||||
</Badge>
|
||||
<FontAwesomeIcon
|
||||
v-if="p.lastErr"
|
||||
:icon="faTriangleExclamation"
|
||||
class="size-3.5 shrink-0 text-destructive"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span class="text-xs text-muted-foreground">{{ refreshLabel(p.discoveryEnabled, p.lastRefresh) }}</span>
|
||||
</span>
|
||||
</AccordionTrigger>
|
||||
</div>
|
||||
<AccordionContent>
|
||||
<dl class="mb-3 grid grid-cols-2 gap-x-6 gap-y-1.5 text-sm sm:grid-cols-3">
|
||||
<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="visibleSections(p).length" class="flex flex-col gap-3">
|
||||
<section v-for="sec in visibleSections(p)" :key="sec.title" class="flex flex-col gap-1.5">
|
||||
<h4 v-if="sec.title" class="text-xs font-medium uppercase tracking-wide text-muted-foreground">{{ sec.title }}</h4>
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<span v-for="m in sec.models" :key="m" class="inline-flex min-w-0 max-w-full items-center gap-1">
|
||||
<ModelChip
|
||||
:id="routableModelId(p.name, m)"
|
||||
:context-tokens="modelMetaFor(p, m).contextTokens"
|
||||
:input-per-m-tok-usd="modelMetaFor(p, m).inputPerMTokUsd"
|
||||
:output-per-m-tok-usd="modelMetaFor(p, m).outputPerMTokUsd"
|
||||
/>
|
||||
<EntityLink :label="routableModelId(p.name, m)" kind="model" :id="routableModelId(p.name, m)" class="min-w-0" label-class="truncate" />
|
||||
<span
|
||||
v-if="modelMetaFor(p, m).contextTokens !== undefined"
|
||||
title="context window"
|
||||
class="text-xs text-muted-foreground tabular-nums"
|
||||
>
|
||||
{{ formatContextWindow(modelMetaFor(p, m).contextTokens as number) }}
|
||||
</span>
|
||||
<ProviderRateBadge
|
||||
v-if="modelIsDegraded(p, m)"
|
||||
:attempts-day="modelRateFor(p, m).attemptsDay"
|
||||
:failures-day="modelRateFor(p, m).failuresDay"
|
||||
/>
|
||||
</span>
|
||||
<code
|
||||
v-for="e in sec.endpoints"
|
||||
:key="e"
|
||||
title="native passthrough path (not a routable model)"
|
||||
class="rounded bg-muted px-1.5 py-0.5 text-xs"
|
||||
>
|
||||
{{ p.name }}{{ e }}
|
||||
</code>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<p v-else class="text-sm text-muted-foreground">no models known yet</p>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Model aliases</CardTitle>
|
||||
<CardDescription>Operator-defined alias → target model mappings.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DataTable label="Model aliases" :columns="aliasColumns" :data="filteredAliases" :empty-message="aliasEmptyMessage" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<p v-if="overview?.version" class="text-xs text-muted-foreground">Version: {{ overview.version }}</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,81 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { dayRateTitle, formatRatePercent, minuteRateTitle, providerRateStatus, providerSuccessRate } from '@/lib/provider-rate'
|
||||
|
||||
/**
|
||||
* ProviderRateBadge is the Models page's success-rate badge (Feature A,
|
||||
* v0.22) — reused for both a provider's own row (ProviderHealthPanel.vue's
|
||||
* accordion trigger, always shown) and a single degraded model beside its
|
||||
* ModelChip (ProviderHealthPanel.vue's accordion content, shown only when
|
||||
* isModelDegraded). attemptsMinute/failuresMinute are OPTIONAL (SHOULD-2,
|
||||
* v0.22 review round): the provider-row call site passes them (admin.go's
|
||||
* adminProviderView carries minute counters); the per-model call site
|
||||
* does not (adminModelRateView no longer does — a model scope's minute
|
||||
* window is never fetched at all, see lib/provider-rate.ts's own
|
||||
* dayRateTitle). Their absence, not a passed-through 0, is what tells
|
||||
* this component to fall back to a day-window-only detail sentence — a
|
||||
* real 0-attempts minute and "no minute data at all" are different
|
||||
* things, and treating them as the identical "0" would silently claim a
|
||||
* live "0 attempts in the last minute" reading a model badge never
|
||||
* actually measured.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
attemptsDay: number
|
||||
failuresDay: number
|
||||
attemptsMinute?: number
|
||||
failuresMinute?: number
|
||||
}>()
|
||||
|
||||
const rate = computed(() => providerSuccessRate(props.attemptsDay, props.failuresDay))
|
||||
const status = computed(() => providerRateStatus(rate.value))
|
||||
|
||||
const label = computed(() => (status.value === 'no-traffic' ? 'no traffic' : formatRatePercent(rate.value as number)))
|
||||
|
||||
/**
|
||||
* detail carries the "right now" (provider) or "today" (model) counts —
|
||||
* the spec's minute-window requirement where that data exists at all
|
||||
* (minuteRateTitle), falling back to dayRateTitle when it does not. Used
|
||||
* as BOTH the badge's title (mouse hover) and, via the sr-only span in
|
||||
* the template, its accessible name for keyboard/screen-reader users
|
||||
* (folded review minor, v0.22 review round: title alone is mouse-only).
|
||||
*
|
||||
* Review fix (v0.23 round): this used to sit directly on `:aria-label`
|
||||
* on the Badge/`<span>` element, which axe flags as `aria-prohibited-
|
||||
* attr` — a `<span>`'s implicit role ("generic") does not support name
|
||||
* computation. See CompactNumber.vue's own doc comment for the identical
|
||||
* fix and the shared visible-abbreviation-plus-sr-only-full-text
|
||||
* pattern this component now uses too.
|
||||
*/
|
||||
const detail = computed(() =>
|
||||
props.attemptsMinute === undefined || props.failuresMinute === undefined
|
||||
? dayRateTitle(props.attemptsDay, props.failuresDay)
|
||||
: minuteRateTitle(props.attemptsMinute, props.failuresMinute),
|
||||
)
|
||||
|
||||
// Badge has no dedicated "amber"/"muted" variant (ui/badge/index.ts) —
|
||||
// severe reuses the built-in `destructive` variant exactly like every
|
||||
// other error state in this panel (e.g. ProviderHealthPanel.vue's own
|
||||
// lastErr icon); healthy/no-traffic reuse `secondary`/`outline`, the
|
||||
// panel's existing "quiet" idioms (ProviderHealthPanel.vue's
|
||||
// provider-type badge is `variant="secondary"`); degraded borrows the
|
||||
// semantic --status-warn token (main.css — MUST-1, v0.22 review round: --chart-tokens-out, this
|
||||
// component's original choice, measures ~2.22:1 against --card in light
|
||||
// mode, a WCAG 1.4.3 text-contrast failure on exactly the "something's
|
||||
// wrong" tier; --status-warn is tuned for body-text contrast instead,
|
||||
// ~5.06:1 light / ~8.97:1 dark).
|
||||
const variant = computed(() => (status.value === 'severe' ? 'destructive' : status.value === 'healthy' ? 'secondary' : 'outline'))
|
||||
const extraClass = computed(() => {
|
||||
if (status.value === 'degraded') return 'border-status-warn/40 text-status-warn'
|
||||
if (status.value === 'no-traffic') return 'text-muted-foreground'
|
||||
return ''
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Badge as="span" :variant="variant" :class="extraClass" class="font-normal tabular-nums" :title="detail">
|
||||
<span aria-hidden="true">{{ label }}</span>
|
||||
<span class="sr-only">{{ detail }}</span>
|
||||
</Badge>
|
||||
</template>
|
||||
@@ -1,80 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { faMagnifyingGlass, faXmark } from '@fortawesome/free-solid-svg-icons'
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/**
|
||||
* SearchInput is the one search-box control every filter in this panel
|
||||
* uses (today: ProviderHealthPanel's model search, ConsumerDirectory's
|
||||
* user/group search, TargetsView's target search, EventsView's user
|
||||
* filter, ModelCatalogTable's model search) — each pre-redesign call site
|
||||
* grew an identical ~22-line magnifying-glass-icon + Input + clear-button
|
||||
* block on its own; extracted into one component (vue.md: "if you've
|
||||
* written it twice, you owe an abstraction"). A controlled component
|
||||
* (modelValue/update:modelValue),
|
||||
* not v-model'd internally, since the incoming modelValue is a prop —
|
||||
* callers pair it with `useSearchQuery()` (composables/useSearchQuery.ts)
|
||||
* for the query/normalized/hasQuery/clear state, or v-model it against any
|
||||
* plain string ref directly.
|
||||
*
|
||||
* The clear button is a real shadcn Button (variant="ghost", size
|
||||
* "icon-xs") instead of a hand-rolled `<button>` — review fix: the
|
||||
* hand-rolled version had no focus-visible ring of its own and a smaller
|
||||
* than WCAG 2.2 SC 2.5.8 24x24 minimum hit target. Button's "icon-xs" size
|
||||
* is exactly size-6 (24x24px, ui/button/index.ts), and buttonVariants
|
||||
* already carries a focus-visible ring — fixing the a11y gap once here
|
||||
* instead of at every call site.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
modelValue: string
|
||||
placeholder: string
|
||||
class?: HTMLAttributes['class']
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: string): void
|
||||
}>()
|
||||
|
||||
const hasValue = computed(() => props.modelValue.length > 0)
|
||||
|
||||
function onInput(value: string | number): void {
|
||||
emit('update:modelValue', String(value))
|
||||
}
|
||||
|
||||
function onClear(): void {
|
||||
emit('update:modelValue', '')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :class="cn('relative', props.class)">
|
||||
<FontAwesomeIcon
|
||||
:icon="faMagnifyingGlass"
|
||||
class="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Input
|
||||
:model-value="modelValue"
|
||||
type="text"
|
||||
:placeholder="placeholder"
|
||||
:aria-label="placeholder"
|
||||
class="pr-8 pl-8"
|
||||
@update:model-value="onInput"
|
||||
/>
|
||||
<Button
|
||||
v-if="hasValue"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
aria-label="Clear search"
|
||||
class="absolute top-1/2 right-1 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
@click="onClear"
|
||||
>
|
||||
<FontAwesomeIcon :icon="faXmark" class="size-3.5" aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,18 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
/**
|
||||
* SkeletonChart is a fixed-aspect placeholder matching
|
||||
* TimeSeriesChart.vue's own container exactly (`h-72 w-full`) — every
|
||||
* chart in this panel (Spend's breakdown, Reliability's per-provider
|
||||
* error rate, BurnDownChart, UserDetail's per-user charts) renders inside
|
||||
* that same fixed height, so swapping this in for the first load never
|
||||
* shifts the layout once the real chart mounts.
|
||||
*/
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="h-72 w-full" role="status" aria-busy="true" aria-label="Loading chart">
|
||||
<Skeleton class="h-full w-full" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,21 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
/**
|
||||
* SkeletonKpiTile mirrors KpiTile.vue's own Card/CardContent structure
|
||||
* and spacing exactly — label, value, and delta lines at the same
|
||||
* heights — so a KPI grid swapping this in for real tiles on first load
|
||||
* causes no layout shift once the real values arrive.
|
||||
*/
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
<CardContent class="flex flex-col gap-1 px-4 py-3">
|
||||
<Skeleton class="h-3 w-20" />
|
||||
<Skeleton class="h-7 w-16" />
|
||||
<Skeleton class="h-3 w-28" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -1,23 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
/**
|
||||
* SkeletonList mirrors TopList.vue's own ranked-row shape (rank number,
|
||||
* label, right-aligned value) — `rows` pulsing rows, defaulting to 5 to
|
||||
* match "top 5" lists, so a list card swapping this in for its first load
|
||||
* causes no layout shift once real rows arrive.
|
||||
*/
|
||||
withDefaults(defineProps<{ rows?: number }>(), { rows: 5 })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ol class="flex flex-col gap-1.5">
|
||||
<li v-for="r in rows" :key="r" class="flex items-center justify-between gap-3">
|
||||
<span class="flex min-w-0 flex-1 items-center gap-2">
|
||||
<Skeleton class="h-3 w-4 shrink-0" />
|
||||
<Skeleton class="h-4 w-full max-w-40" />
|
||||
</span>
|
||||
<Skeleton class="h-4 w-12 shrink-0" />
|
||||
</li>
|
||||
</ol>
|
||||
</template>
|
||||
@@ -1,34 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
|
||||
/**
|
||||
* SkeletonTable is a placeholder shaped exactly like DataTable.vue's own
|
||||
* rendered table — the same Table/TableRow/TableHead/TableCell
|
||||
* primitives, `rows` x `cols` pulsing cells — so a table view swapping
|
||||
* this in for its first load causes no layout shift once real rows
|
||||
* arrive. `cols` defaults to 4, the panel's most common table width;
|
||||
* callers with a narrower or wider table pass their own column count.
|
||||
*/
|
||||
withDefaults(defineProps<{ rows?: number; cols?: number }>(), { rows: 5, cols: 4 })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Table role="status" aria-busy="true" aria-label="Loading">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead v-for="c in cols" :key="c">
|
||||
<span class="sr-only">Loading</span>
|
||||
<Skeleton class="h-4 w-16" />
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="r in rows" :key="r">
|
||||
<TableCell v-for="c in cols" :key="c">
|
||||
<Skeleton class="h-4 w-full max-w-32" />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</template>
|
||||
@@ -1,224 +0,0 @@
|
||||
import { createSSRApp } from 'vue'
|
||||
import { renderToString } from 'vue/server-renderer'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import SmartRoutersCard from '@/components/SmartRoutersCard.vue'
|
||||
import type { AdminRouterView } from '@/types/api'
|
||||
|
||||
const router: AdminRouterView = {
|
||||
name: 'auto',
|
||||
defaultTier: 'small',
|
||||
selection: 'hash',
|
||||
maxAttempts: 3,
|
||||
contextEscalation: false,
|
||||
shadowEnabled: false,
|
||||
classifier: 'v1',
|
||||
riskZ: 128,
|
||||
calibration: { mode: 'off', delta: [], maxLower: 150, maxRaise: 0, freeze: false },
|
||||
saturationDowngrade: false,
|
||||
downgradeBand: 100,
|
||||
downgraded: 0,
|
||||
timeoutFallback: false,
|
||||
fellBack: 0,
|
||||
tiers: [
|
||||
{ name: 'small', minScore: 0, models: ['openai/gpt-5-mini'] },
|
||||
{ name: 'big', minScore: 400, models: ['anthropic/claude-opus', 'openai/gpt-5'] },
|
||||
],
|
||||
keywordRules: [{ tier: 'big', keywords: ['prove', 'audit'] }],
|
||||
contextTokens: 262144,
|
||||
stats: {
|
||||
scope: 'shared',
|
||||
requests: 4,
|
||||
tiers: [
|
||||
{ name: 'small', count: 1 },
|
||||
{ name: 'big', count: 3 },
|
||||
],
|
||||
reasons: [
|
||||
{ name: 'keyword', count: 1 },
|
||||
{ name: 'score', count: 3 },
|
||||
],
|
||||
escalations: [{ from: 'small', to: 'big', count: 2 }],
|
||||
shadow: [],
|
||||
outcomes: [],
|
||||
},
|
||||
}
|
||||
|
||||
function render(routers: AdminRouterView[]): Promise<string> {
|
||||
return renderToString(createSSRApp(SmartRoutersCard, { routers }))
|
||||
}
|
||||
|
||||
describe('SmartRoutersCard', () => {
|
||||
it('shows an empty message with no routers', async () => {
|
||||
expect(await render([])).toContain('None configured.')
|
||||
})
|
||||
|
||||
it('shows calibration, adaptive selection and downgrade settings', async () => {
|
||||
const live: AdminRouterView = {
|
||||
...router,
|
||||
selection: 'adaptive',
|
||||
adaptive: { explorePct: 5, windowHours: 6, latencyWeightPct: 30 },
|
||||
calibration: { mode: 'shadow', delta: [{ tier: 'big', delta: 25 }], maxLower: 150, maxRaise: 0, freeze: false },
|
||||
saturationDowngrade: true,
|
||||
downgradeBand: 100,
|
||||
downgraded: 7,
|
||||
}
|
||||
const html = await render([live])
|
||||
expect(html).toContain('selection: adaptive')
|
||||
expect(html).toContain('explore 5%, window 6h')
|
||||
expect(html).toContain('calibration: shadow')
|
||||
expect(html).toContain('offsets (not applied): big -25')
|
||||
expect(html).toContain('saturation downgrade: on, band 100')
|
||||
expect(html).toContain('downgraded: 7')
|
||||
const off = await render([router])
|
||||
expect(off).toContain('calibration: off')
|
||||
expect(off).toContain('saturation downgrade: off')
|
||||
expect(off).not.toContain('offsets')
|
||||
expect(off).not.toContain('explore')
|
||||
expect(off).not.toContain('downgraded:')
|
||||
})
|
||||
|
||||
it('shows the timeout fallback flag and its count only when on', async () => {
|
||||
const on = await render([{ ...router, timeoutFallback: true, fellBack: 3 }])
|
||||
expect(on).toContain('timeout fallback: on')
|
||||
expect(on).toContain('fell back: 3')
|
||||
const off = await render([router])
|
||||
expect(off).toContain('timeout fallback: off')
|
||||
expect(off).not.toContain('fell back:')
|
||||
})
|
||||
|
||||
it('renders router settings, tiers and keyword rules', async () => {
|
||||
const html = await render([router])
|
||||
expect(html).toContain('Smart routers')
|
||||
expect(html).toContain('auto')
|
||||
expect(html).toContain('default tier: small')
|
||||
expect(html).toContain('selection: hash')
|
||||
expect(html).toContain('max attempts: 3')
|
||||
expect(html).toContain('context escalation: off')
|
||||
expect(html).toContain('from score 400')
|
||||
expect(html).toContain('anthropic/claude-opus, openai/gpt-5')
|
||||
expect(html).toContain('prove, audit')
|
||||
})
|
||||
|
||||
it('shows the first byte timeout only when set', async () => {
|
||||
expect(await render([{ ...router, firstByteTimeout: '40s' }])).toContain('first byte timeout: 40s')
|
||||
expect(await render([router])).not.toContain('first byte timeout')
|
||||
})
|
||||
|
||||
it('shows the tools min tier only when set', async () => {
|
||||
expect(await render([{ ...router, toolsMinTier: 'big' }])).toContain('tools min tier: big')
|
||||
expect(await render([router])).not.toContain('tools min tier')
|
||||
})
|
||||
|
||||
it('shows the classifier and the risk margin only when v2 is involved', async () => {
|
||||
const plain = await render([router])
|
||||
expect(plain).toContain('classifier: v1')
|
||||
expect(plain).not.toContain('risk z')
|
||||
expect(plain).not.toContain('shadow classifier')
|
||||
const shadowed = await render([{ ...router, shadowEnabled: true, shadowClassifier: 'v2', riskZ: 90 }])
|
||||
expect(shadowed).toContain('shadow classifier: v2')
|
||||
expect(shadowed).toContain('risk z: 90')
|
||||
expect(await render([{ ...router, classifier: 'v2' }])).toContain('risk z: 128')
|
||||
})
|
||||
|
||||
it('renders the shadow agreement matrix only when shadow weights are set', async () => {
|
||||
const shadowed: AdminRouterView = {
|
||||
...router,
|
||||
shadowEnabled: true,
|
||||
stats: {
|
||||
...router.stats!,
|
||||
shadow: [
|
||||
{ live: 'small', shadow: 'small', count: 6 },
|
||||
{ live: 'big', shadow: 'small', count: 2 },
|
||||
{ live: 'big', shadow: 'big', count: 2 },
|
||||
],
|
||||
},
|
||||
}
|
||||
const html = await render([shadowed])
|
||||
expect(html).toContain('Shadow weights')
|
||||
expect(html).toContain('aria-label="Shadow agreement matrix for auto"')
|
||||
expect(html).toContain('agreement: 80%')
|
||||
expect(html).toMatch(/<th[^>]*>small<\/th>/)
|
||||
expect(html).toMatch(/data-cell="big:small"[^>]*>2</)
|
||||
expect(html).toMatch(/data-cell="small:big"[^>]*>0</)
|
||||
expect(await render([router])).not.toContain('Shadow weights')
|
||||
})
|
||||
|
||||
it('shows an empty shadow matrix without NaN', async () => {
|
||||
const html = await render([{ ...router, shadowEnabled: true }])
|
||||
expect(html).toContain('Shadow weights')
|
||||
expect(html).toContain('agreement: 0%')
|
||||
expect(html).not.toContain('NaN')
|
||||
})
|
||||
|
||||
it('renders outcome counts per tier summed over reasons', async () => {
|
||||
const withOutcomes: AdminRouterView = {
|
||||
...router,
|
||||
stats: {
|
||||
...router.stats!,
|
||||
outcomes: [
|
||||
{ tier: 'small', reason: 'score', outcome: 'ok', count: 3 },
|
||||
{ tier: 'small', reason: 'keyword', outcome: 'ok', count: 1 },
|
||||
{ tier: 'small', reason: 'score', outcome: 'escalated', count: 2 },
|
||||
{ tier: 'big', reason: 'score', outcome: 'error', count: 1 },
|
||||
{ tier: 'big', reason: 'score', outcome: 'bad', count: 2 },
|
||||
{ tier: 'big', reason: 'score', outcome: 'slow', count: 5 },
|
||||
{ tier: 'big', reason: 'keyword', outcome: 'slow', count: 1 },
|
||||
],
|
||||
},
|
||||
}
|
||||
const html = await render([withOutcomes])
|
||||
expect(html).toContain('aria-label="Outcomes for auto"')
|
||||
expect(html).toMatch(/data-cell="small:ok"[^>]*>4</)
|
||||
expect(html).toMatch(/data-cell="small:escalated"[^>]*>2</)
|
||||
expect(html).toMatch(/data-cell="big:error"[^>]*>1</)
|
||||
expect(html).toMatch(/data-cell="big:bad"[^>]*>2</)
|
||||
expect(html).toMatch(/<th[^>]*>slow<\/th>/)
|
||||
expect(html).toMatch(/data-cell="big:slow"[^>]*>6</)
|
||||
expect(html).toMatch(/data-cell="small:slow"[^>]*>0</)
|
||||
expect(await render([router])).not.toContain('Outcomes for')
|
||||
})
|
||||
|
||||
it('labels shadow and outcome scope like the other counts', async () => {
|
||||
const html = await render([{ ...router, shadowEnabled: true, stats: { ...router.stats!, scope: 'instance' } }])
|
||||
expect(html).toContain('This gateway instance, since start')
|
||||
})
|
||||
|
||||
it('shows the context window, per-tier counts and shares, reasons and escalations', async () => {
|
||||
const html = await render([router])
|
||||
expect(html).toContain('context window: 256k')
|
||||
expect(html).toContain('requests: 4')
|
||||
expect(html).toContain('1 req (25%)')
|
||||
expect(html).toContain('3 req (75%)')
|
||||
expect(html).toContain('width:75%')
|
||||
expect(html).toContain('keyword: 1')
|
||||
expect(html).toContain('score: 3')
|
||||
expect(html).toMatch(/Escalated[\s\S]*small[\s\S]*to[\s\S]*big[\s\S]*: 2/)
|
||||
expect(html).toContain('All replicas, this month (UTC)')
|
||||
})
|
||||
|
||||
it('labels per-instance counts when Redis is not shared', async () => {
|
||||
const html = await render([{ ...router, stats: { ...router.stats!, scope: 'instance' } }])
|
||||
expect(html).toContain('This gateway instance, since start')
|
||||
expect(html).not.toContain('All replicas')
|
||||
})
|
||||
|
||||
it('renders zero counts and no window without stats', async () => {
|
||||
const { contextTokens: _c, stats: _s, ...bare } = router
|
||||
const html = await render([bare])
|
||||
expect(html).not.toContain('context window:')
|
||||
expect(html).toContain('requests: 0')
|
||||
expect(html).toContain('0 req (0%)')
|
||||
expect(html).not.toContain('Routing reasons')
|
||||
expect(html).not.toContain('Escalated')
|
||||
})
|
||||
|
||||
it('handles zero-filled stats without dividing by zero', async () => {
|
||||
const zero: AdminRouterView = {
|
||||
...router,
|
||||
stats: { scope: 'instance', requests: 0, tiers: [{ name: 'small', count: 0 }, { name: 'big', count: 0 }], reasons: [], escalations: [], shadow: [], outcomes: [] },
|
||||
}
|
||||
const html = await render([zero])
|
||||
expect(html).toContain('0 req (0%)')
|
||||
expect(html).not.toContain('NaN')
|
||||
})
|
||||
})
|
||||
@@ -1,180 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { formatContextWindow } from '@/lib/format'
|
||||
import type { AdminRouterView } from '@/types/api'
|
||||
|
||||
/**
|
||||
* SmartRoutersCard is the Models page's read-only view of every configured
|
||||
* smart router (admin_routers.go): tiers cheapest first with their score
|
||||
* floor and models, plus selection, attempt cap and keyword rules. Config
|
||||
* lives in the plugin config; use the Config page's router helper to build a
|
||||
* snippet. Counts are fleet-wide per month with Redis, else per process.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
routers: AdminRouterView[]
|
||||
}>()
|
||||
|
||||
const scopeLabel = computed(() =>
|
||||
props.routers.some((r) => r.stats?.scope === 'shared') ? 'Counts: All replicas, this month (UTC)' : 'Counts: This gateway instance, since start',
|
||||
)
|
||||
|
||||
const OUTCOMES = ['ok', 'escalated', 'error', 'bad', 'slow'] as const
|
||||
|
||||
function shadowCount(router: AdminRouterView, live: string, shadow: string): number {
|
||||
return router.stats?.shadow.find((c) => c.live === live && c.shadow === shadow)?.count ?? 0
|
||||
}
|
||||
|
||||
function shadowAgreement(router: AdminRouterView): number {
|
||||
const cells = router.stats?.shadow ?? []
|
||||
const total = cells.reduce((sum, c) => sum + c.count, 0)
|
||||
const same = cells.filter((c) => c.live === c.shadow).reduce((sum, c) => sum + c.count, 0)
|
||||
return share(same, total)
|
||||
}
|
||||
|
||||
function outcomeCount(router: AdminRouterView, tier: string, outcome: string): number {
|
||||
return (router.stats?.outcomes ?? []).filter((o) => o.tier === tier && o.outcome === outcome).reduce((sum, o) => sum + o.count, 0)
|
||||
}
|
||||
|
||||
function deltaLabel(router: AdminRouterView): string {
|
||||
return router.calibration.delta.map((d) => `${d.tier} -${d.delta}`).join(', ')
|
||||
}
|
||||
|
||||
function share(count: number, total: number): number {
|
||||
return total > 0 ? Math.round((count / total) * 100) : 0
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Smart routers</CardTitle>
|
||||
<CardDescription>Virtual models that pick a tier by request complexity and escalate on failure. {{ scopeLabel }}.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<p v-if="routers.length === 0" class="text-sm text-muted-foreground">None configured.</p>
|
||||
<section v-for="router in routers" :key="router.name" class="flex flex-col gap-2" :aria-label="`Router ${router.name}`">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="font-mono text-sm font-medium">{{ router.name }}</span>
|
||||
<Badge variant="outline" class="font-normal">default tier: {{ router.defaultTier }}</Badge>
|
||||
<Badge v-if="router.toolsMinTier" variant="outline" class="font-normal">tools min tier: {{ router.toolsMinTier }}</Badge>
|
||||
<Badge variant="outline" class="font-normal">classifier: {{ router.classifier }}</Badge>
|
||||
<Badge v-if="router.shadowClassifier" variant="outline" class="font-normal">shadow classifier: {{ router.shadowClassifier }}</Badge>
|
||||
<Badge v-if="router.classifier === 'v2' || router.shadowClassifier" variant="outline" class="font-normal">risk z: {{ router.riskZ }}</Badge>
|
||||
<Badge variant="outline" class="font-normal">selection: {{ router.selection }}</Badge>
|
||||
<Badge v-if="router.adaptive" variant="outline" class="font-normal">
|
||||
explore {{ router.adaptive.explorePct }}%, window {{ router.adaptive.windowHours }}h
|
||||
</Badge>
|
||||
<Badge variant="outline" class="font-normal">calibration: {{ router.calibration.mode }}</Badge>
|
||||
<Badge v-if="router.calibration.mode !== 'off' && router.calibration.freeze" variant="outline" class="font-normal">
|
||||
calibration frozen
|
||||
</Badge>
|
||||
<Badge v-if="router.calibration.mode !== 'off'" variant="outline" class="font-normal">
|
||||
offsets{{ router.calibration.mode === 'shadow' ? ' (not applied)' : '' }}: {{ deltaLabel(router) }}
|
||||
</Badge>
|
||||
<Badge variant="outline" class="font-normal">
|
||||
saturation downgrade: {{ router.saturationDowngrade ? `on, band ${router.downgradeBand}` : 'off' }}
|
||||
</Badge>
|
||||
<Badge v-if="router.saturationDowngrade" variant="secondary" class="font-normal">downgraded: {{ router.downgraded }}</Badge>
|
||||
<Badge variant="outline" class="font-normal">timeout fallback: {{ router.timeoutFallback ? 'on' : 'off' }}</Badge>
|
||||
<Badge v-if="router.timeoutFallback" variant="secondary" class="font-normal">fell back: {{ router.fellBack }}</Badge>
|
||||
<Badge variant="outline" class="font-normal">max attempts: {{ router.maxAttempts }}</Badge>
|
||||
<Badge v-if="router.firstByteTimeout" variant="outline" class="font-normal">
|
||||
first byte timeout: {{ router.firstByteTimeout }}
|
||||
</Badge>
|
||||
<Badge variant="outline" class="font-normal">context escalation: {{ router.contextEscalation ? 'on' : 'off' }}</Badge>
|
||||
<Badge v-if="router.contextTokens" variant="outline" class="font-normal">
|
||||
context window: {{ formatContextWindow(router.contextTokens) }}
|
||||
</Badge>
|
||||
<Badge variant="secondary" class="font-normal">requests: {{ router.stats?.requests ?? 0 }}</Badge>
|
||||
</div>
|
||||
<ol class="flex flex-col gap-1 text-sm">
|
||||
<li v-for="(tier, index) in router.tiers" :key="tier.name" class="flex flex-col gap-1">
|
||||
<div class="flex flex-wrap items-baseline gap-2">
|
||||
<span class="font-medium">{{ tier.name }}</span>
|
||||
<span class="text-xs text-muted-foreground">from score {{ tier.minScore }}</span>
|
||||
<span class="font-mono text-xs break-all">{{ tier.models.join(', ') }}</span>
|
||||
<span class="ml-auto text-xs tabular-nums text-muted-foreground">
|
||||
{{ router.stats?.tiers[index]?.count ?? 0 }} req ({{ share(router.stats?.tiers[index]?.count ?? 0, router.stats?.requests ?? 0) }}%)
|
||||
</span>
|
||||
</div>
|
||||
<div class="h-1.5 w-full overflow-hidden rounded-full bg-muted" aria-hidden="true">
|
||||
<div
|
||||
class="h-full rounded-full bg-primary"
|
||||
:style="{ width: `${share(router.stats?.tiers[index]?.count ?? 0, router.stats?.requests ?? 0)}%` }"
|
||||
/>
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
<p v-if="router.stats && router.stats.reasons.length > 0" class="flex flex-wrap items-center gap-1 text-xs text-muted-foreground">
|
||||
Routing reasons:
|
||||
<Badge v-for="reason in router.stats.reasons" :key="reason.name" variant="outline" class="font-normal">
|
||||
{{ reason.name }}: {{ reason.count }}
|
||||
</Badge>
|
||||
</p>
|
||||
<ul v-if="router.stats && router.stats.escalations.length > 0" class="flex flex-col gap-0.5 text-xs text-muted-foreground">
|
||||
<li v-for="esc in router.stats.escalations" :key="`${esc.from}>${esc.to}`">
|
||||
Escalated <span class="font-medium">{{ esc.from }}</span> to <span class="font-medium">{{ esc.to }}</span>:
|
||||
{{ esc.count }}
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="router.shadowEnabled" class="flex flex-col gap-1">
|
||||
<p class="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
<span class="font-medium">Shadow weights</span>
|
||||
<span>Live tier (rows) against shadow tier (columns). No effect on routing.</span>
|
||||
<Badge variant="outline" class="font-normal">agreement: {{ shadowAgreement(router) }}%</Badge>
|
||||
</p>
|
||||
<table class="w-fit text-xs tabular-nums" :aria-label="`Shadow agreement matrix for ${router.name}`">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-2 py-0.5" />
|
||||
<th v-for="col in router.tiers" :key="col.name" scope="col" class="px-2 py-0.5 text-right font-medium">{{ col.name }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="row in router.tiers" :key="row.name">
|
||||
<th scope="row" class="px-2 py-0.5 text-left font-medium">{{ row.name }}</th>
|
||||
<td
|
||||
v-for="col in router.tiers"
|
||||
:key="col.name"
|
||||
:data-cell="`${row.name}:${col.name}`"
|
||||
class="px-2 py-0.5 text-right"
|
||||
:class="row.name === col.name ? 'bg-muted font-medium' : 'text-muted-foreground'"
|
||||
>
|
||||
{{ shadowCount(router, row.name, col.name) }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div v-if="router.stats && router.stats.outcomes.length > 0" class="flex flex-col gap-1">
|
||||
<p class="text-xs text-muted-foreground">
|
||||
<span class="font-medium">Outcomes</span> by first attempted tier. Escalated means a higher tier served it; error means a final non-2xx; slow means an attempt missed the first-byte timeout.
|
||||
</p>
|
||||
<table class="w-fit text-xs tabular-nums" :aria-label="`Outcomes for ${router.name}`">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-2 py-0.5" />
|
||||
<th v-for="outcome in OUTCOMES" :key="outcome" scope="col" class="px-2 py-0.5 text-right font-medium">{{ outcome }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="tier in router.tiers" :key="tier.name">
|
||||
<th scope="row" class="px-2 py-0.5 text-left font-medium">{{ tier.name }}</th>
|
||||
<td v-for="outcome in OUTCOMES" :key="outcome" :data-cell="`${tier.name}:${outcome}`" class="px-2 py-0.5 text-right">
|
||||
{{ outcomeCount(router, tier.name, outcome) }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p v-for="(rule, index) in router.keywordRules" :key="index" class="text-xs text-muted-foreground">
|
||||
Keywords to <span class="font-medium">{{ rule.tier }}</span
|
||||
>: <span class="font-mono">{{ rule.keywords.join(', ') }}</span>
|
||||
</p>
|
||||
</section>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -1,58 +0,0 @@
|
||||
<script setup lang="ts" generic="TData">
|
||||
import type { Header } from '@tanstack/vue-table'
|
||||
import { faSort, faSortDown, faSortUp } from '@fortawesome/free-solid-svg-icons'
|
||||
import { FlexRender } from '@tanstack/vue-table'
|
||||
import { computed } from 'vue'
|
||||
|
||||
/**
|
||||
* SortHeaderButton is the one clickable, sortable-column control every
|
||||
* sortable header in the panel uses — DataTable.vue's real `<th>` header
|
||||
* buttons AND ConsumerDirectory.vue's Groups sort toolbar (which has no
|
||||
* `<table>` to put a `<th>` in — see that component's own "Groups
|
||||
* accordion" doc comment for why).
|
||||
* Extracted so the button markup, sort-icon logic, click handler, and
|
||||
* accessible name exist in exactly one place (vue.md: "if you've written
|
||||
* it twice, you owe an abstraction"). Extra classes on this component
|
||||
* (e.g. DataTable.vue's `-mx-1.5` cell-edge alignment) fall through onto
|
||||
* the root `<button>` via Vue's default attribute inheritance.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
header: Header<TData, unknown>
|
||||
}>()
|
||||
|
||||
const direction = computed(() => props.header.column.getIsSorted())
|
||||
|
||||
const icon = computed(() => (direction.value === 'asc' ? faSortUp : direction.value === 'desc' ? faSortDown : faSort))
|
||||
|
||||
/** headerLabel reads the column's own string header when it has one (every column def in this app uses a plain string) — falling back to the column id so the accessible name is never empty even for a hypothetical future function-header column. */
|
||||
const headerLabel = computed(() => {
|
||||
const def = props.header.column.columnDef.header
|
||||
return typeof def === 'string' ? def : props.header.column.id
|
||||
})
|
||||
|
||||
const ariaLabel = computed(() => {
|
||||
const state = direction.value === 'asc' ? 'ascending' : direction.value === 'desc' ? 'descending' : 'none'
|
||||
return `Sort by ${headerLabel.value}, currently ${state}`
|
||||
})
|
||||
|
||||
function onClick(): void {
|
||||
props.header.column.toggleSorting(direction.value === 'asc')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
type="button"
|
||||
:aria-label="ariaLabel"
|
||||
class="inline-flex items-center gap-1 rounded px-1.5 py-0.5 hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring"
|
||||
@click="onClick"
|
||||
>
|
||||
<FlexRender v-if="!header.isPlaceholder" :render="header.column.columnDef.header" :props="header.getContext()" />
|
||||
<FontAwesomeIcon
|
||||
:icon="icon"
|
||||
class="size-3 shrink-0"
|
||||
:class="direction ? 'text-foreground' : 'text-muted-foreground/60'"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
</template>
|
||||
@@ -1,14 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { faTriangleExclamation } from '@fortawesome/free-solid-svg-icons'
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
|
||||
defineProps<{ message: string | null }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Alert v-if="message" variant="warn" role="status">
|
||||
<FontAwesomeIcon :icon="faTriangleExclamation" aria-hidden="true" />
|
||||
<AlertDescription>{{ message }}</AlertDescription>
|
||||
</Alert>
|
||||
</template>
|
||||
@@ -1,36 +0,0 @@
|
||||
<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>
|
||||
@@ -1,39 +0,0 @@
|
||||
<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>
|
||||
@@ -1,105 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
import ClampedRangeNotice from '@/components/ClampedRangeNotice.vue'
|
||||
import DataTable from '@/components/DataTable.vue'
|
||||
import LoadStateView from '@/components/LoadStateView.vue'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { adminFetch, messageOf } from '@/lib/api'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { dayOrMonthWindow, totalsUrl } from '@/lib/range'
|
||||
import { targetCallerColumns } from '@/lib/target-columns'
|
||||
import { useFiltersStore } from '@/stores/filters'
|
||||
import type { AdminTotalsResponse } from '@/types/api'
|
||||
|
||||
/**
|
||||
* TargetCallers (redesign-plan.md section 3.4, MCP & Agents page) reads
|
||||
* GET /admin/api/usage/totals?kind=targetcaller — per-caller request
|
||||
* counts, ranked descending, dropped to zero rows server-side. Used in two
|
||||
* modes from TargetsPage.vue, sharing this one component (vue.md: "if
|
||||
* you've written it twice, you owe an abstraction") rather than a
|
||||
* near-duplicate for each:
|
||||
*
|
||||
* - Per-target ("TargetCallers.vue expander"): `target` is set to the
|
||||
* composed "mcp/{name}"/"agent/{name}" id (lib/target-columns.ts's
|
||||
* composeTargetId) of whichever row the reader clicked in TargetsView.vue
|
||||
* — shows only that target's own callers, no Target column (the panel's
|
||||
* own heading already names it).
|
||||
* - Fleet-wide ("top callers" card): `target` omitted — every configured
|
||||
* target's callers, ranked together, WITH a Target column so a caller
|
||||
* who reaches more than one target is not ambiguous.
|
||||
*
|
||||
* `kind=targetcaller` only supports day/month windows (redesign-plan.md
|
||||
* section 1.3.v) — lib/range.ts's dayOrMonthWindow clamps the global
|
||||
* filters store's current (possibly hour-window) range down to a window
|
||||
* this endpoint actually accepts, rather than firing an invalid request
|
||||
* whenever the reader has an hour-resolution range (24h/48h) selected.
|
||||
*/
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** Composed "mcp/{name}" / "agent/{name}" id — omitted means fleet-wide, every target. */
|
||||
target?: string
|
||||
title: string
|
||||
limit?: number
|
||||
}>(),
|
||||
{ limit: 10 },
|
||||
)
|
||||
|
||||
const filters = useFiltersStore()
|
||||
|
||||
const rows = ref<AdminTotalsResponse['rows']>([])
|
||||
const loading = ref(false)
|
||||
/** loadedOk is true only right after a SUCCESSFUL fetch for the CURRENT selection (even with zero rows — a genuine "no callers" answer is still data) — reset synchronously at the top of every load() call, not just on props.target changing, so a range change gets the identical "skeleton while this NEW selection's own fetch is in flight" treatment (states-plan.md item 1: a skeleton only for the current selection's own missing data, never stale data from the previous one). */
|
||||
const loadedOk = ref(false)
|
||||
const error = ref('')
|
||||
/** reqId guards against an out-of-order response overwriting a newer one (latest-request-wins, stores/catalog.ts's own convention) — a quick target switch, or a range change mid-flight, no longer risks showing a STALE target's callers under the new heading. */
|
||||
let reqId = 0
|
||||
|
||||
async function load(): Promise<void> {
|
||||
const requestId = ++reqId
|
||||
loading.value = true
|
||||
rows.value = []
|
||||
loadedOk.value = false
|
||||
error.value = ''
|
||||
try {
|
||||
const { window, span } = dayOrMonthWindow(filters.window, filters.span)
|
||||
const res = await adminFetch<AdminTotalsResponse>(
|
||||
totalsUrl({ kind: 'targetcaller', window, span, metrics: ['req'], limit: props.limit, target: props.target }),
|
||||
)
|
||||
if (requestId !== reqId) return
|
||||
rows.value = res.rows
|
||||
loadedOk.value = true
|
||||
} catch (err) {
|
||||
if (requestId !== reqId) return
|
||||
error.value = messageOf(err)
|
||||
} finally {
|
||||
if (requestId === reqId) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
[() => props.target, () => filters.window, () => filters.span],
|
||||
() => void load(),
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
const columns = computed(() => targetCallerColumns(!props.target))
|
||||
|
||||
/** callersLoadState (lib/load-state.ts) replaces the old "loading…" text this view used to render inline as a fake DataTable empty-row — it no longer distinguished a still-loading fetch from one that had already FAILED (an initial-fetch failure rendered the identical "loading…" text forever, the same class of bug EventsView.vue's own P9 fix addressed). */
|
||||
const callersLoadState = computed(() => loadState({ loading: loading.value, hasData: loadedOk.value, error: error.value }))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{{ title }}</CardTitle>
|
||||
<CardDescription>Ranked by requests, most recent day/month window available for the current range.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-3">
|
||||
<ClampedRangeNotice :window="filters.window" :span="filters.span" />
|
||||
<LoadStateView :state="callersLoadState" :error="error" :on-retry="load" skeleton="table" :rows="5" :cols="columns.length">
|
||||
<DataTable :columns="columns" :data="rows" label="Callers" empty-message="no callers recorded in this window" />
|
||||
</LoadStateView>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -1,150 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import DataTable from '@/components/DataTable.vue'
|
||||
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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { useSearchQuery } from '@/composables/useSearchQuery'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { composeTargetId, targetColumns } from '@/lib/target-columns'
|
||||
import type { TargetKind } from '@/lib/target-columns'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import type { AdminTargetView } from '@/types/api'
|
||||
|
||||
// This component backs the "MCP & Agents" page (redesign-plan.md section
|
||||
// 3.4, TargetsPage.vue) — GET /admin/api/targets (admin.go:
|
||||
// adminTargetsResponse, Feature B v0.21).
|
||||
const dashboard = useDashboardStore()
|
||||
const targets = computed(() => dashboard.targets)
|
||||
|
||||
/**
|
||||
* select (redesign-plan.md section 3.4's "TargetCallers.vue expander")
|
||||
* fires with the composed "mcp/{name}"/"agent/{name}" id and the target's
|
||||
* own display name — TargetsPage.vue listens and renders TargetCallers.vue
|
||||
* for whichever target the reader last clicked. Two separate
|
||||
* targetColumns() instantiations below (MCP servers, Agents) close over
|
||||
* their own fixed `kind` so a click always composes the correct prefix,
|
||||
* without this component needing to carry a per-row kind field itself.
|
||||
*/
|
||||
const emit = defineEmits<{ select: [id: string, label: string] }>()
|
||||
|
||||
function onSelect(kind: TargetKind): (t: AdminTargetView) => void {
|
||||
return (t) => emit('select', composeTargetId(kind, t.name), t.name)
|
||||
}
|
||||
|
||||
// Simple, single-field substring match on name — no separate lib/*-search
|
||||
// module: ProviderHealthPanel.vue's own aliasMatches/providerMatches stay
|
||||
// inline for the identical reason (one field, one comparison), reserving
|
||||
// the extracted-and-tested lib/usage-search.ts treatment for
|
||||
// ConsumerDirectory.vue's genuinely multi-entity (user-or-group-member)
|
||||
// matching semantics.
|
||||
const { query, normalized: normalizedQuery, hasQuery } = useSearchQuery()
|
||||
|
||||
function nameMatches(t: AdminTargetView): boolean {
|
||||
return t.name.toLowerCase().includes(normalizedQuery.value)
|
||||
}
|
||||
|
||||
const filteredMCPServers = computed<AdminTargetView[]>(() => {
|
||||
const all = targets.value?.mcpServers ?? []
|
||||
return hasQuery.value ? all.filter(nameMatches) : all
|
||||
})
|
||||
const filteredAgents = computed<AdminTargetView[]>(() => {
|
||||
const all = targets.value?.agents ?? []
|
||||
return hasQuery.value ? all.filter(nameMatches) : all
|
||||
})
|
||||
|
||||
/** emptyMessage mirrors ConsumerDirectory.vue's groupsEmptyMessage/usersEmptyMessage three-way pattern: distinguishes nothing configured from nothing matching the active query. */
|
||||
function emptyMessage(configuredCount: number, filteredCount: number): string {
|
||||
if (!configuredCount) return 'none configured'
|
||||
if (hasQuery.value && filteredCount === 0) return `no targets match "${query.value}"`
|
||||
return 'none'
|
||||
}
|
||||
|
||||
const mcpEmptyMessage = computed(() => emptyMessage(targets.value?.mcpServers.length ?? 0, filteredMCPServers.value.length))
|
||||
const agentsEmptyMessage = computed(() => emptyMessage(targets.value?.agents.length ?? 0, filteredAgents.value.length))
|
||||
|
||||
/**
|
||||
* targetsLoadState (lib/load-state.ts) — GET /admin/api/targets used to
|
||||
* have NO loading/error handling at all here: `targets` mapped a
|
||||
* not-yet-loaded/errored dashboard.targets straight to `[]` (`?? []`
|
||||
* above), which DataTable then rendered as a confirmed, empty table —
|
||||
* exactly the same class of bug lib/access-matrix.ts's matrixColumnsState
|
||||
* fixed for the Access matrix (Task A). 'ready' once dashboard.targets
|
||||
* has loaded at least once, even if both lists are genuinely empty —
|
||||
* `noTargetsAtAll` below is the SEPARATE "loaded, but nothing configured"
|
||||
* check, same split as matrixColumnsState's own loaded-vs-empty
|
||||
* precedence.
|
||||
*/
|
||||
const targetsLoadState = computed(() => loadState({ loading: true, hasData: dashboard.targets !== null, error: dashboard.error }))
|
||||
|
||||
/**
|
||||
* noTargetsAtAll (states-plan.md item 2: "MCP & Agents: 'No MCP servers
|
||||
* or agents configured'") is true only once targets have genuinely
|
||||
* loaded with BOTH lists empty — read off the raw configured counts, not
|
||||
* the filtered ones, so an active search query never flips this true (a
|
||||
* query matching nothing is `mcpEmptyMessage`/`agentsEmptyMessage`'s own
|
||||
* "no targets match" case instead, a routine filter interaction, not a
|
||||
* fleet-configuration fact worth the same combined empty-state).
|
||||
*/
|
||||
const noTargetsAtAll = computed(
|
||||
() => targetsLoadState.value === 'ready' && (targets.value?.mcpServers.length ?? 0) === 0 && (targets.value?.agents.length ?? 0) === 0,
|
||||
)
|
||||
|
||||
// Two separate column-def sets (lib/target-columns.ts) — MCP servers and
|
||||
// Agents each close over their own fixed `kind` (see onSelect above) so a
|
||||
// name click composes the right "mcp/…"/"agent/…" id. Stateless ColumnDef
|
||||
// objects otherwise, safe to reuse across DataTable's two separate
|
||||
// useVueTable instances (each owns its own sorting state).
|
||||
const mcpColumns = targetColumns(onSelect('mcp'))
|
||||
const agentColumns = targetColumns(onSelect('agent'))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<SearchInput v-model="query" placeholder="Filter MCP servers or agents" class="max-w-sm" />
|
||||
|
||||
<Card v-if="noTargetsAtAll">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
title="No MCP servers or agents configured."
|
||||
description="Add an mcpServers or agents entry to the middleware config to see them here."
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<template v-else>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>MCP servers</CardTitle>
|
||||
<CardDescription>
|
||||
Configured MCP proxy targets, the groups allowed to reach them, and their request counters. Click a name to see
|
||||
its callers.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<SkeletonTable v-if="targetsLoadState === 'skeleton'" :rows="3" :cols="mcpColumns.length" />
|
||||
<ErrorState v-else-if="targetsLoadState === 'error'" :message="dashboard.error" :on-retry="dashboard.refresh" />
|
||||
<DataTable v-else label="MCP servers" :columns="mcpColumns" :data="filteredMCPServers" :empty-message="mcpEmptyMessage" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Agents</CardTitle>
|
||||
<CardDescription>
|
||||
Configured A2A agent proxy targets, the groups allowed to reach them, and their request counters. Click a name to
|
||||
see its callers.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<SkeletonTable v-if="targetsLoadState === 'skeleton'" :rows="3" :cols="agentColumns.length" />
|
||||
<ErrorState v-else-if="targetsLoadState === 'error'" :message="dashboard.error" :on-retry="dashboard.refresh" />
|
||||
<DataTable v-else label="Agents" :columns="agentColumns" :data="filteredAgents" :empty-message="agentsEmptyMessage" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,190 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { ChartData, ChartOptions } from 'chart.js'
|
||||
import { computed, useId } from 'vue'
|
||||
import { Line } from 'vue-chartjs'
|
||||
|
||||
import '@/lib/chart-setup'
|
||||
import { useThemeColors } from '@/composables/useThemeColors'
|
||||
import { formatExactInt } from '@/lib/format'
|
||||
|
||||
/** One line-chart series: a label, its values (index-aligned with the `labels` prop below), and which main.css --chart-* token colors it. */
|
||||
export interface TimeSeriesDataset {
|
||||
label: string
|
||||
data: number[]
|
||||
/** A main.css --chart-* custom property name (e.g. '--chart-requests') — resolved live via getComputedStyle (this component's own resolveToken, below), so a chart already on screen repaints on a `prefers-color-scheme` flip. */
|
||||
color: string
|
||||
}
|
||||
|
||||
/**
|
||||
* TimeSeriesComparisonDataset is one `comparisonDatasets` entry — a plain
|
||||
* TimeSeriesDataset plus an OPT-IN `labelSuffix`, appended to `label`
|
||||
* verbatim (undefined/empty appends nothing). Callers decide per dataset,
|
||||
* not this component for all of them: SpendPage.vue's own "vs previous
|
||||
* period" comparison sets `labelSuffix: ' (previous period)'` (Q5), while
|
||||
* BurnDownChart.vue's flat budget reference line — also rendered through
|
||||
* this same `comparisonDatasets` prop, since a budget ceiling is exactly
|
||||
* the "reference overlay, not a component of the current total" this prop
|
||||
* already means — sets none, so its line reads plain "Budget", never the
|
||||
* misleading "Budget (previous period)" (P2 item 5: a fixed
|
||||
* budget line is not a previous-period ANYTHING).
|
||||
*/
|
||||
export interface TimeSeriesComparisonDataset extends TimeSeriesDataset {
|
||||
labelSuffix?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* TimeSeriesChart (redesign-plan.md section 3.4) is the redesign's shared
|
||||
* line-chart primitive — Spend's cost breakdown (stacked), Reliability's
|
||||
* per-provider error rate (overlaid, not stacked), and any other
|
||||
* multi-series-over-time view build on this ONE component rather than
|
||||
* each growing its own vue-chartjs wiring. It is the only chart component
|
||||
* in this panel — lib/chart-setup.ts registers exactly the Line/Filler
|
||||
* pieces it uses, nothing more.
|
||||
*
|
||||
* `comparisonDatasets` (Q5/section 3.1 "vs previous period", and
|
||||
* BurnDownChart.vue's budget reference line) renders as a SEPARATE set of
|
||||
* dashed lines, one per entry, matched to its solid counterpart by array
|
||||
* index and color — never stacked, never filled, regardless of `stacked`,
|
||||
* since a comparison line is a reference overlay, not a component of the
|
||||
* current total.
|
||||
*/
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
labels: string[]
|
||||
datasets: TimeSeriesDataset[]
|
||||
/** A reference/overlay series, one dashed line per entry — omitted/empty draws no comparison. Each entry's own `labelSuffix` (TimeSeriesComparisonDataset) decides whether its label reads "vs previous period" or plain. */
|
||||
comparisonDatasets?: TimeSeriesComparisonDataset[]
|
||||
/** Stack every dataset into one filled total (Spend's cost breakdown) instead of overlaying them as independent lines (Reliability's per-provider error rate). */
|
||||
stacked?: boolean
|
||||
/** Formats a raw value for the tooltip and y-axis ticks — defaults to formatExactInt (lib/format.ts). Cost callers pass formatCost, a ratio series a percent formatter, and so on. */
|
||||
valueFormatter?: (value: number) => string
|
||||
/** Y-axis tick formatter when the tooltip formatter is too wordy for a tick (cost: "$1,600" not "$1,600.00"); defaults to valueFormatter. */
|
||||
axisFormatter?: (value: number) => string
|
||||
/**
|
||||
* ariaLabel is this chart's accessible name (P3 item 16) — a bare
|
||||
* `<canvas>` has no text alternative at all for a screen reader, so
|
||||
* every call site supplies a short description of what the chart
|
||||
* shows (e.g. "Spend by model over time"). Required, not optional:
|
||||
* there is no safe generic default that would be meaningful across
|
||||
* this component's very different callers (Spend's breakdown,
|
||||
* BurnDownChart's burn-down, Reliability's five series charts,
|
||||
* UserDetail's two per-user charts).
|
||||
*/
|
||||
ariaLabel: string
|
||||
}>(),
|
||||
{
|
||||
comparisonDatasets: () => [],
|
||||
stacked: false,
|
||||
valueFormatter: formatExactInt,
|
||||
},
|
||||
)
|
||||
|
||||
const descId = `timeseries-chart-desc-${useId()}`
|
||||
|
||||
/**
|
||||
* srSummary is the sr-only fallback's own text content (P3 item 16's fix
|
||||
* instruction: "an sr-only summary (latest value, total)") — one short
|
||||
* sentence per dataset, latest bucket's value and the sum across the
|
||||
* whole range, run through the SAME valueFormatter the visible tooltip/
|
||||
* axis use, so a screen reader hears figures in the identical units a
|
||||
* sighted reader sees. Comparison datasets are left out: they are a
|
||||
* reference overlay of the SAME primary series shifted back a period,
|
||||
* not new information this summary needs to repeat.
|
||||
*/
|
||||
const srSummary = computed<string>(() => {
|
||||
if (props.datasets.length === 0 || props.labels.length === 0) return 'No data for this range.'
|
||||
return props.datasets
|
||||
.map((d) => {
|
||||
const latest = d.data.length > 0 ? d.data[d.data.length - 1] : 0
|
||||
const total = d.data.reduce((sum, v) => sum + v, 0)
|
||||
return `${d.label}: latest ${props.valueFormatter(latest)}, total ${props.valueFormatter(total)} over ${props.labels.length} buckets.`
|
||||
})
|
||||
.join(' ')
|
||||
})
|
||||
|
||||
const { foreground, mutedForeground, border } = useThemeColors()
|
||||
|
||||
/** resolveToken reads one of main.css's --chart-* custom properties from :root, live — see this component's own doc comment on `color` above. */
|
||||
function resolveToken(cssVar: string): string {
|
||||
return getComputedStyle(document.documentElement).getPropertyValue(cssVar).trim()
|
||||
}
|
||||
|
||||
const chartData = computed<ChartData<'line'>>(() => {
|
||||
// Touch the theme ref so this computed re-runs (and re-reads the CSS
|
||||
// custom properties via resolveToken) on a `prefers-color-scheme` flip.
|
||||
void foreground.value
|
||||
const solid = props.datasets.map((d) => {
|
||||
const color = resolveToken(d.color)
|
||||
return {
|
||||
label: d.label,
|
||||
data: d.data,
|
||||
borderColor: color,
|
||||
backgroundColor: color,
|
||||
fill: props.stacked,
|
||||
stack: props.stacked ? 'main' : undefined,
|
||||
tension: 0.2,
|
||||
pointRadius: 2,
|
||||
borderWidth: 2,
|
||||
}
|
||||
})
|
||||
const comparison = props.comparisonDatasets.map((d) => {
|
||||
const color = resolveToken(d.color)
|
||||
return {
|
||||
label: `${d.label}${d.labelSuffix ?? ''}`,
|
||||
data: d.data,
|
||||
borderColor: color,
|
||||
backgroundColor: 'transparent',
|
||||
borderDash: [6, 4],
|
||||
fill: false,
|
||||
tension: 0.2,
|
||||
pointRadius: 0,
|
||||
borderWidth: 1.5,
|
||||
}
|
||||
})
|
||||
return { labels: props.labels, datasets: [...solid, ...comparison] }
|
||||
})
|
||||
|
||||
const chartOptions = computed<ChartOptions<'line'>>(() => ({
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
animation: false,
|
||||
interaction: { mode: 'index', intersect: false },
|
||||
scales: {
|
||||
x: {
|
||||
stacked: props.stacked,
|
||||
grid: { color: border.value, display: false },
|
||||
ticks: { color: mutedForeground.value },
|
||||
},
|
||||
y: {
|
||||
// Zero-based, honest axis (dataviz rule) — never a truncated y-scale that would exaggerate a small change.
|
||||
stacked: props.stacked,
|
||||
beginAtZero: true,
|
||||
grid: { color: border.value },
|
||||
// Counts are whole numbers: no 0.1-step ticks on a chart whose largest value is 1.
|
||||
ticks: {
|
||||
color: mutedForeground.value,
|
||||
precision: props.valueFormatter === formatExactInt ? 0 : undefined,
|
||||
callback: (value) => (props.axisFormatter ?? props.valueFormatter)(Number(value)),
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: props.datasets.length > 1 || props.comparisonDatasets.length > 0,
|
||||
labels: { color: foreground.value },
|
||||
},
|
||||
tooltip: {
|
||||
callbacks: {
|
||||
label: (ctx) => `${ctx.dataset.label}: ${props.valueFormatter(ctx.parsed.y ?? 0)}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="h-72 w-full" role="img" :aria-label="ariaLabel" :aria-describedby="descId">
|
||||
<Line :data="chartData" :options="chartOptions" />
|
||||
<p :id="descId" class="sr-only">{{ srSummary }}</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,114 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import EmptyState from '@/components/EmptyState.vue'
|
||||
import EntityLink from '@/components/EntityLink.vue'
|
||||
import ErrorState from '@/components/ErrorState.vue'
|
||||
import SkeletonList from '@/components/SkeletonList.vue'
|
||||
import StaleNotice from '@/components/StaleNotice.vue'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
import { staleNotice } from '@/lib/stale-notice'
|
||||
|
||||
/** One TopList.vue row — an entity id/label, its formatted value, and which EntityLink.vue target it opens. */
|
||||
export interface TopListItem {
|
||||
/** The raw entity id EntityLink.vue navigates on (a user id or a canonical model id). */
|
||||
id: string
|
||||
/** The visible label — usually the same as `id`, but callers may pass a friendlier form. */
|
||||
label: string
|
||||
/** Already-formatted display value (lib/format.ts) — this component renders it verbatim, never reformats. */
|
||||
value: string
|
||||
kind: 'user' | 'model'
|
||||
}
|
||||
|
||||
/**
|
||||
* TopList (redesign-plan.md section 3.4) is the Home page's ranked-list
|
||||
* card: "top 5 users by cost", "top 5 models". Each row is an EntityLink
|
||||
* so clicking a user opens Consumers pre-filtered to them, a model opens
|
||||
* Models — the SAME "jump to detail" affordance every table's id column
|
||||
* (usage-columns.ts, model-table-columns.ts) offers, reused here rather
|
||||
* than a plain unlinked list. The optional `controls` slot renders below
|
||||
* the title (e.g. HomePage.vue's top-users Cost/Requests/Tokens Tabs
|
||||
* switch, lib/top-users.ts) — omitted by callers with no mode switch of
|
||||
* their own, like the plain top-models card, so this stays one shared
|
||||
* component rather than a near-duplicate per card.
|
||||
*
|
||||
* States (states-plan.md item 1/3, verify-ui-states.md #1/#3/#4,
|
||||
* verify-ui-states-2.md #2) are decided via lib/load-state.ts's own
|
||||
* loadState off `loading`/`error`/`loaded` — NOT a bare
|
||||
* `loading && items.length === 0` check, and NOT `items.length > 0`
|
||||
* either: `hasData` here means "a fetch has completed for the CURRENT
|
||||
* selection" (the `loaded` prop, e.g. HomePage.vue's own per-mode
|
||||
* topUsersCache presence), not "there happen to be rows right now". A
|
||||
* caller's genuinely empty, already-settled selection must keep reading
|
||||
* as empty across a background poll's own `loading` flips (skeleton is
|
||||
* for a selection's FIRST fetch only) — using `items.length` for
|
||||
* `hasData` used to flip a settled EmptyState back to a skeleton on
|
||||
* every poll tick for exactly that case. Once `state` is not 'skeleton'
|
||||
* or 'error', the template below decides EmptyState vs. the real list by
|
||||
* checking `items.length` directly, the same way UserDetail.vue's own
|
||||
* "Models used" table does.
|
||||
*/
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
title: string
|
||||
items: TopListItem[]
|
||||
/** Shown in place of the list when `items` is empty (and not loading, not erroring) — e.g. "No traffic in this range." */
|
||||
emptyText: string
|
||||
loading?: boolean
|
||||
/**
|
||||
* True once a fetch has completed for the CURRENT selection (mode/
|
||||
* range), even if it resolved with zero items — the caller's own
|
||||
* per-selection flag (verify-ui-states-2.md #2), reset whenever the
|
||||
* caller's selection genuinely changes. Distinct from `items.length >
|
||||
* 0`: see this component's own States doc comment above.
|
||||
*/
|
||||
loaded?: boolean
|
||||
/** The current fetch's error message, '' (default) when there is none — mirrors lib/load-state.ts's own LoadStateInput.error. A background refresh's failure with `items` already populated never reaches ErrorState (loadState's 'ready' precedence) — stores/toasts.ts covers that case instead. */
|
||||
error?: string
|
||||
/** Renders a "Retry" button on ErrorState — the caller's own refetch action. */
|
||||
onRetry?: () => void | Promise<void>
|
||||
/**
|
||||
* A distinct, higher-precedence notice (e.g. HomePage.vue's top-users
|
||||
* "too many configured users for this range", lib/top-users.ts's
|
||||
* topUsersCapExceeded) that takes over the card's content entirely —
|
||||
* it names a KNOWN reason no data will load until the reader acts
|
||||
* (narrow the range), not a transient loading/error/empty state, so it
|
||||
* is checked before all three.
|
||||
*/
|
||||
notice?: string
|
||||
noticeDescription?: string
|
||||
}>(),
|
||||
{ loading: false, loaded: false, error: '' },
|
||||
)
|
||||
|
||||
const state = computed(() => loadState({ loading: props.loading, hasData: props.loaded, error: props.error ?? '' }))
|
||||
const staleMessage = computed(() => staleNotice(props.loaded, props.error ?? '', null))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{{ title }}</CardTitle>
|
||||
<slot name="controls" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<StaleNotice :message="notice ? null : staleMessage" class="mb-3" />
|
||||
<EmptyState v-if="notice" :title="notice" :description="noticeDescription" />
|
||||
<SkeletonList v-else-if="state === 'skeleton'" :rows="5" />
|
||||
<ErrorState v-else-if="state === 'error'" :message="error ?? ''" :on-retry="onRetry" />
|
||||
<EmptyState v-else-if="items.length === 0" :title="emptyText">
|
||||
<slot name="empty-action" />
|
||||
</EmptyState>
|
||||
<ol v-else class="flex flex-col gap-1.5">
|
||||
<li v-for="(item, i) in items" :key="item.id" class="flex items-center justify-between gap-3 text-sm">
|
||||
<span class="flex min-w-0 items-center gap-2">
|
||||
<span class="w-4 shrink-0 text-right text-xs text-muted-foreground">{{ i + 1 }}</span>
|
||||
<EntityLink :label="item.label" :kind="item.kind" :id="item.id" class="min-w-0" label-class="truncate" />
|
||||
</span>
|
||||
<span class="shrink-0 font-medium tabular-nums">{{ item.value }}</span>
|
||||
</li>
|
||||
</ol>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -1,41 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { RANGE_KEYS } from '@/lib/range'
|
||||
import { useFiltersStore } from '@/stores/filters'
|
||||
|
||||
/**
|
||||
* TryLongerRangeButton is the shared action every "No traffic in this
|
||||
* range" empty state offers (states-plan.md item 2: Spend/Models/Home
|
||||
* lists) — steps the global range to the NEXT LONGER preset in
|
||||
* RANGE_KEYS (verify-ui-states.md #7 fix), via stores/filters.ts, rather
|
||||
* than each empty state re-deriving its own inline click handler
|
||||
* (vue.md: "if you've written it twice, you owe an abstraction" — this
|
||||
* one appears on Home's two TopLists, the Spend page's Attribution
|
||||
* drilldown, and PricingHealthTable).
|
||||
*
|
||||
* Previously this always jumped straight to a fixed '30d' — on 3mo/6mo/
|
||||
* 12mo (lib/range.ts's RANGE_KEYS, already LONGER than 30d) that
|
||||
* SHORTENED the range instead of lengthening it, and did nothing at all
|
||||
* when already on 30d itself. Stepping to `RANGE_KEYS[currentIndex + 1]`
|
||||
* is always strictly longer than the current range, and the button hides
|
||||
* itself entirely at '12mo' (the longest preset — there is nothing
|
||||
* longer left to try).
|
||||
*/
|
||||
const filters = useFiltersStore()
|
||||
|
||||
const nextLongerRange = computed<string | null>(() => {
|
||||
const index = RANGE_KEYS.indexOf(filters.range)
|
||||
const next = RANGE_KEYS[index + 1]
|
||||
return next ?? null
|
||||
})
|
||||
|
||||
function onClick(): void {
|
||||
if (nextLongerRange.value) filters.setFilters({ range: nextLongerRange.value as (typeof RANGE_KEYS)[number] })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Button v-if="nextLongerRange" type="button" variant="outline" size="sm" @click="onClick">Try a longer range</Button>
|
||||
</template>
|
||||
@@ -1,74 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import { ratioTier } from '@/lib/usage-bars'
|
||||
|
||||
/**
|
||||
* UsageBar renders one BudgetRatio (lib/usage-bars.ts) as a compact
|
||||
* horizontal meter — F1, usage-vs-limit bars. A real `role="meter"`
|
||||
* (not a `<progress>` element: a meter reports a measurement against a
|
||||
* range, which is exactly a used/limit reading, where `<progress>`
|
||||
* implies a task moving toward completion) carries the accessible
|
||||
* reading via `aria-valuenow`/`aria-valuemin`/`aria-valuemax`/
|
||||
* `aria-valuetext`, so a screen reader announces the same number a
|
||||
* sighted reader sees in the fill width and the `title` tooltip.
|
||||
*
|
||||
* Used across the panel (usage-columns.ts's numeric cells,
|
||||
* ConsumerDirectory.vue's group detail grid, UserDetail.vue's headroom
|
||||
* bars) — every caller passes a fully-computed BudgetRatio plus its own
|
||||
* human-readable `valueText`, so this component has no formatting
|
||||
* opinion of its own (formatCost/formatExactInt stay the caller's job,
|
||||
* same "logic lives in lib/, not the component" split every other
|
||||
* shared component in this panel follows).
|
||||
*/
|
||||
const props = defineProps<{
|
||||
/** used / limit — may exceed 1 (a scope's usage window can roll past its limit before the next request is rejected). */
|
||||
ratio: number
|
||||
/** The accessible name for this meter, e.g. "req/day" or "cost/month". */
|
||||
label: string
|
||||
/** The human-readable "used of limit" text — both the `title` tooltip and `aria-valuetext`, e.g. "500 / 1,000" or "$1.20 / $5.00". */
|
||||
valueText: string
|
||||
class?: HTMLAttributes['class']
|
||||
}>()
|
||||
|
||||
const tier = computed(() => ratioTier(props.ratio))
|
||||
|
||||
/**
|
||||
* widthPct clamps the visible fill (and, via valueNow below, the
|
||||
* announced aria-valuenow) to 100% — a ratio above 1.0 (over the limit)
|
||||
* still reads as a full bar, with the RED tier and valueText's own real
|
||||
* "used / limit" numbers carrying the "how far over" detail instead of an
|
||||
* overflowing bar or an aria-valuenow exceeding its own declared
|
||||
* aria-valuemax (WAI-ARIA meter role: valuenow must stay within
|
||||
* valuemin/valuemax).
|
||||
*/
|
||||
const widthPct = computed(() => Math.min(100, Math.max(0, props.ratio * 100)))
|
||||
const valueNow = computed(() => Math.round(widthPct.value))
|
||||
|
||||
const TIER_FILL_CLASS: Record<ReturnType<typeof ratioTier>, string> = {
|
||||
normal: 'bg-primary',
|
||||
amber: 'bg-bar-amber',
|
||||
red: 'bg-destructive',
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
role="meter"
|
||||
:aria-label="label"
|
||||
:aria-valuenow="valueNow"
|
||||
aria-valuemin="0"
|
||||
aria-valuemax="100"
|
||||
:aria-valuetext="valueText"
|
||||
:title="valueText"
|
||||
:class="cn('relative inline-block h-1.5 w-14 shrink-0 overflow-hidden rounded-full bg-muted align-middle', props.class)"
|
||||
>
|
||||
<span
|
||||
class="absolute inset-y-0 left-0 rounded-full"
|
||||
:class="TIER_FILL_CLASS[tier]"
|
||||
:style="{ width: `${widthPct}%` }"
|
||||
/>
|
||||
</span>
|
||||
</template>
|
||||
@@ -1,53 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { SortingState } from '@tanstack/vue-table'
|
||||
import { computed } from 'vue'
|
||||
|
||||
import DataTable from '@/components/DataTable.vue'
|
||||
import { usageColumns } from '@/lib/usage-columns'
|
||||
import type { AdminUsageEntryView } from '@/types/api'
|
||||
|
||||
/**
|
||||
* UsageTable renders one scope kind's usage rows (users, or a group's
|
||||
* member users) as a sortable DataTable (shadcn-vue's DataTable pattern,
|
||||
* via the shared usageColumns() defs — vue.md: extract before you paste
|
||||
* it twice). The second column differs per kind: a user's row shows the
|
||||
* group it belongs to; a group's row shows its member count (looked up
|
||||
* from the Overview response, which is the only place member counts
|
||||
* live).
|
||||
*/
|
||||
const props = defineProps<{
|
||||
idLabel: string
|
||||
entries: AdminUsageEntryView[]
|
||||
secondaryColumnLabel: string
|
||||
secondaryValue: (entry: AdminUsageEntryView) => string
|
||||
/** Shown in the empty-state row when entries is empty — e.g. a filtered-search "no X match ..." message. Falls through to DataTable's own 'none' default when omitted. */
|
||||
emptyMessage?: string
|
||||
/** P1: the shared reactive clock (composables/useNow.ts) — threaded into usageColumns() below so this table's own costMonthProj column recomputes as the clock ticks, instead of freezing at whatever instant this computed first ran. */
|
||||
now: Date
|
||||
/** P6: optional controlled sort state, forwarded to DataTable's own `v-model:sorting` (see that component's identical prop doc comment) — omitted everywhere except ConsumerDirectory.vue's top-level Users table, whose export must reflect the table's current sort. */
|
||||
sorting?: SortingState
|
||||
/** Optional per-row source lookup ('inline'/'file'/undefined), forwarded to usage-columns.ts's usageColumns — see that module's sourceColumn doc comment. Omitted everywhere except ConsumerDirectory.vue's flat Users table. */
|
||||
sourceValue?: (entry: AdminUsageEntryView) => string | undefined
|
||||
/** Forwarded to DataTable: rows per page for large user lists. */
|
||||
pageSize?: number
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:sorting': [value: SortingState] }>()
|
||||
|
||||
const columns = computed(() =>
|
||||
usageColumns(props.idLabel, props.secondaryColumnLabel, props.secondaryValue, props.now, props.sourceValue),
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DataTable
|
||||
label="Usage"
|
||||
:page-size="pageSize"
|
||||
:columns="columns"
|
||||
:data="entries"
|
||||
:empty-message="emptyMessage"
|
||||
:row-class="(entry) => (entry.storeDown ? 'bg-destructive/10' : undefined)"
|
||||
:sorting="sorting"
|
||||
@update:sorting="(v) => emit('update:sorting', v)"
|
||||
/>
|
||||
</template>
|
||||
@@ -1,320 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
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 SkeletonTable from '@/components/SkeletonTable.vue'
|
||||
import StatDisabledAlert from '@/components/StatDisabledAlert.vue'
|
||||
import StatItem from '@/components/StatItem.vue'
|
||||
import TryLongerRangeButton from '@/components/TryLongerRangeButton.vue'
|
||||
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 { useNow } from '@/composables/useNow'
|
||||
import { runOutDate as computeRunOutDate } from '@/lib/burndown'
|
||||
import { formatBucketLabel, formatCostAxis, formatCostDisplay, formatLimits, formatShortDate, formatTimestamp } from '@/lib/format'
|
||||
import { loadState } from '@/lib/load-state'
|
||||
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'
|
||||
|
||||
/**
|
||||
* UserDetail (redesign-plan.md section 3.4) is the Consumers page's
|
||||
* `user=<name>` drill-down: a timeline of the user's own req/cost series,
|
||||
* their per-model breakdown (usermodel totals, when admin.stats.userModel
|
||||
* is on), recent errors filtered from the shared Events store, headroom
|
||||
* bars + an estimated run-out date, and their limits/grants.
|
||||
*/
|
||||
const props = defineProps<{ userId: string }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const dashboard = useDashboardStore()
|
||||
const consumers = useConsumersStore()
|
||||
const events = useEventsStore()
|
||||
const filters = useFiltersStore()
|
||||
const { now, start: startClock, stop: stopClock } = useNow()
|
||||
onMounted(startClock)
|
||||
onUnmounted(stopClock)
|
||||
|
||||
/** entry is this user's own row from the polled /admin/api/usage response — live counters, limits, lastSeen. undefined for a configured user who has never made a request (no usage scope created yet) or an id that does not exist at all. */
|
||||
const entry = computed(() => dashboard.usage?.users.find((u) => u.id === props.userId))
|
||||
|
||||
/** consumerUser is this user's own row from GET /admin/api/consumers — source, admin flag, personal grant. */
|
||||
const consumerUser = computed(() => consumers.data?.users.find((u) => u.name === props.userId))
|
||||
|
||||
const featuresUserModelStats = computed(() => dashboard.overview?.features.userModelStats ?? false)
|
||||
|
||||
/**
|
||||
* loadDetail (verify-ui-states-2.md #6 fix) returns fetchUserDetail's own
|
||||
* promise rather than `void`-ing it — ErrorState.onRetryClick (ErrorState.
|
||||
* vue) awaits `onRetry()` to drive its own local `retrying` spinner/disable
|
||||
* state; with this returning `void`, that await resolved immediately and
|
||||
* the Retry button showed no in-flight feedback at all.
|
||||
*/
|
||||
function loadDetail(): Promise<void> {
|
||||
return consumers.fetchUserDetail(props.userId, filters.window, filters.span, featuresUserModelStats.value)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadDetail()
|
||||
void events.refresh()
|
||||
void consumers.ensureConsumers()
|
||||
})
|
||||
// featuresUserModelStats is included alongside userId/range: on a deep
|
||||
// link or reload (#consumers?user=x), this component mounts and fires
|
||||
// loadDetail() BEFORE the polled overview (stores/dashboard.ts) has
|
||||
// necessarily landed its first response, so the very first loadDetail()
|
||||
// call can run with userModelStatsEnabled still false even though the
|
||||
// feature really is on. Once the overview lands and that computed flips
|
||||
// true, this watch refetches — otherwise "Models used" stayed
|
||||
// permanently empty for the rest of the session even after the alert
|
||||
// telling the reader to enable it disappeared (P2).
|
||||
watch([() => props.userId, () => filters.range, featuresUserModelStats], loadDetail)
|
||||
|
||||
const detail = computed(() => consumers.detail[props.userId])
|
||||
|
||||
// Labels are built from the RESPONSE's own `window` (AdminSeriesResponse),
|
||||
// not from the current filters.window directly — two fetchUserDetail
|
||||
// calls for different ranges can land out of order, and reading the
|
||||
// window off the live global filter would then mislabel a still-
|
||||
// displayed stale response's buckets (P1 item 7). Falls back to
|
||||
// filters.window only before any response has ever landed.
|
||||
const reqLabels = computed(() =>
|
||||
(detail.value?.reqSeries?.buckets ?? []).map((b) => formatBucketLabel(b, detail.value?.reqSeries?.window ?? filters.window)),
|
||||
)
|
||||
const reqDatasets = computed(() => [
|
||||
{ label: 'Requests', data: detail.value?.reqSeries?.series[0]?.points ?? [], color: '--chart-requests' },
|
||||
])
|
||||
const costLabels = computed(() =>
|
||||
(detail.value?.costSeries?.buckets ?? []).map((b) => formatBucketLabel(b, detail.value?.costSeries?.window ?? filters.window)),
|
||||
)
|
||||
const costDatasets = computed(() => [
|
||||
{ label: 'Cost', data: (detail.value?.costSeries?.series[0]?.points ?? []).map((v) => v), color: '--chart-cost' },
|
||||
])
|
||||
|
||||
/**
|
||||
* reqState/costState/modelState (verify-ui-states.md #4 fix) replace the
|
||||
* old bare `detail?.loading` skeleton check, which flipped a skeleton
|
||||
* back on over already-valid, already-rendered data in three cases:
|
||||
* (a) re-opening a cached user (consumers.detail[userId] keeps its
|
||||
* series, but loading flips true again on every fetchUserDetail call);
|
||||
* (b) the featuresUserModelStats watch's own follow-up refetch once the
|
||||
* overview lands; (c) a Retry click. `hasData` (reqSeries/costSeries/
|
||||
* modelRows non-null/non-empty) now takes precedence over `loading` —
|
||||
* lib/load-state.ts's own 'ready' precedence — so a background refetch
|
||||
* with data already on screen never shows a skeleton, and each chart/
|
||||
* table reads only its OWN error field (stores/consumers.ts's
|
||||
* UserDetailState split), so an unrelated section's failure never
|
||||
* blanks a perfectly valid one.
|
||||
*/
|
||||
const reqState = computed(() => loadState({ loading: detail.value?.loading ?? false, hasData: detail.value?.reqSeries != null, error: detail.value?.reqError ?? '' }))
|
||||
const costState = computed(() => loadState({ loading: detail.value?.loading ?? false, hasData: detail.value?.costSeries != null, error: detail.value?.costError ?? '' }))
|
||||
|
||||
/** showUserModelHint mirrors AttributionDrilldown.vue's own convention (Spend page): the hint shows when the client's own feature flag reads off, OR the usermodel call itself came back 404 (stores/consumers.ts's modelTotalsUnavailable) — the second case catches a stale/not-yet-loaded overview on a deep link or reload, where featuresUserModelStats can read true for a moment while the server still says otherwise. */
|
||||
const showUserModelHint = computed(() => (dashboard.overview !== null && !featuresUserModelStats.value) || detail.value?.modelTotalsUnavailable === true)
|
||||
|
||||
/** modelRows ranks usermodel totals by cost desc (falling back to req when cost is absent from the requested metrics) — a small, page-local sort since this table has no other consumer that would justify a shared column/sort helper. */
|
||||
const modelRows = computed(() => {
|
||||
const rows = detail.value?.modelTotals?.rows ?? []
|
||||
return [...rows].sort((a, b) => (b.values.cost ?? b.values.req ?? 0) - (a.values.cost ?? a.values.req ?? 0))
|
||||
})
|
||||
|
||||
/**
|
||||
* modelState mirrors reqState/costState above for the "Models used" table
|
||||
* — only reachable once showUserModelHint is false (the template checks
|
||||
* that Alert first), so 'error'/'skeleton' here are always a genuine fetch
|
||||
* problem, not the feature simply being off. `hasData` (verify-ui-states-2.
|
||||
* md #2 fix) is `detail.modelTotals != null`, not `modelRows.length > 0` —
|
||||
* a user with genuinely zero per-model rows used to flash a skeleton back
|
||||
* on over the "No traffic in this range." EmptyState on a re-open, a
|
||||
* Retry, or the featuresUserModelStats follow-up refetch (every one of
|
||||
* which flips `detail.loading` true again). The template's own
|
||||
* `!modelRows.length` check (below) still routes an empty result to
|
||||
* EmptyState.
|
||||
*/
|
||||
const modelState = computed(() => loadState({ loading: detail.value?.loading ?? false, hasData: detail.value?.modelTotals != null, error: detail.value?.modelError ?? '' }))
|
||||
|
||||
/** recentErrors filters the shared Events store (WP-F, read-only import) down to this user — the newest 10, matching the store's own newest-first order. */
|
||||
const recentErrors = computed(() => events.events.filter((e) => e.user === props.userId).slice(0, 10))
|
||||
const recentErrorsState = computed(() => loadState({ loading: events.refreshing, hasData: events.lastUpdated !== null, error: events.error }))
|
||||
|
||||
const ratios = computed(() => (entry.value ? budgetRatios(entry.value) : []))
|
||||
|
||||
/**
|
||||
* runOutDate reuses lib/burndown.ts's own runOutDate — the SAME function
|
||||
* BurnDownChart.vue projects the Spend page's burn-down line with — rather
|
||||
* than a second, disagreeing implementation (P2 item 14: the two used to
|
||||
* differ on an already-exceeded budget and on day 1 of the month).
|
||||
*/
|
||||
const runOutDate = computed(() => {
|
||||
const limitUsd = entry.value?.limits?.costPerMonthUSD
|
||||
if (!entry.value || !limitUsd) return null
|
||||
return computeRunOutDate(entry.value.costPerMonthMicroUsd, usdToMicros(limitUsd), now.value)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<Button type="button" variant="ghost" size="sm" @click="emit('close')">
|
||||
<FontAwesomeIcon :icon="faArrowLeft" class="size-3.5" aria-hidden="true" />
|
||||
Back to directory
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<CardTitle class="min-w-0 break-all font-mono">{{ userId }}</CardTitle>
|
||||
<Badge v-if="consumerUser?.admin" variant="destructive">admin</Badge>
|
||||
<Badge v-if="consumerUser?.source" variant="secondary">{{ consumerUser.source }}</Badge>
|
||||
</div>
|
||||
<CardDescription v-if="entry?.groups?.length || entry?.groupName">
|
||||
Member of {{ (entry?.groups ?? [entry?.groupName]).filter(Boolean).join(', ') }}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent v-if="!entry" class="text-sm text-muted-foreground">
|
||||
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">
|
||||
<StatItem label="Requests/day"><CompactNumber :value="entry.requestsPerDay" /></StatItem>
|
||||
<StatItem v-if="entry.exemptRequestsPerMonth" label="Exempt requests/month">
|
||||
<CompactNumber :value="entry.exemptRequestsPerMonth" />
|
||||
</StatItem>
|
||||
<StatItem label="Cost/day">{{ formatCostDisplay(entry.costPerDayMicroUsd) }}</StatItem>
|
||||
<StatItem label="Cost/month">{{ formatCostDisplay(entry.costPerMonthMicroUsd) }}</StatItem>
|
||||
<div>
|
||||
<p class="text-muted-foreground">Limits</p>
|
||||
<p class="text-sm">{{ formatLimits(entry.limits, entry.limitSources) }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card v-if="entry && ratios.length">
|
||||
<CardHeader>
|
||||
<CardTitle>Headroom</CardTitle>
|
||||
<CardDescription v-if="runOutDate">At the current pace, cost/month runs out around {{ formatShortDate(runOutDate) }}.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<BudgetRatioBars :ratios="ratios" />
|
||||
</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}`"
|
||||
/>
|
||||
|
||||
<ChartCard
|
||||
title="Cost over time"
|
||||
:state="costState"
|
||||
:error="detail?.costError ?? ''"
|
||||
:on-retry="loadDetail"
|
||||
:labels="costLabels"
|
||||
:datasets="costDatasets"
|
||||
:value-formatter="formatCostDisplay"
|
||||
:axis-formatter="formatCostAxis"
|
||||
:aria-label="`Cost over time for ${userId}`"
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Models used</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-3">
|
||||
<ClampedRangeNotice :window="filters.window" :span="filters.span" />
|
||||
<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.">
|
||||
<TryLongerRangeButton />
|
||||
</EmptyState>
|
||||
<Table v-else>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Model</TableHead>
|
||||
<TableHead class="text-right">Requests</TableHead>
|
||||
<TableHead class="text-right">Cost</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="row in modelRows" :key="row.id">
|
||||
<TableCell><ModelChip :id="row.id" /></TableCell>
|
||||
<TableCell class="text-right tabular-nums"><CompactNumber :value="row.values.req ?? 0" /></TableCell>
|
||||
<TableCell class="text-right tabular-nums">{{ formatCostDisplay(row.values.cost ?? 0) }}</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Recent errors</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<SkeletonTable v-if="recentErrorsState === 'skeleton'" :rows="2" :cols="2" />
|
||||
<ErrorState v-else-if="recentErrorsState === 'error'" :message="events.error" :on-retry="events.refresh" />
|
||||
<ul v-else-if="recentErrors.length" class="flex flex-col gap-2 text-sm">
|
||||
<li v-for="(event, index) in recentErrors" :key="index" class="border-b pb-2 last:border-0 last:pb-0">
|
||||
<p class="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="secondary">{{ event.kind }}</Badge>
|
||||
<span class="text-muted-foreground">{{ formatTimestamp(event.time) }}</span>
|
||||
</p>
|
||||
<p class="break-words text-muted-foreground">{{ event.message }}</p>
|
||||
</li>
|
||||
</ul>
|
||||
<EmptyState v-else title="No recent errors in the current event window." />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card v-if="consumerUser?.providers?.length || consumerUser?.models?.length">
|
||||
<CardHeader>
|
||||
<CardTitle>Personal grant</CardTitle>
|
||||
<CardDescription>Access this user has beyond their group's own.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<p class="mb-1.5 text-xs text-muted-foreground">Providers</p>
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<Badge
|
||||
v-for="name in consumerUser?.providers ?? []"
|
||||
:key="name"
|
||||
as="span"
|
||||
variant="secondary"
|
||||
class="max-w-full truncate font-mono font-normal"
|
||||
:title="name"
|
||||
>
|
||||
{{ name }}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<p class="mb-1.5 text-xs text-muted-foreground">Models</p>
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<ModelChip v-for="id in consumerUser?.models ?? []" :key="id" :id="id" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,27 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccordionRootEmits, AccordionRootProps } from 'reka-ui'
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import {
|
||||
AccordionRoot,
|
||||
useForwardPropsEmits,
|
||||
} from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<AccordionRootProps & { class?: HTMLAttributes['class'] }>()
|
||||
const emits = defineEmits<AccordionRootEmits>()
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class')
|
||||
const forwarded = useForwardPropsEmits(delegatedProps, emits)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AccordionRoot
|
||||
v-slot="slotProps"
|
||||
data-slot="accordion"
|
||||
v-bind="forwarded"
|
||||
:class="cn('flex w-full flex-col', props.class)"
|
||||
>
|
||||
<slot v-bind="slotProps" />
|
||||
</AccordionRoot>
|
||||
</template>
|
||||
@@ -1,28 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccordionContentProps } from 'reka-ui'
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import { AccordionContent } from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<AccordionContentProps & { class?: HTMLAttributes['class'] }>()
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AccordionContent
|
||||
data-slot="accordion-content"
|
||||
v-bind="delegatedProps"
|
||||
class="data-open:animate-accordion-down data-closed:animate-accordion-up text-sm overflow-hidden"
|
||||
>
|
||||
<div
|
||||
:class="cn(
|
||||
'pt-0 pb-2.5 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4',
|
||||
props.class,
|
||||
)"
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</template>
|
||||
@@ -1,24 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccordionItemProps } from 'reka-ui'
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import { AccordionItem, useForwardProps } from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<AccordionItemProps & { class?: HTMLAttributes['class'] }>()
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class')
|
||||
|
||||
const forwardedProps = useForwardProps(delegatedProps)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AccordionItem
|
||||
v-slot="slotProps"
|
||||
data-slot="accordion-item"
|
||||
v-bind="forwardedProps"
|
||||
:class="cn('not-last:border-b', props.class)"
|
||||
>
|
||||
<slot v-bind="slotProps" />
|
||||
</AccordionItem>
|
||||
</template>
|
||||
@@ -1,59 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccordionTriggerProps } from 'reka-ui'
|
||||
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { faChevronDown, faChevronUp } from '@fortawesome/free-solid-svg-icons'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import {
|
||||
AccordionHeader,
|
||||
AccordionTrigger,
|
||||
} from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<AccordionTriggerProps & {
|
||||
class?: HTMLAttributes['class']
|
||||
/**
|
||||
* Class applied to the AccordionHeader (the <h3> wrapper), not the
|
||||
* trigger button. Reka-ui's AccordionTrigger declares its own `class`
|
||||
* prop, so a `class` passed to this component lands on the inner
|
||||
* button, never on the header — pass `flex-1` here (not to `class`)
|
||||
* when the trigger sits next to a sibling in a flex row, so the header
|
||||
* (and the button it wraps) fills the remaining row width instead of
|
||||
* shrinking to content width.
|
||||
*/
|
||||
headerClass?: HTMLAttributes['class']
|
||||
}>()
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class', 'headerClass')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AccordionHeader :class="cn('flex', props.headerClass)">
|
||||
<AccordionTrigger
|
||||
data-slot="accordion-trigger"
|
||||
v-bind="delegatedProps"
|
||||
:class="
|
||||
cn(
|
||||
'focus-visible:ring-ring/50 focus-visible:border-ring focus-visible:after:border-ring **:data-[slot=accordion-trigger-icon]:text-muted-foreground rounded-lg py-2.5 text-left text-sm font-medium hover:underline focus-visible:ring-3 **:data-[slot=accordion-trigger-icon]:ml-auto **:data-[slot=accordion-trigger-icon]:size-4 group/accordion-trigger relative flex flex-1 items-start justify-between border border-transparent transition-all outline-none disabled:pointer-events-none disabled:opacity-50',
|
||||
props.class,
|
||||
)
|
||||
"
|
||||
>
|
||||
<slot />
|
||||
<slot name="icon">
|
||||
<FontAwesomeIcon
|
||||
:icon="faChevronDown"
|
||||
data-slot="accordion-trigger-icon"
|
||||
aria-hidden="true"
|
||||
class="pointer-events-none shrink-0 group-aria-expanded/accordion-trigger:hidden"
|
||||
/>
|
||||
<FontAwesomeIcon
|
||||
:icon="faChevronUp"
|
||||
data-slot="accordion-trigger-icon"
|
||||
aria-hidden="true"
|
||||
class="pointer-events-none hidden shrink-0 group-aria-expanded/accordion-trigger:inline"
|
||||
/>
|
||||
</slot>
|
||||
</AccordionTrigger>
|
||||
</AccordionHeader>
|
||||
</template>
|
||||
@@ -1,4 +0,0 @@
|
||||
export { default as Accordion } from './Accordion.vue'
|
||||
export { default as AccordionContent } from './AccordionContent.vue'
|
||||
export { default as AccordionItem } from './AccordionItem.vue'
|
||||
export { default as AccordionTrigger } from './AccordionTrigger.vue'
|
||||
@@ -3,7 +3,7 @@ import type { SelectItemProps } from 'reka-ui'
|
||||
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { faCheck } from '@fortawesome/free-solid-svg-icons'
|
||||
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
|
||||
import FontAwesomeIcon from '@/components/FaIcon.vue'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import {
|
||||
SelectItem,
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { SelectScrollDownButtonProps } from 'reka-ui'
|
||||
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { faChevronDown } from '@fortawesome/free-solid-svg-icons'
|
||||
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
|
||||
import FontAwesomeIcon from '@/components/FaIcon.vue'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import { SelectScrollDownButton, useForwardProps } from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { SelectScrollUpButtonProps } from 'reka-ui'
|
||||
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { faChevronUp } from '@fortawesome/free-solid-svg-icons'
|
||||
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
|
||||
import FontAwesomeIcon from '@/components/FaIcon.vue'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import { SelectScrollUpButton, useForwardProps } from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { SelectTriggerProps } from 'reka-ui'
|
||||
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { faChevronDown } from '@fortawesome/free-solid-svg-icons'
|
||||
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
|
||||
import FontAwesomeIcon from '@/components/FaIcon.vue'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import { SelectIcon, SelectTrigger, useForwardProps } from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/**
|
||||
* Skeleton is shadcn-vue's own loading-placeholder primitive
|
||||
* (shadcn-vue.com/docs/components/skeleton): a plain pulsing block, sized
|
||||
* by whatever `class` the caller passes (e.g. `h-4 w-24`). Every composed
|
||||
* skeleton in this panel (SkeletonKpiTile, SkeletonTable, SkeletonChart,
|
||||
* SkeletonList) is built from one or more of these, each sized to match
|
||||
* the final layout's own dimensions so data arriving causes no layout
|
||||
* shift (states-plan.md item 1). `motion-reduce:animate-none` honors
|
||||
* prefers-reduced-motion instead of pulsing regardless.
|
||||
*/
|
||||
const props = defineProps<{ class?: HTMLAttributes['class'] }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div data-slot="skeleton" :class="cn('animate-pulse rounded-md bg-muted motion-reduce:animate-none', props.class)" />
|
||||
</template>
|
||||
@@ -1 +0,0 @@
|
||||
export { default as Skeleton } from './Skeleton.vue'
|
||||
@@ -1,18 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
defineOptions({ inheritAttrs: false })
|
||||
|
||||
const props = defineProps<{
|
||||
class?: HTMLAttributes['class']
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div data-slot="table-container" class="scroll-shadow-x relative w-full overflow-x-auto">
|
||||
<table data-slot="table" v-bind="$attrs" :class="cn('w-full caption-bottom text-sm', props.class)">
|
||||
<slot />
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,17 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<{
|
||||
class?: HTMLAttributes['class']
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
:class="cn('[&_tr:last-child]:border-0', props.class)"
|
||||
>
|
||||
<slot />
|
||||
</tbody>
|
||||
</template>
|
||||
@@ -1,17 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<{
|
||||
class?: HTMLAttributes['class']
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
:class="cn('p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0', props.class)"
|
||||
>
|
||||
<slot />
|
||||
</td>
|
||||
</template>
|
||||
@@ -1,34 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import { cn } from '@/lib/utils'
|
||||
import TableCell from './TableCell.vue'
|
||||
import TableRow from './TableRow.vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
class?: HTMLAttributes['class']
|
||||
colspan?: number
|
||||
}>(), {
|
||||
colspan: 1,
|
||||
})
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TableRow>
|
||||
<TableCell
|
||||
:class="
|
||||
cn(
|
||||
'p-4 whitespace-nowrap align-middle text-sm text-foreground',
|
||||
props.class,
|
||||
)
|
||||
"
|
||||
v-bind="delegatedProps"
|
||||
>
|
||||
<div class="flex items-center justify-center py-10">
|
||||
<slot />
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</template>
|
||||
@@ -1,17 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<{
|
||||
class?: HTMLAttributes['class']
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<th
|
||||
data-slot="table-head"
|
||||
:class="cn('text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0', props.class)"
|
||||
>
|
||||
<slot />
|
||||
</th>
|
||||
</template>
|
||||
@@ -1,17 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<{
|
||||
class?: HTMLAttributes['class']
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<thead
|
||||
data-slot="table-header"
|
||||
:class="cn('[&_tr]:border-b', props.class)"
|
||||
>
|
||||
<slot />
|
||||
</thead>
|
||||
</template>
|
||||
@@ -1,17 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<{
|
||||
class?: HTMLAttributes['class']
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
:class="cn('hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors has-aria-expanded:bg-muted/50', props.class)"
|
||||
>
|
||||
<slot />
|
||||
</tr>
|
||||
</template>
|
||||
@@ -1,8 +0,0 @@
|
||||
export { default as Table } from './Table.vue'
|
||||
export { default as TableBody } from './TableBody.vue'
|
||||
export { default as TableCell } from './TableCell.vue'
|
||||
export { default as TableEmpty } from './TableEmpty.vue'
|
||||
export { default as TableHead } from './TableHead.vue'
|
||||
export { default as TableHeader } from './TableHeader.vue'
|
||||
export { default as TableRow } from './TableRow.vue'
|
||||
export { valueUpdater } from './utils'
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { RowData, Updater } from '@tanstack/vue-table'
|
||||
import type { Ref } from 'vue'
|
||||
|
||||
/**
|
||||
* valueUpdater applies one TanStack Table `Updater<T>` — either a new
|
||||
* value, or a function from the old value to the new one — to a plain Vue
|
||||
* ref. This is the standard shadcn-vue glue between TanStack Table's
|
||||
* callback-based state updates (`onSortingChange`, etc.) and Vue's
|
||||
* ref-based reactivity (shadcn-vue docs: /docs/components/data-table).
|
||||
*/
|
||||
export function valueUpdater<T>(updaterOrValue: Updater<T>, ref: Ref<T>): void {
|
||||
ref.value = typeof updaterOrValue === 'function' ? (updaterOrValue as (old: T) => T)(ref.value) : updaterOrValue
|
||||
}
|
||||
|
||||
declare module '@tanstack/vue-table' {
|
||||
interface ColumnMeta<TData extends RowData, TValue> {
|
||||
/** Right-align this column's header button and cell content, with tabular-nums — set on numeric columns (DataTable.vue reads this). */
|
||||
align?: 'right'
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { TabsRootEmits, TabsRootProps } from 'reka-ui'
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import { TabsRoot, useForwardPropsEmits } from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<TabsRootProps & { class?: HTMLAttributes['class'] }>()
|
||||
const emits = defineEmits<TabsRootEmits>()
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class')
|
||||
const forwarded = useForwardPropsEmits(delegatedProps, emits)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TabsRoot
|
||||
v-slot="slotProps"
|
||||
data-slot="tabs"
|
||||
:data-orientation="forwarded.orientation || 'horizontal'"
|
||||
v-bind="forwarded"
|
||||
:class="cn('gap-2 group/tabs flex data-horizontal:flex-col', props.class)"
|
||||
>
|
||||
<slot v-bind="slotProps" />
|
||||
</TabsRoot>
|
||||
</template>
|
||||
@@ -1,21 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { TabsContentProps } from 'reka-ui'
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import { TabsContent } from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<TabsContentProps & { class?: HTMLAttributes['class'] }>()
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TabsContent
|
||||
data-slot="tabs-content"
|
||||
:class="cn('text-sm flex-1 outline-none', props.class)"
|
||||
v-bind="delegatedProps"
|
||||
>
|
||||
<slot />
|
||||
</TabsContent>
|
||||
</template>
|
||||
@@ -1,29 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { TabsListProps } from 'reka-ui'
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import type { TabsListVariants } from '.'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import { TabsList } from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { tabsListVariants } from '.'
|
||||
|
||||
const props = withDefaults(defineProps<TabsListProps & {
|
||||
class?: HTMLAttributes['class']
|
||||
variant?: TabsListVariants['variant']
|
||||
}>(), {
|
||||
variant: 'default',
|
||||
})
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class', 'variant')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TabsList
|
||||
data-slot="tabs-list"
|
||||
:data-variant="variant"
|
||||
v-bind="delegatedProps"
|
||||
:class="cn(tabsListVariants({ variant }), props.class)"
|
||||
>
|
||||
<slot />
|
||||
</TabsList>
|
||||
</template>
|
||||
@@ -1,38 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { TabsTriggerProps } from 'reka-ui'
|
||||
import type { HTMLAttributes } from 'vue'
|
||||
import { reactiveOmit } from '@vueuse/core'
|
||||
import { TabsTrigger, useForwardProps } from 'reka-ui'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const props = defineProps<TabsTriggerProps & { class?: HTMLAttributes['class'] }>()
|
||||
|
||||
const delegatedProps = reactiveOmit(props, 'class')
|
||||
|
||||
const forwardedProps = useForwardProps(delegatedProps)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TabsTrigger
|
||||
data-slot="tabs-trigger"
|
||||
:class="cn(
|
||||
// group-data-horizontal/tabs:shrink-0/flex-none: every trigger keeps
|
||||
// its natural (content) width in a horizontal strip instead of
|
||||
// flex-1-shrinking to fit — TabsList (index.ts) is the thing that
|
||||
// scrolls, not the individual triggers squeezing into an unreadable
|
||||
// sliver. Vertical orientation is unaffected (still
|
||||
// group-data-vertical/tabs:w-full below).
|
||||
// group-data-horizontal/tabs:flex-none alone covers both
|
||||
// flex-grow:0 and flex-shrink:0 (P3 lows fix, verify-ui-states.md
|
||||
// #11) — the separate `shrink-0` utility next to it was redundant.
|
||||
'gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg:not([class*=size-])]:size-4 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center whitespace-nowrap text-foreground/60 transition-all group-data-horizontal/tabs:flex-none group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0',
|
||||
'group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent',
|
||||
'data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground',
|
||||
'after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100',
|
||||
props.class,
|
||||
)"
|
||||
v-bind="forwardedProps"
|
||||
>
|
||||
<slot />
|
||||
</TabsTrigger>
|
||||
</template>
|
||||
@@ -1,51 +0,0 @@
|
||||
import type { VariantProps } from 'class-variance-authority'
|
||||
import { cva } from 'class-variance-authority'
|
||||
|
||||
export { default as Tabs } from './Tabs.vue'
|
||||
export { default as TabsContent } from './TabsContent.vue'
|
||||
export { default as TabsList } from './TabsList.vue'
|
||||
export { default as TabsTrigger } from './TabsTrigger.vue'
|
||||
|
||||
export const tabsListVariants = cva(
|
||||
// Horizontal orientation (the only one this app actually uses, in every
|
||||
// tab strip switching between pages/kinds/forms) is capped to the
|
||||
// available width and made horizontally scrollable instead of letting
|
||||
// `w-fit` push it wider than its container — every Card (ui/card)
|
||||
// clips overflow with `overflow-hidden` by design (rounded corners), so
|
||||
// an uncapped TabsList wider than its Card doesn't spill onto the page
|
||||
// (confirmed via live audit: zero page-level scrollWidth overflow
|
||||
// anywhere) — it just gets silently CLIPPED with no scrollbar and no
|
||||
// way to reach the hidden triggers. That silent clipping, not page
|
||||
// overflow, is what broke "switching tabs on mobile" (measured live:
|
||||
// the 5-trigger Config change-helper strip loses its last ~1.5 triggers
|
||||
// under its Card at 360-390px). `justify-start` overrides the default
|
||||
// centering only for this case: centering an overflowing flex row can
|
||||
// otherwise leave its first item unreachable by scroll in some browsers
|
||||
// (the well-known justify-content/overflow interaction) — reka-ui's own
|
||||
// roving-tabindex keyboard handling on TabsTrigger is untouched by any
|
||||
// of this, so arrow-key/Home/End navigation still works.
|
||||
//
|
||||
// `overflow-x-auto` alone (verify-ui-states.md #2) makes the computed
|
||||
// `overflow-y` resolve to `auto` too (the CSS `overflow` shorthand
|
||||
// behavior when only one axis is set explicitly) — combined with
|
||||
// TabsTrigger's own active-indicator pseudo-element extending 5px below
|
||||
// the 32px-tall list (`after:bottom-[-5px]`), that produced a real,
|
||||
// always-visible vertical scrollbar on every TabsList on any platform
|
||||
// that shows classic (non-overlay) scrollbars. `overflow-y-hidden`
|
||||
// clips that harmless 5px indicator overflow without touching the
|
||||
// horizontal scroll this rule exists for.
|
||||
'rounded-lg p-0.75 group-data-horizontal/tabs:h-8 group-data-horizontal/tabs:max-w-full group-data-horizontal/tabs:justify-start group-data-horizontal/tabs:overflow-x-auto group-data-horizontal/tabs:overflow-y-hidden data-[variant=line]:rounded-none group/tabs-list inline-flex w-fit items-center justify-center text-muted-foreground group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-muted',
|
||||
line: 'gap-1 bg-transparent',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
export type TabsListVariants = VariantProps<typeof tabsListVariants>
|
||||
@@ -1,69 +0,0 @@
|
||||
import { ref } from 'vue'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { useSearchQuery } from './useSearchQuery'
|
||||
|
||||
describe('useSearchQuery', () => {
|
||||
it('normalized trims leading/trailing whitespace', () => {
|
||||
const { query, normalized } = useSearchQuery()
|
||||
query.value = ' alice '
|
||||
expect(normalized.value).toBe('alice')
|
||||
})
|
||||
|
||||
it('normalized lowercases the query', () => {
|
||||
const { query, normalized } = useSearchQuery()
|
||||
query.value = 'AlIcE'
|
||||
expect(normalized.value).toBe('alice')
|
||||
})
|
||||
|
||||
it('hasQuery is false for a whitespace-only query', () => {
|
||||
const { query, hasQuery } = useSearchQuery()
|
||||
query.value = ' '
|
||||
expect(hasQuery.value).toBe(false)
|
||||
})
|
||||
|
||||
// F9 (hash-state): a caller can supply the ref this composable reads and
|
||||
// writes instead of a private local one, so the query round-trips
|
||||
// through an external owner (e.g. ConsumerDirectory.vue's own
|
||||
// `nav.params.q`-backed computed, or EventsView.vue's store-backed
|
||||
// `userFilter` — useSearchQuery.ts's own doc comment) rather than being
|
||||
// lost on remount.
|
||||
describe('with an external ref', () => {
|
||||
it('reads and derives from the external ref\'s current value, rather than starting blank', () => {
|
||||
const external = ref('preset')
|
||||
const { query, normalized, hasQuery } = useSearchQuery(external)
|
||||
|
||||
expect(query.value).toBe('preset')
|
||||
expect(normalized.value).toBe('preset')
|
||||
expect(hasQuery.value).toBe(true)
|
||||
})
|
||||
|
||||
it('writes THROUGH to the external ref — the same ref instance, not a copy', () => {
|
||||
const external = ref('')
|
||||
const { query } = useSearchQuery(external)
|
||||
|
||||
query.value = 'typed'
|
||||
|
||||
expect(external.value).toBe('typed')
|
||||
})
|
||||
|
||||
it('reflects a change made directly to the external ref (bidirectional, not a one-time snapshot)', () => {
|
||||
const external = ref('')
|
||||
const { query, normalized } = useSearchQuery(external)
|
||||
|
||||
external.value = 'set-elsewhere'
|
||||
|
||||
expect(query.value).toBe('set-elsewhere')
|
||||
expect(normalized.value).toBe('set-elsewhere')
|
||||
})
|
||||
|
||||
it('without an external ref, two calls own independent state (no accidental sharing)', () => {
|
||||
const a = useSearchQuery()
|
||||
const b = useSearchQuery()
|
||||
|
||||
a.query.value = 'alice'
|
||||
|
||||
expect(b.query.value).toBe('')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,43 +0,0 @@
|
||||
import type { Ref } from 'vue'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
/**
|
||||
* useSearchQuery is the one raw-query → {normalized, hasQuery} adapter
|
||||
* every search filter in this panel uses — ProviderHealthPanel's
|
||||
* model/provider search, ConsumerDirectory's user/group search
|
||||
* (lib/usage-search.ts), EventsView's user/group filter, TargetsView's
|
||||
* target search, each with its own matching logic but the identical
|
||||
* query/normalizedQuery/hasQuery pairing; extracted so it exists once
|
||||
* (vue.md: "if you've written it twice, you owe an abstraction"). Callers
|
||||
* still own their own matching logic entirely — this only normalizes the
|
||||
* raw input the same way every call site already agreed on: trimmed,
|
||||
* lowercased.
|
||||
*
|
||||
* No `clear()` here — clearing is just setting `query.value = ''`, and
|
||||
* every caller already gets that for free from SearchInput.vue's own
|
||||
* clear button emitting `update:modelValue('')` through the `v-model`
|
||||
* binding, so a separate clear function would be dead API surface no
|
||||
* caller needs.
|
||||
*
|
||||
* `external` (F9, hash-state) lets a caller supply the ref this composable
|
||||
* reads and writes instead of owning a private local one, so that ref's
|
||||
* own search text round-trips through the URL hash. Two current callers
|
||||
* pass it: ConsumerDirectory.vue binds a local `computed` get/set over
|
||||
* `nav.params.q` directly (stores/nav.ts's own `params` is opaque, so the
|
||||
* page owns interpreting/writing its own `q` key — see that computed's
|
||||
* own doc comment for why this replaced an earlier, page-specific
|
||||
* `nav.usageQuery` special case), and EventsView.vue binds
|
||||
* `storeToRefs(events).userFilter`, which composables/useHashState.ts
|
||||
* reads/writes directly against the same hash. Every OTHER caller
|
||||
* (ProviderHealthPanel's model/provider search, TargetsView's target
|
||||
* search) omits it and keeps its private, hash-independent ref instead —
|
||||
* passing `external` changes nothing about `normalized`/`hasQuery`'s own
|
||||
* derivation, only where the raw value itself lives.
|
||||
*/
|
||||
export function useSearchQuery(external?: Ref<string>) {
|
||||
const query = external ?? ref('')
|
||||
const normalized = computed(() => query.value.trim().toLowerCase())
|
||||
const hasQuery = computed(() => normalized.value.length > 0)
|
||||
|
||||
return { query, normalized, hasQuery }
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
|
||||
/**
|
||||
* useThemeColors exposes the current computed values of the design
|
||||
* tokens Chart.js needs to draw axis/grid/legend text (main.css) — Chart.js
|
||||
* paints to a <canvas>, so it cannot pick up CSS variables the way a DOM
|
||||
* element does; the caller must read them and hand them to Chart.js as
|
||||
* plain color strings. Every color literal in main.css is oklch()/hex,
|
||||
* both valid canvas fillStyle values in current evergreen browsers (the
|
||||
* only ones this admin panel targets — see vite.config.ts's
|
||||
* modulePreload note for the same reasoning), so no conversion is needed.
|
||||
*
|
||||
* Re-reads when the `class` of <html> changes (perfect-design's theme
|
||||
* store toggles `.dark` there, including on an OS flip in "system" mode),
|
||||
* so an open chart repaints on a theme switch.
|
||||
*/
|
||||
export function useThemeColors() {
|
||||
const foreground = ref('')
|
||||
const mutedForeground = ref('')
|
||||
const border = ref('')
|
||||
|
||||
function sync(): void {
|
||||
const style = getComputedStyle(document.documentElement)
|
||||
foreground.value = style.getPropertyValue('--foreground').trim()
|
||||
mutedForeground.value = style.getPropertyValue('--muted-foreground').trim()
|
||||
border.value = style.getPropertyValue('--border').trim()
|
||||
}
|
||||
|
||||
let observer: MutationObserver | undefined
|
||||
onMounted(() => {
|
||||
sync()
|
||||
observer = new MutationObserver(sync)
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] })
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
observer?.disconnect()
|
||||
})
|
||||
|
||||
return { foreground, mutedForeground, border }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { hasDist, LIMIT, totalGzip } from '../../scripts/bundle-size.mjs'
|
||||
|
||||
// Needs a prior `npm run build`; skipped when dist/ is absent.
|
||||
describe.skipIf(!hasDist())('bundle gate', () => {
|
||||
it('keeps gzip JS+CSS within the size limit', () => {
|
||||
expect(totalGzip()).toBeLessThanOrEqual(LIMIT)
|
||||
})
|
||||
})
|
||||
@@ -1,27 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { BREAKDOWN_PALETTE, CHART_SERIES_COLORS, seriesColor } from './chart-palette'
|
||||
|
||||
describe('BREAKDOWN_PALETTE', () => {
|
||||
it('starts with the same four colors as CHART_SERIES_COLORS, in the same order', () => {
|
||||
expect(BREAKDOWN_PALETTE.slice(0, 4)).toEqual(CHART_SERIES_COLORS)
|
||||
})
|
||||
|
||||
it('has 8 entries total', () => {
|
||||
expect(BREAKDOWN_PALETTE).toHaveLength(8)
|
||||
})
|
||||
})
|
||||
|
||||
describe('seriesColor', () => {
|
||||
it('cycles through the default palette (CHART_SERIES_COLORS) by index', () => {
|
||||
expect(seriesColor(0)).toBe(CHART_SERIES_COLORS[0])
|
||||
expect(seriesColor(CHART_SERIES_COLORS.length)).toBe(CHART_SERIES_COLORS[0])
|
||||
expect(seriesColor(CHART_SERIES_COLORS.length + 1)).toBe(CHART_SERIES_COLORS[1])
|
||||
})
|
||||
|
||||
it('cycles through an explicitly passed palette (e.g. BREAKDOWN_PALETTE) instead', () => {
|
||||
expect(seriesColor(0, BREAKDOWN_PALETTE)).toBe(BREAKDOWN_PALETTE[0])
|
||||
expect(seriesColor(7, BREAKDOWN_PALETTE)).toBe(BREAKDOWN_PALETTE[7])
|
||||
expect(seriesColor(8, BREAKDOWN_PALETTE)).toBe(BREAKDOWN_PALETTE[0])
|
||||
})
|
||||
})
|
||||
@@ -1,49 +0,0 @@
|
||||
// reuse-audit.md F13: the ONE chart colour palette module. Two call sites
|
||||
// used to each own a palette + its own cycling function — stores/
|
||||
// reliability.ts's RELIABILITY_SERIES_COLORS (a UI concern that had drifted
|
||||
// into a Pinia store) and pages/SpendPage.vue's BREAKDOWN_PALETTE (the
|
||||
// identical first four colours, plus four more) — this module is their one
|
||||
// shared home.
|
||||
|
||||
/**
|
||||
* CHART_SERIES_COLORS cycles through main.css's four existing --chart-*
|
||||
* tokens (assets/main.css is owned by WP-E — this module does not add a
|
||||
* fifth) — used to colour the Reliability page's per-provider error-rate/
|
||||
* timeout/failover overlay charts. With more than four configured
|
||||
* providers, colors repeat — a known, documented limitation rather than a
|
||||
* silent one.
|
||||
*/
|
||||
export const CHART_SERIES_COLORS = ['--chart-requests', '--chart-tokens-in', '--chart-tokens-out', '--chart-cost'] as const
|
||||
|
||||
/**
|
||||
* BREAKDOWN_PALETTE cycles a colorblind-safe (Okabe & Ito, 2008) 8-color
|
||||
* qualitative set across the Spend page's breakdown chart's per-model/
|
||||
* provider/group series. The first four reuse CHART_SERIES_COLORS (already
|
||||
* that same palette's requests/tokens-in/tokens-out/cost members); the
|
||||
* remaining four (--chart-series-a..d) extend it, defined alongside them in
|
||||
* assets/main.css — main.css's original four tokens were sized for four
|
||||
* FIXED semantic metrics, not an open-ended breakdown series count, so this
|
||||
* page needed four more, but every chart color token lives in the one
|
||||
* design-tokens file (Tailwind-only rule), never a component-local <style>
|
||||
* block. Beyond 8 series (e.g. a fleet with more than 8 configured groups)
|
||||
* colors repeat — an accepted qualitative-palette limit, not a bug: legend
|
||||
* labels remain the disambiguator past that point, the same tradeoff any
|
||||
* categorical chart palette makes once it runs out of distinguishable hues.
|
||||
*/
|
||||
export const BREAKDOWN_PALETTE = [
|
||||
...CHART_SERIES_COLORS,
|
||||
'--chart-series-a',
|
||||
'--chart-series-b',
|
||||
'--chart-series-c',
|
||||
'--chart-series-d',
|
||||
] as const
|
||||
|
||||
/**
|
||||
* seriesColor picks one entry from `palette` by index, cycling — defaults
|
||||
* to CHART_SERIES_COLORS (the Reliability page's 4-color set); pass
|
||||
* BREAKDOWN_PALETTE for the Spend page's 8-color breakdown chart, or any
|
||||
* other palette a future chart needs.
|
||||
*/
|
||||
export function seriesColor(index: number, palette: readonly string[] = CHART_SERIES_COLORS): string {
|
||||
return palette[index % palette.length]!
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { CategoryScale, Chart, Filler, Legend, LinearScale, LineController, LineElement, PointElement, Tooltip } from 'chart.js'
|
||||
|
||||
// Registered once at module load (ES module caching makes this a true
|
||||
// singleton regardless of how many components import it) — only the
|
||||
// chart pieces this panel actually uses, not chart.js's full
|
||||
// auto-registry, to keep the baked-in bundle lean. TimeSeriesChart.vue
|
||||
// (redesign-plan.md section 3.4) is the only chart component in this
|
||||
// panel, and it only ever imports `Line` from vue-chartjs (never `Bar`) —
|
||||
// so this registers exactly Line's own pieces, plus `Filler`:
|
||||
// TimeSeriesChart.vue sets `fill: props.stacked` on every stacked
|
||||
// dataset, and without Filler registered chart.js silently ignores that
|
||||
// option — a stacked area chart drew UNFILLED lines at cumulative
|
||||
// heights, so a reader saw the top line at the height of the whole total
|
||||
// rather than its own value (P2). A `BarController`/`BarElement`
|
||||
// registration used to sit here too; it was dead — grep confirms no
|
||||
// component imports vue-chartjs's `Bar`.
|
||||
Chart.register(CategoryScale, LinearScale, Legend, Tooltip, LineController, LineElement, PointElement, Filler)
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { compactColumn, costColumn, EMPTY_CELL, optionalColumn, usageMetricColumns } from './columns'
|
||||
|
||||
interface Row {
|
||||
requests: number
|
||||
tokensIn: number
|
||||
tokensOut: number
|
||||
costMicroUsd: number
|
||||
latencyMs?: number
|
||||
}
|
||||
|
||||
describe('EMPTY_CELL', () => {
|
||||
it('is the em dash', () => {
|
||||
expect(EMPTY_CELL).toBe('—')
|
||||
})
|
||||
})
|
||||
|
||||
describe('compactColumn', () => {
|
||||
it('carries the given id/header and right-aligns', () => {
|
||||
const col = compactColumn<Row>('requests', 'Requests', (r) => r.requests)
|
||||
expect(col.id).toBe('requests')
|
||||
expect(col.header).toBe('Requests')
|
||||
expect(col.meta).toEqual({ align: 'right' })
|
||||
})
|
||||
|
||||
it('accessorFn reads the given field via the read function', () => {
|
||||
const col = compactColumn<Row>('requests', 'Requests', (r) => r.requests) as unknown as { accessorFn: (r: Row) => number }
|
||||
expect(col.accessorFn({ requests: 42, tokensIn: 0, tokensOut: 0, costMicroUsd: 0 })).toBe(42)
|
||||
})
|
||||
})
|
||||
|
||||
describe('costColumn', () => {
|
||||
it('accessorFn reads the given field, unformatted', () => {
|
||||
const col = costColumn<Row>('cost', 'Cost', (r) => r.costMicroUsd) as unknown as { accessorFn: (r: Row) => number }
|
||||
expect(col.accessorFn({ requests: 0, tokensIn: 0, tokensOut: 0, costMicroUsd: 1_500_000 })).toBe(1_500_000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('optionalColumn', () => {
|
||||
it('accessorFn falls back to the default sentinel (0) for an undefined value', () => {
|
||||
const col = optionalColumn<Row>('latency', 'Latency', (r) => r.latencyMs, String) as unknown as { accessorFn: (r: Row) => number }
|
||||
expect(col.accessorFn({ requests: 0, tokensIn: 0, tokensOut: 0, costMicroUsd: 0 })).toBe(0)
|
||||
})
|
||||
|
||||
it('accessorFn falls back to a caller-supplied sortSentinel for an undefined value', () => {
|
||||
const col = optionalColumn<Row>('latency', 'Latency', (r) => r.latencyMs, String, { sortSentinel: -1 }) as unknown as {
|
||||
accessorFn: (r: Row) => number
|
||||
}
|
||||
expect(col.accessorFn({ requests: 0, tokensIn: 0, tokensOut: 0, costMicroUsd: 0 })).toBe(-1)
|
||||
})
|
||||
|
||||
it('accessorFn reads the real value when defined, ignoring the sentinel', () => {
|
||||
const col = optionalColumn<Row>('latency', 'Latency', (r) => r.latencyMs, String, { sortSentinel: -1 }) as unknown as {
|
||||
accessorFn: (r: Row) => number
|
||||
}
|
||||
expect(col.accessorFn({ requests: 0, tokensIn: 0, tokensOut: 0, costMicroUsd: 0, latencyMs: 120 })).toBe(120)
|
||||
})
|
||||
})
|
||||
|
||||
describe('usageMetricColumns', () => {
|
||||
it('builds exactly requests/tokensIn/tokensOut/cost, in that order', () => {
|
||||
const columns = usageMetricColumns<Row>()
|
||||
expect(columns.map((c) => c.id)).toEqual(['requests', 'tokensIn', 'tokensOut', 'cost'])
|
||||
})
|
||||
|
||||
it('each column\'s accessorFn reads its own field', () => {
|
||||
const row: Row = { requests: 1, tokensIn: 2, tokensOut: 3, costMicroUsd: 4 }
|
||||
const columns = usageMetricColumns<Row>() as unknown as { id: string; accessorFn: (r: Row) => number }[]
|
||||
expect(columns.find((c) => c.id === 'requests')?.accessorFn(row)).toBe(1)
|
||||
expect(columns.find((c) => c.id === 'tokensIn')?.accessorFn(row)).toBe(2)
|
||||
expect(columns.find((c) => c.id === 'tokensOut')?.accessorFn(row)).toBe(3)
|
||||
expect(columns.find((c) => c.id === 'cost')?.accessorFn(row)).toBe(4)
|
||||
})
|
||||
})
|
||||
@@ -1,87 +0,0 @@
|
||||
// reuse-audit.md F9: generic TanStack ColumnDef factories for the numeric-
|
||||
// metric columns that repeat across every usage-shaped table in this panel
|
||||
// (lib/model-table-columns.ts, components/PricingHealthTable.vue, lib/
|
||||
// target-columns.ts) — a right-aligned, sortable count column rendered via
|
||||
// CompactNumber, a right-aligned cost column rendered via formatCost, and
|
||||
// an "undefined reads as a placeholder" optional numeric column (p50/p95,
|
||||
// context window). Each factory is generic over the row type `T`: the
|
||||
// duplication these replace was never about the ROW SHAPE (every caller
|
||||
// already has its own row interface), only about the identical id/header/
|
||||
// accessor/cell wiring built on top of it.
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import { h } from 'vue'
|
||||
|
||||
import CompactNumber from '@/components/CompactNumber.vue'
|
||||
import { formatCost } from '@/lib/format'
|
||||
|
||||
/** EMPTY_CELL is the ONE "no value to show" placeholder every table cell in this panel renders instead of a blank — model-table-columns.ts, PricingHealthTable.vue, usage-columns.ts, and events-columns.ts each used to redeclare the same '—' literal. */
|
||||
export const EMPTY_CELL = '—'
|
||||
|
||||
/** compactColumn builds one right-aligned, sortable numeric column rendered via CompactNumber (SI-style, exact value on title/aria-label) — the plain case with no storeDown masking or budget-bar overlay (usage-columns.ts's own richer numericColumn keeps those, see its own doc comment for why it is not built on this one). */
|
||||
export function compactColumn<T>(id: string, header: string, read: (row: T) => number): ColumnDef<T, unknown> {
|
||||
return {
|
||||
id,
|
||||
header,
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (r) => read(r),
|
||||
cell: ({ row }) => h(CompactNumber, { value: read(row.original) }),
|
||||
}
|
||||
}
|
||||
|
||||
/** costColumn builds one right-aligned, sortable micro-USD column rendered via formatCost — the plain case (a caller with its own special-case cell, e.g. model-table-columns.ts's free-priced-model badge, keeps its own hand-written column instead). */
|
||||
export function costColumn<T>(id: string, header: string, read: (row: T) => number): ColumnDef<T, unknown> {
|
||||
return {
|
||||
id,
|
||||
header,
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (r) => read(r),
|
||||
cell: ({ row }) => formatCost(read(row.original)),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* optionalColumn builds one right-aligned, sortable column for a value
|
||||
* that may be undefined (no observations yet, a feature switched off) —
|
||||
* EMPTY_CELL for the cell, `sortSentinel` (default 0) for the accessor so
|
||||
* an "undefined" row still sorts somewhere deterministic (p50/p95 pass -1,
|
||||
* so "no data" sorts below a genuine 0ms reading rather than tying with
|
||||
* it; context window's own 0 default is fine as-is, nothing sorts below a
|
||||
* real context size of 0).
|
||||
*/
|
||||
export function optionalColumn<T>(
|
||||
id: string,
|
||||
header: string,
|
||||
read: (row: T) => number | undefined,
|
||||
format: (n: number) => string,
|
||||
opts?: { sortSentinel?: number },
|
||||
): ColumnDef<T, unknown> {
|
||||
const sentinel = opts?.sortSentinel ?? 0
|
||||
return {
|
||||
id,
|
||||
header,
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (r) => read(r) ?? sentinel,
|
||||
cell: ({ row }) => {
|
||||
const value = read(row.original)
|
||||
return h('span', { class: 'tabular-nums' }, value !== undefined ? format(value) : EMPTY_CELL)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** UsageMetricRow is the field set usageMetricColumns reads — every row shape in this panel that carries per-model/per-scope requests/tokens/cost (ModelCatalogRow, PricingHealthRow) already has exactly these four fields under these exact names. */
|
||||
export interface UsageMetricRow {
|
||||
requests: number
|
||||
tokensIn: number
|
||||
tokensOut: number
|
||||
costMicroUsd: number
|
||||
}
|
||||
|
||||
/** usageMetricColumns builds the requests/tokensIn/tokensOut/cost column set every usage-ranked model table in this panel repeats (reuse-audit.md F9) — a caller with its own special-case cost cell (e.g. a free-priced-model badge) omits 'cost' here and appends its own instead. */
|
||||
export function usageMetricColumns<T extends UsageMetricRow>(): ColumnDef<T, unknown>[] {
|
||||
return [
|
||||
compactColumn<T>('requests', 'Requests', (r) => r.requests),
|
||||
compactColumn<T>('tokensIn', 'Tokens in', (r) => r.tokensIn),
|
||||
compactColumn<T>('tokensOut', 'Tokens out', (r) => r.tokensOut),
|
||||
costColumn<T>('cost', 'Cost', (r) => r.costMicroUsd),
|
||||
]
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import { h } from 'vue'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { EMPTY_CELL } from '@/lib/columns'
|
||||
import { eventKindVariant, kindLabel } from '@/lib/events-filter'
|
||||
import { formatTimestamp } from '@/lib/format'
|
||||
import type { AdminEventView } from '@/types/api'
|
||||
|
||||
/** scopeText renders one event's user/group — a user-scoped event never carries a group and vice versa (AdminEventView's own doc comment), so at most one of the two is ever present; an event with neither (a total/all-scope event, e.g. a capacity rejection recorded user-less — DECISIONS Q4) renders an em dash. */
|
||||
function scopeText(e: AdminEventView): string {
|
||||
if (e.user) return `user:${e.user}`
|
||||
if (e.group) return `group:${e.group}`
|
||||
return EMPTY_CELL
|
||||
}
|
||||
|
||||
/** targetText renders one event's model/provider pair — joined when both are known (an upstream/timeout event names both), just the one that is known otherwise, and an em dash when neither applies (a rate_limit/budget event never carries either). */
|
||||
function targetText(e: AdminEventView): string {
|
||||
const parts = [e.model, e.provider].filter((v): v is string => Boolean(v))
|
||||
return parts.length ? parts.join(' → ') : EMPTY_CELL
|
||||
}
|
||||
|
||||
/**
|
||||
* eventsColumns builds the Events tab's DataTable ColumnDef set
|
||||
* (admin.go/events.go: gatewayEvent — F3). Mirrors target-columns.ts's own
|
||||
* shape: a Badge for the classified `kind` column (eventKindVariant), plain
|
||||
* muted text for everything free-form (route/message), an em dash for a
|
||||
* field this row does not carry rather than a blank cell.
|
||||
*/
|
||||
export function eventsColumns(): ColumnDef<AdminEventView, unknown>[] {
|
||||
return [
|
||||
{
|
||||
id: 'time',
|
||||
header: 'Time',
|
||||
accessorFn: (e) => e.time,
|
||||
cell: ({ row }) => h('span', { class: 'text-muted-foreground tabular-nums' }, formatTimestamp(row.original.time)),
|
||||
},
|
||||
{
|
||||
id: 'kind',
|
||||
header: 'Kind',
|
||||
accessorFn: (e) => e.kind,
|
||||
cell: ({ row }) =>
|
||||
h(
|
||||
Badge,
|
||||
{ as: 'span', variant: eventKindVariant(row.original.kind), class: 'font-normal' },
|
||||
() => kindLabel(row.original.kind),
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'route',
|
||||
header: 'Route',
|
||||
accessorFn: (e) => e.route,
|
||||
cell: ({ row }) => h('span', { class: 'font-mono text-xs' }, row.original.route),
|
||||
},
|
||||
{
|
||||
id: 'scope',
|
||||
header: 'User / group',
|
||||
enableSorting: false,
|
||||
accessorFn: (e) => e.user ?? e.group ?? '',
|
||||
cell: ({ row }) => {
|
||||
const text = scopeText(row.original)
|
||||
return h('span', { class: text === EMPTY_CELL ? 'text-muted-foreground' : undefined }, text)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'target',
|
||||
header: 'Model / provider',
|
||||
enableSorting: false,
|
||||
accessorFn: (e) => `${e.model ?? ''} ${e.provider ?? ''}`,
|
||||
cell: ({ row }) => {
|
||||
const text = targetText(row.original)
|
||||
return h('span', { class: text === EMPTY_CELL ? 'text-muted-foreground' : 'font-mono text-xs' }, text)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'replica',
|
||||
header: 'Replica',
|
||||
accessorFn: (e) => e.replica,
|
||||
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, row.original.replica),
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
header: 'Status',
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (e) => e.status ?? 0,
|
||||
cell: ({ row }) =>
|
||||
h('span', { class: 'tabular-nums' }, row.original.status !== undefined ? String(row.original.status) : EMPTY_CELL),
|
||||
},
|
||||
{
|
||||
id: 'message',
|
||||
header: 'Message',
|
||||
enableSorting: false,
|
||||
accessorFn: (e) => e.message,
|
||||
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, row.original.message),
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -1,40 +1,8 @@
|
||||
import type { VNode } from 'vue'
|
||||
import { isVNode } from 'vue'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import ModelChip from '@/components/ModelChip.vue'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { buildModelCatalogRows, modelCatalogColumns } from './model-table-columns'
|
||||
import type { ModelCatalogRow } from './model-table-columns'
|
||||
import { buildModelCatalogRows } from './model-table-columns'
|
||||
import type { AdminCatalogResponse, AdminPerfResponse, AdminUsageModelsResponse } from '@/types/api'
|
||||
|
||||
function testRow(overrides: Partial<ModelCatalogRow> = {}): ModelCatalogRow {
|
||||
return {
|
||||
id: 'openai/gpt-5',
|
||||
model: 'gpt-5',
|
||||
providerName: 'openai',
|
||||
kind: '',
|
||||
endpoint: false,
|
||||
priceSource: 'builtin',
|
||||
aliases: [],
|
||||
requests: 0,
|
||||
tokensIn: 0,
|
||||
tokensOut: 0,
|
||||
costMicroUsd: 0,
|
||||
attempts: 0,
|
||||
failures: 0,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function accessorFnOf(col: unknown): (row: ModelCatalogRow, index: number) => unknown {
|
||||
return (col as { accessorFn: (row: ModelCatalogRow, index: number) => unknown }).accessorFn
|
||||
}
|
||||
|
||||
function cellOf(col: unknown): (ctx: { row: { original: ModelCatalogRow } }) => unknown {
|
||||
return (col as { cell: (ctx: { row: { original: ModelCatalogRow } }) => unknown }).cell
|
||||
}
|
||||
|
||||
describe('buildModelCatalogRows', () => {
|
||||
function catalog(): AdminCatalogResponse {
|
||||
return {
|
||||
@@ -124,139 +92,6 @@ describe('buildModelCatalogRows', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('modelCatalogColumns: id column', () => {
|
||||
const col = modelCatalogColumns().find((c) => c.id === 'id')
|
||||
|
||||
// This table lives on the Models page, so a link back to it would repeat the chip's own text.
|
||||
it('cell renders one ModelChip and no self-link', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testRow({ id: 'anthropic/claude' }) } }) as VNode
|
||||
expect(rendered.type).toBe(ModelChip)
|
||||
expect(rendered.props?.id).toBe('anthropic/claude')
|
||||
})
|
||||
})
|
||||
|
||||
describe('modelCatalogColumns: price column', () => {
|
||||
const col = modelCatalogColumns().find((c) => c.id === 'price')
|
||||
|
||||
it('renders a destructive "unpriced" Badge for priceSource "unpriced"', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testRow({ priceSource: 'unpriced' }) } }) as VNode
|
||||
expect(rendered.type).toBe(Badge)
|
||||
expect(rendered.props?.variant).toBe('destructive')
|
||||
})
|
||||
|
||||
it('renders a "free" Badge for priceSource "free"', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testRow({ priceSource: 'free' }) } }) as VNode
|
||||
expect(rendered.type).toBe(Badge)
|
||||
const slot = (rendered.children as { default: () => string }).default
|
||||
expect(slot()).toBe('free')
|
||||
})
|
||||
|
||||
it('renders the formatted price plus a source Badge for override/builtin/litellm', () => {
|
||||
const rendered = cellOf(col)({
|
||||
row: { original: testRow({ priceSource: 'litellm', inputPerMTokUsd: 1, outputPerMTokUsd: 2 }) },
|
||||
}) as VNode
|
||||
const children = rendered.children as VNode[]
|
||||
expect((children[0] as VNode).children).toBe('$1.00 / $2.00')
|
||||
const badge = children[1] as VNode
|
||||
expect(badge.type).toBe(Badge)
|
||||
expect((badge.children as { default: () => string }).default()).toBe('litellm')
|
||||
})
|
||||
|
||||
it('renders an em dash placeholder for a priced source with unknown per-token cost (version skew)', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testRow({ priceSource: 'override' }) } }) as VNode
|
||||
const children = rendered.children as VNode[]
|
||||
expect((children[0] as VNode).children).toBe('—')
|
||||
})
|
||||
|
||||
it('sorts unpriced first, then ascending by input price', () => {
|
||||
const accessor = accessorFnOf(col)
|
||||
const rows = [
|
||||
testRow({ id: 'a', priceSource: 'builtin', inputPerMTokUsd: 5 }),
|
||||
testRow({ id: 'b', priceSource: 'unpriced' }),
|
||||
testRow({ id: 'c', priceSource: 'builtin', inputPerMTokUsd: 1 }),
|
||||
]
|
||||
const sorted = [...rows].sort((x, y) => (accessor(x, 0) as number) - (accessor(y, 0) as number))
|
||||
expect(sorted.map((r) => r.id)).toEqual(['b', 'c', 'a'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('modelCatalogColumns: ":free" suffix flag', () => {
|
||||
const col = modelCatalogColumns().find((c) => c.id === 'price')
|
||||
const priced = { priceSource: 'litellm', inputPerMTokUsd: 1, outputPerMTokUsd: 2 } as const
|
||||
|
||||
it('has no separate free column', () => {
|
||||
expect(modelCatalogColumns().some((c) => c.id === 'free')).toBe(false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ displayFree: true, children: 3 },
|
||||
{ displayFree: false, children: 2 },
|
||||
{ displayFree: undefined, children: 2 },
|
||||
])('displayFree=$displayFree renders $children price-cell children', ({ displayFree, children }) => {
|
||||
const rendered = cellOf(col)({ row: { original: testRow({ ...priced, displayFree }) } }) as VNode
|
||||
expect((rendered.children as VNode[]).length).toBe(children)
|
||||
})
|
||||
})
|
||||
|
||||
describe('modelCatalogColumns: aliases column', () => {
|
||||
const col = modelCatalogColumns().find((c) => c.id === 'aliases')
|
||||
|
||||
it('renders an em dash for an empty alias list', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testRow({ aliases: [] }) } })
|
||||
expect(isVNode(rendered) && rendered.children).toBe('—')
|
||||
})
|
||||
|
||||
it('renders one Badge per alias', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testRow({ aliases: ['a', 'b'] }) } }) as VNode
|
||||
const children = rendered.children as VNode[]
|
||||
expect(children).toHaveLength(2)
|
||||
expect(children.every((c) => c.type === Badge)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('modelCatalogColumns: cost column', () => {
|
||||
const col = modelCatalogColumns().find((c) => c.id === 'cost')
|
||||
|
||||
it('renders a "free" Badge for a zero-cost free/displayFree row instead of $0.0000', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testRow({ priceSource: 'free', costMicroUsd: 0 }) } }) as VNode
|
||||
expect(rendered.type).toBe(Badge)
|
||||
const rendered2 = cellOf(col)({ row: { original: testRow({ displayFree: true, costMicroUsd: 0 }) } }) as VNode
|
||||
expect(rendered2.type).toBe(Badge)
|
||||
})
|
||||
|
||||
it('renders the real formatted cost when non-zero, even if free', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testRow({ priceSource: 'free', costMicroUsd: 1_234_500 }) } })
|
||||
expect(rendered).toBe('$1.2345')
|
||||
})
|
||||
|
||||
it('renders plain formatCost for a priced, non-free row', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testRow({ costMicroUsd: 2_000_000 }) } })
|
||||
expect(rendered).toBe('$2.0000')
|
||||
})
|
||||
})
|
||||
|
||||
describe('modelCatalogColumns: p50/p95/error rate columns', () => {
|
||||
it('p50/p95 render an em dash when undefined, formatted latency otherwise', () => {
|
||||
const p50 = modelCatalogColumns().find((c) => c.id === 'p50')
|
||||
const p95 = modelCatalogColumns().find((c) => c.id === 'p95')
|
||||
expect(cellOf(p50)({ row: { original: testRow() } })).toMatchObject({ children: '—' })
|
||||
expect(cellOf(p95)({ row: { original: testRow({ p95Ms: 1500 }) } })).toMatchObject({ children: '1.5s' })
|
||||
})
|
||||
|
||||
it('error rate renders "no data" for zero attempts, a ceiled percent otherwise', () => {
|
||||
const col = modelCatalogColumns().find((c) => c.id === 'errorRate')
|
||||
expect(cellOf(col)({ row: { original: testRow({ attempts: 0, failures: 0 }) } })).toMatchObject({ children: 'no data' })
|
||||
expect(cellOf(col)({ row: { original: testRow({ attempts: 100, failures: 1 }) } })).toMatchObject({ children: '1%' })
|
||||
})
|
||||
|
||||
it('error rate sorts a no-traffic row (-1) below every real rate', () => {
|
||||
const col = modelCatalogColumns().find((c) => c.id === 'errorRate')
|
||||
const accessor = accessorFnOf(col)
|
||||
expect(accessor(testRow({ attempts: 0, failures: 0 }), 0)).toBe(-1)
|
||||
expect(accessor(testRow({ attempts: 10, failures: 0 }), 0)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildModelCatalogRows: router targets', () => {
|
||||
it('carries a model routers list and defaults to empty', () => {
|
||||
const catalog = {
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import { h } from 'vue'
|
||||
|
||||
import ModelChip from '@/components/ModelChip.vue'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import CompactNumber from '@/components/CompactNumber.vue'
|
||||
import { EMPTY_CELL, optionalColumn, usageMetricColumns } from '@/lib/columns'
|
||||
import { formatCost, formatLatencyMs, formatModelCostHover, formatModelPriceShort } from '@/lib/format'
|
||||
import { formatErrorRatePercent, providerErrorRate } from '@/lib/provider-rate'
|
||||
import type { AdminCatalogResponse, AdminPerfResponse, AdminUsageModelsResponse, PriceSource } from '@/types/api'
|
||||
|
||||
/**
|
||||
@@ -102,159 +93,3 @@ export function buildModelCatalogRows(
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
/** PRICE_SOURCE_LABEL is the price-source Badge's visible text for the three "priced by a rule" sources — 'free'/'unpriced' get their own dedicated badge treatment in priceCell below, never this generic label. */
|
||||
const PRICE_SOURCE_LABEL: Record<Extract<PriceSource, 'override' | 'builtin' | 'litellm'>, string> = {
|
||||
override: 'override',
|
||||
builtin: 'builtin',
|
||||
litellm: 'litellm',
|
||||
}
|
||||
|
||||
const FREE_SUFFIX_TITLE = "':free' suffix model — display-only, billing follows the price source"
|
||||
|
||||
function priceCell(row: ModelCatalogRow) {
|
||||
if (row.endpoint) return h('span', { class: 'text-muted-foreground' }, EMPTY_CELL)
|
||||
if (row.priceSource === 'unpriced') {
|
||||
return h(
|
||||
Badge,
|
||||
{ as: 'span', variant: 'destructive', class: 'font-normal', title: 'No pricing rule matched — billed as $0.' },
|
||||
() => 'unpriced',
|
||||
)
|
||||
}
|
||||
if (row.priceSource === 'free') {
|
||||
return h(Badge, { as: 'span', variant: 'secondary', class: 'font-normal', title: 'Configured free (modelMeta.free) — priced at $0.' }, () => 'free')
|
||||
}
|
||||
const known = row.inputPerMTokUsd !== undefined && row.outputPerMTokUsd !== undefined
|
||||
// Narrowed to a local BEFORE the h() callback below — TS control-flow
|
||||
// narrowing on `row.priceSource` (from the two early returns above)
|
||||
// does not cross a closure boundary, so the callback itself still sees
|
||||
// the full PriceSource union unless the already-narrowed value is
|
||||
// captured into its own variable first.
|
||||
const source = row.priceSource as Exclude<PriceSource, 'unpriced' | 'free'>
|
||||
return h('span', { class: 'inline-flex flex-wrap items-center gap-1.5' }, [
|
||||
h(
|
||||
'span',
|
||||
known ? { class: 'tabular-nums', title: formatModelCostHover(row.inputPerMTokUsd as number, row.outputPerMTokUsd as number) } : {},
|
||||
known ? formatModelPriceShort(row.inputPerMTokUsd as number, row.outputPerMTokUsd as number) : EMPTY_CELL,
|
||||
),
|
||||
h(Badge, { as: 'span', variant: 'outline', class: 'font-normal' }, () => PRICE_SOURCE_LABEL[source]),
|
||||
...(row.displayFree ? [h(Badge, { as: 'span', variant: 'secondary', class: 'font-normal', title: FREE_SUFFIX_TITLE }, () => ':free')] : []),
|
||||
])
|
||||
}
|
||||
|
||||
/**
|
||||
* priceSortValue orders unpriced first (nothing to report, worth an
|
||||
* operator's attention), then by ascending input price — accessorFn's
|
||||
* numeric return, not the rendered text, is what DataTable actually sorts
|
||||
* on.
|
||||
*/
|
||||
function priceSortValue(row: ModelCatalogRow): number {
|
||||
if (row.endpoint) return 0
|
||||
if (row.priceSource === 'unpriced') return -1
|
||||
return row.inputPerMTokUsd ?? 0
|
||||
}
|
||||
|
||||
/**
|
||||
* modelCatalogColumns builds the Models page's catalog table (redesign-
|
||||
* plan.md section 3.4): id, context, price + source badge (plus a ':free' badge for
|
||||
* the suffix flag, distinct from the 'free' priceSource badge), aliases,
|
||||
* req/tokens/cost for the current global range, p50/p95, and error rate.
|
||||
* p50/p95 read "—" whenever undefined, regardless of WHY (no observations
|
||||
* yet, or admin.stats.latency off entirely) — ModelCatalogTable.vue itself
|
||||
* carries the admin.stats.latency hint at the table level (task
|
||||
* instruction: "handle latencyEnabled=false with a hint naming
|
||||
* admin.stats.latency"), not repeated on every row.
|
||||
*/
|
||||
export function modelCatalogColumns(): ColumnDef<ModelCatalogRow, unknown>[] {
|
||||
return [
|
||||
{
|
||||
id: 'id',
|
||||
header: 'Model',
|
||||
accessorFn: (r) => r.id,
|
||||
cell: ({ row }) =>
|
||||
h(ModelChip, {
|
||||
id: row.original.id,
|
||||
contextTokens: row.original.contextTokens,
|
||||
inputPerMTokUsd: row.original.inputPerMTokUsd,
|
||||
outputPerMTokUsd: row.original.outputPerMTokUsd,
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'price',
|
||||
header: 'Price $/MTok',
|
||||
accessorFn: (r) => priceSortValue(r),
|
||||
cell: ({ row }) => priceCell(row.original),
|
||||
},
|
||||
{
|
||||
id: 'aliases',
|
||||
header: 'Aliases',
|
||||
enableSorting: false,
|
||||
accessorFn: (r) => r.aliases.join(', '),
|
||||
cell: ({ row }) => {
|
||||
const aliases = row.original.aliases
|
||||
if (aliases.length === 0) return h('span', { class: 'text-muted-foreground' }, EMPTY_CELL)
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'flex flex-wrap gap-1' },
|
||||
aliases.map((a) => h(Badge, { key: a, as: 'span', variant: 'outline', class: 'font-mono font-normal' }, () => a)),
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'routers',
|
||||
header: 'Routers',
|
||||
enableSorting: false,
|
||||
accessorFn: (r) => (r.routers ?? []).join(', '),
|
||||
cell: ({ row }) => {
|
||||
const routers = row.original.routers ?? []
|
||||
if (routers.length === 0) return h('span', { class: 'text-muted-foreground' }, EMPTY_CELL)
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'flex flex-wrap gap-1' },
|
||||
routers.map((r) => h(Badge, { key: r, as: 'span', variant: 'secondary', class: 'font-mono font-normal', title: 'Smart router target' }, () => r)),
|
||||
)
|
||||
},
|
||||
},
|
||||
// reuse-audit.md F9: requests/tokensIn/tokensOut share the shared
|
||||
// usageMetricColumns factory; 'cost' stays hand-written below since
|
||||
// this table's cost cell has an extra free-priced-model badge case
|
||||
// usageMetricColumns' own plain costColumn does not (and should not —
|
||||
// PricingHealthTable.vue's identical-shaped cost column has no such
|
||||
// badge) carry.
|
||||
...usageMetricColumns<ModelCatalogRow>().filter((c) => c.id === 'requests'),
|
||||
{
|
||||
id: 'tokens',
|
||||
header: 'Tokens',
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (r) => r.tokensIn + r.tokensOut,
|
||||
cell: ({ row }) =>
|
||||
h('span', { class: 'inline-flex items-center gap-1 whitespace-nowrap', title: 'input / output tokens' }, [
|
||||
h(CompactNumber, { value: row.original.tokensIn }),
|
||||
h('span', { class: 'text-muted-foreground' }, '/'),
|
||||
h(CompactNumber, { value: row.original.tokensOut }),
|
||||
]),
|
||||
},
|
||||
{
|
||||
id: 'cost',
|
||||
header: 'Cost',
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (r) => r.costMicroUsd,
|
||||
cell: ({ row }) => {
|
||||
const r = row.original
|
||||
if ((r.priceSource === 'free' || r.displayFree) && r.costMicroUsd === 0) {
|
||||
return h(Badge, { as: 'span', variant: 'secondary', class: 'font-normal', title: 'priced at $0 per token' }, () => 'free')
|
||||
}
|
||||
return formatCost(r.costMicroUsd)
|
||||
},
|
||||
},
|
||||
optionalColumn<ModelCatalogRow>('p50', 'p50', (r) => r.p50Ms, formatLatencyMs, { sortSentinel: -1 }),
|
||||
optionalColumn<ModelCatalogRow>('p95', 'p95', (r) => r.p95Ms, formatLatencyMs, { sortSentinel: -1 }),
|
||||
{
|
||||
id: 'errorRate',
|
||||
header: 'Errors',
|
||||
meta: { align: 'right' },
|
||||
accessorFn: (r) => providerErrorRate(r.attempts, r.failures) ?? -1,
|
||||
cell: ({ row }) => h('span', { class: 'tabular-nums' }, formatErrorRatePercent(providerErrorRate(row.original.attempts, row.original.failures))),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { providerSections } from '@/lib/provider-sections'
|
||||
|
||||
describe('providerSections', () => {
|
||||
it('returns one untitled section when no kinds or endpoints are set', () => {
|
||||
expect(providerSections({ models: ['a', 'b'] })).toEqual([{ title: '', models: ['a', 'b'], endpoints: [] }])
|
||||
})
|
||||
|
||||
it('groups models and endpoints by kind, plain models first', () => {
|
||||
const got = providerSections({
|
||||
models: ['chat', 'rerank', 'embed'],
|
||||
kinds: { rerank: 'reranking', embed: 'embedding', '/v1/decide': 'decision' },
|
||||
endpoints: ['/v1/decide'],
|
||||
})
|
||||
expect(got).toEqual([
|
||||
{ title: '', models: ['chat'], endpoints: [] },
|
||||
{ title: 'decision', models: [], endpoints: ['/v1/decide'] },
|
||||
{ title: 'embedding', models: ['embed'], endpoints: [] },
|
||||
{ title: 'reranking', models: ['rerank'], endpoints: [] },
|
||||
])
|
||||
})
|
||||
|
||||
it('files an endpoint without a kind under "endpoints"', () => {
|
||||
const got = providerSections({ models: ['chat'], endpoints: ['/v1/other'] })
|
||||
expect(got).toEqual([
|
||||
{ title: '', models: ['chat'], endpoints: [] },
|
||||
{ title: 'endpoints', models: [], endpoints: ['/v1/other'] },
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -1,40 +0,0 @@
|
||||
export interface ProviderSection {
|
||||
/** Sub-section heading; '' for the untitled plain-model section. */
|
||||
title: string
|
||||
models: string[]
|
||||
endpoints: string[]
|
||||
}
|
||||
|
||||
export interface ProviderSectionInput {
|
||||
models: string[]
|
||||
kinds?: Record<string, string>
|
||||
endpoints?: string[]
|
||||
}
|
||||
|
||||
/** Heading for an endpoint with no configured kind. */
|
||||
export const ENDPOINT_KIND = 'endpoints'
|
||||
|
||||
/**
|
||||
* providerSections splits one provider's rows into sub-sections by kind:
|
||||
* the plain (no-kind) models first, then one section per kind, sorted.
|
||||
* A provider with no kinds and no endpoints yields one untitled section,
|
||||
* so an unconfigured provider renders exactly as the flat list did.
|
||||
*/
|
||||
export function providerSections(p: ProviderSectionInput): ProviderSection[] {
|
||||
const kinds = p.kinds ?? {}
|
||||
const endpoints = p.endpoints ?? []
|
||||
if (endpoints.length === 0 && Object.keys(kinds).length === 0) return [{ title: '', models: p.models, endpoints: [] }]
|
||||
|
||||
const byTitle = new Map<string, ProviderSection>()
|
||||
const section = (title: string): ProviderSection => {
|
||||
let s = byTitle.get(title)
|
||||
if (!s) {
|
||||
s = { title, models: [], endpoints: [] }
|
||||
byTitle.set(title, s)
|
||||
}
|
||||
return s
|
||||
}
|
||||
for (const m of p.models) section(kinds[m] ?? '').models.push(m)
|
||||
for (const e of endpoints) section(kinds[e] ?? ENDPOINT_KIND).endpoints.push(e)
|
||||
return [...byTitle.values()].sort((a, b) => (a.title === '' ? -1 : b.title === '' ? 1 : a.title.localeCompare(b.title)))
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
type ExpandState,
|
||||
clearExpandOverrides,
|
||||
computeExpandedItems,
|
||||
toggleItemExpand,
|
||||
} from './search-expand'
|
||||
|
||||
/** newState is a fresh ExpandState — every test starts from an empty, un-searched panel. */
|
||||
function newState(): ExpandState {
|
||||
return { manuallyExpanded: new Set(), manuallyCollapsed: new Set() }
|
||||
}
|
||||
|
||||
describe('computeExpandedItems', () => {
|
||||
it('returns manuallyExpanded verbatim when there is no active query', () => {
|
||||
const state = newState()
|
||||
state.manuallyExpanded.add('openai')
|
||||
expect(computeExpandedItems(state, false, ['openai', 'anthropic'])).toEqual(new Set(['openai']))
|
||||
})
|
||||
|
||||
it('auto-expands every matching id while a query is active', () => {
|
||||
const state = newState()
|
||||
expect(computeExpandedItems(state, true, ['openai', 'anthropic'])).toEqual(new Set(['openai', 'anthropic']))
|
||||
})
|
||||
|
||||
it('unions manuallyExpanded with matches while a query is active', () => {
|
||||
const state = newState()
|
||||
state.manuallyExpanded.add('gemini') // manually opened before the search started, does not match it
|
||||
expect(computeExpandedItems(state, true, ['openai'])).toEqual(new Set(['gemini', 'openai']))
|
||||
})
|
||||
|
||||
it('suppresses an auto-match the user explicitly collapsed', () => {
|
||||
const state = newState()
|
||||
state.manuallyCollapsed.add('openai')
|
||||
expect(computeExpandedItems(state, true, ['openai', 'anthropic'])).toEqual(new Set(['anthropic']))
|
||||
})
|
||||
})
|
||||
|
||||
describe('toggleItemExpand', () => {
|
||||
it('opening (currentlyExpanded=false) adds to manuallyExpanded and clears any collapse override', () => {
|
||||
const state = newState()
|
||||
state.manuallyCollapsed.add('openai')
|
||||
toggleItemExpand(state, 'openai', false)
|
||||
expect(state.manuallyExpanded.has('openai')).toBe(true)
|
||||
expect(state.manuallyCollapsed.has('openai')).toBe(false)
|
||||
})
|
||||
|
||||
it('closing (currentlyExpanded=true) removes from manuallyExpanded and adds a collapse override', () => {
|
||||
const state = newState()
|
||||
state.manuallyExpanded.add('openai')
|
||||
toggleItemExpand(state, 'openai', true)
|
||||
expect(state.manuallyExpanded.has('openai')).toBe(false)
|
||||
expect(state.manuallyCollapsed.has('openai')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('clearExpandOverrides', () => {
|
||||
it('drops manuallyCollapsed but leaves manuallyExpanded untouched', () => {
|
||||
const state = newState()
|
||||
state.manuallyExpanded.add('openai')
|
||||
state.manuallyCollapsed.add('anthropic')
|
||||
clearExpandOverrides(state)
|
||||
expect(state.manuallyCollapsed.size).toBe(0)
|
||||
expect(state.manuallyExpanded.has('openai')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the review-flagged sequence: an auto-matched (never manually opened) item, clicked closed', () => {
|
||||
it('never enters manuallyExpanded, and stays collapsed after the query clears', () => {
|
||||
const state = newState()
|
||||
const matches = ['openai']
|
||||
|
||||
// 1. Search starts matching "openai" — it shows via auto-expand only,
|
||||
// manuallyExpanded is still empty.
|
||||
let expanded = computeExpandedItems(state, true, matches)
|
||||
expect(expanded.has('openai')).toBe(true)
|
||||
expect(state.manuallyExpanded.has('openai')).toBe(false)
|
||||
|
||||
// 2. User clicks it closed while it's only auto-expanded. The RAW bug
|
||||
// this module exists to fix: reading manuallyExpanded.has('openai')
|
||||
// directly (false) would have ADDED it to manuallyExpanded instead
|
||||
// of suppressing the auto-expand. toggleItemExpand takes the
|
||||
// EFFECTIVE current state (expanded.has('openai') === true) instead.
|
||||
toggleItemExpand(state, 'openai', expanded.has('openai'))
|
||||
expect(state.manuallyExpanded.has('openai')).toBe(false)
|
||||
expect(state.manuallyCollapsed.has('openai')).toBe(true)
|
||||
|
||||
// 3. Still searching: the override suppresses the auto-expand.
|
||||
expanded = computeExpandedItems(state, true, matches)
|
||||
expect(expanded.has('openai')).toBe(false)
|
||||
|
||||
// 4. Query clears: a stale override must never carry into a later,
|
||||
// unrelated search.
|
||||
clearExpandOverrides(state)
|
||||
expanded = computeExpandedItems(state, false, [])
|
||||
expect(expanded.has('openai')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('an item manually opened before search, still matches, clicked closed during search', () => {
|
||||
it("the user's in-search click wins, and it stays closed after the query clears too", () => {
|
||||
const state = newState()
|
||||
state.manuallyExpanded.add('openai') // opened before any search existed
|
||||
const matches = ['openai']
|
||||
|
||||
let expanded = computeExpandedItems(state, true, matches)
|
||||
expect(expanded.has('openai')).toBe(true)
|
||||
|
||||
toggleItemExpand(state, 'openai', expanded.has('openai'))
|
||||
expect(state.manuallyExpanded.has('openai')).toBe(false)
|
||||
expect(state.manuallyCollapsed.has('openai')).toBe(true)
|
||||
|
||||
clearExpandOverrides(state)
|
||||
expanded = computeExpandedItems(state, false, [])
|
||||
expect(expanded.has('openai')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
// This module is domain-agnostic on what an "id" represents — it started as
|
||||
// ProviderHealthPanel.vue's provider names, but ConsumerDirectory.vue also
|
||||
// feeds it group ids (see that component's own doc comment: matchingIds
|
||||
// there is every group that matches ONLY via a member, never via its own
|
||||
// name). These two cases exist to pin that the module behaves identically
|
||||
// for that second domain, not because anything here differs by id shape.
|
||||
describe('generic ids (Usage group ids, not just Providers provider names)', () => {
|
||||
it('auto-expands and can be collapsed/overridden identically for a group id', () => {
|
||||
const state = newState()
|
||||
const matches = ['team-a']
|
||||
|
||||
let expanded = computeExpandedItems(state, true, matches)
|
||||
expect(expanded.has('team-a')).toBe(true)
|
||||
|
||||
toggleItemExpand(state, 'team-a', expanded.has('team-a'))
|
||||
expect(state.manuallyExpanded.has('team-a')).toBe(false)
|
||||
expect(state.manuallyCollapsed.has('team-a')).toBe(true)
|
||||
|
||||
expanded = computeExpandedItems(state, true, matches)
|
||||
expect(expanded.has('team-a')).toBe(false)
|
||||
|
||||
clearExpandOverrides(state)
|
||||
expanded = computeExpandedItems(state, false, [])
|
||||
expect(expanded.has('team-a')).toBe(false)
|
||||
})
|
||||
|
||||
it('a group id manually opened stays open when the query clears', () => {
|
||||
const state = newState()
|
||||
state.manuallyExpanded.add('team-a')
|
||||
expect(computeExpandedItems(state, false, [])).toEqual(new Set(['team-a']))
|
||||
})
|
||||
})
|
||||
@@ -1,96 +0,0 @@
|
||||
/**
|
||||
* Pure expand/collapse state for a search-filterable shadcn-vue Accordion —
|
||||
* shared by ProviderHealthPanel.vue (providers) and ConsumerDirectory.vue
|
||||
* (groups), and generalized (originally provider-expand.ts) so both
|
||||
* consume ONE tested implementation instead of two copies of the same
|
||||
* logic (vue.md: "if you've written it twice, you owe an abstraction").
|
||||
* Extracted out of the component so the exact toggle sequence a review
|
||||
* flagged (see toggleItemExpand's own comment) is tested in isolation,
|
||||
* without mounting Vue — see search-expand.spec.ts (vitest), which
|
||||
* exercises this module directly, including the full flagged sequence.
|
||||
*
|
||||
* Two sets track state, keyed on each accordion item's own string id (a
|
||||
* provider name on the Models page, a group id on the Consumers page —
|
||||
* this module has no opinion on what the id means or on what counts as a
|
||||
* "match"; callers decide that and pass the resulting id list in):
|
||||
* - manuallyExpanded: items the user explicitly opened, independent of any
|
||||
* search query. This is the state a cleared search returns to.
|
||||
* - manuallyCollapsed: items the user explicitly closed WHILE a search
|
||||
* query was auto-expanding them. Only ever consulted while a query is
|
||||
* active (computeExpandedItems below) — once the query clears, effective
|
||||
* state is manuallyExpanded alone, so entries here become inert.
|
||||
* clearExpandOverrides drops them anyway, so a stale collapse from one
|
||||
* search session cannot silently suppress a match in an unrelated later
|
||||
* one.
|
||||
*/
|
||||
export interface ExpandState {
|
||||
manuallyExpanded: Set<string>
|
||||
manuallyCollapsed: Set<string>
|
||||
}
|
||||
|
||||
/**
|
||||
* computeExpandedItems returns the effective set of expanded item ids:
|
||||
* manuallyExpanded verbatim when no query is active; with a query active,
|
||||
* manuallyExpanded plus every id in matchingIds that is not in
|
||||
* manuallyCollapsed (auto-expand every match, unless the user explicitly
|
||||
* closed that one). The caller decides what "matching" means for its own
|
||||
* view, and this module has no opinion on it either way —
|
||||
* ProviderHealthPanel.vue passes every provider that itself matched at
|
||||
* all (every match there implies at least one matching model, so every
|
||||
* match auto-expands); ConsumerDirectory.vue instead passes only the
|
||||
* subset of its own matches that matched via a member rather than via
|
||||
* the group's own name (see that component's own doc comment for why it
|
||||
* draws that narrower distinction).
|
||||
*/
|
||||
export function computeExpandedItems(state: ExpandState, hasQuery: boolean, matchingIds: string[]): Set<string> {
|
||||
if (!hasQuery) return new Set(state.manuallyExpanded)
|
||||
const expanded = new Set(state.manuallyExpanded)
|
||||
for (const id of matchingIds) {
|
||||
if (!state.manuallyCollapsed.has(id)) expanded.add(id)
|
||||
}
|
||||
return expanded
|
||||
}
|
||||
|
||||
/**
|
||||
* toggleItemExpand mutates state for one item, given whether it is
|
||||
* CURRENTLY effectively expanded (computeExpandedItems' own result for
|
||||
* that id — the caller passes this, rather than the function re-deriving
|
||||
* it, so callers stay in charge of what "current" means for their own
|
||||
* render).
|
||||
*
|
||||
* This is the exact fix for a review-flagged bug: the original
|
||||
* implementation toggled manuallyExpanded.has(id) directly — the RAW
|
||||
* manual flag, not the effective (possibly auto-expanded) one. Clicking a
|
||||
* row that was only auto-expanded (matching the search, never manually
|
||||
* opened) read manuallyExpanded.has(id) as false and ADDED it to
|
||||
* manuallyExpanded — invisible immediately (it was already showing via
|
||||
* auto-expand), but wrongly left it expanded after the query cleared,
|
||||
* since manuallyExpanded now contained an item the user never actually
|
||||
* chose to open. Toggling against the EFFECTIVE state fixes this in both
|
||||
* directions:
|
||||
* - Expanded only via auto-match, clicked to close: manuallyExpanded never
|
||||
* gains the entry (nothing to remove); manuallyCollapsed gains it,
|
||||
* suppressing the auto-expand for as long as the query stays active.
|
||||
* Clearing the query drops back to manuallyExpanded, which never had it
|
||||
* — correctly collapsed.
|
||||
* - Expanded via a manual open from BEFORE a search started, still
|
||||
* matches, clicked to close during the search: manuallyExpanded loses it
|
||||
* (the user's own most recent action wins) and manuallyCollapsed gains
|
||||
* it, so it also stays closed after the query clears — treating the
|
||||
* in-search click as the user's current intent, not the older,
|
||||
* pre-search one.
|
||||
*/
|
||||
export function toggleItemExpand(state: ExpandState, id: string, currentlyExpanded: boolean): void {
|
||||
if (currentlyExpanded) {
|
||||
state.manuallyExpanded.delete(id)
|
||||
state.manuallyCollapsed.add(id)
|
||||
} else {
|
||||
state.manuallyCollapsed.delete(id)
|
||||
state.manuallyExpanded.add(id)
|
||||
}
|
||||
}
|
||||
|
||||
/** clearExpandOverrides drops every manuallyCollapsed entry — called when the search query becomes empty, so a suppression from one search session never carries into an unrelated later one (manuallyCollapsed is otherwise never consulted outside an active query anyway; this only matters for a FUTURE query). */
|
||||
export function clearExpandOverrides(state: ExpandState): void {
|
||||
state.manuallyCollapsed.clear()
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { loadState } from './load-state'
|
||||
import { staleNotice } from './stale-notice'
|
||||
|
||||
const at = new Date('2026-11-08T10:11:12Z')
|
||||
|
||||
describe('staleNotice', () => {
|
||||
it.each([
|
||||
{ name: 'no data, error', hasData: false, error: 'boom', want: null },
|
||||
{ name: 'data, no error', hasData: true, error: '', want: null },
|
||||
{ name: 'no data, no error', hasData: false, error: '', want: null },
|
||||
])('is null: $name', ({ hasData, error, want }) => {
|
||||
expect(staleNotice(hasData, error, at)).toBe(want)
|
||||
})
|
||||
|
||||
it('names the error and the data age when data is shown and refresh fails', () => {
|
||||
const msg = staleNotice(true, 'HTTP 503', at)
|
||||
expect(msg).toContain('HTTP 503')
|
||||
expect(msg).toContain(at.toLocaleTimeString())
|
||||
})
|
||||
|
||||
it('omits the age when lastUpdated is unknown', () => {
|
||||
expect(staleNotice(true, 'x', null)).toBe('Refresh failing: x.')
|
||||
})
|
||||
|
||||
// Lean gate Gateway.Ui.Stale.no_silent_stale: ready + error always has a notice.
|
||||
it.each([true, false])('never silent when ready with error (loading=%s)', (loading) => {
|
||||
const state = loadState({ loading, hasData: true, error: 'e' })
|
||||
expect(state).toBe('ready')
|
||||
expect(staleNotice(true, 'e', at)).not.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,6 +0,0 @@
|
||||
/** staleNotice returns the text for a "showing old data" banner, or null. Shown only when data is on screen and the latest refresh failed. */
|
||||
export function staleNotice(hasData: boolean, error: string, lastUpdated: Date | null): string | null {
|
||||
if (!hasData || !error) return null
|
||||
const at = lastUpdated ? ` Data from ${lastUpdated.toLocaleTimeString()}.` : ''
|
||||
return `Refresh failing: ${error}.${at}`
|
||||
}
|
||||
@@ -1,213 +1,7 @@
|
||||
import { isVNode } from 'vue'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import CompactNumber from '@/components/CompactNumber.vue'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { composeTargetId, parseTargetCallerId, resolveTargetRef, targetCallerColumns, targetColumns } from './target-columns'
|
||||
import type { AdminTargetHealthView, AdminTargetsResponse, AdminTargetView, AdminTotalsResponse } from '@/types/api'
|
||||
|
||||
/**
|
||||
* Target health rendering (feat/target-health): mirrors usage-columns.
|
||||
* spec.ts's own approach of exercising a ColumnDef's `cell` renderer
|
||||
* directly (no component mount needed — vite.config.ts's `test` block
|
||||
* runs vitest in the 'node' environment with no @vue/test-utils/jsdom in
|
||||
* this package, so there is no existing "mount a .vue view" pattern to
|
||||
* follow here; the health column's rendering logic lives entirely in this
|
||||
* plain TanStack ColumnDef, exactly like usage-columns.ts's own cells, so
|
||||
* the identical direct-call approach gives full coverage without either).
|
||||
*/
|
||||
function testTarget(health: AdminTargetHealthView): AdminTargetView {
|
||||
return {
|
||||
name: 'my-server',
|
||||
url: 'https://mcp.example.com',
|
||||
counters: { requestsPerMinute: 0, requestsPerDay: 0, requestsPerMonth: 0 },
|
||||
health,
|
||||
}
|
||||
}
|
||||
|
||||
function healthCellOf(target: AdminTargetView): unknown {
|
||||
const col = targetColumns().find((c) => c.id === 'health')
|
||||
const cell = col?.cell as (ctx: { row: { original: AdminTargetView } }) => unknown
|
||||
return cell({ row: { original: target } })
|
||||
}
|
||||
|
||||
describe('targetColumns: health column', () => {
|
||||
it('renders a destructive Badge for unhealthy, with a relative-time label and lastError in the title', () => {
|
||||
const health: AdminTargetHealthView = {
|
||||
state: 'unhealthy',
|
||||
lastCheck: new Date(Date.now() - 42_000).toISOString(),
|
||||
lastError: 'connection refused',
|
||||
consecutiveFailures: 3,
|
||||
source: 'probe',
|
||||
}
|
||||
const rendered = healthCellOf(testTarget(health))
|
||||
|
||||
expect(isVNode(rendered)).toBe(true)
|
||||
const vnode = rendered as { type: unknown; props?: Record<string, unknown>; children?: unknown }
|
||||
expect(vnode.type).toBe(Badge)
|
||||
expect(vnode.props?.variant).toBe('destructive')
|
||||
expect(vnode.props?.title).toBe('3 consecutive failures via probe: connection refused')
|
||||
|
||||
const slot = (vnode.children as { default: () => string }).default
|
||||
expect(slot()).toMatch(/^unhealthy \(\d+s ago\)$/)
|
||||
})
|
||||
|
||||
it('falls back to a bare "unhealthy" label when lastCheck is missing (version-skew defensive case)', () => {
|
||||
const health: AdminTargetHealthView = { state: 'unhealthy', consecutiveFailures: 1 }
|
||||
const rendered = healthCellOf(testTarget(health))
|
||||
const vnode = rendered as { props?: Record<string, unknown>; children?: { default: () => string } }
|
||||
|
||||
expect(vnode.children?.default()).toBe('unhealthy')
|
||||
// Singular "failure", no "via <source>", no lastError.
|
||||
expect(vnode.props?.title).toBe('1 consecutive failure')
|
||||
})
|
||||
|
||||
it('renders an outline Badge labeled "unknown" with a fixed explanatory title', () => {
|
||||
const health: AdminTargetHealthView = { state: 'unknown', consecutiveFailures: 0 }
|
||||
const rendered = healthCellOf(testTarget(health))
|
||||
const vnode = rendered as { type: unknown; props?: Record<string, unknown>; children?: { default: () => string } }
|
||||
|
||||
expect(vnode.type).toBe(Badge)
|
||||
expect(vnode.props?.variant).toBe('outline')
|
||||
expect(vnode.props?.title).toBe('not observed yet — no traffic and probes disabled or not yet run')
|
||||
expect(vnode.children?.default()).toBe('unknown')
|
||||
})
|
||||
|
||||
it('renders no Badge for healthy — plain muted text with latency, and relative time + source in the title', () => {
|
||||
const health: AdminTargetHealthView = {
|
||||
state: 'healthy',
|
||||
lastCheck: new Date(Date.now() - 5_000).toISOString(),
|
||||
consecutiveFailures: 0,
|
||||
latencyMs: 12,
|
||||
source: 'traffic',
|
||||
}
|
||||
const rendered = healthCellOf(testTarget(health))
|
||||
|
||||
expect(isVNode(rendered)).toBe(true)
|
||||
const vnode = rendered as { type: unknown; props?: Record<string, unknown>; children?: unknown }
|
||||
expect(vnode.type).toBe('span')
|
||||
expect(vnode.props?.class).toBe('text-muted-foreground')
|
||||
// formatLatencyMs (lib/format.ts), not a raw "${latencyMs} ms" — no
|
||||
// space, matching every other latency reading in this panel.
|
||||
expect(vnode.children).toBe('healthy · 12ms')
|
||||
expect(vnode.props?.title).toMatch(/^\d+s ago via traffic$/)
|
||||
})
|
||||
|
||||
it('renders the healthy latency suffix in seconds via formatLatencyMs once above 1000ms', () => {
|
||||
const health: AdminTargetHealthView = { state: 'healthy', consecutiveFailures: 0, latencyMs: 1500 }
|
||||
const rendered = healthCellOf(testTarget(health))
|
||||
const vnode = rendered as { children?: unknown }
|
||||
expect(vnode.children).toBe('healthy · 1.5s')
|
||||
})
|
||||
|
||||
it('omits the latency suffix for healthy when latencyMs is unknown', () => {
|
||||
const health: AdminTargetHealthView = { state: 'healthy', consecutiveFailures: 0 }
|
||||
const rendered = healthCellOf(testTarget(health))
|
||||
const vnode = rendered as { children?: unknown; props?: Record<string, unknown> }
|
||||
|
||||
expect(vnode.children).toBe('healthy')
|
||||
// Neither lastCheck nor source known — nothing to show in the title.
|
||||
expect(vnode.props?.title).toBe('')
|
||||
})
|
||||
|
||||
it('the health column is not sortable — three semantic states have no meaningful alphabetical order', () => {
|
||||
const col = targetColumns().find((c) => c.id === 'health')
|
||||
expect(col?.enableSorting).toBe(false)
|
||||
})
|
||||
|
||||
// F4/F7 (feat/target-health review): "unknown" also covers a target
|
||||
// that HAS been observed but has never succeeded, still below
|
||||
// failureThreshold — that case carries real failure detail even
|
||||
// though the label stays "unknown".
|
||||
it('surfaces failure detail in the unknown badge title for a target observed but never succeeded', () => {
|
||||
const health: AdminTargetHealthView = {
|
||||
state: 'unknown',
|
||||
consecutiveFailures: 2,
|
||||
source: 'probe',
|
||||
lastError: 'dial tcp: connection refused',
|
||||
}
|
||||
const rendered = healthCellOf(testTarget(health))
|
||||
const vnode = rendered as { type: unknown; props?: Record<string, unknown>; children?: { default: () => string } }
|
||||
|
||||
expect(vnode.type).toBe(Badge)
|
||||
expect(vnode.props?.variant).toBe('outline')
|
||||
expect(vnode.props?.title).toBe('2 failures so far via probe: dial tcp: connection refused')
|
||||
expect(vnode.children?.default()).toBe('unknown')
|
||||
})
|
||||
|
||||
it('singular "failure" and no "via <source>"/lastError when only consecutiveFailures is known', () => {
|
||||
const health: AdminTargetHealthView = { state: 'unknown', consecutiveFailures: 1 }
|
||||
const rendered = healthCellOf(testTarget(health))
|
||||
const vnode = rendered as { props?: Record<string, unknown> }
|
||||
expect(vnode.props?.title).toBe('1 failure so far')
|
||||
})
|
||||
|
||||
it('falls back to the outline "unknown" badge for any state other than healthy/unhealthy', () => {
|
||||
// Defensive: healthCell's own state check is an explicit
|
||||
// state === 'healthy' branch with "unknown" as the fallback for
|
||||
// everything else — not the reverse — so a value this version of
|
||||
// the webui does not recognize renders as "unknown", never as a
|
||||
// silently-wrong "healthy".
|
||||
const health = { state: 'something-future-versions-might-add', consecutiveFailures: 0 } as unknown as AdminTargetHealthView
|
||||
const rendered = healthCellOf(testTarget(health))
|
||||
const vnode = rendered as { type: unknown; props?: Record<string, unknown>; children?: { default: () => string } }
|
||||
|
||||
expect(vnode.type).toBe(Badge)
|
||||
expect(vnode.props?.variant).toBe('outline')
|
||||
expect(vnode.children?.default()).toBe('unknown')
|
||||
})
|
||||
})
|
||||
|
||||
function accessCellOf(access: AdminTargetView['access']): unknown {
|
||||
const col = targetColumns().find((c) => c.id === 'access')
|
||||
const cell = col?.cell as (ctx: { row: { original: AdminTargetView } }) => unknown
|
||||
return cell({ row: { original: { ...testTarget({ state: 'unknown', consecutiveFailures: 0 }), access } } })
|
||||
}
|
||||
|
||||
describe('targetColumns: access column', () => {
|
||||
it('renders "All groups" for null and absent access', () => {
|
||||
for (const access of [null, undefined]) {
|
||||
const node = accessCellOf(access)
|
||||
expect(isVNode(node) && node.children).toBe('All groups')
|
||||
}
|
||||
})
|
||||
|
||||
it('renders "No groups" for an empty access list, not "All groups"', () => {
|
||||
const node = accessCellOf([])
|
||||
expect(isVNode(node) && node.children).toBe('No groups')
|
||||
})
|
||||
|
||||
it('renders one Badge per group for a non-empty access list', () => {
|
||||
const node = accessCellOf(['a', 'b'])
|
||||
expect(isVNode(node)).toBe(true)
|
||||
const children = (node as { children: unknown[] }).children
|
||||
expect(children).toHaveLength(2)
|
||||
expect(children.every((c) => isVNode(c) && c.type === Badge)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('targetColumns: name column selection', () => {
|
||||
it('renders plain text with no onSelect (default, backward-compatible)', () => {
|
||||
const col = targetColumns().find((c) => c.id === 'name')
|
||||
const cell = col?.cell as (ctx: { row: { original: AdminTargetView } }) => unknown
|
||||
const rendered = cell({ row: { original: testTarget({ state: 'unknown', consecutiveFailures: 0 }) } })
|
||||
expect(isVNode(rendered) && rendered.type).toBe('span')
|
||||
})
|
||||
|
||||
it('renders a clickable button that invokes onSelect with the row when given', () => {
|
||||
const selected: AdminTargetView[] = []
|
||||
const col = targetColumns((t) => selected.push(t)).find((c) => c.id === 'name')
|
||||
const cell = col?.cell as (ctx: { row: { original: AdminTargetView } }) => unknown
|
||||
const target = testTarget({ state: 'unknown', consecutiveFailures: 0 })
|
||||
const rendered = cell({ row: { original: target } })
|
||||
expect(isVNode(rendered) && rendered.type).toBe('button')
|
||||
|
||||
const onClick = (rendered as { props?: Record<string, unknown> }).props?.onClick as (e: MouseEvent) => void
|
||||
onClick({ stopPropagation: () => {} } as MouseEvent)
|
||||
expect(selected).toEqual([target])
|
||||
})
|
||||
})
|
||||
|
||||
import { composeTargetId, parseTargetCallerId, resolveTargetRef } from './target-columns'
|
||||
import type { AdminTargetsResponse, AdminTargetView } from '@/types/api'
|
||||
describe('composeTargetId', () => {
|
||||
it('joins kind and name with a slash', () => {
|
||||
expect(composeTargetId('mcp', 'fetch')).toBe('mcp/fetch')
|
||||
@@ -232,51 +26,6 @@ describe('parseTargetCallerId', () => {
|
||||
expect(parseTargetCallerId('mcp/fetch')).toEqual({ kind: 'mcp', target: 'fetch', caller: '' })
|
||||
})
|
||||
})
|
||||
|
||||
// dayOrMonthWindow moved to lib/range.ts (P2 item 2: a SHARED clamp used
|
||||
// by stores/consumers.ts, stores/spend.ts, AND this module's own
|
||||
// TargetCallers.vue — see range.spec.ts's own describe('dayOrMonthWindow').
|
||||
|
||||
describe('targetCallerColumns', () => {
|
||||
function row(id: string, req: number): AdminTotalsResponse['rows'][number] {
|
||||
return { id, values: { req } }
|
||||
}
|
||||
|
||||
it('omits the Target column when showTarget is false', () => {
|
||||
const columns = targetCallerColumns(false)
|
||||
expect(columns.find((c) => c.id === 'target')).toBeUndefined()
|
||||
expect(columns.map((c) => c.id)).toEqual(['caller', 'requests'])
|
||||
})
|
||||
|
||||
it('includes the Target column, rendering "kind/target", when showTarget is true', () => {
|
||||
const columns = targetCallerColumns(true)
|
||||
const col = columns.find((c) => c.id === 'target')
|
||||
expect(col).toBeDefined()
|
||||
const cell = col?.cell as (ctx: { row: { original: AdminTotalsResponse['rows'][number] } }) => unknown
|
||||
const rendered = cell({ row: { original: row('mcp/fetch/alice', 3) } })
|
||||
expect(isVNode(rendered) && rendered.children).toBe('mcp/fetch')
|
||||
})
|
||||
|
||||
it('caller column reads the parsed caller name, falling back to the raw id', () => {
|
||||
const columns = targetCallerColumns(false)
|
||||
const col = columns.find((c) => c.id === 'caller') as unknown as {
|
||||
accessorFn: (r: AdminTotalsResponse['rows'][number], i: number) => unknown
|
||||
}
|
||||
const accessor = col.accessorFn
|
||||
expect(accessor(row('mcp/fetch/alice', 3), 0)).toBe('alice')
|
||||
expect(accessor(row('malformed', 3), 0)).toBe('malformed')
|
||||
})
|
||||
|
||||
it('requests column renders a CompactNumber reading values.req, defaulting to 0', () => {
|
||||
const columns = targetCallerColumns(false)
|
||||
const col = columns.find((c) => c.id === 'requests')
|
||||
const cell = col?.cell as (ctx: { row: { original: AdminTotalsResponse['rows'][number] } }) => unknown
|
||||
const rendered = cell({ row: { original: { id: 'mcp/fetch/alice', values: {} } } })
|
||||
expect(isVNode(rendered) && rendered.type).toBe(CompactNumber)
|
||||
expect(isVNode(rendered) && rendered.props?.value).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
// --- resolveTargetRef (P2 item: a hand-typed #targets?target=demo-mcp
|
||||
// 400ed — parseTargetRef, stats_read.go, only accepts "mcp/{name}"/
|
||||
// "agent/{name}") ---
|
||||
|
||||
@@ -1,180 +1,4 @@
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import { h } from 'vue'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { compactColumn } from '@/lib/columns'
|
||||
import { formatElapsedAgo, formatLatencyMs } from '@/lib/format'
|
||||
import type { AdminTargetHealthView, AdminTargetsResponse, AdminTargetView, AdminTotalsResponse } from '@/types/api'
|
||||
|
||||
// --- target health (feat/target-health) ---
|
||||
//
|
||||
// Mirrors ProviderHealthPanel.vue's own healthBadgeVariant/healthBadgeLabel
|
||||
// convention for the discovery circuit breaker: a Badge only for the two
|
||||
// states worth flagging (unhealthy, unknown); the common healthy case
|
||||
// renders no badge at all, just muted inline text — the same "nothing to
|
||||
// show reads as no badge" idiom every health/rate indicator in this panel
|
||||
// already follows (see AdminTargetHealthView's own doc comment, api.ts,
|
||||
// for what each field means).
|
||||
|
||||
const UNKNOWN_HEALTH_TITLE = 'not observed yet — no traffic and probes disabled or not yet run'
|
||||
|
||||
/** unhealthyLabel keeps the Badge's own visible text short — "unhealthy (Ns ago)" when lastCheck is known, plain "unhealthy" otherwise (defensive: a version-skewed server response omitting lastCheck on an unhealthy row). */
|
||||
function unhealthyLabel(health: AdminTargetHealthView): string {
|
||||
const ago = formatElapsedAgo(health.lastCheck)
|
||||
return ago ? `unhealthy (${ago})` : 'unhealthy'
|
||||
}
|
||||
|
||||
/** unhealthyTitle carries the detail the short label leaves out — consecutiveFailures, source, and lastError (when present) — e.g. "3 consecutive failures via probe: connection refused". */
|
||||
function unhealthyTitle(health: AdminTargetHealthView): string {
|
||||
const failWord = health.consecutiveFailures === 1 ? 'failure' : 'failures'
|
||||
const sourcePart = health.source ? ` via ${health.source}` : ''
|
||||
const base = `${health.consecutiveFailures} consecutive ${failWord}${sourcePart}`
|
||||
return health.lastError ? `${base}: ${health.lastError}` : base
|
||||
}
|
||||
|
||||
/** healthyTitle is the muted "healthy" text's hover detail — "Ns ago via probe/traffic" — omitting whichever half (relative time, source) the response does not carry. */
|
||||
function healthyTitle(health: AdminTargetHealthView): string {
|
||||
const ago = formatElapsedAgo(health.lastCheck)
|
||||
if (!ago) return health.source ? `via ${health.source}` : ''
|
||||
return health.source ? `${ago} via ${health.source}` : ago
|
||||
}
|
||||
|
||||
/**
|
||||
* unknownTitle renders the "unknown" badge's hover detail. F4
|
||||
* (feat/target-health) reads "unknown" two different ways — see
|
||||
* AdminTargetHealthView's own doc comment (types/api.ts): never observed
|
||||
* at all, which gets the generic UNKNOWN_HEALTH_TITLE, or observed but
|
||||
* never yet succeeded (still below failureThreshold), which carries real
|
||||
* failure detail (consecutiveFailures/source/lastError) even though the
|
||||
* label stays "unknown" — this surfaces that detail instead of the
|
||||
* generic message, mirroring unhealthyTitle's own conditional shape.
|
||||
*/
|
||||
function unknownTitle(health: AdminTargetHealthView): string {
|
||||
if (health.consecutiveFailures <= 0 && !health.lastError) return UNKNOWN_HEALTH_TITLE
|
||||
const failWord = health.consecutiveFailures === 1 ? 'failure' : 'failures'
|
||||
const sourcePart = health.source ? ` via ${health.source}` : ''
|
||||
const base = `${health.consecutiveFailures} ${failWord} so far${sourcePart}`
|
||||
return health.lastError ? `${base}: ${health.lastError}` : base
|
||||
}
|
||||
|
||||
/**
|
||||
* healthCell renders one row's health column: destructive Badge for
|
||||
* unhealthy, muted plain text (plus " · " and formatLatencyMs when
|
||||
* latencyMs is known) for the explicit healthy case, and an outline
|
||||
* "unknown" Badge as the FALLBACK for everything else — not the reverse
|
||||
* — so a state value this webui build does not recognize renders as
|
||||
* "unknown" rather than silently reading as healthy.
|
||||
*/
|
||||
function healthCell(health: AdminTargetHealthView) {
|
||||
if (health.state === 'unhealthy') {
|
||||
return h(
|
||||
Badge,
|
||||
{ as: 'span', variant: 'destructive', class: 'font-normal', title: unhealthyTitle(health) },
|
||||
() => unhealthyLabel(health),
|
||||
)
|
||||
}
|
||||
if (health.state === 'healthy') {
|
||||
const latencyPart = health.latencyMs !== undefined ? ` · ${formatLatencyMs(health.latencyMs)}` : ''
|
||||
return h('span', { class: 'text-muted-foreground', title: healthyTitle(health) }, `healthy${latencyPart}`)
|
||||
}
|
||||
return h(Badge, { as: 'span', variant: 'outline', class: 'font-normal', title: unknownTitle(health) }, () => 'unknown')
|
||||
}
|
||||
|
||||
/**
|
||||
* targetColumns builds the shared TanStack `ColumnDef` set both the MCP
|
||||
* servers and the Agents DataTable in TargetsView.vue use (admin.go:
|
||||
* adminTargetView — the two tables share one identical row shape). name is
|
||||
* plain text (not the ModelChip copy treatment — a target name is not a
|
||||
* routable model id) UNLESS `onSelect` is given, in which case it renders
|
||||
* as a real `<button>` (same structural convention as EntityLink.vue: a
|
||||
* click opens that target's own caller breakdown, TargetCallers.vue,
|
||||
* rather than navigating away — redesign-plan.md section 3.4's
|
||||
* "TargetCallers.vue expander"). url is muted and truncated with a title
|
||||
* attribute for the full value; health is the Badge/muted-text pair
|
||||
* healthCell above builds (feat/target-health); access renders as a
|
||||
* Badge per allowed group, or a muted "All groups" when unrestricted —
|
||||
* the exact idiom ConsumerDirectory.vue's own group Access block already
|
||||
* established (Providers/Models/MCP servers/Agents dt/dd pairs there).
|
||||
*/
|
||||
export function targetColumns(onSelect?: (target: AdminTargetView) => void): ColumnDef<AdminTargetView, unknown>[] {
|
||||
return [
|
||||
{
|
||||
id: 'name',
|
||||
header: 'Name',
|
||||
accessorFn: (t) => t.name,
|
||||
cell: ({ row }) => {
|
||||
if (!onSelect) return h('span', { class: 'font-medium' }, row.original.name)
|
||||
return h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class:
|
||||
'cursor-pointer rounded-sm font-medium hover:text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',
|
||||
title: `View ${row.original.name}'s callers`,
|
||||
onClick: (event: MouseEvent) => {
|
||||
event.stopPropagation()
|
||||
onSelect(row.original)
|
||||
},
|
||||
},
|
||||
row.original.name,
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'url',
|
||||
header: 'URL',
|
||||
accessorFn: (t) => t.url,
|
||||
cell: ({ row }) =>
|
||||
h(
|
||||
'span',
|
||||
{ class: 'block max-w-xs truncate text-muted-foreground', title: row.original.url },
|
||||
row.original.url,
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'health',
|
||||
header: 'Health',
|
||||
// No natural sort order across three semantic states (healthy/
|
||||
// unhealthy/unknown) — plain alphabetical would put "healthy" and
|
||||
// "unhealthy" beside each other for the wrong reason. Same call the
|
||||
// access column below makes for its own non-primitive shape.
|
||||
enableSorting: false,
|
||||
accessorFn: (t) => t.health.state,
|
||||
cell: ({ row }) => healthCell(row.original.health),
|
||||
},
|
||||
{
|
||||
id: 'access',
|
||||
header: 'Access',
|
||||
enableSorting: false,
|
||||
accessorFn: (t) => (t.access ?? []).join(', '),
|
||||
cell: ({ row }) => {
|
||||
const access = row.original.access
|
||||
// null/absent = every group; [] = no group (admin.go adminTargetView.Access).
|
||||
if (access == null) return h('span', { class: 'text-muted-foreground' }, 'All groups')
|
||||
if (access.length === 0) return h('span', { class: 'text-muted-foreground' }, 'No groups')
|
||||
return h(
|
||||
'div',
|
||||
{ class: 'flex flex-wrap gap-1.5' },
|
||||
access.map((name) => h(Badge, { key: name, as: 'span', variant: 'secondary', class: 'font-mono font-normal' }, () => name)),
|
||||
)
|
||||
},
|
||||
},
|
||||
compactColumn<AdminTargetView>('reqMin', 'req/min', (t) => t.counters.requestsPerMinute),
|
||||
compactColumn<AdminTargetView>('reqDay', 'req/day', (t) => t.counters.requestsPerDay),
|
||||
compactColumn<AdminTargetView>('reqMonth', 'req/month', (t) => t.counters.requestsPerMonth),
|
||||
]
|
||||
}
|
||||
|
||||
// --- target x caller (redesign-plan.md section 3.4's "TargetCallers.vue
|
||||
// expander" + "top callers" card) ---
|
||||
//
|
||||
// GET /admin/api/usage/totals?kind=targetcaller (redesign-plan.md section
|
||||
// 1.3.v) has no dedicated row type in types/api.ts — AdminTotalsResponse
|
||||
// inlines its row shape rather than naming it, so `TargetCallerRow` is
|
||||
// derived from that response's own `rows` element type here (single source
|
||||
// of truth: a future field added to the inline shape needs no second edit
|
||||
// in this file).
|
||||
type TargetCallerRow = AdminTotalsResponse['rows'][number]
|
||||
import type { AdminTargetsResponse } from '@/types/api'
|
||||
|
||||
export type TargetKind = 'mcp' | 'agent'
|
||||
|
||||
@@ -278,42 +102,3 @@ export function parseTargetCallerId(id: string): ParsedTargetCallerId {
|
||||
if (second === -1) return { kind, target: rest, caller: '' }
|
||||
return { kind, target: rest.slice(0, second), caller: rest.slice(second + 1) }
|
||||
}
|
||||
|
||||
/**
|
||||
* targetCallerColumns builds the shared TanStack `ColumnDef` set
|
||||
* TargetCallers.vue's DataTable uses for both its modes: a single
|
||||
* target's own caller breakdown (`showTarget: false` — the panel's own
|
||||
* heading already names the target) and the fleet-wide "top callers" card
|
||||
* (`showTarget: true` — each row's own target is not implied by anything
|
||||
* else on screen). `requests` is the only metric the server returns for
|
||||
* this kind (contract: "targetcaller req only"), so there is no metric
|
||||
* picker here, unlike model-table-columns.ts's multi-metric table.
|
||||
*/
|
||||
export function targetCallerColumns(showTarget: boolean): ColumnDef<TargetCallerRow, unknown>[] {
|
||||
const columns: ColumnDef<TargetCallerRow, unknown>[] = []
|
||||
if (showTarget) {
|
||||
columns.push({
|
||||
id: 'target',
|
||||
header: 'Target',
|
||||
accessorFn: (row) => {
|
||||
const p = parseTargetCallerId(row.id)
|
||||
return `${p.kind}/${p.target}`
|
||||
},
|
||||
cell: ({ row }) => {
|
||||
const p = parseTargetCallerId(row.original.id)
|
||||
return h('span', { class: 'font-mono text-xs text-muted-foreground' }, `${p.kind}/${p.target}`)
|
||||
},
|
||||
})
|
||||
}
|
||||
columns.push({
|
||||
id: 'caller',
|
||||
header: 'Caller',
|
||||
accessorFn: (row) => parseTargetCallerId(row.id).caller || row.id,
|
||||
cell: ({ row }) => {
|
||||
const caller = parseTargetCallerId(row.original.id).caller
|
||||
return h('span', { class: 'font-medium' }, caller || row.original.id)
|
||||
},
|
||||
})
|
||||
columns.push(compactColumn<TargetCallerRow>('requests', 'Requests', (row) => row.values.req ?? 0))
|
||||
return columns
|
||||
}
|
||||
|
||||
@@ -1,323 +0,0 @@
|
||||
import type { VNode } from 'vue'
|
||||
import { isVNode } from 'vue'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import EntityLink from '@/components/EntityLink.vue'
|
||||
import { usageColumns } from './usage-columns'
|
||||
import type { AdminUsageEntryView } from '@/types/api'
|
||||
|
||||
/**
|
||||
* Compact-number rendering (feature v0.23 addendum) must land ONLY in
|
||||
* each numeric column's cell renderer, never in its accessorFn — the
|
||||
* accessorFn is what getSortedRowModel actually sorts by, so a compacted
|
||||
* STRING there ("15.0M") would sort lexicographically instead of
|
||||
* numerically. These tests exercise the ColumnDef objects directly
|
||||
* (no table mount needed) to pin that separation.
|
||||
*/
|
||||
function testEntry(overrides: Partial<AdminUsageEntryView> = {}): AdminUsageEntryView {
|
||||
return {
|
||||
kind: 'user',
|
||||
id: 'alice',
|
||||
requestsPerMinute: 5,
|
||||
requestsPerDay: 15_000_000,
|
||||
tokensInPerDay: 999,
|
||||
tokensOutPerDay: 0,
|
||||
tokensInPerMonth: 0,
|
||||
tokensOutPerMonth: 0,
|
||||
costPerDayMicroUsd: 1_234_500,
|
||||
costPerMonthMicroUsd: 0,
|
||||
rejectionsPerDay: 0,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* accessorFnOf narrows a plain `ColumnDef` (a union of accessor/display
|
||||
* column shapes TypeScript does not narrow automatically) down to the
|
||||
* `accessorFn` every numericColumn-built column in this test file
|
||||
* actually carries — a thin, test-local cast, not a production type.
|
||||
*/
|
||||
function accessorFnOf(col: unknown): (row: AdminUsageEntryView, index: number) => unknown {
|
||||
return (col as { accessorFn: (row: AdminUsageEntryView, index: number) => unknown }).accessorFn
|
||||
}
|
||||
|
||||
function cellOf(col: unknown): (ctx: { row: { original: AdminUsageEntryView } }) => unknown {
|
||||
return (col as { cell: (ctx: { row: { original: AdminUsageEntryView } }) => unknown }).cell
|
||||
}
|
||||
|
||||
describe('usageColumns: sorting stays on raw numeric values', () => {
|
||||
const columns = usageColumns('Name', 'Group', () => 'g')
|
||||
|
||||
it('a count column (reqDay) accessorFn returns the raw number, not a compact string', () => {
|
||||
const col = columns.find((c) => c.id === 'reqDay')
|
||||
expect(accessorFnOf(col)(testEntry(), 0)).toBe(15_000_000)
|
||||
})
|
||||
|
||||
it('a count column cell renders a CompactNumber vnode, not the raw number as text, when no limit is configured', () => {
|
||||
const col = columns.find((c) => c.id === 'reqDay')
|
||||
const rendered = cellOf(col)({ row: { original: testEntry() } })
|
||||
expect(isVNode(rendered)).toBe(true)
|
||||
})
|
||||
|
||||
it('a cost column cell still renders plain formatted text (compact:false), not a CompactNumber vnode, when no limit is configured', () => {
|
||||
const col = columns.find((c) => c.id === 'costDay')
|
||||
const rendered = cellOf(col)({ row: { original: testEntry() } })
|
||||
expect(isVNode(rendered)).toBe(false)
|
||||
expect(rendered).toBe('$1.2345')
|
||||
})
|
||||
|
||||
it('a storeDown row still masks every count cell as "?" regardless of compact rendering', () => {
|
||||
const col = columns.find((c) => c.id === 'tokInDay')
|
||||
const rendered = cellOf(col)({ row: { original: testEntry({ storeDown: true }) } })
|
||||
expect(rendered).toBe('?')
|
||||
})
|
||||
|
||||
// Review finding: TanStack's getAutoSortingFn only inspects rows 11+
|
||||
// (RowSorting.js's own `flatRows.slice(10)`) to auto-detect numeric vs.
|
||||
// string sorting, so a Groups table with 10 or fewer rows silently fell
|
||||
// back to `basic` (plain string a > b comparison), sorting "10" before "9".
|
||||
// An explicit sortingFn sidesteps that row-count-dependent auto-detection
|
||||
// entirely.
|
||||
it('the secondary (Members/Group) column declares an explicit sortingFn, not left to row-count-dependent auto-detection', () => {
|
||||
const col = columns.find((c) => c.id === 'secondary')
|
||||
expect((col as { sortingFn?: string }).sortingFn).toBe('alphanumeric')
|
||||
})
|
||||
|
||||
it('sorting a set of entries by reqDay orders numerically, not lexicographically (the bug this separation prevents)', () => {
|
||||
const col = columns.find((c) => c.id === 'reqDay')
|
||||
const accessor = accessorFnOf(col)
|
||||
const entries = [testEntry({ id: 'a', requestsPerDay: 15_000_000 }), testEntry({ id: 'b', requestsPerDay: 999 }), testEntry({ id: 'c', requestsPerDay: 12_000 })]
|
||||
const sorted = [...entries].sort((x, y) => (accessor(x, 0) as number) - (accessor(y, 0) as number))
|
||||
expect(sorted.map((e) => e.id)).toEqual(['b', 'c', 'a'])
|
||||
// A lexicographic sort on the COMPACT TEXT would instead order
|
||||
// "1,000+" digits, "12k", "15.0M" as strings ("12k" < "15.0M" <
|
||||
// "999" alphabetically) — the wrong order, which is exactly why
|
||||
// accessorFn must stay numeric.
|
||||
})
|
||||
})
|
||||
|
||||
// F1 (usage-vs-limit bars): a column built with limitOf renders a UsageBar
|
||||
// beside its number ONLY when the row's own limit is actually configured
|
||||
// and the row is not storeDown — no fabricated bar for an unlimited scope.
|
||||
describe('usageColumns: F1 usage-vs-limit bars', () => {
|
||||
const columns = usageColumns('Name', 'Group', () => 'g')
|
||||
|
||||
it('reqDay renders a bare CompactNumber vnode, no bar, when the row has no limit configured', () => {
|
||||
const col = columns.find((c) => c.id === 'reqDay')
|
||||
const rendered = cellOf(col)({ row: { original: testEntry() } }) as VNode
|
||||
expect(rendered.type).not.toBe('span')
|
||||
})
|
||||
|
||||
it('reqDay wraps the number with a UsageBar when the row has that limit configured', () => {
|
||||
const col = columns.find((c) => c.id === 'reqDay')
|
||||
const entry = testEntry({ limits: { requestsPerDay: 100 }, requestsPerDay: 40 })
|
||||
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
|
||||
expect(isVNode(rendered)).toBe(true)
|
||||
expect(rendered.type).toBe('span')
|
||||
const children = rendered.children as VNode[]
|
||||
expect(children).toHaveLength(2)
|
||||
expect(children[1].props?.ratio).toBeCloseTo(0.4)
|
||||
})
|
||||
|
||||
it('the token-day columns measure the bar against the COMBINED in+out total, not each column\'s own individual count', () => {
|
||||
const col = columns.find((c) => c.id === 'tokInDay')
|
||||
const entry = testEntry({ limits: { tokensPerDay: 1000 }, tokensInPerDay: 300, tokensOutPerDay: 400 })
|
||||
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
|
||||
const children = rendered.children as VNode[]
|
||||
expect(children[1].props?.ratio).toBeCloseTo(0.7)
|
||||
})
|
||||
|
||||
it('a cost column converts its USD limit to micro-USD before computing the ratio', () => {
|
||||
const col = columns.find((c) => c.id === 'costDay')
|
||||
const entry = testEntry({ limits: { costPerDayUSD: 1 }, costPerDayMicroUsd: 250_000 })
|
||||
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
|
||||
const children = rendered.children as VNode[]
|
||||
expect(children[1].props?.ratio).toBeCloseTo(0.25)
|
||||
})
|
||||
|
||||
it('renders no bar for a storeDown row even when a limit is configured', () => {
|
||||
const col = columns.find((c) => c.id === 'reqDay')
|
||||
const entry = testEntry({ limits: { requestsPerDay: 100 }, storeDown: true })
|
||||
expect(cellOf(col)({ row: { original: entry } })).toBe('?')
|
||||
})
|
||||
|
||||
// P10 review fix: the token columns' bar must announce the COMBINED
|
||||
// in+out measurement it actually shows, not the column's own single-
|
||||
// direction header text — a screen-reader user has no other column
|
||||
// beside it to infer that from, unlike a sighted reader.
|
||||
it('the tokIn/day column\'s bar label spells out "tokens (in+out)/day", not the column header "tokIn/day"', () => {
|
||||
const col = columns.find((c) => c.id === 'tokInDay')
|
||||
const entry = testEntry({ limits: { tokensPerDay: 1000 }, tokensInPerDay: 300, tokensOutPerDay: 400 })
|
||||
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
|
||||
const children = rendered.children as VNode[]
|
||||
expect(children[1].props?.label).toBe('tokens (in+out)/day')
|
||||
})
|
||||
|
||||
it('the tokOut/month column\'s bar label spells out "tokens (in+out)/month"', () => {
|
||||
const col = columns.find((c) => c.id === 'tokOutMonth')
|
||||
const entry = testEntry({ limits: { tokensPerMonth: 1000 }, tokensInPerMonth: 300, tokensOutPerMonth: 400 })
|
||||
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
|
||||
const children = rendered.children as VNode[]
|
||||
expect(children[1].props?.label).toBe('tokens (in+out)/month')
|
||||
})
|
||||
|
||||
it('the req/day column\'s bar label is "req/day" (matches its own header — no in+out ambiguity there)', () => {
|
||||
const col = columns.find((c) => c.id === 'reqDay')
|
||||
const entry = testEntry({ limits: { requestsPerDay: 100 }, requestsPerDay: 40 })
|
||||
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
|
||||
const children = rendered.children as VNode[]
|
||||
expect(children[1].props?.label).toBe('req/day')
|
||||
})
|
||||
|
||||
// P11 review fix: numericColumn now reuses budgetRatios (lib/usage-bars.ts)
|
||||
// instead of its own dropped limitOf/usdLimitMicros — a cost limit that
|
||||
// rounds to 0 micro-USD is skipped (no bar, no Infinity/NaN ratio),
|
||||
// exactly like Go, rather than the column's old independent conversion
|
||||
// disagreeing with budgetRatios about it.
|
||||
it('costDay renders no bar (skips, does not divide by 0) when the configured limit rounds to 0 micro-USD', () => {
|
||||
const col = columns.find((c) => c.id === 'costDay')
|
||||
const entry = testEntry({ limits: { costPerDayUSD: 0.0000001 }, costPerDayMicroUsd: 5 })
|
||||
const rendered = cellOf(col)({ row: { original: entry } })
|
||||
expect(isVNode(rendered)).toBe(false) // plain formatted text, not a UsageBar-wrapping span
|
||||
})
|
||||
})
|
||||
|
||||
// F6 (EntityLink id cell): the id column renders an EntityLink pointed at
|
||||
// Consumers?user={id}, never a plain span — the click-through-to-detail
|
||||
// affordance every Users/Members row gets.
|
||||
describe('usageColumns: F6 id cell is an EntityLink', () => {
|
||||
const columns = usageColumns('Name', 'Group', () => 'g')
|
||||
const col = columns.find((c) => c.id === 'id')
|
||||
|
||||
it('renders an EntityLink vnode, not a plain span', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testEntry({ id: 'alice', kind: 'user' }) } }) as VNode
|
||||
expect(rendered.type).toBe(EntityLink)
|
||||
})
|
||||
|
||||
it('builds kind "user" and the row id, with the label matching', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testEntry({ id: 'alice', kind: 'user' }) } }) as VNode
|
||||
expect(rendered.props?.kind).toBe('user')
|
||||
expect(rendered.props?.id).toBe('alice')
|
||||
expect(rendered.props?.label).toBe('alice')
|
||||
})
|
||||
|
||||
it('is not masked by storeDown — the link stays clickable even for a row with stale/unknown counters', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testEntry({ id: 'alice', kind: 'user', storeDown: true }) } }) as VNode
|
||||
expect(rendered.type).toBe(EntityLink)
|
||||
})
|
||||
})
|
||||
|
||||
describe('usageColumns: last seen column', () => {
|
||||
const now = new Date(Date.UTC(2026, 3, 16, 12, 0, 0))
|
||||
const columns = usageColumns('Name', 'Group', () => 'g', now)
|
||||
const col = columns.find((c) => c.id === 'lastSeen')
|
||||
|
||||
it('accessorFn reads the raw unix-seconds value, defaulting to 0 when unset', () => {
|
||||
expect(accessorFnOf(col)(testEntry(), 0)).toBe(0)
|
||||
expect(accessorFnOf(col)(testEntry({ lastSeen: 123 }), 0)).toBe(123)
|
||||
})
|
||||
|
||||
it('cell renders "never" when unset', () => {
|
||||
expect(cellOf(col)({ row: { original: testEntry() } })).toBe('never')
|
||||
})
|
||||
|
||||
it('cell renders a relative-time label when set', () => {
|
||||
const seconds = Math.floor(now.getTime() / 1000) - 300
|
||||
expect(cellOf(col)({ row: { original: testEntry({ lastSeen: seconds }) } })).toBe('5m ago')
|
||||
})
|
||||
|
||||
it('is NOT masked by storeDown — lastSeen is its own counter family, independent of the usage counters storeDown guards', () => {
|
||||
const seconds = Math.floor(now.getTime() / 1000) - 300
|
||||
expect(cellOf(col)({ row: { original: testEntry({ lastSeen: seconds, storeDown: true }) } })).toBe('5m ago')
|
||||
})
|
||||
})
|
||||
|
||||
describe('usageColumns: optional source column', () => {
|
||||
it('is absent when no sourceValue is passed', () => {
|
||||
const columns = usageColumns('Name', 'Group', () => 'g')
|
||||
expect(columns.find((c) => c.id === 'source')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('is inserted right after the secondary column when sourceValue is passed', () => {
|
||||
const columns = usageColumns('Name', 'Group', () => 'g', new Date(), (e) => (e.id === 'alice' ? 'inline' : undefined))
|
||||
const ids = columns.map((c) => c.id)
|
||||
expect(ids.indexOf('source')).toBe(ids.indexOf('secondary') + 1)
|
||||
})
|
||||
|
||||
it('renders the resolved source text', () => {
|
||||
const columns = usageColumns('Name', 'Group', () => 'g', new Date(), (e) => (e.id === 'alice' ? 'inline' : undefined))
|
||||
const col = columns.find((c) => c.id === 'source')
|
||||
const rendered = cellOf(col)({ row: { original: testEntry({ id: 'alice' }) } }) as VNode
|
||||
expect(rendered.children).toBe('inline')
|
||||
})
|
||||
|
||||
it('renders an em dash when the lookup returns undefined (no matching /consumers entry)', () => {
|
||||
const columns = usageColumns('Name', 'Group', () => 'g', new Date(), () => undefined)
|
||||
const col = columns.find((c) => c.id === 'source')
|
||||
const rendered = cellOf(col)({ row: { original: testEntry({ id: 'bob' }) } }) as VNode
|
||||
expect(rendered.children).toBe('—')
|
||||
})
|
||||
})
|
||||
|
||||
// F4 (rejected/day column): destructive tint applies only once the count
|
||||
// is actually positive — a healthy scope (0 rejections) renders plain,
|
||||
// matching every other "nothing to show reads as no flag" indicator in
|
||||
// this panel (ProviderHealthPanel.vue's badges).
|
||||
describe('usageColumns: F4 rejected/day column', () => {
|
||||
const columns = usageColumns('Name', 'Group', () => 'g')
|
||||
const col = columns.find((c) => c.id === 'rejDay')
|
||||
|
||||
it('accessorFn reads the raw rejectionsPerDay number', () => {
|
||||
expect(accessorFnOf(col)(testEntry({ rejectionsPerDay: 12 }), 0)).toBe(12)
|
||||
})
|
||||
|
||||
it('renders no destructive class when rejectionsPerDay is 0', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testEntry({ rejectionsPerDay: 0 }) } }) as VNode
|
||||
expect(rendered.props?.class).toBeUndefined()
|
||||
})
|
||||
|
||||
it('renders a destructive class when rejectionsPerDay is positive', () => {
|
||||
const rendered = cellOf(col)({ row: { original: testEntry({ rejectionsPerDay: 3 }) } }) as VNode
|
||||
expect(rendered.props?.class).toBe('text-destructive')
|
||||
})
|
||||
|
||||
it('masks as "?" for a storeDown row', () => {
|
||||
expect(cellOf(col)({ row: { original: testEntry({ storeDown: true }) } })).toBe('?')
|
||||
})
|
||||
})
|
||||
|
||||
// F7 (cost forecast per row): costMonthProjColumn extrapolates each row's
|
||||
// own costPerMonthMicroUsd against the SAME `now` every row in one
|
||||
// usageColumns() call shares — passed in explicitly so this stays
|
||||
// deterministic under test (coordinator brief: "now passed as prop for
|
||||
// determinism").
|
||||
describe('usageColumns: F7 cost/month (proj.) column', () => {
|
||||
// Fixed at exactly the midpoint of a UTC 30-day month (April 2026) so
|
||||
// elapsedFraction is a clean 0.5 — projectMonthEnd(mtd, 0.5) == mtd*2.
|
||||
const now = new Date(Date.UTC(2026, 3, 16, 0, 0, 0))
|
||||
const columns = usageColumns('Name', 'Group', () => 'g', now)
|
||||
const col = columns.find((c) => c.id === 'costMonthProj')
|
||||
|
||||
it('renders the projected month-end cost, formatted', () => {
|
||||
const entry = testEntry({ costPerMonthMicroUsd: 5_000_000 })
|
||||
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
|
||||
expect(rendered.children).toBe('$10.0000')
|
||||
})
|
||||
|
||||
it('renders a destructive class + title when the projection exceeds the configured cost/month limit', () => {
|
||||
const entry = testEntry({ costPerMonthMicroUsd: 5_000_000, limits: { costPerMonthUSD: 8 } })
|
||||
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
|
||||
expect(rendered.props?.class).toBe('text-destructive')
|
||||
expect(rendered.props?.title).toMatch(/exceed/)
|
||||
})
|
||||
|
||||
it('renders no destructive class when the projection stays under the limit', () => {
|
||||
const entry = testEntry({ costPerMonthMicroUsd: 5_000_000, limits: { costPerMonthUSD: 20 } })
|
||||
const rendered = cellOf(col)({ row: { original: entry } }) as VNode
|
||||
expect(rendered.props?.class).toBeUndefined()
|
||||
})
|
||||
|
||||
it('masks as "?" for a storeDown row', () => {
|
||||
expect(cellOf(col)({ row: { original: testEntry({ storeDown: true }) } })).toBe('?')
|
||||
})
|
||||
})
|
||||
@@ -1,274 +0,0 @@
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import { h } from 'vue'
|
||||
|
||||
import CompactNumber from '@/components/CompactNumber.vue'
|
||||
import EntityLink from '@/components/EntityLink.vue'
|
||||
import UsageBar from '@/components/UsageBar.vue'
|
||||
import { EMPTY_CELL } from '@/lib/columns'
|
||||
import { monthCostProjection, NOT_ENOUGH_DATA, WILL_EXCEED_TITLE } from '@/lib/forecast'
|
||||
import { formatCost, formatExactInt, formatLimits } from '@/lib/format'
|
||||
import { formatLastSeen } from '@/lib/last-seen'
|
||||
import { BUDGET_RATIO_LABEL, budgetRatios } from '@/lib/usage-bars'
|
||||
import type { AdminUsageEntryView } from '@/types/api'
|
||||
|
||||
/**
|
||||
* numericColumn builds one right-aligned, sortable numeric column that
|
||||
* reads '?' instead of a stale number while the entry's own scope has a
|
||||
* down store — DataTable.vue's cell renderer, not the accessor, does this
|
||||
* check, so sorting itself still uses the entry's real underlying value
|
||||
* (a storeDown row sorts by its last-known number, same as the rest of
|
||||
* the table; only the DISPLAYED text is masked). Mirrors the pre-DataTable
|
||||
* UsageTable.vue template's own `entry.storeDown ? '?' : ...` convention.
|
||||
*
|
||||
* compact (default true) renders the value through CompactNumber (SI-
|
||||
* style, with the exact figure on title/aria-label) instead of the plain
|
||||
* `format`/String path — used for every raw token/request COUNT column
|
||||
* below; the two cost columns pass compact:false, since formatCost
|
||||
* already shows full precision and compacting a dollar figure is not
|
||||
* this feature's concern. The accessorFn (and therefore sorting) always
|
||||
* reads the true raw number either way — only the cell's rendered text
|
||||
* changes.
|
||||
*
|
||||
* F1 (usage-vs-limit bars): `budgetId` optionally names WHICH
|
||||
* lib/usage-bars.ts BudgetRatio this column illustrates (one of
|
||||
* budgetRatios' own ids — "reqMin", "reqDay", "tokDay", "tokMonth",
|
||||
* "costDay", "costMonth"). When the row is not storeDown and
|
||||
* budgetRatios(row) actually contains that id (i.e. the scope has that
|
||||
* limit configured), the cell renders a UsageBar beside the number.
|
||||
*
|
||||
* P11 review fix (DRY + correctness): this used to take its own
|
||||
* `limitOf`/`usedOf` accessor pair and re-derive the USD->micro-USD
|
||||
* conversion locally (a dropped usdLimitMicros helper) — a second,
|
||||
* independent implementation of exactly what budgetRatios already computes,
|
||||
* and one that disagreed with it: budgetRatios gated on the RAW USD value
|
||||
* being truthy before rounding (a limit rounding to 0 micro-USD produced an
|
||||
* Infinity/NaN ratio there), while this column's own usdLimitMicros rounded
|
||||
* first — the two could show a bar in one place, mask it in the other, for
|
||||
* the identical scope. Reusing budgetRatios here (now fixed to round-then-
|
||||
* skip, matching Go — see that module's own doc comment) makes both paths
|
||||
* agree by construction: there is only one ratio computation left, not two.
|
||||
*
|
||||
* BUDGET_RATIO_LABEL[budgetId] (P10 review fix), not the column's own
|
||||
* `header`, backs the bar's accessible label: the token columns'
|
||||
* "tokDay"/"tokMonth" ratio combines BOTH directions
|
||||
* (budgetRatios' own doc comment), so the bar's aria-label spells out
|
||||
* "tokens (in+out)/day" — the column HEADER stays "tokIn/day"/"tokOut/day"
|
||||
* (that identity is real and worth keeping visually), but a screen-reader
|
||||
* user hearing just "tokIn/day, 1,500 / 2,000" beside a cell showing 500
|
||||
* has no other cue that the meter measures the combined total, not that
|
||||
* column's own count.
|
||||
*/
|
||||
function numericColumn(
|
||||
id: string,
|
||||
header: string,
|
||||
read: (entry: AdminUsageEntryView) => number,
|
||||
format: (n: number) => string = String,
|
||||
compact = true,
|
||||
budgetId?: string,
|
||||
): ColumnDef<AdminUsageEntryView, unknown> {
|
||||
return {
|
||||
id,
|
||||
header,
|
||||
accessorFn: read,
|
||||
meta: { align: 'right' },
|
||||
cell: ({ row }) => {
|
||||
if (row.original.storeDown) return '?'
|
||||
const value = read(row.original)
|
||||
const valueNode = compact ? h(CompactNumber, { value }) : format(value)
|
||||
if (!budgetId) return valueNode
|
||||
const ratio = budgetRatios(row.original).find((r) => r.id === budgetId)
|
||||
if (!ratio) return valueNode
|
||||
const valueText = compact
|
||||
? `${formatExactInt(ratio.used)} / ${formatExactInt(ratio.limit)}`
|
||||
: `${format(ratio.used)} / ${format(ratio.limit)}`
|
||||
return h('span', { class: 'inline-flex items-center justify-end gap-1.5' }, [
|
||||
valueNode,
|
||||
h(UsageBar, { ratio: ratio.ratio, label: BUDGET_RATIO_LABEL[budgetId] ?? header, valueText }),
|
||||
])
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* rejDayColumn (F4) renders rejectionsPerDay — fleet-wide requests denied
|
||||
* by a limit check today (types/api.ts's own doc comment). Not built via
|
||||
* numericColumn: it needs a destructive tint whenever the count is
|
||||
* positive at all (coordinator brief: "destructive tint when > 0"),
|
||||
* independent of any configured limit/bar — a rejection count itself IS
|
||||
* the signal, there is nothing to compare it against.
|
||||
*/
|
||||
function rejDayColumn(): ColumnDef<AdminUsageEntryView, unknown> {
|
||||
return {
|
||||
id: 'rejDay',
|
||||
header: 'rejected/day',
|
||||
accessorFn: (entry) => entry.rejectionsPerDay,
|
||||
meta: { align: 'right' },
|
||||
cell: ({ row }) => {
|
||||
if (row.original.storeDown) return '?'
|
||||
const value = row.original.rejectionsPerDay
|
||||
return h(CompactNumber, { value, class: value > 0 ? 'text-destructive' : undefined })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* costMonthProjColumn (F7) renders lib/forecast.ts's projected month-end
|
||||
* cost for each row, extrapolated from that row's own costPerMonthMicroUsd
|
||||
* — the same math CostForecastCard.vue applies to the Total entry, here
|
||||
* applied per user/group so an operator can see WHICH scope is on track
|
||||
* to blow its own cost/month limit, not just the fleet-wide total. Reuses
|
||||
* lib/forecast.ts's own monthCostProjection (F7's one projection+headroom
|
||||
* pairing) rather than calling projectMonthEnd/headroom separately here —
|
||||
* the same helper ConsumerDirectory.vue's groupCostProjection and lib/
|
||||
* usage-csv.ts's own CSV row call.
|
||||
*
|
||||
* `now` is threaded in from the caller (coordinator brief: "now passed as
|
||||
* prop for determinism") rather than read via `new Date()` inside this
|
||||
* module — usageColumns() takes it as an optional parameter, defaulting
|
||||
* to the real current time for every production call site, so a test can
|
||||
* pin it instead.
|
||||
*/
|
||||
function costMonthProjColumn(now: Date): ColumnDef<AdminUsageEntryView, unknown> {
|
||||
return {
|
||||
id: 'costMonthProj',
|
||||
header: 'cost/month (proj.)',
|
||||
meta: { align: 'right' },
|
||||
// Sorting: a not-enough-data-yet row (null projection) has no real
|
||||
// figure to compare — it sorts as if projected to 0, the smallest
|
||||
// possible spend, rather than being excluded from sorting entirely.
|
||||
accessorFn: (entry) => monthCostProjection(entry, now).micros ?? 0,
|
||||
cell: ({ row }) => {
|
||||
if (row.original.storeDown) return '?'
|
||||
const projection = monthCostProjection(row.original, now)
|
||||
if (projection.micros === null) return h('span', { class: 'text-muted-foreground' }, NOT_ENOUGH_DATA)
|
||||
return h(
|
||||
'span',
|
||||
{
|
||||
class: projection.willExceed ? 'text-destructive' : undefined,
|
||||
title: projection.willExceed ? WILL_EXCEED_TITLE : undefined,
|
||||
},
|
||||
formatCost(projection.micros),
|
||||
)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* sourceColumn (Consumers redesign, redesign-plan.md section 3.4) renders
|
||||
* a user's directory source — 'inline' (defined directly in the plugin
|
||||
* config) or 'file' (loaded from users.file, admin.go: adminConsumerUser.
|
||||
* Source) — via the caller-supplied `sourceValue` lookup (ConsumerDirectory.
|
||||
* vue joins this row's id against the /admin/api/consumers response, which
|
||||
* this module has no fetch access to itself). Only ever added when a
|
||||
* caller passes `sourceValue` to usageColumns (see its own doc comment) —
|
||||
* a group row (no such concept) and the headless Groups sort toolbar never
|
||||
* get this column at all. `sourceValue` returning undefined (a group's
|
||||
* nested member row whose name has no matching /consumers entry yet, e.g.
|
||||
* mid-fetch) renders an em dash rather than blank, so the column never
|
||||
* looks like a rendering bug.
|
||||
*/
|
||||
function sourceColumn(sourceValue: (entry: AdminUsageEntryView) => string | undefined): ColumnDef<AdminUsageEntryView, unknown> {
|
||||
return {
|
||||
id: 'source',
|
||||
header: 'Source',
|
||||
accessorFn: (entry) => sourceValue(entry) ?? '',
|
||||
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, sourceValue(row.original) ?? EMPTY_CELL),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* lastSeenColumn (Consumers redesign) renders AdminUsageEntryView.lastSeen
|
||||
* via lib/last-seen.ts's formatLastSeen — added unconditionally (unlike
|
||||
* sourceColumn above): lastSeen is a fleet-wide counter written for BOTH
|
||||
* user and group scopes (redesign-plan.md section 1.2's last-seen family:
|
||||
* "user + every group scope"), so it is meaningful in every context
|
||||
* usageColumns() is used in, not just the flat Users table. A storeDown
|
||||
* row is NOT masked as "?" here (unlike every numericColumn) — lastSeen is
|
||||
* its own separate counter family (a SET, not the same INCRBY scope
|
||||
* counters storeDown actually guards), so a down usage store does not
|
||||
* make this value stale/unknown the way it does for req/tok/cost.
|
||||
*/
|
||||
function lastSeenColumn(now: Date): ColumnDef<AdminUsageEntryView, unknown> {
|
||||
return {
|
||||
id: 'lastSeen',
|
||||
header: 'Last seen',
|
||||
accessorFn: (entry) => entry.lastSeen ?? 0,
|
||||
cell: ({ row }) => formatLastSeen(row.original.lastSeen, now),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* usageColumns builds the shared TanStack `ColumnDef` set for one
|
||||
* AdminUsageEntryView table. Used by UsageTable.vue (the flat Users list,
|
||||
* and — reused unmodified — a group's nested member-user list inside
|
||||
* ConsumerDirectory.vue's Groups accordion) and, headlessly (no `<Table>`
|
||||
* render, see that component's own doc comment for why), by its Groups
|
||||
* sort bar, so both surfaces sort by the exact same column semantics.
|
||||
* idLabel/secondaryColumnLabel name the first two columns; secondaryValue
|
||||
* reads the second column's per-row value (a user's group name, or a
|
||||
* group's member count). `now` (F7) defaults to the real current time —
|
||||
* see costMonthProjColumn's own doc comment for why a caller can override
|
||||
* it. `sourceValue`, when supplied, inserts sourceColumn right after the
|
||||
* secondary column — ConsumerDirectory.vue's flat Users table is the only
|
||||
* caller that passes it (see sourceColumn's own doc comment).
|
||||
*/
|
||||
export function usageColumns(
|
||||
idLabel: string,
|
||||
secondaryColumnLabel: string,
|
||||
secondaryValue: (entry: AdminUsageEntryView) => string,
|
||||
now: Date = new Date(),
|
||||
sourceValue?: (entry: AdminUsageEntryView) => string | undefined,
|
||||
): ColumnDef<AdminUsageEntryView, unknown>[] {
|
||||
const columns: ColumnDef<AdminUsageEntryView, unknown>[] = [
|
||||
{
|
||||
id: 'id',
|
||||
header: idLabel,
|
||||
accessorFn: (entry) => entry.id,
|
||||
// EntityLink (redesign-plan.md section 3.5, replacing ScopeLink):
|
||||
// this column only ever renders 'user' kind entries in practice —
|
||||
// UsageTable.vue's own doc comment ("users, or a group's member
|
||||
// users") — so it links straight to Consumers?user={id}, opening
|
||||
// that row's own UserDetail, rather than a Charts scope jump.
|
||||
cell: ({ row }) => h(EntityLink, { class: 'font-medium', label: row.original.id, kind: 'user', id: row.original.id }),
|
||||
},
|
||||
{
|
||||
id: 'secondary',
|
||||
header: secondaryColumnLabel,
|
||||
accessorFn: secondaryValue,
|
||||
// 'alphanumeric' (not the default auto-detected sortingFn): this
|
||||
// column's value is a plain string everywhere EXCEPT the Groups
|
||||
// toolbar, where ConsumerDirectory.vue passes memberCountOf — a
|
||||
// numeric count rendered as a string. TanStack's getAutoSortingFn
|
||||
// only inspects rows 11+ (flatRows.slice(10)) to decide numeric vs
|
||||
// basic, so a groups table with 10 or fewer rows silently fell back
|
||||
// to `basic` (plain a > b string comparison), sorting "10" before
|
||||
// "9". 'alphanumeric' handles both cases correctly regardless of row
|
||||
// count: numeric substrings compare numerically, and it degrades
|
||||
// gracefully for the plain-text group-name case (secondaryValue on
|
||||
// the Users table).
|
||||
sortingFn: 'alphanumeric',
|
||||
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, secondaryValue(row.original)),
|
||||
},
|
||||
]
|
||||
if (sourceValue) columns.push(sourceColumn(sourceValue))
|
||||
columns.push(
|
||||
{
|
||||
id: 'limits',
|
||||
header: 'Limits',
|
||||
accessorFn: (entry) => formatLimits(entry.limits),
|
||||
cell: ({ row }) => h('span', { class: 'text-muted-foreground' }, formatLimits(row.original.limits)),
|
||||
},
|
||||
numericColumn('reqMin', 'req/min', (e) => e.requestsPerMinute, String, true, 'reqMin'),
|
||||
numericColumn('reqDay', 'req/day', (e) => e.requestsPerDay, String, true, 'reqDay'),
|
||||
rejDayColumn(),
|
||||
numericColumn('tokInDay', 'tokIn/day', (e) => e.tokensInPerDay, String, true, 'tokDay'),
|
||||
numericColumn('tokOutDay', 'tokOut/day', (e) => e.tokensOutPerDay, String, true, 'tokDay'),
|
||||
numericColumn('tokInMonth', 'tokIn/month', (e) => e.tokensInPerMonth, String, true, 'tokMonth'),
|
||||
numericColumn('tokOutMonth', 'tokOut/month', (e) => e.tokensOutPerMonth, String, true, 'tokMonth'),
|
||||
numericColumn('costDay', 'cost/day', (e) => e.costPerDayMicroUsd, formatCost, false, 'costDay'),
|
||||
numericColumn('costMonth', 'cost/month', (e) => e.costPerMonthMicroUsd, formatCost, false, 'costMonth'),
|
||||
costMonthProjColumn(now),
|
||||
lastSeenColumn(now),
|
||||
)
|
||||
return columns
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { groupMatches, groupNameMatches, matchingMembersOfGroup, membersOfGroup, userMatches } from './usage-search'
|
||||
import type { AdminUsageEntryView } from '@/types/api'
|
||||
|
||||
/** entry builds a minimal AdminUsageEntryView — only id/groupName/groups matter to this module, the rest are never read. */
|
||||
function entry(id: string, groupName?: string, groups?: string[]): AdminUsageEntryView {
|
||||
return {
|
||||
kind: groupName === undefined ? 'group' : 'user',
|
||||
id,
|
||||
groupName,
|
||||
groups,
|
||||
requestsPerMinute: 0,
|
||||
requestsPerDay: 0,
|
||||
tokensInPerDay: 0,
|
||||
tokensOutPerDay: 0,
|
||||
tokensInPerMonth: 0,
|
||||
tokensOutPerMonth: 0,
|
||||
costPerDayMicroUsd: 0,
|
||||
costPerMonthMicroUsd: 0,
|
||||
rejectionsPerDay: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const alice = entry('alice', 'team-a')
|
||||
const bob = entry('bob', 'team-a')
|
||||
const carol = entry('carol', 'team-b')
|
||||
const teamA = entry('team-a')
|
||||
const teamB = entry('team-b')
|
||||
const users = [alice, bob, carol]
|
||||
|
||||
describe('userMatches', () => {
|
||||
it('matches a case-insensitive substring of the id (query pre-lowercased by the caller)', () => {
|
||||
expect(userMatches(alice, 'lic')).toBe(true)
|
||||
})
|
||||
|
||||
it('does not match an unrelated query', () => {
|
||||
expect(userMatches(alice, 'zzz')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('groupNameMatches', () => {
|
||||
it('matches on the group id alone, ignoring members entirely', () => {
|
||||
expect(groupNameMatches(teamA, 'team-a')).toBe(true)
|
||||
})
|
||||
|
||||
it('does not match a query that only a member would match', () => {
|
||||
expect(groupNameMatches(teamA, 'alice')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('membersOfGroup', () => {
|
||||
it('joins users to a group on groupName === group.id', () => {
|
||||
expect(membersOfGroup(teamA, users)).toEqual([alice, bob])
|
||||
expect(membersOfGroup(teamB, users)).toEqual([carol])
|
||||
})
|
||||
|
||||
// Multi-group support (review finding 4): a user's full membership lives
|
||||
// in `groups` (admin.go's adminUsageEntryView.Groups); groupName alone
|
||||
// only ever carries the FIRST one. Before this fix, membersOfGroup's
|
||||
// `groupName === group.id` join silently dropped a multi-group user from
|
||||
// every group but their first.
|
||||
it('joins a multi-group user into EVERY one of their member groups via `groups`, not just groupName', () => {
|
||||
const dave = entry('dave', 'team-a', ['team-a', 'team-b'])
|
||||
const roster = [alice, bob, carol, dave]
|
||||
|
||||
expect(membersOfGroup(teamA, roster)).toEqual([alice, bob, dave])
|
||||
expect(membersOfGroup(teamB, roster)).toEqual([carol, dave])
|
||||
})
|
||||
|
||||
it('falls back to [groupName] when `groups` is absent (a single-group user, or a fixture predating the field)', () => {
|
||||
expect(membersOfGroup(teamA, users)).toEqual([alice, bob])
|
||||
})
|
||||
})
|
||||
|
||||
describe('matchingMembersOfGroup', () => {
|
||||
it('returns only the group members that themselves match query', () => {
|
||||
expect(matchingMembersOfGroup(teamA, users, 'alice')).toEqual([alice])
|
||||
})
|
||||
|
||||
it('returns an empty array when no member matches', () => {
|
||||
expect(matchingMembersOfGroup(teamA, users, 'zzz')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('groupMatches', () => {
|
||||
it('matches via the group’s own name, with no matching member', () => {
|
||||
expect(groupMatches(teamA, users, 'team-a')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches via a member, with no name match', () => {
|
||||
expect(groupMatches(teamA, users, 'alice')).toBe(true)
|
||||
})
|
||||
|
||||
it('does not match when neither the name nor any member matches', () => {
|
||||
expect(groupMatches(teamA, users, 'zzz')).toBe(false)
|
||||
})
|
||||
|
||||
it('a group with no members only matches by name', () => {
|
||||
const lonely = entry('lonely-group')
|
||||
expect(groupMatches(lonely, users, 'lonely')).toBe(true)
|
||||
expect(groupMatches(lonely, users, 'alice')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,68 +0,0 @@
|
||||
import type { AdminUsageEntryView } from '@/types/api'
|
||||
|
||||
/**
|
||||
* Shared matching helpers for the "Filter users or groups" search
|
||||
* ConsumerDirectory.vue offers (operator directive: identical semantics,
|
||||
* ONE implementation — no second copy of this logic; extracted here
|
||||
* rather than left inline specifically because the pre-redesign Usage
|
||||
* AND Charts tabs both needed the identical matching rules before this
|
||||
* module existed).
|
||||
*
|
||||
* Every `query` parameter here is expected to already be trimmed and
|
||||
* lowercased by the caller, mirroring ProviderHealthPanel.vue's own
|
||||
* normalizedQuery convention (modelMatches/aliasMatches there never
|
||||
* re-normalize either) — these functions stay pure string/array
|
||||
* operations, with the caller owning the single source of truth for "is a
|
||||
* query active at all".
|
||||
*/
|
||||
|
||||
/** userMatches: a user matches when its own id (display name) contains query. */
|
||||
export function userMatches(user: Pick<AdminUsageEntryView, 'id'>, query: string): boolean {
|
||||
return user.id.toLowerCase().includes(query)
|
||||
}
|
||||
|
||||
/** groupNameMatches: a group matches by its own id (display name) alone, ignoring its members. */
|
||||
export function groupNameMatches(group: Pick<AdminUsageEntryView, 'id'>, query: string): boolean {
|
||||
return group.id.toLowerCase().includes(query)
|
||||
}
|
||||
|
||||
/**
|
||||
* membersOfGroup: group's own member user rows, joined on group.id being
|
||||
* one of the user's own member groups — a user's row carries its full
|
||||
* membership in `groups` (admin.go's adminUsageEntryView.Groups, multi-group
|
||||
* support) and falls back to the single-group `groupName` for a user
|
||||
* predating that field (or a mock/fixture that only sets groupName). Never
|
||||
* `groupName` alone: a multi-group user would otherwise silently drop out
|
||||
* of every group but their first. This is a plain client-side join against
|
||||
* the already-polled GET /admin/api/usage response, no extra fetch.
|
||||
* ConsumerDirectory.vue calls this directly (replacing the pre-redesign
|
||||
* Usage tab's own former local membersOf helper); matchingMembersOfGroup
|
||||
* below builds on it too, which is how ConsumerDirectory.vue's own
|
||||
* groupMatches call ends up depending on this same join — indirectly,
|
||||
* through matchingMembersOfGroup — without calling membersOfGroup itself.
|
||||
*/
|
||||
export function membersOfGroup(group: Pick<AdminUsageEntryView, 'id'>, users: AdminUsageEntryView[]): AdminUsageEntryView[] {
|
||||
return users.filter((u) => (u.groups ?? [u.groupName]).includes(group.id))
|
||||
}
|
||||
|
||||
/** matchingMembersOfGroup: group's own members that themselves match query. */
|
||||
export function matchingMembersOfGroup(
|
||||
group: Pick<AdminUsageEntryView, 'id'>,
|
||||
users: AdminUsageEntryView[],
|
||||
query: string,
|
||||
): AdminUsageEntryView[] {
|
||||
return membersOfGroup(group, users).filter((u) => userMatches(u, query))
|
||||
}
|
||||
|
||||
/**
|
||||
* groupMatches: a group matches if its own name contains query OR it has
|
||||
* at least one matching member (binding search semantics). Callers that
|
||||
* need to distinguish WHICH of the two reasons a group matched — to decide
|
||||
* whether to show all of its members or only the matching ones — use
|
||||
* groupNameMatches and matchingMembersOfGroup directly instead (see
|
||||
* ConsumerDirectory.vue's own memberOnlyMatchIds doc comment for that
|
||||
* distinction).
|
||||
*/
|
||||
export function groupMatches(group: Pick<AdminUsageEntryView, 'id'>, users: AdminUsageEntryView[], query: string): boolean {
|
||||
return groupNameMatches(group, query) || matchingMembersOfGroup(group, users, query).length > 0
|
||||
}
|
||||
+2
-6
@@ -1,17 +1,13 @@
|
||||
import { config } from '@fortawesome/fontawesome-svg-core'
|
||||
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
|
||||
import { useThemeStore } from '@perfect-design/ui'
|
||||
import { createPinia } from 'pinia'
|
||||
import { createApp } from 'vue'
|
||||
|
||||
import App from '@/App.vue'
|
||||
import FaIcon from '@/components/FaIcon.vue'
|
||||
import '@/assets/main.css'
|
||||
import { messageOf } from '@/lib/api'
|
||||
import { useToastsStore } from '@/stores/toasts'
|
||||
|
||||
// The admin CSP is style-src 'self': FontAwesome's runtime <style> injection is blocked, so its CSS ships in the bundle instead.
|
||||
config.autoAddCss = false
|
||||
|
||||
const app = createApp(App)
|
||||
const pinia = createPinia()
|
||||
app.use(pinia)
|
||||
@@ -23,5 +19,5 @@ app.config.errorHandler = (err) => {
|
||||
const theme = useThemeStore(pinia)
|
||||
theme.init()
|
||||
theme.setStyle('workbench')
|
||||
app.component('FontAwesomeIcon', FontAwesomeIcon)
|
||||
app.component('FontAwesomeIcon', FaIcon)
|
||||
app.mount('#app')
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
import AccessMatrix from '@/components/AccessMatrix.vue'
|
||||
import ConsumerDirectory from '@/components/ConsumerDirectory.vue'
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import UserDetail from '@/components/UserDetail.vue'
|
||||
import { parseMatrixKind } from '@/lib/access-matrix'
|
||||
import type { MatrixKind } from '@/lib/access-matrix'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
/**
|
||||
* ConsumersPage (redesign-plan.md section 3.4) is the Consumers page's own
|
||||
* router: `user=<name>` (set by an EntityLink kind="user" click anywhere in
|
||||
* the panel) opens UserDetail; otherwise `view=directory|matrix` (default
|
||||
* directory) switches between ConsumerDirectory and AccessMatrix, and
|
||||
* (P4 three-view split) `matrix=models|mcp|agents` (default models) picks
|
||||
* AccessMatrix's own column-group tab. All three params live in nav.params
|
||||
* (stores/nav.ts's own opaque per-page record), never a private local ref —
|
||||
* a bookmarked/shared #consumers?user=... link must restore the same view.
|
||||
*/
|
||||
const nav = useNavStore()
|
||||
|
||||
const userParam = computed(() => nav.params.user)
|
||||
const view = computed<'directory' | 'matrix'>(() => (nav.params.view === 'matrix' ? 'matrix' : 'directory'))
|
||||
const matrixKind = computed<MatrixKind>(() => parseMatrixKind(nav.params.matrix))
|
||||
|
||||
function setView(next: unknown): void {
|
||||
if (next !== 'directory' && next !== 'matrix') return
|
||||
const { user: _user, ...rest } = nav.params
|
||||
nav.goTo('users', { ...rest, view: next })
|
||||
}
|
||||
|
||||
/**
|
||||
* setMatrixKind writes the AccessMatrix Tabs selection into nav.params:
|
||||
* omit `matrix` when 'models'; `view` is always written.
|
||||
*/
|
||||
function setMatrixKind(next: MatrixKind): void {
|
||||
const { user: _user, matrix: _matrix, ...rest } = nav.params
|
||||
if (next === 'models') {
|
||||
nav.goTo('users', { ...rest, view: 'matrix' })
|
||||
return
|
||||
}
|
||||
nav.goTo('users', { ...rest, view: 'matrix', matrix: next })
|
||||
}
|
||||
|
||||
function closeUserDetail(): void {
|
||||
const { user: _user, ...rest } = nav.params
|
||||
nav.goTo('users', rest)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UserDetail v-if="userParam" :user-id="userParam" @close="closeUserDetail" />
|
||||
<div v-else class="flex flex-col gap-4">
|
||||
<Tabs :model-value="view" @update:model-value="setView">
|
||||
<TabsList>
|
||||
<TabsTrigger value="directory">Directory</TabsTrigger>
|
||||
<TabsTrigger value="matrix">Access matrix</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<ConsumerDirectory v-if="view === 'directory'" />
|
||||
<AccessMatrix v-else :kind="matrixKind" @update:kind="setMatrixKind" />
|
||||
</div>
|
||||
</template>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user