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
Release 0.4.14
nash_suff84ee9ec131
diff --git a/package-lock.json b/package-lock.jsonindex b58d644f..b92d1ab5 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "llm-wiki",- "version": "0.4.12",+ "version": "0.4.14","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "llm-wiki",- "version": "0.4.12",+ "version": "0.4.14","dependencies": {"@base-ui/react": "^1.3.0","@fontsource-variable/geist": "^5.2.8",diff --git a/package.json b/package.jsonindex b1e8d2ac..d2e6ce1b 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "llm-wiki","private": true,- "version": "0.4.13",+ "version": "0.4.14","type": "module","scripts": {"dev": "vite",diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 29fa2705..aa92f349 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -4420,7 +4420,7 @@ checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"[[package]]name = "llm-wiki"-version = "0.4.13"+version = "0.4.14"dependencies = ["arrow-array","arrow-schema",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex c773adb7..afa8a846 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "llm-wiki"-version = "0.4.13"+version = "0.4.14"description = "LLM Wiki - A personal knowledge base for LLM concepts"authors = []edition = "2021"diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex dc8ed0b3..8a896493 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "LLM Wiki",- "version": "0.4.13",+ "version": "0.4.14","identifier": "com.llmwiki.app","build": {"beforeDevCommand": "npm run dev",diff --git a/src/components/layout/icon-sidebar.tsx b/src/components/layout/icon-sidebar.tsxindex a95f7546..576a64f3 100644--- a/src/components/layout/icon-sidebar.tsx+++ b/src/components/layout/icon-sidebar.tsx@@ -113,7 +113,7 @@ export function IconSidebar({ onSwitchProject }: IconSidebarProps) {</span>)}</TooltipTrigger>- <TooltipContent side="right">Deep Research</TooltipContent>+ <TooltipContent side="right">{t("research.title")}</TooltipContent></Tooltip></div>{/* Bottom: daemon status + settings + switch project */}diff --git a/src/components/layout/research-panel.tsx b/src/components/layout/research-panel.tsxindex 5c8358ee..c453648f 100644--- a/src/components/layout/research-panel.tsx+++ b/src/components/layout/research-panel.tsx@@ -6,7 +6,7 @@ import rehypeKatex from "rehype-katex"import "katex/dist/katex.min.css"import {Search, Loader2, CheckCircle2, AlertCircle, ChevronRight, ChevronDown, X,- FileText, Send,+ FileSearch, FileText, Globe2, Send,} from "lucide-react"import { Button } from "@/components/ui/button"import { useResearchStore, type ResearchTask } from "@/stores/research-store"@@ -14,13 +14,15 @@ import { useWikiStore } from "@/stores/wiki-store"import { readFile } from "@/commands/fs"import { queueResearch } from "@/lib/deep-research"import { normalizePath } from "@/lib/path-utils"-import { hasConfiguredSearchProvider } from "@/lib/web-search"+import { hasConfiguredDeepResearchSources } from "@/lib/web-search"import { isImeComposing } from "@/lib/keyboard-utils"import { detectLanguage } from "@/lib/detect-language"import { getHtmlLang, getTextDirection } from "@/lib/language-metadata"import { MermaidDiagram, unwrapMermaidPre } from "@/components/mermaid-diagram"+import { useTranslation } from "react-i18next"export function ResearchPanel() {+ const { t } = useTranslation()const tasks = useResearchStore((s) => s.tasks)const removeTask = useResearchStore((s) => s.removeTask)const setPanelOpen = useResearchStore((s) => s.setPanelOpen)@@ -36,8 +38,8 @@ export function ResearchPanel() {function handleStartResearch() {const topic = inputValue.trim()if (!topic || !project) return- if (!hasConfiguredSearchProvider(searchApiConfig)) {- window.alert("Web Search not configured. Go to Settings → Web Search to configure a provider.")+ if (!hasConfiguredDeepResearchSources(searchApiConfig)) {+ window.alert(t("research.notConfigured"))return}queueResearch(normalizePath(project.path), topic, llmConfig, searchApiConfig)@@ -49,10 +51,10 @@ export function ResearchPanel() {<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>+ <span className="text-sm font-semibold">{t("research.title")}</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} active{queued.length > 0 ? `, ${queued.length} queued` : ""}+ {t("research.activeBadge", { running: running.length, queued: queued.length })}</span>)}</div>@@ -74,8 +76,8 @@ export function ResearchPanel() {if (isImeComposing(e)) returnif (e.key === "Enter") handleStartResearch()}}- placeholder="Enter a research topic..."className="flex-1 rounded border bg-background px-2 py-1 text-xs outline-none placeholder:text-muted-foreground focus:ring-1 focus:ring-ring"+ placeholder={t("research.inputPlaceholder")}/><Button size="icon" variant="ghost" className="h-7 w-7" onClick={handleStartResearch} disabled={!inputValue.trim()}><Send className="h-3.5 w-3.5" />@@ -86,8 +88,8 @@ export function ResearchPanel() {{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>- <p>Enter a topic above or click "Deep Research" in Review</p>+ <p>{t("research.emptyTitle")}</p>+ <p>{t("research.emptyHint")}</p></div>) : (<div className="flex flex-col gap-1 p-2">@@ -216,6 +218,7 @@ function SynthesisBlock({ synthesis, isStreaming }: { synthesis: string; isStrea}function ResearchTaskCard({ task, onRemove }: { task: ResearchTask; onRemove: (id: string) => void }) {+ const { t } = useTranslation()const [expanded, setExpanded] = useState(task.status === "synthesizing" || task.status === "searching")@@ -233,12 +236,12 @@ function ResearchTaskCard({ task, onRemove }: { task: ResearchTask; onRemove: (i}[task.status]const statusText = {- queued: "Queued",- searching: "Searching web...",- synthesizing: "Synthesizing...",- saving: "Saving to wiki...",- done: task.savedPath ? "Saved" : "Done",- error: "Failed",+ queued: t("research.status.queued"),+ searching: t("research.status.searching"),+ synthesizing: t("research.status.synthesizing"),+ saving: t("research.status.saving"),+ done: task.savedPath ? t("research.status.saved") : t("research.status.done"),+ error: t("research.status.failed"),}[task.status]async function handleOpenSaved() {@@ -282,18 +285,26 @@ function ResearchTaskCard({ task, onRemove }: { task: ResearchTask; onRemove: (i{task.webResults.length > 0 && (<div className="mb-2"><div className="mb-1 font-medium text-muted-foreground">- Sources ({task.webResults.length})+ {t("research.sourcesCount", { count: 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>+ {task.webResults.map((r, i) => {+ const isAnyTxt = r.source.toLowerCase() === "anytxt"+ const SourceIcon = isAnyTxt ? FileSearch : Globe2+ return (+ <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>+ <SourceIcon+ className={`mt-0.5 h-3.5 w-3.5 shrink-0 ${isAnyTxt ? "text-amber-600" : "text-blue-600"}`}+ aria-label={isAnyTxt ? t("research.anyTxtSource") : t("research.webSource")}+ />+ <div className="min-w-0 flex-1">+ <div className="truncate font-medium">{r.title}</div>+ <div className="truncate text-muted-foreground">{isAnyTxt ? "AnyTXT" : r.source}</div>+ </div></div>- </div>- ))}+ )+ })}</div></div>)}@@ -308,7 +319,7 @@ function ResearchTaskCard({ task, onRemove }: { task: ResearchTask; onRemove: (i{task.savedPath && (<Button variant="outline" size="sm" className="h-6 text-[11px] gap-1" onClick={handleOpenSaved}><FileText className="h-3 w-3" />- Open+ {t("research.open")}</Button>)}{(task.status === "done" || task.status === "error") && (@@ -319,7 +330,7 @@ function ResearchTaskCard({ task, onRemove }: { task: ResearchTask; onRemove: (ionClick={() => onRemove(task.id)}><X className="h-3 w-3" />- Remove+ {t("research.remove")}</Button>)}</div>diff --git a/src/components/review/review-view.tsx b/src/components/review/review-view.tsxindex b5ec72eb..be20af9b 100644--- a/src/components/review/review-view.tsx+++ b/src/components/review/review-view.tsx@@ -16,7 +16,8 @@ import { useReviewStore, type ReviewItem } from "@/stores/review-store"import { useWikiStore } from "@/stores/wiki-store"import { writeFile, readFile, listDirectory, deleteFile } from "@/commands/fs"import { normalizePath } from "@/lib/path-utils"-import { hasConfiguredSearchProvider } from "@/lib/web-search"+import { hasConfiguredDeepResearchSources } from "@/lib/web-search"+import { useTranslation } from "react-i18next"const typeConfig: Record<ReviewItem["type"], { icon: typeof AlertTriangle; label: string; color: string }> = {contradiction: { icon: AlertTriangle, label: "Contradiction", color: "text-amber-500" },@@ -27,6 +28,7 @@ const typeConfig: Record<ReviewItem["type"], { icon: typeof AlertTriangle; label}export function ReviewView() {+ const { t } = useTranslation()const items = useReviewStore((s) => s.items)const resolveItem = useReviewStore((s) => s.resolveItem)const dismissItem = useReviewStore((s) => s.dismissItem)@@ -40,8 +42,8 @@ export function ReviewView() {// Deep Research — must be checked FIRST before any fuzzy matchingif (action === "__deep_research__" && project) {const searchConfig = useWikiStore.getState().searchApiConfig- if (!hasConfiguredSearchProvider(searchConfig)) {- window.alert("Web Search not configured. Go to Settings → Web Search to configure a provider first.")+ if (!hasConfiguredDeepResearchSources(searchConfig)) {+ window.alert(t("research.notConfigured"))return}if (item) {@@ -144,8 +146,8 @@ export function ReviewView() {} else if (actionLooksLikeResearch(action) && project) {// Actions with "research" trigger deep research, not just page creationconst searchConfig = useWikiStore.getState().searchApiConfig- if (!hasConfiguredSearchProvider(searchConfig)) {- // No search API — fall through to create a page instead+ if (!hasConfiguredDeepResearchSources(searchConfig)) {+ // No research source — fall through to create a page insteadif (item) {handleResolve(id, "__create_page__:" + action)}@@ -230,7 +232,7 @@ export function ReviewView() {<div className="flex h-full flex-col"><div className="flex items-center justify-between border-b px-4 py-3"><h2 className="text-sm font-semibold">- Review+ {t("review.title")}{pending.length > 0 && (<span className="ml-2 rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground">{pending.length}@@ -240,7 +242,7 @@ export function ReviewView() {{resolved.length > 0 && (<Button variant="ghost" size="sm" onClick={clearResolved} className="text-xs"><Trash2 className="mr-1 h-3 w-3" />- Clear resolved+ {t("review.clearResolved")}</Button>)}</div>@@ -249,7 +251,7 @@ export function ReviewView() {{items.length === 0 ? (<div className="flex flex-col items-center justify-center gap-2 p-8 text-center text-sm text-muted-foreground"><CheckCircle2 className="h-8 w-8 text-muted-foreground/30" />- <p>All clear — nothing to review</p>+ <p>{t("review.allClear")}</p></div>) : (<div className="flex flex-col gap-2 p-3">@@ -263,7 +265,7 @@ export function ReviewView() {))}{resolved.length > 0 && pending.length > 0 && (<div className="my-2 text-center text-xs text-muted-foreground">- — Resolved —+ {t("review.resolvedDivider")}</div>)}{resolved.map((item) => (@@ -290,6 +292,7 @@ function ReviewCard({onResolve: (id: string, action: string) => voidonDismiss: (id: string) => void}) {+ const { t } = useTranslation()const config = typeConfig[item.type]const Icon = config.icon@@ -329,7 +332,7 @@ function ReviewCard({className="h-7 text-xs gap-1"onClick={() => onResolve(item.id, "__deep_research__")}>- 🔍 Deep Research+ 🔍 {t("research.title")}</Button>)}{item.options.map((opt) => (diff --git a/src/components/settings/sections/web-search-section.tsx b/src/components/settings/sections/web-search-section.tsxindex 53f8f8cf..f78d7157 100644--- a/src/components/settings/sections/web-search-section.tsx+++ b/src/components/settings/sections/web-search-section.tsx@@ -5,10 +5,13 @@ import { Input } from "@/components/ui/input"import { Label } from "@/components/ui/label"import {useWikiStore,+ type AnyTxtConfig,+ type DeepResearchSource,type SearchApiConfig,type SearchProvider,type SearchProviderOverride,} from "@/stores/wiki-store"+import { normalizeAnyTxtConfig } from "@/lib/anytxt-search"import {SEARXNG_CATEGORY_OPTIONS,SERPAPI_ENGINE_OPTIONS,@@ -51,6 +54,9 @@ export function WebSearchSection() {const searchApiConfig = useWikiStore((s) => s.searchApiConfig)const setSearchApiConfig = useWikiStore((s) => s.setSearchApiConfig)const resolvedConfig = resolveSearchConfig(searchApiConfig)+ const anyTxtConfig = normalizeAnyTxtConfig(resolvedConfig.anyTxt)+ const anyTxtFilterDir = resolvedConfig.anyTxt?.filterDir ?? ""+ const showBroadAnyTxtWarning = isBroadAnyTxtFilterDir(anyTxtFilterDir)const [expanded, setExpanded] = useState<Record<string, boolean>>({})const [savedId, setSavedId] = useState<string | null>(null)@@ -78,16 +84,127 @@ export function WebSearchSection() {persist(resolveSearchConfig({ ...resolvedConfig, provider: nextProvider })).catch(() => {})}+ function updateDeepResearchSource(deepResearchSource: DeepResearchSource) {+ persist(resolveSearchConfig({ ...resolvedConfig, deepResearchSource })).catch(() => {})+ }++ function updateAnyTxt(patch: AnyTxtConfig) {+ const next = resolveSearchConfig({+ ...resolvedConfig,+ anyTxt: {+ ...anyTxtConfig,+ ...patch,+ },+ })+ persist(next).catch(() => {})+ setSavedId("anytxt")+ setTimeout(() => setSavedId((cur) => (cur === "anytxt" ? null : cur)), 1500)+ }+return (<div className="space-y-4"><div>- <h2 className="text-xl font-semibold">{t("settings.sections.webSearch.title")} (Deep Research)</h2>+ <h2 className="text-xl font-semibold">{t("settings.sections.webSearch.title")}</h2><p className="mt-1 text-sm text-muted-foreground">{t("settings.sections.webSearch.description")}</p></div>+ <div className="space-y-2 rounded-lg border p-3">+ <div>+ <Label>{t("settings.sections.webSearch.deepResearchSources")}</Label>+ <p className="mt-1 text-xs text-muted-foreground">+ {t("settings.sections.webSearch.deepResearchSourcesHint")}+ </p>+ </div>+ <div className="grid gap-2 sm:grid-cols-3">+ {([+ ["web", t("settings.sections.webSearch.sourceWeb")],+ ["anytxt", t("settings.sections.webSearch.sourceAnyTxt")],+ ["both", t("settings.sections.webSearch.sourceBoth")],+ ] as const).map(([value, label]) => (+ <button+ key={value}+ type="button"+ onClick={() => updateDeepResearchSource(value)}+ className={`rounded-md border px-3 py-2 text-left text-sm transition-colors ${+ (resolvedConfig.deepResearchSource ?? "web") === value+ ? "border-primary bg-primary text-primary-foreground"+ : "border-border hover:bg-accent"+ }`}+ >+ {label}+ </button>+ ))}+ </div>+ </div>++ <div className="space-y-3 rounded-lg border p-3">+ <div className="flex items-start justify-between gap-3">+ <div>+ <Label>{t("settings.sections.webSearch.anyTxtTitle")}</Label>+ <p className="mt-1 text-xs text-muted-foreground">+ {t("settings.sections.webSearch.anyTxtDescription")}+ </p>+ </div>+ {savedId === "anytxt" && (+ <span className="shrink-0 text-[10px] text-emerald-600">+ {t("settings.sections.webSearch.savedBadge")}+ </span>+ )}+ </div>+ <div className="grid gap-3 md:grid-cols-2">+ <div className="space-y-2">+ <Label>{t("settings.sections.webSearch.anyTxtEndpoint")}</Label>+ <Input+ value={anyTxtConfig.endpoint}+ onChange={(e) => updateAnyTxt({ endpoint: e.target.value })}+ placeholder="http://127.0.0.1:9920"+ />+ </div>+ <div className="space-y-2">+ <Label>{t("settings.sections.webSearch.anyTxtLimit")}</Label>+ <Input+ type="number"+ min={1}+ max={100}+ value={anyTxtConfig.limit}+ onChange={(e) => {+ const value = e.target.value.trim()+ updateAnyTxt({ limit: value ? Number(value) : undefined })+ }}+ placeholder="20"+ />+ </div>+ <div className="space-y-2">+ <Label>{t("settings.sections.webSearch.anyTxtFilterDir")}</Label>+ <Input+ value={anyTxtFilterDir}+ onChange={(e) => updateAnyTxt({ filterDir: e.target.value })}+ placeholder={t("settings.sections.webSearch.anyTxtFilterDirPlaceholder")}+ />+ {showBroadAnyTxtWarning && (+ <p className="text-xs text-destructive">+ {t("settings.sections.webSearch.anyTxtBroadDirWarning")}+ </p>+ )}+ </div>+ <div className="space-y-2">+ <Label>{t("settings.sections.webSearch.anyTxtFilterExt")}</Label>+ <Input+ value={anyTxtConfig.filterExt}+ onChange={(e) => updateAnyTxt({ filterExt: e.target.value })}+ placeholder="*"+ />+ </div>+ </div>+ <p className="text-xs text-muted-foreground">+ {t("settings.sections.webSearch.anyTxtHint")}+ </p>+ </div>+<div className="space-y-2">+ <Label>{t("settings.sections.webSearch.webProviders")}</Label>{SEARCH_PROVIDERS.map((provider) => {const override = resolvedConfig.providerConfigs?.[provider.id]const isActive = resolvedConfig.provider === provider.id@@ -212,6 +329,15 @@ export function WebSearchSection() {)}+function isBroadAnyTxtFilterDir(value: string): boolean {+ const trimmed = value.trim().replace(/\\/g, "/")+ if (!trimmed) return false+ if (trimmed === "/" || trimmed === "~") return true+ if (/^\/\/[^/]+\/[^/]+\/?$/.test(trimmed)) return true+ if (/^[A-Za-z]:\/?$/.test(trimmed)) return true+ return /^\/(?:Users|home|Volumes|mnt|media)?\/?$/.test(trimmed)+}+function SearXngCategoryPicker({value,onChange,diff --git a/src/i18n/en.json b/src/i18n/en.jsonindex 4cb3e028..3f737d4d 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -29,6 +29,28 @@"knowledge": "Knowledge","files": "Files"},+ "research": {+ "title": "Deep Research",+ "notConfigured": "Deep Research sources are not configured. Go to Settings → Deep Research to configure Web Search or AnyTXT.",+ "activeBadge": "{{running}} active{{queued, plural, =0 {} other {, {{queued}} queued}}}",+ "inputPlaceholder": "Enter a research topic...",+ "emptyTitle": "No research tasks yet",+ "emptyHint": "Enter a topic above or click Deep Research in Review",+ "sourcesCount": "Sources ({{count}})",+ "anyTxtSource": "AnyTXT source",+ "webSource": "Web source",+ "open": "Open",+ "remove": "Remove",+ "status": {+ "queued": "Queued",+ "searching": "Searching sources...",+ "synthesizing": "Synthesizing...",+ "saving": "Saving to wiki...",+ "saved": "Saved",+ "done": "Done",+ "failed": "Failed"+ }+ },"project": {"createTitle": "Create New Wiki Project","name": "Project Name",@@ -155,7 +177,8 @@"review": {"title": "Review","clearResolved": "Clear resolved",- "allClear": "All clear — nothing to review"+ "allClear": "All clear — nothing to review",+ "resolvedDivider": "— Resolved —"},"settings": {"title": "Settings",@@ -180,7 +203,7 @@"llm": "LLM Models","embedding": "Embeddings","multimodal": "Image Captioning",- "webSearch": "Web Search",+ "webSearch": "Deep Research","network": "Network","sourceWatch": "Source Watch","scheduledImport": "Scheduled Import",@@ -313,8 +336,23 @@"costPoint4": "Prefer a local vision model (Qwen2.5-VL via LM Studio / Ollama) for bulk ingestion; reserve hosted vision APIs for one-off high-stakes documents."},"webSearch": {- "title": "Web Search",- "description": "Used by Deep Research to pull fresh external context.",+ "title": "Deep Research",+ "description": "Choose where Deep Research gathers context before synthesis.",+ "deepResearchSources": "Research sources",+ "deepResearchSourcesHint": "Web Search uses the selected online provider. AnyTXT searches local indexed files through ATGUI.exe on this machine.",+ "sourceWeb": "Web Search",+ "sourceAnyTxt": "AnyTXT",+ "sourceBoth": "Both",+ "webProviders": "Web Search providers",+ "anyTxtTitle": "AnyTXT local file search",+ "anyTxtDescription": "Use AnyTXT's local JSON-RPC API as a Deep Research source. Keep ATGUI.exe running before starting research.",+ "anyTxtEndpoint": "AnyTXT endpoint",+ "anyTxtFilterDir": "Search folder",+ "anyTxtFilterDirPlaceholder": "Leave blank for AnyTXT's default scope; on Windows, set a drive or folder if needed",+ "anyTxtFilterExt": "Extension filter",+ "anyTxtLimit": "Max local results",+ "anyTxtHint": "AnyTXT pattern text is sent directly to AnyTXT, so its native search syntax applies. AnyTXT API is local beta software; respect AnyTXT's usage terms.",+ "anyTxtBroadDirWarning": "This folder looks very broad. Deep Research may send matching local file fragments, including sensitive content, to the selected LLM.","expand": "Expand","collapse": "Collapse","activate": "Activate",diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex 39b2146e..54f1593c 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -29,6 +29,28 @@"knowledge": "知识库","files": "文件"},+ "research": {+ "title": "深度研究",+ "notConfigured": "深度研究信息来源尚未配置。请到设置 → 深度研究中配置网页搜索或 AnyTXT。",+ "activeBadge": "{{running}} 个运行中{{queued, plural, =0 {} other {,{{queued}} 个排队中}}}",+ "inputPlaceholder": "输入研究主题...",+ "emptyTitle": "还没有研究任务",+ "emptyHint": "在上方输入主题,或在待审阅中点击深度研究",+ "sourcesCount": "来源({{count}})",+ "anyTxtSource": "AnyTXT 来源",+ "webSource": "网页来源",+ "open": "打开",+ "remove": "移除",+ "status": {+ "queued": "排队中",+ "searching": "正在搜索来源...",+ "synthesizing": "正在综合...",+ "saving": "正在保存到 Wiki...",+ "saved": "已保存",+ "done": "已完成",+ "failed": "失败"+ }+ },"project": {"createTitle": "新建 Wiki 项目","name": "项目名称",@@ -155,7 +177,8 @@"review": {"title": "待审阅","clearResolved": "清除已解决",- "allClear": "一切正常,无需审阅"+ "allClear": "一切正常,无需审阅",+ "resolvedDivider": "— 已解决 —"},"settings": {"title": "设置",@@ -180,7 +203,7 @@"llm": "LLM 模型","embedding": "向量嵌入","multimodal": "图片描述",- "webSearch": "网页搜索",+ "webSearch": "深度研究","network": "网络","sourceWatch": "资料文件夹监控","scheduledImport": "定时导入",@@ -313,8 +336,23 @@"costPoint4": "批量 ingest 推荐用本地视觉模型(LM Studio / Ollama 跑 Qwen2.5-VL);托管视觉 API 留给少量高价值文档。"},"webSearch": {- "title": "网页搜索",- "description": "Deep Research 会用它拉取最新的外部上下文。",+ "title": "深度研究",+ "description": "选择 Deep Research 在综合分析前从哪些来源收集上下文。",+ "deepResearchSources": "研究信息来源",+ "deepResearchSourcesHint": "网页搜索使用当前选中的在线搜索 Provider。AnyTXT 会通过本机 ATGUI.exe 的本地索引搜索文件内容。",+ "sourceWeb": "网页搜索",+ "sourceAnyTxt": "AnyTXT",+ "sourceBoth": "两者都用",+ "webProviders": "网页搜索 Provider",+ "anyTxtTitle": "AnyTXT 本地文件搜索",+ "anyTxtDescription": "把 AnyTXT 的本地 JSON-RPC API 作为 Deep Research 的信息来源。开始研究前请保持 ATGUI.exe 运行。",+ "anyTxtEndpoint": "AnyTXT 端点",+ "anyTxtFilterDir": "搜索文件夹",+ "anyTxtFilterDirPlaceholder": "留空则使用 AnyTXT 默认范围;Windows 如需其他盘符请指定盘符或文件夹",+ "anyTxtFilterExt": "扩展名过滤",+ "anyTxtLimit": "最多本地结果数",+ "anyTxtHint": "AnyTXT pattern 会直接传给 AnyTXT,因此会使用 AnyTXT 自己的搜索语法。AnyTXT API 是本地 Beta 能力,请遵守 AnyTXT 的使用条款。",+ "anyTxtBroadDirWarning": "这个目录范围很大。Deep Research 可能会把匹配到的本地文件片段(包括敏感内容)发送给当前选择的 LLM。","expand": "展开","collapse": "收起","activate": "启用",diff --git a/src/lib/anytxt-search.test.ts b/src/lib/anytxt-search.test.tsnew file mode 100644index 00000000..694dec68--- /dev/null+++ b/src/lib/anytxt-search.test.ts@@ -0,0 +1,258 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { anyTxtSearch, normalizeAnyTxtConfig } from "./anytxt-search"++const fetchMock = vi.fn<typeof fetch>()++function jsonResponse(body: unknown, init?: ResponseInit): Response {+ return new Response(JSON.stringify(body), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ ...init,+ })+}++describe("anyTxtSearch", () => {+ beforeEach(() => {+ fetchMock.mockReset()+ vi.stubGlobal("fetch", fetchMock)+ })++ it("calls AnyTXT GetResult and fetches fragments for matching files", async () => {+ fetchMock+ .mockResolvedValueOnce(jsonResponse({+ jsonrpc: "2.0",+ id: 1,+ result: {+ output: {+ items: [+ {+ fid: "9223736511748752040",+ path: "C:\\docs\\alpha.pdf",+ name: "alpha.pdf",+ },+ ],+ },+ },+ }))+ .mockResolvedValueOnce(jsonResponse({+ jsonrpc: "2.0",+ id: 2,+ result: {+ output: {+ text: "matching fragment text",+ },+ },+ }))++ const out = await anyTxtSearch(+ "alpha",+ {+ endpoint: "127.0.0.1:9920",+ filterDir: "C:\\docs",+ filterExt: "*.pdf",+ limit: 10,+ },+ 5,+ )++ expect(fetchMock).toHaveBeenCalledTimes(2)+ const [url, init] = fetchMock.mock.calls[0]+ expect(url).toBe("http://127.0.0.1:9920")+ expect(JSON.parse(String(init?.body))).toMatchObject({+ jsonrpc: "2.0",+ method: "ATRpcServer.Searcher.V1.GetResult",+ params: {+ input: {+ pattern: "alpha",+ filterDir: "C:\\docs",+ filterExt: "*.pdf",+ limit: "5",+ },+ },+ })+ expect(JSON.parse(String(fetchMock.mock.calls[1][1]?.body))).toMatchObject({+ method: "ATRpcServer.Searcher.V1.GetFragment",+ params: { input: { fid: "9223736511748752040", pattern: "alpha" } },+ })+ expect(out).toEqual([+ {+ title: "alpha.pdf",+ url: "file:///C:/docs/alpha.pdf",+ snippet: "matching fragment text",+ source: "AnyTXT",+ },+ ])+ })++ it("normalizes tolerant AnyTXT response shapes without fragments", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({+ result: {+ output: [+ {+ full_path: "/Users/me/docs/note.md",+ hitText: "local note match",+ },+ ],+ },+ }))++ const out = await anyTxtSearch("note", { endpoint: "http://127.0.0.1:9920" }, 3, "/project")++ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(out[0]).toMatchObject({+ title: "note.md",+ url: "file:///Users/me/docs/note.md",+ snippet: "local note match",+ source: "AnyTXT",+ })+ })++ it("normalizes AnyTXT data.output.files rows using the returned field list", async () => {+ fetchMock+ .mockResolvedValueOnce(jsonResponse({+ id: 1,+ jsonrpc: "2.0",+ result: {+ data: {+ output: {+ count: 1,+ field: ["fid", "lastModify", "size", "file"],+ files: [["9223736511748752040", 1711588801, 1200, "D:\\docs\\煤矿安全.md"]],+ },+ },+ errno: 0,+ },+ }))+ .mockResolvedValueOnce(jsonResponse({+ result: {+ data: {+ output: {+ text: "煤矿安全 fragment",+ },+ },+ },+ }))++ const out = await anyTxtSearch("煤矿", { endpoint: "http://127.0.0.1:9920" }, 5)++ expect(out).toEqual([+ {+ title: "煤矿安全.md",+ url: "file:///D:/docs/%E7%85%A4%E7%9F%BF%E5%AE%89%E5%85%A8.md",+ snippet: "煤矿安全 fragment",+ source: "AnyTXT",+ },+ ])+ })++ it("normalizes UNC network paths to file URLs", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({+ result: {+ data: {+ output: {+ field: ["fid", "file"],+ files: [["unc-1", "\\\\nas\\share\\研究报告.md"]],+ },+ },+ },+ }))++ const out = await anyTxtSearch("研究", { endpoint: "http://127.0.0.1:9920" }, 5)++ expect(out[0]).toMatchObject({+ title: "研究报告.md",+ url: "file://nas/share/%E7%A0%94%E7%A9%B6%E6%8A%A5%E5%91%8A.md",+ source: "AnyTXT",+ })+ })++ it("uses the Unix root for blank filterDir on macOS/Linux projects", () => {+ expect(normalizeAnyTxtConfig({ filterDir: "" }, "/Users/me/wiki").filterDir)+ .toBe("/")+ })++ it("leaves blank filterDir unset for Windows projects", () => {+ expect(normalizeAnyTxtConfig({ filterDir: "" }, "C:/Users/me/wiki").filterDir)+ .toBe("")+ })++ it("sends the Unix root as filterDir when folder filtering is blank on macOS/Linux", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ result: { items: [] } }))++ await anyTxtSearch("alpha", { endpoint: "http://127.0.0.1:9920", filterDir: "" }, 5, "/Users/me/wiki")++ const body = JSON.parse(String(fetchMock.mock.calls[0][1]?.body))+ expect(body.params.input.filterDir).toBe("/")+ })++ it("normalizes endpoints and clamps limits", () => {+ expect(normalizeAnyTxtConfig({ endpoint: "localhost:9920" }).endpoint).toBe("http://localhost:9920")+ expect(normalizeAnyTxtConfig({ endpoint: "https://anytxt.local/" }).endpoint).toBe("https://anytxt.local/")+ expect(normalizeAnyTxtConfig({ limit: -1 }).limit).toBe(1)+ expect(normalizeAnyTxtConfig({ limit: 1000 }).limit).toBe(100)+ })++ it("returns no results for blank queries without calling AnyTXT", async () => {+ const out = await anyTxtSearch(" ", { endpoint: "http://127.0.0.1:9920" })++ expect(fetchMock).not.toHaveBeenCalled()+ expect(out).toEqual([])+ })++ it("surfaces JSON-RPC errors", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({+ jsonrpc: "2.0",+ id: 1,+ error: { message: "bad pattern" },+ }))++ await expect(anyTxtSearch("alpha", { endpoint: "http://127.0.0.1:9920" }))+ .rejects.toThrow("AnyTXT error: bad pattern")+ })++ it("surfaces HTTP failures with status codes", async () => {+ fetchMock.mockResolvedValueOnce(new Response("oops", { status: 500 }))++ await expect(anyTxtSearch("alpha", { endpoint: "http://127.0.0.1:9920" }))+ .rejects.toThrow("AnyTXT request failed (500): oops")+ })++ it("falls back to item snippets when fragment lookup fails", async () => {+ fetchMock+ .mockResolvedValueOnce(jsonResponse({+ result: {+ items: [+ { fid: "1", path: "/tmp/a.md", snippet: "fallback snippet" },+ ],+ },+ }))+ .mockResolvedValueOnce(new Response("fragment failed", { status: 500 }))++ const out = await anyTxtSearch("alpha", { endpoint: "http://127.0.0.1:9920" })++ expect(out[0].snippet).toBe("fallback snippet")+ })++ it("filters blank AnyTXT result items", async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({+ result: {+ items: [+ {},+ { path: "/tmp/valid.md", snippet: "valid" },+ ],+ },+ }))++ const out = await anyTxtSearch("alpha", { endpoint: "http://127.0.0.1:9920" })++ expect(out).toHaveLength(1)+ expect(out[0].url).toBe("file:///tmp/valid.md")+ })++ it("turns fetch network failures into AnyTXT connection guidance", async () => {+ fetchMock.mockRejectedValueOnce(new TypeError("Failed to fetch"))++ await expect(anyTxtSearch("alpha", { endpoint: "http://127.0.0.1:9920" }))+ .rejects.toThrow("Check that ATGUI.exe is running")+ })+})diff --git a/src/lib/anytxt-search.ts b/src/lib/anytxt-search.tsnew file mode 100644index 00000000..0eb5541c--- /dev/null+++ b/src/lib/anytxt-search.ts@@ -0,0 +1,285 @@+import type { AnyTxtConfig } from "@/stores/wiki-store"+import { getHttpFetch, isFetchNetworkError } from "@/lib/tauri-fetch"+import { normalizePath } from "@/lib/path-utils"+import type { WebSearchResult } from "./web-search"++export const DEFAULT_ANYTXT_ENDPOINT = "http://127.0.0.1:9920"+export const DEFAULT_ANYTXT_FILTER_EXT = "*"+export const DEFAULT_ANYTXT_LIMIT = 20+const ANYTXT_LAST_MODIFY_END = 2147483647 // AnyTXT docs use signed 32-bit Unix timestamps.+let nextRpcId = 1++interface AnyTxtRpcResponse {+ result?: unknown+ error?: string | { message?: string; code?: number }+}++interface AnyTxtItem {+ fid: string+ path: string+ title: string+ snippet: string+}++export function normalizeAnyTxtConfig(config?: AnyTxtConfig, _projectPath?: string): Required<AnyTxtConfig> {+ return {+ endpoint: normalizeAnyTxtEndpoint(config?.endpoint),+ filterDir: config?.filterDir?.trim() || defaultAnyTxtFilterDir(_projectPath),+ filterExt: config?.filterExt?.trim() || DEFAULT_ANYTXT_FILTER_EXT,+ limit: clampAnyTxtLimit(config?.limit),+ }+}++export function hasConfiguredAnyTxt(config?: AnyTxtConfig): boolean {+ return Boolean(normalizeAnyTxtEndpoint(config?.endpoint).trim())+}++export async function anyTxtSearch(+ query: string,+ config?: AnyTxtConfig,+ maxResults: number = DEFAULT_ANYTXT_LIMIT,+ projectPath?: string,+): Promise<WebSearchResult[]> {+ if (!query.trim()) return []+ const resolved = normalizeAnyTxtConfig(config, projectPath)+ const limit = Math.min(clampAnyTxtLimit(maxResults), resolved.limit)+ const response = await callAnyTxtRpc(resolved.endpoint, "ATRpcServer.Searcher.V1.GetResult", buildAnyTxtSearchInput({+ pattern: query,+ filterDir: resolved.filterDir,+ filterExt: resolved.filterExt,+ lastModifyBegin: 0,+ lastModifyEnd: ANYTXT_LAST_MODIFY_END,+ // AnyTXT's documented GetResult shape expects limit as a string while+ // offset/order/timestamps are numbers.+ limit: String(limit),+ offset: 0,+ order: 0,+ }))++ const items = extractAnyTxtItems(response).slice(0, limit)+ const out: WebSearchResult[] = []+ for (const item of items) {+ const fragment = item.fid+ ? await getAnyTxtFragment(resolved.endpoint, item.fid, query).catch(() => "")+ : ""+ out.push({+ title: item.title,+ url: fileUrlForPath(item.path) || (item.fid ? `anytxt://${item.fid}` : ""),+ snippet: trimFragment(fragment || item.snippet || item.path),+ source: "AnyTXT",+ })+ }+ return out.filter((item) => item.url || item.snippet)+}++async function getAnyTxtFragment(endpoint: string, fid: string, pattern: string): Promise<string> {+ const response = await callAnyTxtRpc(endpoint, "ATRpcServer.Searcher.V1.GetFragment", {+ fid,+ pattern,+ })+ return extractFragmentText(response)+}++async function callAnyTxtRpc(endpoint: string, method: string, input: Record<string, unknown>): Promise<unknown> {+ const httpFetch = await getHttpFetch()+ let response: Response+ try {+ response = await httpFetch(endpoint, {+ method: "POST",+ headers: {+ Accept: "application/json",+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ id: nextRpcId++,+ jsonrpc: "2.0",+ method,+ params: { input },+ }),+ })+ } catch (err) {+ if (isFetchNetworkError(err)) {+ throw new Error("Network error reaching AnyTXT. Check that ATGUI.exe is running and the JSON-RPC API is listening.")+ }+ throw err+ }++ if (!response.ok) {+ const errorText = await response.text().catch(() => "Unknown error")+ throw new Error(`AnyTXT request failed (${response.status}): ${errorText}`)+ }++ const data = (await response.json()) as AnyTxtRpcResponse+ if (data.error) {+ const message = typeof data.error === "string" ? data.error : data.error.message ?? JSON.stringify(data.error)+ throw new Error(`AnyTXT error: ${message}`)+ }+ return data.result+}++function extractAnyTxtItems(result: unknown): AnyTxtItem[] {+ const rawItems = firstArray(+ result,+ getPath(result, ["output"]),+ getPath(result, ["output", "items"]),+ getPath(result, ["output", "results"]),+ getPath(result, ["output", "list"]),+ getPath(result, ["output", "files"]),+ getPath(result, ["output", "data"]),+ getPath(result, ["output", "value"]),+ getPath(result, ["data", "output", "files"]),+ getPath(result, ["data", "output", "items"]),+ getPath(result, ["data", "output", "results"]),+ getPath(result, ["data", "output", "list"]),+ getPath(result, ["data", "files"]),+ getPath(result, ["data", "items"]),+ getPath(result, ["data", "results"]),+ getPath(result, ["data", "list"]),+ getPath(result, ["items"]),+ getPath(result, ["results"]),+ getPath(result, ["list"]),+ getPath(result, ["files"]),+ getPath(result, ["data"]),+ getPath(result, ["value"]),+ )+ const fields = firstStringArray(+ getPath(result, ["field"]),+ getPath(result, ["output", "field"]),+ getPath(result, ["data", "output", "field"]),+ getPath(result, ["data", "field"]),+ )++ return rawItems.map((item) => normalizeAnyTxtItem(item, fields)).filter((item): item is AnyTxtItem => item !== null)+}++function normalizeAnyTxtItem(item: unknown, fields: string[] = []): AnyTxtItem | null {+ if (!item || (typeof item !== "object" && !Array.isArray(item))) return null+ const record = Array.isArray(item) ? recordFromFields(fields, item) : item as Record<string, unknown>+ const fid = stringField(record, "fid", "id", "fileId", "file_id")+ const path = normalizePath(stringField(record, "path", "file", "filePath", "file_path", "fullPath", "full_path", "filename", "fileName", "name"))+ const title = stringField(record, "title", "name", "fileName", "filename") || basename(path) || fid || "AnyTXT result"+ const snippet = stringField(record, "snippet", "fragment", "content", "contents", "text", "summary", "highlight", "hitText")+ if (!fid && !path && !snippet) return null+ return { fid, path, title, snippet }+}++function extractFragmentText(result: unknown): string {+ if (typeof result === "string") return result+ if (Array.isArray(result)) return result.map(extractFragmentText).filter(Boolean).join("\n\n")+ if (!result || typeof result !== "object") return ""+ const record = result as Record<string, unknown>+ return stringField(record, "text", "fragment", "content", "snippet", "html")+ || extractFragmentText(record.output)+ || extractFragmentText(record.result)+ || extractFragmentText(record.data)+ || extractFragmentText(getPath(record, ["data", "output"]))+ || extractFragmentText(record.fragments)+ || extractFragmentText(record.items)+ || extractFragmentText(record.list)+}++function buildAnyTxtSearchInput(input: {+ pattern: string+ filterDir: string+ filterExt: string+ lastModifyBegin: number+ lastModifyEnd: number+ limit: string+ offset: number+ order: number+}): Record<string, unknown> {+ const out: Record<string, unknown> = {+ pattern: input.pattern,+ filterExt: input.filterExt,+ lastModifyBegin: input.lastModifyBegin,+ lastModifyEnd: input.lastModifyEnd,+ limit: input.limit,+ offset: input.offset,+ order: input.order,+ }+ if (input.filterDir.trim()) {+ out.filterDir = input.filterDir+ }+ return out+}++function firstArray(...values: unknown[]): unknown[] {+ for (const value of values) {+ if (Array.isArray(value)) return value+ }+ return []+}++function firstStringArray(...values: unknown[]): string[] {+ for (const value of values) {+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) {+ return value+ }+ }+ return []+}++function recordFromFields(fields: string[], row: unknown[]): Record<string, unknown> {+ const record: Record<string, unknown> = {}+ fields.forEach((field, index) => {+ record[field] = row[index]+ })+ return record+}++function getPath(value: unknown, path: string[]): unknown {+ let current = value+ for (const key of path) {+ if (!current || typeof current !== "object") return undefined+ current = (current as Record<string, unknown>)[key]+ }+ return current+}++function stringField(record: Record<string, unknown>, ...keys: string[]): string {+ for (const key of keys) {+ const value = record[key]+ if (typeof value === "string" && value.trim()) return value.trim()+ if (typeof value === "number" && Number.isFinite(value)) return String(value)+ }+ return ""+}++function normalizeAnyTxtEndpoint(endpoint?: string): string {+ const trimmed = endpoint?.trim() || DEFAULT_ANYTXT_ENDPOINT+ if (/^https?:\/\//i.test(trimmed)) return trimmed+ return `http://${trimmed}`+}++function clampAnyTxtLimit(limit: unknown): number {+ const parsed = typeof limit === "number" ? limit : Number(limit)+ if (!Number.isFinite(parsed)) return DEFAULT_ANYTXT_LIMIT+ return Math.min(100, Math.max(1, Math.floor(parsed)))+}++function defaultAnyTxtFilterDir(projectPath?: string): string {+ const pp = projectPath ? normalizePath(projectPath) : ""+ // On the macOS/Linux AnyTXT API, omitting filterDir has been observed to+ // fall back to "C:" instead of "all indexed files". Use "/" as the explicit+ // unrestricted root for Unix-style projects. Keep Windows blank because+ // AnyTXT cannot represent "all drive letters" with one filterDir.+ return pp.startsWith("/") ? "/" : ""+}++function basename(path: string): string {+ return path.split(/[\\/]/).filter(Boolean).pop() ?? ""+}++function fileUrlForPath(path: string): string {+ if (!path) return ""+ const normalized = normalizePath(path)+ if (/^[a-z]+:\/\//i.test(normalized)) return normalized+ if (normalized.startsWith("//")) return `file:${encodeURI(normalized)}`+ if (/^[A-Za-z]:\//.test(normalized)) return `file:///${encodeURI(normalized)}`+ if (normalized.startsWith("/")) return `file://${encodeURI(normalized)}`+ return normalized+}++function trimFragment(text: string): string {+ return text.replace(/\s+/g, " ").trim().slice(0, 1200)+}diff --git a/src/lib/changelog.ts b/src/lib/changelog.tsindex 571e8bc2..7f567b8b 100644--- a/src/lib/changelog.ts+++ b/src/lib/changelog.ts@@ -25,6 +25,22 @@ export interface ChangelogEntry {}export const CHANGELOG: ChangelogEntry[] = [+ {+ version: "0.4.14",+ date: "2026-05-26",+ highlights: {+ en: [+ "Deep Research can now use AnyTXT local file search alongside web search, with configurable research sources.",+ "Improved long-document ingestion with more resilient chunked analysis and follow-up research suggestions.",+ "Fixed provider compatibility and Windows path handling issues.",+ ],+ zh: [+ "Deep Research 现在可结合 AnyTXT 本地文件搜索和网页搜索,并支持配置研究信息来源。",+ "改进长文档导入:分块分析更稳,并优化补充研究建议生成。",+ "修复 Provider 兼容性和 Windows 路径处理相关问题。",+ ],+ },+ },{version: "0.4.13",date: "2026-05-24",diff --git a/src/lib/deep-research.test.ts b/src/lib/deep-research.test.tsnew file mode 100644index 00000000..84076f42--- /dev/null+++ b/src/lib/deep-research.test.ts@@ -0,0 +1,235 @@+import { describe, expect, it, vi } from "vitest"+import { collectResearchSources, parseAnyTxtQueryRewrite } from "./deep-research"+import type { SearchApiConfig } from "@/stores/wiki-store"+import type { WebSearchResult } from "./web-search"++const webResult: WebSearchResult = {+ title: "Web",+ url: "https://example.com/web",+ snippet: "web snippet",+ source: "example.com",+}++const localResult: WebSearchResult = {+ title: "Local",+ url: "file:///C:/docs/local.md",+ snippet: "local snippet",+ source: "AnyTXT",+}++function config(patch: Partial<SearchApiConfig>): SearchApiConfig {+ return {+ provider: "none",+ apiKey: "",+ ...patch,+ }+}++describe("collectResearchSources", () => {+ it("uses only Web Search when source mode is web", async () => {+ const webSearch = vi.fn().mockResolvedValue([webResult])+ const anyTxtSearch = vi.fn().mockResolvedValue([localResult])++ const out = await collectResearchSources(+ ["alpha"],+ config({ deepResearchSource: "web", provider: "tavily", apiKey: "tvly" }),+ "/project",+ { webSearch, anyTxtSearch },+ )++ expect(webSearch).toHaveBeenCalledTimes(1)+ expect(anyTxtSearch).not.toHaveBeenCalled()+ expect(out.results).toEqual([webResult])+ })++ it("uses only AnyTXT when source mode is anytxt", async () => {+ const webSearch = vi.fn().mockResolvedValue([webResult])+ const anyTxtSearch = vi.fn().mockResolvedValue([localResult])++ const out = await collectResearchSources(+ ["alpha"],+ config({+ deepResearchSource: "anytxt",+ provider: "tavily",+ apiKey: "tvly",+ anyTxt: { endpoint: "http://127.0.0.1:9920" },+ }),+ "/project",+ { webSearch, anyTxtSearch },+ )++ expect(webSearch).not.toHaveBeenCalled()+ expect(anyTxtSearch).toHaveBeenCalledTimes(1)+ expect(out.results).toEqual([localResult])+ })++ it("uses both sources concurrently and deduplicates by URL", async () => {+ const duplicate = { ...localResult, url: webResult.url }+ const webSearch = vi.fn().mockResolvedValue([webResult])+ const anyTxtSearch = vi.fn().mockResolvedValue([duplicate, localResult])++ const out = await collectResearchSources(+ ["alpha"],+ config({+ deepResearchSource: "both",+ provider: "tavily",+ apiKey: "tvly",+ anyTxt: { endpoint: "http://127.0.0.1:9920" },+ }),+ "/project",+ { webSearch, anyTxtSearch },+ )++ expect(webSearch).toHaveBeenCalledTimes(1)+ expect(anyTxtSearch).toHaveBeenCalledTimes(1)+ expect(out.results).toEqual([webResult, localResult])+ })++ it("keeps web results when AnyTXT fails and exposes the source error", async () => {+ const webSearch = vi.fn().mockResolvedValue([webResult])+ const anyTxtSearch = vi.fn().mockRejectedValue(new Error("Check that ATGUI.exe is running"))++ const out = await collectResearchSources(+ ["alpha"],+ config({+ deepResearchSource: "both",+ provider: "tavily",+ apiKey: "tvly",+ anyTxt: { endpoint: "http://127.0.0.1:9920" },+ }),+ "/project",+ { webSearch, anyTxtSearch },+ )++ expect(out.results).toEqual([webResult])+ expect(out.errors).toEqual(["Check that ATGUI.exe is running"])+ })++ it("skips Web Search in both mode when no web provider is configured", async () => {+ const webSearch = vi.fn().mockResolvedValue([webResult])+ const anyTxtSearch = vi.fn().mockResolvedValue([localResult])++ const out = await collectResearchSources(+ ["alpha"],+ config({+ deepResearchSource: "both",+ provider: "none",+ anyTxt: { endpoint: "http://127.0.0.1:9920" },+ }),+ "/project",+ { webSearch, anyTxtSearch },+ )++ expect(webSearch).not.toHaveBeenCalled()+ expect(anyTxtSearch).toHaveBeenCalledTimes(1)+ expect(out.results).toEqual([localResult])+ })++ it("returns no results for blank queries", async () => {+ const webSearch = vi.fn().mockResolvedValue([webResult])+ const anyTxtSearch = vi.fn().mockResolvedValue([localResult])++ const out = await collectResearchSources(+ [" ", ""],+ config({ deepResearchSource: "both", provider: "tavily", apiKey: "tvly" }),+ "/project",+ { webSearch, anyTxtSearch },+ )++ expect(webSearch).not.toHaveBeenCalled()+ expect(anyTxtSearch).not.toHaveBeenCalled()+ expect(out.results).toEqual([])+ })++ it("uses original and rewritten AnyTXT queries without changing Web Search queries", async () => {+ const webSearch = vi.fn().mockResolvedValue([webResult])+ const anyTxtSearch = vi.fn().mockResolvedValue([localResult])++ await collectResearchSources(+ ["how did the membrane bioreactor project handle winter ammonia spikes?"],+ config({+ deepResearchSource: "both",+ provider: "tavily",+ apiKey: "tvly",+ anyTxt: { endpoint: "http://127.0.0.1:9920" },+ }),+ "/project",+ { webSearch, anyTxtSearch },+ { anyTxtQueries: ["membrane bioreactor winter ammonia"] },+ )++ expect(webSearch).toHaveBeenCalledWith(+ "how did the membrane bioreactor project handle winter ammonia spikes?",+ expect.any(Object),+ 5,+ )+ expect(anyTxtSearch).toHaveBeenNthCalledWith(+ 1,+ "membrane bioreactor winter ammonia",+ expect.any(Object),+ 5,+ "/project",+ )+ expect(anyTxtSearch).toHaveBeenNthCalledWith(+ 2,+ "how did the membrane bioreactor project handle winter ammonia spikes?",+ expect.any(Object),+ 5,+ "/project",+ )+ })++ it("prefers rewritten AnyTXT queries when original queries would fill the cap", async () => {+ const webSearch = vi.fn().mockResolvedValue([])+ const anyTxtSearch = vi.fn().mockResolvedValue([])++ await collectResearchSources(+ ["q1 long natural language", "q2 long natural language", "q3 long natural language"],+ config({+ deepResearchSource: "anytxt",+ anyTxt: { endpoint: "http://127.0.0.1:9920" },+ }),+ "/project",+ { webSearch, anyTxtSearch },+ { anyTxtQueries: ["kw1", "kw2", "kw3"] },+ )++ expect(anyTxtSearch.mock.calls.map((call) => call[0])).toEqual(["kw1", "kw2", "kw3"])+ })++ it("logs once when research sources are capped", async () => {+ const infoSpy = vi.spyOn(console, "info").mockImplementation(() => {})+ const webSearch = vi.fn().mockResolvedValue(+ Array.from({ length: 25 }, (_, index) => ({+ title: `Result ${index}`,+ url: `https://example.com/${index}`,+ snippet: "snippet",+ source: "example.com",+ })),+ )+ const anyTxtSearch = vi.fn().mockResolvedValue([])++ const out = await collectResearchSources(+ ["alpha", "beta"],+ config({ deepResearchSource: "web", provider: "tavily", apiKey: "tvly" }),+ "/project",+ { webSearch, anyTxtSearch },+ )++ expect(out.results).toHaveLength(20)+ expect(infoSpy).toHaveBeenCalledTimes(1)+ infoSpy.mockRestore()+ })+})++describe("parseAnyTxtQueryRewrite", () => {+ it("parses JSON-array query rewrites and deduplicates them", () => {+ expect(parseAnyTxtQueryRewrite('```json\n["MBR ammonia", "winter nitrification", "MBR ammonia"]\n```'))+ .toEqual(["MBR ammonia", "winter nitrification"])+ })++ it("falls back to line-based query parsing", () => {+ expect(parseAnyTxtQueryRewrite("QUERY: 反硝化除磷\n- 污水处理 冬季 氨氮\n3. MBR nitrification"))+ .toEqual(["反硝化除磷", "污水处理 冬季 氨氮", "MBR nitrification"])+ })+})diff --git a/src/lib/deep-research.ts b/src/lib/deep-research.tsindex d850ea50..70957526 100644--- a/src/lib/deep-research.ts+++ b/src/lib/deep-research.ts@@ -1,4 +1,5 @@-import { webSearch } from "./web-search"+import { anyTxtSearch } from "./anytxt-search"+import { hasConfiguredSearchProvider, resolveSearchConfig, webSearch } from "./web-search"import { streamChat } from "./llm-client"import { autoIngest } from "./ingest"import { writeFile, readFile, listDirectory } from "@/commands/fs"@@ -7,6 +8,22 @@ import { useResearchStore } from "@/stores/research-store"import { normalizePath } from "@/lib/path-utils"import { buildLanguageDirective } from "@/lib/output-language"+const MAX_RESEARCH_SOURCES = 20++interface ResearchSourceDeps {+ webSearch: typeof webSearch+ anyTxtSearch: typeof anyTxtSearch+}++interface CollectResearchSourceOptions {+ anyTxtQueries?: string[]+}++interface ResearchSourceCollection {+ results: import("./web-search").WebSearchResult[]+ errors: string[]+}+/*** Queue a deep research task. Automatically starts processing if under concurrency limit.*/@@ -32,6 +49,151 @@ export function queueResearch(return taskId}+export async function collectResearchSources(+ queries: string[],+ searchConfig: SearchApiConfig,+ projectPath: string,+ deps: ResearchSourceDeps = { webSearch, anyTxtSearch },+ options: CollectResearchSourceOptions = {},+): Promise<ResearchSourceCollection> {+ const resolvedSearchConfig = resolveSearchConfig(searchConfig)+ const sourceMode = resolvedSearchConfig.deepResearchSource ?? "web"+ const useWeb = sourceMode === "web" || sourceMode === "both"+ const useAnyTxt = hasAnyTxtSource(resolvedSearchConfig)+ const webConfigured = hasConfiguredSearchProvider(resolvedSearchConfig)+ const allResults: import("./web-search").WebSearchResult[] = []+ const errors: string[] = []+ const seenUrls = new Set<string>()+ let cappedWarned = false++ function addResults(results: import("./web-search").WebSearchResult[]) {+ for (const r of results) {+ if (allResults.length >= MAX_RESEARCH_SOURCES) {+ if (!cappedWarned) {+ console.info(`[DeepResearch] capped at ${MAX_RESEARCH_SOURCES} research sources; later results were truncated.`)+ cappedWarned = true+ }+ return+ }+ const key = (r.url || `${r.source}:${r.title}:${r.snippet}`).toLowerCase()+ if (!seenUrls.has(key)) {+ seenUrls.add(key)+ allResults.push(r)+ }+ }+ }++ const webQueries = queries.map((q) => q.trim()).filter(Boolean)+ const anyTxtQueries = uniqueQueries([+ ...(options.anyTxtQueries ?? []),+ ...queries,+ ])+ const maxQueryCount = Math.max(webQueries.length, anyTxtQueries.length)++ for (let i = 0; i < maxQueryCount; i++) {+ const webQuery = webQueries[i]+ const anyTxtQuery = anyTxtQueries[i]+ const calls: Array<Promise<{ results: import("./web-search").WebSearchResult[] }>> = []+ if (useWeb && webConfigured && webQuery) {+ calls.push(deps.webSearch(webQuery, resolvedSearchConfig, 5).then((results) => ({ results })))+ }+ if (useAnyTxt && anyTxtQuery) {+ calls.push(deps.anyTxtSearch(anyTxtQuery, resolvedSearchConfig.anyTxt, 5, projectPath).then((results) => ({ results })))+ }+ const settled = await Promise.allSettled(calls)+ for (const item of settled) {+ if (item.status === "fulfilled") {+ addResults(item.value.results)+ } else {+ const message = item.reason instanceof Error ? item.reason.message : String(item.reason)+ errors.push(message)+ console.warn("[DeepResearch] source search failed:", message)+ }+ }+ }++ return { results: allResults, errors }+}++function hasAnyTxtSource(searchConfig: SearchApiConfig): boolean {+ const sourceMode = searchConfig.deepResearchSource ?? "web"+ return sourceMode === "anytxt" || sourceMode === "both"+}++export async function rewriteAnyTxtQueries(queries: string[], llmConfig: LlmConfig): Promise<string[]> {+ const cleanQueries = queries.map((q) => q.trim()).filter(Boolean)+ if (cleanQueries.length === 0) return []++ const prompt = [+ "Convert the user's research topics into concise AnyTXT local file search keyword queries.",+ "",+ "AnyTXT searches local indexed file text. Natural-language questions often fail, so produce keyword-style searches.",+ "Rules:",+ "- Return ONLY a JSON array of strings.",+ "- Produce 1-3 search queries total.",+ "- Keep proper nouns, filenames, technical terms, dates, abbreviations, and non-English terms.",+ "- Prefer compact keyword phrases over full questions.",+ "- Do not add explanations, markdown, comments, or code fences.",+ "",+ "User research topics:",+ JSON.stringify(cleanQueries, null, 2),+ ].join("\n")++ let output = ""+ await streamChat(+ llmConfig,+ [{ role: "user", content: prompt }],+ {+ onToken: (token) => { output += token },+ onDone: () => {},+ onError: () => {},+ },+ undefined,+ { temperature: 0.1, max_tokens: 512, reasoning: { mode: "off" } },+ )++ const rewritten = parseAnyTxtQueryRewrite(output)+ return rewritten.length > 0 ? rewritten : cleanQueries+}++export function parseAnyTxtQueryRewrite(output: string): string[] {+ const stripped = output+ .replace(/```(?:json)?/gi, "")+ .replace(/```/g, "")+ .trim()++ const jsonMatch = stripped.match(/\[[\s\S]*\]/)+ if (jsonMatch) {+ try {+ const parsed = JSON.parse(jsonMatch[0])+ if (Array.isArray(parsed)) {+ return uniqueQueries(parsed.map((item) => typeof item === "string" ? item : ""))+ }+ } catch {+ // fall through to line parser+ }+ }++ return uniqueQueries(stripped+ .split(/\r?\n/)+ .map((line) => line.replace(/^\s*(?:[-*]|\d+[.)]|QUERY:)\s*/i, "").trim()))+}++function uniqueQueries(queries: string[]): string[] {+ const seen = new Set<string>()+ const out: string[] = []+ for (const raw of queries) {+ const query = raw.replace(/^["']|["']$/g, "").trim()+ if (!query) continue+ const key = query.toLowerCase()+ if (seen.has(key)) continue+ seen.add(key)+ out.push(query)+ if (out.length >= 3) break+ }+ return out+}+/*** Process queued tasks up to maxConcurrent limit.*/@@ -62,36 +224,39 @@ async function executeResearch(const store = useResearchStore.getState()try {- // Step 1: Web search — use multiple queries if available, merge and deduplicate+ // Step 1: gather research sources — use multiple queries if available,+ // merge Web Search and local AnyTXT results, then deduplicate.store.updateTask(taskId, { status: "searching" })const task = useResearchStore.getState().tasks.find((t) => t.id === taskId)const queries = task?.searchQueries && task.searchQueries.length > 0? task.searchQueries: [topic]-- const allResults: import("./web-search").WebSearchResult[] = []- const seenUrls = new Set<string>()-- for (const query of queries) {+ let anyTxtQueries: string[] | undefined+ if (hasAnyTxtSource(resolveSearchConfig(searchConfig))) {try {- const results = await webSearch(query, searchConfig, 5)- for (const r of results) {- if (!seenUrls.has(r.url)) {- seenUrls.add(r.url)- allResults.push(r)- }- }- } catch {- // continue with other queries+ anyTxtQueries = await rewriteAnyTxtQueries(queries, llmConfig)+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err)+ console.warn("[DeepResearch] AnyTXT query rewrite failed, using original queries:", message)}}+ const { results: allResults, errors: sourceErrors } = await collectResearchSources(+ queries,+ searchConfig,+ pp,+ { webSearch, anyTxtSearch },+ { anyTxtQueries },+ )const webResults = allResultsstore.updateTask(taskId, { webResults })if (webResults.length === 0) {- store.updateTask(taskId, { status: "done", synthesis: "No web results found." })+ store.updateTask(taskId, {+ status: "done",+ synthesis: sourceErrors.length > 0 ? sourceErrors.join("\n") : "No research sources found.",+ })onTaskFinished(pp, llmConfig, searchConfig)return}@@ -112,7 +277,7 @@ async function executeResearch(}const systemPrompt = [- "You are a research assistant. Synthesize the web search results into a comprehensive wiki page.",+ "You are a research assistant. Synthesize the collected research sources into a comprehensive wiki page.","",buildLanguageDirective(topic),"",@@ -124,7 +289,7 @@ async function executeResearch("","## Writing Rules","- Organize into clear sections with headings",- "- Cite web sources using [N] notation",+ "- Cite sources using [N] notation","- Note contradictions or gaps","- Suggest additional sources worth finding","- Neutral, encyclopedic tone",@@ -138,7 +303,7 @@ async function executeResearch(llmConfig,[{ role: "system", content: systemPrompt },- { role: "user", content: `Research topic: **${topic}**\n\n## Web Search Results\n\n${searchContext}\n\nSynthesize into a wiki page.` },+ { role: "user", content: `Research topic: **${topic}**\n\n## Research Sources\n\n${searchContext}\n\nSynthesize into a wiki page.` },],{onToken: (token) => {diff --git a/src/lib/web-search.test.ts b/src/lib/web-search.test.tsindex 96ffec64..c66d03a5 100644--- a/src/lib/web-search.test.ts+++ b/src/lib/web-search.test.ts@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from "vitest"-import { hasConfiguredSearchProvider, resolveSearchConfig, webSearch } from "./web-search"+import { hasConfiguredDeepResearchSources, hasConfiguredSearchProvider, resolveSearchConfig, webSearch } from "./web-search"const fetchMock = vi.fn<typeof fetch>()@@ -212,6 +212,27 @@ describe("webSearch", () => {expect(resolved.ollamaUrl).toBe("https://ollama.com")})+ it("tracks Deep Research source configuration independently from the active web provider", () => {+ expect(hasConfiguredDeepResearchSources({+ provider: "none",+ apiKey: "",+ deepResearchSource: "anytxt",+ anyTxt: { endpoint: "http://127.0.0.1:9920" },+ })).toBe(true)++ expect(hasConfiguredDeepResearchSources({+ provider: "none",+ apiKey: "",+ deepResearchSource: "web",+ anyTxt: { endpoint: "http://127.0.0.1:9920" },+ })).toBe(false)++ expect(resolveSearchConfig({+ provider: "none",+ apiKey: "",+ }).deepResearchSource).toBe("web")+ })+it("calls the Ollama Web Search API with Bearer auth", async () => {fetchMock.mockResolvedValueOnce(jsonResponse({results: [diff --git a/src/lib/web-search.ts b/src/lib/web-search.tsindex 0edf93c1..8761b0b7 100644--- a/src/lib/web-search.ts+++ b/src/lib/web-search.ts@@ -6,6 +6,7 @@ import type {SerpApiEngine,} from "@/stores/wiki-store"import { getHttpFetch, isFetchNetworkError } from "@/lib/tauri-fetch"+import { hasConfiguredAnyTxt, normalizeAnyTxtConfig } from "@/lib/anytxt-search"export interface WebSearchResult {title: string@@ -85,6 +86,8 @@ export function resolveSearchConfig(config: SearchApiConfig): SearchApiConfig {searXngCategories: config.searXngCategories ?? providerConfigs.searxng?.searXngCategories ?? ["general"],ollamaUrl: providerConfigs.ollama?.ollamaUrl ?? "https://ollama.com",providerConfigs,+ deepResearchSource: config.deepResearchSource ?? "web",+ anyTxt: normalizeAnyTxtConfig(config.anyTxt),}}@@ -97,6 +100,8 @@ export function resolveSearchConfig(config: SearchApiConfig): SearchApiConfig {searXngCategories: activeOverride?.searXngCategories ?? config.searXngCategories ?? ["general"],ollamaUrl: resolvedOllamaUrl,providerConfigs,+ deepResearchSource: config.deepResearchSource ?? "web",+ anyTxt: normalizeAnyTxtConfig(config.anyTxt),}}@@ -112,6 +117,17 @@ export function hasConfiguredSearchProvider(config: SearchApiConfig): boolean {return Boolean(resolved.apiKey?.trim())}+export function hasConfiguredDeepResearchSources(config: SearchApiConfig): boolean {+ const resolved = resolveSearchConfig(config)+ const source = resolved.deepResearchSource ?? "web"+ const webConfigured = hasConfiguredSearchProvider(resolved)+ const anyTxtConfigured = hasConfiguredAnyTxt(resolved.anyTxt)++ if (source === "web") return webConfigured+ if (source === "anytxt") return anyTxtConfigured+ return webConfigured || anyTxtConfigured+}+export async function webSearch(query: string,config: SearchApiConfig,diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.tsindex 4303a18c..1cfc97df 100644--- a/src/stores/wiki-store.ts+++ b/src/stores/wiki-store.ts@@ -31,6 +31,7 @@ interface LlmConfig {}export type SearchProvider = "tavily" | "serpapi" | "searxng" | "ollama" | "none"+export type DeepResearchSource = "web" | "anytxt" | "both"export type SerpApiEngine =| "google"| "google_news"@@ -65,6 +66,13 @@ export interface SearchProviderOverride {export type SearchProviderConfigs = Partial<Record<Exclude<SearchProvider, "none">, SearchProviderOverride>>+export interface AnyTxtConfig {+ endpoint?: string+ filterDir?: string+ filterExt?: string+ limit?: number+}+interface SearchApiConfig {provider: SearchProviderapiKey: string@@ -73,6 +81,8 @@ interface SearchApiConfig {searXngCategories?: SearXngCategory[]ollamaUrl?: stringproviderConfigs?: SearchProviderConfigs+ deepResearchSource?: DeepResearchSource+ anyTxt?: AnyTxtConfig}interface EmbeddingConfig {@@ -337,6 +347,13 @@ export const useWikiStore = create<WikiState>((set) => ({searXngUrl: "",searXngCategories: ["general"],providerConfigs: {},+ deepResearchSource: "web",+ anyTxt: {+ endpoint: "http://127.0.0.1:9920",+ filterDir: "",+ filterExt: "*",+ limit: 20,+ },},embeddingConfig: {