mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
feat(webui): perfect-design app shell, command palette and theme boot
This commit is contained in:
+1
-1
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<html lang="en" data-style="workbench">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<!-- Inline data: URI, not a file under public/: admin.go's asset map only
|
||||
|
||||
+25
-20
@@ -3,7 +3,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import type { Plugin } from 'vite'
|
||||
import type { Connect, Plugin } from 'vite'
|
||||
|
||||
import type { Fixture } from './match.ts'
|
||||
import { respond } from './respond.ts'
|
||||
@@ -24,33 +24,38 @@ const header = (req: IncomingMessage, name: string) => {
|
||||
return Array.isArray(v) ? v[0] : v
|
||||
}
|
||||
|
||||
/** Vite plugin serving /admin/api/* from the captured fixtures; dev server only, enabled by MOCK=1 in vite.config.ts. */
|
||||
/** Vite plugin serving /admin/api/* from the captured fixtures; dev and preview servers only, enabled by MOCK=1 in vite.config.ts. */
|
||||
export function mockAdminApi(): Plugin {
|
||||
const manifest = JSON.parse(readFileSync(join(HERE, 'manifest.json'), 'utf8')) as Fixture[]
|
||||
const readFixture = (file: string) => JSON.parse(readFileSync(join(HERE, 'fixtures', file), 'utf8')) as unknown
|
||||
const handle = async (req: Connect.IncomingMessage, res: ServerResponse) => {
|
||||
const url = new URL(req.originalUrl ?? req.url ?? '/', 'http://mock.local')
|
||||
const scenarios = parseScenarios(header(req, 'referer'), header(req, 'x-mock-scenario'))
|
||||
if (req.method !== 'GET') return send(res, 405, errorEnvelope(405, 'invalid_request_error', 'method not allowed'))
|
||||
const hasKey = (header(req, 'x-api-key') ?? '').trim() !== ''
|
||||
const out = respond({
|
||||
manifest,
|
||||
readFixture,
|
||||
path: url.pathname,
|
||||
query: url.searchParams,
|
||||
scenarios: hasKey ? scenarios : [...scenarios, 'auth-401'],
|
||||
now: Date.now(),
|
||||
rng: Math.random,
|
||||
})
|
||||
const delay = scenarioDelayMs(scenarios)
|
||||
if (delay > 0) await new Promise((r) => setTimeout(r, delay))
|
||||
send(res, out.status, out.body)
|
||||
}
|
||||
return {
|
||||
name: 'mock-admin-api',
|
||||
apply: 'serve',
|
||||
configureServer(server) {
|
||||
server.middlewares.use(API_PREFIX, async (req, res) => {
|
||||
const url = new URL(req.originalUrl ?? req.url ?? '/', 'http://mock.local')
|
||||
const scenarios = parseScenarios(header(req, 'referer'), header(req, 'x-mock-scenario'))
|
||||
if (req.method !== 'GET') return send(res, 405, errorEnvelope(405, 'invalid_request_error', 'method not allowed'))
|
||||
const hasKey = (header(req, 'x-api-key') ?? '').trim() !== ''
|
||||
const out = respond({
|
||||
manifest,
|
||||
readFixture,
|
||||
path: url.pathname,
|
||||
query: url.searchParams,
|
||||
scenarios: hasKey ? scenarios : [...scenarios, 'auth-401'],
|
||||
now: Date.now(),
|
||||
rng: Math.random,
|
||||
})
|
||||
const delay = scenarioDelayMs(scenarios)
|
||||
if (delay > 0) await new Promise((r) => setTimeout(r, delay))
|
||||
send(res, out.status, out.body)
|
||||
})
|
||||
server.middlewares.use(API_PREFIX, handle)
|
||||
server.config.logger.info(` mock admin API active (scenarios via ?mock=a,b)`)
|
||||
},
|
||||
// `vite preview` of a built dist (CSP checks) serves the same fixtures.
|
||||
configurePreviewServer(server) {
|
||||
server.middlewares.use(API_PREFIX, handle)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+15
@@ -12,6 +12,7 @@
|
||||
"@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",
|
||||
@@ -964,6 +965,20 @@
|
||||
"url": "https://github.com/sponsors/Boshen"
|
||||
}
|
||||
},
|
||||
"node_modules/@perfect-design/ui": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://github.com/lukaszraczylo/perfect-design/releases/download/v0.4.0/perfect-design-ui-0.4.0.tgz",
|
||||
"integrity": "sha512-iAAW2L6ZckwzHUa72bvQkIQjtYTgVBZ5XhH7FMIRQ0zD99G7F7DMgoD8zwomR1tIxkZETNYFzA3lVU50bG30zQ==",
|
||||
"dependencies": {
|
||||
"reka-ui": "^2.5.0",
|
||||
"tailwind-merge": "^3.3.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"pinia": "^3.0.0 || ^4.0.0",
|
||||
"tailwindcss": "^4.1.0",
|
||||
"vue": "^3.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-android-arm-eabi": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.5.tgz",
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"@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",
|
||||
|
||||
+17
-98
@@ -1,27 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
import type { Component } from 'vue'
|
||||
import { faGithub } from '@fortawesome/free-brands-svg-icons'
|
||||
import { faCircleExclamation } from '@fortawesome/free-solid-svg-icons'
|
||||
import { computed, defineAsyncComponent, onMounted, watch } from 'vue'
|
||||
|
||||
import AuthGate from '@/components/AuthGate.vue'
|
||||
import ConfigWarningsBanner from '@/components/ConfigWarningsBanner.vue'
|
||||
import PageLoadError from '@/components/PageLoadError.vue'
|
||||
import GlobalFilterBar from '@/components/GlobalFilterBar.vue'
|
||||
import SidebarNav from '@/components/SidebarNav.vue'
|
||||
import ToastViewport from '@/components/ToastViewport.vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useHashState } from '@/composables/useHashState'
|
||||
import AppLayout from '@/layout/AppLayout.vue'
|
||||
import type { PageId } from '@/lib/pages'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
import { resetSessionData } from '@/stores/session'
|
||||
|
||||
/** The module path (go.mod / .traefik.yml `import:`) — same repo the plugin ships from, so this is the one canonical URL rather than a guess. */
|
||||
const GITHUB_REPO_URL = 'https://github.com/lukaszraczylo/traefik-llmgateway'
|
||||
|
||||
const auth = useAuthStore()
|
||||
const dashboard = useDashboardStore()
|
||||
const nav = useNavStore()
|
||||
@@ -49,43 +41,22 @@ function lazyPage(loader: () => Promise<Component>): Component {
|
||||
return defineAsyncComponent({ loader, errorComponent: PageLoadError, timeout: 30_000 })
|
||||
}
|
||||
|
||||
// Legacy pages stand in until their redesigned replacements land: routers
|
||||
// still lives inside the Models page and events inside Reliability.
|
||||
const PAGES: Record<PageId, Component> = {
|
||||
home: lazyPage(() => import('@/pages/HomePage.vue')),
|
||||
spend: lazyPage(() => import('@/pages/SpendPage.vue')),
|
||||
consumers: lazyPage(() => import('@/pages/ConsumersPage.vue')),
|
||||
models: lazyPage(() => import('@/pages/ModelsPage.vue')),
|
||||
overview: lazyPage(() => import('@/pages/HomePage.vue')),
|
||||
usage: lazyPage(() => import('@/pages/SpendPage.vue')),
|
||||
reliability: lazyPage(() => import('@/pages/ReliabilityPage.vue')),
|
||||
config: lazyPage(() => import('@/pages/ConfigPage.vue')),
|
||||
users: lazyPage(() => import('@/pages/ConsumersPage.vue')),
|
||||
models: lazyPage(() => import('@/pages/ModelsPage.vue')),
|
||||
routers: lazyPage(() => import('@/pages/ModelsPage.vue')),
|
||||
targets: lazyPage(() => import('@/pages/TargetsPage.vue')),
|
||||
events: lazyPage(() => import('@/pages/ReliabilityPage.vue')),
|
||||
config: lazyPage(() => import('@/pages/ConfigPage.vue')),
|
||||
}
|
||||
|
||||
const currentPage = computed<Component>(() => PAGES[nav.page])
|
||||
|
||||
// statusText reads dashboard.error/lastUpdated unconditionally — it is
|
||||
// correct only while the template's own `v-if="auth.isAuthenticated"`
|
||||
// below keeps it off-screen otherwise, so a first load with no stored
|
||||
// key never shows a stale "refresh failed" line under the auth gate.
|
||||
// Appended only on a genuinely successful poll — dashboard.overview.
|
||||
// replica reflects WHICH replica answered that poll, so it must never be
|
||||
// shown alongside a stale value during a failed or still-loading refresh.
|
||||
// The unreachable 'loading...' fallback (verify-ui-states.md #5 fix) was
|
||||
// dead code: isInitialStatusLoad below covers exactly
|
||||
// `!dashboard.error && !dashboard.lastUpdated`, the ONLY state in which
|
||||
// neither of this function's two `if` branches fires, and the template
|
||||
// renders the Skeleton for that state instead of ever reading statusText.
|
||||
const statusText = computed<string>(() => {
|
||||
if (dashboard.error) {
|
||||
const age = dashboard.lastUpdated ? ` · data from ${dashboard.lastUpdated.toLocaleTimeString()}` : ''
|
||||
return `refresh failed: ${dashboard.error}${age}`
|
||||
}
|
||||
const replica = dashboard.overview?.replica
|
||||
const updated = dashboard.lastUpdated?.toLocaleTimeString() ?? ''
|
||||
return `last updated ${updated}${replica ? ` · replica ${replica}` : ''}`
|
||||
})
|
||||
|
||||
/** isInitialStatusLoad gates the header status line's skeleton — the FIRST dashboard poll only (states-plan.md item 1: a skeleton only when there is no data yet, never on a background refresh — dashboard.lastUpdated stays set through every later poll, success or failure). */
|
||||
const isInitialStatusLoad = computed<boolean>(() => !dashboard.error && !dashboard.lastUpdated)
|
||||
|
||||
// A different key may carry different privileges, so never keep the previous key's data on screen.
|
||||
watch(
|
||||
() => auth.apiKey,
|
||||
@@ -100,65 +71,13 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex w-full flex-col gap-4 px-4 py-6 sm:px-6 lg:px-8">
|
||||
<header class="flex flex-col gap-3">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<h1 class="text-xl font-semibold tracking-tight">LLM Gateway — Admin</h1>
|
||||
<Button
|
||||
as="a"
|
||||
:href="GITHUB_REPO_URL"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="GitHub repository"
|
||||
class="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<FontAwesomeIcon :icon="faGithub" class="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
<!--
|
||||
No role="status" here (verify-ui-states.md #5 fix) — this line
|
||||
updates every 5s (dashboard.ts's POLL_MS), and a live region
|
||||
re-announces its FULL text on every single change; a screen
|
||||
reader would have read "last updated HH:MM:SS" once every 5
|
||||
seconds for as long as the session stayed open. A background
|
||||
refresh FAILURE (the one change actually worth announcing) is
|
||||
already a "meaningful change" a screen reader hears from
|
||||
elsewhere: stores/dashboard.ts's own toast (states-plan.md item 3,
|
||||
"background refresh failures when data is already shown") fires
|
||||
exactly once per failure streak, through ToastViewport's own
|
||||
assertive live region — a second, duplicate announcement here
|
||||
would only repeat it.
|
||||
-->
|
||||
<p v-if="auth.isAuthenticated" class="flex items-center gap-1.5 text-sm text-muted-foreground">
|
||||
<template v-if="isInitialStatusLoad">
|
||||
<Skeleton class="h-4 w-40" />
|
||||
<span class="sr-only">Loading dashboard status…</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<FontAwesomeIcon v-if="dashboard.error" :icon="faCircleExclamation" class="size-3.5 text-destructive" aria-hidden="true" />
|
||||
<span :class="dashboard.error ? 'text-destructive' : undefined">{{ statusText }}</span>
|
||||
</template>
|
||||
</p>
|
||||
<GlobalFilterBar v-if="auth.isAuthenticated" />
|
||||
</header>
|
||||
|
||||
<!-- GET /admin/api/overview's config warnings — renders nothing itself once `warnings` is empty, so this is always safe to mount. -->
|
||||
<ConfigWarningsBanner
|
||||
v-if="auth.isAuthenticated"
|
||||
:warnings="dashboard.overview?.warnings ?? []"
|
||||
:warnings-dropped="dashboard.overview?.warningsDropped"
|
||||
/>
|
||||
|
||||
<AuthGate v-if="!auth.isAuthenticated" />
|
||||
|
||||
<div v-else class="flex flex-col gap-4 md:flex-row">
|
||||
<SidebarNav />
|
||||
<main class="min-w-0 flex-1">
|
||||
<component :is="currentPage" />
|
||||
</main>
|
||||
</div>
|
||||
<div v-if="!auth.isAuthenticated" class="px-4 py-6 sm:px-6 lg:px-8">
|
||||
<AuthGate />
|
||||
</div>
|
||||
<AppLayout v-else>
|
||||
<!-- GET /admin/api/overview's config warnings — renders nothing itself once `warnings` is empty, so this is always safe to mount. -->
|
||||
<ConfigWarningsBanner :warnings="dashboard.overview?.warnings ?? []" :warnings-dropped="dashboard.overview?.warningsDropped" />
|
||||
<component :is="currentPage" />
|
||||
</AppLayout>
|
||||
<ToastViewport />
|
||||
</template>
|
||||
|
||||
+34
-66
@@ -3,8 +3,16 @@
|
||||
@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";
|
||||
|
||||
/*
|
||||
* The base palette (background, primary, border, radius, ...) now comes from
|
||||
* @perfect-design/ui/theme.css; only the chart and status tokens below stay local.
|
||||
* Dark mode follows the `.dark` class that perfect-design's theme store (and its
|
||||
* boot script) maintains on <html>, including the "system" mode.
|
||||
*
|
||||
* Theme tokens (design note, not slop-by-default): shadcn-vue's `init`
|
||||
* scaffolds an achromatic "stone" palette (chroma 0 everywhere), a Google
|
||||
* Fonts Inter import, and a Geist Variable heading font. All three are
|
||||
@@ -73,25 +81,6 @@
|
||||
}
|
||||
|
||||
:root {
|
||||
--background: oklch(0.99 0.004 75);
|
||||
--foreground: oklch(0.19 0.012 75);
|
||||
--card: oklch(0.995 0.003 75);
|
||||
--card-foreground: oklch(0.19 0.012 75);
|
||||
--popover: oklch(0.995 0.003 75);
|
||||
--popover-foreground: oklch(0.19 0.012 75);
|
||||
--primary: oklch(0.46 0.09 200);
|
||||
--primary-foreground: oklch(0.98 0.006 200);
|
||||
--secondary: oklch(0.95 0.006 75);
|
||||
--secondary-foreground: oklch(0.22 0.01 75);
|
||||
--muted: oklch(0.95 0.006 75);
|
||||
--muted-foreground: oklch(0.48 0.012 75);
|
||||
--accent: oklch(0.93 0.02 200);
|
||||
--accent-foreground: oklch(0.28 0.05 200);
|
||||
--destructive: oklch(0.55 0.2 25);
|
||||
--border: oklch(0.9 0.007 75);
|
||||
--input: oklch(0.9 0.007 75);
|
||||
--ring: oklch(0.55 0.09 200);
|
||||
--radius: 0.375rem;
|
||||
|
||||
/* Chart series — Okabe & Ito (2008) colorblind-safe qualitative set. */
|
||||
--chart-requests: #009e73;
|
||||
@@ -158,56 +147,35 @@
|
||||
--bar-amber: #a35c00;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: oklch(0.17 0.007 75);
|
||||
--foreground: oklch(0.95 0.005 75);
|
||||
--card: oklch(0.21 0.009 75);
|
||||
--card-foreground: oklch(0.95 0.005 75);
|
||||
--popover: oklch(0.21 0.009 75);
|
||||
--popover-foreground: oklch(0.95 0.005 75);
|
||||
--primary: oklch(0.74 0.11 200);
|
||||
--primary-foreground: oklch(0.16 0.012 200);
|
||||
--secondary: oklch(0.27 0.011 75);
|
||||
--secondary-foreground: oklch(0.93 0.005 75);
|
||||
--muted: oklch(0.27 0.011 75);
|
||||
--muted-foreground: oklch(0.68 0.012 75);
|
||||
--accent: oklch(0.32 0.035 200);
|
||||
--accent-foreground: oklch(0.91 0.03 200);
|
||||
--destructive: oklch(0.68 0.19 25);
|
||||
--border: oklch(1 0 0 / 12%);
|
||||
--input: oklch(1 0 0 / 16%);
|
||||
--ring: oklch(0.62 0.1 200);
|
||||
.dark {
|
||||
/* Same hues, most already legible on a dark ground at this
|
||||
saturation — Okabe-Ito was designed for slide/print use on light
|
||||
and dark backgrounds alike. */
|
||||
--chart-requests: #16b891;
|
||||
--chart-tokens-in: #4098d7;
|
||||
--chart-tokens-out: #f0ac1f;
|
||||
--chart-cost: #e8763a;
|
||||
|
||||
/* Same hues, most already legible on a dark ground at this
|
||||
saturation — Okabe-Ito was designed for slide/print use on light
|
||||
and dark backgrounds alike. */
|
||||
--chart-requests: #16b891;
|
||||
--chart-tokens-in: #4098d7;
|
||||
--chart-tokens-out: #f0ac1f;
|
||||
--chart-cost: #e8763a;
|
||||
/* Same Okabe-Ito hues as the light-mode block's own doc comment
|
||||
above — already legible on a dark ground at this saturation
|
||||
(Okabe-Ito was designed for slide/print use on light and dark
|
||||
backgrounds alike), so only --chart-series-b's LIGHT value
|
||||
needed darkening; here it keeps the original #f0e442. */
|
||||
--chart-series-a: #56b4e9;
|
||||
--chart-series-b: #f0e442;
|
||||
--chart-series-c: #cc79a7;
|
||||
--chart-series-d: #b8b8b8;
|
||||
|
||||
/* Same Okabe-Ito hues as the light-mode block's own doc comment
|
||||
above — already legible on a dark ground at this saturation
|
||||
(Okabe-Ito was designed for slide/print use on light and dark
|
||||
backgrounds alike), so only --chart-series-b's LIGHT value
|
||||
needed darkening; here it keeps the original #f0e442. */
|
||||
--chart-series-a: #56b4e9;
|
||||
--chart-series-b: #f0e442;
|
||||
--chart-series-c: #cc79a7;
|
||||
--chart-series-d: #b8b8b8;
|
||||
/* #f0ac1f on the dark --card measures ~8.97:1 — no separate dark
|
||||
value was needed to clear WCAG 1.4.3 here, unlike light mode
|
||||
(see --status-warn's own doc comment above), but the token is
|
||||
still redefined per-mode rather than left to fall through, so a
|
||||
reader auditing this block sees every semantic-color token's
|
||||
dark value in one place. */
|
||||
--status-warn: #f0ac1f;
|
||||
|
||||
/* #f0ac1f on the dark --card measures ~8.97:1 — no separate dark
|
||||
value was needed to clear WCAG 1.4.3 here, unlike light mode
|
||||
(see --status-warn's own doc comment above), but the token is
|
||||
still redefined per-mode rather than left to fall through, so a
|
||||
reader auditing this block sees every semantic-color token's
|
||||
dark value in one place. */
|
||||
--status-warn: #f0ac1f;
|
||||
|
||||
/* Same reasoning as --chart-tokens-out's own dark-mode comment above — legible as-is, redefined here anyway so every semantic-color token's dark value lives in one place. */
|
||||
--bar-amber: #f0ac1f;
|
||||
}
|
||||
/* Same reasoning as --chart-tokens-out's own dark-mode comment above — legible as-is, redefined here anyway so every semantic-color token's dark value lives in one place. */
|
||||
--bar-amber: #f0ac1f;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
|
||||
@@ -116,7 +116,7 @@ function sourceOf(entry: AdminUsageEntryView): string | undefined {
|
||||
// the old nav.usageQuery special case.
|
||||
const usageQuery = computed<string>({
|
||||
get: () => nav.params.q ?? '',
|
||||
set: (value) => nav.goTo('consumers', { ...nav.params, q: value }),
|
||||
set: (value) => nav.goTo('users', { ...nav.params, q: value }),
|
||||
})
|
||||
const { query: userQuery, normalized: normalizedQuery, hasQuery } = useSearchQuery(usageQuery)
|
||||
|
||||
|
||||
@@ -47,8 +47,8 @@ const props = defineProps<{
|
||||
const nav = useNavStore()
|
||||
const { isAlias } = useAliasNames()
|
||||
|
||||
const TARGET: Record<'user' | 'model', { page: 'consumers' | 'models'; paramKey: 'user' | 'model'; noun: string }> = {
|
||||
user: { page: 'consumers', paramKey: 'user', noun: 'Consumers' },
|
||||
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' },
|
||||
}
|
||||
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { faArrowRightArrowLeft } from '@fortawesome/free-solid-svg-icons'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
import LabeledSelect from '@/components/LabeledSelect.vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { SCOPE_PATTERN } from '@/lib/hash-state'
|
||||
import { RANGE_KEYS } from '@/lib/range'
|
||||
import type { RangeKey } from '@/lib/range'
|
||||
import { DEFAULT_SCOPE, useFiltersStore } from '@/stores/filters'
|
||||
|
||||
/** RANGE_LABEL is the range Select's display text per lib/range.ts's RangeKey — kept here (not lib/range.ts) since it is pure presentation, not logic a store or another page's fetch needs. */
|
||||
const RANGE_LABEL: Record<RangeKey, string> = {
|
||||
'24h': 'Last 24 hours',
|
||||
'48h': 'Last 48 hours',
|
||||
'7d': 'Last 7 days',
|
||||
'14d': 'Last 14 days',
|
||||
'30d': 'Last 30 days',
|
||||
'3mo': 'Last 3 months',
|
||||
'6mo': 'Last 6 months',
|
||||
'12mo': 'Last 12 months',
|
||||
}
|
||||
const RANGE_OPTIONS = RANGE_KEYS.map((key) => ({ value: key, label: RANGE_LABEL[key] }))
|
||||
|
||||
/**
|
||||
* GlobalFilterBar (redesign-plan.md section 3.1) is the shell's one
|
||||
* control surface for the three global filters (stores/filters.ts):
|
||||
* time range, "vs previous period" comparison, and an optional
|
||||
* group/user/provider scope narrowing. Every page reads the SAME filters
|
||||
* store; this bar is mounted once, in App.vue's header, not per-page.
|
||||
*/
|
||||
const filters = useFiltersStore()
|
||||
|
||||
function onRangeUpdate(value: unknown): void {
|
||||
if (typeof value !== 'string') return
|
||||
filters.setFilters({ range: value as RangeKey })
|
||||
}
|
||||
|
||||
/**
|
||||
* toggleCmp (P3 item 19): turning the comparison OFF is always allowed,
|
||||
* even when the CURRENT range does not support one — a `cmp=prev` value
|
||||
* restored from the hash (e.g. loaded directly onto a 48h/30d/12mo range,
|
||||
* where 2*span exceeds the retention ceiling) used to leave the button
|
||||
* permanently pressed-and-disabled, with no way to turn it off short of
|
||||
* changing the range first. filters.cmpSpec.requested already gates the
|
||||
* actual fetch on availability (stores/filters.ts's own doc comment), so
|
||||
* this was purely a stuck AFFORDANCE, never a bad request. Turning it ON
|
||||
* still requires availability — there is nothing to compare against
|
||||
* otherwise.
|
||||
*/
|
||||
function toggleCmp(): void {
|
||||
if (filters.cmp === 'prev') {
|
||||
filters.setFilters({ cmp: 'none' })
|
||||
return
|
||||
}
|
||||
if (!filters.cmpSpec.available) return
|
||||
filters.setFilters({ cmp: 'prev' })
|
||||
}
|
||||
|
||||
/** cmpDisabled only blocks turning the toggle ON when unavailable — turning an already-on comparison OFF is never blocked (toggleCmp's own doc comment). */
|
||||
const cmpDisabled = computed<boolean>(() => filters.cmp !== 'prev' && !filters.cmpSpec.available)
|
||||
|
||||
const cmpTitle = computed<string>(() => {
|
||||
if (filters.cmp === 'prev' && !filters.cmpSpec.available) {
|
||||
return `Comparison unavailable for this range (${filters.cmpSpec.reason}) — click to turn off`
|
||||
}
|
||||
if (filters.cmpSpec.available) return 'Compare against the previous equal-length period'
|
||||
return `Comparison unavailable for this range: ${filters.cmpSpec.reason}`
|
||||
})
|
||||
|
||||
// scopeDraft is a local editing buffer, not bound straight to
|
||||
// filters.scope: a partially-typed value ("group:") must not spam
|
||||
// setFilters/refetch every store on every keystroke, and an invalid
|
||||
// commit (onBlur/Enter, below) must revert the FIELD, not the store —
|
||||
// the store keeps whatever scope was last valid.
|
||||
const scopeDraft = ref(filters.scope)
|
||||
watch(
|
||||
() => filters.scope,
|
||||
(scope) => {
|
||||
scopeDraft.value = scope
|
||||
},
|
||||
)
|
||||
|
||||
function commitScope(): void {
|
||||
const value = scopeDraft.value.trim() || DEFAULT_SCOPE
|
||||
if (SCOPE_PATTERN.test(value)) {
|
||||
filters.setFilters({ scope: value })
|
||||
} else {
|
||||
// Invalid — revert the field to the store's own current value rather than keeping the bad text on screen.
|
||||
scopeDraft.value = filters.scope
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-wrap items-end gap-3">
|
||||
<LabeledSelect label="Range" :model-value="filters.range" :options="RANGE_OPTIONS" trigger-class="w-36" @update:model-value="onRangeUpdate" />
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
:aria-pressed="filters.cmp === 'prev'"
|
||||
:disabled="cmpDisabled"
|
||||
:title="cmpTitle"
|
||||
@click="toggleCmp"
|
||||
>
|
||||
<FontAwesomeIcon :icon="faArrowRightArrowLeft" class="size-3.5" aria-hidden="true" />
|
||||
vs previous period
|
||||
</Button>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<label for="global-filter-scope" class="text-xs font-medium text-muted-foreground">Scope</label>
|
||||
<Input
|
||||
id="global-filter-scope"
|
||||
v-model="scopeDraft"
|
||||
class="w-48"
|
||||
placeholder="all"
|
||||
title="all, group:<name>, user:<name>, or provider:<name>"
|
||||
@keyup.enter="commitScope"
|
||||
@blur="commitScope"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,40 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { PAGE_NAV } from '@/lib/pages'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
/**
|
||||
* SidebarNav (redesign-plan.md section 3.1) is the shell's primary
|
||||
* navigation: a vertical list of pages on a normal-width viewport,
|
||||
* collapsing to a horizontally-scrollable bar on a narrow one (the
|
||||
* `md:` breakpoint below) rather than a hamburger/drawer — every page is
|
||||
* still one tap away, and the panel is an internal admin tool with no
|
||||
* phone-first audience to justify hiding the list behind an extra tap.
|
||||
*
|
||||
* Real `<button>` elements, not `<a href>` (mirrors EntityLink.vue's own
|
||||
* structural note): activating one is a programmatic Pinia navigation
|
||||
* (nav.goTo), not a traditional link follow, and there is no separate
|
||||
* URL to navigate to server-side — the hash is derived FROM this state
|
||||
* (composables/useHashState.ts), not the other way around.
|
||||
*/
|
||||
const nav = useNavStore()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav
|
||||
aria-label="Primary"
|
||||
class="flex gap-1 overflow-x-auto border-b border-border pb-2 md:w-52 md:shrink-0 md:flex-col md:border-r md:border-b-0 md:pr-3 md:pb-0"
|
||||
>
|
||||
<button
|
||||
v-for="entry in PAGE_NAV"
|
||||
:key="entry.id"
|
||||
type="button"
|
||||
:aria-current="nav.page === entry.id ? 'page' : undefined"
|
||||
class="flex shrink-0 items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium whitespace-nowrap transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 md:w-full"
|
||||
:class="nav.page === entry.id ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:bg-muted hover:text-foreground'"
|
||||
@click="nav.goTo(entry.id)"
|
||||
>
|
||||
<FontAwesomeIcon :icon="entry.icon" class="size-4" aria-hidden="true" />
|
||||
<span>{{ entry.label }}</span>
|
||||
</button>
|
||||
</nav>
|
||||
</template>
|
||||
@@ -20,10 +20,10 @@ import { useNavStore } from '@/stores/nav'
|
||||
* design (stores/nav.ts's own doc comment).
|
||||
* - A single computed re-derives the hash from filters' current state
|
||||
* plus nav.page/nav.params, and writes it back via history.
|
||||
* replaceState whenever it changes — never pushState (one browser-
|
||||
* history entry per admin session, not per click) and never a bare
|
||||
* `location.hash =` assignment (which would also jump scroll position
|
||||
* to any element whose id happens to match).
|
||||
* replaceState whenever it changes, except when nav.pushPending is set
|
||||
* (nav.openPanel): then pushState, so Back closes the panel. Never a
|
||||
* bare `location.hash =` assignment (which would also jump scroll
|
||||
* position to any element whose id happens to match).
|
||||
* - It listens for the browser's own `hashchange` event (back/forward
|
||||
* navigation, or a hand-edited URL) and re-parses from scratch,
|
||||
* reapplying the same restore path as the initial read.
|
||||
@@ -86,9 +86,12 @@ export function useHashState(): void {
|
||||
watch(
|
||||
currentHash,
|
||||
(hash) => {
|
||||
const push = nav.pushPending
|
||||
nav.pushPending = false
|
||||
if (!hasWindow) return
|
||||
if (window.location.hash === hash) return
|
||||
window.history.replaceState(null, '', hash)
|
||||
if (push) window.history.pushState(null, '', hash)
|
||||
else window.history.replaceState(null, '', hash)
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
@@ -10,10 +10,9 @@ import { onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
* only ones this admin panel targets — see vite.config.ts's
|
||||
* modulePreload note for the same reasoning), so no conversion is needed.
|
||||
*
|
||||
* Re-reads on a `prefers-color-scheme` change so an open Charts view
|
||||
* repaints if the OS theme flips while it's on screen — main.css's own
|
||||
* dark-mode block is a plain media query, not a class toggle, so this is
|
||||
* the only way a chart already on screen learns about it.
|
||||
* 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('')
|
||||
@@ -27,14 +26,14 @@ export function useThemeColors() {
|
||||
border.value = style.getPropertyValue('--border').trim()
|
||||
}
|
||||
|
||||
let media: MediaQueryList | undefined
|
||||
let observer: MutationObserver | undefined
|
||||
onMounted(() => {
|
||||
sync()
|
||||
media = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
media.addEventListener('change', sync)
|
||||
observer = new MutationObserver(sync)
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] })
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
media?.removeEventListener('change', sync)
|
||||
observer?.disconnect()
|
||||
})
|
||||
|
||||
return { foreground, mutedForeground, border }
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
<script setup lang="ts">
|
||||
import { faArrowRightArrowLeft, faBars, faMagnifyingGlass } from '@fortawesome/free-solid-svg-icons'
|
||||
import { Button, Icon, Input, Kbd, OfflineIndicator, SegmentedControl, StaleNotice, ThemeToggle } from '@perfect-design/ui'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
import { SCOPE_PATTERN } from '@/lib/hash-state'
|
||||
import { RANGE_KEYS } from '@/lib/range'
|
||||
import type { RangeKey } from '@/lib/range'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { DEFAULT_SCOPE, useFiltersStore } from '@/stores/filters'
|
||||
|
||||
defineProps<{ triggerProps: Record<string, string> }>()
|
||||
const emit = defineEmits<{ toggleSidebar: []; openPalette: [] }>()
|
||||
|
||||
const RANGE_OPTIONS = RANGE_KEYS.map((key) => ({ value: key, label: key }))
|
||||
/** Matches the dashboard store's 5s poll: data older than this means polling has stalled. */
|
||||
const STALE_AFTER_MS = 30_000
|
||||
|
||||
const filters = useFiltersStore()
|
||||
const dashboard = useDashboardStore()
|
||||
|
||||
const cmpDisabled = computed<boolean>(() => filters.cmp !== 'prev' && !filters.cmpSpec.available)
|
||||
const cmpTitle = computed<string>(() => {
|
||||
if (filters.cmp === 'prev' && !filters.cmpSpec.available) {
|
||||
return `Comparison unavailable for this range (${filters.cmpSpec.reason}) — click to turn off`
|
||||
}
|
||||
if (filters.cmpSpec.available) return 'Compare against the previous equal-length period'
|
||||
return `Comparison unavailable for this range: ${filters.cmpSpec.reason}`
|
||||
})
|
||||
|
||||
// A draft buffer: a half-typed scope must not refetch every store per keystroke, and an invalid commit reverts the field only.
|
||||
const scopeDraft = ref(filters.scope)
|
||||
watch(
|
||||
() => filters.scope,
|
||||
(scope) => {
|
||||
scopeDraft.value = scope
|
||||
},
|
||||
)
|
||||
|
||||
function commitScope(): void {
|
||||
const value = String(scopeDraft.value).trim() || DEFAULT_SCOPE
|
||||
if (SCOPE_PATTERN.test(value)) filters.setFilters({ scope: value })
|
||||
else scopeDraft.value = filters.scope
|
||||
}
|
||||
|
||||
function onRange(value: string): void {
|
||||
filters.setFilters({ range: value as RangeKey })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex w-full flex-wrap items-center gap-x-3 gap-y-2 px-3 py-2">
|
||||
<Button variant="ghost" size="sm" class="lg:hidden" aria-label="Toggle navigation" v-bind="triggerProps" @click="emit('toggleSidebar')">
|
||||
<Icon :icon="faBars" size="sm" />
|
||||
</Button>
|
||||
<span class="text-sm font-semibold tracking-tight">LLM Gateway</span>
|
||||
|
||||
<div class="max-w-full overflow-x-auto">
|
||||
<SegmentedControl :model-value="filters.range" :options="RANGE_OPTIONS" size="sm" aria-label="Time range" @update:model-value="onRange" />
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:aria-pressed="filters.cmp === 'prev'"
|
||||
:disabled="cmpDisabled"
|
||||
:title="cmpTitle"
|
||||
@click="filters.toggleCmp()"
|
||||
>
|
||||
<Icon :icon="faArrowRightArrowLeft" size="sm" />
|
||||
vs previous
|
||||
</Button>
|
||||
|
||||
<Input
|
||||
v-model="scopeDraft"
|
||||
size="sm"
|
||||
class="w-40"
|
||||
placeholder="scope: all"
|
||||
aria-label="Scope"
|
||||
title="all, group:<name>, user:<name>, or provider:<name>"
|
||||
@keyup.enter="commitScope"
|
||||
@blur="commitScope"
|
||||
/>
|
||||
|
||||
<div class="ml-auto flex items-center gap-2">
|
||||
<StaleNotice
|
||||
v-if="dashboard.lastUpdated"
|
||||
variant="inline"
|
||||
:timestamp="dashboard.lastUpdated"
|
||||
:stale-after="STALE_AFTER_MS"
|
||||
:refreshing="dashboard.refreshing"
|
||||
refreshable
|
||||
hide-when-fresh
|
||||
@refresh="dashboard.refresh()"
|
||||
/>
|
||||
<OfflineIndicator variant="pill" />
|
||||
<span v-if="dashboard.error" class="text-destructive text-xs" role="status">refresh failed</span>
|
||||
<Button variant="outline" size="sm" aria-label="Open command palette" @click="emit('openPalette')">
|
||||
<Icon :icon="faMagnifyingGlass" size="sm" />
|
||||
<span class="hidden sm:inline">Search</span>
|
||||
<Kbd>⌘K</Kbd>
|
||||
</Button>
|
||||
<ThemeToggle />
|
||||
<span v-if="dashboard.overview?.version" class="text-muted-foreground hidden text-xs md:inline">
|
||||
v{{ dashboard.overview.version }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,65 @@
|
||||
<script setup lang="ts">
|
||||
import { AppShell, SidebarNav, Toaster } from '@perfect-design/ui'
|
||||
import type { SidebarNavGroup } from '@perfect-design/ui'
|
||||
import { useEventListener } from '@vueuse/core'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
import AppHeader from '@/layout/AppHeader.vue'
|
||||
import CommandPalette from '@/layout/CommandPalette.vue'
|
||||
import { NAV_GROUPS, navCounts } from '@/lib/nav-groups'
|
||||
import type { PageId } from '@/lib/pages'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
const nav = useNavStore()
|
||||
const dashboard = useDashboardStore()
|
||||
|
||||
const collapsed = ref(false)
|
||||
const open = ref(false)
|
||||
const paletteOpen = ref(false)
|
||||
|
||||
const counts = computed(() => navCounts(dashboard.overview, dashboard.usage, dashboard.targets))
|
||||
|
||||
const groups = computed<SidebarNavGroup[]>(() =>
|
||||
NAV_GROUPS.map((g, i) => ({
|
||||
id: `group-${i}`,
|
||||
label: g.label ?? undefined,
|
||||
items: g.items.map((item) => ({
|
||||
id: item.id,
|
||||
label: item.label,
|
||||
icon: item.icon,
|
||||
active: nav.page === item.id,
|
||||
badge: item.countKey ? counts.value[item.countKey] : undefined,
|
||||
})),
|
||||
})),
|
||||
)
|
||||
|
||||
useEventListener(window, 'keydown', (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
|
||||
e.preventDefault()
|
||||
paletteOpen.value = !paletteOpen.value
|
||||
}
|
||||
})
|
||||
|
||||
function onNavigate(item: { id?: string }, event: MouseEvent): void {
|
||||
event.preventDefault()
|
||||
if (item.id) nav.goTo(item.id as PageId)
|
||||
open.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppShell v-model:collapsed="collapsed" v-model:open="open" drawer-breakpoint="lg" sidebar-label="Primary">
|
||||
<template #header="{ toggle, triggerProps }">
|
||||
<AppHeader :trigger-props="triggerProps" @toggle-sidebar="toggle" @open-palette="paletteOpen = true" />
|
||||
</template>
|
||||
<template #sidebar>
|
||||
<SidebarNav v-model:collapsed="collapsed" :groups="groups" :current="nav.page" label="Primary" @navigate="onNavigate" />
|
||||
</template>
|
||||
<div class="min-w-0 p-4">
|
||||
<slot />
|
||||
</div>
|
||||
</AppShell>
|
||||
<CommandPalette v-model:open="paletteOpen" />
|
||||
<Toaster />
|
||||
</template>
|
||||
@@ -0,0 +1,100 @@
|
||||
<script setup lang="ts">
|
||||
import { faArrowRightArrowLeft, faClock, faCircleHalfStroke } from '@fortawesome/free-solid-svg-icons'
|
||||
import {
|
||||
CommandDialog,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
Icon,
|
||||
useThemeStore,
|
||||
} from '@perfect-design/ui'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
import { NAV_GROUPS } from '@/lib/nav-groups'
|
||||
import { paletteEntities } from '@/lib/palette-items'
|
||||
import { PANEL_PAGE } from '@/lib/panel-selection'
|
||||
import type { PanelKind } from '@/lib/panel-selection'
|
||||
import { RANGE_KEYS } from '@/lib/range'
|
||||
import { useDashboardStore } from '@/stores/dashboard'
|
||||
import { useFiltersStore } from '@/stores/filters'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
const open = defineModel<boolean>('open', { default: false })
|
||||
|
||||
const nav = useNavStore()
|
||||
const filters = useFiltersStore()
|
||||
const dashboard = useDashboardStore()
|
||||
const theme = useThemeStore()
|
||||
|
||||
const search = ref('')
|
||||
const pages = NAV_GROUPS.flatMap((g) => g.items)
|
||||
const entities = computed(() => paletteEntities(dashboard.overview, dashboard.usage, dashboard.targets))
|
||||
|
||||
/** Runs an action, then closes the palette and resets the query. */
|
||||
function run(action: () => void): void {
|
||||
action()
|
||||
open.value = false
|
||||
search.value = ''
|
||||
}
|
||||
|
||||
function openEntity(kind: PanelKind, id: string): void {
|
||||
run(() => {
|
||||
nav.goTo(PANEL_PAGE[kind])
|
||||
nav.openPanel(kind, id)
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<CommandDialog v-model:open="open" v-model:search="search" title="Command palette" description="Jump to a page or entity, or run an action.">
|
||||
<CommandInput placeholder="Search pages, entities and actions" />
|
||||
<CommandList>
|
||||
<CommandEmpty>No matches.</CommandEmpty>
|
||||
<CommandGroup heading="Pages">
|
||||
<CommandItem v-for="p in pages" :key="p.id" :value="`page ${p.label}`" @select="run(() => nav.goTo(p.id))">
|
||||
<Icon :icon="p.icon" size="sm" />
|
||||
{{ p.label }}
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
<CommandGroup heading="Range">
|
||||
<CommandItem
|
||||
v-for="r in RANGE_KEYS"
|
||||
:key="r"
|
||||
:value="`range ${r}`"
|
||||
@select="run(() => filters.setFilters({ range: r }))"
|
||||
>
|
||||
<Icon :icon="faClock" size="sm" />
|
||||
Range {{ r }}
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
<CommandGroup heading="Actions">
|
||||
<CommandItem value="action toggle comparison previous period" @select="run(() => filters.toggleCmp())">
|
||||
<Icon :icon="faArrowRightArrowLeft" size="sm" />
|
||||
Toggle comparison with previous period
|
||||
</CommandItem>
|
||||
<CommandItem
|
||||
v-for="m in (['light', 'dark', 'system'] as const)"
|
||||
:key="m"
|
||||
:value="`action theme ${m}`"
|
||||
@select="run(() => theme.setMode(m))"
|
||||
>
|
||||
<Icon :icon="faCircleHalfStroke" size="sm" />
|
||||
Theme: {{ m }}
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
<CommandGroup v-if="entities.length" heading="Entities">
|
||||
<CommandItem
|
||||
v-for="e in entities"
|
||||
:key="`${e.kind}:${e.id}`"
|
||||
:value="`${e.kind} ${e.label}`"
|
||||
@select="openEntity(e.kind, e.id)"
|
||||
>
|
||||
<span class="text-muted-foreground w-16 shrink-0 text-xs">{{ e.kind }}</span>
|
||||
<span class="truncate">{{ e.label }}</span>
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</CommandDialog>
|
||||
</template>
|
||||
@@ -5,25 +5,25 @@ import { buildHash, parseGlobalParams, parseHashState, parsePageParams } from '.
|
||||
|
||||
describe('parseHashState', () => {
|
||||
it('splits a page and query string', () => {
|
||||
const { page, query } = parseHashState('#spend?range=30d&by=model')
|
||||
expect(page).toBe('spend')
|
||||
const { page, query } = parseHashState('#usage?range=30d&by=model')
|
||||
expect(page).toBe('usage')
|
||||
expect(query.get('range')).toBe('30d')
|
||||
expect(query.get('by')).toBe('model')
|
||||
})
|
||||
|
||||
it('parses a bare page with no query to an empty query', () => {
|
||||
const { page, query } = parseHashState('#consumers')
|
||||
expect(page).toBe('consumers')
|
||||
const { page, query } = parseHashState('#users')
|
||||
expect(page).toBe('users')
|
||||
expect(Array.from(query.keys())).toEqual([])
|
||||
})
|
||||
|
||||
it('falls back to DEFAULT_PAGE ("home") for an empty hash', () => {
|
||||
expect(parseHashState('').page).toBe('home')
|
||||
it('falls back to DEFAULT_PAGE ("overview") for an empty hash', () => {
|
||||
expect(parseHashState('').page).toBe('overview')
|
||||
})
|
||||
|
||||
it('falls back to DEFAULT_PAGE for an unrecognized, non-legacy page, and still parses its query', () => {
|
||||
const { page, query } = parseHashState('#bogus?range=30d')
|
||||
expect(page).toBe('home')
|
||||
expect(page).toBe('overview')
|
||||
expect(query.get('range')).toBe('30d')
|
||||
})
|
||||
|
||||
@@ -40,17 +40,27 @@ describe('parseHashState', () => {
|
||||
describe('legacy tab-name mapping', () => {
|
||||
it.each([
|
||||
['providers', 'models'],
|
||||
['usage', 'consumers'],
|
||||
['charts', 'spend'],
|
||||
['events', 'reliability'],
|
||||
['charts', 'usage'],
|
||||
['events', 'events'],
|
||||
['targets', 'targets'],
|
||||
] as const)('#%s maps to #%s', (legacy, mapped) => {
|
||||
expect(parseHashState(`#${legacy}`).page).toBe(mapped)
|
||||
})
|
||||
|
||||
it('legacy ids map to new ids (home→overview, spend→usage, consumers→users)', () => {
|
||||
expect(parseHashState('#home').page).toBe('overview')
|
||||
expect(parseHashState('#spend').page).toBe('usage')
|
||||
expect(parseHashState('#consumers').page).toBe('users')
|
||||
})
|
||||
|
||||
it('a new id wins over a legacy alias of the same name (usage, events)', () => {
|
||||
expect(parseHashState('#usage').page).toBe('usage')
|
||||
expect(parseHashState('#events').page).toBe('events')
|
||||
})
|
||||
|
||||
it('drops the old hash\'s query params entirely, regardless of shape', () => {
|
||||
const { page, query } = parseHashState('#charts?tab=models&metric=cost&scope=user%3Aalice')
|
||||
expect(page).toBe('spend')
|
||||
expect(page).toBe('usage')
|
||||
expect(Array.from(query.keys())).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -58,20 +68,20 @@ describe('parseHashState', () => {
|
||||
|
||||
describe('buildHash', () => {
|
||||
it('omits the query suffix entirely when params is empty', () => {
|
||||
expect(buildHash('home', {})).toBe('#home')
|
||||
expect(buildHash('overview', {})).toBe('#overview')
|
||||
})
|
||||
|
||||
it('appends a query string for non-empty params', () => {
|
||||
expect(buildHash('spend', { range: '30d' })).toBe('#spend?range=30d')
|
||||
expect(buildHash('usage', { range: '30d' })).toBe('#usage?range=30d')
|
||||
})
|
||||
|
||||
it('joins multiple params with &, in insertion order', () => {
|
||||
const hash = buildHash('spend', { range: '30d', cmp: 'prev', scope: 'user:alice' })
|
||||
expect(hash).toBe('#spend?range=30d&cmp=prev&scope=user%3Aalice')
|
||||
const hash = buildHash('usage', { range: '30d', cmp: 'prev', scope: 'user:alice' })
|
||||
expect(hash).toBe('#usage?range=30d&cmp=prev&scope=user%3Aalice')
|
||||
})
|
||||
|
||||
it('drops a param whose value is an explicit empty string', () => {
|
||||
expect(buildHash('consumers', { q: '' })).toBe('#consumers')
|
||||
expect(buildHash('users', { q: '' })).toBe('#users')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -112,6 +122,22 @@ describe('parseGlobalParams', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('sel param', () => {
|
||||
it('sel survives round trip', () => {
|
||||
const hash = buildHash('models', { range: '7d', sel: 'model:uni%2Fglm-5.3-flash' })
|
||||
const { page, query } = parseHashState(hash)
|
||||
expect(page).toBe('models')
|
||||
expect(parsePageParams(query).sel).toBe('model:uni%2Fglm-5.3-flash')
|
||||
expect(parseGlobalParams(query)).toEqual({ range: '7d' })
|
||||
})
|
||||
|
||||
it('scope param still parsed alongside sel', () => {
|
||||
const { query } = parseHashState('#users?scope=group%3Aeng&sel=user%3Aalice')
|
||||
expect(parseGlobalParams(query).scope).toBe('group:eng')
|
||||
expect(parsePageParams(query)).toEqual({ sel: 'user:alice' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('parsePageParams', () => {
|
||||
it('excludes range/cmp/scope but keeps every other key', () => {
|
||||
const p = parsePageParams(new URLSearchParams('range=30d&cmp=prev&scope=all&by=model&metric=cost'))
|
||||
|
||||
+10
-19
@@ -4,25 +4,17 @@ import { isCmpMode, isRangeKey } from '@/lib/range'
|
||||
import type { CmpMode, RangeKey } from '@/lib/range'
|
||||
|
||||
/**
|
||||
* LEGACY_PAGE_MAP redirects the pre-redesign flat-tab hash names to their
|
||||
* redesign home (redesign-plan.md section 3.1's legacy mapping): a
|
||||
* bookmark or shared link built against the old #providers/#usage/
|
||||
* #charts/#events/#targets shell still lands somewhere sensible instead
|
||||
* of falling back to the default page. `targets` keeps its own name —
|
||||
* the MCP & Agents page is the one page that did not move.
|
||||
*
|
||||
* The OLD hash's query params never carry over (see parseHashState below)
|
||||
* — they were shaped for the old tab (e.g. #charts's `tab=models&metric=
|
||||
* cost`), and none of that maps cleanly onto the new page's own param
|
||||
* names, so a legacy hash lands on a clean instance of its mapped page
|
||||
* rather than misapplying a stale param.
|
||||
* Pre-redesign hash names that no longer exist as page ids, pointed at their
|
||||
* new home. A name that is also a current PageId (usage, events, targets)
|
||||
* is never looked up here: the new id wins. Old query params are dropped,
|
||||
* since they were shaped for the old page.
|
||||
*/
|
||||
const LEGACY_PAGE_MAP: Record<string, PageId> = {
|
||||
home: 'overview',
|
||||
spend: 'usage',
|
||||
consumers: 'users',
|
||||
providers: 'models',
|
||||
usage: 'consumers',
|
||||
charts: 'spend',
|
||||
events: 'reliability',
|
||||
targets: 'targets',
|
||||
charts: 'usage',
|
||||
}
|
||||
|
||||
export interface HashState {
|
||||
@@ -36,9 +28,8 @@ export interface HashState {
|
||||
*
|
||||
* 1. The page segment is a current PageId (lib/pages.ts) — parse the
|
||||
* query normally.
|
||||
* 2. The page segment is a legacy tab name (LEGACY_PAGE_MAP) — map to the
|
||||
* new page, with an EMPTY query (old params dropped, see the map's own
|
||||
* doc comment).
|
||||
* 2. The page segment is a legacy name (LEGACY_PAGE_MAP) — map to the
|
||||
* new page, with an EMPTY query.
|
||||
* 3. Anything else (absent, empty, or unrecognized) — DEFAULT_PAGE, query
|
||||
* parsed as-is (so a malformed page segment does not also swallow an
|
||||
* otherwise-valid query string).
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { NAV_GROUPS, navCounts } from './nav-groups'
|
||||
import { DEFAULT_PAGE, PAGE_IDS } from './pages'
|
||||
|
||||
describe('NAV_GROUPS', () => {
|
||||
it('every PAGE_ID appears exactly once in NAV_GROUPS', () => {
|
||||
const ids = NAV_GROUPS.flatMap((g) => g.items.map((i) => i.id))
|
||||
expect([...ids].sort()).toEqual([...PAGE_IDS].sort())
|
||||
expect(new Set(ids).size).toBe(ids.length)
|
||||
})
|
||||
|
||||
it('orders groups as Overview/Usage/Reliability | Directory | Events/Config', () => {
|
||||
expect(NAV_GROUPS.map((g) => [g.label, g.items.map((i) => i.id)])).toEqual([
|
||||
[null, ['overview', 'usage', 'reliability']],
|
||||
['Directory', ['users', 'models', 'routers', 'targets']],
|
||||
[null, ['events', 'config']],
|
||||
])
|
||||
})
|
||||
|
||||
it('labels the directory pages as specified', () => {
|
||||
const labels = NAV_GROUPS[1].items.map((i) => i.label)
|
||||
expect(labels).toEqual(['Users & groups', 'Models & providers', 'Smart routers', 'MCP & agents'])
|
||||
})
|
||||
|
||||
it('defaults to overview', () => {
|
||||
expect(DEFAULT_PAGE).toBe('overview')
|
||||
})
|
||||
})
|
||||
|
||||
describe('navCounts', () => {
|
||||
it('is empty before any data has loaded', () => {
|
||||
expect(navCounts(null, null, null)).toEqual({})
|
||||
})
|
||||
|
||||
it('derives the four directory counts', () => {
|
||||
const counts = navCounts(
|
||||
{ providers: [{ models: ['a', 'b'] }, { models: ['c'] }], routers: [{}, {}] },
|
||||
{ users: [{}, {}, {}] },
|
||||
{ mcpServers: [{}], agents: [{}, {}] },
|
||||
)
|
||||
expect(counts).toEqual({ users: 3, models: 3, routers: 2, targets: 3 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
import {
|
||||
faBolt,
|
||||
faChartLine,
|
||||
faCubes,
|
||||
faGaugeHigh,
|
||||
faHeartPulse,
|
||||
faPlug,
|
||||
faRoute,
|
||||
faSliders,
|
||||
faUsers,
|
||||
} from '@fortawesome/free-solid-svg-icons'
|
||||
import type { IconDefinition } from '@fortawesome/free-solid-svg-icons'
|
||||
|
||||
import type { PageId } from '@/lib/pages'
|
||||
import type { AdminOverviewResponse, AdminTargetsResponse, AdminUsageResponse } from '@/types/api'
|
||||
|
||||
export type NavCountKey = 'users' | 'models' | 'routers' | 'targets'
|
||||
|
||||
export interface NavItem {
|
||||
id: PageId
|
||||
label: string
|
||||
icon: IconDefinition
|
||||
countKey?: NavCountKey
|
||||
}
|
||||
|
||||
export interface NavGroup {
|
||||
label: string | null
|
||||
items: NavItem[]
|
||||
}
|
||||
|
||||
/** Sidebar structure; every PageId appears exactly once. */
|
||||
export const NAV_GROUPS: NavGroup[] = [
|
||||
{
|
||||
label: null,
|
||||
items: [
|
||||
{ id: 'overview', label: 'Overview', icon: faGaugeHigh },
|
||||
{ id: 'usage', label: 'Usage & spend', icon: faChartLine },
|
||||
{ id: 'reliability', label: 'Reliability', icon: faHeartPulse },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Directory',
|
||||
items: [
|
||||
{ id: 'users', label: 'Users & groups', icon: faUsers, countKey: 'users' },
|
||||
{ id: 'models', label: 'Models & providers', icon: faCubes, countKey: 'models' },
|
||||
{ id: 'routers', label: 'Smart routers', icon: faRoute, countKey: 'routers' },
|
||||
{ id: 'targets', label: 'MCP & agents', icon: faPlug, countKey: 'targets' },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: null,
|
||||
items: [
|
||||
{ id: 'events', label: 'Events', icon: faBolt },
|
||||
{ id: 'config', label: 'Config', icon: faSliders },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
type OverviewCounts = { providers?: Array<{ models: unknown[] }>; routers?: unknown[] } | null
|
||||
type UsageCounts = { users: unknown[] } | null
|
||||
type TargetCounts = { mcpServers: unknown[]; agents: unknown[] } | null
|
||||
|
||||
/** Sidebar badge counts; a key is omitted until its source has loaded. */
|
||||
export function navCounts(
|
||||
overview: OverviewCounts | AdminOverviewResponse,
|
||||
usage: UsageCounts | AdminUsageResponse,
|
||||
targets: TargetCounts | AdminTargetsResponse,
|
||||
): Partial<Record<NavCountKey, number>> {
|
||||
const counts: Partial<Record<NavCountKey, number>> = {}
|
||||
if (usage) counts.users = usage.users.length
|
||||
if (overview?.providers) counts.models = overview.providers.reduce((n, p) => n + p.models.length, 0)
|
||||
if (overview?.routers) counts.routers = overview.routers.length
|
||||
if (targets) counts.targets = targets.mcpServers.length + targets.agents.length
|
||||
return counts
|
||||
}
|
||||
+5
-41
@@ -1,48 +1,12 @@
|
||||
import {
|
||||
faCoins,
|
||||
faCubes,
|
||||
faHeartPulse,
|
||||
faHouse,
|
||||
faPlug,
|
||||
faSliders,
|
||||
faUsers,
|
||||
} from '@fortawesome/free-solid-svg-icons'
|
||||
import type { IconDefinition } from '@fortawesome/free-solid-svg-icons'
|
||||
|
||||
/**
|
||||
* PAGE_IDS is the sidebar redesign's page union (redesign-plan.md section
|
||||
* 3.1) — replaces composables/useTabHash.ts's old flat TAB_VALUES. The
|
||||
* single source of truth for every "which page" check: SidebarNav.vue's
|
||||
* link list, stores/nav.ts's `page` state, and lib/hash-state.ts's
|
||||
* outer "#<page>" segment all import PAGE_IDS/PageId rather than each
|
||||
* redeclaring their own copy.
|
||||
*/
|
||||
export const PAGE_IDS = ['home', 'spend', 'consumers', 'models', 'reliability', 'config', 'targets'] as const
|
||||
/** Page ids of the redesigned shell: the single source for nav, the store and the hash's page segment. */
|
||||
export const PAGE_IDS = ['overview', 'usage', 'reliability', 'users', 'models', 'routers', 'targets', 'events', 'config'] as const
|
||||
|
||||
export type PageId = (typeof PAGE_IDS)[number]
|
||||
|
||||
/** The landing page when the hash names nothing recognized, or is absent (first load). */
|
||||
export const DEFAULT_PAGE: PageId = 'home'
|
||||
/** The landing page when the hash names nothing recognized, or is absent. */
|
||||
export const DEFAULT_PAGE: PageId = 'overview'
|
||||
|
||||
/** One sidebar entry: the page it navigates to, its visible label, and its icon (redesign-plan.md section 3.1's fixed icon list). */
|
||||
export interface PageNavEntry {
|
||||
id: PageId
|
||||
label: string
|
||||
icon: IconDefinition
|
||||
}
|
||||
|
||||
/** PAGE_NAV drives SidebarNav.vue's link list, in display order. */
|
||||
export const PAGE_NAV: readonly PageNavEntry[] = [
|
||||
{ id: 'home', label: 'Home', icon: faHouse },
|
||||
{ id: 'spend', label: 'Spend', icon: faCoins },
|
||||
{ id: 'consumers', label: 'Consumers', icon: faUsers },
|
||||
{ id: 'models', label: 'Models', icon: faCubes },
|
||||
{ id: 'reliability', label: 'Reliability', icon: faHeartPulse },
|
||||
{ id: 'config', label: 'Config', icon: faSliders },
|
||||
{ id: 'targets', label: 'MCP & Agents', icon: faPlug },
|
||||
]
|
||||
|
||||
/** isPageId is a runtime type guard against PAGE_IDS — the only place that string union is checked against untrusted input (a hash, a hand-typed URL). */
|
||||
/** Runtime guard for untrusted input (a hash, a hand-typed URL). */
|
||||
export function isPageId(value: string): value is PageId {
|
||||
return (PAGE_IDS as readonly string[]).includes(value)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { paletteEntities } from './palette-items'
|
||||
import { PANEL_PAGE } from './panel-selection'
|
||||
|
||||
describe('paletteEntities', () => {
|
||||
it('is empty before data loads', () => {
|
||||
expect(paletteEntities(null, null, null)).toEqual([])
|
||||
})
|
||||
|
||||
it('lists each entity kind with a provider-prefixed model id', () => {
|
||||
const items = paletteEntities(
|
||||
{ providers: [{ name: 'uni', models: ['glm-5.3-flash'] }], groups: [{ name: 'eng' }], routers: [{ name: 'auto' }] },
|
||||
{ users: [{ id: 'alice' }] },
|
||||
{ mcpServers: [{ name: 'fetch' }], agents: [{ name: 'coder' }] },
|
||||
)
|
||||
expect(items.map((i) => `${i.kind}:${i.id}`)).toEqual([
|
||||
'user:alice',
|
||||
'group:eng',
|
||||
'provider:uni',
|
||||
'model:uni/glm-5.3-flash',
|
||||
'router:auto',
|
||||
'target:fetch',
|
||||
'target:coder',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('PANEL_PAGE', () => {
|
||||
it('routes every kind to its directory page', () => {
|
||||
expect(PANEL_PAGE).toEqual({
|
||||
user: 'users',
|
||||
group: 'users',
|
||||
model: 'models',
|
||||
provider: 'models',
|
||||
router: 'routers',
|
||||
target: 'targets',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { PanelKind } from '@/lib/panel-selection'
|
||||
|
||||
export interface PaletteEntity {
|
||||
kind: PanelKind
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
type OverviewSource = {
|
||||
providers?: Array<{ name: string; models: string[] }>
|
||||
groups?: Array<{ name: string }>
|
||||
routers?: Array<{ name: string }>
|
||||
} | null
|
||||
|
||||
/** Entities the command palette can open a detail panel for; empty until the dashboard has data. */
|
||||
export function paletteEntities(
|
||||
overview: OverviewSource,
|
||||
usage: { users: Array<{ id: string }> } | null,
|
||||
targets: { mcpServers: Array<{ name: string }>; agents: Array<{ name: string }> } | null,
|
||||
): PaletteEntity[] {
|
||||
const out: PaletteEntity[] = []
|
||||
for (const u of usage?.users ?? []) out.push({ kind: 'user', id: u.id, label: u.id })
|
||||
for (const g of overview?.groups ?? []) out.push({ kind: 'group', id: g.name, label: g.name })
|
||||
for (const p of overview?.providers ?? []) {
|
||||
out.push({ kind: 'provider', id: p.name, label: p.name })
|
||||
for (const m of p.models) out.push({ kind: 'model', id: `${p.name}/${m}`, label: `${p.name}/${m}` })
|
||||
}
|
||||
for (const r of overview?.routers ?? []) out.push({ kind: 'router', id: r.name, label: r.name })
|
||||
for (const t of [...(targets?.mcpServers ?? []), ...(targets?.agents ?? [])]) out.push({ kind: 'target', id: t.name, label: t.name })
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { buildHash, parseHashState, parsePageParams } from './hash-state'
|
||||
import { formatSel, parseSel, resolveSel } from './panel-selection'
|
||||
|
||||
describe('parseSel', () => {
|
||||
it('parses kind:id', () => {
|
||||
expect(parseSel('user:alice')).toEqual({ kind: 'user', id: 'alice' })
|
||||
})
|
||||
|
||||
it('rejects unknown kind', () => {
|
||||
expect(parseSel('galaxy:alice')).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects absent, empty and id-less values', () => {
|
||||
expect(parseSel(undefined)).toBeNull()
|
||||
expect(parseSel('')).toBeNull()
|
||||
expect(parseSel('user')).toBeNull()
|
||||
expect(parseSel('user:')).toBeNull()
|
||||
})
|
||||
|
||||
it('splits on the first colon only', () => {
|
||||
expect(parseSel('target:mcp:fetch')).toEqual({ kind: 'target', id: 'mcp:fetch' })
|
||||
})
|
||||
|
||||
it('rejects a malformed percent escape instead of throwing', () => {
|
||||
expect(parseSel('user:%E0%A4%A')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatSel', () => {
|
||||
it('encodes ids with slashes (uni/glm-5.3-flash)', () => {
|
||||
const s = formatSel('model', 'uni/glm-5.3-flash')
|
||||
expect(s).toBe('model:uni%2Fglm-5.3-flash')
|
||||
expect(parseSel(s)).toEqual({ kind: 'model', id: 'uni/glm-5.3-flash' })
|
||||
})
|
||||
|
||||
it('round-trips ids containing colons, percent signs and spaces', () => {
|
||||
for (const id of ['mcp:fetch', '100%', 'a b', 'x&y=z#w']) {
|
||||
expect(parseSel(formatSel('target', id))).toEqual({ kind: 'target', id })
|
||||
}
|
||||
})
|
||||
|
||||
it('survives the hash round trip through buildHash and parseHashState', () => {
|
||||
const id = 'uni/glm-5.3-flash'
|
||||
const hash = buildHash('models', { sel: formatSel('model', id) })
|
||||
const { page, query } = parseHashState(hash)
|
||||
expect(page).toBe('models')
|
||||
expect(parseSel(parsePageParams(query).sel)).toEqual({ kind: 'model', id })
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveSel', () => {
|
||||
const known = new Set(['user:alice'])
|
||||
const exists = (kind: string, id: string) => known.has(`${kind}:${id}`)
|
||||
|
||||
it('keeps a known selection', () => {
|
||||
expect(resolveSel({ kind: 'user', id: 'alice' }, exists)).toEqual({ kind: 'user', id: 'alice' })
|
||||
})
|
||||
|
||||
it('unknown id clears sel', () => {
|
||||
expect(resolveSel({ kind: 'user', id: 'ghost' }, exists)).toBeNull()
|
||||
})
|
||||
|
||||
it('passes null through', () => {
|
||||
expect(resolveSel(null, exists)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { PageId } from '@/lib/pages'
|
||||
|
||||
/** Entity kinds a detail panel can open, carried in the hash as `sel=<kind>:<id>`. */
|
||||
export const PANEL_KINDS = ['user', 'group', 'model', 'provider', 'router', 'target'] as const
|
||||
|
||||
export type PanelKind = (typeof PANEL_KINDS)[number]
|
||||
|
||||
export interface PanelSelection {
|
||||
kind: PanelKind
|
||||
id: string
|
||||
}
|
||||
|
||||
function isPanelKind(value: string): value is PanelKind {
|
||||
return (PANEL_KINDS as readonly string[]).includes(value)
|
||||
}
|
||||
|
||||
/** Parses a `sel` value; null for absent, unknown kind, empty id or a malformed escape. Splits on the first colon only. */
|
||||
export function parseSel(v: string | undefined): PanelSelection | null {
|
||||
if (!v) return null
|
||||
const colon = v.indexOf(':')
|
||||
if (colon === -1) return null
|
||||
const kind = v.slice(0, colon)
|
||||
const rawId = v.slice(colon + 1)
|
||||
if (!isPanelKind(kind) || rawId === '') return null
|
||||
try {
|
||||
return { kind, id: decodeURIComponent(rawId) }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** The id is percent-encoded so slashes, colons and `&` survive; the hash layer's own query encoding is applied on top and undone symmetrically. */
|
||||
export function formatSel(kind: PanelKind, id: string): string {
|
||||
return `${kind}:${encodeURIComponent(id)}`
|
||||
}
|
||||
|
||||
/** Returns the selection when its entity exists, else null (the caller then clears `sel` with a replace). */
|
||||
export function resolveSel(
|
||||
sel: PanelSelection | null,
|
||||
existsFn: (kind: PanelKind, id: string) => boolean,
|
||||
): PanelSelection | null {
|
||||
if (!sel) return null
|
||||
return existsFn(sel.kind, sel.id) ? sel : null
|
||||
}
|
||||
|
||||
/** The page whose directory lists each kind; opening a panel from elsewhere navigates here first. */
|
||||
export const PANEL_PAGE: Record<PanelKind, PageId> = {
|
||||
user: 'users',
|
||||
group: 'users',
|
||||
model: 'models',
|
||||
provider: 'models',
|
||||
router: 'routers',
|
||||
target: 'targets',
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
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'
|
||||
|
||||
@@ -18,5 +19,9 @@ app.config.errorHandler = (err) => {
|
||||
console.error(err)
|
||||
useToastsStore(pinia).push({ kind: 'error', message: `Unexpected error: ${messageOf(err)}` })
|
||||
}
|
||||
// Workbench is the app-wide style; init() restores the saved mode and the persisted choice survives reloads.
|
||||
const theme = useThemeStore(pinia)
|
||||
theme.init()
|
||||
theme.setStyle('workbench')
|
||||
app.component('FontAwesomeIcon', FontAwesomeIcon)
|
||||
app.mount('#app')
|
||||
|
||||
@@ -28,7 +28,7 @@ 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('consumers', { ...rest, view: next })
|
||||
nav.goTo('users', { ...rest, view: next })
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -38,15 +38,15 @@ function setView(next: unknown): void {
|
||||
function setMatrixKind(next: MatrixKind): void {
|
||||
const { user: _user, matrix: _matrix, ...rest } = nav.params
|
||||
if (next === 'models') {
|
||||
nav.goTo('consumers', { ...rest, view: 'matrix' })
|
||||
nav.goTo('users', { ...rest, view: 'matrix' })
|
||||
return
|
||||
}
|
||||
nav.goTo('consumers', { ...rest, view: 'matrix', matrix: next })
|
||||
nav.goTo('users', { ...rest, view: 'matrix', matrix: next })
|
||||
}
|
||||
|
||||
function closeUserDetail(): void {
|
||||
const { user: _user, ...rest } = nav.params
|
||||
nav.goTo('consumers', rest)
|
||||
nav.goTo('users', rest)
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -162,10 +162,10 @@ function setTopUsersMode(next: unknown): void {
|
||||
const mode = next as TopUsersMode
|
||||
if (mode === DEFAULT_TOP_USERS_MODE) {
|
||||
const { top: _top, ...rest } = nav.params
|
||||
nav.goTo('home', rest)
|
||||
nav.goTo('overview', rest)
|
||||
return
|
||||
}
|
||||
nav.goTo('home', { ...nav.params, top: mode })
|
||||
nav.goTo('overview', { ...nav.params, top: mode })
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -408,13 +408,13 @@ onUnmounted(() => {
|
||||
<ErrorState :message="dashboard.error" :on-retry="dashboard.refresh" />
|
||||
</div>
|
||||
<template v-else>
|
||||
<KpiTile label="Spend (MTD)" :value="formatCostDisplay(spendMtdMicros)" :delta="spendDelta" :tier="spendTier" :to="{ page: 'spend' }" />
|
||||
<KpiTile label="Spend (MTD)" :value="formatCostDisplay(spendMtdMicros)" :delta="spendDelta" :tier="spendTier" :to="{ page: 'usage' }" />
|
||||
<KpiTile
|
||||
label="Projected month-end"
|
||||
:value="projectedValue"
|
||||
:delta="projectedDelta"
|
||||
:tier="projectedTier"
|
||||
:to="{ page: 'spend' }"
|
||||
:to="{ page: 'usage' }"
|
||||
/>
|
||||
<KpiTile label="Requests/min" :value="formatCompactCount(requestsPerMinute)" />
|
||||
<KpiTile
|
||||
@@ -440,7 +440,7 @@ onUnmounted(() => {
|
||||
label="Unpriced models"
|
||||
:value="String(unpricedCount)"
|
||||
:tier="unpricedCount > 0 ? 'warn' : 'ok'"
|
||||
:to="{ page: 'spend' }"
|
||||
:to="{ page: 'usage' }"
|
||||
/>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
@@ -61,7 +61,7 @@ function updateParams(next: Partial<{ by: SpendBy; metric: HistoryMetric; ref: s
|
||||
if (merged.metric !== 'cost') params.metric = merged.metric
|
||||
if (merged.ref !== '') params.ref = merged.ref
|
||||
if (merged.drill !== '') params.drill = merged.drill
|
||||
nav.goTo('spend', params)
|
||||
nav.goTo('usage', params)
|
||||
}
|
||||
|
||||
function onByChange(value: string | number): void {
|
||||
|
||||
@@ -44,6 +44,11 @@ export const useFiltersStore = defineStore('filters', {
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
/** Flips comparison. Turning it OFF is always allowed; turning it ON needs a range that supports one. */
|
||||
toggleCmp(): void {
|
||||
if (this.cmp === 'prev') this.cmp = 'none'
|
||||
else if (this.cmpSpec.available) this.cmp = 'prev'
|
||||
},
|
||||
/** setFilters applies any subset of range/cmp/scope in one call — omitted fields keep their current value, the same "apply a partial update, one atomic write" convention the pre-redesign stores/history.ts's own setSelection (deleted; this store replaces it) used, and stores/spend.ts's own setSelection still follows today. */
|
||||
setFilters(next: { range?: RangeKey; cmp?: CmpMode; scope?: string }): void {
|
||||
if (next.range !== undefined) this.range = next.range
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import { PAGE_IDS } from '@/lib/pages'
|
||||
import { useNavStore } from '@/stores/nav'
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -10,7 +11,7 @@ beforeEach(() => {
|
||||
describe('useNavStore: initial state', () => {
|
||||
it('defaults page to "home" and params to an empty record', () => {
|
||||
const nav = useNavStore()
|
||||
expect(nav.page).toBe('home')
|
||||
expect(nav.page).toBe('overview')
|
||||
expect(nav.params).toEqual({})
|
||||
})
|
||||
})
|
||||
@@ -18,31 +19,75 @@ describe('useNavStore: initial state', () => {
|
||||
describe('useNavStore.goTo', () => {
|
||||
it('sets page and params together', () => {
|
||||
const nav = useNavStore()
|
||||
nav.goTo('consumers', { user: 'alice' })
|
||||
expect(nav.page).toBe('consumers')
|
||||
nav.goTo('users', { user: 'alice' })
|
||||
expect(nav.page).toBe('users')
|
||||
expect(nav.params).toEqual({ user: 'alice' })
|
||||
})
|
||||
|
||||
it('defaults params to an empty record when omitted', () => {
|
||||
const nav = useNavStore()
|
||||
nav.goTo('models', { model: 'openai/gpt-5' })
|
||||
nav.goTo('spend')
|
||||
expect(nav.page).toBe('spend')
|
||||
nav.goTo('usage')
|
||||
expect(nav.page).toBe('usage')
|
||||
expect(nav.params).toEqual({})
|
||||
})
|
||||
|
||||
it('replaces, never merges, the previous page\'s params', () => {
|
||||
const nav = useNavStore()
|
||||
nav.goTo('consumers', { user: 'alice', view: 'directory' })
|
||||
nav.goTo('consumers', { view: 'matrix' })
|
||||
nav.goTo('users', { user: 'alice', view: 'directory' })
|
||||
nav.goTo('users', { view: 'matrix' })
|
||||
expect(nav.params).toEqual({ view: 'matrix' })
|
||||
})
|
||||
|
||||
it('accepts every page id', () => {
|
||||
const nav = useNavStore()
|
||||
for (const page of ['home', 'spend', 'consumers', 'models', 'reliability', 'config', 'targets'] as const) {
|
||||
for (const page of PAGE_IDS) {
|
||||
nav.goTo(page)
|
||||
expect(nav.page).toBe(page)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('useNavStore panels', () => {
|
||||
it('openPanel sets sel, keeps other params and requests a history push', () => {
|
||||
const nav = useNavStore()
|
||||
nav.goTo('models', { q: 'gpt' })
|
||||
nav.openPanel('model', 'uni/glm-5.3-flash')
|
||||
expect(nav.params).toEqual({ q: 'gpt', sel: 'model:uni%2Fglm-5.3-flash' })
|
||||
expect(nav.pushPending).toBe(true)
|
||||
expect(nav.selection).toEqual({ kind: 'model', id: 'uni/glm-5.3-flash' })
|
||||
})
|
||||
|
||||
it('openPanel on the already-open panel does not request a second push', () => {
|
||||
const nav = useNavStore()
|
||||
nav.openPanel('user', 'alice')
|
||||
nav.pushPending = false
|
||||
nav.openPanel('user', 'alice')
|
||||
expect(nav.pushPending).toBe(false)
|
||||
})
|
||||
|
||||
it('closePanel without a pushed entry clears sel in place and requests no push', () => {
|
||||
const nav = useNavStore()
|
||||
nav.goTo('users', { q: 'a', sel: 'user:alice' })
|
||||
nav.closePanel()
|
||||
expect(nav.params).toEqual({ q: 'a' })
|
||||
expect(nav.pushPending).toBe(false)
|
||||
expect(nav.selection).toBeNull()
|
||||
})
|
||||
|
||||
it('goTo with replace:false requests a push; default does not', () => {
|
||||
const nav = useNavStore()
|
||||
nav.goTo('users')
|
||||
expect(nav.pushPending).toBe(false)
|
||||
nav.goTo('models', {}, { replace: false })
|
||||
expect(nav.pushPending).toBe(true)
|
||||
})
|
||||
|
||||
it('goTo resets the pushed-panel marker so a later close replaces', () => {
|
||||
const nav = useNavStore()
|
||||
nav.openPanel('user', 'alice')
|
||||
expect(nav.panelPushed).toBe(true)
|
||||
nav.goTo('users', { sel: 'user:alice' })
|
||||
expect(nav.panelPushed).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
+33
-1
@@ -2,6 +2,8 @@ import { defineStore } from 'pinia'
|
||||
|
||||
import { DEFAULT_PAGE } from '@/lib/pages'
|
||||
import type { PageId } from '@/lib/pages'
|
||||
import { formatSel, parseSel } from '@/lib/panel-selection'
|
||||
import type { PanelKind, PanelSelection } from '@/lib/panel-selection'
|
||||
|
||||
/**
|
||||
* useNavStore is the redesign's single navigation store (redesign-plan.md
|
||||
@@ -23,7 +25,15 @@ export const useNavStore = defineStore('nav', {
|
||||
state: () => ({
|
||||
page: DEFAULT_PAGE as PageId,
|
||||
params: {} as Record<string, string>,
|
||||
/** Set by openPanel / goTo(replace:false); composables/useHashState.ts consumes it to choose pushState over replaceState. */
|
||||
pushPending: false,
|
||||
/** True while the current history entry was created by openPanel, so closePanel can go Back instead of stacking another entry. */
|
||||
panelPushed: false,
|
||||
}),
|
||||
getters: {
|
||||
/** The open detail panel parsed from the `sel` param, or null. */
|
||||
selection: (state): PanelSelection | null => parseSel(state.params.sel),
|
||||
},
|
||||
actions: {
|
||||
/**
|
||||
* goTo navigates to `page` with `params` as that page's complete
|
||||
@@ -34,9 +44,31 @@ export const useNavStore = defineStore('nav', {
|
||||
* single click is always one atomic state change (and, downstream,
|
||||
* one hash rewrite — composables/useHashState.ts's own watcher).
|
||||
*/
|
||||
goTo(page: PageId, params: Record<string, string> = {}): void {
|
||||
goTo(page: PageId, params: Record<string, string> = {}, opts: { replace?: boolean } = {}): void {
|
||||
this.page = page
|
||||
this.params = params
|
||||
this.pushPending = opts.replace === false
|
||||
this.panelPushed = false
|
||||
},
|
||||
/** Opens a detail panel and pushes a history entry, so Back closes it. */
|
||||
openPanel(kind: PanelKind, id: string): void {
|
||||
const sel = formatSel(kind, id)
|
||||
if (this.params.sel === sel) return
|
||||
this.params = { ...this.params, sel }
|
||||
this.pushPending = true
|
||||
this.panelPushed = true
|
||||
},
|
||||
/** Goes Back when the panel owns the last history entry; otherwise drops `sel` in place. */
|
||||
closePanel(): void {
|
||||
if (this.panelPushed && typeof window !== 'undefined') {
|
||||
this.panelPushed = false
|
||||
window.history.back()
|
||||
return
|
||||
}
|
||||
const { sel: _sel, ...rest } = this.params
|
||||
this.params = rest
|
||||
this.pushPending = false
|
||||
this.panelPushed = false
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
import { themeBootScript } from '@perfect-design/ui/stores/theme-boot'
|
||||
import type { Plugin } from 'vite'
|
||||
|
||||
/** Ships perfect-design's pre-paint theme script as an external file: the admin CSP (script-src 'self') forbids the inline form. */
|
||||
export function themeBoot(): Plugin {
|
||||
const hash = createHash('sha256').update(themeBootScript).digest('hex').slice(0, 8)
|
||||
const fileName = `assets/theme-boot.${hash}.js`
|
||||
let base = '/'
|
||||
|
||||
return {
|
||||
name: 'theme-boot',
|
||||
configResolved(config) {
|
||||
base = config.base
|
||||
},
|
||||
configureServer(server) {
|
||||
server.middlewares.use((req, res, next) => {
|
||||
if (req.url?.split('?')[0] !== `${base}${fileName}`) return next()
|
||||
res.setHeader('Content-Type', 'text/javascript; charset=utf-8')
|
||||
res.end(themeBootScript)
|
||||
})
|
||||
},
|
||||
generateBundle() {
|
||||
this.emitFile({ type: 'asset', fileName, source: themeBootScript })
|
||||
},
|
||||
transformIndexHtml() {
|
||||
return [{ tag: 'script', attrs: { src: `${base}${fileName}` }, injectTo: 'head-prepend' }]
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,15 @@ import vue from '@vitejs/plugin-vue'
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
import { mockAdminApi } from './mock/server.ts'
|
||||
import { themeBoot } from './vite-plugins/theme-boot.ts'
|
||||
|
||||
// MOCK=1 serves /admin/api/* from webui/mock (dev server only; apply: 'serve' keeps it out of vite build).
|
||||
const useMock = process.env.MOCK === '1'
|
||||
|
||||
// Keep identical to adminCSP in ../admin.go: `vite preview` serves the built dist under it so a CSP violation shows up in the browser console.
|
||||
const ADMIN_CSP =
|
||||
"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'none'"
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
// admin.go serves this build's index.html at GET /admin and every hashed
|
||||
@@ -20,7 +25,7 @@ export default defineConfig({
|
||||
// emitted index.html's own <script>/<link> references resolve correctly
|
||||
// regardless of what path the browser first loaded the page from.
|
||||
base: '/admin/',
|
||||
plugins: [vue(), tailwindcss(), ...(useMock ? [mockAdminApi()] : [])],
|
||||
plugins: [vue(), tailwindcss(), themeBoot(), ...(useMock ? [mockAdminApi()] : [])],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
@@ -37,6 +42,7 @@ export default defineConfig({
|
||||
// polyfill has nothing to do here anyway.
|
||||
modulePreload: { polyfill: false },
|
||||
},
|
||||
preview: { headers: { 'Content-Security-Policy': ADMIN_CSP } },
|
||||
server: {
|
||||
// `npm run dev` serves this app at :5173 (or whatever Vite picks), but
|
||||
// every fetch('/admin/api/...') (lib/api.ts) is a same-origin, relative
|
||||
|
||||
Reference in New Issue
Block a user