Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

fix: address reported ingest and provider bugs

nash_sudb6d3347e57c
diff --git a/src/lib/deep-research.test.ts b/src/lib/deep-research.test.ts
index 4ee4ed1b..22d3fc59 100644
--- a/src/lib/deep-research.test.ts
+++ b/src/lib/deep-research.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest"
-import { collectResearchSources } from "./deep-research"
+import { collectResearchSources, makeDeepResearchFileName } from "./deep-research"
import type { SearchApiConfig } from "@/stores/wiki-store"
import type { WebSearchResult } from "./web-search"
@@ -25,6 +25,23 @@ function config(patch: Partial<SearchApiConfig>): SearchApiConfig {
}
}
+describe("makeDeepResearchFileName", () => {
+ it("keeps Unicode topics and includes time to avoid same-day overwrite", () => {
+ const first = makeDeepResearchFileName(
+ "反硝化除磷",
+ new Date("2026-06-06T10:00:00.000Z"),
+ )
+ const second = makeDeepResearchFileName(
+ "反硝化除磷",
+ new Date("2026-06-06T10:00:01.000Z"),
+ )
+
+ expect(first.fileName).toBe("research-反硝化除磷-2026-06-06-100000.md")
+ expect(second.fileName).toBe("research-反硝化除磷-2026-06-06-100001.md")
+ expect(first.fileName).not.toBe(second.fileName)
+ })
+})
+
describe("collectResearchSources", () => {
it("uses only Web Search when source mode is web", async () => {
const webSearch = vi.fn().mockResolvedValue([webResult])
diff --git a/src/lib/deep-research.ts b/src/lib/deep-research.ts
index 40ccea76..a8a73e8b 100644
--- a/src/lib/deep-research.ts
+++ b/src/lib/deep-research.ts
@@ -7,6 +7,7 @@ import { useWikiStore, type LlmConfig, type SearchApiConfig } from "@/stores/wik
import { useResearchStore } from "@/stores/research-store"
import { normalizePath } from "@/lib/path-utils"
import { buildLanguageDirective } from "@/lib/output-language"
+import { makeQueryFileName } from "@/lib/wiki-filename"
const MAX_RESEARCH_SOURCES = 20
@@ -24,6 +25,14 @@ interface ResearchSourceCollection {
errors: string[]
}
+export function makeDeepResearchFileName(topic: string, now: Date = new Date()): {
+ fileName: string
+ date: string
+} {
+ const { fileName, date } = makeQueryFileName(`research-${topic}`, now)
+ return { fileName, date }
+}
+
/**
* Queue a deep research task. Automatically starts processing if under concurrency limit.
*/
@@ -241,9 +250,7 @@ async function executeResearch(
// Step 3: Save to wiki
store.updateTask(taskId, { status: "saving", synthesis: accumulated })
- const date = new Date().toISOString().slice(0, 10)
- const slug = topic.toLowerCase().replace(/[^a-z0-9\s-]/g, "").trim().replace(/\s+/g, "-").slice(0, 50)
- const fileName = `research-${slug}-${date}.md`
+ const { fileName, date } = makeDeepResearchFileName(topic)
const filePath = `${pp}/wiki/queries/${fileName}`
const references = webResults
diff --git a/src/lib/ingest-parse.test.ts b/src/lib/ingest-parse.test.ts
index 060c4cb6..ae0c8d69 100644
--- a/src/lib/ingest-parse.test.ts
+++ b/src/lib/ingest-parse.test.ts
@@ -18,7 +18,13 @@
* to dropping pages without telling anyone.
*/
import { describe, it, expect } from "vitest"
-import { parseFileBlocks, isSafeIngestPath } from "./ingest"
+import {
+ parseFileBlocks,
+ isSafeIngestPath,
+ stampGeneratedFrontmatterDates,
+ stampGeneratedLogDate,
+ buildGenerationPrompt,
+} from "./ingest"
// ── Happy paths ─────────────────────────────────────────────────────
@@ -470,3 +476,58 @@ describe("parseFileBlocks — path-traversal guard end-to-end", () => {
expect(warnings.some((w) => w.includes("../config.json"))).toBe(true)
})
})
+
+describe("generated ingest dates", () => {
+ it("stamps frontmatter dates to the application date instead of model guesses", () => {
+ const out = stampGeneratedFrontmatterDates(
+ [
+ "---",
+ "type: concept",
+ "title: Wrong Date",
+ "created: 2024-01-01",
+ "updated: 2025-02-02",
+ "tags: []",
+ "---",
+ "# Body",
+ ].join("\n"),
+ "2026-06-07",
+ )
+
+ expect(out).toContain("created: 2026-06-07")
+ expect(out).toContain("updated: 2026-06-07")
+ expect(out).not.toContain("2024-01-01")
+ expect(out).not.toContain("2025-02-02")
+ })
+
+ it("adds missing frontmatter dates when the model omits them", () => {
+ const out = stampGeneratedFrontmatterDates(
+ [
+ "---",
+ "type: concept",
+ "title: Missing Date",
+ "tags: []",
+ "---",
+ "# Body",
+ ].join("\n"),
+ "2026-06-07",
+ )
+
+ expect(out).toContain("created: 2026-06-07")
+ expect(out).toContain("updated: 2026-06-07")
+ })
+
+ it("stamps generated log headings to the application date", () => {
+ expect(stampGeneratedLogDate("## [2024-01-01] ingest | Foo", "2026-06-07"))
+ .toBe("## [2026-06-07] ingest | Foo")
+ expect(stampGeneratedLogDate("## [YYYY-MM-DD] ingest | Foo", "2026-06-07"))
+ .toBe("## [2026-06-07] ingest | Foo")
+ })
+
+ it("tells the model the exact current date in the generation prompt", () => {
+ const prompt = buildGenerationPrompt("", "", "", "paper.pdf")
+
+ expect(prompt).toContain("Today's date is")
+ expect(prompt).toContain("Use this exact date")
+ expect(prompt).not.toContain("created: 2026-04-29")
+ })
+})
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index da4b2a99..47e85bae 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -1171,6 +1171,43 @@ async function matchingRawSourceIdentitiesForBasename(
return matches
}
+export function currentWikiDate(now: Date = new Date()): string {
+ const year = now.getFullYear()
+ const month = String(now.getMonth() + 1).padStart(2, "0")
+ const day = String(now.getDate()).padStart(2, "0")
+ return `${year}-${month}-${day}`
+}
+
+export function stampGeneratedFrontmatterDates(content: string, date: string): string {
+ const fmRe = /^(---\s*\r?\n)([\s\S]*?)(\r?\n---\s*(?:\r?\n|$))/
+ const match = content.match(fmRe)
+ if (!match) return content
+
+ let payload = match[2]
+ payload = setOrAppendFrontmatterDate(payload, "created", date)
+ payload = setOrAppendFrontmatterDate(payload, "updated", date)
+ return `${match[1]}${payload}${match[3]}${content.slice(match[0].length)}`
+}
+
+export function stampGeneratedLogDate(content: string, date: string): string {
+ const normalized = content.replace(/\bYYYY-MM-DD\b/g, date)
+ if (/^\s*##\s*\[?\d{4}-\d{2}-\d{2}\]?/m.test(normalized)) {
+ return normalized.replace(
+ /^(\s*##\s*\[?)\d{4}-\d{2}-\d{2}(\]?)/m,
+ `$1${date}$2`,
+ )
+ }
+ return normalized
+}
+
+function setOrAppendFrontmatterDate(payload: string, key: "created" | "updated", date: string): string {
+ const lineRe = new RegExp(`(^|\\n)(${key}\\s*:\\s*)[^\\n\\r]*`, "i")
+ if (lineRe.test(payload)) {
+ return payload.replace(lineRe, (_match, prefix: string, label: string) => `${prefix}${label}${date}`)
+ }
+ return `${payload.trimEnd()}\n${key}: ${date}`
+}
+
async function writeFileBlocks(
projectPath: string,
text: string,
@@ -1193,6 +1230,7 @@ async function writeFileBlocks(
const hardFailures: string[] = []
const targetLang = useWikiStore.getState().outputLanguage
+ const today = currentWikiDate()
for (const { path: rawRelativePath, content: rawContent } of blocks) {
let relativePath = rawRelativePath
@@ -1209,6 +1247,11 @@ async function writeFileBlocks(
// unparseable frontmatter and the read-time fallback had to
// paper over it forever.
let content = sanitizeIngestedFileContent(rawContent)
+ if (isLogPath(relativePath)) {
+ content = stampGeneratedLogDate(content, today)
+ } else if (!isListingPath(relativePath)) {
+ content = stampGeneratedFrontmatterDates(content, today)
+ }
if (!isLogPath(relativePath) && !isListingPath(relativePath)) {
content = canonicalizeSourcesField(content, sourceFileName)
}
@@ -1438,6 +1481,7 @@ export function buildGenerationPrompt(
// Use original filename (without extension) as the source summary page name
const sourceBaseName = sourceFileName.replace(/\.[^.]+$/, "")
const summaryPath = sourceSummaryPath ?? `wiki/sources/${sourceBaseName}.md`
+ const today = currentWikiDate()
return [
"You are a wiki maintainer. Based on the analysis provided, generate wiki files.",
@@ -1448,6 +1492,7 @@ export function buildGenerationPrompt(
`## IMPORTANT: Source File`,
`The original source file is: **${sourceFileName}**`,
`All wiki pages generated from this source MUST include this filename in their frontmatter \`sources\` field.`,
+ `Today's date is **${today}**. Use this exact date for all new \`created\`, \`updated\`, and wiki/log.md ingest dates.`,
"",
schema
? [
@@ -1486,8 +1531,8 @@ export function buildGenerationPrompt(
"Required fields and types:",
` • type — one of the known types (${GENERATION_WIKI_TYPES.join(" | ")}), or a custom type explicitly defined by the project schema`,
" • title — string (quote it if it contains a colon, e.g. `title: \"Foo: Bar\"`)",
- " • created — date in YYYY-MM-DD form (no quotes)",
- " • updated — same as created",
+ ` • created — ${today} for new pages (YYYY-MM-DD, no quotes)`,
+ ` • updated — ${today} for new pages (same as created)`,
" • tags — array of bare strings: `tags: [microbiology, ai]`",
" • related — array of bare wiki page slugs: `related: [foo, bar-baz]`. Do NOT include",
" `wiki/`, `.md`, or `[[…]]` here — slugs only.",
@@ -1499,8 +1544,8 @@ export function buildGenerationPrompt(
" ---",
" type: entity",
" title: Example Entity",
- " created: 2026-04-29",
- " updated: 2026-04-29",
+ ` created: ${today}`,
+ ` updated: ${today}`,
" tags: [example, demo]",
" related: [related-slug-1, related-slug-2]",
` sources: ["${sourceFileName}"]`,
diff --git a/src/lib/llm-providers.test.ts b/src/lib/llm-providers.test.ts
index 463b2511..f823ee2b 100644
--- a/src/lib/llm-providers.test.ts
+++ b/src/lib/llm-providers.test.ts
@@ -290,7 +290,7 @@ describe("Ollama / custom (chat_completions) — vision content", () => {
})
describe("reasoning controls", () => {
- it("maps DeepSeek-compatible custom endpoints to thinking disabled for structured tasks", () => {
+ it("does not send thinking to legacy DeepSeek chat models that reject the field", () => {
const cfg = mkConfig({
provider: "custom",
model: "deepseek-chat",
@@ -302,14 +302,30 @@ describe("reasoning controls", () => {
{ reasoning: { mode: "off" } },
) as Record<string, unknown>
+ expect(body.thinking).toBeUndefined()
+ expect(body.reasoning).toBeUndefined()
+ })
+
+ it("maps DeepSeek V4 reasoning off to thinking disabled for structured tasks", () => {
+ const cfg = mkConfig({
+ provider: "custom",
+ model: "deepseek-v4-flash",
+ customEndpoint: "https://api.deepseek.com/v1",
+ apiMode: "chat_completions",
+ })
+ const body = getProviderConfig(cfg).buildBody(
+ [{ role: "user", content: "hi" }],
+ { reasoning: { mode: "off" } },
+ ) as Record<string, unknown>
+
expect(body.thinking).toEqual({ type: "disabled" })
expect(body.reasoning).toBeUndefined()
})
- it("maps DeepSeek high reasoning to thinking enabled plus reasoning_effort", () => {
+ it("maps DeepSeek V4 high reasoning to thinking enabled plus reasoning_effort", () => {
const cfg = mkConfig({
provider: "custom",
- model: "deepseek-reasoner",
+ model: "deepseek-v4-pro",
customEndpoint: "https://api.deepseek.com/v1",
apiMode: "chat_completions",
})
@@ -325,7 +341,7 @@ describe("reasoning controls", () => {
it("does not send an undocumented DeepSeek max_reasoning_tokens field", () => {
const cfg = mkConfig({
provider: "custom",
- model: "deepseek-reasoner",
+ model: "deepseek-v4-pro",
customEndpoint: "https://api.deepseek.com/v1",
apiMode: "chat_completions",
})
diff --git a/src/lib/llm-providers.ts b/src/lib/llm-providers.ts
index a0fde2c4..3d96629e 100644
--- a/src/lib/llm-providers.ts
+++ b/src/lib/llm-providers.ts
@@ -263,6 +263,10 @@ function isDeepSeekEndpoint(config: LlmConfig): boolean {
return /deepseek/i.test(config.model) || /deepseek/i.test(config.customEndpoint)
}
+function supportsDeepSeekThinkingParam(config: LlmConfig): boolean {
+ return /deepseek[-_]?v4/i.test(config.model)
+}
+
function isQwenThinkingModel(model: string): boolean {
return /qwen[-_]?3/i.test(model)
}
@@ -364,12 +368,14 @@ function buildOpenAiCompatibleBody(
// important path for ingestion/rewrite tasks: it prevents the model
// from spending the whole response on `reasoning_content` with no
// final `content`.
- if (reasoning.mode === "off") {
- body.thinking = { type: "disabled" }
- } else if (reasoning.mode !== "auto") {
- body.thinking = { type: "enabled" }
- if (reasoning.mode === "high" || reasoning.mode === "max") {
- body.reasoning_effort = reasoning.mode
+ if (supportsDeepSeekThinkingParam(config)) {
+ if (reasoning.mode === "off") {
+ body.thinking = { type: "disabled" }
+ } else if (reasoning.mode !== "auto") {
+ body.thinking = { type: "enabled" }
+ if (reasoning.mode === "high" || reasoning.mode === "max") {
+ body.reasoning_effort = reasoning.mode
+ }
}
}
return body
diff --git a/src/lib/source-identity.test.ts b/src/lib/source-identity.test.ts
index 92041a85..ee78c814 100644
--- a/src/lib/source-identity.test.ts
+++ b/src/lib/source-identity.test.ts
@@ -39,7 +39,7 @@ describe("source identity helpers", () => {
it("escapes slug segments so delimiter-containing folders do not collide", () => {
expect(sourceSummarySlugFromIdentity("a--b/config.yaml")).toMatch(
- /^4-a--b--6-config--[a-z0-9]+$/,
+ /^3-a-b--6-config--[a-z0-9]+$/,
)
expect(sourceSummarySlugFromIdentity("a/b/config.yaml")).toMatch(
/^1-a--1-b--6-config--[a-z0-9]+$/,
@@ -55,6 +55,10 @@ describe("source identity helpers", () => {
expect(slug.length).toBeLessThanOrEqual(120)
expect(`wiki/sources/${slug}.md`.length).toBeLessThanOrEqual(136)
expect(slug).toMatch(/--[a-z0-9]+$/)
+ expect(slug).toContain("2024年")
+ expect(slug).toContain("污水处理")
+ expect(slug).toContain("反硝化除磷技术研究报告")
+ expect(slug).not.toContain("%")
})
it("keeps stable hashes when truncating long nested source slugs", () => {
diff --git a/src/lib/source-identity.ts b/src/lib/source-identity.ts
index 41367bc1..3bd5f0eb 100644
--- a/src/lib/source-identity.ts
+++ b/src/lib/source-identity.ts
@@ -3,6 +3,7 @@ import { getFileName, normalizePath } from "@/lib/path-utils"
const RAW_SOURCES_PREFIX = "raw/sources/"
const RAW_SOURCES_MARKER = "/raw/sources/"
const MAX_SOURCE_SUMMARY_SLUG_LENGTH = 120
+const FALLBACK_SOURCE_PART = "source"
export function sourceIdentityForPath(projectPath: string, sourcePath: string): string {
const pp = normalizePath(projectPath).replace(/\/+$/, "")
@@ -48,11 +49,8 @@ export function sourceSummarySlugFromIdentity(sourceIdentity: string): string {
const hash = stableSlugHash(sourceIdentity)
const slug = parts.map((part) => {
- const encoded = encodeURIComponent(part).replace(
- /[!'()*]/g,
- (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
- )
- return `${encoded.length}-${encoded}`
+ const readable = readableSlugPart(part)
+ return `${Array.from(readable).length}-${readable}`
}).join("--")
const fullSlug = `${slug}--${hash}`
if (fullSlug.length <= MAX_SOURCE_SUMMARY_SLUG_LENGTH) {
@@ -70,6 +68,18 @@ function trimIncompletePercentEncoding(value: string): string {
return value.replace(/%(?:[0-9A-F])?$/i, "")
}
+function readableSlugPart(part: string): string {
+ const slug = part
+ .normalize("NFKC")
+ .trim()
+ .replace(/\s+/g, "-")
+ .replace(/[^\p{L}\p{N}-]/gu, "")
+ .replace(/-+/g, "-")
+ .replace(/^-|-$/g, "")
+ .toLowerCase()
+ return slug || FALLBACK_SOURCE_PART
+}
+
function stableSlugHash(value: string): string {
let hash = 0x811c9dc5
for (let i = 0; i < value.length; i += 1) {