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: surface "model thought but never answered" with a real diagnostic
nash_su654fe45019da
diff --git a/src/lib/llm-client.ts b/src/lib/llm-client.tsindex 140aa3dd..4c43ab62 100644--- a/src/lib/llm-client.ts+++ b/src/lib/llm-client.ts@@ -1,6 +1,7 @@import type { LlmConfig } from "@/stores/wiki-store"import { getProviderConfig, type RequestOverrides } from "./llm-providers"import { getHttpFetch, isFetchNetworkError } from "./tauri-fetch"+import { countReasoningCharsInLine } from "./reasoning-detector"export type { ChatMessage, RequestOverrides } from "./llm-providers"export { isFetchNetworkError } from "./tauri-fetch"@@ -147,14 +148,33 @@ export async function streamChat(const reader = response.body.getReader()let lineBuffer = ""+ // Diagnostic counters. Some OpenAI-compatible endpoints stream+ // chain-of-thought through a `reasoning_content` (DeepSeek-R1,+ // Kimi K2.x) or `reasoning` (Qwen-flavored deployments) field+ // and only put the actual answer in `delta.content` after+ // thinking ends. Misbehaving endpoints sometimes emit kilobytes+ // of reasoning and end the stream with no content at all,+ // leaving the user with a silent empty analysis. We track the+ // two channels separately so the stream-end path can tell the+ // difference between "model said nothing" and "model thought+ // out loud but never produced an answer". See reasoning-+ // detector.ts.+ let contentCharsEmitted = 0+ let reasoningCharsObserved = 0+ const recordToken = (text: string) => {+ contentCharsEmitted += text.length+ onToken(text)+ }+try {while (true) {const { done, value } = await reader.read()if (done) {if (lineBuffer.trim()) {+ reasoningCharsObserved += countReasoningCharsInLine(lineBuffer.trim())const token = providerConfig.parseStream(lineBuffer.trim())- if (token !== null) onToken(token)+ if (token !== null) recordToken(token)}break}@@ -165,11 +185,34 @@ export async function streamChat(for (const line of lines) {const trimmed = line.trim()if (!trimmed) continue+ reasoningCharsObserved += countReasoningCharsInLine(trimmed)const token = providerConfig.parseStream(trimmed)- if (token !== null) onToken(token)+ if (token !== null) recordToken(token)}}+ // Stream ended cleanly. If the model produced thinking tokens+ // but no actual answer, surface that as a clear diagnostic+ // instead of letting the caller silently see "" (which usually+ // surfaces several layers up as "analysis not available" with+ // no clue why). Threshold guards against single-stray-byte+ // false positives from spurious empty `reasoning:""` deltas.+ const REASONING_DIAGNOSTIC_THRESHOLD = 200+ if (+ contentCharsEmitted === 0 &&+ reasoningCharsObserved >= REASONING_DIAGNOSTIC_THRESHOLD+ ) {+ onError(+ new Error(+ `Model produced ${reasoningCharsObserved.toLocaleString()} characters of reasoning / chain-of-thought, but no actual response content. ` ++ `This usually means the endpoint hit a thinking-token limit, the model didn't transition from thinking to answering, ` ++ `or the endpoint is misbehaving (the official Anthropic / OpenAI APIs don't have this issue). ` ++ `Try a shorter input, increase max_tokens, or switch to a different model in Settings.`,+ ),+ )+ return+ }+onDone()} catch (err) {if (err instanceof Error && (err.name === "AbortError" || (signal?.aborted))) {diff --git a/src/lib/reasoning-detector.test.ts b/src/lib/reasoning-detector.test.tsnew file mode 100644index 00000000..e02f9ce1--- /dev/null+++ b/src/lib/reasoning-detector.test.ts@@ -0,0 +1,71 @@+import { describe, it, expect } from "vitest"+import { countReasoningCharsInLine } from "./reasoning-detector"++describe("countReasoningCharsInLine", () => {+ it("returns 0 for empty / non-stream lines", () => {+ expect(countReasoningCharsInLine("")).toBe(0)+ expect(countReasoningCharsInLine("data: [DONE]")).toBe(0)+ expect(countReasoningCharsInLine("not even json")).toBe(0)+ })++ it("returns 0 when only `content` is present (the normal happy path)", () => {+ const line =+ 'data: {"choices":[{"index":0,"delta":{"content":"hello"},"finish_reason":null}]}'+ expect(countReasoningCharsInLine(line)).toBe(0)+ })++ it("counts chars in `reasoning_content` (DeepSeek-R1 / Kimi K2.6 convention)", () => {+ const line =+ 'data: {"choices":[{"index":0,"delta":{"reasoning_content":"thinking"}}]}'+ expect(countReasoningCharsInLine(line)).toBe("thinking".length)+ })++ it("counts chars in `reasoning` (the user's Qwen3.5-122B endpoint)", () => {+ const line =+ 'data: {"choices":[{"index":0,"delta":{"reasoning":"Let me think..."}}]}'+ expect(countReasoningCharsInLine(line)).toBe("Let me think...".length)+ })++ it("doesn't double-count `reasoning_content` as `reasoning`", () => {+ // Defensive: only one of the two fields ever appears per chunk+ // in real-world endpoints, but if both showed up we'd count+ // each exactly once.+ const line =+ 'data: {"choices":[{"delta":{"reasoning":"abc","reasoning_content":"xyz"}}]}'+ expect(countReasoningCharsInLine(line)).toBe(6)+ })++ it("ignores other fields whose names contain `reasoning` substring", () => {+ // e.g. a hypothetical `reasoning_done: true` flag — we only+ // want string-valued reasoning fields. The regex requires `:`+ // immediately followed by a quoted string, so this is safe.+ const line = 'data: {"reasoning_done":true,"delta":{"content":"hi"}}'+ expect(countReasoningCharsInLine(line)).toBe(0)+ })++ it("handles JSON string escapes in the reasoning text", () => {+ // The escaped-length is what we count (we don't decode); for+ // a "\n" escape sequence that's 2 chars, not 1. Acceptable+ // for the diagnostic threshold check.+ const line =+ 'data: {"choices":[{"delta":{"reasoning":"line one\\nline two"}}]}'+ expect(countReasoningCharsInLine(line)).toBe("line one\\nline two".length)+ })++ it("returns 0 for malformed JSON without crashing", () => {+ expect(countReasoningCharsInLine('data: {"reasoning":')).toBe(0)+ expect(countReasoningCharsInLine('{"unclosed: "string"}')).toBe(0)+ })++ it("works on a real Kimi K2.6 chunk (reasoning_content path)", () => {+ const line =+ 'data: {"id":"chatcmpl-abc","choices":[{"index":0,"delta":{"reasoning_content":"用户"},"finish_reason":null}]}'+ expect(countReasoningCharsInLine(line)).toBe("用户".length)+ })++ it("works on a real Qwen3.5 chunk (the user's reported case)", () => {+ const line =+ 'data: {"id":"chatcmpl-b5152c89f36f8aa7","object":"chat.completion.chunk","model":"Qwen3.5-122B","choices":[{"index":0,"delta":{"reasoning":"Thinking"},"logprobs":null,"finish_reason":null}]}'+ expect(countReasoningCharsInLine(line)).toBe("Thinking".length)+ })+})diff --git a/src/lib/reasoning-detector.ts b/src/lib/reasoning-detector.tsnew file mode 100644index 00000000..dec3d68f--- /dev/null+++ b/src/lib/reasoning-detector.ts@@ -0,0 +1,48 @@+/**+ * Diagnostic helper for "model emitted thinking but no actual answer"+ * symptoms.+ *+ * Some OpenAI-compatible endpoints (DeepSeek-R1, Kimi K2.x, Qwen+ * reasoning models, various third-party deployments) stream the+ * model's chain-of-thought through a non-content delta field —+ * either `reasoning_content` (DeepSeek/Kimi convention) or just+ * `reasoning` (some Qwen-flavored deployments). The user-facing+ * answer normally appears in `delta.content` AFTER the thinking+ * phase completes.+ *+ * When an endpoint misbehaves (max_tokens too small, server-side+ * thinking budget exhaustion, model bug) it can emit megabytes of+ * reasoning text and then end the stream with no content at all.+ * The streaming layer's parser correctly ignores reasoning fields+ * (we don't want to leak chain-of-thought into the user's wiki+ * output), but it leaves us with a silent empty-analysis result —+ * the user sees a meaningless "analysis not available" with no+ * actionable diagnosis.+ *+ * This helper does ONE thing: tally the byte-length of reasoning+ * text seen on a raw SSE line, so the streaming layer can+ * distinguish two stream-end states:+ *+ * - 0 content + 0 reasoning → plain empty response, network /+ * auth / rate-limit territory; the existing error paths cover+ * this.+ * - 0 content + N>>0 reasoning → the diagnostic case above;+ * surface "model only produced N chars of thinking, no final+ * answer" instead of silently emptying the analysis.+ *+ * Implementation note: counts the JSON-escaped form's length+ * (e.g. `\\n` counts as 2). Close enough for a threshold check —+ * we're distinguishing "0 vs hundreds of chars", not measuring+ * exact tokens.+ */++const REASONING_FIELD_RE =+ /"reasoning(?:_content)?"\s*:\s*"((?:[^"\\]|\\.)*)"/g++export function countReasoningCharsInLine(rawLine: string): number {+ let total = 0+ for (const match of rawLine.matchAll(REASONING_FIELD_RE)) {+ total += match[1].length+ }+ return total+}