Skip to content

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

feat(docs): regenerate a document, and only warn about real drift

Pouzor185d9bcacb8b
diff --git a/backend/app/api/routes/documents.py b/backend/app/api/routes/documents.py
index 2f9b63a..43d8c3a 100644
--- a/backend/app/api/routes/documents.py
+++ b/backend/app/api/routes/documents.py
@@ -174,6 +174,43 @@ async def _scaffold_body(db: AsyncSession, doc: Document, template_id: str | Non
doc.template_id = template_id or "blank"
+def _has_drifted(doc: Document, device: InventoryDevice | None) -> bool:
+ """Whether the device has moved on since this document was snapshotted.
+
+ The comparison lives on the server rather than in the UI because
+ `facts_snapshot` is the server's own shape — `label` and `type` are stored
+ through their fallbacks and `properties` as a flat map — so nothing else
+ can compare it to a device row correctly. Same rule as the coverage count.
+ """
+ if not doc.device_id or not doc.facts_snapshot or device is None:
+ return False
+ return doc.facts_snapshot != facts_snapshot(device)
+
+
+async def _devices_for(db: AsyncSession, docs: list[Document]) -> dict[str, InventoryDevice]:
+ """The devices a batch of documents describes, in one query."""
+ wanted = {d.device_id for d in docs if d.device_id and d.facts_snapshot}
+ if not wanted:
+ return {}
+ rows = (
+ await db.execute(select(InventoryDevice).where(InventoryDevice.id.in_(wanted)))
+ ).scalars().all()
+ return {device.id: device for device in rows}
+
+
+def _summary(doc: Document, device: InventoryDevice | None) -> DocumentSummary:
+ payload = DocumentSummary.model_validate(doc)
+ payload.drifted = _has_drifted(doc, device)
+ return payload
+
+
+async def _response(db: AsyncSession, doc: Document) -> DocumentResponse:
+ """One document, with the drift flag resolved against the live device."""
+ payload = DocumentResponse.model_validate(doc)
+ payload.drifted = _has_drifted(doc, await db.get(InventoryDevice, doc.device_id) if doc.device_id else None)
+ return payload
+
+
# ── list / read ─────────────────────────────────────────────────────────────
@@ -197,7 +234,8 @@ async def list_documents(
if tag:
wanted = tag.lower()
docs = [d for d in docs if any(str(t).lower() == wanted for t in (d.tags or []))]
- return [DocumentSummary.model_validate(d) for d in docs]
+ devices = await _devices_for(db, list(docs))
+ return [_summary(d, devices.get(d.device_id or "")) for d in docs]
@router.get("/coverage", response_model=CoverageResponse)
@@ -303,7 +341,7 @@ async def get_document(
doc = await db.get(Document, document_id)
if not doc:
raise HTTPException(404, "Document not found")
- return DocumentResponse.model_validate(doc)
+ return await _response(db, doc)
@router.get("/{document_id}/revisions", response_model=list[RevisionSummary])
@@ -412,7 +450,7 @@ async def create_document(
await doc_search.index_document(db, doc)
await db.commit()
await db.refresh(doc)
- return DocumentResponse.model_validate(doc)
+ return await _response(db, doc)
@router.patch("/{document_id}", response_model=DocumentResponse)
@@ -468,7 +506,7 @@ async def update_document(
await doc_search.index_document(db, doc)
await db.commit()
await db.refresh(doc)
- return DocumentResponse.model_validate(doc)
+ return await _response(db, doc)
@router.post("/{document_id}/revisions/{revision_id}/restore", response_model=DocumentResponse)
@@ -491,7 +529,38 @@ async def restore_revision(
await doc_search.index_document(db, doc)
await db.commit()
await db.refresh(doc)
- return DocumentResponse.model_validate(doc)
+ return await _response(db, doc)
+
+
[email protected]("/{document_id}/regenerate", response_model=DocumentResponse)
+async def regenerate_document(
+ document_id: str,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> DocumentResponse:
+ """Throw the body away and scaffold it again from what the database holds.
+
+ The one place that overwrites a body the user owns, so it is only ever
+ reached from an explicit confirmation. The replaced body is snapshotted
+ first, which makes the whole thing undoable from the history list.
+ """
+ doc = await db.get(Document, document_id)
+ if not doc:
+ raise HTTPException(404, "Document not found")
+ if doc.kind == "folder":
+ raise HTTPException(400, "A folder has no body to regenerate")
+ if doc.device_id and not await db.get(InventoryDevice, doc.device_id):
+ raise HTTPException(404, "Device not found")
+
+ await _record_revision(db, doc, "regenerate")
+ await _scaffold_body(db, doc, doc.template_id)
+ # Back to a freshly generated document: nothing of the user's is left in it.
+ doc.edited_at = None
+ await db.flush()
+ await doc_search.index_document(db, doc)
+ await db.commit()
+ await db.refresh(doc)
+ return await _response(db, doc)
@router.post("/scaffold", response_model=ScaffoldResponse)
diff --git a/backend/app/schemas/documents.py b/backend/app/schemas/documents.py
index 1b4dd6e..c76892b 100644
--- a/backend/app/schemas/documents.py
+++ b/backend/app/schemas/documents.py
@@ -76,6 +76,12 @@ class DocumentSummary(BaseModel):
frontmatter: dict[str, Any] = {}
starred: bool = False
template_id: str | None = None
+ # Whether the device has moved on since the snapshot was taken. Computed by
+ # the server because only the server knows the snapshot's shape: it holds
+ # `label` and `type` through their fallbacks and `properties` as a flat
+ # map, none of which the inventory wire shape can be compared against
+ # field by field.
+ drifted: bool = False
reviewed_at: datetime | None = None
edited_at: datetime | None = None
facts_synced_at: datetime | None = None
diff --git a/backend/tests/test_documents.py b/backend/tests/test_documents.py
index 142b635..05f8b3a 100644
--- a/backend/tests/test_documents.py
+++ b/backend/tests/test_documents.py
@@ -333,6 +333,90 @@ async def test_resyncing_facts_clears_the_drift_without_touching_the_body(client
assert "192.168.1.20" in res.json()["body"]
+# ── drift ───────────────────────────────────────────────────────────────────
+
+
+async def test_a_fresh_device_document_has_not_drifted(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+ assert doc["drifted"] is False
+ read = (await client.get(f"/api/v1/documents/{doc['id']}", headers=headers)).json()
+ assert read["drifted"] is False
+
+
+async def test_changing_the_device_marks_the_document_drifted(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+ await client.patch(
+ f"/api/v1/scan/pending/{device['id']}", json={"ip": "192.168.1.99"}, headers=headers
+ )
+ read = (await client.get(f"/api/v1/documents/{doc['id']}", headers=headers)).json()
+ assert read["drifted"] is True
+
+
+async def test_a_property_edit_alone_marks_the_document_drifted(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+ await client.patch(
+ f"/api/v1/scan/pending/{device['id']}",
+ json={"properties": [{"key": "Rack", "value": "A1"}]},
+ headers=headers,
+ )
+ read = (await client.get(f"/api/v1/documents/{doc['id']}", headers=headers)).json()
+ assert read["drifted"] is True
+
+
+async def test_editing_the_body_does_not_make_a_document_drift(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+ res = await client.patch(f"/api/v1/documents/{doc['id']}", json={"body": "my words"}, headers=headers)
+ assert res.json()["drifted"] is False
+
+
+async def test_accepting_the_facts_clears_the_drift(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+ await client.patch(
+ f"/api/v1/scan/pending/{device['id']}", json={"ip": "192.168.1.99"}, headers=headers
+ )
+ res = await client.patch(
+ f"/api/v1/documents/{doc['id']}", json={"resync_facts": True}, headers=headers
+ )
+ assert res.json()["drifted"] is False
+
+
+async def test_regenerating_clears_the_drift(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+ await client.patch(
+ f"/api/v1/scan/pending/{device['id']}", json={"ip": "192.168.1.99"}, headers=headers
+ )
+ res = await client.post(f"/api/v1/documents/{doc['id']}/regenerate", headers=headers)
+ assert res.json()["drifted"] is False
+
+
+async def test_the_listing_carries_the_drift_flag_for_the_tree_badge(
+ client: AsyncClient, headers: dict
+):
+ fresh = await _device(client, headers, label="switch-01", ip="192.168.1.2")
+ stale = await _device(client, headers, label="nas-01", ip="192.168.1.20")
+ in_sync = await _create(client, headers, title="switch-01", kind="device", device_id=fresh["id"])
+ moved = await _create(client, headers, title="nas-01", kind="device", device_id=stale["id"])
+ await client.patch(
+ f"/api/v1/scan/pending/{stale['id']}", json={"ip": "192.168.1.99"}, headers=headers
+ )
+
+ listing = (await client.get("/api/v1/documents", headers=headers)).json()
+ by_id = {d["id"]: d for d in listing}
+ assert by_id[moved["id"]]["drifted"] is True
+ assert by_id[in_sync["id"]]["drifted"] is False
+
+
+async def test_a_library_page_never_drifts(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="VLAN plan")
+ assert doc["drifted"] is False
+
+
# ── revisions ───────────────────────────────────────────────────────────────
@@ -386,6 +470,75 @@ async def test_history_is_pruned_to_the_limit(client: AsyncClient, headers: dict
assert len(revisions) == REVISION_LIMIT
+# ── regenerate ──────────────────────────────────────────────────────────────
+
+
+async def test_regenerate_requires_auth(client: AsyncClient):
+ assert (await client.post("/api/v1/documents/x/regenerate")).status_code == 401
+
+
+async def test_regenerating_a_device_document_rebuilds_it_from_the_facts(
+ client: AsyncClient, headers: dict
+):
+ device = await _device(client, headers)
+ doc = await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+ await client.patch(f"/api/v1/documents/{doc['id']}", json={"body": "everything I wrote"}, headers=headers)
+
+ res = await client.post(f"/api/v1/documents/{doc['id']}/regenerate", headers=headers)
+ assert res.status_code == 200, res.text
+ body = res.json()
+ assert "everything I wrote" not in body["body"]
+ assert "192.168.1.20" in body["body"]
+ # A regenerated document is only the template again, as it was on day one.
+ assert body["edited_at"] is None
+ assert body["template_id"] == "device"
+
+
+async def test_regenerating_reads_the_devices_current_facts(client: AsyncClient, headers: dict):
+ device = await _device(client, headers)
+ doc = await _create(client, headers, title="nas-01", kind="device", device_id=device["id"])
+ await client.patch(
+ f"/api/v1/scan/pending/{device['id']}", json={"ip": "192.168.1.99"}, headers=headers
+ )
+
+ res = await client.post(f"/api/v1/documents/{doc['id']}/regenerate", headers=headers)
+ assert "192.168.1.99" in res.json()["body"]
+ # Regenerating documents the device as it is now, so the drift is gone.
+ assert res.json()["facts_snapshot"]["ip"] == "192.168.1.99"
+
+
+async def test_regenerating_keeps_the_replaced_body_in_the_history(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="VLAN plan", body="my own words")
+ await client.post(f"/api/v1/documents/{doc['id']}/regenerate", headers=headers)
+
+ revisions = (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json()
+ assert revisions[0]["reason"] == "regenerate"
+ stored = (await client.get(f"/api/v1/documents/revisions/{revisions[0]['id']}", headers=headers)).json()
+ assert stored["body"] == "my own words"
+
+
+async def test_regenerating_a_library_page_uses_its_template(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Restart the NAS", template_id="runbook")
+ await client.patch(f"/api/v1/documents/{doc['id']}", json={"body": "gone"}, headers=headers)
+
+ res = await client.post(f"/api/v1/documents/{doc['id']}/regenerate", headers=headers)
+ assert res.status_code == 200, res.text
+ assert "gone" not in res.json()["body"]
+ assert "# Restart the NAS" in res.json()["body"]
+ assert res.json()["template_id"] == "runbook"
+
+
+async def test_regenerating_a_folder_is_rejected(client: AsyncClient, headers: dict):
+ folder = await _create(client, headers, title="Runbooks", kind="folder")
+ res = await client.post(f"/api/v1/documents/{folder['id']}/regenerate", headers=headers)
+ assert res.status_code == 400
+
+
+async def test_regenerating_an_unknown_document_is_404(client: AsyncClient, headers: dict):
+ res = await client.post(f"/api/v1/documents/{uuid.uuid4()}/regenerate", headers=headers)
+ assert res.status_code == 404
+
+
# ── delete ──────────────────────────────────────────────────────────────────
diff --git a/docs/documentation.md b/docs/documentation.md
index e188892..3293646 100644
--- a/docs/documentation.md
+++ b/docs/documentation.md
@@ -167,6 +167,7 @@ Non-destructive and repeatable.
| `DELETE` | `/api/v1/documents/{id}` — a folder takes its subtree |
| `GET` | `/api/v1/documents/{id}/revisions`, `/revisions/{rev_id}` |
| `POST` | `/api/v1/documents/{id}/revisions/{rev_id}/restore` |
+| `POST` | `/api/v1/documents/{id}/regenerate` — erase the body and scaffold it again |
| `GET` | `/api/v1/documents/search?q=&limit=` |
| `GET` | `/api/v1/documents/blocks?block=&device_id=` |
| `GET` | `/api/v1/documents/coverage` |
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index 89f4f05..85e8cba 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -337,6 +337,8 @@ export const documentsApi = {
),
restore: (id: string, revisionId: string) =>
api.post<import('@/documentation/types').Doc>(`/documents/${id}/revisions/${revisionId}/restore`),
+ regenerate: (id: string) =>
+ api.post<import('@/documentation/types').Doc>(`/documents/${id}/regenerate`),
search: (q: string, limit = 25) =>
api.get<import('@/documentation/types').DocSearchResult>('/documents/search', {
params: { q, limit },
diff --git a/frontend/src/documentation/__tests__/RegenerateDoc.test.tsx b/frontend/src/documentation/__tests__/RegenerateDoc.test.tsx
new file mode 100644
index 0000000..127d383
--- /dev/null
+++ b/frontend/src/documentation/__tests__/RegenerateDoc.test.tsx
@@ -0,0 +1,111 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+
+import { DocViewer } from '../components/DocViewer'
+import { RegenerateDocModal } from '../components/RegenerateDocModal'
+import type { Doc } from '../types'
+
+function doc(overrides: Partial<Doc> = {}): Doc {
+ return {
+ id: 'doc-1',
+ kind: 'device',
+ title: 'nas-01',
+ slug: 'nas-01',
+ sort_order: 0,
+ tags: [],
+ frontmatter: {},
+ starred: false,
+ device_id: 'dev-1',
+ body: '# nas-01\n',
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ ...overrides,
+ } as Doc
+}
+
+function viewer(overrides: Partial<React.ComponentProps<typeof DocViewer>> = {}) {
+ const onRegenerate = vi.fn()
+ render(
+ <DocViewer
+ doc={doc()}
+ docs={[]}
+ devices={[]}
+ drifted={false}
+ onEdit={vi.fn()}
+ onToggleStar={vi.fn()}
+ onMarkReviewed={vi.fn()}
+ onRegenerate={onRegenerate}
+ onDelete={vi.fn()}
+ onOpenDoc={vi.fn()}
+ onCreateFromLink={vi.fn()}
+ onToggleTask={vi.fn()}
+ {...overrides}
+ />,
+ )
+ return { onRegenerate }
+}
+
+describe('the regenerate button', () => {
+ it('asks the view to confirm rather than regenerating on the spot', async () => {
+ const { onRegenerate } = viewer()
+ await userEvent.click(screen.getByRole('button', { name: 'Regenerate this document' }))
+ expect(onRegenerate).toHaveBeenCalledTimes(1)
+ })
+
+ it('is not offered on a folder, which has no generated body', () => {
+ viewer({ doc: doc({ kind: 'folder', device_id: null }) })
+ expect(screen.queryByRole('button', { name: 'Regenerate this document' })).toBeNull()
+ })
+})
+
+describe('the regenerate confirmation', () => {
+ function setup(overrides: Partial<React.ComponentProps<typeof RegenerateDocModal>> = {}) {
+ const onConfirm = vi.fn()
+ const onCancel = vi.fn()
+ render(
+ <RegenerateDocModal
+ open
+ title="nas-01"
+ fromDevice
+ onCancel={onCancel}
+ onConfirm={onConfirm}
+ {...overrides}
+ />,
+ )
+ return { onConfirm, onCancel }
+ }
+
+ it('spells out that the written body is erased', () => {
+ setup()
+ expect(screen.getByText(/Everything written in this document is erased/)).toBeTruthy()
+ expect(screen.getByText(/Your notes, sections and edits in it are lost/)).toBeTruthy()
+ expect(screen.getByText(/saved to the history first/)).toBeTruthy()
+ })
+
+ it('names the device facts as the source for a device document', () => {
+ setup()
+ expect(screen.getByText(/current facts in the database/)).toBeTruthy()
+ })
+
+ it('names the template as the source for a library page', () => {
+ setup({ fromDevice: false })
+ expect(screen.getByText(/from the template this page was created with/)).toBeTruthy()
+ })
+
+ it('only regenerates once the destructive button is pressed', async () => {
+ const { onConfirm, onCancel } = setup()
+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ expect(onCancel).toHaveBeenCalledTimes(1)
+ expect(onConfirm).not.toHaveBeenCalled()
+
+ await userEvent.click(screen.getByRole('button', { name: /Erase and regenerate/ }))
+ expect(onConfirm).toHaveBeenCalledTimes(1)
+ })
+
+ it('locks both buttons while the server is working', () => {
+ setup({ busy: true })
+ expect(screen.getByRole('button', { name: 'Cancel' }).hasAttribute('disabled')).toBe(true)
+ expect(screen.getByRole('button', { name: /Regenerating/ }).hasAttribute('disabled')).toBe(true)
+ })
+})
diff --git a/frontend/src/documentation/__tests__/store.test.ts b/frontend/src/documentation/__tests__/store.test.ts
index bc5d175..18a409c 100644
--- a/frontend/src/documentation/__tests__/store.test.ts
+++ b/frontend/src/documentation/__tests__/store.test.ts
@@ -4,6 +4,7 @@ import { documentsApi } from '@/api/client'
import {
clearDraft,
draftKey,
+ driftedIds,
isDescendant,
overdueIds,
readDraft,
@@ -22,6 +23,7 @@ vi.mock('@/api/client', () => ({
revisions: vi.fn(),
revision: vi.fn(),
restore: vi.fn(),
+ regenerate: vi.fn(),
search: vi.fn(),
block: vi.fn(),
coverage: vi.fn(),
@@ -277,6 +279,76 @@ describe('mutations', () => {
expect(useDocsStore.getState().openDoc?.body).toBe('old')
expect(api.revisions).toHaveBeenCalledWith('doc-1')
})
+
+ it('regenerates the open document and drops the draft with it', async () => {
+ api.regenerate.mockResolvedValue({ data: doc({ body: 'generated' }) } as never)
+ useDocsStore.setState({ docs: [summary()], openDoc: doc(), draft: 'half written', dirty: true })
+ writeDraft('doc-1', { body: 'half written', savedAt: 1, base: '2026-01-01T00:00:00Z' })
+
+ expect(await useDocsStore.getState().regenerate('doc-1')).toBe(true)
+
+ const state = useDocsStore.getState()
+ expect(api.regenerate).toHaveBeenCalledWith('doc-1')
+ expect(state.openDoc?.body).toBe('generated')
+ expect(state.draft).toBeNull()
+ expect(state.dirty).toBe(false)
+ expect(readDraft('doc-1')).toBeNull()
+ })
+
+ it('refreshes the history when it is already on screen', async () => {
+ api.regenerate.mockResolvedValue({ data: doc({ body: 'generated' }) } as never)
+ api.revisions.mockResolvedValue({ data: [] } as never)
+ useDocsStore.setState({
+ docs: [summary()],
+ openDoc: doc(),
+ revisions: [
+ { id: 'rev-1', document_id: 'doc-1', title: 'Page', reason: 'edit', saved_at: '2026-01-01T00:00:00Z', size: 8 },
+ ],
+ })
+ await useDocsStore.getState().regenerate('doc-1')
+ expect(api.revisions).toHaveBeenCalledWith('doc-1')
+ })
+
+ it('reports a failed regenerate and leaves the body alone', async () => {
+ api.regenerate.mockRejectedValue({ response: { data: { detail: 'Device not found' } } } as never)
+ useDocsStore.setState({ docs: [summary()], openDoc: doc() })
+
+ expect(await useDocsStore.getState().regenerate('doc-1')).toBe(false)
+ expect(useDocsStore.getState().openDoc?.body).toBe('original')
+ expect(useDocsStore.getState().loadError).toBe('Device not found')
+ })
+
+ it('leaves the editor alone when another document is regenerated', async () => {
+ api.regenerate.mockResolvedValue({ data: doc({ id: 'doc-2', body: 'generated' }) } as never)
+ useDocsStore.setState({
+ docs: [summary(), summary({ id: 'doc-2' })],
+ openDoc: doc(),
+ draft: 'mine',
+ dirty: true,
+ })
+ await useDocsStore.getState().regenerate('doc-2')
+ const state = useDocsStore.getState()
+ expect(state.openDoc?.id).toBe('doc-1')
+ expect(state.draft).toBe('mine')
+ expect((state.docs.find((d) => d.id === 'doc-2') as Doc).body).toBe('generated')
+ })
+})
+
+// ── badges ──────────────────────────────────────────────────────────────────
+
+describe('driftedIds', () => {
+ it('collects the documents the server flagged', () => {
+ const ids = driftedIds([
+ summary({ id: 'doc-1', drifted: true }),
+ summary({ id: 'doc-2', drifted: false }),
+ summary({ id: 'doc-3' }),
+ ])
+ expect([...ids]).toEqual(['doc-1'])
+ })
+
+ it('is empty when nothing has drifted', () => {
+ expect(driftedIds([summary()]).size).toBe(0)
+ })
})
// ── search ──────────────────────────────────────────────────────────────────
diff --git a/frontend/src/documentation/components/DocViewer.tsx b/frontend/src/documentation/components/DocViewer.tsx
index 4bb0f45..a567349 100644
--- a/frontend/src/documentation/components/DocViewer.tsx
+++ b/frontend/src/documentation/components/DocViewer.tsx
@@ -17,6 +17,7 @@ interface Props {
onEdit: () => void
onToggleStar: () => void
onMarkReviewed: () => void
+ onRegenerate: () => void
onDelete: () => void
onOpenDoc: (id: string) => void
onCreateFromLink: (label: string) => void
@@ -38,6 +39,7 @@ export function DocViewer({
onEdit,
onToggleStar,
onMarkReviewed,
+ onRegenerate,
onDelete,
onOpenDoc,
onCreateFromLink,
@@ -65,6 +67,19 @@ export function DocViewer({
<Button size="sm" variant="ghost" onClick={onEdit} className="cursor-pointer gap-1">
<Pencil size={13} /> Edit
</Button>
+ {/* A folder holds children, not a generated body — nothing to rebuild. */}
+ {doc.kind !== 'folder' && (
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ title="Regenerate this document from the database"
+ aria-label="Regenerate this document"
+ onClick={onRegenerate}
+ className="cursor-pointer"
+ >
+ <RefreshCw />
+ </Button>
+ )}
<Button size="icon-xs" variant="ghost" title="Delete this document" onClick={onDelete} className="cursor-pointer">
<Trash2 />
</Button>
diff --git a/frontend/src/documentation/components/DocumentationView.tsx b/frontend/src/documentation/components/DocumentationView.tsx
index c402336..9615440 100644
--- a/frontend/src/documentation/components/DocumentationView.tsx
+++ b/frontend/src/documentation/components/DocumentationView.tsx
@@ -10,7 +10,7 @@ import { useDesignStore } from '@/stores/designStore'
import type { InventoryEntry } from '@/types'
import { cn } from '@/lib/utils'
import { isOverdue } from '../frontmatter'
-import { useDocsStore } from '../store'
+import { driftedIds, useDocsStore } from '../store'
import { buildDeviceTree, buildLibraryTree, deviceLabel, filterGroups, filterTree } from '../tree'
import { GROUP_BY_LABELS, type GroupBy, type TreeLeaf } from '../types'
import { DocEditor } from './DocEditor'
@@ -18,6 +18,7 @@ import { DocTreeGroups, DocTreeItem } from './DocTree'
import { DocViewer } from './DocViewer'
import { MigrateNotesBanner } from './MigrateNotesBanner'
import { NewDocMenu } from './NewDocMenu'
+import { RegenerateDocModal } from './RegenerateDocModal'
const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
@@ -51,6 +52,7 @@ export function DocumentationView() {
remove,
toggleStar,
markReviewed,
+ regenerate,
coverage,
loadCoverage,
scaffold,
@@ -70,6 +72,8 @@ export function DocumentationView() {
const [devices, setDevices] = useState<InventoryEntry[]>([])
const [libraryOpen, setLibraryOpen] = useState(true)
+ const [regenerateOpen, setRegenerateOpen] = useState(false)
+ const [regenerating, setRegenerating] = useState(false)
useEffect(() => {
void loadDocs()
@@ -93,6 +97,8 @@ export function DocumentationView() {
[docs],
)
+ const drifted = useMemo(() => driftedIds(docs), [docs])
+
const deviceGroups = useMemo(
() =>
filterGroups(
@@ -101,11 +107,12 @@ export function DocumentationView() {
devices,
docs,
context: { nodes, designs, activeDesignId, ranges: [] },
+ drifted,
overdue,
}),
filter,
),
- [activeDesignId, designs, devices, docs, filter, groupBy, nodes, overdue],
+ [activeDesignId, designs, devices, docs, drifted, filter, groupBy, nodes, overdue],
)
const libraryItems = useMemo(() => filterTree(buildLibraryTree(docs), filter), [docs, filter])
@@ -115,18 +122,6 @@ export function DocumentationView() {
[devices],
)
- const drifted = useMemo(() => {
- if (!openDoc?.device_id || !openDoc.facts_snapshot) return false
- const device = devices.find((d) => d.id === openDoc.device_id)
- if (!device) return false
- // The snapshot is the server's shape; compare only what it recorded.
- return Object.entries(openDoc.facts_snapshot).some(([key, value]) => {
- if (key === 'services') return false
- const current = (device as unknown as Record<string, unknown>)[key]
- return (current ?? null) !== (value ?? null)
- })
- }, [devices, openDoc])
-
const handleSelect = useCallback(
async (leaf: TreeLeaf) => {
if (dirty && !window.confirm('Discard the unsaved changes to this document?')) return
@@ -160,6 +155,19 @@ export function DocumentationView() {
toast.success('Document deleted')
}, [openDoc, remove])
+ const handleRegenerate = useCallback(async () => {
+ if (!openDoc) return
+ setRegenerating(true)
+ const ok = await regenerate(openDoc.id)
+ setRegenerating(false)
+ if (!ok) {
+ toast.error('Could not regenerate that document')
+ return
+ }
+ setRegenerateOpen(false)
+ toast.success('Document regenerated — the old body is in its history')
+ }, [openDoc, regenerate])
+
const handleMigrate = useCallback(async () => {
const created = await scaffold({ onlyWithNotes: true })
await loadDocs()
@@ -363,10 +371,11 @@ export function DocumentationView() {
doc={openDoc}
docs={docs}
devices={linkableDevices}
- drifted={drifted}
+ drifted={openDoc.drifted ?? false}
onEdit={startEdit}
onToggleStar={() => void toggleStar(openDoc.id)}
onMarkReviewed={() => void markReviewed(openDoc.id)}
+ onRegenerate={() => setRegenerateOpen(true)}
onDelete={() => void handleDelete()}
onOpenDoc={(id) => void open(id)}
onCreateFromLink={async (label) => {
@@ -395,6 +404,15 @@ export function DocumentationView() {
devices={linkableDevices}
/>
)}
+
+ <RegenerateDocModal
+ open={regenerateOpen && openDoc !== null}
+ title={openDoc?.title ?? ''}
+ fromDevice={Boolean(openDoc?.device_id)}
+ busy={regenerating}
+ onCancel={() => setRegenerateOpen(false)}
+ onConfirm={() => void handleRegenerate()}
+ />
</div>
</div>
)
diff --git a/frontend/src/documentation/components/RegenerateDocModal.tsx b/frontend/src/documentation/components/RegenerateDocModal.tsx
new file mode 100644
index 0000000..346fff6
--- /dev/null
+++ b/frontend/src/documentation/components/RegenerateDocModal.tsx
@@ -0,0 +1,68 @@
+import { AlertTriangle, RefreshCw } from 'lucide-react'
+
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+
+interface Props {
+ open: boolean
+ title: string
+ /** A device document regenerates from live facts; a page from its template. */
+ fromDevice: boolean
+ busy?: boolean
+ onCancel: () => void
+ onConfirm: () => void
+}
+
+/**
+ * The confirmation for the one action that overwrites a body the user owns.
+ *
+ * Regenerating is not an edit that can be walked back in the editor, so it is
+ * spelled out here in full — including the one consolation, that the replaced
+ * body is snapshotted into the document's history first.
+ */
+export function RegenerateDocModal({ open, title, fromDevice, busy, onCancel, onConfirm }: Props) {
+ return (
+ <Dialog open={open} onOpenChange={(value) => !value && onCancel()}>
+ <DialogContent className="max-w-md border-border bg-[#161b22]">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2 text-foreground">
+ <AlertTriangle size={16} className="text-[var(--status-pending,#e3b341)]" />
+ Regenerate “{title}”?
+ </DialogTitle>
+ <DialogDescription className="text-xs">
+ Everything written in this document is erased and replaced by a freshly generated one.
+ </DialogDescription>
+ </DialogHeader>
+
+ <ul className="space-y-1.5 rounded-md border border-border bg-[#0d1117]/60 px-3 py-2.5 text-xs text-muted-foreground">
+ <li>
+ The body is rebuilt {fromDevice ? "from the device's current facts in the database" : 'from the template this page was created with'}.
+ </li>
+ <li>Your notes, sections and edits in it are lost.</li>
+ <li>The current body is saved to the history first, so this can be undone from there.</li>
+ </ul>
+
+ <DialogFooter className="gap-2">
+ <Button variant="ghost" onClick={onCancel} disabled={busy}>
+ Cancel
+ </Button>
+ <Button
+ onClick={onConfirm}
+ disabled={busy}
+ className="gap-1.5 bg-[var(--status-offline,#f85149)] text-[#0d1117] hover:bg-[var(--status-offline,#f85149)]/90"
+ >
+ <RefreshCw size={13} />
+ {busy ? 'Regenerating…' : 'Erase and regenerate'}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/documentation/store.ts b/frontend/src/documentation/store.ts
index 532dc2d..477efc6 100644
--- a/frontend/src/documentation/store.ts
+++ b/frontend/src/documentation/store.ts
@@ -141,6 +141,7 @@ export interface DocsState {
loadRevisions: (id: string) => Promise<void>
restore: (id: string, revisionId: string) => Promise<void>
+ regenerate: (id: string) => Promise<boolean>
loadCoverage: () => Promise<void>
scaffold: (input: { deviceIds?: string[]; onlyWithNotes?: boolean }) => Promise<number>
@@ -358,6 +359,27 @@ export const useDocsStore = create<DocsState>()((set, get) => ({
await get().loadRevisions(id)
},
+ regenerate: async (id) => {
+ try {
+ const { data } = await documentsApi.regenerate(id)
+ // The body the user was editing no longer exists; drop the draft with it
+ // rather than letting a stale edit be saved back over the new one.
+ clearDraft(id)
+ set((state) => ({
+ openDoc: state.openDoc?.id === id ? data : state.openDoc,
+ draft: state.openDoc?.id === id ? null : state.draft,
+ dirty: state.openDoc?.id === id ? false : state.dirty,
+ pendingDraft: state.openDoc?.id === id ? null : state.pendingDraft,
+ docs: state.docs.map((d) => (d.id === id ? { ...d, ...data } : d)),
+ }))
+ if (get().openDoc?.id === id && get().revisions.length > 0) await get().loadRevisions(id)
+ return true
+ } catch (error) {
+ set({ loadError: message(error, 'Could not regenerate that document') })
+ return false
+ }
+ },
+
loadCoverage: async () => {
if (STANDALONE) return
try {
@@ -433,6 +455,11 @@ export function isDescendant(all: DocumentSummary[], doc: DocumentSummary, ances
return false
}
+/** Document ids the server flagged as drifted. Used for the tree badge. */
+export function driftedIds(docs: DocumentSummary[]): Set<string> {
+ return new Set(docs.filter((doc) => doc.drifted).map((doc) => doc.id))
+}
+
/** Document ids whose `review_every` has elapsed. Used for the tree badge. */
export function overdueIds(docs: DocumentSummary[], now = Date.now()): Set<string> {
return new Set(
diff --git a/frontend/src/documentation/types.ts b/frontend/src/documentation/types.ts
index a8d0f31..79121a3 100644
--- a/frontend/src/documentation/types.ts
+++ b/frontend/src/documentation/types.ts
@@ -25,6 +25,11 @@ export interface DocumentSummary {
frontmatter: Record<string, unknown>
starred: boolean
template_id?: string | null
+ /**
+ * The device has changed since this document's facts were snapshotted.
+ * Decided by the server — the snapshot is its shape, not the inventory's.
+ */
+ drifted?: boolean
reviewed_at?: string | null
edited_at?: string | null
facts_synced_at?: string | null
@@ -41,7 +46,7 @@ export interface DocRevision {
id: string
document_id: string
title: string
- reason: 'edit' | 'restore' | 'import' | 'migrate' | 'scaffold'
+ reason: 'edit' | 'restore' | 'import' | 'migrate' | 'scaffold' | 'regenerate'
saved_at: string
size: number
}