feat(webui): config page

This commit is contained in:
2026-11-25 11:52:38 +00:00
parent 32a6d0c51f
commit 1f8bdd8777
11 changed files with 377 additions and 54 deletions
+1 -1
View File
@@ -74,7 +74,7 @@ onMounted(() => {
</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" />
<ConfigWarningsBanner v-if="nav.page !== 'config'" :warnings="dashboard.overview?.warnings ?? []" :warnings-dropped="dashboard.overview?.warningsDropped" />
<component :is="currentPage" />
</AppLayout>
<ToastViewport />
+2 -13
View File
@@ -8,21 +8,10 @@ import PricingForm from '@/components/forms/PricingForm.vue'
import RouterForm from '@/components/forms/RouterForm.vue'
import UserForm from '@/components/forms/UserForm.vue'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { HELPER_IDS, HELPER_LABEL } from '@/lib/helper-forms'
import type { HelperId } from '@/lib/helper-forms'
import { useNavStore } from '@/stores/nav'
/** HELPER_IDS mirrors the Config page's own `helper` hash param (redesign-plan.md section 3.1: `helper=limits|grant|pricing|model|router|user`) — the single source of truth for which tab is selected and which form renders. */
const HELPER_IDS = ['limits', 'grant', 'pricing', 'model', 'router', 'user'] as const
type HelperId = (typeof HELPER_IDS)[number]
const HELPER_LABEL: Record<HelperId, string> = {
limits: 'Limits',
grant: 'Access grant',
pricing: 'Pricing',
model: 'Model metadata',
router: 'Smart router',
user: 'New user',
}
/**
* ChangeHelper (redesign-plan.md section 3.4) is the Config page's
* snippet-building surface: six forms (LimitsForm, GrantForm,
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest'
import { filterSections, splitConfigSections } from '@/lib/config-sections'
const YAML = ['admin:', ' enabled: true', 'agents:', ' a:', ' url: x', ' b:', ' url: y', '"odd/key":', ' v: 1', 'redis:', ' addr: r'].join('\n')
describe('splitConfigSections', () => {
it('splits at each top-level key with 1-based start lines and line counts', () => {
const s = splitConfigSections(YAML)
expect(s.map((x) => [x.key, x.startLine, x.lineCount])).toEqual([
['admin', 1, 2],
['agents', 3, 5],
['odd/key', 8, 2],
['redis', 10, 2],
])
})
it('keeps each section text verbatim so the sections join back to the document', () => {
expect(splitConfigSections(YAML).map((x) => x.text).join('\n')).toBe(YAML)
})
it('returns no sections for empty text', () => {
expect(splitConfigSections('')).toEqual([])
})
it('does not treat list items or comments at column 0 as keys', () => {
const s = splitConfigSections(['a:', '- x: 1', '# note', 'b: 2'].join('\n'))
expect(s.map((x) => x.key)).toEqual(['a', 'b'])
expect(s[0].lineCount).toBe(3)
})
})
describe('filterSections', () => {
const s = splitConfigSections(YAML)
it('returns all sections for a blank query', () => {
expect(filterSections(s, ' ')).toHaveLength(4)
})
it('matches keys case-insensitively by substring', () => {
expect(filterSections(s, 'AG').map((x) => x.key)).toEqual(['agents'])
})
it('returns none when nothing matches', () => {
expect(filterSections(s, 'zzz')).toEqual([])
})
})
+40
View File
@@ -0,0 +1,40 @@
export interface ConfigSection {
key: string
/** 1-based line of the key in the full document. */
startLine: number
lineCount: number
text: string
}
const TOP_KEY = /^([^\s#-][^:]*|"[^"]*"|'[^']*'):/
function unquote(raw: string): string {
const q = raw[0]
return (q === '"' || q === "'") && raw.endsWith(q) ? raw.slice(1, -1) : raw
}
/** Splits a block-style YAML document at its column-0 keys; joining the section texts with newlines gives the document back. */
export function splitConfigSections(yaml: string): ConfigSection[] {
if (yaml === '') return []
const out: ConfigSection[] = []
const lines = yaml.split('\n')
let current: { key: string; startLine: number; lines: string[] } | null = null
const flush = (): void => {
if (current) out.push({ key: current.key, startLine: current.startLine, lineCount: current.lines.length, text: current.lines.join('\n') })
}
lines.forEach((line, i) => {
const m = TOP_KEY.exec(line)
if (m) {
flush()
current = { key: unquote(m[1]), startLine: i + 1, lines: [line] }
} else current?.lines.push(line)
})
flush()
return out
}
/** Sections whose key contains the query, case-insensitively; a blank query keeps all. */
export function filterSections(sections: ConfigSection[], query: string): ConfigSection[] {
const q = query.trim().toLowerCase()
return q === '' ? sections : sections.filter((s) => s.key.toLowerCase().includes(q))
}
+24
View File
@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest'
import { HELPER_IDS, HELPER_LABEL, formatHelperSel, parseHelperSel } from '@/lib/helper-forms'
describe('helper selection', () => {
it('round-trips every helper id', () => {
for (const id of HELPER_IDS) expect(parseHelperSel(formatHelperSel(id))).toBe(id)
})
it('formats as helper:<id>', () => {
expect(formatHelperSel('router')).toBe('helper:router')
})
it('rejects absent, unknown and non-helper values', () => {
expect(parseHelperSel(undefined)).toBeNull()
expect(parseHelperSel('helper:nope')).toBeNull()
expect(parseHelperSel('helper:')).toBeNull()
expect(parseHelperSel('user:router')).toBeNull()
})
it('opens the first form for a bare "helper" selection', () => {
expect(parseHelperSel('helper')).toBe(HELPER_IDS[0])
})
it('has a label for every id', () => {
for (const id of HELPER_IDS) expect(HELPER_LABEL[id]).toBeTruthy()
})
})
+27
View File
@@ -0,0 +1,27 @@
/** The ChangeHelper forms, in picker order; the single source for the Config page's `sel=helper:<id>` hash and the form switch. */
export const HELPER_IDS = ['limits', 'grant', 'pricing', 'model', 'router', 'user'] as const
export type HelperId = (typeof HELPER_IDS)[number]
export const HELPER_LABEL: Record<HelperId, string> = {
limits: 'Limits',
grant: 'Access grant',
pricing: 'Pricing',
model: 'Model metadata',
router: 'Smart router',
user: 'New user',
}
const PREFIX = 'helper'
export function formatHelperSel(id: HelperId): string {
return `${PREFIX}:${id}`
}
/** A bare `helper` opens the first form; an unknown id or foreign kind is null. */
export function parseHelperSel(v: string | undefined): HelperId | null {
if (v === PREFIX) return HELPER_IDS[0]
if (!v?.startsWith(`${PREFIX}:`)) return null
const id = v.slice(PREFIX.length + 1)
return (HELPER_IDS as readonly string[]).includes(id) ? (id as HelperId) : null
}
+103 -39
View File
@@ -1,64 +1,128 @@
<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { faChevronDown, faChevronRight } from '@fortawesome/free-solid-svg-icons'
import { Button, Callout, Card, CardAction, CardContent, CardHeader, CardTitle, SearchInput, YamlViewer } from '@perfect-design/ui'
import { computed, onMounted, ref } from 'vue'
import ChangeHelper from '@/components/ChangeHelper.vue'
import ConfigTree from '@/components/ConfigTree.vue'
import ErrorState from '@/components/ErrorState.vue'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { copyText } from '@/lib/clipboard'
import { filterSections, splitConfigSections } from '@/lib/config-sections'
import { formatHelperSel, parseHelperSel } from '@/lib/helper-forms'
import type { HelperId } from '@/lib/helper-forms'
import { loadState } from '@/lib/load-state'
import { emitYamlDocument, toYamlValue } from '@/lib/yaml-emit'
import type { YamlValue } from '@/lib/yaml-emit'
import ChangeHelperPanel from '@/panels/ChangeHelperPanel.vue'
import { useConfigStore } from '@/stores/config'
import { useConsumersStore } from '@/stores/consumers'
import { useDashboardStore } from '@/stores/dashboard'
import { useNavStore } from '@/stores/nav'
import { useToastsStore } from '@/stores/toasts'
import StateView from '@/widgets/StateView.vue'
import type { ViewState } from '@/widgets/StateView.vue'
/**
* ConfigPage (redesign-plan.md section 3.4) composes the redacted config
* tree (ConfigTree.vue, GET /admin/api/config, fetched on demand) above
* the change helper (ChangeHelper.vue's five snippet-building forms) —
* group/user names for those forms' target pickers come from the already-
* polled dashboard store (overview.groups) and the on-demand consumers
* store (users), so this page fetches config once and reuses whatever the
* other two stores already have rather than a third redundant call.
*/
const config = useConfigStore()
const dashboard = useDashboardStore()
const consumers = useConsumersStore()
const dashboard = useDashboardStore()
const nav = useNavStore()
const toasts = useToastsStore()
onMounted(() => {
void config.ensureConfig()
void consumers.ensureConsumers()
})
const groupNames = computed(() => (dashboard.overview?.groups ?? []).map((g) => g.name))
// The server redacts secrets before this response; the page renders it as received and never rewrites values.
const yamlText = computed(() => (config.data ? emitYamlDocument(toYamlValue(config.data.config) as Record<string, YamlValue | undefined>) : ''))
const sections = computed(() => splitConfigSections(yamlText.value))
const query = ref('')
const shown = computed(() => filterSections(sections.value, query.value))
const collapsed = ref<Set<string>>(new Set())
function toggle(key: string): void {
const next = new Set(collapsed.value)
if (!next.delete(key)) next.add(key)
collapsed.value = next
}
function jump(key: string): void {
query.value = ''
const next = new Set(collapsed.value)
next.delete(key)
collapsed.value = next
requestAnimationFrame(() => document.getElementById(`cfg-${key}`)?.scrollIntoView({ block: 'start' }))
}
const state = computed<ViewState>(() => {
const s = loadState({ loading: config.loading, hasData: config.data !== null, error: config.error })
if (s === 'skeleton') return 'loading'
if (s === 'error') return 'error'
return sections.value.length === 0 ? 'empty' : 'ready'
})
const warnings = computed(() => config.data?.warnings ?? [])
const warningsDropped = computed(() => dashboard.overview?.warningsDropped ?? 0)
async function copyConfig(): Promise<void> {
const result = await copyText(yamlText.value)
toasts.push(result === 'copied' ? { kind: 'success', message: 'Config copied.' } : { kind: 'error', message: 'Could not copy the config.' })
}
// --- Change helper sheet: lives in the hash as sel=helper:<form> ---
const helperForm = computed(() => parseHelperSel(nav.params.sel))
const groupNames = computed(() => (consumers.data?.groups ?? []).map((g) => g.name))
const userNames = computed(() => (consumers.data?.users ?? []).map((u) => u.name))
function openHelper(): void {
nav.openSheet(formatHelperSel(helperForm.value ?? 'limits'))
}
function selectForm(id: HelperId): void {
nav.swapSheet(formatHelperSel(id))
}
</script>
<template>
<div class="flex flex-col gap-6">
<Card v-if="config.error && !config.data">
<CardHeader>
<div class="flex flex-col gap-4">
<Card size="sm">
<CardHeader class="items-center">
<CardTitle>Config</CardTitle>
<CardAction class="flex items-center gap-2 self-center">
<span v-if="config.data?.version" class="text-muted-foreground font-mono text-xs">{{ config.data.version }}</span>
<Button variant="outline" size="sm" :disabled="!yamlText" @click="copyConfig">Copy config</Button>
<Button size="sm" @click="openHelper">Change helper</Button>
</CardAction>
</CardHeader>
<CardContent>
<ErrorState :message="config.error" :on-retry="config.fetchConfig" />
</CardContent>
</Card>
<!-- Mirrors ConfigTree's own final SnippetBlock shape (a label line above a bordered block) so it causes no layout shift once the real config arrives. -->
<Card v-else-if="config.loading && !config.data">
<CardContent class="flex flex-col gap-1.5">
<Skeleton class="h-3 w-56" />
<Skeleton class="h-64 w-full rounded-md" />
</CardContent>
</Card>
<ConfigTree v-else-if="config.data" :config="config.data.config" :warnings="config.data.warnings" />
<CardContent class="flex flex-col gap-3">
<div v-if="warnings.length > 0" class="flex flex-col gap-2" data-testid="config-warnings">
<Callout v-for="(w, i) in warnings" :key="i" type="warning" size="sm" title="Config warning">
<span class="font-mono text-xs break-words">{{ w }}</span>
</Callout>
<p v-if="warningsDropped > 0" class="text-muted-foreground m-0 text-xs">{{ warningsDropped.toLocaleString('en-US') }} more warnings were dropped by the server cap.</p>
</div>
<Card>
<CardHeader>
<CardTitle>Change helper</CardTitle>
<CardDescription>Build a paste-ready snippet for middleware.yaml or users.json — nothing here writes to the running config.</CardDescription>
</CardHeader>
<CardContent>
<ChangeHelper :group-names="groupNames" :user-names="userNames" />
<StateView :state="state" empty-title="No config returned" :error-message="config.error" @retry="config.fetchConfig()">
<div class="flex flex-col gap-2">
<SearchInput v-model="query" size="sm" class="max-w-sm" placeholder="Filter sections" aria-label="Filter config sections" />
<nav class="flex flex-wrap gap-1" aria-label="Config sections">
<Button v-for="s in sections" :key="s.key" variant="ghost" size="xs" class="font-mono" @click="jump(s.key)">{{ s.key }}</Button>
</nav>
<p v-if="shown.length === 0" class="text-muted-foreground m-0 py-3 text-sm">No section matches "{{ query }}".</p>
<section v-for="s in shown" :id="`cfg-${s.key}`" :key="s.key" class="border-border flex flex-col border-t first:border-t-0" :aria-label="s.key">
<button
type="button"
class="hover:bg-accent focus-visible:ring-ring flex h-8 w-full items-center gap-2 rounded px-2 text-left focus-visible:ring-2 focus-visible:outline-none"
:aria-expanded="!collapsed.has(s.key)"
@click="toggle(s.key)"
>
<FontAwesomeIcon :icon="collapsed.has(s.key) ? faChevronRight : faChevronDown" class="text-muted-foreground size-3" aria-hidden="true" />
<span class="font-mono text-sm font-medium">{{ s.key }}</span>
<span class="text-muted-foreground ml-auto font-mono text-xs tabular-nums">{{ s.lineCount.toLocaleString('en-US') }} lines</span>
</button>
<YamlViewer v-if="!collapsed.has(s.key)" :source="s.text" :start-line="s.startLine" variant="plain" size="sm" line-numbers foldable :copy="false" :label="`${s.key} config`" />
</section>
</div>
</StateView>
</CardContent>
</Card>
<ChangeHelperPanel v-if="helperForm" :form="helperForm" :group-names="groupNames" :user-names="userNames" @select="selectForm" @close="nav.closePanel()" />
</div>
</template>
+53
View File
@@ -0,0 +1,53 @@
<script setup lang="ts">
import { Button, Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@perfect-design/ui'
import GrantForm from '@/components/forms/GrantForm.vue'
import LimitsForm from '@/components/forms/LimitsForm.vue'
import ModelMetaForm from '@/components/forms/ModelMetaForm.vue'
import PricingForm from '@/components/forms/PricingForm.vue'
import RouterForm from '@/components/forms/RouterForm.vue'
import UserForm from '@/components/forms/UserForm.vue'
import { HELPER_IDS, HELPER_LABEL } from '@/lib/helper-forms'
import type { HelperId } from '@/lib/helper-forms'
defineProps<{ form: HelperId; groupNames: string[]; userNames: string[] }>()
const emit = defineEmits<{ close: []; select: [id: HelperId] }>()
function onOpen(open: boolean): void {
if (!open) emit('close')
}
</script>
<template>
<Sheet :open="true" @update:open="onOpen">
<SheetContent side="right" size="lg" data-panel-kind="helper" :data-panel-id="form">
<SheetHeader>
<SheetTitle>Change helper</SheetTitle>
<SheetDescription>Build a paste-ready snippet for middleware.yaml or users.json. Nothing here changes the running config.</SheetDescription>
</SheetHeader>
<div class="min-w-0 flex-1 overflow-y-auto" data-panel-scroll>
<div class="flex flex-col gap-4 px-1 pb-4">
<div class="flex flex-wrap gap-1" role="group" aria-label="Snippet form">
<Button
v-for="id in HELPER_IDS"
:key="id"
type="button"
size="sm"
:variant="id === form ? 'default' : 'outline'"
:aria-pressed="id === form"
@click="emit('select', id)"
>
{{ HELPER_LABEL[id] }}
</Button>
</div>
<LimitsForm v-if="form === 'limits'" :group-names="groupNames" :user-names="userNames" />
<GrantForm v-else-if="form === 'grant'" :group-names="groupNames" :user-names="userNames" />
<PricingForm v-else-if="form === 'pricing'" />
<ModelMetaForm v-else-if="form === 'model'" />
<RouterForm v-else-if="form === 'router'" />
<UserForm v-else :group-names="groupNames" />
</div>
</div>
</SheetContent>
</Sheet>
</template>
+21
View File
@@ -92,6 +92,27 @@ describe('useNavStore panels', () => {
})
})
describe('useNavStore raw sheet selection', () => {
it('openSheet sets an opaque sel, pushes history and lets close go Back', () => {
const nav = useNavStore()
nav.goTo('config', { q: 'x' })
nav.openSheet('helper:router')
expect(nav.params).toEqual({ q: 'x', sel: 'helper:router' })
expect(nav.pushPending).toBe(true)
expect(nav.panelPushed).toBe(true)
})
it('swapSheet changes sel in place and keeps the pushed marker', () => {
const nav = useNavStore()
nav.openSheet('helper:router')
nav.pushPending = false
nav.swapSheet('helper:limits')
expect(nav.params.sel).toBe('helper:limits')
expect(nav.pushPending).toBe(false)
expect(nav.panelPushed).toBe(true)
})
})
describe('useNavStore no-op navigation', () => {
it('goTo to the identical page and params with replace:false does not leave a push pending', () => {
const nav = useNavStore()
+10 -1
View File
@@ -59,12 +59,21 @@ export const useNavStore = defineStore('nav', {
},
/** Opens a detail panel and pushes a history entry, so Back closes it. */
openPanel(kind: PanelKind, id: string): void {
const sel = formatSel(kind, id)
this.openSheet(formatSel(kind, id))
},
/** Opens a sheet whose `sel` is not an entity panel (e.g. `helper:router`), pushing a history entry like openPanel. */
openSheet(sel: string): void {
if (this.params.sel === sel) return
this.params = { ...this.params, sel }
this.pushPending = true
this.panelPushed = true
},
/** Switches the open sheet's `sel` in place: no new history entry, and Back still closes it. */
swapSheet(sel: string): void {
if (this.params.sel === sel) return
this.params = { ...this.params, sel }
this.pushPending = false
},
/** Goes Back when the panel owns the last history entry; otherwise drops `sel` in place. */
closePanel(): void {
if (this.panelPushed && typeof window !== 'undefined') {