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: v0.6.10
nash_su889789c3218e
diff --git a/package-lock.json b/package-lock.jsonindex dbd034b6..07eed0d6 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "llm-wiki",- "version": "0.6.9",+ "version": "0.6.10","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "llm-wiki",- "version": "0.6.9",+ "version": "0.6.10","dependencies": {"@base-ui/react": "^1.3.0","@fontsource-variable/geist": "^5.2.8",diff --git a/package.json b/package.jsonindex 06cfd9cb..566152e3 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "llm-wiki","private": true,- "version": "0.6.9",+ "version": "0.6.10","type": "module","scripts": {"dev": "vite",diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 58e28195..c1f6f1a0 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -4753,7 +4753,7 @@ checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"[[package]]name = "llm-wiki"-version = "0.6.9"+version = "0.6.10"dependencies = ["anydoc","arrow-array",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex edaa0374..04d539ab 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "llm-wiki"-version = "0.6.9"+version = "0.6.10"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 dd8be1f0..95c2415e 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.6.9",+ "version": "0.6.10","identifier": "com.llmwiki.app","build": {"beforeDevCommand": "npm run dev",diff --git a/src/components/layout/research-panel.tsx b/src/components/layout/research-panel.tsxindex 6bf14f44..c8acc9c5 100644--- a/src/components/layout/research-panel.tsx+++ b/src/components/layout/research-panel.tsx@@ -9,7 +9,7 @@ import {FileSearch, FileText, Globe2, Send, RotateCcw,} from "lucide-react"import { Button } from "@/components/ui/button"-import { useResearchStore, type ResearchTask } from "@/stores/research-store"+import { hasActiveResearchRerun, useResearchStore, type ResearchTask } from "@/stores/research-store"import { useWikiStore } from "@/stores/wiki-store"import { readFile } from "@/commands/fs"import { queueResearch, queueResearchBatch } from "@/lib/deep-research"@@ -22,13 +22,6 @@ import { MermaidDiagram, unwrapMermaidPre } from "@/components/mermaid-diagram"import { useTranslation } from "react-i18next"import { useAppDialog } from "@/stores/app-dialog-store"-function hasActiveRerun(tasks: ResearchTask[], taskId: string): boolean {- return tasks.some((task) =>- task.rerunOfTaskId === taskId &&- ["queued", "searching", "synthesizing", "saving"].includes(task.status),- )-}-export function ResearchPanel() {const { t } = useTranslation()const appDialog = useAppDialog()@@ -57,6 +50,7 @@ export function ResearchPanel() {async function handleRetryResearch(task: ResearchTask) {if (!project) return+ if (hasActiveResearchRerun(useResearchStore.getState().tasks, task.id)) returnif (!hasConfiguredDeepResearchSources(searchApiConfig)) {await appDialog.alert({ message: t("research.notConfigured") })return@@ -127,14 +121,14 @@ export function ResearchPanel() {task={task}onRemove={removeTask}onRetry={handleRetryResearch}- rerunPending={hasActiveRerun(tasks, task.id)}+ rerunPending={hasActiveResearchRerun(tasks, task.id)}/>))}{queued.map((task) => (- <ResearchTaskCard key={task.id} task={task} onRemove={removeTask} onRetry={handleRetryResearch} rerunPending={hasActiveRerun(tasks, task.id)} />+ <ResearchTaskCard key={task.id} task={task} onRemove={removeTask} onRetry={handleRetryResearch} rerunPending={hasActiveResearchRerun(tasks, task.id)} />))}{done.map((task) => (- <ResearchTaskCard key={task.id} task={task} onRemove={removeTask} onRetry={handleRetryResearch} rerunPending={hasActiveRerun(tasks, task.id)} />+ <ResearchTaskCard key={task.id} task={task} onRemove={removeTask} onRetry={handleRetryResearch} rerunPending={hasActiveResearchRerun(tasks, task.id)} />))}</div>)}diff --git a/src/components/review/review-view.tsx b/src/components/review/review-view.tsxindex 7060b0a4..08a8fa30 100644--- a/src/components/review/review-view.tsx+++ b/src/components/review/review-view.tsx@@ -347,7 +347,13 @@ export function ReviewView() {)const handleBatchResearch = useCallback(async () => {- if (!project || batchResearchItems.length === 0) return+ if (!project) return+ const eligibleItems = selectedResearchReviews(+ items,+ selectedReviewIds,+ useResearchStore.getState().tasks,+ )+ if (eligibleItems.length === 0) returnconst state = useWikiStore.getState()if (!hasConfiguredDeepResearchSources(state.searchApiConfig)) {await appDialog.alert({ message: t("research.notConfigured") })@@ -355,7 +361,7 @@ export function ReviewView() {}queueResearchBatch(normalizePath(project.path),- batchResearchItems.map((item) => ({+ eligibleItems.map((item) => ({topic: reviewResearchTopic(item),searchQueries: item.searchQueries,sourceReviewId: item.id,@@ -363,9 +369,9 @@ export function ReviewView() {state.llmConfig,state.searchApiConfig,)- const queuedIds = new Set(batchResearchItems.map((item) => item.id))+ const queuedIds = new Set(eligibleItems.map((item) => item.id))setSelectedReviewIds((current) => new Set([...current].filter((id) => !queuedIds.has(id))))- }, [appDialog, batchResearchItems, project, t])+ }, [appDialog, items, project, selectedReviewIds, t])return (<div className="flex h-full flex-col">diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsxindex 42e4ebd0..cd0c3054 100644--- a/src/components/sources/sources-view.tsx+++ b/src/components/sources/sources-view.tsx@@ -32,6 +32,7 @@ import { getQueue, type IngestTask } from "@/lib/ingest-queue"const SOURCE_TREE_INITIAL_ROWS = 160const SOURCE_TREE_LOAD_BATCH = 160+const IMPORT_SKIP_INITIAL_ROWS = 100type SourceIngestStatus = "not-ingested" | "ingested" | IngestTask["status"]export function SourcesView() {@@ -54,6 +55,7 @@ export function SourcesView() {const [urlError, setUrlError] = useState<string | null>(null)const [urlResults, setUrlResults] = useState<UrlImportResult[]>([])const [importOutcome, setImportOutcome] = useState<ImportOutcome | null>(null)+ const [showAllImportSkips, setShowAllImportSkips] = useState(false)const [ingestedIdentities, setIngestedIdentities] = useState<string[]>([])const [queueSnapshot, setQueueSnapshot] = useState<IngestTask[]>(() => [...getQueue()])const [sourceQuery, setSourceQuery] = useState("")@@ -206,6 +208,7 @@ export function SourcesView() {setImporting(true)setImportOutcome(null)+ setShowAllImportSkips(false)const paths = Array.isArray(selected) ? selected : [selected]try {const result = await importSourceFiles(project, paths, llmConfig, sourceWatchConfig)@@ -231,6 +234,7 @@ export function SourcesView() {setImporting(true)setImportOutcome(null)+ setShowAllImportSkips(false)try {const result = await importSourceFolder(project, selected, llmConfig, sourceWatchConfig)setImportOutcome(summarizeImportOutcome(result, null))@@ -509,16 +513,31 @@ export function SourcesView() {<X className="h-3 w-3" /></button></div>- {importOutcome.skipped.map((item, index) => (- <div key={`${item.name}-${index}`} className="pl-1">- {item.name}- {": "}- {t(`sources.importSkip.reason.${item.reason}`, {- defaultValue: item.reason,- })}- {item.detail ? ` (${item.detail})` : ""}- </div>- ))}+ {importOutcome.skipped+ .slice(0, showAllImportSkips ? undefined : IMPORT_SKIP_INITIAL_ROWS)+ .map((item, index) => (+ <div key={`${item.name}-${index}`} className="pl-1">+ {item.name}+ {": "}+ {t(`sources.importSkip.reason.${item.reason}`, {+ defaultValue: item.reason,+ })}+ {item.detail ? ` (${item.detail})` : ""}+ </div>+ ))}+ {importOutcome.skipped.length > IMPORT_SKIP_INITIAL_ROWS && (+ <button+ type="button"+ className="pl-1 font-medium underline underline-offset-2"+ onClick={() => setShowAllImportSkips((current) => !current)}+ >+ {showAllImportSkips+ ? t("sources.importSkip.showLess")+ : t("sources.importSkip.showRemaining", {+ count: importOutcome.skipped.length - IMPORT_SKIP_INITIAL_ROWS,+ })}+ </button>+ )}</div>)}{sources.length === 0 ? (diff --git a/src/i18n/en.json b/src/i18n/en.jsonindex b39112f8..4c698535 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -192,6 +192,8 @@"importSkip": {"failed": "Import failed: {{error}}","summary": "Imported {{imported}}, skipped {{skipped}}",+ "showRemaining": "Show {{count}} more skipped files",+ "showLess": "Show fewer skipped files","reason": {"unsupported-type": "Unsupported file type","excluded": "Blocked by an exclusion rule",diff --git a/src/i18n/it.json b/src/i18n/it.jsonindex 78781e1b..cdf7a3f2 100644--- a/src/i18n/it.json+++ b/src/i18n/it.json@@ -192,6 +192,8 @@"importSkip": {"failed": "Importazione non riuscita: {{error}}","summary": "Importati {{imported}}, ignorati {{skipped}}",+ "showRemaining": "Mostra altri {{count}} file ignorati",+ "showLess": "Mostra meno file ignorati","reason": {"unsupported-type": "Tipo di file non supportato","excluded": "Bloccato da una regola di esclusione",diff --git a/src/i18n/ru.json b/src/i18n/ru.jsonindex b6c00c88..38665c2d 100644--- a/src/i18n/ru.json+++ b/src/i18n/ru.json@@ -192,6 +192,8 @@"importSkip": {"failed": "Не удалось импортировать: {{error}}","summary": "Импортировано: {{imported}}, пропущено: {{skipped}}",+ "showRemaining": "Показать ещё {{count}} пропущенных файлов",+ "showLess": "Свернуть список пропущенных файлов","reason": {"unsupported-type": "Неподдерживаемый тип файла","excluded": "Заблокировано правилом исключения",diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex 296b5cfa..c3eb9a19 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -192,6 +192,8 @@"importSkip": {"failed": "导入失败:{{error}}","summary": "已导入 {{imported}} 个,跳过 {{skipped}} 个",+ "showRemaining": "显示其余 {{count}} 个跳过的文件",+ "showLess": "收起跳过的文件","reason": {"unsupported-type": "不支持的文件类型","excluded": "被排除规则阻止",diff --git a/src/lib/changelog.ts b/src/lib/changelog.tsindex 96d6a421..3ae14aed 100644--- a/src/lib/changelog.ts+++ b/src/lib/changelog.ts@@ -25,6 +25,28 @@ export interface ChangelogEntry {}export const CHANGELOG: ChangelogEntry[] = [+ {+ version: "0.6.10",+ date: "2026-08-21",+ highlights: {+ en: [+ "Added source-based knowledge filtering.",+ "Added batch Deep Research for review items and support for rerunning completed or failed research tasks.",+ "Added support for MinerU 3.0-3.2 backend names and made image captions follow the configured output language.",+ "Added detailed reporting for files skipped during source import.",+ "Improved large duplicate scans and fixed Deep Research concurrency, file naming, vector indexing, and wikilink consistency.",+ "Improved Agent model routing and provider compatibility, and fixed language detection, retry behavior, and Windows CRLF data integrity issues.",+ ],+ zh: [+ "新增按原始资料来源筛选知识内容。",+ "Review 支持批量执行深度研究,并可重新运行已完成或失败的研究任务。",+ "支持 MinerU 3.0-3.2 后端名称,图片描述会遵循配置的输出语言。",+ "文件导入新增跳过文件及具体原因的详细报告。",+ "优化大规模重复文件扫描,并修复深度研究并发、文件命名、向量索引和 Wiki 链接一致性问题。",+ "完善 Agent 模型路由与 Provider 兼容性,并修复语言误判、重试行为和 Windows CRLF 数据完整性问题。",+ ],+ },+ },{version: "0.6.9",date: "2026-08-14",diff --git a/src/lib/deep-research.test.ts b/src/lib/deep-research.test.tsindex df99fee4..4d86b232 100644--- a/src/lib/deep-research.test.ts+++ b/src/lib/deep-research.test.ts@@ -1,10 +1,13 @@import { describe, expect, it, vi } from "vitest"import {citedResearchSourceIndexes,+ addResearchTaskDiscriminator,buildResearchPageContent,collectResearchSources,makeDeepResearchFileName,+ makeAvailableResearchFilePath,noResearchSourcesTaskPatch,+ researchPageIdFromPath,resolveReviewForSavedResearch,validateResearchSynthesis,} from "./deep-research"@@ -76,6 +79,48 @@ describe("buildResearchPageContent", () => {expect(content).toContain("`[[concepts/code-example]]`")expect(content).toContain("![[media/chart.png]]")})++ it("keeps multiline topics inside one safe YAML scalar and heading", () => {+ const content = buildResearchPageContent(+ "first line\nsecond: \"quoted\"",+ "2026-08-20",+ "Substantive synthesis [1].",+ "1. [Source](https://example.com)",+ )+ expect(content).toContain('title: "Research: first line second: \\"quoted\\""')+ expect(content).toContain("# Research: first line second: \"quoted\"")+ expect(content).not.toContain("first line\nsecond")+ })+})++describe("makeAvailableResearchFilePath", () => {+ it("adds a suffix instead of overwriting a same-second research result", async () => {+ const existing = new Set([+ "/project/wiki/queries/research-topic-2026-08-20-120000.md",+ "/project/wiki/queries/research-topic-2026-08-20-120000-2.md",+ ])+ await expect(makeAvailableResearchFilePath(+ "/project/wiki/queries",+ "research-topic-2026-08-20-120000.md",+ async (path) => existing.has(path),+ )).resolves.toBe("/project/wiki/queries/research-topic-2026-08-20-120000-3.md")+ })++ it("gives concurrent tasks distinct readable filenames before existence checks", () => {+ const fileName = "research-topic-2026-08-20-120000.md"+ expect(addResearchTaskDiscriminator(fileName, "research-41"))+ .toBe("research-topic-2026-08-20-120000-research-41.md")+ expect(addResearchTaskDiscriminator(fileName, "research-42"))+ .not.toBe(addResearchTaskDiscriminator(fileName, "research-41"))+ })++ it("derives the vector page id from the final collision-safe path", () => {+ expect(researchPageIdFromPath(+ "/project/wiki/queries/research-topic-2026-08-20-120000-research-41-2.md",+ )).toBe("research-topic-2026-08-20-120000-research-41-2")+ expect(researchPageIdFromPath("C:\\project\\wiki\\queries\\research-topic-3.MD"))+ .toBe("research-topic-3")+ })})describe("validateResearchSynthesis", () => {diff --git a/src/lib/deep-research.ts b/src/lib/deep-research.tsindex 6e551bb5..3754084f 100644--- a/src/lib/deep-research.ts+++ b/src/lib/deep-research.ts@@ -2,7 +2,7 @@ import { anyTxtSearchSmart, hasConfiguredAnyTxt } from "./anytxt-search"import { hasConfiguredSearchProvider, resolveSearchConfig, webSearch } from "./web-search"import { streamChat } from "./llm-client"import { currentWikiDate } from "./ingest"-import { writeFile, readFile } from "@/commands/fs"+import { fileExists, writeFile, readFile } from "@/commands/fs"import { useWikiStore, type LlmConfig, type SearchApiConfig } from "@/stores/wiki-store"import { useResearchStore } from "@/stores/research-store"import { normalizePath } from "@/lib/path-utils"@@ -29,16 +29,17 @@ export function buildResearchPageContent(synthesis: string,references: string,): string {+ const displayTopic = topic.replace(/\s+/g, " ").trim()return stripBodyWikilinkPathPrefixes(["---","type: query",- `title: "Research: ${topic.replace(/"/g, '\\"')}"`,+ `title: ${JSON.stringify(`Research: ${displayTopic}`)}`,`created: ${date}`,"origin: deep-research","tags: [research]","---","",- `# Research: ${topic}`,+ `# Research: ${displayTopic}`,"",synthesis,"",@@ -49,6 +50,35 @@ export function buildResearchPageContent(].join("\n"))}+export async function makeAvailableResearchFilePath(+ directory: string,+ fileName: string,+ exists: (path: string) => Promise<boolean> = fileExists,+): Promise<string> {+ const basePath = `${directory}/${fileName}`+ if (!(await exists(basePath))) return basePath++ const extensionIndex = fileName.toLowerCase().endsWith(".md") ? fileName.length - 3 : fileName.length+ const stem = fileName.slice(0, extensionIndex)+ const extension = fileName.slice(extensionIndex)+ for (let suffix = 2; suffix <= 999; suffix++) {+ const candidate = `${directory}/${stem}-${suffix}${extension}`+ if (!(await exists(candidate))) return candidate+ }+ return `${directory}/${stem}-${Date.now()}${extension}`+}++export function addResearchTaskDiscriminator(fileName: string, taskId: string): string {+ const safeTaskId = taskId.replace(/[^A-Za-z0-9-]/g, "-").replace(/-+/g, "-")+ const extensionIndex = fileName.toLowerCase().endsWith(".md") ? fileName.length - 3 : fileName.length+ return `${fileName.slice(0, extensionIndex)}-${safeTaskId || "task"}${fileName.slice(extensionIndex)}`+}++export function researchPageIdFromPath(filePath: string): string {+ const fileName = filePath.split(/[\\/]/).pop() || filePath+ return fileName.replace(/\.md$/i, "")+}+interface ResearchSourceDeps {webSearch: typeof webSearchanyTxtSearch: typeof anyTxtSearchSmart@@ -461,7 +491,8 @@ async function executeResearch(if (!updateTaskIfActive(pp, taskId, { status: "saving", synthesis: validation.cleaned })) returnconst { fileName, date } = makeDeepResearchFileName(topic)- const filePath = `${pp}/wiki/queries/${fileName}`+ const taskFileName = addResearchTaskDiscriminator(fileName, taskId)+ const filePath = await makeAvailableResearchFilePath(`${pp}/wiki/queries`, taskFileName)// Persist only sources cited by the synthesis. Search providers can return// broad candidates; listing every candidate makes unused, off-topic hits@@ -481,7 +512,7 @@ async function executeResearch()await writeFile(filePath, pageContent)- const savedPath = `wiki/queries/${fileName}`+ const savedPath = filePath.slice(`${pp}/`.length)if (!updateTaskIfActive(pp, taskId, {status: "done",@@ -502,7 +533,7 @@ async function executeResearch(if (embeddingConfig.enabled && embeddingConfig.model) {try {const { embedPage } = await import("@/lib/embedding")- await embedPage(pp, fileName.replace(/\.md$/i, ""), `Research: ${topic}`, pageContent, embeddingConfig)+ await embedPage(pp, researchPageIdFromPath(filePath), `Research: ${topic}`, pageContent, embeddingConfig)} catch (err) {console.warn("[DeepResearch] failed to index generated query page:", err)}diff --git a/src/lib/knowledge-source-filter.ts b/src/lib/knowledge-source-filter.tsindex 63dc1228..49e0d9a1 100644--- a/src/lib/knowledge-source-filter.ts+++ b/src/lib/knowledge-source-filter.ts@@ -8,7 +8,7 @@ export function normalizeSourceIdentity(source: string): string {return normalizePath(source).replace(/^\.\//, "").replace(/^raw\/sources\//i, "")- .toLocaleLowerCase()+ .toLowerCase()}export function listPageSourceIdentities<T extends SourceLinkedPage>(pages: readonly T[]): string[] {diff --git a/src/lib/sources-merge.test.ts b/src/lib/sources-merge.test.tsindex 8d7e3e6b..6314a29f 100644--- a/src/lib/sources-merge.test.ts+++ b/src/lib/sources-merge.test.ts@@ -65,6 +65,11 @@ describe("parseSources — inline `sources: [...]`", () => {])})+ it("parses CRLF frontmatter", () => {+ const content = '---\r\ntitle: Windows\r\nsources: ["BookA.pdf", "BookB.pdf"]\r\n---\r\n# Body\r\n'+ expect(parseSources(content)).toEqual(["BookA.pdf", "BookB.pdf"])+ })+it("keeps commas inside quoted source filenames", () => {expect(parseSources(WRAP('sources: ["reports/Q1, revised.pdf", "测试,最终版.md"]'))).toEqual(["reports/Q1, revised.pdf",@@ -99,6 +104,12 @@ describe("parseSources — multi-line YAML list form", () => {// ── writeSources ────────────────────────────────────────────────────describe("writeSources", () => {+ it("preserves CRLF frontmatter delimiters when updating sources", () => {+ const before = '---\r\ntitle: Windows\r\nsources: ["a.md"]\r\n---\r\n# Body\r\n'+ const after = writeSources(before, ["a.md", "b.md"])+ expect(after).toContain('---\r\ntitle: Windows\r\nsources: ["a.md", "b.md"]\r\n---\r\n')+ expect(parseSources(after)).toEqual(["a.md", "b.md"])+ })it("replaces an existing inline sources array", () => {const before = WRAP('title: X\nsources: ["a.md"]')const after = writeSources(before, ["a.md", "b.md"])@@ -136,6 +147,32 @@ describe("writeSources", () => {expect(after).not.toMatch(/^\s+-\s+a\.md/m)})+ it("preserves the following frontmatter field after an LF block list", () => {+ const before = WRAP(+ ["title: X", "sources:", " - a.md", " - b.md", "tags: [keep]"].join("\n"),+ )+ const after = writeSources(before, ["a.md", "b.md", "c.md"])++ expect(after).toContain('sources: ["a.md", "b.md", "c.md"]\ntags: [keep]')+ })++ it("preserves the following frontmatter field after a CRLF block list", () => {+ const before = [+ "---",+ "title: Windows",+ "sources:",+ " - a.md",+ " - b.md",+ "tags: [keep]",+ "---",+ "# Body",+ "",+ ].join("\r\n")+ const after = writeSources(before, ["a.md", "b.md", "c.md"])++ expect(after).toContain('sources: ["a.md", "b.md", "c.md"]\r\ntags: [keep]')+ })+it("returns content unchanged when there is no frontmatter", () => {const before = "# heading\n\nbody"expect(writeSources(before, ["a.md"])).toBe(before)@@ -153,6 +190,35 @@ describe("writeSources", () => {})})+describe("mergeArrayFieldsIntoContent — CRLF", () => {+ it("preserves existing array values when the existing page uses CRLF", () => {+ const existing = [+ "---",+ "title: Windows",+ 'sources: ["old.pdf"]',+ "tags: [existing]",+ "---",+ "# Existing",+ "",+ ].join("\r\n")+ const incoming = WRAP([+ "title: Windows",+ 'sources: ["new.pdf"]',+ "tags: [incoming]",+ ].join("\n"), "# Updated\n")++ const merged = mergeArrayFieldsIntoContent(+ incoming,+ existing,+ ["sources", "tags"],+ )++ expect(parseFrontmatterArray(merged, "sources")).toEqual(["old.pdf", "new.pdf"])+ expect(parseFrontmatterArray(merged, "tags")).toEqual(["existing", "incoming"])+ expect(merged).toContain("# Updated")+ })+})+// ── mergeSourcesLists ───────────────────────────────────────────────describe("mergeSourcesLists", () => {diff --git a/src/lib/sources-merge.ts b/src/lib/sources-merge.tsindex fcf1bceb..bd0b3750 100644--- a/src/lib/sources-merge.ts+++ b/src/lib/sources-merge.ts@@ -34,20 +34,20 @@* `parseFrontmatterArray(c, "rel")` won't match `related: [...]`.*/export function parseFrontmatterArray(content: string, fieldName: string): string[] {- const fmMatch = content.match(/^---\n([\s\S]*?)\n---/)+ const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/)if (!fmMatch) return []const fm = fmMatch[1]// Anchor to start of line + exact field name + colon. The negative// lookahead-style check is done by requiring `:` immediately after.const escapedName = fieldName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")const blockRe = new RegExp(- `^${escapedName}:\\s*\\n((?:[ \\t]+-\\s+.+\\n?)+)`,+ `^${escapedName}:\\s*\\r?\\n((?:[ \\t]+-\\s+.+(?:\\r?\\n|$))+)`,"m",)const block = fm.match(blockRe)if (block) {const out: string[] = []- for (const line of block[1].split("\n")) {+ for (const line of block[1].split(/\r?\n/)) {const m = line.match(/^\s+-\s+["']?(.+?)["']?\s*$/)if (m && m[1]) out.push(m[1].trim())}@@ -116,10 +116,11 @@ export function writeFrontmatterArray(fieldName: string,values: string[],): string {- const fmMatch = content.match(/^(---\n)([\s\S]*?)(\n---)/)+ const fmMatch = content.match(/^(---\r?\n)([\s\S]*?)(\r?\n---)/)if (!fmMatch) return contentconst [, openDelim, fmBody, closeDelim] = fmMatch+ const newline = openDelim.endsWith("\r\n") ? "\r\n" : "\n"const escapedName = fieldName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")const serialized = values.map(quoteInlineArrayValue).join(", ")const newLine = `${fieldName}: [${serialized}]`@@ -133,16 +134,18 @@ export function writeFrontmatterArray(// Replace block form in place, normalized to inline form.const blockRe = new RegExp(- `^${escapedName}:\\s*\\n((?:[ \\t]+-\\s+.+\\n?)+)`,+ `^${escapedName}:\\s*\\r?\\n((?:[ \\t]+-\\s+.+(?:\\r?\\n|$))+)`,"m",)if (blockRe.test(fmBody)) {- const rewritten = fmBody.replace(blockRe, newLine)+ const rewritten = fmBody.replace(blockRe, (matched) =>+ `${newLine}${/\r?\n$/.test(matched) ? newline : ""}`,+ )return `${openDelim}${rewritten}${closeDelim}${content.slice(fmMatch[0].length)}`}// Field absent — append at end of frontmatter.- const rewritten = `${fmBody}\n${newLine}`+ const rewritten = `${fmBody}${newline}${newLine}`return `${openDelim}${rewritten}${closeDelim}${content.slice(fmMatch[0].length)}`}@@ -187,7 +190,7 @@ export function mergeArrayFieldsIntoContent(fields: readonly string[],): string {if (!existingContent) return newContent- if (!/^---\n/.test(existingContent)) return newContent+ if (!/^---\r?\n/.test(existingContent)) return newContentlet result = newContentlet changed = falsediff --git a/src/stores/research-store.test.ts b/src/stores/research-store.test.tsindex 17b05043..3e13405d 100644--- a/src/stores/research-store.test.ts+++ b/src/stores/research-store.test.ts@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it } from "vitest"-import { useResearchStore } from "./research-store"+import { hasActiveResearchRerun, useResearchStore, type ResearchTask } from "./research-store"beforeEach(() => {useResearchStore.setState({ tasks: [], panelOpen: false, maxConcurrent: 3 })@@ -35,3 +35,33 @@ describe("research store batch queue", () => {expect(useResearchStore.getState().tasks).toEqual([])})})++describe("research rerun lineage", () => {+ const task = (id: string, status: ResearchTask["status"], rerunOfTaskId?: string) => ({+ id,+ topic: id,+ status,+ rerunOfTaskId,+ webResults: [],+ synthesis: "",+ savedPath: null,+ error: null,+ createdAt: 1,+ }) satisfies ResearchTask++ it("blocks concurrent reruns started from any task in the same lineage", () => {+ const tasks = [+ task("original", "done"),+ task("rerun-1", "done", "original"),+ task("rerun-2", "searching", "rerun-1"),+ ]+ expect(hasActiveResearchRerun(tasks, "original")).toBe(true)+ expect(hasActiveResearchRerun(tasks, "rerun-1")).toBe(true)+ })++ it("does not block a different lineage or a completed rerun", () => {+ const tasks = [task("original", "done"), task("rerun", "done", "original")]+ expect(hasActiveResearchRerun(tasks, "original")).toBe(false)+ expect(hasActiveResearchRerun([...tasks, task("other", "queued")], "original")).toBe(false)+ })+})diff --git a/src/stores/research-store.ts b/src/stores/research-store.tsindex 101efb31..60437c74 100644--- a/src/stores/research-store.ts+++ b/src/stores/research-store.ts@@ -33,6 +33,35 @@ interface ResearchState {let counter = 0+const ACTIVE_RESEARCH_STATUSES = new Set<ResearchTask["status"]>([+ "queued",+ "searching",+ "synthesizing",+ "saving",+])++function researchLineageRoot(tasksById: ReadonlyMap<string, ResearchTask>, taskId: string): string {+ let current = taskId+ const visited = new Set<string>()+ while (!visited.has(current)) {+ visited.add(current)+ const parent = tasksById.get(current)?.rerunOfTaskId+ if (!parent) break+ current = parent+ }+ return current+}++export function hasActiveResearchRerun(tasks: readonly ResearchTask[], taskId: string): boolean {+ const tasksById = new Map(tasks.map((task) => [task.id, task]))+ const root = researchLineageRoot(tasksById, taskId)+ return tasks.some((task) =>+ task.id !== taskId &&+ ACTIVE_RESEARCH_STATUSES.has(task.status) &&+ researchLineageRoot(tasksById, task.id) === root,+ )+}+function createResearchTask(input: Pick<ResearchTask, "topic" | "searchQueries" | "sourceReviewId" | "rerunOfTaskId">,): ResearchTask {