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
fix: validate deep research synthesis before saving
nash_suc33a895aa97d
diff --git a/src/components/layout/research-panel.tsx b/src/components/layout/research-panel.tsxindex 4285a12a..5b15407a 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,- FileSearch, FileText, Globe2, Send,+ FileSearch, FileText, Globe2, Send, RotateCcw,} from "lucide-react"import { Button } from "@/components/ui/button"import { useResearchStore, type ResearchTask } from "@/stores/research-store"@@ -46,6 +46,23 @@ export function ResearchPanel() {setInputValue("")}+ function handleRetryResearch(task: ResearchTask) {+ if (!project) return+ if (!hasConfiguredDeepResearchSources(searchApiConfig)) {+ window.alert(t("research.notConfigured"))+ return+ }+ queueResearch(+ normalizePath(project.path),+ task.topic,+ llmConfig,+ searchApiConfig,+ task.searchQueries,+ task.sourceReviewId,+ )+ removeTask(task.id)+ }+return (<div className="flex h-full flex-col"><div className="flex shrink-0 items-center justify-between border-b px-3 py-2">@@ -94,13 +111,18 @@ export function ResearchPanel() {) : (<div className="flex flex-col gap-1 p-2">{running.map((task) => (- <ResearchTaskCard key={task.id} task={task} onRemove={removeTask} />+ <ResearchTaskCard+ key={task.id}+ task={task}+ onRemove={removeTask}+ onRetry={handleRetryResearch}+ />))}{queued.map((task) => (- <ResearchTaskCard key={task.id} task={task} onRemove={removeTask} />+ <ResearchTaskCard key={task.id} task={task} onRemove={removeTask} onRetry={handleRetryResearch} />))}{done.map((task) => (- <ResearchTaskCard key={task.id} task={task} onRemove={removeTask} />+ <ResearchTaskCard key={task.id} task={task} onRemove={removeTask} onRetry={handleRetryResearch} />))}</div>)}@@ -218,7 +240,15 @@ function SynthesisBlock({ synthesis, isStreaming }: { synthesis: string; isStrea)}-function ResearchTaskCard({ task, onRemove }: { task: ResearchTask; onRemove: (id: string) => void }) {+function ResearchTaskCard({+ task,+ onRemove,+ onRetry,+}: {+ task: ResearchTask+ onRemove: (id: string) => void+ onRetry: (task: ResearchTask) => void+}) {const { t } = useTranslation()const [expanded, setExpanded] = useState(task.status === "synthesizing" || task.status === "searching"@@ -321,6 +351,17 @@ function ResearchTaskCard({ task, onRemove }: { task: ResearchTask; onRemove: (i{t("research.open")}</Button>)}+ {task.status === "error" && (+ <Button+ variant="outline"+ size="sm"+ className="h-6 text-[11px] gap-1"+ onClick={() => onRetry(task)}+ >+ <RotateCcw className="h-3 w-3" />+ {t("research.retry")}+ </Button>+ )}{(task.status === "done" || task.status === "error") && (<Buttonvariant="ghost"diff --git a/src/i18n/en.json b/src/i18n/en.jsonindex d3a19f9b..4df3968f 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -107,6 +107,7 @@"synthesis": "Synthesis","thinking": "Thinking","open": "Open",+ "retry": "Retry","remove": "Remove","status": {"queued": "Queued",diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex dc32ee25..62574220 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -107,6 +107,7 @@"synthesis": "综合结果","thinking": "思考中","open": "打开",+ "retry": "重试","remove": "移除","status": {"queued": "排队中",diff --git a/src/lib/deep-research.test.ts b/src/lib/deep-research.test.tsindex 897be829..e2b21f48 100644--- a/src/lib/deep-research.test.ts+++ b/src/lib/deep-research.test.ts@@ -1,5 +1,12 @@import { describe, expect, it, vi } from "vitest"-import { collectResearchSources, makeDeepResearchFileName, noResearchSourcesTaskPatch, resolveReviewForSavedResearch } from "./deep-research"+import {+ citedResearchSourceIndexes,+ collectResearchSources,+ makeDeepResearchFileName,+ noResearchSourcesTaskPatch,+ resolveReviewForSavedResearch,+ validateResearchSynthesis,+} from "./deep-research"import type { SearchApiConfig } from "@/stores/wiki-store"import type { WebSearchResult } from "./web-search"import { useWikiStore } from "@/stores/wiki-store"@@ -51,6 +58,39 @@ describe("makeDeepResearchFileName", () => {})})+describe("validateResearchSynthesis", () => {+ const substantiveChinese = [+ "解离是一类涉及记忆、身份、意识与环境感知连续性受扰的心理现象。[1]",+ "现有研究通常区分短暂的正常体验与造成显著痛苦或功能损害的临床表现。评估时需要结合持续时间、诱因、共病情况以及对日常生活的影响,不能仅凭单一症状下结论。[2]",+ "不同理论模型对其机制仍有分歧,因此研究结论需要结合样本来源、测量工具与临床背景解释。现有证据更适合支持分层评估,而不是把单项自评结果直接视为诊断。",+ ].join("\n\n")++ it("rejects empty, reasoning-only, and short output", () => {+ expect(validateResearchSynthesis("", 2).valid).toBe(false)+ expect(validateResearchSynthesis("<think>private reasoning only</think>", 2).valid).toBe(false)+ expect(validateResearchSynthesis("## 概述\n\n内容很短。[1]", 2).valid).toBe(false)+ })++ it("accepts substantive Unicode prose with a valid citation", () => {+ const result = validateResearchSynthesis(substantiveChinese, 2)++ expect(result.valid).toBe(true)+ expect(result.citedSourceIndexes).toEqual([1, 2])+ })++ it("rejects substantive output that cites no collected source", () => {+ const result = validateResearchSynthesis(substantiveChinese.replace(/\[\d+\]/g, ""), 2)++ expect(result.valid).toBe(false)+ expect(result.error).toContain("did not cite")+ })++ it("extracts valid citation groups and bounded ranges", () => {+ expect(citedResearchSourceIndexes("Evidence [3, 1] and comparison [4-5], ignore [0] [8].", 5))+ .toEqual([1, 3, 4, 5])+ })+})+describe("noResearchSourcesTaskPatch", () => {it("marks source failures as an error instead of completed", () => {expect(noResearchSourcesTaskPatch(["Firecrawl blocked this IP", "AnyTXT offline"])).toEqual({@@ -90,7 +130,7 @@ describe("review-linked research", () => {sourceReviewId: review.id,status: "done",webResults: [],- synthesis: "answer",+ synthesis: "This completed synthesis contains enough substantive analysis to explain the evidence, its limitations, and the conclusions that can reasonably be drawn. It also distinguishes established findings from open questions so the saved research is useful for later review.",savedPath: "wiki/queries/research-topic.md",error: null,createdAt: 1,@@ -157,6 +197,31 @@ describe("review-linked research", () => {)).toBe(false)expect(useReviewStore.getState().items[0].resolved).toBe(false)})++ it("does not resolve a saved task with incomplete synthesis", () => {+ useWikiStore.setState({ project: { id: "p1", name: "Project", path: "/project" } })+ useReviewStore.setState({ items: [review] })+ useResearchStore.setState({+ tasks: [{+ id: "research-1",+ topic: "topic",+ sourceReviewId: review.id,+ status: "done",+ webResults: [webResult],+ synthesis: "[1]",+ savedPath: "wiki/queries/research-topic.md",+ error: null,+ createdAt: 1,+ }],+ })++ expect(resolveReviewForSavedResearch(+ "/project",+ "research-1",+ "wiki/queries/research-topic.md",+ )).toBe(false)+ expect(useReviewStore.getState().items[0].resolved).toBe(false)+ })})describe("collectResearchSources", () => {diff --git a/src/lib/deep-research.ts b/src/lib/deep-research.tsindex e984d677..eb52eb8b 100644--- a/src/lib/deep-research.ts+++ b/src/lib/deep-research.ts@@ -12,6 +12,15 @@ import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"import { useReviewStore } from "@/stores/review-store"const MAX_RESEARCH_SOURCES = 20+const MIN_RESEARCH_CONTENT_CHARS = 120+const MIN_RESEARCH_BLOCK_CHARS = 40++export interface ResearchSynthesisValidation {+ valid: boolean+ cleaned: string+ citedSourceIndexes: number[]+ error: string | null+}interface ResearchSourceDeps {webSearch: typeof webSearch@@ -57,6 +66,84 @@ export function makeDeepResearchFileName(topic: string, now: Date = new Date()):return { fileName, date: currentWikiDate(now) }}+/**+ * Remove private reasoning before validating or persisting model output. Keep+ * this shared with the completion gate so content cannot pass validation and+ * then become empty after a different save-time cleanup.+ */+export function cleanResearchSynthesis(content: string): string {+ return content+ .replace(/<think(?:ing)?>\s*[\s\S]*?<\/think(?:ing)?>\s*/gi, "")+ .replace(/<think(?:ing)?>\s*[\s\S]*$/gi, "")+ .trim()+}++function meaningfulCharacterCount(content: string): number {+ // Unicode letters and numbers work across languages without relying on+ // localized section names or language-specific tokenization.+ return (content.match(/[\p{L}\p{N}]/gu) ?? []).length+}++/** Return one-based source indexes cited with Markdown-style [N] markers. */+export function citedResearchSourceIndexes(content: string, sourceCount: number): number[] {+ const cited = new Set<number>()+ for (const match of content.matchAll(/\[([\d,\-\s]+)\]/g)) {+ for (const part of match[1].split(",")) {+ const range = part.trim().match(/^(\d+)\s*-\s*(\d+)$/)+ if (range) {+ const start = Number(range[1])+ const end = Number(range[2])+ if (start <= end && end - start <= sourceCount) {+ for (let index = start; index <= end; index++) {+ if (index >= 1 && index <= sourceCount) cited.add(index)+ }+ }+ continue+ }+ const index = Number(part.trim())+ if (Number.isInteger(index) && index >= 1 && index <= sourceCount) cited.add(index)+ }+ }+ return [...cited].sort((a, b) => a - b)+}++/**+ * A completed research task must contain substantive prose and cite at least+ * one collected source. This is deliberately language-neutral: it evaluates+ * Unicode text structure rather than requiring named English/Chinese sections.+ */+export function validateResearchSynthesis(+ content: string,+ sourceCount: number,+): ResearchSynthesisValidation {+ const cleaned = cleanResearchSynthesis(content)+ const blocks = cleaned+ .split(/\n\s*\n/)+ .map((block) => block.replace(/^\s{0,3}#{1,6}\s+/gm, ""))+ .map(meaningfulCharacterCount)+ .filter((count) => count >= MIN_RESEARCH_BLOCK_CHARS)+ const meaningfulChars = meaningfulCharacterCount(cleaned)+ const citedSourceIndexes = citedResearchSourceIndexes(cleaned, sourceCount)++ if (meaningfulChars < MIN_RESEARCH_CONTENT_CHARS || blocks.length === 0) {+ return {+ valid: false,+ cleaned,+ citedSourceIndexes,+ error: "The research synthesis was empty or incomplete. Please retry.",+ }+ }+ if (sourceCount > 0 && citedSourceIndexes.length === 0) {+ return {+ valid: false,+ cleaned,+ citedSourceIndexes,+ error: "The research synthesis did not cite any collected sources. Please retry.",+ }+ }+ return { valid: true, cleaned, citedSourceIndexes, error: null }+}+/*** Queue a deep research task. Automatically starts processing if under concurrency limit.*/@@ -94,7 +181,8 @@ export function resolveReviewForSavedResearch(if (!task?.sourceReviewId ||task.status !== "done" ||- task.savedPath !== savedPath+ task.savedPath !== savedPath ||+ !validateResearchSynthesis(task.synthesis, task.webResults.length).valid) return falseconst review = useReviewStore.getState().items.find((item) => item.id === task.sourceReviewId)if (!review || review.resolved) return false@@ -307,22 +395,34 @@ async function executeResearch(}if (!isActiveProjectPath(pp)) return- // Step 3: Save to wiki- if (!updateTaskIfActive(pp, taskId, { status: "saving", synthesis: accumulated })) return+ // Step 3: Validate before writing. A successful stream can still contain+ // no assistant prose (for example, only a reasoning block). Such output+ // must remain retryable instead of creating a references-only artifact.+ const validation = validateResearchSynthesis(accumulated, webResults.length)+ if (!validation.valid) {+ if (!updateTaskIfActive(pp, taskId, {+ status: "error",+ synthesis: validation.cleaned,+ error: validation.error,+ })) return+ if (isActiveProjectPath(pp)) onTaskFinished(pp, llmConfig, searchConfig)+ return+ }+ if (!updateTaskIfActive(pp, taskId, { status: "saving", synthesis: validation.cleaned })) returnconst { fileName, date } = makeDeepResearchFileName(topic)const filePath = `${pp}/wiki/queries/${fileName}`- const references = webResults- .map((r, i) => `${i + 1}. [${r.title}](${r.url}) — ${r.source}`)+ // Persist only sources cited by the synthesis. Search providers can return+ // broad candidates; listing every candidate makes unused, off-topic hits+ // appear to support the final research.+ const references = validation.citedSourceIndexes+ .map((sourceIndex) => {+ const result = webResults[sourceIndex - 1]+ return `${sourceIndex}. [${result.title}](${result.url}) — ${result.source}`+ }).join("\n")- // Strip <think>/<thinking> blocks before saving- const cleanedSynthesis = accumulated- .replace(/<think(?:ing)?>\s*[\s\S]*?<\/think(?:ing)?>\s*/gi, "")- .replace(/<think(?:ing)?>\s*[\s\S]*$/gi, "") // unclosed thinking block- .trimStart()-const pageContent = ["---",`type: query`,@@ -334,7 +434,7 @@ async function executeResearch("",`# Research: ${topic}`,"",- cleanedSynthesis,+ validation.cleaned,"","## References","",