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: auto-ingest on import + fix chat scrolling
nash_su00799559db54
diff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsxindex 0a5ec412..4ca98744 100644--- a/src/components/chat/chat-panel.tsx+++ b/src/components/chat/chat-panel.tsx@@ -1,6 +1,5 @@import { useRef, useEffect, useCallback } from "react"import { BookOpen } from "lucide-react"-import { ScrollArea } from "@/components/ui/scroll-area"import { Button } from "@/components/ui/button"import { ChatMessage, StreamingMessage } from "./chat-message"import { ChatInput } from "./chat-input"@@ -25,10 +24,15 @@ export function ChatPanel() {const setFileTree = useWikiStore((s) => s.setFileTree)const abortRef = useRef<AbortController | null>(null)+ const scrollContainerRef = useRef<HTMLDivElement>(null)const bottomRef = useRef<HTMLDivElement>(null)+ // Auto-scroll to bottom when messages change or streaming content updatesuseEffect(() => {- bottomRef.current?.scrollIntoView({ behavior: "smooth" })+ const container = scrollContainerRef.current+ if (container) {+ container.scrollTop = container.scrollHeight+ }}, [messages, streamingContent])const handleSend = useCallback(@@ -76,12 +80,11 @@ export function ChatPanel() {if (!project) returntry {await executeIngestWrites(project.path, llmConfig, undefined, undefined)- // Refresh the file tree after writestry {- const tree = await listDirectory(`${project.path}/wiki`)+ const tree = await listDirectory(project.path)setFileTree(tree)} catch {- // ignore tree refresh failure+ // ignore}} catch (err) {console.error("Failed to write to wiki:", err)@@ -93,7 +96,10 @@ export function ChatPanel() {return (<div className="flex h-full flex-col">- <ScrollArea className="flex-1 px-3 py-2">+ <div+ ref={scrollContainerRef}+ className="flex-1 overflow-y-auto px-3 py-2"+ ><div className="flex flex-col gap-3">{messages.map((msg) => (<ChatMessage key={msg.id} message={msg} />@@ -101,7 +107,7 @@ export function ChatPanel() {{isStreaming && <StreamingMessage content={streamingContent} />}<div ref={bottomRef} /></div>- </ScrollArea>+ </div>{showWriteButton && (<div className="border-t px-3 py-2">diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsxindex 07ff3826..a3db499a 100644--- a/src/components/sources/sources-view.tsx+++ b/src/components/sources/sources-view.tsx@@ -6,7 +6,7 @@ import { ScrollArea } from "@/components/ui/scroll-area"import { useWikiStore } from "@/stores/wiki-store"import { copyFile, listDirectory, readFile } from "@/commands/fs"import type { FileNode } from "@/types/wiki"-import { startIngest } from "@/lib/ingest"+import { startIngest, autoIngest } from "@/lib/ingest"export function SourcesView() {const project = useWikiStore((s) => s.project)@@ -90,6 +90,17 @@ export function SourcesView() {setImporting(false)await loadSources()++ // Auto-ingest each imported file+ if (llmConfig.apiKey || llmConfig.provider === "ollama") {+ setChatExpanded(true)+ setActiveView("wiki")+ for (const sourcePath of paths) {+ const fileName = sourcePath.split("/").pop() || sourcePath.split("\\").pop() || "unknown"+ const destPath = `${project.path}/raw/sources/${fileName}`+ await autoIngest(project.path, destPath, llmConfig)+ }+ }}async function handleOpenSource(node: FileNode) {diff --git a/src/lib/ingest.ts b/src/lib/ingest.tsindex 8268779d..d4661bb3 100644--- a/src/lib/ingest.ts+++ b/src/lib/ingest.ts@@ -1,10 +1,136 @@-import { readFile, writeFile } from "@/commands/fs"+import { readFile, writeFile, listDirectory } from "@/commands/fs"import { streamChat } from "@/lib/llm-client"import type { LlmConfig } from "@/stores/wiki-store"+import { useWikiStore } from "@/stores/wiki-store"import { useChatStore } from "@/stores/chat-store"const FILE_BLOCK_REGEX = /---FILE:\s*([^\n-]+?)\s*---\n([\s\S]*?)---END FILE---/g+/**+ * Auto-ingest: reads source → LLM analyzes → LLM writes wiki pages, all in one go.+ * Used when importing new files.+ */+export async function autoIngest(+ projectPath: string,+ sourcePath: string,+ llmConfig: LlmConfig,+ signal?: AbortSignal,+): Promise<string[]> {+ const store = getStore()+ store.setMode("ingest")+ store.setIngestSource(sourcePath)+ store.clearMessages()+ store.setStreaming(false)++ const [sourceContent, schema, purpose, index] = await Promise.all([+ tryReadFile(sourcePath),+ tryReadFile(`${projectPath}/schema.md`),+ tryReadFile(`${projectPath}/purpose.md`),+ tryReadFile(`${projectPath}/wiki/index.md`),+ ])++ const fileName = sourcePath.split("/").pop() ?? sourcePath++ const systemPrompt = [+ "You are a wiki maintainer. You will read a source document and directly produce wiki files.",+ "Output ONLY wiki files in this exact format:",+ "",+ "---FILE: wiki/sources/filename.md---",+ "(complete file content with YAML frontmatter)",+ "---END FILE---",+ "",+ "For each source, produce:",+ "1. A source summary page in wiki/sources/",+ "2. Entity pages in wiki/entities/ for key entities (people, organizations, products)",+ "3. Concept pages in wiki/concepts/ for key concepts (theories, methods, techniques)",+ "4. An updated wiki/index.md with new entries added to existing categories",+ "5. A log entry for wiki/log.md (just the new entry to append)",+ "",+ "Use YAML frontmatter on every page. Use [[wikilink]] syntax for cross-references.",+ "Use kebab-case filenames.",+ "",+ purpose ? `## Wiki Purpose\n${purpose}` : "",+ schema ? `## Wiki Schema\n${schema}` : "",+ index ? `## Current Wiki Index (add to this, don't remove existing entries)\n${index}` : "",+ ].filter(Boolean).join("\n")++ const userMessage = `Ingest this source into the wiki:\n\n**File:** ${fileName}\n\n---\n\n${sourceContent.length > 50000 ? sourceContent.slice(0, 50000) + "\n\n[...truncated...]" : sourceContent}`++ store.addMessage("system", `Auto-ingesting: ${fileName}`)+ store.addMessage("user", userMessage)+ store.setStreaming(true)++ let accumulated = ""++ await streamChat(+ llmConfig,+ [+ { role: "system", content: systemPrompt },+ { role: "user", content: userMessage },+ ],+ {+ onToken: (token) => {+ accumulated += token+ getStore().appendStreamToken(token)+ },+ onDone: () => {+ getStore().finalizeStream(accumulated)+ },+ onError: (err) => {+ getStore().finalizeStream(`Error during auto-ingest: ${err.message}`)+ },+ },+ signal,+ )++ // Parse and write files+ const writtenPaths = await writeFileBlocks(projectPath, accumulated)++ if (writtenPaths.length > 0) {+ const fileList = writtenPaths.map((p) => `- ${p}`).join("\n")+ getStore().addMessage("system", `✓ Wiki updated (${writtenPaths.length} files):\n${fileList}`)++ // Refresh file tree+ try {+ const tree = await listDirectory(projectPath)+ useWikiStore.getState().setFileTree(tree)+ } catch {+ // ignore+ }+ } else {+ getStore().addMessage("system", "No wiki files were generated.")+ }++ return writtenPaths+}++async function writeFileBlocks(projectPath: string, text: string): Promise<string[]> {+ const writtenPaths: string[] = []+ const matches = text.matchAll(FILE_BLOCK_REGEX)++ for (const match of matches) {+ const relativePath = match[1].trim()+ const content = match[2]+ if (!relativePath) continue++ const fullPath = `${projectPath}/${relativePath}`+ try {+ if (relativePath === "wiki/log.md" || relativePath.endsWith("/log.md")) {+ const existing = await tryReadFile(fullPath)+ const appended = existing ? `${existing}\n\n${content.trim()}` : content.trim()+ await writeFile(fullPath, appended)+ } else {+ await writeFile(fullPath, content)+ }+ writtenPaths.push(relativePath)+ } catch (err) {+ console.error(`Failed to write ${fullPath}:`, err)+ }+ }++ return writtenPaths+}+function getStore() {return useChatStore.getState()}