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: Deep Research panel with task queue and concurrent execution
nash_sud3b411ca0c61
diff --git a/src/components/layout/app-layout.tsx b/src/components/layout/app-layout.tsxindex 9c4b380f..f171f363 100644--- a/src/components/layout/app-layout.tsx+++ b/src/components/layout/app-layout.tsx@@ -5,7 +5,9 @@ import { IconSidebar } from "./icon-sidebar"import { SidebarPanel } from "./sidebar-panel"import { ContentArea } from "./content-area"import { PreviewPanel } from "./preview-panel"+import { ResearchPanel } from "./research-panel"import { ActivityPanel } from "./activity-panel"+import { useResearchStore } from "@/stores/research-store"interface AppLayoutProps {onSwitchProject: () => void@@ -14,6 +16,8 @@ interface AppLayoutProps {export function AppLayout({ onSwitchProject }: AppLayoutProps) {const project = useWikiStore((s) => s.project)const selectedFile = useWikiStore((s) => s.selectedFile)+ const researchPanelOpen = useResearchStore((s) => s.panelOpen)+ const researchTasks = useResearchStore((s) => s.tasks)const setFileTree = useWikiStore((s) => s.setFileTree)const [leftWidth, setLeftWidth] = useState(220)const [rightWidth, setRightWidth] = useState(400)@@ -96,18 +100,29 @@ export function AppLayout({ onSwitchProject }: AppLayoutProps) {<ContentArea /></div>- {/* Right: File preview (shown when a file is selected) */}- {selectedFile && (+ {/* Right panels */}+ {(selectedFile || researchPanelOpen) && (<><divclassName="w-1.5 shrink-0 cursor-col-resize bg-border/40 transition-colors hover:bg-primary/30 active:bg-primary/40"onMouseDown={startDrag("right")}/><div- className="shrink-0 overflow-hidden border-l"+ className="flex shrink-0 flex-col overflow-hidden border-l"style={{ width: rightWidth }}>- <PreviewPanel />+ {/* File preview on top (if file selected) */}+ {selectedFile && (+ <div className={researchPanelOpen ? "flex-1 overflow-hidden border-b" : "flex-1 overflow-hidden"}>+ <PreviewPanel />+ </div>+ )}+ {/* Research panel on bottom (if open) */}+ {researchPanelOpen && (+ <div className={selectedFile ? "h-1/2 shrink-0 overflow-hidden" : "flex-1 overflow-hidden"}>+ <ResearchPanel />+ </div>+ )}</div></>)}diff --git a/src/components/layout/research-panel.tsx b/src/components/layout/research-panel.tsxnew file mode 100644index 00000000..59dd9e46--- /dev/null+++ b/src/components/layout/research-panel.tsx@@ -0,0 +1,185 @@+import { useState } from "react"+import ReactMarkdown from "react-markdown"+import {+ Search, Loader2, CheckCircle2, AlertCircle, ChevronRight, ChevronDown, X,+ ExternalLink, FileText,+} from "lucide-react"+import { Button } from "@/components/ui/button"+import { useResearchStore, type ResearchTask } from "@/stores/research-store"+import { useWikiStore } from "@/stores/wiki-store"+import { readFile } from "@/commands/fs"++export function ResearchPanel() {+ const tasks = useResearchStore((s) => s.tasks)+ const removeTask = useResearchStore((s) => s.removeTask)+ const setPanelOpen = useResearchStore((s) => s.setPanelOpen)++ const running = tasks.filter((t) => ["searching", "synthesizing", "saving"].includes(t.status))+ const queued = tasks.filter((t) => t.status === "queued")+ const done = tasks.filter((t) => t.status === "done" || t.status === "error")++ return (+ <div className="flex h-full flex-col">+ <div className="flex shrink-0 items-center justify-between border-b px-3 py-2">+ <div className="flex items-center gap-2">+ <Search className="h-4 w-4 text-muted-foreground" />+ <span className="text-sm font-semibold">Deep Research</span>+ {(running.length > 0 || queued.length > 0) && (+ <span className="rounded-full bg-primary/20 px-1.5 py-0.5 text-[10px] font-medium text-primary">+ {running.length} running{queued.length > 0 ? `, ${queued.length} queued` : ""}+ </span>+ )}+ </div>+ <button+ onClick={() => setPanelOpen(false)}+ className="rounded p-1 text-muted-foreground hover:bg-accent"+ >+ <X className="h-3.5 w-3.5" />+ </button>+ </div>++ <div className="flex-1 overflow-y-auto">+ {tasks.length === 0 ? (+ <div className="flex flex-col items-center justify-center gap-2 p-8 text-center text-xs text-muted-foreground">+ <Search className="h-8 w-8 opacity-20" />+ <p>No research tasks yet</p>+ </div>+ ) : (+ <div className="flex flex-col gap-1 p-2">+ {running.map((task) => (+ <ResearchTaskCard key={task.id} task={task} onRemove={removeTask} />+ ))}+ {queued.map((task) => (+ <ResearchTaskCard key={task.id} task={task} onRemove={removeTask} />+ ))}+ {done.map((task) => (+ <ResearchTaskCard key={task.id} task={task} onRemove={removeTask} />+ ))}+ </div>+ )}+ </div>+ </div>+ )+}++function ResearchTaskCard({ task, onRemove }: { task: ResearchTask; onRemove: (id: string) => void }) {+ const [expanded, setExpanded] = useState(+ task.status === "synthesizing" || task.status === "searching"+ )+ const setSelectedFile = useWikiStore((s) => s.setSelectedFile)+ const setFileContent = useWikiStore((s) => s.setFileContent)+ const project = useWikiStore((s) => s.project)++ const statusIcon = {+ queued: <div className="h-3 w-3 rounded-full border-2 border-muted-foreground" />,+ searching: <Loader2 className="h-3 w-3 animate-spin text-blue-500" />,+ synthesizing: <Loader2 className="h-3 w-3 animate-spin text-purple-500" />,+ saving: <Loader2 className="h-3 w-3 animate-spin text-orange-500" />,+ done: <CheckCircle2 className="h-3 w-3 text-emerald-500" />,+ error: <AlertCircle className="h-3 w-3 text-destructive" />,+ }[task.status]++ const statusText = {+ queued: "Queued",+ searching: "Searching web...",+ synthesizing: "Synthesizing...",+ saving: "Saving to wiki...",+ done: task.savedPath ? "Saved" : "Done",+ error: "Failed",+ }[task.status]++ async function handleOpenSaved() {+ if (!project || !task.savedPath) return+ const path = `${project.path}/${task.savedPath}`+ try {+ const content = await readFile(path)+ setSelectedFile(path)+ setFileContent(content)+ } catch {+ // ignore+ }+ }++ return (+ <div className="rounded-lg border text-xs">+ {/* Header */}+ <button+ onClick={() => setExpanded(!expanded)}+ className="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-accent/50"+ >+ {expanded ? (+ <ChevronDown className="h-3 w-3 shrink-0 text-muted-foreground" />+ ) : (+ <ChevronRight className="h-3 w-3 shrink-0 text-muted-foreground" />+ )}+ {statusIcon}+ <span className="flex-1 truncate font-medium">{task.topic}</span>+ <span className="shrink-0 text-muted-foreground">{statusText}</span>+ </button>++ {/* Expanded content */}+ {expanded && (+ <div className="border-t px-3 py-2">+ {/* Error */}+ {task.error && (+ <p className="mb-2 text-destructive">{task.error}</p>+ )}++ {/* Web results */}+ {task.webResults.length > 0 && (+ <div className="mb-2">+ <div className="mb-1 font-medium text-muted-foreground">+ Sources ({task.webResults.length})+ </div>+ <div className="flex flex-col gap-1">+ {task.webResults.map((r, i) => (+ <div key={i} className="flex items-start gap-1.5 rounded bg-muted/50 px-2 py-1">+ <span className="shrink-0 font-mono text-muted-foreground">[{i + 1}]</span>+ <div className="min-w-0 flex-1">+ <div className="truncate font-medium">{r.title}</div>+ <div className="truncate text-muted-foreground">{r.source}</div>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Synthesis (streaming) */}+ {task.synthesis && (+ <div className="mb-2">+ <div className="mb-1 font-medium text-muted-foreground">Synthesis</div>+ <div className="max-h-64 overflow-y-auto rounded bg-muted/30 p-2 prose prose-xs prose-invert max-w-none">+ <ReactMarkdown>{task.synthesis}</ReactMarkdown>+ {task.status === "synthesizing" && (+ <span className="animate-pulse">▊</span>+ )}+ </div>+ </div>+ )}++ {/* Actions */}+ <div className="flex items-center gap-1.5 mt-2">+ {task.savedPath && (+ <Button variant="outline" size="sm" className="h-6 text-[11px] gap-1" onClick={handleOpenSaved}>+ <FileText className="h-3 w-3" />+ Open+ </Button>+ )}+ {(task.status === "done" || task.status === "error") && (+ <Button+ variant="ghost"+ size="sm"+ className="h-6 text-[11px] gap-1 text-muted-foreground"+ onClick={() => onRemove(task.id)}+ >+ <X className="h-3 w-3" />+ Remove+ </Button>+ )}+ </div>+ </div>+ )}+ </div>+ )+}diff --git a/src/components/review/review-view.tsx b/src/components/review/review-view.tsxindex 828f4d76..fb7cf0c0 100644--- a/src/components/review/review-view.tsx+++ b/src/components/review/review-view.tsx@@ -1,5 +1,5 @@import { useCallback } from "react"-import { deepResearch } from "@/lib/deep-research"+import { queueResearch } from "@/lib/deep-research"import {AlertTriangle,Copy,@@ -167,19 +167,14 @@ export function ReviewView() {resolveItem(id, action)}} else if (action === "__deep_research__" && project) {- // Deep Research: use web search + LLM to explore the topic+ // Queue deep research taskconst item = items.find((i) => i.id === id)if (item) {const llmConfig = useWikiStore.getState().llmConfigconst searchConfig = useWikiStore.getState().searchApiConfigconst topic = item.title.replace(/^(Save to Wiki|Create|Research)[:\s]*/i, "").trim() || item.description.split("\n")[0]- try {- const result = await deepResearch(project.path, topic, llmConfig, searchConfig)- resolveItem(id, result.savedPath ? `Researched → ${result.savedPath}` : "Researched (no results)")- } catch (err) {- const msg = err instanceof Error ? err.message : String(err)- resolveItem(id, `Research failed: ${msg}`)- }+ queueResearch(project.path, topic, llmConfig, searchConfig)+ resolveItem(id, "Queued for research")} else {resolveItem(id, action)}diff --git a/src/lib/deep-research.ts b/src/lib/deep-research.tsindex 2783034b..284d47e4 100644--- a/src/lib/deep-research.ts+++ b/src/lib/deep-research.ts@@ -1,190 +1,177 @@-import { webSearch, type WebSearchResult } from "./web-search"+import { webSearch } from "./web-search"import { streamChat } from "./llm-client"-import { writeFile } from "@/commands/fs"+import { writeFile, listDirectory } from "@/commands/fs"import { useWikiStore, type LlmConfig, type SearchApiConfig } from "@/stores/wiki-store"-import { useActivityStore } from "@/stores/activity-store"-import { useChatStore } from "@/stores/chat-store"-import { listDirectory } from "@/commands/fs"--export interface ResearchResult {- query: string- webResults: WebSearchResult[]- synthesis: string- savedPath: string | null+import { useResearchStore } from "@/stores/research-store"++let processing = false++/**+ * Queue a deep research task. Automatically starts processing if under concurrency limit.+ */+export function queueResearch(+ projectPath: string,+ topic: string,+ llmConfig: LlmConfig,+ searchConfig: SearchApiConfig,+): string {+ const store = useResearchStore.getState()+ const taskId = store.addTask(topic)+ processQueue(projectPath, llmConfig, searchConfig)+ return taskId}/**- * Deep Research: search the web for a topic, synthesize findings with LLM, save to wiki.- * Shows the entire process in the Chat panel.+ * Process queued tasks up to maxConcurrent limit.*/-export async function deepResearch(+function processQueue(+ projectPath: string,+ llmConfig: LlmConfig,+ searchConfig: SearchApiConfig,+) {+ const store = useResearchStore.getState()+ const running = store.getRunningCount()+ const available = store.maxConcurrent - running++ for (let i = 0; i < available; i++) {+ const next = useResearchStore.getState().getNextQueued()+ if (!next) break+ executeResearch(projectPath, next.id, next.topic, llmConfig, searchConfig)+ }+}++async function executeResearch(projectPath: string,+ taskId: string,topic: string,llmConfig: LlmConfig,searchConfig: SearchApiConfig,-): Promise<ResearchResult> {- const activity = useActivityStore.getState()- const chat = useChatStore.getState()-- const activityId = activity.addItem({- type: "query",- title: `Research: ${topic.slice(0, 50)}`,- status: "running",- detail: "Searching the web...",- filesWritten: [],- })-- // Switch chat to show the research process- chat.setMode("chat")- chat.clearMessages()- chat.addMessage("system", `🔍 Deep Research: ${topic}`)-- // Make sure chat is visible- useWikiStore.getState().setActiveView("wiki")-- let webResults: WebSearchResult[] = []- let synthesis = ""- let savedPath: string | null = null+) {+ const store = useResearchStore.getState()try {// Step 1: Web search- chat.addMessage("system", "Searching the web...")- webResults = await webSearch(topic, searchConfig, 8)+ store.updateTask(taskId, { status: "searching" })++ const webResults = await webSearch(topic, searchConfig, 8)+ store.updateTask(taskId, { webResults })if (webResults.length === 0) {- chat.addMessage("system", "No web results found for this topic.")- activity.updateItem(activityId, { status: "done", detail: "No results found" })- return { query: topic, webResults, synthesis: "", savedPath: null }+ store.updateTask(taskId, { status: "done", synthesis: "No web results found." })+ onTaskFinished(projectPath, llmConfig, searchConfig)+ return}- // Show search results in chat- const resultsText = webResults- .map((r, i) => `**${i + 1}. [${r.title}](${r.url})**\n> ${r.snippet}\n> _${r.source}_`)- .join("\n\n")-- chat.addMessage("assistant", `Found **${webResults.length} sources**:\n\n${resultsText}`)-- activity.updateItem(activityId, {- detail: `Found ${webResults.length} results, synthesizing...`,- })-- // Step 2: LLM synthesizes findings (streamed to chat)- chat.addMessage("system", "Synthesizing findings...")+ // Step 2: LLM synthesis+ store.updateTask(taskId, { status: "synthesizing" })const searchContext = webResults.map((r, i) => `[${i + 1}] **${r.title}** (${r.source})\n${r.snippet}`).join("\n\n")const systemPrompt = [- "You are a research assistant. Synthesize the web search results below into a comprehensive wiki page.",- "",- "Rules:",- "- Organize findings into clear sections with headings",- "- Cite sources using [N] notation matching the search result numbers",- "- Note any contradictions or gaps in the findings",- "- Suggest what additional sources might be valuable",- "- Write in a neutral, encyclopedic tone",- "- Use [[wikilink]] syntax if referencing concepts that might exist in the wiki",- ].join("\n")-- const userMessage = [- `Research topic: **${topic}**`,- "",- "## Web Search Results",- "",- searchContext,- "",- "Please synthesize these findings into a comprehensive wiki page.",+ "You are a research assistant. Synthesize the web search results into a comprehensive wiki page.",+ "- Organize into clear sections with headings",+ "- Cite sources using [N] notation",+ "- Note contradictions or gaps",+ "- Suggest additional sources worth finding",+ "- Neutral, encyclopedic tone",+ "- Use [[wikilink]] for cross-references",].join("\n")let accumulated = ""- chat.setStreaming(true)await streamChat(llmConfig,[{ role: "system", content: systemPrompt },- { role: "user", content: userMessage },+ { role: "user", content: `Research topic: **${topic}**\n\n## Web Search Results\n\n${searchContext}\n\nSynthesize into a wiki page.` },],{onToken: (token) => {accumulated += token- useChatStore.getState().appendStreamToken(token)- },- onDone: () => {- useChatStore.getState().finalizeStream(accumulated)+ // Update synthesis progressively so UI shows real-time text+ useResearchStore.getState().updateTask(taskId, { synthesis: accumulated })},+ onDone: () => {},onError: (err) => {- useChatStore.getState().finalizeStream(`Research synthesis error: ${err.message}`)+ useResearchStore.getState().updateTask(taskId, {+ status: "error",+ error: err.message,+ })},},)- synthesis = accumulated+ // Check if errored during streaming+ if (useResearchStore.getState().tasks.find((t) => t.id === taskId)?.status === "error") {+ onTaskFinished(projectPath, llmConfig, searchConfig)+ return+ }// Step 3: Save to wiki- if (synthesis && !synthesis.startsWith("Research synthesis error")) {- activity.updateItem(activityId, { detail: "Saving to wiki..." })-- const date = new Date().toISOString().slice(0, 10)- const slug = topic- .toLowerCase()- .replace(/[^a-z0-9\s-]/g, "")- .trim()- .replace(/\s+/g, "-")- .slice(0, 50)- const fileName = `research-${slug}-${date}.md`- const filePath = `${projectPath}/wiki/queries/${fileName}`-- const references = webResults- .map((r, i) => `${i + 1}. [${r.title}](${r.url}) — ${r.source}`)- .join("\n")-- const pageContent = [- "---",- `type: query`,- `title: "Research: ${topic.replace(/"/g, '\\"')}"`,- `created: ${date}`,- `origin: deep-research`,- `tags: [research]`,- "---",- "",- `# Research: ${topic}`,- "",- synthesis,- "",- "## References",- "",- references,- "",- ].join("\n")-- await writeFile(filePath, pageContent)- savedPath = `wiki/queries/${fileName}`-- // Show save confirmation in chat- useChatStore.getState().addMessage("system", `✅ Saved to wiki: \`${savedPath}\`\n\nReferences:\n${references}`)-- // Refresh tree- try {- const tree = await listDirectory(projectPath)- useWikiStore.getState().setFileTree(tree)- useWikiStore.getState().bumpDataVersion()- } catch {- // ignore- }- }+ store.updateTask(taskId, { status: "saving", synthesis: accumulated })++ const date = new Date().toISOString().slice(0, 10)+ const slug = topic.toLowerCase().replace(/[^a-z0-9\s-]/g, "").trim().replace(/\s+/g, "-").slice(0, 50)+ const fileName = `research-${slug}-${date}.md`+ const filePath = `${projectPath}/wiki/queries/${fileName}`++ const references = webResults+ .map((r, i) => `${i + 1}. [${r.title}](${r.url}) — ${r.source}`)+ .join("\n")++ const pageContent = [+ "---",+ `type: query`,+ `title: "Research: ${topic.replace(/"/g, '\\"')}"`,+ `created: ${date}`,+ `origin: deep-research`,+ `tags: [research]`,+ "---",+ "",+ `# Research: ${topic}`,+ "",+ accumulated,+ "",+ "## References",+ "",+ references,+ "",+ ].join("\n")++ await writeFile(filePath, pageContent)+ const savedPath = `wiki/queries/${fileName}`- activity.updateItem(activityId, {+ useResearchStore.getState().updateTask(taskId, {status: "done",- detail: `${webResults.length} sources found${savedPath ? ", saved to wiki" : ""}`,- filesWritten: savedPath ? [savedPath] : [],+ savedPath,})++ // Refresh tree+ try {+ const tree = await listDirectory(projectPath)+ useWikiStore.getState().setFileTree(tree)+ useWikiStore.getState().bumpDataVersion()+ } catch {+ // ignore+ }} catch (err) {const message = err instanceof Error ? err.message : String(err)- activity.updateItem(activityId, { status: "error", detail: message })- useChatStore.getState().addMessage("system", `❌ Research failed: ${message}`)+ useResearchStore.getState().updateTask(taskId, {+ status: "error",+ error: message,+ })}- return { query: topic, webResults, synthesis, savedPath }+ onTaskFinished(projectPath, llmConfig, searchConfig)+}++function onTaskFinished(+ projectPath: string,+ llmConfig: LlmConfig,+ searchConfig: SearchApiConfig,+) {+ // Process next queued task+ setTimeout(() => processQueue(projectPath, llmConfig, searchConfig), 100)}diff --git a/src/stores/research-store.ts b/src/stores/research-store.tsnew file mode 100644index 00000000..b913e710--- /dev/null+++ b/src/stores/research-store.ts@@ -0,0 +1,79 @@+import { create } from "zustand"+import type { WebSearchResult } from "@/lib/web-search"++export interface ResearchTask {+ id: string+ topic: string+ status: "queued" | "searching" | "synthesizing" | "saving" | "done" | "error"+ webResults: WebSearchResult[]+ synthesis: string+ savedPath: string | null+ error: string | null+ createdAt: number+}++interface ResearchState {+ tasks: ResearchTask[]+ panelOpen: boolean+ maxConcurrent: number++ addTask: (topic: string) => string+ updateTask: (id: string, updates: Partial<ResearchTask>) => void+ removeTask: (id: string) => void+ setPanelOpen: (open: boolean) => void+ getRunningCount: () => number+ getNextQueued: () => ResearchTask | undefined+}++let counter = 0++export const useResearchStore = create<ResearchState>((set, get) => ({+ tasks: [],+ panelOpen: false,+ maxConcurrent: 3,++ addTask: (topic) => {+ const id = `research-${++counter}`+ set((state) => ({+ tasks: [+ ...state.tasks,+ {+ id,+ topic,+ status: "queued",+ webResults: [],+ synthesis: "",+ savedPath: null,+ error: null,+ createdAt: Date.now(),+ },+ ],+ panelOpen: true,+ }))+ return id+ },++ updateTask: (id, updates) =>+ set((state) => ({+ tasks: state.tasks.map((t) => (t.id === id ? { ...t, ...updates } : t)),+ })),++ removeTask: (id) =>+ set((state) => ({+ tasks: state.tasks.filter((t) => t.id !== id),+ })),++ setPanelOpen: (panelOpen) => set({ panelOpen }),++ getRunningCount: () => {+ const { tasks } = get()+ return tasks.filter((t) =>+ t.status === "searching" || t.status === "synthesizing" || t.status === "saving"+ ).length+ },++ getNextQueued: () => {+ const { tasks } = get()+ return tasks.find((t) => t.status === "queued")+ },+}))