diff --git a/webui/index.html b/webui/index.html index ec3d0cd..a57919e 100644 --- a/webui/index.html +++ b/webui/index.html @@ -1,5 +1,5 @@ - + -

- - -

- - - - - - - - -
- -
- -
-
+
+
+ + + + + diff --git a/webui/src/assets/main.css b/webui/src/assets/main.css index c409a4e..1842bca 100644 --- a/webui/src/assets/main.css +++ b/webui/src/assets/main.css @@ -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 , 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 { diff --git a/webui/src/components/ConsumerDirectory.vue b/webui/src/components/ConsumerDirectory.vue index 2e2b394..261df87 100644 --- a/webui/src/components/ConsumerDirectory.vue +++ b/webui/src/components/ConsumerDirectory.vue @@ -116,7 +116,7 @@ function sourceOf(entry: AdminUsageEntryView): string | undefined { // the old nav.usageQuery special case. const usageQuery = computed({ 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) diff --git a/webui/src/components/EntityLink.vue b/webui/src/components/EntityLink.vue index b283b44..77365cc 100644 --- a/webui/src/components/EntityLink.vue +++ b/webui/src/components/EntityLink.vue @@ -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' }, } diff --git a/webui/src/components/GlobalFilterBar.vue b/webui/src/components/GlobalFilterBar.vue deleted file mode 100644 index edbfc4b..0000000 --- a/webui/src/components/GlobalFilterBar.vue +++ /dev/null @@ -1,125 +0,0 @@ - - - diff --git a/webui/src/components/SidebarNav.vue b/webui/src/components/SidebarNav.vue deleted file mode 100644 index 6f9a8a3..0000000 --- a/webui/src/components/SidebarNav.vue +++ /dev/null @@ -1,40 +0,0 @@ - - - diff --git a/webui/src/composables/useHashState.ts b/webui/src/composables/useHashState.ts index 9674ea4..daafdb5 100644 --- a/webui/src/composables/useHashState.ts +++ b/webui/src/composables/useHashState.ts @@ -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 }, ) diff --git a/webui/src/composables/useThemeColors.ts b/webui/src/composables/useThemeColors.ts index ae43913..58067f2 100644 --- a/webui/src/composables/useThemeColors.ts +++ b/webui/src/composables/useThemeColors.ts @@ -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 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 } diff --git a/webui/src/layout/AppHeader.vue b/webui/src/layout/AppHeader.vue new file mode 100644 index 0000000..b494f9a --- /dev/null +++ b/webui/src/layout/AppHeader.vue @@ -0,0 +1,109 @@ + + + diff --git a/webui/src/layout/AppLayout.vue b/webui/src/layout/AppLayout.vue new file mode 100644 index 0000000..655a894 --- /dev/null +++ b/webui/src/layout/AppLayout.vue @@ -0,0 +1,65 @@ + + + diff --git a/webui/src/layout/CommandPalette.vue b/webui/src/layout/CommandPalette.vue new file mode 100644 index 0000000..8f27e89 --- /dev/null +++ b/webui/src/layout/CommandPalette.vue @@ -0,0 +1,100 @@ + + + diff --git a/webui/src/lib/hash-state.spec.ts b/webui/src/lib/hash-state.spec.ts index 7032229..4b5a798 100644 --- a/webui/src/lib/hash-state.spec.ts +++ b/webui/src/lib/hash-state.spec.ts @@ -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')) diff --git a/webui/src/lib/hash-state.ts b/webui/src/lib/hash-state.ts index 6b04c6a..a292262 100644 --- a/webui/src/lib/hash-state.ts +++ b/webui/src/lib/hash-state.ts @@ -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 = { + 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). diff --git a/webui/src/lib/nav-groups.spec.ts b/webui/src/lib/nav-groups.spec.ts new file mode 100644 index 0000000..2843c85 --- /dev/null +++ b/webui/src/lib/nav-groups.spec.ts @@ -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 }) + }) +}) diff --git a/webui/src/lib/nav-groups.ts b/webui/src/lib/nav-groups.ts new file mode 100644 index 0000000..2585f50 --- /dev/null +++ b/webui/src/lib/nav-groups.ts @@ -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> { + const counts: Partial> = {} + 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 +} diff --git a/webui/src/lib/pages.ts b/webui/src/lib/pages.ts index c2deb21..c204a74 100644 --- a/webui/src/lib/pages.ts +++ b/webui/src/lib/pages.ts @@ -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 "#" 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) } diff --git a/webui/src/lib/palette-items.spec.ts b/webui/src/lib/palette-items.spec.ts new file mode 100644 index 0000000..7c71fa8 --- /dev/null +++ b/webui/src/lib/palette-items.spec.ts @@ -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', + }) + }) +}) diff --git a/webui/src/lib/palette-items.ts b/webui/src/lib/palette-items.ts new file mode 100644 index 0000000..3580138 --- /dev/null +++ b/webui/src/lib/palette-items.ts @@ -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 +} diff --git a/webui/src/lib/panel-selection.spec.ts b/webui/src/lib/panel-selection.spec.ts new file mode 100644 index 0000000..7f13900 --- /dev/null +++ b/webui/src/lib/panel-selection.spec.ts @@ -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() + }) +}) diff --git a/webui/src/lib/panel-selection.ts b/webui/src/lib/panel-selection.ts new file mode 100644 index 0000000..34ff64a --- /dev/null +++ b/webui/src/lib/panel-selection.ts @@ -0,0 +1,54 @@ +import type { PageId } from '@/lib/pages' + +/** Entity kinds a detail panel can open, carried in the hash as `sel=:`. */ +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 = { + user: 'users', + group: 'users', + model: 'models', + provider: 'models', + router: 'routers', + target: 'targets', +} diff --git a/webui/src/main.ts b/webui/src/main.ts index 14bca5c..2a40744 100644 --- a/webui/src/main.ts +++ b/webui/src/main.ts @@ -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') diff --git a/webui/src/pages/ConsumersPage.vue b/webui/src/pages/ConsumersPage.vue index 5c3d8ef..3466f6c 100644 --- a/webui/src/pages/ConsumersPage.vue +++ b/webui/src/pages/ConsumersPage.vue @@ -28,7 +28,7 @@ const matrixKind = computed(() => 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) } diff --git a/webui/src/pages/HomePage.vue b/webui/src/pages/HomePage.vue index 9173f1b..8852289 100644 --- a/webui/src/pages/HomePage.vue +++ b/webui/src/pages/HomePage.vue @@ -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(() => { diff --git a/webui/src/pages/SpendPage.vue b/webui/src/pages/SpendPage.vue index b1f840c..5a2a378 100644 --- a/webui/src/pages/SpendPage.vue +++ b/webui/src/pages/SpendPage.vue @@ -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 { diff --git a/webui/src/stores/filters.ts b/webui/src/stores/filters.ts index a98cd71..0966d8b 100644 --- a/webui/src/stores/filters.ts +++ b/webui/src/stores/filters.ts @@ -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 diff --git a/webui/src/stores/nav.spec.ts b/webui/src/stores/nav.spec.ts index c8b8d17..959c443 100644 --- a/webui/src/stores/nav.spec.ts +++ b/webui/src/stores/nav.spec.ts @@ -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) + }) +}) diff --git a/webui/src/stores/nav.ts b/webui/src/stores/nav.ts index 412b444..c84e7bb 100644 --- a/webui/src/stores/nav.ts +++ b/webui/src/stores/nav.ts @@ -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, + /** 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 = {}): void { + goTo(page: PageId, params: Record = {}, 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 }, }, }) diff --git a/webui/vite-plugins/theme-boot.ts b/webui/vite-plugins/theme-boot.ts new file mode 100644 index 0000000..a9a8b75 --- /dev/null +++ b/webui/vite-plugins/theme-boot.ts @@ -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' }] + }, + } +} diff --git a/webui/vite.config.ts b/webui/vite.config.ts index ba8a9b1..59f6d04 100644 --- a/webui/vite.config.ts +++ b/webui/vite.config.ts @@ -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