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: preserve source summary slug compatibility

nash_sua3049ece3fde
diff --git a/src/lib/deep-research.test.ts b/src/lib/deep-research.test.ts
index 22d3fc59..5143796e 100644
--- a/src/lib/deep-research.test.ts
+++ b/src/lib/deep-research.test.ts
@@ -40,6 +40,12 @@ describe("makeDeepResearchFileName", () => {
expect(second.fileName).toBe("research-反硝化除磷-2026-06-06-100001.md")
expect(first.fileName).not.toBe(second.fileName)
})
+
+ it("uses the local calendar date for frontmatter metadata", () => {
+ const localMorning = new Date(2026, 5, 6, 1, 30, 0)
+
+ expect(makeDeepResearchFileName("政策版本差异", localMorning).date).toBe("2026-06-06")
+ })
})
describe("collectResearchSources", () => {
diff --git a/src/lib/deep-research.ts b/src/lib/deep-research.ts
index 0cff3ded..7f6e0853 100644
--- a/src/lib/deep-research.ts
+++ b/src/lib/deep-research.ts
@@ -1,7 +1,7 @@
import { anyTxtSearchSmart, hasConfiguredAnyTxt } from "./anytxt-search"
import { hasConfiguredSearchProvider, resolveSearchConfig, webSearch } from "./web-search"
import { streamChat } from "./llm-client"
-import { autoIngest } from "./ingest"
+import { autoIngest, currentWikiDate } from "./ingest"
import { writeFile, readFile, listDirectory } from "@/commands/fs"
import { useWikiStore, type LlmConfig, type SearchApiConfig } from "@/stores/wiki-store"
import { useResearchStore } from "@/stores/research-store"
@@ -29,8 +29,8 @@ export function makeDeepResearchFileName(topic: string, now: Date = new Date()):
fileName: string
date: string
} {
- const { fileName, date } = makeQueryFileName(`research-${topic}`, now)
- return { fileName, date }
+ const { fileName } = makeQueryFileName(`research-${topic}`, now)
+ return { fileName, date: currentWikiDate(now) }
}
/**
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index 6515212f..fe1922cb 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -17,6 +17,7 @@ import { useReviewStore, type ReviewItem } from "@/stores/review-store"
import { getFileName, normalizePath } from "@/lib/path-utils"
import {
sourceIdentityForPath,
+ sourceSummarySlugCandidatesFromIdentity,
sourceSummarySlugFromIdentity,
} from "@/lib/source-identity"
import { parseSources, writeSources } from "@/lib/sources-merge"
@@ -1084,6 +1085,10 @@ async function migrateLegacySourceSummaryIfSafe(
const normalizedIdentity = normalizePath(sourceIdentity)
if (!normalizedIdentity.includes("/")) return
+ if (await migrateExactLegacySourceSummaryIfSafe(projectPath, normalizedIdentity, sourceSummaryPath)) {
+ return
+ }
+
const basename = getFileName(normalizedIdentity)
const legacySlug = basename.replace(/\.[^.]+$/, "")
const legacyPath = `wiki/sources/${legacySlug}.md`
@@ -1134,6 +1139,58 @@ async function migrateLegacySourceSummaryIfSafe(
}
}
+async function migrateExactLegacySourceSummaryIfSafe(
+ projectPath: string,
+ sourceIdentity: string,
+ sourceSummaryPath: string,
+): Promise<boolean> {
+ const pp = normalizePath(projectPath)
+ const canonicalFullPath = `${pp}/${sourceSummaryPath}`
+ let canonicalExists = false
+ try {
+ canonicalExists = await fileExists(canonicalFullPath)
+ } catch {
+ return false
+ }
+ if (canonicalExists) return false
+
+ const sourceKey = normalizePath(sourceIdentity).toLowerCase()
+ const legacyPaths = sourceSummarySlugCandidatesFromIdentity(sourceIdentity)
+ .map((slug) => `wiki/sources/${slug}.md`)
+ .filter((path) => path !== sourceSummaryPath)
+
+ for (const legacyPath of legacyPaths) {
+ const legacyFullPath = `${pp}/${legacyPath}`
+ let legacyContent = ""
+ try {
+ if (!(await fileExists(legacyFullPath))) continue
+ legacyContent = await readFile(legacyFullPath)
+ } catch {
+ continue
+ }
+
+ const sources = parseSources(legacyContent)
+ const referencesSameSource = sources.some(
+ (source) => normalizePath(source).toLowerCase() === sourceKey,
+ )
+ if (!referencesSameSource) continue
+
+ try {
+ await writeFile(canonicalFullPath, canonicalizeSourcesField(legacyContent, sourceIdentity))
+ await deleteFile(legacyFullPath)
+ return true
+ } catch (err) {
+ console.warn(
+ `[ingest] failed to migrate legacy source summary ${legacyPath} -> ${sourceSummaryPath}:`,
+ err instanceof Error ? err.message : err,
+ )
+ return false
+ }
+ }
+
+ return false
+}
+
async function matchingRawSourceIdentitiesForBasename(
projectPath: string,
basename: string,
diff --git a/src/lib/raw-source-resolver.test.ts b/src/lib/raw-source-resolver.test.ts
index bc222c87..d4c40d4b 100644
--- a/src/lib/raw-source-resolver.test.ts
+++ b/src/lib/raw-source-resolver.test.ts
@@ -1,7 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createTempProject, realFs, writeFileRaw } from "@/test-helpers/fs-temp"
import { findRawSourceForImage, imageUrlToAbsolute } from "./raw-source-resolver"
-import { sourceSummarySlugFromIdentity } from "./source-identity"
+import {
+ legacySourceSummarySlugFromIdentity,
+ sourceSummarySlugFromIdentity,
+} from "./source-identity"
vi.mock("@/commands/fs", () => realFs)
@@ -37,6 +40,18 @@ describe("raw source image resolver", () => {
).resolves.toBe(`${tmp.path}/raw/sources/project-a/config.pdf`)
})
+ it("resolves nested source media slugs created with legacy percent-encoded source slugs", async () => {
+ if (!tmp) throw new Error("missing temp project")
+
+ await writeFileRaw(`${tmp.path}/raw/sources/2024年/污水处理.pdf`, "nested CJK source\n")
+ const slug = legacySourceSummarySlugFromIdentity("2024年/污水处理.pdf")
+
+ expect(slug).toContain("%")
+ await expect(
+ findRawSourceForImage(`media/${slug}/img-1.png`, tmp.path),
+ ).resolves.toBe(`${tmp.path}/raw/sources/2024年/污水处理.pdf`)
+ })
+
it("normalizes wiki-relative image URLs to absolute wiki media paths", () => {
expect(imageUrlToAbsolute("media/report/img-1.png", "/project")).toBe(
"/project/wiki/media/report/img-1.png",
diff --git a/src/lib/raw-source-resolver.ts b/src/lib/raw-source-resolver.ts
index e514d962..33765ca1 100644
--- a/src/lib/raw-source-resolver.ts
+++ b/src/lib/raw-source-resolver.ts
@@ -22,7 +22,7 @@
import { listDirectory } from "@/commands/fs"
import {
sourceIdentityForPath,
- sourceSummarySlugFromIdentity,
+ sourceSummarySlugCandidatesFromIdentity,
} from "@/lib/source-identity"
import type { FileNode } from "@/types/wiki"
@@ -56,7 +56,7 @@ export async function findRawSourceForImage(
continue
}
const identity = sourceIdentityForPath(normalizedProjectPath, node.path)
- if (sourceSummarySlugFromIdentity(identity) === slug) return node.path
+ if (sourceSummarySlugCandidatesFromIdentity(identity).includes(slug)) return node.path
// Backward compatibility for media folders created before nested source
// identities were encoded into the slug.
diff --git a/src/lib/source-identity.test.ts b/src/lib/source-identity.test.ts
index ee78c814..51b5764e 100644
--- a/src/lib/source-identity.test.ts
+++ b/src/lib/source-identity.test.ts
@@ -1,7 +1,9 @@
import { describe, expect, it } from "vitest"
import {
+ legacySourceSummarySlugFromIdentity,
sourceIdentityForPath,
sourceReferenceIdentity,
+ sourceSummarySlugCandidatesFromIdentity,
sourceSummarySlugFromIdentity,
} from "./source-identity"
@@ -38,8 +40,10 @@ describe("source identity helpers", () => {
})
it("escapes slug segments so delimiter-containing folders do not collide", () => {
- expect(sourceSummarySlugFromIdentity("a--b/config.yaml")).toMatch(
- /^3-a-b--6-config--[a-z0-9]+$/,
+ const slug = sourceSummarySlugFromIdentity("a--b/config.yaml")
+
+ expect(slug).toMatch(
+ /^4-a-b--6-config--[a-z0-9]+$/,
)
expect(sourceSummarySlugFromIdentity("a/b/config.yaml")).toMatch(
/^1-a--1-b--6-config--[a-z0-9]+$/,
@@ -47,6 +51,9 @@ describe("source identity helpers", () => {
expect(sourceSummarySlugFromIdentity("4-a--b--6-config.yaml")).not.toBe(
sourceSummarySlugFromIdentity("a--b/config.yaml"),
)
+ expect(sourceSummarySlugCandidatesFromIdentity("a--b/config.yaml")).toContain(
+ slug.replace(/^4-a-b/, "3-a-b"),
+ )
})
it("caps nested source summary slugs to avoid Windows path length failures", () => {
@@ -69,4 +76,15 @@ describe("source identity helpers", () => {
expect(first.length).toBeLessThanOrEqual(120)
expect(second.length).toBeLessThanOrEqual(120)
})
+
+ it("keeps legacy percent-encoded nested slug candidates for old source pages", () => {
+ const identity = "2024年/污水处理/反硝化除磷技术研究报告.pdf"
+ const canonical = sourceSummarySlugFromIdentity(identity)
+ const legacy = legacySourceSummarySlugFromIdentity(identity)
+
+ expect(canonical).not.toBe(legacy)
+ expect(canonical).not.toContain("%")
+ expect(legacy).toContain("%E6")
+ expect(sourceSummarySlugCandidatesFromIdentity(identity)).toEqual([canonical, legacy])
+ })
})
diff --git a/src/lib/source-identity.ts b/src/lib/source-identity.ts
index 3bd5f0eb..e1e943ac 100644
--- a/src/lib/source-identity.ts
+++ b/src/lib/source-identity.ts
@@ -49,8 +49,8 @@ export function sourceSummarySlugFromIdentity(sourceIdentity: string): string {
const hash = stableSlugHash(sourceIdentity)
const slug = parts.map((part) => {
- const readable = readableSlugPart(part)
- return `${Array.from(readable).length}-${readable}`
+ const { readable, structuralLength } = readableSlugPart(part)
+ return `${structuralLength}-${readable}`
}).join("--")
const fullSlug = `${slug}--${hash}`
if (fullSlug.length <= MAX_SOURCE_SUMMARY_SLUG_LENGTH) {
@@ -58,26 +58,75 @@ export function sourceSummarySlugFromIdentity(sourceIdentity: string): string {
}
const readableLimit = MAX_SOURCE_SUMMARY_SLUG_LENGTH - hash.length - 2
- const readablePrefix = trimIncompletePercentEncoding(slug.slice(0, readableLimit))
- .replace(/-+$/, "")
- .replace(/%$/, "")
+ const readablePrefix = slug.slice(0, readableLimit).replace(/-+$/, "")
return `${readablePrefix || "source"}--${hash}`
}
-function trimIncompletePercentEncoding(value: string): string {
- return value.replace(/%(?:[0-9A-F])?$/i, "")
+export function legacySourceSummarySlugFromIdentity(sourceIdentity: string): string {
+ const withoutExt = sourceIdentity.replace(/\.[^/.]+$/, "")
+ const parts = withoutExt
+ .split("/")
+ .map((part) => part.trim())
+ .filter(Boolean)
+
+ if (parts.length <= 1) {
+ return parts[0] || "source"
+ }
+
+ const hash = stableSlugHash(sourceIdentity)
+ const slug = parts.map((part) => {
+ const encoded = encodeURIComponent(part)
+ return `${encoded.length}-${encoded}`
+ }).join("--")
+ return `${slug}--${hash}`
+}
+
+export function sourceSummarySlugCandidatesFromIdentity(sourceIdentity: string): string[] {
+ const canonical = sourceSummarySlugFromIdentity(sourceIdentity)
+ const previousReadable = previousReadableSourceSummarySlugFromIdentity(sourceIdentity)
+ const legacy = legacySourceSummarySlugFromIdentity(sourceIdentity)
+ return Array.from(new Set([canonical, previousReadable, legacy]))
+}
+
+function previousReadableSourceSummarySlugFromIdentity(sourceIdentity: string): string {
+ const withoutExt = sourceIdentity.replace(/\.[^/.]+$/, "")
+ const parts = withoutExt
+ .split("/")
+ .map((part) => part.trim())
+ .filter(Boolean)
+
+ if (parts.length <= 1) {
+ return parts[0] || "source"
+ }
+
+ const hash = stableSlugHash(sourceIdentity)
+ const slug = parts.map((part) => {
+ const { readable } = readableSlugPart(part)
+ return `${Array.from(readable).length}-${readable}`
+ }).join("--")
+ const fullSlug = `${slug}--${hash}`
+ if (fullSlug.length <= MAX_SOURCE_SUMMARY_SLUG_LENGTH) {
+ return fullSlug
+ }
+
+ const readableLimit = MAX_SOURCE_SUMMARY_SLUG_LENGTH - hash.length - 2
+ const readablePrefix = slug.slice(0, readableLimit).replace(/-+$/, "")
+ return `${readablePrefix || "source"}--${hash}`
}
-function readableSlugPart(part: string): string {
- const slug = part
+function readableSlugPart(part: string): { readable: string; structuralLength: number } {
+ const structural = part
.normalize("NFKC")
.trim()
.replace(/\s+/g, "-")
.replace(/[^\p{L}\p{N}-]/gu, "")
- .replace(/-+/g, "-")
.replace(/^-|-$/g, "")
.toLowerCase()
- return slug || FALLBACK_SOURCE_PART
+ const readable = structural.replace(/-+/g, "-") || FALLBACK_SOURCE_PART
+ return {
+ readable,
+ structuralLength: Math.max(1, Array.from(structural || FALLBACK_SOURCE_PART).length),
+ }
}
function stableSlugHash(value: string): string {