Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

feat(docs): edit a document's tags, and say they exist

Pouzor94f42cf9c5a3
diff --git a/backend/app/services/doc_template.py b/backend/app/services/doc_template.py
index 2c5e3ae..18a327b 100644
--- a/backend/app/services/doc_template.py
+++ b/backend/app/services/doc_template.py
@@ -379,10 +379,15 @@ def render_frontmatter(values: dict[str, Any]) -> str:
Hand-rolled rather than `yaml.safe_dump` so key order is the order written
here — the frontmatter is read by humans at the top of every document.
+
+ An empty list still prints. `tags: []` is the only advertisement tags have:
+ dropped, the key never appears in any document and nobody learns it exists.
+ An empty string is still dropped — `owner:` teaches nothing a reader of the
+ template does not already see.
"""
lines = ["---"]
for key, value in values.items():
- if value is None or value == "" or value == []:
+ if value is None or value == "":
continue
if isinstance(value, list):
lines.append(f"{key}: [{', '.join(str(v) for v in value)}]")
diff --git a/backend/tests/test_doc_template.py b/backend/tests/test_doc_template.py
index 023c95c..109d099 100644
--- a/backend/tests/test_doc_template.py
+++ b/backend/tests/test_doc_template.py
@@ -310,6 +310,11 @@ def test_device_document_opens_with_versioned_frontmatter():
assert "device: dev-1" in md
assert "created: 2026-09-05" in md
assert "review_every: 6m" in md
+ assert "tags: []" in md
+
+
+def test_library_document_advertises_tags_too():
+ assert "tags: []" in t.render_library_document(t.TEMPLATE_RUNBOOK, "Reboot the NAS")
def test_device_document_appends_old_notes_verbatim_with_provenance():
@@ -363,9 +368,10 @@ def test_unknown_template_falls_back_to_blank_rather_than_failing():
assert "# Scratch" in md
-def test_frontmatter_omits_empty_values():
+def test_frontmatter_omits_empty_scalars_but_prints_an_empty_list():
+ # `tags: []` is how a user learns tags exist at all, so an empty list stays.
rendered = t.render_frontmatter({"a": 1, "b": None, "c": "", "d": [], "e": ["x", "y"]})
- assert rendered == "---\na: 1\ne: [x, y]\n---"
+ assert rendered == "---\na: 1\nd: []\ne: [x, y]\n---"
# ── the drift snapshot ──────────────────────────────────────────────────────
diff --git a/frontend/src/documentation/__tests__/DocViewer.test.tsx b/frontend/src/documentation/__tests__/DocViewer.test.tsx
new file mode 100644
index 0000000..dcfab29
--- /dev/null
+++ b/frontend/src/documentation/__tests__/DocViewer.test.tsx
@@ -0,0 +1,94 @@
+/**
+ * The chips under a document title are its editor for tags: the frontmatter
+ * key most documents never grow because nobody knows it is there.
+ */
+import { describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen } from '@testing-library/react'
+
+import { DocViewer } from '../components/DocViewer'
+import type { Doc } from '../types'
+
+function makeDoc(overrides: Partial<Doc> = {}): Doc {
+ return {
+ id: 'doc-1',
+ kind: 'page',
+ title: 'NAS',
+ slug: 'nas',
+ sort_order: 0,
+ tags: [],
+ frontmatter: {},
+ starred: false,
+ body: '---\ntitle: NAS\n---\n\n# NAS\n',
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ ...overrides,
+ } as Doc
+}
+
+const noop = {
+ docs: [],
+ devices: [],
+ drifted: false,
+ onEdit: vi.fn(),
+ onToggleStar: vi.fn(),
+ onMarkReviewed: vi.fn(),
+ onRegenerate: vi.fn(),
+ onDelete: vi.fn(),
+ onOpenDoc: vi.fn(),
+ onCreateFromLink: vi.fn(),
+ onToggleTask: vi.fn(),
+}
+
+function addTag(text: string) {
+ fireEvent.click(screen.getByText('Tag'))
+ const input = screen.getByLabelText('New tag')
+ fireEvent.change(input, { target: { value: text } })
+ fireEvent.keyDown(input, { key: 'Enter' })
+}
+
+describe('DocViewer — tags', () => {
+ it('adds a typed tag to the ones already there', () => {
+ const onSetTags = vi.fn()
+ render(<DocViewer {...noop} doc={makeDoc({ tags: ['prod'] })} onSetTags={onSetTags} />)
+ addTag('backup')
+ expect(onSetTags).toHaveBeenCalledWith(['prod', 'backup'])
+ })
+
+ it('takes a whole list from one field', () => {
+ const onSetTags = vi.fn()
+ render(<DocViewer {...noop} doc={makeDoc()} onSetTags={onSetTags} />)
+ addTag(' web , prod ')
+ expect(onSetTags).toHaveBeenCalledWith(['web', 'prod'])
+ })
+
+ it('does not add a tag the document already carries, whatever its case', () => {
+ const onSetTags = vi.fn()
+ render(<DocViewer {...noop} doc={makeDoc({ tags: ['Prod'] })} onSetTags={onSetTags} />)
+ addTag('prod')
+ expect(onSetTags).not.toHaveBeenCalled()
+ })
+
+ it('removes the tag whose chip was crossed out', () => {
+ const onSetTags = vi.fn()
+ render(<DocViewer {...noop} doc={makeDoc({ tags: ['prod', 'backup'] })} onSetTags={onSetTags} />)
+ fireEvent.click(screen.getByLabelText('Remove tag prod'))
+ expect(onSetTags).toHaveBeenCalledWith(['backup'])
+ })
+
+ it('writes nothing when the field is abandoned with Escape', () => {
+ const onSetTags = vi.fn()
+ render(<DocViewer {...noop} doc={makeDoc()} onSetTags={onSetTags} />)
+ fireEvent.click(screen.getByText('Tag'))
+ const input = screen.getByLabelText('New tag')
+ fireEvent.change(input, { target: { value: 'backup' } })
+ fireEvent.keyDown(input, { key: 'Escape' })
+ expect(onSetTags).not.toHaveBeenCalled()
+ expect(screen.queryByLabelText('New tag')).not.toBeInTheDocument()
+ })
+
+ it('offers the field back after a tag is added', () => {
+ render(<DocViewer {...noop} doc={makeDoc()} onSetTags={vi.fn()} />)
+ addTag('backup')
+ expect(screen.getByText('Tag')).toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/documentation/__tests__/frontmatter.test.ts b/frontend/src/documentation/__tests__/frontmatter.test.ts
index 1725fe7..f295a11 100644
--- a/frontend/src/documentation/__tests__/frontmatter.test.ts
+++ b/frontend/src/documentation/__tests__/frontmatter.test.ts
@@ -7,6 +7,7 @@ import {
summaryOf,
tagsOf,
withFrontmatter,
+ withTags,
} from '../frontmatter'
describe('parseFrontmatter', () => {
@@ -55,6 +56,42 @@ describe('parseFrontmatter', () => {
})
})
+describe('withTags', () => {
+ it('replaces an inline list and leaves every other line as written', () => {
+ const body = '---\ntitle: NAS\ntags: [old]\ncreated: 2026-09-07\n---\n\n# NAS\n'
+ expect(withTags(body, ['a', 'b'])).toBe(
+ '---\ntitle: NAS\ntags: [a, b]\ncreated: 2026-09-07\n---\n\n# NAS\n',
+ )
+ })
+
+ it('replaces a block list with its items', () => {
+ const body = '---\ntags:\n - old\n - older\nowner: me\n---\n\n# NAS\n'
+ expect(withTags(body, ['a'])).toBe('---\ntags: [a]\nowner: me\n---\n\n# NAS\n')
+ })
+
+ it('adds the key to a block that has none', () => {
+ expect(parseFrontmatter(withTags('---\ntitle: NAS\n---\n\n# NAS\n', ['a'])).data).toEqual({
+ title: 'NAS',
+ tags: ['a'],
+ })
+ })
+
+ it('opens a block on a body that has none', () => {
+ const next = withTags('# NAS', ['a'])
+ expect(parseFrontmatter(next).data).toEqual({ tags: ['a'] })
+ expect(parseFrontmatter(next).content.trim()).toBe('# NAS')
+ })
+
+ it('empties the list rather than dropping the key — the key is how tags are found', () => {
+ expect(withTags('---\ntags: [a]\n---\n', [])).toBe('---\ntags: []\n---\n')
+ })
+
+ it('quotes a tag flow style would misread', () => {
+ const next = withTags('---\ntitle: NAS\n---\n', ['needs: review', 'plain'])
+ expect(parseFrontmatter(next).data.tags).toEqual(['needs: review', 'plain'])
+ })
+})
+
describe('withFrontmatter', () => {
it('replaces an existing block, keeping the body', () => {
const next = withFrontmatter('---\ntitle: Old\n---\n\n# Body\n', { title: 'New' })
diff --git a/frontend/src/documentation/__tests__/store.test.ts b/frontend/src/documentation/__tests__/store.test.ts
index 7a197b5..511ef92 100644
--- a/frontend/src/documentation/__tests__/store.test.ts
+++ b/frontend/src/documentation/__tests__/store.test.ts
@@ -264,6 +264,26 @@ describe('mutations', () => {
expect(useDocsStore.getState().docs[0].starred).toBe(true)
})
+ it('writes tags into the body, because the body owns them', async () => {
+ api.update.mockResolvedValue({ data: doc({ tags: ['prod'] }) } as never)
+ useDocsStore.setState({ docs: [summary()], openDoc: doc({ body: '---\ntitle: NAS\n---\n\n# NAS\n' }) })
+ await useDocsStore.getState().setTags(['prod'])
+ expect(api.update).toHaveBeenCalledWith('doc-1', { body: '---\ntitle: NAS\ntags: [prod]\n---\n\n# NAS\n' })
+ expect(useDocsStore.getState().docs[0].tags).toEqual(['prod'])
+ })
+
+ it('reports a failed tag write rather than pretending it landed', async () => {
+ api.update.mockRejectedValue({ response: { data: { detail: 'nope' } } })
+ useDocsStore.setState({ openDoc: doc() })
+ expect(await useDocsStore.getState().setTags(['prod'])).toBe(false)
+ expect(useDocsStore.getState().loadError).toBe('nope')
+ })
+
+ it('has no tags to write with no document open', async () => {
+ expect(await useDocsStore.getState().setTags(['prod'])).toBe(false)
+ expect(api.update).not.toHaveBeenCalled()
+ })
+
it('accepts the current facts without touching the body', async () => {
api.update.mockResolvedValue({ data: doc() } as never)
useDocsStore.setState({ docs: [summary()] })
diff --git a/frontend/src/documentation/components/DocViewer.tsx b/frontend/src/documentation/components/DocViewer.tsx
index a567349..1b1e10b 100644
--- a/frontend/src/documentation/components/DocViewer.tsx
+++ b/frontend/src/documentation/components/DocViewer.tsx
@@ -1,5 +1,5 @@
-import { useMemo } from 'react'
-import { Clock, Pencil, RefreshCw, Star, Trash2 } from 'lucide-react'
+import { useMemo, useState } from 'react'
+import { Clock, Pencil, Plus, RefreshCw, Star, Trash2, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
@@ -22,6 +22,8 @@ interface Props {
onOpenDoc: (id: string) => void
onCreateFromLink: (label: string) => void
onToggleTask: (body: string) => void
+ /** Writes the whole tag list back into the document's frontmatter. */
+ onSetTags: (tags: string[]) => void
}
/** The metadata a frontmatter block is worth surfacing as a chip. */
@@ -44,11 +46,28 @@ export function DocViewer({
onOpenDoc,
onCreateFromLink,
onToggleTask,
+ onSetTags,
}: Props) {
const { data } = useMemo(() => parseFrontmatter(doc.body), [doc.body])
+ const [tagDraft, setTagDraft] = useState<string | null>(null)
const toc = useMemo(() => extractToc(doc.body), [doc.body])
const overdue = isOverdue(data, doc.reviewed_at, doc.created_at)
+ // One field takes a whole list: "web, prod" adds two tags, and a tag already
+ // on the document is not added twice whatever its case.
+ function commitTags() {
+ const known = new Set(doc.tags.map((tag) => tag.toLowerCase()))
+ const added: string[] = []
+ for (const raw of (tagDraft ?? '').split(',')) {
+ const tag = raw.trim()
+ if (!tag || known.has(tag.toLowerCase())) continue
+ known.add(tag.toLowerCase())
+ added.push(tag)
+ }
+ if (added.length) onSetTags([...doc.tags, ...added])
+ setTagDraft(null)
+ }
+
return (
<div className="flex min-h-0 flex-1">
<div className="min-w-0 flex-1 overflow-y-auto">
@@ -92,10 +111,41 @@ export function DocViewer({
</span>
))}
{doc.tags.map((tag) => (
- <span key={tag} className="rounded bg-primary/10 px-1.5 py-0.5 text-primary">
+ <span key={tag} className="flex items-center gap-1 rounded bg-primary/10 py-0.5 pl-1.5 pr-1 text-primary">
#{tag}
+ <button
+ type="button"
+ aria-label={`Remove tag ${tag}`}
+ onClick={() => onSetTags(doc.tags.filter((t) => t !== tag))}
+ className="cursor-pointer opacity-60 hover:opacity-100"
+ >
+ <X size={10} />
+ </button>
</span>
))}
+ {tagDraft === null ? (
+ <button
+ type="button"
+ onClick={() => setTagDraft('')}
+ className="flex cursor-pointer items-center gap-0.5 rounded bg-muted px-1.5 py-0.5 text-muted-foreground hover:text-foreground"
+ >
+ <Plus size={10} /> Tag
+ </button>
+ ) : (
+ <input
+ autoFocus
+ value={tagDraft}
+ aria-label="New tag"
+ placeholder="tag, tag…"
+ onChange={(event) => setTagDraft(event.target.value)}
+ onBlur={commitTags}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') commitTags()
+ if (event.key === 'Escape') setTagDraft(null)
+ }}
+ className="w-28 rounded bg-muted px-1.5 py-0.5 text-[10px] text-foreground outline-none ring-1 ring-border focus:ring-primary"
+ />
+ )}
{!doc.edited_at && (
<span className="rounded bg-muted px-1.5 py-0.5 text-muted-foreground">
Only the generated header so far
diff --git a/frontend/src/documentation/components/DocumentationView.tsx b/frontend/src/documentation/components/DocumentationView.tsx
index b81f079..37c3b29 100644
--- a/frontend/src/documentation/components/DocumentationView.tsx
+++ b/frontend/src/documentation/components/DocumentationView.tsx
@@ -60,6 +60,7 @@ export function DocumentationView() {
remove,
toggleStar,
markReviewed,
+ setTags,
regenerate,
coverage,
loadCoverage,
@@ -470,6 +471,7 @@ export function DocumentationView() {
onEdit={startEdit}
onToggleStar={() => void toggleStar(openDoc.id)}
onMarkReviewed={() => void markReviewed(openDoc.id)}
+ onSetTags={(tags) => void setTags(tags)}
onRegenerate={() => setRegenerateOpen(true)}
onDelete={() => void handleDelete()}
onOpenDoc={(id) => void open(id)}
diff --git a/frontend/src/documentation/frontmatter.ts b/frontend/src/documentation/frontmatter.ts
index 4056107..9c14f69 100644
--- a/frontend/src/documentation/frontmatter.ts
+++ b/frontend/src/documentation/frontmatter.ts
@@ -43,6 +43,38 @@ export function tagsOf(data: Record<string, unknown>): string[] {
return raw.map((t) => String(t).trim()).filter(Boolean)
}
+/** A tag needs quoting when flow style would read it as YAML syntax. */
+function tagLiteral(tag: string): string {
+ return /[[\]{},:#&*!|>'"%@`]|^\s|\s$/.test(tag) ? JSON.stringify(tag) : tag
+}
+
+/**
+ * Rewrite only the `tags:` entry of the block, leaving every other line byte
+ * for byte as the user wrote it.
+ *
+ * `withFrontmatter` would round-trip the whole block through the YAML dumper,
+ * which reformats what it did not need to touch — `created: 2026-09-07` comes
+ * back as a full timestamp, because that is what the date parsed to. Editing a
+ * tag should not rewrite a date.
+ */
+export function withTags(body: string, tags: string[]): string {
+ const line = `tags: [${tags.map(tagLiteral).join(', ')}]`
+ const match = BLOCK.exec(body ?? '')
+ if (!match) return `---\n${line}\n---\n\n${body ?? ''}`
+ const lines = match[1].split('\n')
+ const at = lines.findIndex((entry) => /^tags[ \t]*:/.test(entry))
+ if (at === -1) {
+ lines.push(line)
+ } else {
+ // The key alone when it was written inline; the key and its items when it
+ // was written as a block list.
+ let end = at + 1
+ while (end < lines.length && /^[ \t]*-[ \t]/.test(lines[end])) end += 1
+ lines.splice(at, end - at, line)
+ }
+ return `---\n${lines.join('\n')}\n---\n${(body ?? '').slice(match[0].length)}`
+}
+
/** Replace the frontmatter block, or add one when the body has none. */
export function withFrontmatter(body: string, data: Record<string, unknown>): string {
const block = `---\n${yaml.dump(data, { lineWidth: 120 }).trimEnd()}\n---\n`
diff --git a/frontend/src/documentation/store.ts b/frontend/src/documentation/store.ts
index 55eb379..3766201 100644
--- a/frontend/src/documentation/store.ts
+++ b/frontend/src/documentation/store.ts
@@ -1,7 +1,7 @@
import { create } from 'zustand'
import { documentsApi } from '@/api/client'
-import { isOverdue } from './frontmatter'
+import { isOverdue, withTags } from './frontmatter'
import { isDescendant } from './tree'
import type {
Doc,
@@ -141,6 +141,8 @@ export interface DocsState {
}) => Promise<Doc | null>
rename: (id: string, title: string) => Promise<void>
move: (id: string, parentId: string | null) => Promise<void>
+ /** Rewrite the `tags:` list in the open document's frontmatter. */
+ setTags: (tags: string[]) => Promise<boolean>
toggleStar: (id: string) => Promise<void>
markReviewed: (id: string) => Promise<void>
resyncFacts: (id: string) => Promise<void>
@@ -338,6 +340,28 @@ export const useDocsStore = create<DocsState>()((set, get) => ({
}))
},
+ // Tags are frontmatter, and the body is what owns them — the `tags` column is
+ // a cache the server refills from it. So this rewrites the block and saves the
+ // body, rather than patching a field the next body save would overwrite. It
+ // writes straight through, like starring: a chip the user clicked off is not
+ // a draft of the document.
+ setTags: async (tags) => {
+ const { openDoc } = get()
+ if (!openDoc) return false
+ const body = withTags(openDoc.body, tags)
+ try {
+ const { data } = await documentsApi.update(openDoc.id, { body })
+ set((state) => ({
+ openDoc: data,
+ docs: state.docs.map((d) => (d.id === data.id ? { ...d, ...data } : d)),
+ }))
+ return true
+ } catch (error) {
+ set({ loadError: message(error, 'Could not save the tags') })
+ return false
+ }
+ },
+
toggleStar: async (id) => {
const current = get().docs.find((d) => d.id === id)
const { data } = await documentsApi.update(id, { starred: !current?.starred })