LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
feat: add knowledge graph filters
nash_su963aa50864b8
diff --git a/src/components/graph/graph-view.tsx b/src/components/graph/graph-view.tsxindex a7aeed89..92fdda7a 100644--- a/src/components/graph/graph-view.tsx+++ b/src/components/graph/graph-view.tsx@@ -1,9 +1,10 @@-import { useEffect, useCallback, useState, useRef, type ChangeEvent } from "react"+import { useEffect, useCallback, useMemo, useState, useRef, type ChangeEvent } from "react"import Graph from "graphology"import { SigmaContainer, useLoadGraph, useRegisterEvents, useSigma } from "@react-sigma/core"import "@react-sigma/core/lib/style.css"+import type { SigmaNodeEventPayload } from "sigma/types"import forceAtlas2 from "graphology-layout-forceatlas2"-import { Network, RefreshCw, ZoomIn, ZoomOut, Maximize, Layers, Tag, Lightbulb, AlertTriangle, Link2, X, Search, Loader2 } from "lucide-react"+import { Network, RefreshCw, ZoomIn, ZoomOut, Maximize, Layers, Tag, Lightbulb, AlertTriangle, Link2, X, Search, Loader2, Filter, RotateCcw, EyeOff } from "lucide-react"import { ErrorBoundary } from "@/components/error-boundary"import { useResearchStore } from "@/stores/research-store"import { Button } from "@/components/ui/button"@@ -14,7 +15,7 @@ import { findSurprisingConnections, detectKnowledgeGaps, type SurprisingConnectiimport { queueResearch } from "@/lib/deep-research"import { optimizeResearchTopic } from "@/lib/optimize-research-topic"import { normalizePath } from "@/lib/path-utils"-import { shouldHideEdgeByNodeTypes, shouldHideNodeType } from "@/lib/graph-visibility"+import { applyGraphFilters, DEFAULT_GRAPH_FILTERS, hasActiveGraphFilters, type GraphFilterState } from "@/lib/graph-filters"const NODE_TYPE_COLORS: Record<string, string> = {entity: "#60a5fa", // blue-400@@ -166,40 +167,6 @@ function GraphLoader({ nodes, edges, colorMode }: { nodes: GraphNode[]; edges: Greturn null}-/**- * Manages edge visibility based on hidden node types.- * When a node type is hidden, all connected edges are also hidden- * to prevent orphaned edge rendering.- */-function HiddenTypeManager({ hiddenTypes }: { hiddenTypes: Set<string> }) {- const sigma = useSigma()-- useEffect(() => {- if (hiddenTypes.size === 0) {- // Show all edges when no types are hidden- const graph = sigma.getGraph()- graph.forEachEdge((e) => {- graph.removeEdgeAttribute(e, "hidden")- })- } else {- // Hide edges connected to hidden node types- const graph = sigma.getGraph()- graph.forEachEdge((e, _attrs, source, target) => {- const sourceType = graph.getNodeAttribute(source, "nodeType") as string | undefined- const targetType = graph.getNodeAttribute(target, "nodeType") as string | undefined- if (shouldHideEdgeByNodeTypes(sourceType, targetType, hiddenTypes)) {- graph.setEdgeAttribute(e, "hidden", true)- } else {- graph.removeEdgeAttribute(e, "hidden")- }- })- }- sigma.refresh()- }, [sigma, hiddenTypes])-- return null-}-function HighlightManager({ highlightedNodes }: { highlightedNodes: Set<string> }) {const sigma = useSigma()@@ -240,13 +207,26 @@ function HighlightManager({ highlightedNodes }: { highlightedNodes: Set<string>return null}-function EventHandler({ onNodeClick }: { onNodeClick: (nodeId: string) => void }) {+function EventHandler({+ onNodeClick,+ onNodeContextMenu,+}: {+ onNodeClick: (nodeId: string) => void+ onNodeContextMenu: (nodeId: string, x: number, y: number) => void+}) {const registerEvents = useRegisterEvents()const sigma = useSigma()useEffect(() => {registerEvents({clickNode: ({ node }) => onNodeClick(node),+ rightClickNode: (payload: SigmaNodeEventPayload) => {+ payload.preventSigmaDefault()+ payload.event.original.preventDefault()+ const point = clientPointFromEvent(payload.event.original)+ onNodeContextMenu(nodeIdFromPayload(payload), point.x, point.y)+ },+ rightClickStage: () => onNodeContextMenu("", 0, 0),enterNode: ({ node }) => {const container = sigma.getContainer()container.style.cursor = "pointer"@@ -281,11 +261,21 @@ function EventHandler({ onNodeClick }: { onNodeClick: (nodeId: string) => void }sigma.refresh()},})- }, [registerEvents, sigma, onNodeClick])+ }, [registerEvents, sigma, onNodeClick, onNodeContextMenu])return null}+function nodeIdFromPayload(payload: SigmaNodeEventPayload): string {+ return payload.node+}++function clientPointFromEvent(event: MouseEvent | TouchEvent): { x: number; y: number } {+ if ("clientX" in event) return { x: event.clientX, y: event.clientY }+ const touch = event.touches[0] ?? event.changedTouches[0]+ return { x: touch?.clientX ?? 0, y: touch?.clientY ?? 0 }+}+function ZoomControls() {const sigma = useSigma()@@ -351,7 +341,13 @@ export function GraphView() {const [sigmaKey, setSigmaKey] = useState(0)const [isResizing, setIsResizing] = useState(false)const [legendCollapsed, setLegendCollapsed] = useState(false)- const [hiddenTypes, setHiddenTypes] = useState<Set<string>>(new Set())+ const [showFilters, setShowFilters] = useState(false)+ const [filters, setFilters] = useState<GraphFilterState>(() => ({+ ...DEFAULT_GRAPH_FILTERS,+ hiddenTypes: new Set(),+ hiddenNodeIds: new Set(),+ }))+ const [nodeMenu, setNodeMenu] = useState<{ nodeId: string; x: number; y: number } | null>(null)const graphContainerRef = useRef<HTMLDivElement>(null)// Research confirmation dialogconst [researchDialog, setResearchDialog] = useState<{@@ -402,6 +398,28 @@ export function GraphView() {[nodes, setSelectedFile, setFileContent],)+ const handleNodeContextMenu = useCallback((nodeId: string, x: number, y: number) => {+ if (!nodeId) {+ setNodeMenu(null)+ return+ }+ const rect = graphContainerRef.current?.getBoundingClientRect()+ setNodeMenu({+ nodeId,+ x: rect ? x - rect.left : x,+ y: rect ? y - rect.top : y,+ })+ }, [])++ const resetFilters = useCallback(() => {+ setFilters({+ ...DEFAULT_GRAPH_FILTERS,+ hiddenTypes: new Set(),+ hiddenNodeIds: new Set(),+ })+ setNodeMenu(null)+ }, [])+const handleResearchClick = useCallback(async (gapTitle: string, gapDescription: string, gapType: string) => {const store = useWikiStore.getState()if (!store.project) return@@ -493,6 +511,14 @@ export function GraphView() {return acc}, {})+ const filteredGraph = useMemo(+ () => applyGraphFilters(nodes, edges, filters),+ [nodes, edges, filters],+ )+ const hiddenCount = nodes.length - filteredGraph.nodes.length+ const filtersActive = hasActiveGraphFilters(filters)+ const contextNode = nodeMenu ? nodes.find((node) => node.id === nodeMenu.nodeId) : null+if (!project) {return (<div className="flex h-full flex-col items-center justify-center gap-3 text-muted-foreground">@@ -541,11 +567,37 @@ export function GraphView() {<span className="text-sm font-medium">Knowledge Graph</span></div><div className="flex items-center gap-1.5 text-xs text-muted-foreground">- <span className="rounded bg-muted px-1.5 py-0.5">{nodes.length} pages</span>- <span className="rounded bg-muted px-1.5 py-0.5">{edges.length} links</span>+ <span className="rounded bg-muted px-1.5 py-0.5">{filteredGraph.nodes.length}/{nodes.length} pages</span>+ <span className="rounded bg-muted px-1.5 py-0.5">{filteredGraph.edges.length}/{edges.length} links</span>+ {hiddenCount > 0 && (+ <span className="rounded bg-amber-500/10 px-1.5 py-0.5 text-amber-700 dark:text-amber-300">+ {hiddenCount} hidden+ </span>+ )}</div></div><div className="flex items-center gap-1">+ <Button+ variant={showFilters ? "secondary" : "ghost"}+ size="sm"+ onClick={() => setShowFilters((v) => !v)}+ className="text-xs gap-1 h-7"+ >+ <Filter className="h-3 w-3" />+ Filter+ </Button>+ {filtersActive && (+ <Button+ variant="ghost"+ size="sm"+ onClick={resetFilters}+ className="text-xs gap-1 h-7"+ title="Reset graph filters"+ >+ <RotateCcw className="h-3 w-3" />+ Reset+ </Button>+ )}<Buttonvariant={colorMode === "type" ? "secondary" : "ghost"}size="sm"@@ -592,7 +644,12 @@ export function GraphView() {{/* Graph canvas + Insights side panel */}<div className="flex flex-1 min-h-0">{/* Graph canvas */}- <div ref={graphContainerRef} className="relative flex-1 min-w-0 overflow-hidden bg-slate-50 dark:bg-slate-950">+ <div+ ref={graphContainerRef}+ className="relative flex-1 min-w-0 overflow-hidden bg-slate-50 dark:bg-slate-950"+ onContextMenu={(e) => e.preventDefault()}+ onClick={() => setNodeMenu(null)}+ >{isResizing ? (<div className="flex h-full items-center justify-center text-xs text-muted-foreground">Resizing...@@ -614,11 +671,6 @@ export function GraphView() {stagePadding: 30,nodeReducer: (_node, attrs) => {const result = { ...attrs }- const nodeType = attrs.nodeType as string- if (shouldHideNodeType(nodeType, hiddenTypes)) {- result.hidden = true- return result- }if (attrs.insightHighlight) {result.size = (attrs.size ?? BASE_NODE_SIZE) * 1.5result.zIndex = 10@@ -653,15 +705,161 @@ export function GraphView() {},}}>- <GraphLoader nodes={nodes} edges={edges} colorMode={colorMode} />- <HiddenTypeManager hiddenTypes={hiddenTypes} />- <EventHandler onNodeClick={handleNodeClick} />+ <GraphLoader nodes={filteredGraph.nodes} edges={filteredGraph.edges} colorMode={colorMode} />+ <EventHandler onNodeClick={handleNodeClick} onNodeContextMenu={handleNodeContextMenu} /><HighlightManager highlightedNodes={highlightedNodes} /><ZoomControls /></SigmaContainer></ErrorBoundary>)}+ {showFilters && (+ <div className="absolute top-3 left-3 w-72 rounded-lg border bg-background/95 p-3 text-xs shadow-lg backdrop-blur-sm">+ <div className="mb-3 flex items-center justify-between">+ <div className="flex items-center gap-1.5 font-semibold text-foreground">+ <Filter className="h-3.5 w-3.5" />+ Graph Filters+ </div>+ <Button+ variant="ghost"+ size="sm"+ className="h-6 px-1.5 text-[10px]"+ onClick={resetFilters}+ >+ Reset+ </Button>+ </div>++ <div className="space-y-3">+ <div className="space-y-1.5">+ <div className="font-medium text-muted-foreground">Quick filters</div>+ <label className="flex items-center gap-2">+ <input+ type="checkbox"+ checked={filters.hideStructural}+ onChange={(e) => setFilters((prev) => ({ ...prev, hideStructural: e.target.checked }))}+ />+ <span>Hide index / overview / log</span>+ </label>+ <label className="flex items-center gap-2">+ <input+ type="checkbox"+ checked={filters.hideIsolated}+ onChange={(e) => setFilters((prev) => ({ ...prev, hideIsolated: e.target.checked }))}+ />+ <span>Hide isolated nodes</span>+ </label>+ </div>++ <div className="space-y-1.5">+ <div className="font-medium text-muted-foreground">Max links</div>+ <div className="flex items-center gap-2">+ <input+ type="number"+ min={0}+ className="h-7 w-20 rounded border bg-background px-2 text-xs"+ value={filters.maxLinks ?? ""}+ onChange={(e) => {+ const raw = e.target.value.trim()+ const value = Number(raw)+ setFilters((prev) => ({+ ...prev,+ maxLinks: raw === "" || !Number.isFinite(value) ? undefined : Math.max(0, value),+ }))+ }}+ placeholder="Any"+ />+ <span className="text-muted-foreground">Hide nodes above this link count</span>+ </div>+ </div>++ <div className="space-y-1.5">+ <div className="font-medium text-muted-foreground">Node types</div>+ <div className="grid grid-cols-2 gap-1">+ {Object.entries(NODE_TYPE_LABELS)+ .filter(([type]) => (typeCounts[type] ?? 0) > 0)+ .map(([type, label]) => (+ <label key={type} className="flex min-w-0 items-center gap-1.5">+ <input+ type="checkbox"+ checked={!filters.hiddenTypes.has(type)}+ onChange={(e) => {+ setFilters((prev) => {+ const next = new Set(prev.hiddenTypes)+ if (e.target.checked) next.delete(type)+ else next.add(type)+ return { ...prev, hiddenTypes: next }+ })+ }}+ />+ <span className="truncate">{label}</span>+ <span className="text-muted-foreground/60">{typeCounts[type]}</span>+ </label>+ ))}+ </div>+ </div>++ {filters.hiddenNodeIds.size > 0 && (+ <div className="space-y-1.5">+ <div className="font-medium text-muted-foreground">Hidden nodes</div>+ <div className="max-h-24 space-y-1 overflow-y-auto">+ {[...filters.hiddenNodeIds].map((nodeId) => {+ const node = nodes.find((n) => n.id === nodeId)+ return (+ <div key={nodeId} className="flex items-center justify-between gap-2 rounded bg-muted/50 px-2 py-1">+ <span className="truncate">{node?.label ?? nodeId}</span>+ <button+ type="button"+ className="text-muted-foreground hover:text-foreground"+ onClick={() => setFilters((prev) => {+ const next = new Set(prev.hiddenNodeIds)+ next.delete(nodeId)+ return { ...prev, hiddenNodeIds: next }+ })}+ >+ Show+ </button>+ </div>+ )+ })}+ </div>+ </div>+ )}++ <div className="rounded bg-muted/50 px-2 py-1.5 text-muted-foreground">+ Showing {filteredGraph.nodes.length} of {nodes.length} pages and {filteredGraph.edges.length} of {edges.length} links.+ </div>+ </div>+ </div>+ )}++ {nodeMenu && contextNode && (+ <div+ className="absolute z-20 w-48 rounded-md border bg-background py-1 text-xs shadow-lg"+ style={{ left: nodeMenu.x, top: nodeMenu.y }}+ onClick={(e) => e.stopPropagation()}+ >+ <div className="border-b px-3 py-2">+ <div className="truncate font-medium text-foreground">{contextNode.label}</div>+ <div className="text-muted-foreground">{contextNode.linkCount} links</div>+ </div>+ <button+ type="button"+ className="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-accent"+ onClick={() => {+ setFilters((prev) => ({+ ...prev,+ hiddenNodeIds: new Set([...prev.hiddenNodeIds, contextNode.id]),+ }))+ setNodeMenu(null)+ }}+ >+ <EyeOff className="h-3.5 w-3.5" />+ Hide this node+ </button>+ </div>+ )}+{/* Legend */}<div className="absolute bottom-3 left-3 rounded-lg border bg-background/90 backdrop-blur-sm px-3 py-2 text-xs shadow-sm max-w-[260px]"><div className="flex items-center justify-between mb-1.5">@@ -669,12 +867,12 @@ export function GraphView() {{colorMode === "type" ? "Node Types" : "Communities"}</span><div className="flex items-center gap-1">- {colorMode === "type" && hiddenTypes.size > 0 && (+ {colorMode === "type" && filters.hiddenTypes.size > 0 && (<Buttonvariant="ghost"size="sm"className="h-6 text-[10px] px-1"- onClick={() => setHiddenTypes(new Set())}+ onClick={() => setFilters((prev) => ({ ...prev, hiddenTypes: new Set() }))}title="Show all types">Show all@@ -698,7 +896,7 @@ export function GraphView() {{Object.entries(NODE_TYPE_LABELS).filter(([type]) => (typeCounts[type] ?? 0) > 0).map(([type, label]) => {- const isHidden = hiddenTypes.has(type)+ const isHidden = filters.hiddenTypes.has(type)return (<divkey={type}@@ -706,14 +904,14 @@ export function GraphView() {onMouseEnter={() => setHoveredType(type)}onMouseLeave={() => setHoveredType(null)}onDoubleClick={() => {- setHiddenTypes((prev) => {- const next = new Set(prev)+ setFilters((prev) => {+ const next = new Set(prev.hiddenTypes)if (next.has(type)) {next.delete(type)} else {next.add(type)}- return next+ return { ...prev, hiddenTypes: next }})}}title="Double-click to toggle visibility"diff --git a/src/lib/graph-filters.test.ts b/src/lib/graph-filters.test.tsnew file mode 100644index 00000000..cbd72c52--- /dev/null+++ b/src/lib/graph-filters.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from "vitest"+import type { GraphEdge, GraphNode } from "@/lib/wiki-graph"+import { applyGraphFilters, DEFAULT_GRAPH_FILTERS, hasActiveGraphFilters, isStructuralGraphNode, type GraphFilterState } from "./graph-filters"++const nodes: GraphNode[] = [+ { id: "index", label: "Index", type: "other", path: "/p/wiki/index.md", linkCount: 4, community: 0 },+ { id: "concept-a", label: "Concept A", type: "concept", path: "/p/wiki/concepts/a.md", linkCount: 2, community: 0 },+ { id: "entity-b", label: "Entity B", type: "entity", path: "/p/wiki/entities/b.md", linkCount: 3, community: 0 },+ { id: "source-c", label: "Source C", type: "source", path: "/p/wiki/sources/c.md", linkCount: 1, community: 1 },+ { id: "isolated", label: "Isolated", type: "concept", path: "/p/wiki/concepts/isolated.md", linkCount: 0, community: 2 },+]++const edges: GraphEdge[] = [+ { source: "index", target: "concept-a", weight: 1 },+ { source: "index", target: "entity-b", weight: 1 },+ { source: "concept-a", target: "entity-b", weight: 2 },+ { source: "source-c", target: "entity-b", weight: 3 },+]++function makeFilters(overrides: Partial<GraphFilterState> = {}): GraphFilterState {+ return {+ ...DEFAULT_GRAPH_FILTERS,+ hiddenTypes: new Set<string>(),+ hiddenNodeIds: new Set<string>(),+ ...overrides,+ }+}++describe("graph filters", () => {+ it("detects structural graph nodes by id, type, and path", () => {+ expect(isStructuralGraphNode(nodes[0])).toBe(true)+ expect(isStructuralGraphNode({ ...nodes[1], id: "overview", path: "/p/wiki/concepts/overview.md" })).toBe(true)+ expect(isStructuralGraphNode({ ...nodes[1], type: "overview" })).toBe(true)+ expect(isStructuralGraphNode(nodes[1])).toBe(false)+ })++ it("hides structural nodes and their connected edges by default", () => {+ const out = applyGraphFilters(nodes, edges, makeFilters())++ expect(out.nodes.map((n) => n.id)).not.toContain("index")+ expect(out.edges).toEqual([+ { source: "concept-a", target: "entity-b", weight: 2 },+ { source: "source-c", target: "entity-b", weight: 3 },+ ])+ })++ it("hides selected node types", () => {+ const out = applyGraphFilters(nodes, edges, makeFilters({+ hideStructural: false,+ hiddenTypes: new Set(["source"]),+ }))++ expect(out.nodes.map((n) => n.id)).not.toContain("source-c")+ expect(out.edges.some((e) => e.source === "source-c" || e.target === "source-c")).toBe(false)+ })++ it("hides manually selected nodes", () => {+ const out = applyGraphFilters(nodes, edges, makeFilters({+ hideStructural: false,+ hiddenNodeIds: new Set(["entity-b"]),+ }))++ expect(out.nodes.map((n) => n.id)).not.toContain("entity-b")+ expect(out.edges).toEqual([{ source: "index", target: "concept-a", weight: 1 }])+ })++ it("hides hub nodes above the max link threshold", () => {+ const out = applyGraphFilters(nodes, edges, makeFilters({+ hideStructural: false,+ maxLinks: 2,+ }))++ expect(out.nodes.map((n) => n.id)).not.toContain("index")+ expect(out.nodes.map((n) => n.id)).not.toContain("entity-b")+ expect(out.edges).toEqual([])+ })++ it("hides isolated nodes when requested", () => {+ const out = applyGraphFilters(nodes, edges, makeFilters({+ hideStructural: false,+ hideIsolated: true,+ }))++ expect(out.nodes.map((n) => n.id)).not.toContain("isolated")+ })++ it("reports whether filters are active", () => {+ expect(hasActiveGraphFilters(makeFilters({ hideStructural: false }))).toBe(false)+ expect(hasActiveGraphFilters(makeFilters())).toBe(true)+ expect(hasActiveGraphFilters(makeFilters({ hideStructural: false, hiddenNodeIds: new Set(["x"]) }))).toBe(true)+ })+})diff --git a/src/lib/graph-filters.ts b/src/lib/graph-filters.tsnew file mode 100644index 00000000..900e4312--- /dev/null+++ b/src/lib/graph-filters.ts@@ -0,0 +1,89 @@+import type { GraphEdge, GraphNode } from "@/lib/wiki-graph"+import { shouldHideNodeType } from "@/lib/graph-visibility"++export interface GraphFilterState {+ hiddenTypes: ReadonlySet<string>+ hiddenNodeIds: ReadonlySet<string>+ hideStructural: boolean+ hideIsolated: boolean+ maxLinks?: number+}++export interface FilteredGraph {+ nodes: GraphNode[]+ edges: GraphEdge[]+ hiddenNodeIds: Set<string>+}++export const DEFAULT_GRAPH_FILTERS: GraphFilterState = {+ hiddenTypes: new Set(),+ hiddenNodeIds: new Set(),+ hideStructural: true,+ hideIsolated: false,+ maxLinks: undefined,+}++const STRUCTURAL_IDS = new Set(["index", "overview", "log", "schema", "purpose"])++export function isStructuralGraphNode(node: Pick<GraphNode, "id" | "path" | "type">): boolean {+ const id = node.id.toLowerCase()+ if (STRUCTURAL_IDS.has(id)) return true+ if (node.type === "overview") return true++ const normalizedPath = node.path.replace(/\\/g, "/").toLowerCase()+ return (+ normalizedPath.endsWith("/wiki/index.md") ||+ normalizedPath.endsWith("/wiki/overview.md") ||+ normalizedPath.endsWith("/wiki/log.md") ||+ normalizedPath.endsWith("/purpose.md") ||+ normalizedPath.endsWith("/schema.md")+ )+}++export function applyGraphFilters(+ nodes: readonly GraphNode[],+ edges: readonly GraphEdge[],+ filters: GraphFilterState,+): FilteredGraph {+ const hiddenNodeIds = new Set<string>()++ for (const node of nodes) {+ if (filters.hiddenNodeIds.has(node.id)) {+ hiddenNodeIds.add(node.id)+ continue+ }+ if (shouldHideNodeType(node.type, filters.hiddenTypes)) {+ hiddenNodeIds.add(node.id)+ continue+ }+ if (filters.hideStructural && isStructuralGraphNode(node)) {+ hiddenNodeIds.add(node.id)+ continue+ }+ if (filters.hideIsolated && node.linkCount <= 0) {+ hiddenNodeIds.add(node.id)+ continue+ }+ if (filters.maxLinks !== undefined && node.linkCount > filters.maxLinks) {+ hiddenNodeIds.add(node.id)+ }+ }++ const visibleNodes = nodes.filter((node) => !hiddenNodeIds.has(node.id))+ const visibleNodeIds = new Set(visibleNodes.map((node) => node.id))+ const visibleEdges = edges.filter(+ (edge) => visibleNodeIds.has(edge.source) && visibleNodeIds.has(edge.target),+ )++ return { nodes: visibleNodes, edges: visibleEdges, hiddenNodeIds }+}++export function hasActiveGraphFilters(filters: GraphFilterState): boolean {+ return (+ filters.hideStructural ||+ filters.hideIsolated ||+ filters.hiddenTypes.size > 0 ||+ filters.hiddenNodeIds.size > 0 ||+ filters.maxLinks !== undefined+ )+}