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(ingest): bound source summary filenames by UTF-8 bytes

xinyuan0801065ee1375f76
diff --git a/src/lib/ingest-source-path-collision.test.ts b/src/lib/ingest-source-path-collision.test.ts
index 48e4c111..6b2b9693 100644
--- a/src/lib/ingest-source-path-collision.test.ts
+++ b/src/lib/ingest-source-path-collision.test.ts
@@ -261,6 +261,39 @@ describe("autoIngest source summary paths", () => {
expect(content).toContain("-end")
})
+ it.each([
+ `${"中文".repeat(35)}.md`,
+ `${"资".repeat(30)}/${"文".repeat(70)}.md`,
+ ])("ingests a long CJK source into a filesystem-safe summary: %s", async (identity) => {
+ if (!tmp) throw new Error("missing temp project")
+ sourceMarkers = ["long source ingested"]
+ await writeFileRaw(`${tmp.path}/raw/sources/${identity}`, "Long CJK filename source.\n")
+
+ const written = await autoIngest(tmp.path, `${tmp.path}/raw/sources/${identity}`, useWikiStore.getState().llmConfig)
+ const summaryPath = `wiki/sources/${sourceSummarySlugFromIdentity(identity)}.md`
+
+ expect(written).toContain(summaryPath)
+ expect(await fs.readFile(`${tmp.path}/${summaryPath}`, "utf8")).toContain("long source ingested")
+ expect(await fs.readFile(`${tmp.path}/${summaryPath}`, "utf8")).toContain(identity)
+ expect(useActivityStore.getState().items.some((item) => item.status === "error")).toBe(false)
+ })
+
+ it("keeps an existing portable CJK summary at its original path", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ const stem = "中文".repeat(35)
+ const identity = `${stem}.md`
+ const oldSummaryPath = `${tmp.path}/wiki/sources/${stem}.md`
+ sourceMarkers = ["regenerated long source"]
+ await writeFileRaw(`${tmp.path}/raw/sources/${identity}`, "Updated source.\n")
+ await writeFileRaw(oldSummaryPath, `---\nsources: ["${identity}"]\n---\n# Previous summary`)
+
+ await autoIngest(tmp.path, `${tmp.path}/raw/sources/${identity}`, useWikiStore.getState().llmConfig)
+
+ const summaryPath = `${tmp.path}/wiki/sources/${sourceSummarySlugFromIdentity(identity)}.md`
+ expect(summaryPath).toBe(oldSummaryPath)
+ expect(await fs.readFile(summaryPath, "utf8")).toContain("regenerated long source")
+ })
+
it("keeps distinct source summaries for same-basename files in different source subdirectories", async () => {
if (!tmp) throw new Error("missing temp project")
sourceMarkers = ["project-a config", "project-b config"]
diff --git a/src/lib/raw-source-resolver.test.ts b/src/lib/raw-source-resolver.test.ts
index 0fbfad04..e242ef30 100644
--- a/src/lib/raw-source-resolver.test.ts
+++ b/src/lib/raw-source-resolver.test.ts
@@ -3,6 +3,7 @@ import { createTempProject, realFs, writeFileRaw } from "@/test-helpers/fs-temp"
import { findRawSourceForImage, imageUrlToAbsolute } from "./raw-source-resolver"
import {
legacySourceSummarySlugFromIdentity,
+ sourceSummarySlugCandidatesFromIdentity,
sourceSummarySlugFromIdentity,
} from "./source-identity"
@@ -68,4 +69,17 @@ describe("raw source image resolver", () => {
"/project/wiki/media/report/img-1.png",
)
})
+
+ it("resolves both byte-bounded and former media slugs for a long CJK source", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ const identity = `${"资料".repeat(8)}/${"中文".repeat(35)}.pdf`
+ const rawPath = `${tmp.path}/raw/sources/${identity}`
+ await writeFileRaw(rawPath, "long CJK source\n")
+ const candidates = sourceSummarySlugCandidatesFromIdentity(identity)
+ expect(candidates[0]).not.toBe(candidates[1])
+
+ for (const slug of candidates.slice(0, 2)) {
+ await expect(findRawSourceForImage(`media/${slug}/img-1.png`, tmp.path)).resolves.toBe(rawPath)
+ }
+ })
})
diff --git a/src/lib/source-identity.test.ts b/src/lib/source-identity.test.ts
index 51b5764e..2d82f146 100644
--- a/src/lib/source-identity.test.ts
+++ b/src/lib/source-identity.test.ts
@@ -1,4 +1,7 @@
import { describe, expect, it } from "vitest"
+import fs from "node:fs/promises"
+import os from "node:os"
+import path from "node:path"
import {
legacySourceSummarySlugFromIdentity,
sourceIdentityForPath,
@@ -87,4 +90,64 @@ describe("source identity helpers", () => {
expect(legacy).toContain("%E6")
expect(sourceSummarySlugCandidatesFromIdentity(identity)).toEqual([canonical, legacy])
})
+
+ it.each([
+ `${"资料".repeat(15)}/${"中文文档".repeat(18)}.pdf`,
+ `${"国际公约".repeat(30)}.md`,
+ `${"a".repeat(300)}.txt`,
+ `${"𠮷".repeat(40)}/${"𠮷".repeat(40)}.pdf`,
+ ])("bounds the UTF-8 size of the summary and media name for %s", (identity) => {
+ const slug = sourceSummarySlugFromIdentity(identity)
+
+ expect(Buffer.byteLength(slug, "utf8")).toBeLessThanOrEqual(252)
+ expect(Buffer.byteLength(`${slug}.md`, "utf8")).toBeLessThanOrEqual(255)
+ expect(slug).toMatch(/--[a-z0-9]+$/)
+ expect(slug).not.toMatch(/[\uD800-\uDFFF]/u)
+ })
+
+ it("keeps distinct hashes for long names sharing the same readable prefix", () => {
+ const prefix = "中文".repeat(60)
+ const first = sourceSummarySlugFromIdentity(`${prefix}甲.md`)
+ const second = sourceSummarySlugFromIdentity(`${prefix}乙.md`)
+
+ expect(first.split("--")[0]).toBe(second.split("--")[0])
+ expect(first).not.toBe(second)
+ expect(sourceSummarySlugFromIdentity(`${prefix}甲.md`)).toBe(first)
+ })
+
+ it("preserves the former root and nested names as legacy lookup candidates", () => {
+ const rootStem = "中文".repeat(50)
+ expect(sourceSummarySlugCandidatesFromIdentity(`${rootStem}.md`)).toContain(rootStem)
+
+ const identity = `folder/${rootStem}.md`
+ const canonical = sourceSummarySlugFromIdentity(identity)
+ const hash = canonical.split("--").pop()
+ const formerPrefix = `6-folder--100-${rootStem}`.slice(0, 120 - String(hash).length - 2)
+ expect(sourceSummarySlugCandidatesFromIdentity(identity)).toContain(`${formerPrefix}--${hash}`)
+ })
+
+ it("keeps existing portable CJK root names even when they exceed 120 bytes", () => {
+ const stem = "中文".repeat(35)
+ expect(sourceSummarySlugFromIdentity(`${stem}.md`)).toBe(stem)
+ })
+
+ it("writes a CJK summary and media directory when the old slug exceeds 255 bytes", async () => {
+ const identity = `${"资".repeat(30)}/${"文".repeat(70)}.pdf`
+ const slug = sourceSummarySlugFromIdentity(identity)
+ const previous = sourceSummarySlugCandidatesFromIdentity(identity)[1]
+ expect(Buffer.byteLength(`${previous}.md`, "utf8")).toBeGreaterThan(255)
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "source-slug-bytes-"))
+ try {
+ const summary = path.join(directory, "sources", `${slug}.md`)
+ const media = path.join(directory, "media", slug, "image.png")
+ await fs.mkdir(path.dirname(summary), { recursive: true })
+ await fs.mkdir(path.dirname(media), { recursive: true })
+ await fs.writeFile(summary, "# Summary")
+ await fs.writeFile(media, "image")
+ expect(await fs.readFile(summary, "utf8")).toBe("# Summary")
+ expect(await fs.readFile(media, "utf8")).toBe("image")
+ } finally {
+ await fs.rm(directory, { recursive: true, force: true })
+ }
+ })
})
diff --git a/src/lib/source-identity.ts b/src/lib/source-identity.ts
index e1e943ac..93e03947 100644
--- a/src/lib/source-identity.ts
+++ b/src/lib/source-identity.ts
@@ -3,6 +3,9 @@ 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
+// Filesystem components commonly allow 255 UTF-8 bytes; reserve three for
+// the .md extension. Keep portable existing names unchanged.
+const MAX_SOURCE_SUMMARY_SLUG_BYTES = 252
const FALLBACK_SOURCE_PART = "source"
export function sourceIdentityForPath(projectPath: string, sourcePath: string): string {
@@ -37,6 +40,30 @@ export function sourceReferenceIdentity(sourceReference: string): string {
}
export function sourceSummarySlugFromIdentity(sourceIdentity: string): string {
+ const previous = previousSourceSummarySlugFromIdentity(sourceIdentity)
+ const encoder = new TextEncoder()
+ if (encoder.encode(previous).length <= MAX_SOURCE_SUMMARY_SLUG_BYTES && !/[\uD800-\uDFFF]/u.test(previous)) {
+ return previous
+ }
+
+ const suffix = `--${stableSlugHash(sourceIdentity)}`
+ const readable = (previous.endsWith(suffix) ? previous.slice(0, -suffix.length) : previous)
+ .replace(/[\uD800-\uDFFF]/gu, "")
+ const prefixBudget = MAX_SOURCE_SUMMARY_SLUG_BYTES - encoder.encode(suffix).length
+ let prefix = ""
+ let bytes = 0
+ // Iterate code points, rather than UTF-16 units, to avoid splitting a
+ // surrogate pair at the truncation boundary.
+ for (const character of readable) {
+ const size = encoder.encode(character).length
+ if (bytes + size > prefixBudget) break
+ prefix += character
+ bytes += size
+ }
+ return `${prefix.replace(/-+$/, "") || FALLBACK_SOURCE_PART}${suffix}`
+}
+
+function previousSourceSummarySlugFromIdentity(sourceIdentity: string): string {
const withoutExt = sourceIdentity.replace(/\.[^/.]+$/, "")
const parts = withoutExt
.split("/")
@@ -83,9 +110,10 @@ export function legacySourceSummarySlugFromIdentity(sourceIdentity: string): str
export function sourceSummarySlugCandidatesFromIdentity(sourceIdentity: string): string[] {
const canonical = sourceSummarySlugFromIdentity(sourceIdentity)
+ const previous = previousSourceSummarySlugFromIdentity(sourceIdentity)
const previousReadable = previousReadableSourceSummarySlugFromIdentity(sourceIdentity)
const legacy = legacySourceSummarySlugFromIdentity(sourceIdentity)
- return Array.from(new Set([canonical, previousReadable, legacy]))
+ return Array.from(new Set([canonical, previous, previousReadable, legacy]))
}
function previousReadableSourceSummarySlugFromIdentity(sourceIdentity: string): string {