Skip to content

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 — AI-powered web search to explore knowledge gaps

nash_su48194200a075
diff --git a/src/App.tsx b/src/App.tsx
index c114de6f..3f42b6db 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -3,7 +3,7 @@ import { open } from "@tauri-apps/plugin-dialog"
import i18n from "@/i18n"
import { useWikiStore } from "@/stores/wiki-store"
import { listDirectory, openProject } from "@/commands/fs"
-import { getLastProject, saveLastProject, loadLlmConfig, loadLanguage } from "@/lib/project-store"
+import { getLastProject, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig } from "@/lib/project-store"
import { AppLayout } from "@/components/layout/app-layout"
import { WelcomeScreen } from "@/components/project/welcome-screen"
import { CreateProjectDialog } from "@/components/project/create-project-dialog"
@@ -26,6 +26,10 @@ function App() {
if (savedConfig) {
useWikiStore.getState().setLlmConfig(savedConfig)
}
+ const savedSearchConfig = await loadSearchApiConfig()
+ if (savedSearchConfig) {
+ useWikiStore.getState().setSearchApiConfig(savedSearchConfig)
+ }
const savedLang = await loadLanguage()
if (savedLang) {
await i18n.changeLanguage(savedLang)
diff --git a/src/components/review/review-view.tsx b/src/components/review/review-view.tsx
index a97b4989..828f4d76 100644
--- a/src/components/review/review-view.tsx
+++ b/src/components/review/review-view.tsx
@@ -1,4 +1,5 @@
import { useCallback } from "react"
+import { deepResearch } from "@/lib/deep-research"
import {
AlertTriangle,
Copy,
@@ -165,6 +166,23 @@ export function ReviewView() {
} else {
resolveItem(id, action)
}
+ } else if (action === "__deep_research__" && project) {
+ // Deep Research: use web search + LLM to explore the topic
+ const item = items.find((i) => i.id === id)
+ if (item) {
+ const llmConfig = useWikiStore.getState().llmConfig
+ const searchConfig = useWikiStore.getState().searchApiConfig
+ const 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}`)
+ }
+ } else {
+ resolveItem(id, action)
+ }
} else {
resolveItem(id, action)
}
@@ -269,6 +287,16 @@ function ReviewCard({
{!item.resolved ? (
<div className="flex flex-wrap gap-1.5">
+ {(item.type === "suggestion" || item.type === "missing-page") && (
+ <Button
+ variant="default"
+ size="sm"
+ className="h-7 text-xs gap-1"
+ onClick={() => onResolve(item.id, "__deep_research__")}
+ >
+ 🔍 Deep Research
+ </Button>
+ )}
{item.options.map((opt) => (
<Button
key={opt.action}
diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsx
index 2022030d..eed5f8bc 100644
--- a/src/components/settings/settings-view.tsx
+++ b/src/components/settings/settings-view.tsx
@@ -24,12 +24,16 @@ export function SettingsView() {
const { t } = useTranslation()
const llmConfig = useWikiStore((s) => s.llmConfig)
const setLlmConfig = useWikiStore((s) => s.setLlmConfig)
+ const searchApiConfig = useWikiStore((s) => s.searchApiConfig)
+ const setSearchApiConfig = useWikiStore((s) => s.setSearchApiConfig)
const [provider, setProvider] = useState(llmConfig.provider)
const [apiKey, setApiKey] = useState(llmConfig.apiKey)
const [model, setModel] = useState(llmConfig.model)
const [ollamaUrl, setOllamaUrl] = useState(llmConfig.ollamaUrl)
const [customEndpoint, setCustomEndpoint] = useState(llmConfig.customEndpoint)
+ const [searchProvider, setSearchProvider] = useState(searchApiConfig.provider)
+ const [searchApiKey, setSearchApiKey] = useState(searchApiConfig.apiKey)
const [saved, setSaved] = useState(false)
const [currentLang, setCurrentLang] = useState(i18n.language)
@@ -41,11 +45,19 @@ export function SettingsView() {
setCustomEndpoint(llmConfig.customEndpoint)
}, [llmConfig])
+ useEffect(() => {
+ setSearchProvider(searchApiConfig.provider)
+ setSearchApiKey(searchApiConfig.apiKey)
+ }, [searchApiConfig])
+
const currentProvider = PROVIDERS.find((p) => p.value === provider)
async function handleSave() {
- const { saveLlmConfig } = await import("@/lib/project-store")
+ const { saveLlmConfig, saveSearchApiConfig } = await import("@/lib/project-store")
const newConfig = { provider, apiKey, model, ollamaUrl, customEndpoint }
+ const newSearchConfig = { provider: searchProvider, apiKey: searchApiKey }
+ setSearchApiConfig(newSearchConfig)
+ await saveSearchApiConfig(newSearchConfig)
setLlmConfig(newConfig)
await saveLlmConfig(newConfig)
setSaved(true)
@@ -191,6 +203,49 @@ export function SettingsView() {
</div>
</div>
+ {/* Web Search API section */}
+ <div className="space-y-4 rounded-lg border p-4">
+ <h3 className="font-semibold">Web Search (Deep Research)</h3>
+ <p className="text-xs text-muted-foreground">
+ Enable AI-powered web research to automatically find relevant sources for knowledge gaps.
+ </p>
+
+ <div className="space-y-2">
+ <Label>Search Provider</Label>
+ <div className="flex flex-wrap gap-2">
+ {[
+ { value: "none" as const, label: "Disabled" },
+ { value: "tavily" as const, label: "Tavily" },
+ ].map((p) => (
+ <button
+ key={p.value}
+ onClick={() => setSearchProvider(p.value)}
+ className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
+ searchProvider === p.value
+ ? "border-primary bg-primary text-primary-foreground"
+ : "border-border hover:bg-accent"
+ }`}
+ >
+ {p.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {searchProvider !== "none" && (
+ <div className="space-y-2">
+ <Label htmlFor="searchApiKey">API Key</Label>
+ <Input
+ id="searchApiKey"
+ type="password"
+ value={searchApiKey}
+ onChange={(e) => setSearchApiKey(e.target.value)}
+ placeholder="Enter your Tavily API key (tavily.com)"
+ />
+ </div>
+ )}
+ </div>
+
<Button onClick={handleSave} className="w-full">
{saved ? t("settings.saved") : t("settings.save")}
</Button>
diff --git a/src/lib/deep-research.ts b/src/lib/deep-research.ts
new file mode 100644
index 00000000..f61919d7
--- /dev/null
+++ b/src/lib/deep-research.ts
@@ -0,0 +1,151 @@
+import { webSearch, type WebSearchResult } from "./web-search"
+import { streamChat } from "./llm-client"
+import { writeFile } from "@/commands/fs"
+import { useWikiStore, type LlmConfig, type SearchApiConfig } from "@/stores/wiki-store"
+import { useActivityStore } from "@/stores/activity-store"
+import { listDirectory } from "@/commands/fs"
+
+export interface ResearchResult {
+ query: string
+ webResults: WebSearchResult[]
+ synthesis: string
+ savedPath: string | null
+}
+
+/**
+ * Deep Research: search the web for a topic, synthesize findings with LLM, save to wiki.
+ */
+export async function deepResearch(
+ projectPath: string,
+ topic: string,
+ llmConfig: LlmConfig,
+ searchConfig: SearchApiConfig,
+): Promise<ResearchResult> {
+ const activity = useActivityStore.getState()
+ const activityId = activity.addItem({
+ type: "query",
+ title: `Research: ${topic.slice(0, 50)}`,
+ status: "running",
+ detail: "Searching the web...",
+ filesWritten: [],
+ })
+
+ let webResults: WebSearchResult[] = []
+ let synthesis = ""
+ let savedPath: string | null = null
+
+ try {
+ // Step 1: Web search
+ webResults = await webSearch(topic, searchConfig, 8)
+ activity.updateItem(activityId, {
+ detail: `Found ${webResults.length} results, synthesizing...`,
+ })
+
+ // Step 2: LLM synthesizes findings
+ 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.",
+ ].join("\n")
+
+ let accumulated = ""
+
+ await streamChat(
+ llmConfig,
+ [
+ { role: "system", content: systemPrompt },
+ { role: "user", content: userMessage },
+ ],
+ {
+ onToken: (token) => { accumulated += token },
+ onDone: () => {},
+ onError: (err) => {
+ synthesis = `Research error: ${err.message}`
+ },
+ },
+ )
+
+ synthesis = accumulated || synthesis
+
+ // Step 3: Save to wiki as a query/research page
+ if (synthesis && !synthesis.startsWith("Research 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}`
+
+ // Refresh tree
+ try {
+ const tree = await listDirectory(projectPath)
+ useWikiStore.getState().setFileTree(tree)
+ useWikiStore.getState().bumpDataVersion()
+ } catch {
+ // ignore
+ }
+ }
+
+ activity.updateItem(activityId, {
+ status: "done",
+ detail: `${webResults.length} sources found${savedPath ? ", saved to wiki" : ""}`,
+ filesWritten: savedPath ? [savedPath] : [],
+ })
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err)
+ activity.updateItem(activityId, { status: "error", detail: message })
+ }
+
+ return { query: topic, webResults, synthesis, savedPath }
+}
diff --git a/src/lib/project-store.ts b/src/lib/project-store.ts
index 108d28cc..67f7f512 100644
--- a/src/lib/project-store.ts
+++ b/src/lib/project-store.ts
@@ -1,6 +1,6 @@
import { load } from "@tauri-apps/plugin-store"
import type { WikiProject } from "@/types/wiki"
-import type { LlmConfig } from "@/stores/wiki-store"
+import type { LlmConfig, SearchApiConfig } from "@/stores/wiki-store"
const STORE_NAME = "app-state.json"
const RECENT_PROJECTS_KEY = "recentProjects"
@@ -50,6 +50,18 @@ export async function loadLlmConfig(): Promise<LlmConfig | null> {
return (await store.get<LlmConfig>(LLM_CONFIG_KEY)) ?? null
}
+const SEARCH_API_KEY = "searchApiConfig"
+
+export async function saveSearchApiConfig(config: SearchApiConfig): Promise<void> {
+ const store = await getStore()
+ await store.set(SEARCH_API_KEY, config)
+}
+
+export async function loadSearchApiConfig(): Promise<SearchApiConfig | null> {
+ const store = await getStore()
+ return (await store.get<SearchApiConfig>(SEARCH_API_KEY)) ?? null
+}
+
export async function removeFromRecentProjects(
path: string
): Promise<void> {
diff --git a/src/lib/web-search.ts b/src/lib/web-search.ts
new file mode 100644
index 00000000..f128624d
--- /dev/null
+++ b/src/lib/web-search.ts
@@ -0,0 +1,57 @@
+import type { SearchApiConfig } from "@/stores/wiki-store"
+
+export interface WebSearchResult {
+ title: string
+ url: string
+ snippet: string
+ source: string
+}
+
+export async function webSearch(
+ query: string,
+ config: SearchApiConfig,
+ maxResults: number = 10,
+): Promise<WebSearchResult[]> {
+ if (config.provider === "none" || !config.apiKey) {
+ throw new Error("Web search not configured. Add a Tavily API key in Settings.")
+ }
+
+ switch (config.provider) {
+ case "tavily":
+ return tavilySearch(query, config.apiKey, maxResults)
+ default:
+ throw new Error(`Unknown search provider: ${config.provider}`)
+ }
+}
+
+async function tavilySearch(
+ query: string,
+ apiKey: string,
+ maxResults: number,
+): Promise<WebSearchResult[]> {
+ const response = await fetch("https://api.tavily.com/search", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ api_key: apiKey,
+ query,
+ max_results: maxResults,
+ search_depth: "advanced",
+ include_answer: false,
+ }),
+ })
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => "Unknown error")
+ throw new Error(`Tavily search failed (${response.status}): ${errorText}`)
+ }
+
+ const data = await response.json()
+
+ return (data.results ?? []).map((r: { title: string; url: string; content: string }) => ({
+ title: r.title ?? "Untitled",
+ url: r.url ?? "",
+ snippet: r.content?.slice(0, 300) ?? "",
+ source: new URL(r.url).hostname.replace("www.", ""),
+ }))
+}
diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.ts
index 8c1d06fc..3ee3d669 100644
--- a/src/stores/wiki-store.ts
+++ b/src/stores/wiki-store.ts
@@ -9,6 +9,11 @@ interface LlmConfig {
customEndpoint: string
}
+interface SearchApiConfig {
+ provider: "tavily" | "none"
+ apiKey: string
+}
+
interface WikiState {
project: WikiProject | null
fileTree: FileNode[]
@@ -17,6 +22,7 @@ interface WikiState {
chatExpanded: boolean
activeView: "wiki" | "sources" | "search" | "graph" | "lint" | "review" | "settings"
llmConfig: LlmConfig
+ searchApiConfig: SearchApiConfig
dataVersion: number
setProject: (project: WikiProject | null) => void
@@ -26,6 +32,7 @@ interface WikiState {
setChatExpanded: (expanded: boolean) => void
setActiveView: (view: WikiState["activeView"]) => void
setLlmConfig: (config: LlmConfig) => void
+ setSearchApiConfig: (config: SearchApiConfig) => void
bumpDataVersion: () => void
}
@@ -52,8 +59,14 @@ export const useWikiStore = create<WikiState>((set) => ({
setFileContent: (fileContent) => set({ fileContent }),
setChatExpanded: (chatExpanded) => set({ chatExpanded }),
setActiveView: (activeView) => set({ activeView }),
+ searchApiConfig: {
+ provider: "none",
+ apiKey: "",
+ },
+
setLlmConfig: (llmConfig) => set({ llmConfig }),
+ setSearchApiConfig: (searchApiConfig) => set({ searchApiConfig }),
bumpDataVersion: () => set((state) => ({ dataVersion: state.dataVersion + 1 })),
}))
-export type { WikiState, LlmConfig }
+export type { WikiState, LlmConfig, SearchApiConfig }