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
release: v0.4.7
nash_sucddc1b7c0255
diff --git a/package-lock.json b/package-lock.jsonindex 60c73a82..04ff7798 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "llm-wiki",- "version": "0.4.6",+ "version": "0.4.7","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "llm-wiki",- "version": "0.4.6",+ "version": "0.4.7","dependencies": {"@base-ui/react": "^1.3.0","@fontsource-variable/geist": "^5.2.8",diff --git a/package.json b/package.jsonindex 2f591c5a..ef9ca14e 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "llm-wiki","private": true,- "version": "0.4.6",+ "version": "0.4.7","type": "module","scripts": {"dev": "vite",diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex fa824f6a..0c3e8851 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -4420,7 +4420,7 @@ checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"[[package]]name = "llm-wiki"-version = "0.4.6"+version = "0.4.7"dependencies = ["arrow-array","arrow-schema",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 7176bc6f..acb8e038 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "llm-wiki"-version = "0.4.6"+version = "0.4.7"description = "LLM Wiki - A personal knowledge base for LLM concepts"authors = []edition = "2021"diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex f470b841..2cd8b6ab 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "LLM Wiki",- "version": "0.4.6",+ "version": "0.4.7","identifier": "com.llmwiki.app","build": {"beforeDevCommand": "npm run dev",diff --git a/src/App.tsx b/src/App.tsxindex e4f63f5e..f3a6fdc6 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -218,10 +218,6 @@ function App() {if (savedMultimodalConfig) {useWikiStore.getState().setMultimodalConfig(savedMultimodalConfig)}- const savedOutputLang = await loadOutputLanguage()- if (savedOutputLang) {- useWikiStore.getState().setOutputLanguage(savedOutputLang)- }const savedProxy = await loadProxyConfig()if (savedProxy) {useWikiStore.getState().setProxyConfig(savedProxy)@@ -257,6 +253,8 @@ function App() {await resetProjectState()setProject(proj)+ const projectOutputLang = await loadOutputLanguage(proj.id)+ useWikiStore.getState().setOutputLanguage(projectOutputLang ?? "auto")setSelectedFile(null)setActiveView("wiki")// Bump data version so any cached graphs/views invalidatediff --git a/src/components/chat/chat-input.tsx b/src/components/chat/chat-input.tsxindex 74851167..a8ade743 100644--- a/src/components/chat/chat-input.tsx+++ b/src/components/chat/chat-input.tsx@@ -51,6 +51,7 @@ export function ChatInput({ onSend, onStop, isStreaming, placeholder }: ChatInpu<textarearef={textareaRef}value={value}+ dir="auto"onChange={handleInput}onKeyDown={handleKeyDown}placeholder={placeholder ?? "Type a message... (Enter to send, Shift+Enter for newline)"}diff --git a/src/components/chat/chat-message.tsx b/src/components/chat/chat-message.tsxindex ac2ad505..ae23d8eb 100644--- a/src/components/chat/chat-message.tsx+++ b/src/components/chat/chat-message.tsx@@ -21,6 +21,8 @@ import { makeQueryFileName } from "@/lib/wiki-filename"import { hasUsableLlm } from "@/lib/has-usable-llm"import { resolveMarkdownImageSrc } from "@/lib/markdown-image-resolver"import { findRawSourceForImage, imageUrlToAbsolute } from "@/lib/raw-source-resolver"+import { detectLanguage } from "@/lib/detect-language"+import { getHtmlLang, getTextDirection } from "@/lib/language-metadata"import { MermaidDiagram, unwrapMermaidPre } from "@/components/mermaid-diagram"// Module-level cache of source file names@@ -94,7 +96,7 @@ export function ChatMessage({ message, isLastAssistant, onRegenerate }: ChatMess}`}>{isUser ? (- <p className="whitespace-pre-wrap break-words">{message.content}</p>+ <p dir="auto" className="whitespace-pre-wrap break-words">{message.content}</p>) : (<MarkdownContent content={message.content} />)}@@ -654,11 +656,19 @@ function MarkdownContent({ content }: { content: string }) {// Separate thinking blocks from main contentconst { thinking, answer } = useMemo(() => separateThinking(cleaned), [cleaned])const processed = useMemo(() => processContent(answer), [answer])+ const renderLanguage = useMemo(() => detectLanguage(answer), [answer])+ const direction = getTextDirection(renderLanguage)+ const htmlLang = getHtmlLang(renderLanguage)return (<div>{thinking && <ThinkingBlock content={thinking} />}- <div className="chat-markdown prose prose-sm max-w-none dark:prose-invert prose-p:my-1 prose-headings:my-2 prose-ul:my-1 prose-ol:my-1 prose-li:my-0 prose-pre:my-2 prose-code:text-xs prose-code:before:content-none prose-code:after:content-none">+ <div+ className="chat-markdown prose prose-sm max-w-none dark:prose-invert prose-p:my-1 prose-headings:my-2 prose-ul:my-1 prose-ol:my-1 prose-li:my-0 prose-pre:my-2 prose-code:text-xs prose-code:before:content-none prose-code:after:content-none"+ dir={direction}+ lang={htmlLang}+ style={{ textAlign: "start" }}+ ><ReactMarkdownremarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}@@ -692,7 +702,7 @@ function MarkdownContent({ content }: { content: string }) {<thead className="bg-muted" {...props}>{children}</thead>),th: ({ children, ...props }) => (- <th className="border border-border/80 px-3 py-1.5 text-left font-semibold bg-muted" {...props}>{children}</th>+ <th className="border border-border/80 px-3 py-1.5 text-start font-semibold bg-muted" {...props}>{children}</th>),td: ({ children, ...props }) => (<td className="border border-border/60 px-3 py-1.5" {...props}>{children}</td>@@ -700,7 +710,16 @@ function MarkdownContent({ content }: { content: string }) {pre: ({ children, ...props }) => {const mermaid = unwrapMermaidPre(children)if (mermaid) return <>{mermaid}</>- return <pre className="rounded bg-background/50 p-2 text-xs overflow-x-auto" {...props}>{children}</pre>+ return (+ <pre+ dir="ltr"+ className="rounded bg-background/50 p-2 text-xs overflow-x-auto"+ style={{ textAlign: "left" }}+ {...props}+ >+ {children}+ </pre>+ )},code: ({ className, children, ...props }) => {const lang = className?.replace("language-", "")@@ -708,7 +727,7 @@ function MarkdownContent({ content }: { content: string }) {if (lang === "mermaid") {return <MermaidDiagram code={codeText} />}- return <code className={className} {...props}>{children}</code>+ return <code dir="ltr" className={className} {...props}>{children}</code>},}}>diff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsxindex 078f42c9..65ef8ad5 100644--- a/src/components/chat/chat-panel.tsx+++ b/src/components/chat/chat-panel.tsx@@ -379,16 +379,38 @@ export function ChatPanel() {abortRef.current = controllerlet accumulated = ""+ let thinkingOpen = false++ const appendReasoning = (token: string) => {+ if (!token) return+ if (!thinkingOpen) {+ thinkingOpen = true+ accumulated += "<think>"+ appendStreamToken("<think>")+ }+ accumulated += token+ appendStreamToken(token)+ }++ const closeReasoning = () => {+ if (!thinkingOpen) return+ thinkingOpen = false+ accumulated += "</think>"+ appendStreamToken("</think>")+ }await streamChat(llmConfig,llmMessages,{onToken: (token) => {+ closeReasoning()accumulated += tokenappendStreamToken(token)},+ onReasoningToken: appendReasoning,onDone: () => {+ closeReasoning()finalizeStream(accumulated, queryRefs)abortRef.current = null// save-worthy detection removed — user has direct "Save to Wiki" button on each message@@ -521,4 +543,3 @@ export function ChatPanel() {</div>)}-diff --git a/src/components/editor/file-preview.tsx b/src/components/editor/file-preview.tsxindex f44142b6..da8e5296 100644--- a/src/components/editor/file-preview.tsx+++ b/src/components/editor/file-preview.tsx@@ -17,6 +17,8 @@ import { getFileCategory, getCodeLanguage } from "@/lib/file-types"import type { FileCategory } from "@/lib/file-types"import { getFileName } from "@/lib/path-utils"import { resolveMarkdownImageSrc } from "@/lib/markdown-image-resolver"+import { detectLanguage } from "@/lib/detect-language"+import { getHtmlLang, getTextDirection } from "@/lib/language-metadata"import { parseFrontmatter } from "@/lib/frontmatter"import { FrontmatterPanel } from "@/components/editor/frontmatter-panel"import { useWikiStore } from "@/stores/wiki-store"@@ -123,6 +125,9 @@ function TextPreview({ filePath, content, label }: { filePath: string; content:const scrollRootRef = useRef<HTMLDivElement | null>(null)const { frontmatter, body } = useMemo(() => parseFrontmatter(content), [content])+ const renderLanguage = useMemo(() => detectLanguage(body), [body])+ const direction = getTextDirection(renderLanguage)+ const htmlLang = getHtmlLang(renderLanguage)// Consume `pendingScrollImageSrc` once the file has rendered.// We re-scan the DOM whenever:@@ -185,7 +190,12 @@ function TextPreview({ filePath, content, label }: { filePath: string; content:<span className="rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase">{label}</span></div>{frontmatter && <FrontmatterPanel data={frontmatter} />}- <div className="prose prose-sm max-w-none dark:prose-invert">+ <div+ className="prose prose-sm max-w-none dark:prose-invert"+ dir={direction}+ lang={htmlLang}+ style={{ textAlign: "start" }}+ ><ReactMarkdownremarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}@@ -219,7 +229,7 @@ function TextPreview({ filePath, content, label }: { filePath: string; content:<thead className="bg-muted" {...props}>{children}</thead>),th: ({ children, ...props }) => (- <th className="border border-border/80 px-3 py-1.5 text-left font-semibold bg-muted" {...props}>{children}</th>+ <th className="border border-border/80 px-3 py-1.5 text-start font-semibold bg-muted" {...props}>{children}</th>),td: ({ children, ...props }) => (<td className="border border-border/60 px-3 py-1.5" {...props}>{children}</td>@@ -227,13 +237,13 @@ function TextPreview({ filePath, content, label }: { filePath: string; content:pre: ({ children, ...props }) => {const mermaid = unwrapMermaidPre(children)if (mermaid) return <>{mermaid}</>- return <pre {...props}>{children}</pre>+ return <pre dir="ltr" style={{ textAlign: "left" }} {...props}>{children}</pre>},code: ({ className, children, ...props }) => {const lang = className?.replace("language-", "")const codeText = String(children).replace(/\n$/, "")if (lang === "mermaid") return <MermaidDiagram code={codeText} />- return <code className={className} {...props}>{children}</code>+ return <code dir="ltr" className={className} {...props}>{children}</code>},}}>diff --git a/src/components/editor/wiki-reader.tsx b/src/components/editor/wiki-reader.tsxindex 57515826..e9bbd363 100644--- a/src/components/editor/wiki-reader.tsx+++ b/src/components/editor/wiki-reader.tsx@@ -8,6 +8,8 @@ import { transformWikilinks } from "@/lib/wikilink-transform"import { resolveRelatedSlug } from "@/lib/wiki-page-resolver"import { resolveMarkdownImageSrc } from "@/lib/markdown-image-resolver"import { normalizePath } from "@/lib/path-utils"+import { detectLanguage } from "@/lib/detect-language"+import { getHtmlLang, getTextDirection } from "@/lib/language-metadata"import { useWikiStore } from "@/stores/wiki-store"import { MermaidDiagram, unwrapMermaidPre } from "@/components/mermaid-diagram"@@ -33,6 +35,9 @@ export function WikiReader({ body }: WikiReaderProps) {const setSelectedFile = useWikiStore((s) => s.setSelectedFile)const transformed = useMemo(() => transformWikilinks(body), [body])+ const renderLanguage = detectLanguage(body)+ const direction = getTextDirection(renderLanguage)+ const htmlLang = getHtmlLang(renderLanguage)const projectPath = project ? normalizePath(project.path) : nullconst wikiRoot = projectPath ? `${projectPath}/wiki` : null@@ -52,7 +57,12 @@ export function WikiReader({ body }: WikiReaderProps) {}return (- <div className="prose prose-invert min-w-0 max-w-none">+ <div+ className="prose prose-invert min-w-0 max-w-none"+ dir={direction}+ lang={htmlLang}+ style={{ textAlign: "start" }}+ ><ReactMarkdownremarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}@@ -103,7 +113,7 @@ export function WikiReader({ body }: WikiReaderProps) {),th: ({ children, ...props }) => (<th- className="border border-border/80 bg-muted px-3 py-1.5 text-left font-semibold"+ className="border border-border/80 bg-muted px-3 py-1.5 text-start font-semibold"{...props}>{children}@@ -117,13 +127,13 @@ export function WikiReader({ body }: WikiReaderProps) {pre: ({ children, ...props }) => {const mermaid = unwrapMermaidPre(children)if (mermaid) return <>{mermaid}</>- return <pre {...props}>{children}</pre>+ return <pre dir="ltr" style={{ textAlign: "left" }} {...props}>{children}</pre>},code: ({ className, children, ...props }) => {const lang = className?.replace("language-", "")const codeText = String(children).replace(/\n$/, "")if (lang === "mermaid") return <MermaidDiagram code={codeText} />- return <code className={className} {...props}>{children}</code>+ return <code dir="ltr" className={className} {...props}>{children}</code>},}}>diff --git a/src/components/layout/research-panel.tsx b/src/components/layout/research-panel.tsxindex 151bf8e9..e3542124 100644--- a/src/components/layout/research-panel.tsx+++ b/src/components/layout/research-panel.tsx@@ -15,6 +15,8 @@ import { readFile } from "@/commands/fs"import { queueResearch } from "@/lib/deep-research"import { normalizePath } from "@/lib/path-utils"import { isImeComposing } from "@/lib/keyboard-utils"+import { detectLanguage } from "@/lib/detect-language"+import { getHtmlLang, getTextDirection } from "@/lib/language-metadata"import { MermaidDiagram, unwrapMermaidPre } from "@/components/mermaid-diagram"export function ResearchPanel() {@@ -65,6 +67,7 @@ export function ResearchPanel() {<div className="flex shrink-0 items-center gap-1.5 border-b px-3 py-2"><inputvalue={inputValue}+ dir="auto"onChange={(e) => setInputValue(e.target.value)}onKeyDown={(e) => {if (isImeComposing(e)) return@@ -119,6 +122,9 @@ function separateThinking(text: string): { thinking: string; answer: string } {function SynthesisBlock({ synthesis, isStreaming }: { synthesis: string; isStreaming: boolean }) {const scrollRef = useRef<HTMLDivElement>(null)const { thinking, answer } = useMemo(() => separateThinking(synthesis), [synthesis])+ const renderLanguage = useMemo(() => detectLanguage(answer || synthesis), [answer, synthesis])+ const direction = getTextDirection(renderLanguage)+ const htmlLang = getHtmlLang(renderLanguage)const [thinkingCollapsed, setThinkingCollapsed] = useState(false)// Auto-collapse thinking when answer starts appearing@@ -141,7 +147,9 @@ function SynthesisBlock({ synthesis, isStreaming }: { synthesis: string; isStrea<divref={scrollRef}className="flex-1 overflow-y-auto rounded bg-muted/30 p-2 prose prose-xs prose-invert max-w-none"- style={{ maxHeight: "calc(100vh - 400px)", minHeight: "120px" }}+ dir={direction}+ lang={htmlLang}+ style={{ maxHeight: "calc(100vh - 400px)", minHeight: "120px", textAlign: "start" }}>{thinking && (<div className="mb-2">@@ -179,7 +187,7 @@ function SynthesisBlock({ synthesis, isStreaming }: { synthesis: string; isStrea<thead className="bg-muted" {...props}>{children}</thead>),th: ({ children, ...props }) => (- <th className="border border-border/80 px-3 py-1.5 text-left font-semibold bg-muted" {...props}>{children}</th>+ <th className="border border-border/80 px-3 py-1.5 text-start font-semibold bg-muted" {...props}>{children}</th>),td: ({ children, ...props }) => (<td className="border border-border/60 px-3 py-1.5" {...props}>{children}</td>@@ -187,13 +195,13 @@ function SynthesisBlock({ synthesis, isStreaming }: { synthesis: string; isStreapre: ({ children, ...props }) => {const mermaid = unwrapMermaidPre(children)if (mermaid) return <>{mermaid}</>- return <pre {...props}>{children}</pre>+ return <pre dir="ltr" style={{ textAlign: "left" }} {...props}>{children}</pre>},code: ({ className, children, ...props }) => {const lang = className?.replace("language-", "")const codeText = String(children).replace(/\n$/, "")if (lang === "mermaid") return <MermaidDiagram code={codeText} />- return <code className={className} {...props}>{children}</code>+ return <code dir="ltr" className={className} {...props}>{children}</code>},}}>diff --git a/src/components/project/create-project-dialog.tsx b/src/components/project/create-project-dialog.tsxindex ede16ea1..85859489 100644--- a/src/components/project/create-project-dialog.tsx+++ b/src/components/project/create-project-dialog.tsx@@ -75,7 +75,7 @@ export function CreateProjectDialog({ open: isOpen, onOpenChange, onCreated }: C// wouldn't survive past the dialog closing.const lang = language as OutputLanguagesetOutputLanguage(lang)- await saveOutputLanguage(lang)+ await saveOutputLanguage(lang, project.id)onCreated(project)onOpenChange(false)diff --git a/src/components/settings/preset-resolver.test.ts b/src/components/settings/preset-resolver.test.tsnew file mode 100644index 00000000..f8140150--- /dev/null+++ b/src/components/settings/preset-resolver.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from "vitest"+import { resolveConfig } from "./preset-resolver"+import type { LlmConfig } from "@/stores/wiki-store"+import type { LlmPreset } from "./llm-presets"++function fallbackConfig(overrides: Partial<LlmConfig> = {}): LlmConfig {+ return {+ provider: "openai",+ apiKey: "sk-old",+ model: "gpt-4o",+ ollamaUrl: "http://localhost:11434",+ customEndpoint: "https://example.test/v1",+ maxContextSize: 8192,+ reasoning: { mode: "high" },+ ...overrides,+ }+}++describe("resolveConfig", () => {+ it("defaults reasoning to auto instead of inheriting another preset's fallback", () => {+ const preset: LlmPreset = {+ id: "deepseek",+ label: "DeepSeek",+ provider: "custom",+ baseUrl: "https://api.deepseek.com/v1",+ defaultModel: "deepseek-chat",+ apiMode: "chat_completions",+ }++ const resolved = resolveConfig(preset, undefined, fallbackConfig())++ expect(resolved.reasoning).toEqual({ mode: "auto" })+ })++ it("keeps an explicit provider-level reasoning override", () => {+ const preset: LlmPreset = {+ id: "qwen",+ label: "Qwen",+ provider: "custom",+ baseUrl: "http://localhost:8000/v1",+ defaultModel: "Qwen3.5-122B",+ apiMode: "chat_completions",+ }++ const resolved = resolveConfig(+ preset,+ { reasoning: { mode: "off" } },+ fallbackConfig(),+ )++ expect(resolved.reasoning).toEqual({ mode: "off" })+ })+})diff --git a/src/components/settings/preset-resolver.ts b/src/components/settings/preset-resolver.tsindex 156c6047..77188535 100644--- a/src/components/settings/preset-resolver.ts+++ b/src/components/settings/preset-resolver.ts@@ -17,6 +17,7 @@ export function resolveConfig(const model = ov.model ?? preset.defaultModel ?? ""const maxContextSize =ov.maxContextSize ?? preset.suggestedContextSize ?? fallback.maxContextSize+ const reasoning = ov.reasoning ?? { mode: "auto" as const }if (preset.provider === "custom") {return {@@ -27,6 +28,7 @@ export function resolveConfig(customEndpoint: ov.baseUrl ?? preset.baseUrl ?? "",maxContextSize,apiMode: ov.apiMode ?? preset.apiMode ?? "chat_completions",+ reasoning,}}@@ -38,6 +40,7 @@ export function resolveConfig(ollamaUrl: ov.baseUrl ?? preset.baseUrl ?? "http://localhost:11434",customEndpoint: fallback.customEndpoint,maxContextSize,+ reasoning,}}@@ -51,6 +54,7 @@ export function resolveConfig(ollamaUrl: fallback.ollamaUrl,customEndpoint: fallback.customEndpoint,maxContextSize,+ reasoning,}}@@ -64,5 +68,6 @@ export function resolveConfig(ollamaUrl: fallback.ollamaUrl,customEndpoint: fallback.customEndpoint,maxContextSize,+ reasoning,}}diff --git a/src/components/settings/sections/llm-provider-section.tsx b/src/components/settings/sections/llm-provider-section.tsxindex fd0930c1..d3903870 100644--- a/src/components/settings/sections/llm-provider-section.tsx+++ b/src/components/settings/sections/llm-provider-section.tsx@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next"import { invoke } from "@tauri-apps/api/core"import { Input } from "@/components/ui/input"import { Label } from "@/components/ui/label"-import { useWikiStore, type ProviderOverride } from "@/stores/wiki-store"+import { useWikiStore, type ProviderOverride, type ReasoningConfig, type ReasoningMode } from "@/stores/wiki-store"import { LLM_PRESETS, type LlmPreset } from "../llm-presets"import { ContextSizeSelector } from "../context-size-selector"import { resolveConfig } from "../preset-resolver"@@ -118,6 +118,7 @@ function PresetRow({const apiMode = ov.apiMode ?? preset.apiMode ?? "chat_completions"const baseUrl = ov.baseUrl ?? preset.baseUrl ?? ""const context = ov.maxContextSize ?? preset.suggestedContextSize ?? 131072+ const reasoning = ov.reasoning ?? { mode: "auto" as const }const hasConfig = !!apiKey || !!ov.baseUrl || !!ov.model// Claude Code CLI authenticates via the user's existing ~/.claude OAuth// (inherited from the spawned subprocess), so no API key field is@@ -280,8 +281,79 @@ function PresetRow({onChange={(v) => onChange({ maxContextSize: v })}/></div>++ <ReasoningControls+ value={reasoning}+ onChange={(reasoning) => onChange({ reasoning })}+ />+ </div>+ )}+ </div>+ )+}++function ReasoningControls({+ value,+ onChange,+}: {+ value: ReasoningConfig+ onChange: (value: ReasoningConfig) => void+}) {+ const modes: { value: ReasoningMode; label: string }[] = [+ { value: "auto", label: "Auto" },+ { value: "off", label: "Off" },+ { value: "low", label: "Low" },+ { value: "medium", label: "Medium" },+ { value: "high", label: "High" },+ { value: "max", label: "Max" },+ { value: "custom", label: "Custom" },+ ]++ return (+ <div className="space-y-2">+ <Label>Reasoning / thinking</Label>+ <div className="flex flex-wrap gap-1.5">+ {modes.map((m) => {+ const active = value.mode === m.value+ return (+ <button+ key={m.value}+ type="button"+ onClick={() => onChange({ ...value, mode: m.value })}+ className={`rounded-md border px-2.5 py-1 text-xs transition-colors ${+ active+ ? "border-primary bg-primary text-primary-foreground"+ : "border-border hover:bg-accent"+ }`}+ >+ {m.label}+ </button>+ )+ })}+ </div>+ {value.mode === "custom" && (+ <div className="flex items-center gap-2">+ <Input+ type="number"+ min={0}+ className="w-28"+ value={value.budgetTokens ?? ""}+ onChange={(e) => {+ const raw = e.target.value.trim()+ const n = Number(raw)+ onChange({+ ...value,+ budgetTokens: raw === "" || !Number.isFinite(n) ? undefined : Math.max(0, n),+ })+ }}+ placeholder="1024"+ />+ <span className="text-xs text-muted-foreground">thinking budget tokens</span></div>)}+ <p className="text-xs text-muted-foreground">+ Structured tasks such as ingest may override this to Off to avoid reasoning-only responses.+ </p></div>)}diff --git a/src/components/settings/settings-types.ts b/src/components/settings/settings-types.tsindex 69b380af..c5ffa4d7 100644--- a/src/components/settings/settings-types.ts+++ b/src/components/settings/settings-types.ts@@ -1,4 +1,5 @@import type { CustomApiMode } from "./llm-presets"+import type { ReasoningConfig } from "@/stores/wiki-store"/*** Shape of the draft state each section reads from and writes into.@@ -15,6 +16,7 @@ export interface SettingsDraft {customEndpoint: stringmaxContextSize: numberapiMode: CustomApiMode | undefined+ reasoning: ReasoningConfig | undefined// EmbeddingembeddingEnabled: booleandiff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsxindex db7d64f3..7f9de82c 100644--- a/src/components/settings/settings-view.tsx+++ b/src/components/settings/settings-view.tsx@@ -82,6 +82,7 @@ function initialDraft(customEndpoint: llm.customEndpoint,maxContextSize: llm.maxContextSize ?? 204800,apiMode: llm.apiMode,+ reasoning: llm.reasoning,embeddingEnabled: embed.enabled,embeddingEndpoint: embed.endpoint,embeddingApiKey: embed.apiKey,@@ -116,6 +117,7 @@ export function SettingsView() {const setMultimodalConfig = useWikiStore((s) => s.setMultimodalConfig)const outputLanguage = useWikiStore((s) => s.outputLanguage)const setOutputLanguage = useWikiStore((s) => s.setOutputLanguage)+ const project = useWikiStore((s) => s.project)const proxyConfig = useWikiStore((s) => s.proxyConfig)const setProxyConfig = useWikiStore((s) => s.setProxyConfig)const maxHistoryMessages = useChatStore((s) => s.maxHistoryMessages)@@ -194,6 +196,7 @@ export function SettingsView() {customEndpoint: draft.customEndpoint,maxContextSize: draft.maxContextSize,apiMode: draft.provider === "custom" ? draft.apiMode : undefined,+ reasoning: draft.reasoning,}const newEmbed = {enabled: draft.embeddingEnabled,@@ -234,7 +237,7 @@ export function SettingsView() {setMultimodalConfig(newMultimodal)await saveMultimodalConfig(newMultimodal)setOutputLanguage(draft.outputLanguage as typeof outputLanguage)- await saveOutputLanguage(draft.outputLanguage as typeof outputLanguage)+ await saveOutputLanguage(draft.outputLanguage as typeof outputLanguage, project?.id)setProxyConfig(newProxy)await saveProxyConfig(newProxy)// Apply the proxy env vars LIVE so the next outbound request@@ -263,6 +266,7 @@ export function SettingsView() {setProxyConfig,setMaxHistoryMessages,outputLanguage,+ project,])const body = useMemo(() => {diff --git a/src/lib/changelog.ts b/src/lib/changelog.tsindex 518ddd2e..0d78f434 100644--- a/src/lib/changelog.ts+++ b/src/lib/changelog.ts@@ -25,6 +25,24 @@ export interface ChangelogEntry {}export const CHANGELOG: ChangelogEntry[] = [+ {+ version: "0.4.7",+ date: "2026-05-06",+ highlights: {+ en: [+ "Web search now supports multiple providers: Tavily and SerpApi can be configured separately, with independent API keys and SerpApi search-engine selection.",+ "Reasoning-model support is improved across providers: thinking controls are available in LLM settings, structured ingest avoids reasoning-only failures, and chat can show model thinking when an endpoint streams it.",+ "Knowledge graph exploration is cleaner with filters, structural-node hiding, right-click node hide, and reset controls.",+ "Persian (Farsi) is now available as an output language, with better auto-detection from Arabic, RTL rendering, and per-project target-language preferences.",+ ],+ zh: [+ "网页搜索支持多 Provider:Tavily 和 SerpApi 可分别配置,API Key 独立保存,并支持选择 SerpApi 搜索引擎。",+ "推理型模型支持增强:LLM 设置里新增 thinking / reasoning 控制,结构化导入会避免只输出思考不输出正文的问题,聊天中也能显示模型流式返回的思考过程。",+ "关系图新增过滤能力:可隐藏结构性节点、按节点/连接过滤、右键隐藏单个节点,并可一键重置。",+ "新增 Persian (Farsi) 输出语言支持:自动检测可更好地区分 Persian 和 Arabic,内容按 RTL 显示,Target Language 也改为按项目独立保存。",+ ],+ },+ },{version: "0.4.6",date: "2026-05-01",diff --git a/src/lib/detect-language.test.ts b/src/lib/detect-language.test.tsindex ef29db5b..4ccd0d31 100644--- a/src/lib/detect-language.test.ts+++ b/src/lib/detect-language.test.ts@@ -29,6 +29,18 @@ describe("detectLanguage", () => {expect(detectLanguage("مرحبا بالعالم")).toBe("Arabic")})+ it("detects Persian via Persian-specific letters and words", () => {+ expect(detectLanguage("سلام دنیا، این یک متن فارسی برای آزمایش است")).toBe("Persian")+ })++ it("keeps Arabic distinct from Persian", () => {+ expect(detectLanguage("اللغة العربية مهمة في العالم")).toBe("Arabic")+ })++ it("keeps ambiguous short Arabic-script snippets conservative", () => {+ expect(detectLanguage("سلام")).toBe("Arabic")+ })+it("detects Thai", () => {expect(detectLanguage("สวัสดีครับ")).toBe("Thai")})diff --git a/src/lib/detect-language.ts b/src/lib/detect-language.tsindex 26ba7d83..d17ab842 100644--- a/src/lib/detect-language.ts+++ b/src/lib/detect-language.ts@@ -35,6 +35,10 @@ export function detectLanguage(text: string): string {}}+ if (maxScript === "Arabic" && maxCount >= 2) {+ return detectArabicScriptLanguage(text)+ }+if (maxScript && maxCount >= 2) {return maxScript}@@ -46,6 +50,75 @@ export function detectLanguage(text: string): string {return "English"}+function detectArabicScriptLanguage(text: string): "Arabic" | "Persian" {+ let persianScore = 0+ let arabicScore = 0++ for (const ch of text) {+ switch (ch) {+ case "پ":+ case "چ":+ case "ژ":+ case "گ":+ persianScore += 3+ break+ case "ک":+ case "ی":+ persianScore += 1+ break+ case "ك":+ case "ي":+ case "ة":+ case "ى":+ case "إ":+ case "أ":+ case "ؤ":+ case "ئ":+ arabicScore += 1+ break+ }+ }++ const normalized = ` ${text.replace(/[^\p{L}\p{N}]+/gu, " ")} `+ const persianWords = [+ "این",+ "است",+ "که",+ "برای",+ "های",+ "را",+ "در",+ "به",+ "از",+ "می",+ "یک",+ ]+ const arabicWords = [+ "ال",+ "في",+ "من",+ "على",+ "هذا",+ "هذه",+ "إلى",+ "التي",+ "الذي",+ "كان",+ ]++ for (const word of persianWords) {+ if (normalized.includes(` ${word} `)) persianScore += 2+ }+ for (const word of arabicWords) {+ if (normalized.includes(` ${word} `)) arabicScore += 2+ }++ // Be conservative: Persian has reliable orthographic clues, but short+ // Arabic-script snippets can be ambiguous. Fall back to Arabic unless the+ // Persian signal is clearly stronger.+ return persianScore >= 3 && persianScore > arabicScore ? "Persian" : "Arabic"+}+function getScript(cp: number): string | null {// CJK Unified Ideographs (Chinese/Japanese Kanji)if ((cp >= 0x4E00 && cp <= 0x9FFF) || (cp >= 0x3400 && cp <= 0x4DBF) ||diff --git a/src/lib/ingest.ts b/src/lib/ingest.tsindex 06e8471f..279b3f26 100644--- a/src/lib/ingest.ts+++ b/src/lib/ingest.ts@@ -47,6 +47,7 @@ function resolveCaptionConfig(}import { buildLanguageDirective } from "@/lib/output-language"import { detectLanguage } from "@/lib/detect-language"+import { sameScriptFamily } from "@/lib/language-metadata"// Legacy export kept for backward compatibility with existing diagnostic// tests. The live pipeline goes through parseFileBlocks() below, which@@ -530,7 +531,7 @@ async function autoIngestImpl(},},signal,- { temperature: 0.1 },+ { temperature: 0.1, reasoning: { mode: "off" }, max_tokens: 4096 },)// A silent `return []` here would look like success to the queue@@ -584,7 +585,7 @@ async function autoIngestImpl(},},signal,- { temperature: 0.1 },+ { temperature: 0.1, reasoning: { mode: "off" }, max_tokens: 8192 },)const generationActivity = useActivityStore.getState().items.find((i) => i.id === activityId)@@ -753,10 +754,13 @@ function contentMatchesTargetLanguage(content: string, target: string): boolean// accept any Latin family (English may mis-detect as Italian/French for// short idiomatic samples — that's fine). Cross-family is the real bug.const cjk = new Set(["Chinese", "Traditional Chinese", "Japanese", "Korean"])+ const distinctNonLatin = new Set(["Arabic", "Persian", "Hindi", "Thai", "Hebrew"])const targetIsCjk = cjk.has(target)const detectedIsCjk = cjk.has(detected)if (targetIsCjk) return detectedIsCjk- return !detectedIsCjk && !["Arabic", "Hindi", "Thai", "Hebrew"].includes(detected)+ if (distinctNonLatin.has(target)) return detected === target+ if (distinctNonLatin.has(detected)) return sameScriptFamily(target, detected)+ return !detectedIsCjk}async function writeFileBlocks(@@ -951,6 +955,7 @@ function parseReviewBlocks(export function buildAnalysisPrompt(purpose: string, index: string, sourceContent: string = ""): string {return ["You are an expert research analyst. Read the source document and produce a structured analysis.",+ "Do not output chain-of-thought, hidden reasoning, or a thinking transcript. Reason internally and write only the concise final analysis.","",languageRule(sourceContent),"",@@ -1004,6 +1009,7 @@ export function buildGenerationPrompt(schema: string, purpose: string, index: streturn ["You are a wiki maintainer. Based on the analysis provided, generate wiki files.",+ "Do not output chain-of-thought, hidden reasoning, or explanatory preamble. Reason internally and output only the requested FILE/REVIEW blocks.","",languageRule(sourceContent),"",diff --git a/src/lib/language-metadata.test.ts b/src/lib/language-metadata.test.tsnew file mode 100644index 00000000..c54604e7--- /dev/null+++ b/src/lib/language-metadata.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from "vitest"+import {+ getHtmlLang,+ getLanguagePromptName,+ getTextDirection,+ sameScriptFamily,+} from "./language-metadata"++describe("language metadata", () => {+ it("marks Persian as RTL Farsi for rendering and prompts", () => {+ expect(getLanguagePromptName("Persian")).toBe("Persian (Farsi / فارسی)")+ expect(getTextDirection("Persian")).toBe("rtl")+ expect(getHtmlLang("Persian")).toBe("fa")+ })++ it("keeps Persian and Arabic in the same script family", () => {+ expect(sameScriptFamily("Persian", "Arabic")).toBe(true)+ })++ it("defaults unknown languages to LTR with the original prompt name", () => {+ expect(getLanguagePromptName("Vietnamese")).toBe("Vietnamese")+ expect(getTextDirection("Vietnamese")).toBe("ltr")+ })+})diff --git a/src/lib/language-metadata.ts b/src/lib/language-metadata.tsnew file mode 100644index 00000000..768b200a--- /dev/null+++ b/src/lib/language-metadata.ts@@ -0,0 +1,88 @@+export type TextDirection = "ltr" | "rtl"++interface LanguageMetadata {+ promptName: string+ htmlLang?: string+ direction: TextDirection+ scriptFamily: "arabic" | "cjk" | "latin" | "other"+}++const LANGUAGE_METADATA: Record<string, LanguageMetadata> = {+ English: {+ promptName: "English",+ htmlLang: "en",+ direction: "ltr",+ scriptFamily: "latin",+ },+ Arabic: {+ promptName: "Arabic / العربية",+ htmlLang: "ar",+ direction: "rtl",+ scriptFamily: "arabic",+ },+ Persian: {+ promptName: "Persian (Farsi / فارسی)",+ htmlLang: "fa",+ direction: "rtl",+ scriptFamily: "arabic",+ },+ Hebrew: {+ promptName: "Hebrew / עברית",+ htmlLang: "he",+ direction: "rtl",+ scriptFamily: "other",+ },+ Chinese: {+ promptName: "Chinese",+ htmlLang: "zh-Hans",+ direction: "ltr",+ scriptFamily: "cjk",+ },+ "Traditional Chinese": {+ promptName: "Traditional Chinese",+ htmlLang: "zh-Hant",+ direction: "ltr",+ scriptFamily: "cjk",+ },+ Japanese: {+ promptName: "Japanese",+ htmlLang: "ja",+ direction: "ltr",+ scriptFamily: "cjk",+ },+ Korean: {+ promptName: "Korean",+ htmlLang: "ko",+ direction: "ltr",+ scriptFamily: "cjk",+ },+}++const DEFAULT_METADATA: LanguageMetadata = {+ promptName: "English",+ direction: "ltr",+ scriptFamily: "latin",+}++export function getLanguageMetadata(language: string): LanguageMetadata {+ return LANGUAGE_METADATA[language] ?? {+ ...DEFAULT_METADATA,+ promptName: language || DEFAULT_METADATA.promptName,+ }+}++export function getLanguagePromptName(language: string): string {+ return getLanguageMetadata(language).promptName+}++export function getTextDirection(language: string): TextDirection {+ return getLanguageMetadata(language).direction+}++export function getHtmlLang(language: string): string | undefined {+ return getLanguageMetadata(language).htmlLang+}++export function sameScriptFamily(a: string, b: string): boolean {+ return getLanguageMetadata(a).scriptFamily === getLanguageMetadata(b).scriptFamily+}diff --git a/src/lib/llm-client.ts b/src/lib/llm-client.tsindex 4c43ab62..d2f8c205 100644--- a/src/lib/llm-client.ts+++ b/src/lib/llm-client.ts@@ -1,13 +1,14 @@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"+import { countReasoningCharsInLine, extractReasoningTextFromLine } from "./reasoning-detector"export type { ChatMessage, RequestOverrides } from "./llm-providers"export { isFetchNetworkError } from "./tauri-fetch"export interface StreamCallbacks {onToken: (token: string) => void+ onReasoningToken?: (token: string) => voidonDone: () => voidonError: (error: Error) => void}@@ -165,6 +166,12 @@ export async function streamChat(contentCharsEmitted += text.lengthonToken(text)}+ const recordReasoning = (line: string) => {+ const reasoningParts = extractReasoningTextFromLine(line)+ for (const part of reasoningParts) {+ callbacks.onReasoningToken?.(part)+ }+ }try {while (true) {@@ -172,8 +179,10 @@ export async function streamChat(if (done) {if (lineBuffer.trim()) {- reasoningCharsObserved += countReasoningCharsInLine(lineBuffer.trim())- const token = providerConfig.parseStream(lineBuffer.trim())+ const trimmed = lineBuffer.trim()+ reasoningCharsObserved += countReasoningCharsInLine(trimmed)+ recordReasoning(trimmed)+ const token = providerConfig.parseStream(trimmed)if (token !== null) recordToken(token)}break@@ -186,6 +195,7 @@ export async function streamChat(const trimmed = line.trim()if (!trimmed) continuereasoningCharsObserved += countReasoningCharsInLine(trimmed)+ recordReasoning(trimmed)const token = providerConfig.parseStream(trimmed)if (token !== null) recordToken(token)}diff --git a/src/lib/llm-providers.test.ts b/src/lib/llm-providers.test.tsindex 4bfe6573..3f1cb708 100644--- a/src/lib/llm-providers.test.ts+++ b/src/lib/llm-providers.test.ts@@ -161,3 +161,89 @@ describe("Ollama / custom (chat_completions) — vision content", () => {})})})++describe("reasoning controls", () => {+ it("maps DeepSeek-compatible custom endpoints to thinking disabled for structured tasks", () => {+ const cfg = mkConfig({+ provider: "custom",+ model: "deepseek-chat",+ customEndpoint: "https://api.deepseek.com/v1",+ apiMode: "chat_completions",+ })+ const body = getProviderConfig(cfg).buildBody(+ [{ role: "user", content: "hi" }],+ { reasoning: { mode: "off" } },+ ) as Record<string, unknown>++ expect(body.thinking).toEqual({ type: "disabled" })+ expect(body.reasoning).toBeUndefined()+ })++ it("maps DeepSeek high reasoning to thinking enabled plus reasoning_effort", () => {+ const cfg = mkConfig({+ provider: "custom",+ model: "deepseek-reasoner",+ customEndpoint: "https://api.deepseek.com/v1",+ apiMode: "chat_completions",+ })+ const body = getProviderConfig(cfg).buildBody(+ [{ role: "user", content: "hi" }],+ { reasoning: { mode: "high" } },+ ) as Record<string, unknown>++ expect(body.thinking).toEqual({ type: "enabled" })+ expect(body.reasoning_effort).toBe("high")+ })++ it("does not send an undocumented DeepSeek max_reasoning_tokens field", () => {+ const cfg = mkConfig({+ provider: "custom",+ model: "deepseek-reasoner",+ customEndpoint: "https://api.deepseek.com/v1",+ apiMode: "chat_completions",+ })+ const body = getProviderConfig(cfg).buildBody(+ [{ role: "user", content: "hi" }],+ { reasoning: { mode: "custom", budgetTokens: 2048 } },+ ) as Record<string, unknown>++ expect(body.thinking).toEqual({ type: "enabled" })+ expect(body.max_reasoning_tokens).toBeUndefined()+ })++ it("disables Qwen3 thinking on OpenAI-compatible local endpoints", () => {+ const cfg = mkConfig({+ provider: "custom",+ model: "Qwen3.5-122B",+ customEndpoint: "http://127.0.0.1:8000/v1",+ apiMode: "chat_completions",+ })+ const body = getProviderConfig(cfg).buildBody(+ [{ role: "user", content: "hi" }],+ { reasoning: { mode: "off" } },+ ) as Record<string, unknown>++ expect(body.chat_template_kwargs).toEqual({ enable_thinking: false })+ })++ it("maps Anthropic reasoning budget to extended thinking and removes sampling knobs", () => {+ const cfg = mkConfig({ provider: "anthropic", model: "claude-sonnet-4-5-20250929" })+ const body = getProviderConfig(cfg).buildBody(+ [{ role: "user", content: "hi" }],+ { reasoning: { mode: "custom", budgetTokens: 2048 }, temperature: 0.1, max_tokens: 4096 },+ ) as Record<string, unknown>++ expect(body.thinking).toEqual({ type: "enabled", budget_tokens: 2048 })+ expect(body.temperature).toBeUndefined()+ })++ it("maps Gemini reasoning off to thinkingBudget 0", () => {+ const cfg = mkConfig({ provider: "google", model: "gemini-2.5-pro" })+ const body = getProviderConfig(cfg).buildBody(+ [{ role: "user", content: "hi" }],+ { reasoning: { mode: "off" } },+ ) as { generationConfig?: Record<string, unknown> }++ expect(body.generationConfig?.thinkingConfig).toEqual({ thinkingBudget: 0 })+ })+})diff --git a/src/lib/llm-providers.ts b/src/lib/llm-providers.tsindex 5bc2c04e..6e5503b1 100644--- a/src/lib/llm-providers.ts+++ b/src/lib/llm-providers.ts@@ -1,4 +1,4 @@-import type { LlmConfig } from "@/stores/wiki-store"+import type { LlmConfig, ReasoningConfig } from "@/stores/wiki-store"/*** One piece of a multimodal message body. Text + image is the only@@ -49,6 +49,7 @@ export interface RequestOverrides {top_k?: numbermax_tokens?: numberstop?: string | string[]+ reasoning?: ReasoningConfig}interface ProviderConfig {@@ -218,7 +219,61 @@ function buildOpenAiBody(role: m.role,content: toOpenAiContent(m.content),}))- return { messages: translated, stream: true, ...(overrides ?? {}) }+ return { messages: translated, stream: true, ...stripWireAgnosticOverrides(overrides) }+}++function stripWireAgnosticOverrides(overrides?: RequestOverrides): Omit<RequestOverrides, "reasoning"> {+ const { reasoning: _reasoning, ...rest } = overrides ?? {}+ return rest+}++function effectiveReasoning(config: LlmConfig, overrides?: RequestOverrides): ReasoningConfig {+ return overrides?.reasoning ?? config.reasoning ?? { mode: "auto" }+}++function isDeepSeekEndpoint(config: LlmConfig): boolean {+ return /deepseek/i.test(config.model) || /deepseek/i.test(config.customEndpoint)+}++function isQwenThinkingModel(model: string): boolean {+ return /qwen[-_]?3/i.test(model)+}++function buildOpenAiCompatibleBody(+ config: LlmConfig,+ messages: ChatMessage[],+ overrides?: RequestOverrides,+): Record<string, unknown> {+ const reasoning = effectiveReasoning(config, overrides)+ const body: Record<string, unknown> = buildOpenAiBody(messages, stripWireAgnosticOverrides(overrides))++ if (isDeepSeekEndpoint(config)) {+ // DeepSeek V4 thinking mode. `thinking.type=disabled` is the most+ // important path for ingestion/rewrite tasks: it prevents the model+ // from spending the whole response on `reasoning_content` with no+ // final `content`.+ if (reasoning.mode === "off") {+ body.thinking = { type: "disabled" }+ } else if (reasoning.mode !== "auto") {+ body.thinking = { type: "enabled" }+ if (reasoning.mode === "high" || reasoning.mode === "max") {+ body.reasoning_effort = reasoning.mode+ }+ }+ return body+ }++ if (reasoning.mode === "off" && isQwenThinkingModel(config.model)) {+ body.chat_template_kwargs = { enable_thinking: false }+ }++ if (config.provider === "openai" && reasoning.mode !== "auto" && reasoning.mode !== "off") {+ if (reasoning.mode === "low" || reasoning.mode === "medium" || reasoning.mode === "high") {+ body.reasoning_effort = reasoning.mode+ }+ }++ return body}/**@@ -294,6 +349,34 @@ function buildAnthropicBody(}}+function buildAnthropicBodyWithReasoning(+ config: LlmConfig,+ messages: ChatMessage[],+ overrides?: RequestOverrides,+): Record<string, unknown> {+ const body = buildAnthropicBody(messages, overrides)+ const reasoning = effectiveReasoning(config, overrides)+ if (reasoning.mode === "auto" || reasoning.mode === "off") return body++ const budget =+ reasoning.mode === "custom" && reasoning.budgetTokens !== undefined+ ? reasoning.budgetTokens+ : reasoning.mode === "low"+ ? 1024+ : reasoning.mode === "medium"+ ? 4096+ : 8192+ const budgetTokens = Math.max(1024, budget)+ if ((body.max_tokens as number) <= budgetTokens) {+ body.max_tokens = budgetTokens + 1+ }+ body.thinking = { type: "enabled", budget_tokens: budgetTokens }+ delete body.temperature+ delete body.top_p+ delete body.top_k+ return body+}+/*** Some Anthropic-compatible third-party endpoints (MiniMax global + CN)* serve the Messages API but authenticate with `Authorization: Bearer`@@ -417,6 +500,19 @@ function buildGoogleBody(if (overrides?.stop !== undefined) {generationConfig.stopSequences = Array.isArray(overrides.stop) ? overrides.stop : [overrides.stop]}+ if (overrides?.reasoning?.mode === "off") {+ generationConfig.thinkingConfig = { thinkingBudget: 0 }+ } else if (overrides?.reasoning && overrides.reasoning.mode !== "auto") {+ const budget =+ overrides.reasoning.mode === "custom" && overrides.reasoning.budgetTokens !== undefined+ ? overrides.reasoning.budgetTokens+ : overrides.reasoning.mode === "low"+ ? 1024+ : overrides.reasoning.mode === "medium"+ ? 4096+ : 8192+ generationConfig.thinkingConfig = { thinkingBudget: budget }+ }return {contents,@@ -437,7 +533,7 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {Authorization: `Bearer ${apiKey}`,},buildBody: (messages, overrides) => ({- ...buildOpenAiBody(messages, overrides),+ ...buildOpenAiCompatibleBody(config, messages, overrides),model,}),parseStream: parseOpenAiLine,@@ -449,7 +545,7 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {url,headers: buildAnthropicHeaders(apiKey, url),buildBody: (messages, overrides) => ({- ...buildAnthropicBody(messages, overrides),+ ...buildAnthropicBodyWithReasoning(config, messages, overrides),model,}),parseStream: parseAnthropicLine,@@ -468,7 +564,10 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {"Content-Type": JSON_CONTENT_TYPE,"x-goog-api-key": apiKey,},- buildBody: buildGoogleBody,+ buildBody: (messages, overrides) => buildGoogleBody(messages, {+ ...(overrides ?? {}),+ reasoning: effectiveReasoning(config, overrides),+ }),parseStream: parseGoogleLine,}}@@ -490,21 +589,10 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {"Content-Type": JSON_CONTENT_TYPE,...localLlmOriginHeader(),},- buildBody: (messages, overrides) => {- const body: Record<string, unknown> = {- ...buildOpenAiBody(messages, overrides),- model,- }- // Qwen3 thinking mode disable. Recognized by llama.cpp server- // launched with `--jinja` (reads chat_template_kwargs from the- // OpenAI body and forwards to the Jinja chat template). Real- // Ollama silently ignores unknown fields, so this is safe.- // Requires llama-server --jinja; without it, thinking stays on.- if (/qwen[-_]?3/i.test(model)) {- body.chat_template_kwargs = { enable_thinking: false }- }- return body- },+ buildBody: (messages, overrides) => ({+ ...buildOpenAiCompatibleBody(config, messages, overrides),+ model,+ }),parseStream: parseOpenAiLine,}}@@ -520,7 +608,7 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {url,headers: buildAnthropicHeaders(apiKey, url),buildBody: (messages, overrides) => ({- ...buildAnthropicBody(messages, overrides),+ ...buildAnthropicBodyWithReasoning(config, messages, overrides),model,}),parseStream: parseAnthropicLine,@@ -548,7 +636,7 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {url,headers: buildAnthropicHeaders(apiKey, url),buildBody: (messages, overrides) => ({- ...buildAnthropicBody(messages, overrides),+ ...buildAnthropicBodyWithReasoning(config, messages, overrides),model,}),parseStream: parseAnthropicLine,@@ -573,7 +661,7 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {...localLlmOriginHeader(),},buildBody: (messages, overrides) => ({- ...buildOpenAiBody(messages, overrides),+ ...buildOpenAiCompatibleBody(config, messages, overrides),model,}),parseStream: parseOpenAiLine,diff --git a/src/lib/output-language-options.ts b/src/lib/output-language-options.tsindex 50387493..f28c15bd 100644--- a/src/lib/output-language-options.ts+++ b/src/lib/output-language-options.ts@@ -29,6 +29,7 @@ export const OUTPUT_LANGUAGE_OPTIONS = [{ value: "Italian", label: "Italiano (Italian)" },{ value: "Russian", label: "Русский (Russian)" },{ value: "Arabic", label: "العربية (Arabic)" },+ { value: "Persian", label: "فارسی (Persian / Farsi)" },{ value: "Hindi", label: "हिन्दी (Hindi)" },{ value: "Turkish", label: "Türkçe (Turkish)" },{ value: "Dutch", label: "Nederlands (Dutch)" },diff --git a/src/lib/output-language.test.ts b/src/lib/output-language.test.tsindex 3bf753c7..51081d8b 100644--- a/src/lib/output-language.test.ts+++ b/src/lib/output-language.test.ts@@ -24,6 +24,11 @@ describe("getOutputLanguage", () => {expect(getOutputLanguage("注意力机制是什么")).toBe("Chinese")})+ it("auto mode detects Persian separately from Arabic", () => {+ useWikiStore.getState().setOutputLanguage("auto")+ expect(getOutputLanguage("پردازش زبان طبیعی در فارسی کاربردهای زیادی دارد")).toBe("Persian")+ })+it("auto mode with empty fallback defaults to English", () => {useWikiStore.getState().setOutputLanguage("auto")expect(getOutputLanguage("")).toBe("English")@@ -63,6 +68,12 @@ describe("buildLanguageDirective", () => {expect(directive).toContain("Vietnamese")})+ it("uses an explicit Persian/Farsi prompt name", () => {+ useWikiStore.getState().setOutputLanguage("Persian")+ const directive = buildLanguageDirective()+ expect(directive).toContain("MANDATORY OUTPUT LANGUAGE: Persian (Farsi / فارسی)")+ })+it("explicitly overrides source content language", () => {useWikiStore.getState().setOutputLanguage("English")const directive = buildLanguageDirective()@@ -88,4 +99,9 @@ describe("buildLanguageReminder", () => {useWikiStore.getState().setOutputLanguage("auto")expect(buildLanguageReminder("これは日本語です")).toContain("Japanese")})++ it("reminds Persian as Persian/Farsi", () => {+ useWikiStore.getState().setOutputLanguage("Persian")+ expect(buildLanguageReminder()).toContain("Persian (Farsi / فارسی)")+ })})diff --git a/src/lib/output-language.ts b/src/lib/output-language.tsindex ce829565..b2ee6c3d 100644--- a/src/lib/output-language.ts+++ b/src/lib/output-language.ts@@ -1,5 +1,6 @@import { useWikiStore } from "@/stores/wiki-store"import { detectLanguage } from "./detect-language"+import { getLanguagePromptName } from "./language-metadata"/*** Get the effective output language for LLM content generation.@@ -20,13 +21,14 @@ export function getOutputLanguage(fallbackText: string = ""): string {*/export function buildLanguageDirective(fallbackText: string = ""): string {const lang = getOutputLanguage(fallbackText)+ const promptLang = getLanguagePromptName(lang)return [- `## ⚠️ MANDATORY OUTPUT LANGUAGE: ${lang}`,+ `## ⚠️ MANDATORY OUTPUT LANGUAGE: ${promptLang}`,"",- `You MUST write your entire response (including wiki page titles, content, descriptions, summaries, and any generated text) in **${lang}**.`,+ `You MUST write your entire response (including wiki page titles, content, descriptions, summaries, and any generated text) in **${promptLang}**.`,`The source material or wiki content may be in a different language, but this is IRRELEVANT to your output language.`,- `Ignore the language of any source content. Generate everything in ${lang} only.`,- `Proper nouns should use standard ${lang} transliteration when appropriate.`,+ `Ignore the language of any source content. Generate everything in ${promptLang} only.`,+ `Proper nouns should use standard ${promptLang} transliteration when appropriate.`,`DO NOT use any other language. This overrides all other instructions.`,].join("\n")}@@ -36,5 +38,5 @@ export function buildLanguageDirective(fallbackText: string = ""): string {*/export function buildLanguageReminder(fallbackText: string = ""): string {const lang = getOutputLanguage(fallbackText)- return `REMINDER: All output must be in ${lang}. Do not use any other language.`+ return `REMINDER: All output must be in ${getLanguagePromptName(lang)}. Do not use any other language.`}diff --git a/src/lib/project-store.ts b/src/lib/project-store.tsindex 278d2dae..4b80ee8c 100644--- a/src/lib/project-store.ts+++ b/src/lib/project-store.ts@@ -165,14 +165,23 @@ export async function loadLanguage(): Promise<string | null> {}const OUTPUT_LANGUAGE_KEY = "outputLanguage"+const PROJECT_OUTPUT_LANGUAGE_KEY = "projectOutputLanguages"-export async function saveOutputLanguage(lang: OutputLanguage): Promise<void> {+export async function saveOutputLanguage(lang: OutputLanguage, projectId?: string): Promise<void> {const store = await getStore()+ if (projectId) {+ const existing = (await store.get<Record<string, OutputLanguage>>(PROJECT_OUTPUT_LANGUAGE_KEY)) ?? {}+ await store.set(PROJECT_OUTPUT_LANGUAGE_KEY, { ...existing, [projectId]: lang })+ }await store.set(OUTPUT_LANGUAGE_KEY, lang)}-export async function loadOutputLanguage(): Promise<OutputLanguage | null> {+export async function loadOutputLanguage(projectId?: string): Promise<OutputLanguage | null> {const store = await getStore()+ if (projectId) {+ const projectLanguages = await store.get<Record<string, OutputLanguage>>(PROJECT_OUTPUT_LANGUAGE_KEY)+ return projectLanguages?.[projectId] ?? null+ }return (await store.get<OutputLanguage>(OUTPUT_LANGUAGE_KEY)) ?? null}diff --git a/src/lib/reasoning-detector.test.ts b/src/lib/reasoning-detector.test.tsindex e02f9ce1..c0fc5247 100644--- a/src/lib/reasoning-detector.test.ts+++ b/src/lib/reasoning-detector.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest"-import { countReasoningCharsInLine } from "./reasoning-detector"+import { countReasoningCharsInLine, extractReasoningTextFromLine } from "./reasoning-detector"describe("countReasoningCharsInLine", () => {it("returns 0 for empty / non-stream lines", () => {@@ -69,3 +69,35 @@ describe("countReasoningCharsInLine", () => {expect(countReasoningCharsInLine(line)).toBe("Thinking".length)})})++describe("extractReasoningTextFromLine", () => {+ it("extracts OpenAI-compatible reasoning_content chunks", () => {+ const line =+ 'data: {"choices":[{"index":0,"delta":{"reasoning_content":"thinking"}}]}'+ expect(extractReasoningTextFromLine(line)).toEqual(["thinking"])+ })++ it("extracts Qwen-style reasoning chunks", () => {+ const line =+ 'data: {"choices":[{"index":0,"delta":{"reasoning":"Let me think"}}]}'+ expect(extractReasoningTextFromLine(line)).toEqual(["Let me think"])+ })++ it("extracts Anthropic thinking deltas", () => {+ const line =+ 'data: {"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":"reasoning"}}'+ expect(extractReasoningTextFromLine(line)).toEqual(["reasoning"])+ })++ it("extracts Gemini thought parts", () => {+ const line =+ 'data: {"candidates":[{"content":{"parts":[{"thought":true,"text":"hidden"},{"text":"visible"}]}}]}'+ expect(extractReasoningTextFromLine(line)).toEqual(["hidden"])+ })++ it("ignores visible content", () => {+ const line =+ 'data: {"choices":[{"index":0,"delta":{"content":"hello"},"finish_reason":null}]}'+ expect(extractReasoningTextFromLine(line)).toEqual([])+ })+})diff --git a/src/lib/reasoning-detector.ts b/src/lib/reasoning-detector.tsindex dec3d68f..c739ed5e 100644--- a/src/lib/reasoning-detector.ts+++ b/src/lib/reasoning-detector.ts@@ -46,3 +46,42 @@ export function countReasoningCharsInLine(rawLine: string): number {}return total}++export function extractReasoningTextFromLine(rawLine: string): string[] {+ const line = rawLine.trim()+ if (!line.startsWith("data: ")) return []+ const data = line.slice(6).trim()+ if (!data || data === "[DONE]") return []++ try {+ const parsed = JSON.parse(data) as {+ choices?: Array<{ delta?: { reasoning_content?: string; reasoning?: string } }>+ delta?: { type?: string; text?: string; thinking?: string }+ candidates?: Array<{+ content?: { parts?: Array<{ text?: string; thought?: boolean }> }+ }>+ }++ const out: string[] = []+ for (const choice of parsed.choices ?? []) {+ const delta = choice.delta+ if (typeof delta?.reasoning_content === "string") out.push(delta.reasoning_content)+ if (typeof delta?.reasoning === "string") out.push(delta.reasoning)+ }++ if (parsed.delta?.type === "thinking_delta") {+ if (typeof parsed.delta.thinking === "string") out.push(parsed.delta.thinking)+ if (typeof parsed.delta.text === "string") out.push(parsed.delta.text)+ }++ for (const candidate of parsed.candidates ?? []) {+ for (const part of candidate.content?.parts ?? []) {+ if (part.thought && typeof part.text === "string") out.push(part.text)+ }+ }++ return out+ } catch {+ return []+ }+}diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.tsindex 292dbd7b..ed82cd6a 100644--- a/src/stores/wiki-store.ts+++ b/src/stores/wiki-store.ts@@ -8,6 +8,12 @@ import type { WikiProject, FileNode } from "@/types/wiki"* `chat_completions` for backward compatibility with pre-0.3.7 configs.*/export type CustomApiMode = "chat_completions" | "anthropic_messages"+export type ReasoningMode = "auto" | "off" | "low" | "medium" | "high" | "max" | "custom"++export interface ReasoningConfig {+ mode: ReasoningMode+ budgetTokens?: number+}interface LlmConfig {provider: "openai" | "anthropic" | "google" | "ollama" | "custom" | "minimax" | "claude-code"@@ -17,6 +23,7 @@ interface LlmConfig {customEndpoint: stringmaxContextSize: number // max context window in charactersapiMode?: CustomApiMode+ reasoning?: ReasoningConfig}export type SearchProvider = "tavily" | "serpapi" | "none"@@ -144,6 +151,7 @@ type OutputLanguage =| "Italian"| "Russian"| "Arabic"+ | "Persian"| "Hindi"| "Turkish"| "Dutch"@@ -151,6 +159,7 @@ type OutputLanguage =| "Swedish"| "Indonesian"| "Thai"+ | "Ukrainian"/*** Per-preset saved fields. Each entry survives turning the preset off@@ -163,6 +172,7 @@ export interface ProviderOverride {baseUrl?: string // customEndpoint for custom presets, ollamaUrl for ollamaapiMode?: CustomApiModemaxContextSize?: number+ reasoning?: ReasoningConfig}export type ProviderConfigs = Record<string, ProviderOverride>@@ -234,6 +244,7 @@ export const useWikiStore = create<WikiState>((set) => ({model: "",ollamaUrl: "http://localhost:11434",customEndpoint: "",+ reasoning: { mode: "auto" },},providerConfigs: {},activePresetId: null,