feat(web): redesign Knowledge as an editable wiki
Some checks failed
ci / build-test (push) Has been cancelled
ci / docker-build (push) Has been cancelled
ci / web (push) Has been cancelled
Desktop App / Build Linux (amd64) (push) Has been cancelled
Desktop App / Attach to Release (push) Has been cancelled

Replaces the read-only stats dashboard with a three-pane wiki: a
navigator tree (group by folder/type/tag/entity), a reader/editor with
bare-slug auto-linking and revision history + diff, and a context rail
for backlinks and related notes. Adds a Cleanup mode for the drift
tools (duplicates, tag manager, orphans, trash) and a Cmd+K quick-open.

Also:
- Adds a real landing view (hero count, KPI row, Nomos-share meter,
  recently-updated, busiest tags) in place of the old "Select a note"
  empty state, and extends the design pass across the tree/reader/rail
  (kind icons instead of repeated text badges, accent-bar selection,
  constrained prose measure).
- Guards every note-selection path behind a confirm when there's an
  unsaved edit in progress, so switching notes can no longer silently
  discard a draft.
- Extracts the markdown-rendering CSS duplicated across ChatThread,
  EntityDetailContent, and the new WikiReader into a shared
  .markdown-body class in app.css, with ChatThread keeping only its
  decorative deltas.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-27 22:50:54 +02:00
parent ce0e4142ff
commit 89312a9ce4
14 changed files with 2626 additions and 268 deletions

View File

@@ -1,162 +1,224 @@
<script lang="ts">
import DOMPurify from 'dompurify'
import { searchKnowledge, fetchRecentKnowledge, type KnowledgeHit, type RecentKnowledge } from '$lib/api'
import * as Card from '$lib/components/ui/card'
import { Badge } from '$lib/components/ui/badge'
import { Input } from '$lib/components/ui/input'
// The Knowledge app, redesigned as a wiki: browse, read, and now actually
// edit everything the operator and Nomos have recorded — 102 notes that
// were previously stats-only (the old page could search and show a
// recency feed, but nothing was clickable: see git history on this file).
//
// Three panes (WikiTree | WikiReader | WikiContextRail) for browsing and
// editing day to day, plus a separate Cleanup mode (WikiCleanup) for the
// maintenance work the collection actually needs — duplicate pileups,
// tag-casing drift, orphaned notes, and the trash. Both modes share the
// same `items` list, loaded once here.
import { onMount } from 'svelte'
import { Pane, Splitpanes } from 'svelte-splitpanes'
import { listKnowledge, KnowledgeApiError, type KnowledgeListItem } from '$lib/api'
import WikiTree from '$lib/components/knowledge/WikiTree.svelte'
import WikiReader from '$lib/components/knowledge/WikiReader.svelte'
import WikiContextRail from '$lib/components/knowledge/WikiContextRail.svelte'
import WikiCleanup from '$lib/components/knowledge/WikiCleanup.svelte'
import WikiNewDialog from '$lib/components/knowledge/WikiNewDialog.svelte'
import WikiQuickOpen from '$lib/components/knowledge/WikiQuickOpen.svelte'
import * as Dialog from '$lib/components/ui/dialog'
import { Button } from '$lib/components/ui/button'
import { ScrollArea } from '$lib/components/ui/scroll-area'
import { openEntityWindow } from '$lib/stores/windows'
import { relativeTime } from '$lib/utils'
import StatusBadge from '$lib/components/StatusBadge.svelte'
import SearchIcon from '@lucide/svelte/icons/search'
import SparklesIcon from '@lucide/svelte/icons/sparkles'
import BotIcon from '@lucide/svelte/icons/bot'
import WrenchIcon from '@lucide/svelte/icons/wrench'
import BookOpenIcon from '@lucide/svelte/icons/book-open'
let query = $state('')
let results = $state<KnowledgeHit[]>([])
let loading = $state(false)
let searched = $state(false)
type Mode = 'wiki' | 'cleanup'
let recent = $state<RecentKnowledge>({ stats: { total: 0, by_kind: {}, agent_authored: 0, last_7d: 0 }, items: [] })
let agentOnly = $state(false)
let loadingRecent = $state(true)
let items = $state<KnowledgeListItem[]>([])
let itemsLoading = $state(true)
let selectedSlug = $state<string | null>(null)
let mode = $state<Mode>('wiki')
let newDialogOpen = $state(false)
let quickOpenOpen = $state(false)
// True while WikiReader has an in-progress, unsaved edit — set via
// bind:dirty. requestSelect below is the single choke point every
// selection path (tree, context rail, quick-open, a newly-created note)
// goes through, so gating it here is enough to stop a stray click from
// silently discarding an edit in progress (see WikiReader's own comment
// on why this is "in edit mode" rather than a real dirty-diff).
let readerDirty = $state(false)
let pendingSlug = $state<string | null>(null)
// Distinct from "0 notes": listKnowledge now throws on a failed request
// rather than returning [] (a real outage was previously indistinguishable
// from an empty collection — see api.ts's comment on the same helper).
let loadError = $state('')
async function loadRecent() {
loadingRecent = true
recent = await fetchRecentKnowledge(agentOnly ? 'nomos-agent' : undefined)
loadingRecent = false
}
loadRecent()
function toggleAgentOnly() {
agentOnly = !agentOnly
loadRecent()
async function loadItems(): Promise<void> {
itemsLoading = true
loadError = ''
try {
items = await listKnowledge()
} catch (e) {
loadError = e instanceof KnowledgeApiError ? e.message : 'Failed to load notes.'
} finally {
itemsLoading = false
}
}
async function search() {
if (!query.trim()) { searched = false; return }
loading = true
results = await searchKnowledge(query)
loading = false
searched = true
// Cmd/Ctrl+K quick-open, scoped to while this app's window is around —
// Desktop.svelte doesn't have a global command-palette convention to hook
// into, so this is a plain window listener added/removed with the
// component's lifetime rather than a shell-level keybinding.
function handleKeydown(e: KeyboardEvent): void {
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault()
quickOpenOpen = true
}
}
onMount(() => {
loadItems()
window.addEventListener('keydown', handleKeydown)
return () => window.removeEventListener('keydown', handleKeydown)
})
// Every note's own slug, for WikiReader's click handler to tell a
// wiki-internal link (navigate in place) from an entity link (open an
// entity window) — see wikiText.ts's slugFromKbHref.
const knownSlugs = $derived(new Set(items.map((i) => i.slug)))
const selectedItem = $derived(items.find((i) => i.slug === selectedSlug) ?? null)
function selectNow(slug: string): void {
readerDirty = false
selectedSlug = slug
mode = 'wiki'
}
// Every selection path (tree click, context-rail click, quick-open,
// opening a just-created note) routes through here rather than mutating
// selectedSlug directly, so an in-progress edit can never be silently
// discarded by a stray click elsewhere in the app.
function requestSelect(slug: string): void {
if (slug === selectedSlug) {
mode = 'wiki' // already selected — e.g. Cleanup's "view" links back into Wiki mode
return
}
if (readerDirty) {
pendingSlug = slug
return
}
selectNow(slug)
}
function confirmDiscardAndSwitch(): void {
if (pendingSlug) selectNow(pendingSlug)
pendingSlug = null
}
function handleCreated(slug: string): void {
loadItems()
requestSelect(slug)
}
</script>
<div class="flex h-full flex-col gap-4 p-2">
<div class="flex h-full flex-col gap-2 p-2">
<div class="flex items-center justify-between">
<h1 class="text-lg font-semibold">Knowledge</h1>
</div>
<!-- Learning stats: the system getting smarter, made visible -->
<div class="grid grid-cols-2 gap-3 sm:grid-cols-4">
<Card.Root>
<Card.Header class="p-3">
<Card.Description class="text-xs">Total notes</Card.Description>
<Card.Title class="text-2xl">{recent.stats.total}</Card.Title>
</Card.Header>
</Card.Root>
<Card.Root class="border-primary/30 bg-primary/5">
<Card.Header class="p-3">
<Card.Description class="flex items-center gap-1 text-xs"><BotIcon class="size-3" /> Written by Nomos</Card.Description>
<Card.Title class="text-2xl text-primary">{recent.stats.agent_authored}</Card.Title>
</Card.Header>
</Card.Root>
<Card.Root class="border-success/30 bg-success/5">
<Card.Header class="p-3">
<Card.Description class="flex items-center gap-1 text-xs"><SparklesIcon class="size-3" /> Learned this week</Card.Description>
<Card.Title class="text-2xl text-success">{recent.stats.last_7d}</Card.Title>
</Card.Header>
</Card.Root>
<Card.Root>
<Card.Header class="p-3">
<Card.Description class="text-xs">Runbooks / investigations</Card.Description>
<Card.Title class="text-2xl">{(recent.stats.by_kind.runbook ?? 0)} / {(recent.stats.by_kind.investigation ?? 0)}</Card.Title>
</Card.Header>
</Card.Root>
</div>
<!-- Search -->
<form onsubmit={(e) => { e.preventDefault(); search() }} class="flex gap-2">
<div class="relative flex-1 max-w-lg">
<SearchIcon class="absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input placeholder="Search documents, runbooks, investigations…" bind:value={query} class="pl-8" />
</div>
<Button type="submit" disabled={loading || !query.trim()}>{loading ? 'Searching…' : 'Search'}</Button>
{#if searched}
<Button type="button" variant="ghost" onclick={() => { query = ''; searched = false }}>Clear</Button>
{/if}
</form>
{#if searched}
<!-- Search results mode -->
<p class="text-sm text-muted-foreground">{results.length} result{results.length === 1 ? '' : 's'} for "{query}"</p>
<ScrollArea class="flex-1">
<div class="flex flex-col gap-3 pr-4">
{#each results as hit (hit.slug)}
<Card.Root class="transition-colors hover:bg-muted/50">
<Card.Header>
<div class="flex items-center gap-2">
<Card.Title class="text-sm">{hit.title}</Card.Title>
<StatusBadge kind="type" value={hit.type} />
</div>
{#if hit.snippet}
<Card.Description class="text-xs">
<!-- eslint-disable-next-line svelte/no-at-html-tags — sanitized inline; ts_headline only ever emits <b> -->
{@html DOMPurify.sanitize(hit.snippet, { ALLOWED_TAGS: ['b'], ALLOWED_ATTR: [] })}
</Card.Description>
{/if}
{#if hit.linked_entities?.length}
<div class="mt-1 flex flex-wrap gap-1">
{#each hit.linked_entities as slug}
<button type="button" class="font-mono text-xs text-muted-foreground underline" onclick={() => openEntityWindow(slug)}>{slug}</button>
{/each}
</div>
{/if}
</Card.Header>
</Card.Root>
{:else}
{#if !loading}<p class="py-12 text-center text-muted-foreground">No results found.</p>{/if}
{/each}
<div class="flex items-center gap-2">
<span class="text-xs text-muted-foreground">{items.length} notes</span>
<button
type="button"
class="rounded border px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground hover:bg-muted/50"
onclick={() => (quickOpenOpen = true)}
>
⌘K
</button>
<div class="inline-flex overflow-hidden rounded-md border">
<button
type="button"
class="flex items-center gap-1 px-2 py-1 text-xs {mode === 'wiki'
? 'bg-secondary text-secondary-foreground'
: 'hover:bg-muted/50'}"
onclick={() => (mode = 'wiki')}
>
<BookOpenIcon class="size-3.5" /> Wiki
</button>
<button
type="button"
class="flex items-center gap-1 px-2 py-1 text-xs {mode === 'cleanup'
? 'bg-secondary text-secondary-foreground'
: 'hover:bg-muted/50'}"
onclick={() => (mode = 'cleanup')}
>
<WrenchIcon class="size-3.5" /> Cleanup
</button>
</div>
</ScrollArea>
{:else}
<!-- Recently learned mode (default) -->
<div class="flex items-center justify-between">
<h2 class="text-sm font-medium text-muted-foreground">Recently learned</h2>
<Button size="sm" variant={agentOnly ? 'default' : 'outline'} class="h-7 gap-1 text-xs" onclick={toggleAgentOnly}>
<BotIcon class="size-3" /> {agentOnly ? 'Nomos only' : 'All sources'}
</Button>
</div>
<ScrollArea class="flex-1">
<div class="flex flex-col gap-2 pr-4">
{#each recent.items as it (it.slug)}
<div class="flex items-start gap-3 rounded-lg border px-3 py-2 transition-colors hover:bg-muted/40 {it.agent_authored ? 'border-primary/30 bg-primary/[0.03]' : ''}">
<div class="mt-0.5">
{#if it.agent_authored}<BotIcon class="size-4 text-primary" />{:else}<SearchIcon class="size-4 text-muted-foreground" />{/if}
</div>
<div class="min-w-0 flex-1">
<div class="flex flex-wrap items-center gap-2">
<span class="text-sm font-medium">{it.title}</span>
<StatusBadge kind="type" value={it.kind} class="text-[10px]" />
{#if it.agent_authored}<Badge variant="outline" class="border-primary/40 text-[10px] text-primary">learned by Nomos</Badge>{/if}
</div>
{#if it.tags.length}
<div class="mt-1 flex flex-wrap gap-1">
{#each it.tags as t}<span class="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">{t}</span>{/each}
</div>
{/if}
</div>
<span class="shrink-0 text-xs text-muted-foreground">{relativeTime(it.updated_at)}</span>
</div>
<div class="min-h-0 flex-1">
{#if itemsLoading}
<div class="flex h-full items-center justify-center text-sm text-muted-foreground">
Loading…
</div>
{:else if loadError}
<div class="flex h-full flex-col items-center justify-center gap-2 text-sm">
<p class="text-destructive">{loadError}</p>
<Button size="sm" variant="outline" onclick={loadItems}>Retry</Button>
</div>
{:else if mode === 'wiki'}
<Splitpanes theme="oikos-theme" dblClickSplitter={false} class="h-full">
<Pane size={22} minSize={15} maxSize={40}>
<div class="h-full overflow-hidden p-1.5">
<WikiTree
{items}
{selectedSlug}
onSelect={requestSelect}
onNew={() => (newDialogOpen = true)}
/>
</div>
{:else}
{#if !loadingRecent}
<p class="py-12 text-center text-sm text-muted-foreground">
{agentOnly ? 'Nomos hasnt recorded any learnings yet — it will write them here as it solves problems.' : 'No knowledge yet.'}
</p>
{/if}
{/each}
</div>
</ScrollArea>
{/if}
</Pane>
<Pane size={56} minSize={30}>
<div class="h-full overflow-hidden p-2">
<WikiReader
item={selectedItem}
allItems={items}
{knownSlugs}
onNavigate={requestSelect}
onNew={() => (newDialogOpen = true)}
onChanged={loadItems}
bind:dirty={readerDirty}
/>
</div>
</Pane>
<!-- The context rail is about the selected note, so it only exists
when there is one. Left mounted it rendered a "Nothing selected."
placeholder next to the overview — two competing empty states,
and a fifth of the width spent saying nothing. -->
{#if selectedItem}
<Pane size={22} minSize={15} maxSize={40}>
<div class="h-full overflow-hidden p-1.5">
<WikiContextRail item={selectedItem} allItems={items} onSelect={requestSelect} />
</div>
</Pane>
{/if}
</Splitpanes>
{:else}
<WikiCleanup onSelect={requestSelect} onChanged={loadItems} />
{/if}
</div>
</div>
<WikiNewDialog bind:open={newDialogOpen} onCreated={handleCreated} />
<WikiQuickOpen bind:open={quickOpenOpen} {items} onSelect={requestSelect} />
<Dialog.Root
open={pendingSlug !== null}
onOpenChange={(o) => {
if (!o) pendingSlug = null
}}
>
<Dialog.Content class="sm:max-w-sm">
<Dialog.Header>
<Dialog.Title>Discard unsaved changes?</Dialog.Title>
<Dialog.Description>
You're editing a note. Switching now will discard what you haven't saved.
</Dialog.Description>
</Dialog.Header>
<Dialog.Footer>
<Button variant="ghost" onclick={() => (pendingSlug = null)}>Keep editing</Button>
<Button variant="destructive" onclick={confirmDiscardAndSwitch}>Discard and switch</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>