fix(webui): compact config viewer, clear unknown helper sel, harness port guard

This commit is contained in:
2026-11-25 11:52:38 +00:00
parent 1f8bdd8777
commit 945621a3c5
9 changed files with 123 additions and 16 deletions
+7
View File
@@ -100,3 +100,10 @@ npm run build # what `make admin-ui` runs, plus webui/generate.mjs
- `generate.mjs` — reads `dist/` after `vite build` and writes
`../admin_assets_gen.go`; see its own header comment for why every
asset is base64-encoded rather than embedded as a raw string literal.
## Visual harness
`npm run test:visual` starts the mock dev server on `PW_PORT` (default 5199)
and fails fast if that port is taken, so two runs cannot share one server or
the `.screenshots/` output. Set `PW_REUSE=1` to attach to a server you
already started.
+28 -3
View File
@@ -183,13 +183,38 @@ test('config change helper opens from the header and Back closes it', async ({ p
await expect(page.locator('[data-panel-kind="helper"]')).toHaveCount(0)
})
test('config sections fold, filter and the copied text is redacted', async ({ page }) => {
test('config page starts compact on desktop', async ({ page }) => {
await page.setViewportSize(VIEWPORTS.desktop)
await visit(page, '#config', 'live', 'light')
const height = await page.evaluate(() => document.documentElement.scrollHeight)
expect(height).toBeLessThan(2500)
})
test('config clears an unknown helper sel with replace', async ({ page }) => {
await page.setViewportSize(VIEWPORTS.desktop)
await visit(page, '#config', 'live', 'light')
const before = await page.evaluate(() => history.length)
await page.goto(page.url().replace(/#.*/, '#config?sel=helper:bogus'))
await expect(page).not.toHaveURL(/sel=/)
await expect(page.locator('[data-panel-kind="helper"]')).toHaveCount(0)
expect(await page.evaluate(() => history.length)).toBeLessThanOrEqual(before + 1)
})
// Smoke check only: the page never renders secret-shaped strings. The real redaction guard is the Go side
// (admin_config_guard_test.go, nonSecretConfigKeys); a fixture that redacts would test the mock, not the product.
test('config sections fold and filter, and the page shows no secret-shaped strings', async ({ page }) => {
await page.setViewportSize(VIEWPORTS.desktop)
await visit(page, '#config', 'live', 'light')
const providers = page.getByRole('region', { name: 'providers', exact: true })
const toggle = providers.getByRole('button', { name: /providers/ }).first()
await expect(toggle).toHaveAttribute('aria-expanded', 'false')
await expect(providers.getByText('baseUrl')).toHaveCount(0)
await toggle.click()
await expect(providers.getByText('baseUrl').first()).toBeVisible()
await providers.getByRole('button', { name: /providers/ }).first().click()
await expect(providers.getByRole('button', { name: /providers/ }).first()).toHaveAttribute('aria-expanded', 'false')
await page.getByRole('button', { name: 'Collapse all' }).click()
await expect(toggle).toHaveAttribute('aria-expanded', 'false')
await page.getByRole('button', { name: 'Expand all' }).click()
await expect(toggle).toHaveAttribute('aria-expanded', 'true')
await page.getByLabel('Filter config sections').fill('redis')
await expect(page.getByRole('region', { name: 'redis', exact: true })).toBeVisible()
await expect(page.getByRole('region', { name: 'providers', exact: true })).toHaveCount(0)
+3 -2
View File
@@ -1,6 +1,7 @@
import { defineConfig } from '@playwright/test'
const PORT = 5199
// PW_PORT sets the dev-server port; PW_REUSE=1 attaches to a running server (default: fail fast, so two runs cannot share one).
const PORT = Number(process.env.PW_PORT ?? 5199)
export default defineConfig({
testDir: './e2e',
@@ -14,7 +15,7 @@ export default defineConfig({
webServer: {
command: `npm run dev:mock -- --port ${PORT} --strictPort`,
url: `http://localhost:${PORT}/admin/`,
reuseExistingServer: !process.env.CI,
reuseExistingServer: process.env.PW_REUSE === '1',
timeout: 60_000,
},
})
+3 -1
View File
@@ -10,11 +10,13 @@ import { useHashState } from '@/composables/useHashState'
import AppLayout from '@/layout/AppLayout.vue'
import type { PageId } from '@/lib/pages'
import { useAuthStore } from '@/stores/auth'
import { useConfigStore } from '@/stores/config'
import { useDashboardStore } from '@/stores/dashboard'
import { useNavStore } from '@/stores/nav'
import { resetSessionData } from '@/stores/session'
const auth = useAuthStore()
const config = useConfigStore()
const dashboard = useDashboardStore()
const nav = useNavStore()
@@ -74,7 +76,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 v-if="nav.page !== 'config'" :warnings="dashboard.overview?.warnings ?? []" :warnings-dropped="dashboard.overview?.warningsDropped" />
<ConfigWarningsBanner v-if="nav.page !== 'config' || (config.error !== '' && !config.data)" :warnings="dashboard.overview?.warnings ?? []" :warnings-dropped="dashboard.overview?.warningsDropped" />
<component :is="currentPage" />
</AppLayout>
<ToastViewport />
+19 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { filterSections, splitConfigSections } from '@/lib/config-sections'
import { filterSections, initialFold, 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')
@@ -42,3 +42,21 @@ describe('filterSections', () => {
expect(filterSections(s, 'zzz')).toEqual([])
})
})
describe('initialFold', () => {
const big = (key: string, n: number) => [`${key}:`, ...Array.from({ length: n - 1 }, (_, i) => ` k${i}: v`)].join('\n')
const secs = splitConfigSections([big('small', 8), big('medium', 9), big('large', 40)].join('\n'))
it('collapses sections over 8 lines and keeps small ones open', () => {
expect([...initialFold(secs, {})].sort()).toEqual(['large', 'medium'])
})
it('keeps the hash target open', () => {
expect([...initialFold(secs, { target: 'large' })]).toEqual(['medium'])
})
it('keeps filter matches open', () => {
expect([...initialFold(secs, { filter: 'med' })]).toEqual(['large'])
})
it('ignores a blank filter and an unknown target', () => {
expect([...initialFold(secs, { filter: ' ', target: 'nope' })].sort()).toEqual(['large', 'medium'])
})
})
+11
View File
@@ -38,3 +38,14 @@ export function filterSections(sections: ConfigSection[], query: string): Config
const q = query.trim().toLowerCase()
return q === '' ? sections : sections.filter((s) => s.key.toLowerCase().includes(q))
}
const SMALL_SECTION_LINES = 8
/** Keys of the sections that start collapsed: all but small ones, filter matches and the jump target. */
export function initialFold(sections: ConfigSection[], opts: { filter?: string; target?: string }): Set<string> {
const matched = new Set(filterSections(sections, opts.filter ?? '').map((s) => s.key))
const filtering = (opts.filter ?? '').trim() !== ''
return new Set(
sections.filter((s) => s.lineCount > SMALL_SECTION_LINES && s.key !== opts.target && !(filtering && matched.has(s.key))).map((s) => s.key),
)
}
+12 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { HELPER_IDS, HELPER_LABEL, formatHelperSel, parseHelperSel } from '@/lib/helper-forms'
import { HELPER_IDS, HELPER_LABEL, formatHelperSel, isStaleHelperSel, parseHelperSel } from '@/lib/helper-forms'
describe('helper selection', () => {
it('round-trips every helper id', () => {
@@ -22,3 +22,14 @@ describe('helper selection', () => {
for (const id of HELPER_IDS) expect(HELPER_LABEL[id]).toBeTruthy()
})
})
describe('isStaleHelperSel', () => {
it('is false when absent or a valid helper', () => {
expect(isStaleHelperSel(undefined)).toBe(false)
expect(isStaleHelperSel('helper:router')).toBe(false)
})
it('is true for an unknown helper id or a foreign sel the Config page cannot open', () => {
expect(isStaleHelperSel('helper:bogus')).toBe(true)
expect(isStaleHelperSel('user:alice')).toBe(true)
})
})
+5
View File
@@ -25,3 +25,8 @@ export function parseHelperSel(v: string | undefined): HelperId | null {
const id = v.slice(PREFIX.length + 1)
return (HELPER_IDS as readonly string[]).includes(id) ? (id as HelperId) : null
}
/** True when `sel` is set but opens no helper form; the Config page has no other sheet, so it clears such a value. */
export function isStaleHelperSel(v: string | undefined): boolean {
return v !== undefined && parseHelperSel(v) === null
}
+35 -8
View File
@@ -1,11 +1,11 @@
<script setup lang="ts">
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 { computed, nextTick, onMounted, ref, watch } from 'vue'
import { copyText } from '@/lib/clipboard'
import { filterSections, splitConfigSections } from '@/lib/config-sections'
import { formatHelperSel, parseHelperSel } from '@/lib/helper-forms'
import { filterSections, initialFold, splitConfigSections } from '@/lib/config-sections'
import { formatHelperSel, isStaleHelperSel, 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'
@@ -36,6 +36,13 @@ const sections = computed(() => splitConfigSections(yamlText.value))
const query = ref('')
const shown = computed(() => filterSections(sections.value, query.value))
const collapsed = ref<Set<string>>(new Set())
const target = computed(() => nav.params.section)
// Default fold: big sections closed, small ones, filter matches and the hash target open.
function resetFold(): void {
collapsed.value = initialFold(sections.value, { filter: query.value, target: target.value })
}
watch([sections, query], resetFold, { immediate: true })
function toggle(key: string): void {
const next = new Set(collapsed.value)
@@ -43,12 +50,18 @@ function toggle(key: string): void {
collapsed.value = next
}
function jump(key: string): void {
query.value = ''
function setAll(open: boolean): void {
collapsed.value = open ? new Set() : new Set(sections.value.map((s) => s.key))
}
async function jump(key: string): Promise<void> {
const next = new Set(collapsed.value)
next.delete(key)
query.value = ''
await nextTick()
collapsed.value = next
requestAnimationFrame(() => document.getElementById(`cfg-${key}`)?.scrollIntoView({ block: 'start' }))
await nextTick()
document.getElementById(`cfg-${key}`)?.scrollIntoView({ block: 'start' })
}
const state = computed<ViewState>(() => {
@@ -68,6 +81,16 @@ async function copyConfig(): Promise<void> {
// --- Change helper sheet: lives in the hash as sel=helper:<form> ---
const helperForm = computed(() => parseHelperSel(nav.params.sel))
// This page has no entity panels, so any other `sel` is stale: drop it in place, like resolveSel does elsewhere.
watch(
() => nav.params.sel,
(sel) => {
if (!isStaleHelperSel(sel)) return
const { sel: _sel, ...rest } = nav.params
nav.goTo('config', rest)
},
{ immediate: true },
)
const groupNames = computed(() => (consumers.data?.groups ?? []).map((g) => g.name))
const userNames = computed(() => (consumers.data?.users ?? []).map((u) => u.name))
@@ -101,6 +124,10 @@ function selectForm(id: HelperId): void {
<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" />
<div class="flex flex-wrap items-center gap-1">
<Button variant="outline" size="xs" @click="setAll(true)">Expand all</Button>
<Button variant="outline" size="xs" @click="setAll(false)">Collapse all</Button>
</div>
<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>
@@ -114,9 +141,9 @@ function selectForm(id: HelperId): void {
>
<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>
<span class="text-muted-foreground ml-auto font-mono text-xs tabular-nums">{{ s.lineCount.toLocaleString('en-US') }} {{ s.lineCount === 1 ? 'line' : '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`" />
<YamlViewer v-if="!collapsed.has(s.key)" :source="s.text" :start-line="s.startLine" variant="plain" size="sm" line-numbers :foldable="false" :copy="false" :label="`${s.key} config`" />
</section>
</div>
</StateView>