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: stop dedup scan hanging to the 30-min backstop ("request cancelled")

Kostadis Rousoss253771b2de19
diff --git a/src/lib/dedup-runner.test.ts b/src/lib/dedup-runner.test.ts
new file mode 100644
index 00000000..e8661a6e
--- /dev/null
+++ b/src/lib/dedup-runner.test.ts
@@ -0,0 +1,91 @@
+/**
+ * Unit coverage for `buildDedupLlmCall`. Mocks streamChat so we can
+ * pin the request overrides it forwards — specifically that dedup
+ * (like every other structured-output caller) disables thinking. A
+ * reasoning-capable model left thinking-on burns its whole budget on
+ * chain-of-thought and ends the stream with empty content, which on
+ * the scan path runs silently to the 30-min backstop and surfaces as
+ * a bare "Request cancelled".
+ */
+import { describe, it, expect, vi, beforeEach } from "vitest"
+
+// vi.mock is hoisted above imports; vi.hoisted keeps the fn out of the TDZ.
+const { mockStreamChat } = vi.hoisted(() => ({ mockStreamChat: vi.fn() }))
+vi.mock("./llm-client", async () => {
+ const actual = await vi.importActual<typeof import("./llm-client")>("./llm-client")
+ return { ...actual, streamChat: mockStreamChat }
+})
+
+import { buildDedupLlmCall } from "./dedup-runner"
+import type { LlmConfig } from "@/stores/wiki-store"
+
+const cfg: LlmConfig = {
+ provider: "ollama",
+ apiKey: "",
+ model: "qwen3:8b",
+ ollamaUrl: "http://localhost:11434",
+ customEndpoint: "",
+ apiMode: "chat_completions",
+ maxContextSize: 8192,
+}
+
+beforeEach(() => {
+ mockStreamChat.mockReset()
+})
+
+describe("buildDedupLlmCall", () => {
+ it("disables thinking and caps output so reasoning models answer instead of streaming chain-of-thought to the backstop", async () => {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => {
+ cb.onToken('{"groups": []}')
+ cb.onDone()
+ })
+
+ const call = buildDedupLlmCall(cfg, 8192)
+ const out = await call("system prompt", "user message", undefined)
+ expect(out).toBe('{"groups": []}')
+
+ const overrides = mockStreamChat.mock.calls[0][4]
+ expect(overrides).toMatchObject({
+ temperature: 0.1,
+ reasoning: { mode: "off" },
+ max_tokens: 8192,
+ })
+ })
+
+ it("forwards the caller's max_tokens budget (detection small, merge generous)", async () => {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => cb.onDone())
+
+ await buildDedupLlmCall(cfg, 32768)("s", "u", undefined)
+ expect(mockStreamChat.mock.calls[0][4]).toMatchObject({ max_tokens: 32768 })
+ })
+
+ it("forces reasoning off even when the config requests a thinking mode", async () => {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => cb.onDone())
+
+ const reasoningCfg: LlmConfig = { ...cfg, reasoning: { mode: "high" } }
+ await buildDedupLlmCall(reasoningCfg, 8192)("s", "u", undefined)
+
+ expect(mockStreamChat.mock.calls[0][4]).toMatchObject({
+ reasoning: { mode: "off" },
+ })
+ })
+
+ it("forwards the abort signal through to streamChat", async () => {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => cb.onDone())
+ const controller = new AbortController()
+
+ await buildDedupLlmCall(cfg, 8192)("s", "u", controller.signal)
+
+ expect(mockStreamChat.mock.calls[0][3]).toBe(controller.signal)
+ })
+
+ it("rethrows when streamChat reports an error (no silent empty result)", async () => {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => {
+ cb.onError(new Error("HTTP 500: model unavailable"))
+ })
+
+ await expect(buildDedupLlmCall(cfg, 8192)("s", "u", undefined)).rejects.toThrow(
+ /HTTP 500: model unavailable/,
+ )
+ })
+})
diff --git a/src/lib/dedup-runner.ts b/src/lib/dedup-runner.ts
index c81a055a..2d45635d 100644
--- a/src/lib/dedup-runner.ts
+++ b/src/lib/dedup-runner.ts
@@ -9,6 +9,28 @@ import { streamChat } from "@/lib/llm-client"
import { normalizePath } from "@/lib/path-utils"
import type { LlmConfig } from "@/stores/wiki-store"
import type { FileNode } from "@/types/wiki"
+
+/**
+ * Detection emits a bounded JSON list of duplicate groups — a few tens
+ * of tokens per group — so a modest cap covers even a very duplicate-
+ * heavy wiki. The cap's real job is a safety net: without it, a model
+ * that ignores the reasoning-off lever (an unrecognized reasoning model
+ * behind a custom endpoint, e.g. a vLLM Nemotron build) could stream
+ * chain-of-thought unbounded until the 30-min backstop fires — which
+ * surfaces to the user as a bare "request cancelled". Capping turns a
+ * 30-min hang into a fast (truncated) response instead.
+ */
+const DEDUP_DETECTION_MAX_TOKENS = 8_192
+
+/**
+ * Merge rewrites a COMPLETE page that gets written to disk, so it needs
+ * a generous cap that won't truncate the canonical content. 16K tokens
+ * is ~64KB of text — far beyond any realistic merged entity/concept
+ * page — while still bounding a runaway short of the 30-min backstop.
+ * Kept local (not the ingest generation ladder) so this module doesn't
+ * drag in the heavy ingest dependency graph.
+ */
+const DEDUP_MERGE_MAX_TOKENS = 16_384
import {
detectDuplicateGroups,
extractEntitySummary,
@@ -25,8 +47,17 @@ import { loadNotDuplicates } from "./dedup-storage"
* Wrap streamChat into the (system, user, signal) → string shape
* the dedup module expects. Same pattern page-merge uses — keeps
* the algorithm modules free of any LlmConfig knowledge.
+ *
+ * `maxTokens` is required, not defaulted: detection and merge have
+ * very different output-size needs (a tiny JSON list vs. a complete
+ * rewritten page), and silently sharing one cap risks truncating a
+ * merged page on disk. Forcing each caller to state its budget makes
+ * that choice explicit.
*/
-export function buildDedupLlmCall(llmConfig: LlmConfig): DedupLlmCall {
+export function buildDedupLlmCall(
+ llmConfig: LlmConfig,
+ maxTokens: number,
+): DedupLlmCall {
return async (systemPrompt, userMessage, signal) => {
let result = ""
let streamError: Error | null = null
@@ -48,7 +79,14 @@ export function buildDedupLlmCall(llmConfig: LlmConfig): DedupLlmCall {
},
},
signal,
- { temperature: 0.1 },
+ // Dedup detection + merge want JSON, never chain-of-thought.
+ // Like every other structured caller (ingest, connection-tests,
+ // vision-caption, anytxt-search), disable thinking AND cap output
+ // so a reasoning-capable model (an Ollama thinking model, or an
+ // unrecognized reasoning model behind a custom endpoint) doesn't
+ // spend its whole budget on reasoning and run the stream to the
+ // 30-min backstop — which surfaces as a bare "Request cancelled".
+ { temperature: 0.1, reasoning: { mode: "off" }, max_tokens: maxTokens },
).catch((err) => {
streamError = err instanceof Error ? err : new Error(String(err))
resolve()
@@ -139,7 +177,7 @@ export async function runDuplicateDetection(
const summaries = await loadAllEntitySummaries(projectPath)
if (summaries.length < 2) return []
const notDup = await loadNotDuplicates(projectPath)
- const llm = buildDedupLlmCall(llmConfig)
+ const llm = buildDedupLlmCall(llmConfig, DEDUP_DETECTION_MAX_TOKENS)
return detectDuplicateGroups(summaries, llm, {
signal: options.signal,
notDuplicates: notDup,
@@ -198,7 +236,10 @@ export async function executeMerge(
const groupPaths = new Set(groupPages.map((p) => p.path))
const otherPages = allPages.filter((p) => !groupPaths.has(p.path))
- const llm = buildDedupLlmCall(llmConfig)
+ // Merge rewrites a COMPLETE page that gets written to disk, so it gets
+ // the generous merge budget — never the small detection cap, which
+ // would truncate the canonical content.
+ const llm = buildDedupLlmCall(llmConfig, DEDUP_MERGE_MAX_TOKENS)
const result = await mergeDuplicateGroup(
{
group: groupPages,
diff --git a/src/lib/llm-client.test.ts b/src/lib/llm-client.test.ts
index f0fcc222..8ec0d227 100644
--- a/src/lib/llm-client.test.ts
+++ b/src/lib/llm-client.test.ts
@@ -1,5 +1,16 @@
-import { describe, it, expect } from "vitest"
-import { isFetchNetworkError } from "./llm-client"
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
+
+// Stub getHttpFetch so streamChat hits our in-test responder; keep the
+// rest of tauri-fetch (notably isFetchNetworkError) real so the existing
+// cross-webview tests below still exercise the genuine classifier.
+const mockHttpFetch = vi.fn<(url: string, opts?: RequestInit) => Promise<Response>>()
+vi.mock("./tauri-fetch", async () => {
+ const actual = await vi.importActual<typeof import("./tauri-fetch")>("./tauri-fetch")
+ return { ...actual, getHttpFetch: () => Promise.resolve(mockHttpFetch) }
+})
+
+import { isFetchNetworkError, streamChat } from "./llm-client"
+import type { LlmConfig } from "@/stores/wiki-store"
/**
* Guards for cross-webview error detection. Tauri renders the frontend
@@ -50,3 +61,109 @@ describe("isFetchNetworkError — cross-webview fetch failures", () => {
expect(isFetchNetworkError({ message: "Load failed" })).toBe(false)
})
})
+
+/**
+ * The streaming-path abort handling. When the 30-min backstop fires
+ * mid-stream the Tauri HTTP plugin tears the body stream down with a
+ * BARE STRING "Request cancelled" (controller.error(string)), not an
+ * Error. The old guard only matched `err instanceof Error`, so that
+ * string fell through to the generic branch and surfaced verbatim —
+ * exactly the cryptic "request cancelled" the dedup scan showed. These
+ * pin down that the string is now recognized as an abort and mapped to
+ * the actionable timeout message (or a silent cancel when no backstop).
+ */
+const cfg: LlmConfig = {
+ provider: "ollama",
+ apiKey: "",
+ model: "qwen3:8b",
+ ollamaUrl: "http://localhost:11434",
+ customEndpoint: "",
+ apiMode: "chat_completions",
+ maxContextSize: 8192,
+}
+
+/** A Response whose reader.read() stays pending until we reject it,
+ * letting the test interleave the 30-min backstop before the abort.
+ * `readCalled` resolves once streamChat reaches read(), so the test
+ * can await it instead of guessing how many microtasks to flush. */
+function pendingStreamResponse(): {
+ response: Response
+ getReject: () => (e: unknown) => void
+ readCalled: Promise<void>
+} {
+ let reject!: (e: unknown) => void
+ let signalReadCalled!: () => void
+ const readCalled = new Promise<void>((res) => { signalReadCalled = res })
+ const reader = {
+ read: () =>
+ new Promise<never>((_resolve, rej) => {
+ reject = rej
+ signalReadCalled()
+ }),
+ releaseLock: () => {},
+ cancel: () => {},
+ }
+ const response = {
+ ok: true,
+ body: { getReader: () => reader },
+ } as unknown as Response
+ return { response, getReject: () => reject, readCalled }
+}
+
+describe("streamChat — mid-stream abort mapping", () => {
+ beforeEach(() => {
+ mockHttpFetch.mockReset()
+ vi.useFakeTimers()
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it("maps the plugin's bare-string abort to the timeout message when the 30-min backstop fired", async () => {
+ const { response, getReject, readCalled } = pendingStreamResponse()
+ mockHttpFetch.mockResolvedValue(response)
+
+ const onError = vi.fn()
+ const onDone = vi.fn()
+ const promise = streamChat(
+ cfg,
+ [{ role: "user", content: "hi" }],
+ { onToken: vi.fn(), onDone, onError },
+ undefined,
+ {},
+ )
+
+ // Wait until streamChat is parked in read(), then fire the long-horizon
+ // backstop and let the plugin error the stream with its bare string.
+ await readCalled
+ await vi.advanceTimersByTimeAsync(30 * 60 * 1000)
+ getReject()("Request cancelled")
+ await promise
+
+ expect(onError).toHaveBeenCalledTimes(1)
+ expect(onError.mock.calls[0][0].message).toMatch(/timed out after 30 min/)
+ expect(onDone).not.toHaveBeenCalled()
+ })
+
+ it("treats a bare-string abort as a silent cancel when the backstop did NOT fire", async () => {
+ const { response, getReject, readCalled } = pendingStreamResponse()
+ mockHttpFetch.mockResolvedValue(response)
+
+ const onError = vi.fn()
+ const onDone = vi.fn()
+ const promise = streamChat(
+ cfg,
+ [{ role: "user", content: "hi" }],
+ { onToken: vi.fn(), onDone, onError },
+ undefined,
+ {},
+ )
+
+ await readCalled
+ getReject()("Request cancelled")
+ await promise
+
+ expect(onDone).toHaveBeenCalledTimes(1)
+ expect(onError).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/lib/llm-client.ts b/src/lib/llm-client.ts
index 616c9f7e..68e8a70f 100644
--- a/src/lib/llm-client.ts
+++ b/src/lib/llm-client.ts
@@ -256,7 +256,23 @@ export async function streamChat(
onDone()
} catch (err) {
- if (err instanceof Error && (err.name === "AbortError" || (signal?.aborted))) {
+ // The abort can reach us two ways: a real AbortError, or — when the
+ // Tauri HTTP plugin tears down the body stream — a bare *string*
+ // "Request cancelled" passed to controller.error(). The latter is not
+ // an Error, so the old `err instanceof Error` guard let it fall through
+ // to the generic branch and surface verbatim. Recognize both shapes.
+ const isAbort =
+ signal?.aborted ||
+ timeoutFired ||
+ (err instanceof Error && err.name === "AbortError") ||
+ (err instanceof Error ? err.message : String(err)) === "Request cancelled"
+ if (isAbort) {
+ // Mirror the pre-fetch catch: distinguish our long-horizon backstop
+ // (an actionable timeout) from a user-initiated cancel (silent).
+ if (timeoutFired) {
+ onError(new Error(`Request timed out after ${Math.round(timeoutMs / 60000)} min. Try a faster model or a smaller context.`))
+ return
+ }
onDone()
return
}