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: detect truncated ingest analysis
nash_su6693da15f7d5
diff --git a/src/lib/ingest-queue.ts b/src/lib/ingest-queue.tsindex 9ac9c1a4..7778767e 100644--- a/src/lib/ingest-queue.ts+++ b/src/lib/ingest-queue.ts@@ -1040,6 +1040,17 @@ async function runTask(}const message = err instanceof Error ? err.message : String(err)+ if (+ err instanceof Error+ && "nonRetryable" in err+ && (err as Error & { nonRetryable?: unknown }).nonRetryable === true+ ) {+ task.status = "failed"+ task.error = message+ await saveQueue(projectPath)+ console.log(`[Ingest Queue] Failed without retry: ${task.sourcePath} — ${message}`)+ return+ }if (isUsageLimitError(message)) {task.status = "pending"task.error = `Paused after provider usage limit: ${message}`diff --git a/src/lib/ingest.prompt.test.ts b/src/lib/ingest.prompt.test.tsindex 05ad1792..241875c1 100644--- a/src/lib/ingest.prompt.test.ts+++ b/src/lib/ingest.prompt.test.ts@@ -4,6 +4,7 @@ import {buildGenerationPrompt,buildPageMergeSystemPrompt,computeIngestGenerationMaxTokens,+ computeIngestAnalysisMaxTokens,computeIngestReviewMaxTokens,computeIngestSourceBudget,formatIngestWarningLogEntry,@@ -203,6 +204,10 @@ describe("long-source ingest planning", () => {expect(computeIngestGenerationMaxTokens(128_000)).toBe(16_384)expect(computeIngestGenerationMaxTokens(256_000)).toBe(24_576)expect(computeIngestGenerationMaxTokens(1_000_000)).toBe(32_768)+ expect(computeIngestAnalysisMaxTokens(64_000)).toBe(4_096)+ expect(computeIngestAnalysisMaxTokens(128_000)).toBe(4_800)+ expect(computeIngestAnalysisMaxTokens(256_000)).toBe(8_192)+ expect(computeIngestAnalysisMaxTokens(1_000_000)).toBe(8_192)expect(computeIngestReviewMaxTokens(1_000_000)).toBe(8_192)})diff --git a/src/lib/ingest.ts b/src/lib/ingest.tsindex 82c27aed..6a3a8879 100644--- a/src/lib/ingest.ts+++ b/src/lib/ingest.ts@@ -10,7 +10,7 @@ import {listDirectory,} from "@/commands/fs"import { streamChat } from "@/lib/llm-client"-import type { LlmConfig } from "@/stores/wiki-store"+import type { LlmConfig, ReasoningConfig } from "@/stores/wiki-store"import { useWikiStore } from "@/stores/wiki-store"import { parseWithMineruResult } from "@/lib/mineru"import { useChatStore } from "@/stores/chat-store"@@ -54,10 +54,22 @@ const INGEST_GENERATION_TOKENS_DEFAULT = 8_192const INGEST_GENERATION_TOKENS_128K = 16_384const INGEST_GENERATION_TOKENS_256K = 24_576const INGEST_GENERATION_TOKENS_512K = 32_768+const INGEST_ANALYSIS_TOKENS_MIN = 4_096+const INGEST_ANALYSIS_TOKENS_MAX = 8_192+const CONSERVATIVE_CHARS_PER_OUTPUT_TOKEN = 4const REVIEW_STAGE_MIN_SIGNAL_CHARS = 10_000const REVIEW_STAGE_MIN_FILE_BLOCKS = 4const AGGREGATE_WIKI_PATHS = ["wiki/index.md", "wiki/overview.md", "wiki/log.md"] as const+export class NonRetryableIngestError extends Error {+ readonly nonRetryable = true++ constructor(message: string) {+ super(message)+ this.name = "NonRetryableIngestError"+ }+}+function appendSavedImageRefsForCaption(content: string, images: SavedImage[]): string {if (images.length === 0) return contentconst refs = images@@ -68,6 +80,33 @@ function appendSavedImageRefsForCaption(content: string, images: SavedImage[]):return `${content}\n\n## Referenced Local Images\n\n${refs.join("\n")}\n`}+function ingestAnalysisRequest(config: LlmConfig): {+ maxTokens: number+ reasoning: ReasoningConfig+} {+ const contentTokens = computeIngestAnalysisMaxTokens(config.maxContextSize)+ const requested = resolveIngestReasoning(config)+ const reasoning = requested.mode === "custom"+ ? {+ ...requested,+ budgetTokens: Math.max(+ 1_024,+ Math.min(requested.budgetTokens ?? 0, INGEST_ANALYSIS_TOKENS_MAX),+ ),+ }+ : requested+ const reasoningTokens = reasoning.mode === "low"+ ? 1_024+ : reasoning.mode === "medium"+ ? 4_096+ : reasoning.mode === "high" || reasoning.mode === "max"+ ? 8_192+ : reasoning.mode === "custom"+ ? reasoning.budgetTokens ?? 0+ : 0+ return { maxTokens: contentTokens + reasoningTokens, reasoning }+}+const ingestImageExtractionPromises = new Map<string, Promise<SavedImage[]>>()async function imageExtractionKey(@@ -1033,6 +1072,8 @@ async function autoIngestImpl(let analysis = precomputedAnalysisif (!analysis) {+ let analysisTruncated = false+ const analysisRequest = ingestAnalysisRequest(llmConfig)await streamChat(llmConfig,[@@ -1041,14 +1082,21 @@ async function autoIngestImpl(],{onToken: (token) => { analysis += token },- onDone: () => {},+ onDone: (completion) => { analysisTruncated = completion?.truncated === true },onError: (err) => {activity.updateItem(activityId, { status: "error", detail: `Analysis failed: ${err.message}` })},},signal,- { temperature: 0.1, reasoning: resolveIngestReasoning(llmConfig), max_tokens: 4096 },+ { temperature: 0.1, reasoning: analysisRequest.reasoning, max_tokens: analysisRequest.maxTokens },)+ if (analysisTruncated) {+ const message =+ `Analysis was truncated after reaching the ${analysisRequest.maxTokens.toLocaleString()} token output limit. ` ++ "Wiki pages were not generated from the incomplete analysis. Split the source or use a model with a larger output limit."+ activity.updateItem(activityId, { status: "error", detail: message })+ throw new NonRetryableIngestError(message)+ }}// A silent `return []` here would look like success to the queue@@ -2584,6 +2632,18 @@ export function computeIngestGenerationMaxTokens(maxContextSize: number | undefireturn INGEST_GENERATION_TOKENS_DEFAULT}+export function computeIngestAnalysisMaxTokens(maxContextSize: number | undefined): number {+ const { responseReserve } = computeContextBudget(maxContextSize)+ const reservedOutputTokens = Math.floor(+ responseReserve / CONSERVATIVE_CHARS_PER_OUTPUT_TOKEN,+ )+ return clampNumber(+ reservedOutputTokens,+ INGEST_ANALYSIS_TOKENS_MIN,+ INGEST_ANALYSIS_TOKENS_MAX,+ )+}+export function computeIngestReviewMaxTokens(maxContextSize: number | undefined): number {return Math.min(8_192, Math.max(4_096, Math.floor(computeIngestGenerationMaxTokens(maxContextSize) / 2)))}@@ -2914,6 +2974,7 @@ async function analyzeLongSourceInChunks(})}+ const analysisRequest = ingestAnalysisRequest(llmConfig)for (const chunk of chunks) {if (chunk.index <= completedThrough) continuethrowIfIngestAborted(signal, activityId)@@ -2923,6 +2984,7 @@ async function analyzeLongSourceInChunks(let raw = ""let hadError = false+ let analysisTruncated = falseawait streamChat(llmConfig,[@@ -2939,18 +3001,25 @@ async function analyzeLongSourceInChunks(],{onToken: (token) => { raw += token },- onDone: () => {},+ onDone: (completion) => { analysisTruncated = completion?.truncated === true },onError: (err) => {hadError = trueactivity.updateItem(activityId, { status: "error", detail: `Chunk analysis failed: ${err.message}` })},},signal,- { temperature: 0.1, reasoning: resolveIngestReasoning(llmConfig), max_tokens: 4096 },+ { temperature: 0.1, reasoning: analysisRequest.reasoning, max_tokens: analysisRequest.maxTokens },)throwIfIngestAborted(signal, activityId)if (hadError) throw new Error("Chunk analysis stream failed")+ if (analysisTruncated) {+ const message =+ `Chunk ${chunk.index}/${chunk.total} analysis was truncated after reaching the ` ++ `${analysisRequest.maxTokens.toLocaleString()} token output limit; the saved checkpoint will be retried`+ activity.updateItem(activityId, { status: "error", detail: message })+ throw new Error(message)+ }const chunkAnalysis = extractMarkedSection(raw, "Chunk Analysis") || raw.trim()const nextDigest = extractMarkedSection(raw, "Updated Global Digest")diff --git a/src/lib/llm-client.test.ts b/src/lib/llm-client.test.tsindex 9176e573..5511f194 100644--- a/src/lib/llm-client.test.ts+++ b/src/lib/llm-client.test.ts@@ -225,6 +225,109 @@ describe("streamChat — buffered streaming responses", () => {expect(onError).not.toHaveBeenCalled()})+ it("reports token-limit stream completion without discarding emitted content", async () => {+ const body = [+ openAiSseToken("partial analysis"),+ `data: ${JSON.stringify({ choices: [{ delta: {}, finish_reason: "length" }] })}`,+ "data: [DONE]",+ ].join("\n\n")+ mockHttpFetch.mockResolvedValue(new Response(body, {+ status: 200,+ headers: { "Content-Type": "text/event-stream" },+ }))+ const onToken = vi.fn()+ const onDone = vi.fn()+ const onError = vi.fn()++ await streamChat(+ customStreamingCfg,+ [{ role: "user", content: "hi" }],+ { onToken, onDone, onError },+ )++ expect(onToken).toHaveBeenCalledWith("partial analysis")+ expect(onDone).toHaveBeenCalledWith({ finishReason: "length", truncated: true })+ expect(onError).not.toHaveBeenCalled()+ })++ it.each([+ [+ "Anthropic",+ 'data: {"type":"message_delta","delta":{"stop_reason":"max_tokens"}}',+ "max_tokens",+ ],+ [+ "Gemini",+ 'data: {"candidates":[{"finishReason":"MAX_TOKENS"}]}',+ "MAX_TOKENS",+ ],+ ])("reports %s token-limit completion", async (_provider, terminal, reason) => {+ mockHttpFetch.mockResolvedValue(new Response([+ openAiSseToken("partial"),+ terminal,+ ].join("\n\n"), { status: 200 }))+ const onDone = vi.fn()++ await streamChat(+ customStreamingCfg,+ [{ role: "user", content: "hi" }],+ { onToken: vi.fn(), onDone, onError: vi.fn() },+ )++ expect(onDone).toHaveBeenCalledWith({ finishReason: reason, truncated: true })+ })++ it("reports a normal stop as complete", async () => {+ mockHttpFetch.mockResolvedValue(new Response([+ openAiSseToken("complete"),+ 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}',+ "data: [DONE]",+ ].join("\n\n"), { status: 200 }))+ const onDone = vi.fn()++ await streamChat(+ customStreamingCfg,+ [{ role: "user", content: "hi" }],+ { onToken: vi.fn(), onDone, onError: vi.fn() },+ )++ expect(onDone).toHaveBeenCalledWith({ finishReason: "stop", truncated: false })+ })++ it("reports token-limit completion for a non-streaming response", async () => {+ const config = { ...customStreamingCfg, streamingEnabled: false }+ mockHttpFetch.mockResolvedValue(new Response(JSON.stringify({+ choices: [{ message: { content: "partial" }, finish_reason: "length" }],+ }), { status: 200 }))+ const onDone = vi.fn()++ await streamChat(+ config,+ [{ role: "user", content: "hi" }],+ { onToken: vi.fn(), onDone, onError: vi.fn() },+ )++ expect(onDone).toHaveBeenCalledWith({ finishReason: "length", truncated: true })+ })++ it("reports an empty token-limited non-streaming response as truncated", async () => {+ const config = { ...customStreamingCfg, streamingEnabled: false }+ mockHttpFetch.mockResolvedValue(new Response(JSON.stringify({+ choices: [{ message: { content: "" }, finish_reason: "length" }],+ }), { status: 200 }))+ const onDone = vi.fn()+ const onError = vi.fn()++ await streamChat(+ config,+ [{ role: "user", content: "hi" }],+ { onToken: vi.fn(), onDone, onError },+ )++ expect(onDone).toHaveBeenCalledWith({ finishReason: "length", truncated: true })+ expect(onError).not.toHaveBeenCalled()+ })+it("normalizes escaped separators in a buffered SSE body", async () => {const body = [openAiSseToken("Hello"),diff --git a/src/lib/llm-client.ts b/src/lib/llm-client.tsindex 5e0cd519..7ac25d50 100644--- a/src/lib/llm-client.ts+++ b/src/lib/llm-client.ts@@ -10,25 +10,67 @@ export { isFetchNetworkError } from "./tauri-fetch"export interface StreamCallbacks {onToken: (token: string) => voidonReasoningToken?: (token: string) => void- onDone: () => void+ onDone: (completion?: StreamCompletion) => voidonError: (error: Error) => void}+export interface StreamCompletion {+ finishReason?: string+ truncated: boolean+}+function bufferedStreamCallbacks(callbacks: StreamCallbacks): StreamCallbacks {let content = ""let reasoning = ""return {onToken: (token) => { content += token },onReasoningToken: (token) => { reasoning += token },- onDone: () => {+ onDone: (completion) => {if (reasoning) callbacks.onReasoningToken?.(reasoning)if (content) callbacks.onToken(content)- callbacks.onDone()+ callbacks.onDone(completion)},onError: callbacks.onError,}}+function streamFinishReason(record: string): string | undefined {+ const payload = record.startsWith("data:") ? record.slice(5).trim() : record.trim()+ if (!payload.startsWith("{")) return undefined+ try {+ const value = JSON.parse(payload) as {+ choices?: Array<{ finish_reason?: string | null }>+ delta?: { stop_reason?: string | null }+ stop_reason?: string | null+ candidates?: Array<{ finishReason?: string | null }>+ }+ return value.choices?.[0]?.finish_reason+ ?? value.delta?.stop_reason+ ?? value.stop_reason+ ?? value.candidates?.[0]?.finishReason+ ?? undefined+ } catch {+ return undefined+ }+}++function responseFinishReason(payload: unknown): string | undefined {+ if (!payload || typeof payload !== "object") return undefined+ const value = payload as {+ choices?: Array<{ finish_reason?: string | null }>+ stop_reason?: string | null+ candidates?: Array<{ finishReason?: string | null }>+ }+ return value.choices?.[0]?.finish_reason+ ?? value.stop_reason+ ?? value.candidates?.[0]?.finishReason+ ?? undefined+}++function isTokenLimitFinishReason(reason: string | undefined): boolean {+ return Boolean(reason && /^(length|max_tokens|max_output_tokens)$/i.test(reason))+}+// Lazy import keeps the Tauri event/invoke bindings out of bundles that// never touch the subprocess provider (e.g. vitest with a fetch mock).async function streamViaClaudeCodeCli(@@ -307,12 +349,17 @@ export async function streamChat(try {const payload: unknown = await response.json()const content = providerConfig.parseResponse(payload)+ const finishReason = responseFinishReason(payload)if (!content) {+ if (isTokenLimitFinishReason(finishReason)) {+ onDone({ finishReason, truncated: true })+ return+ }onError(new Error("Model returned an empty non-streaming response"))return}onToken(content)- onDone()+ onDone({ finishReason, truncated: isTokenLimitFinishReason(finishReason) })} catch (err) {if (timeoutFired) {onError(new Error(`Request timed out after ${Math.round(timeoutMs / 60000)} min. Try a faster model or a smaller context.`))@@ -359,6 +406,7 @@ export async function streamChat(// detector.ts.let contentCharsEmitted = 0let reasoningCharsObserved = 0+ let finishReason: string | undefinedconst recordToken = (text: string) => {contentCharsEmitted += text.lengthonToken(text)@@ -374,6 +422,7 @@ export async function streamChat(if (!trimmed) return nullreasoningCharsObserved += countReasoningCharsInLine(trimmed)+ finishReason = streamFinishReason(trimmed) ?? finishReasonrecordReasoning(trimmed)const token = providerConfig.parseStream(trimmed)if (token !== null) {@@ -429,6 +478,10 @@ export async function streamChat(// no clue why). Threshold guards against single-stray-byte// false positives from spurious empty `reasoning:""` deltas.const REASONING_DIAGNOSTIC_THRESHOLD = 200+ if (contentCharsEmitted === 0 && isTokenLimitFinishReason(finishReason)) {+ onDone({ finishReason, truncated: true })+ return+ }if (contentCharsEmitted === 0 &&reasoningCharsObserved >= REASONING_DIAGNOSTIC_THRESHOLD@@ -444,7 +497,7 @@ export async function streamChat(return}- onDone()+ onDone({ finishReason, truncated: isTokenLimitFinishReason(finishReason) })} catch (err) {// The abort can reach us two ways: a real AbortError, or — when the// Tauri HTTP plugin tears down the body stream — a bare *string*