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

release: v0.3.7 — LLM provider overhaul + Windows fixes

nash_su4f116bc03c1d
diff --git a/.gitignore b/.gitignore
index dd70a6b9..dcc50549 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,6 +4,7 @@ node_modules/
# Build outputs
dist/
dist-ssr/
+*.tsbuildinfo
# Rust build artifacts
src-tauri/target/
diff --git a/package-lock.json b/package-lock.json
index 229edb74..b39d0083 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "llm-wiki",
- "version": "0.3.6",
+ "version": "0.3.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "llm-wiki",
- "version": "0.3.6",
+ "version": "0.3.7",
"dependencies": {
"@base-ui/react": "^1.3.0",
"@fontsource-variable/geist": "^5.2.8",
diff --git a/package.json b/package.json
index e4fd8495..49cab1b0 100644
--- a/package.json
+++ b/package.json
@@ -1,11 +1,12 @@
{
"name": "llm-wiki",
"private": true,
- "version": "0.3.6",
+ "version": "0.3.7",
"type": "module",
"scripts": {
"dev": "vite",
- "build": "tsc && vite build",
+ "typecheck": "tsc --build --pretty",
+ "build": "npm run typecheck && vite build",
"preview": "vite preview",
"test": "vitest run --exclude='**/*.real-llm.test.ts'",
"test:llm": "RUN_LLM_TESTS=1 vitest run real-llm --no-file-parallelism --reporter=verbose",
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 9e974141..efa1543b 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -4361,7 +4361,7 @@ checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
[[package]]
name = "llm-wiki"
-version = "0.3.6"
+version = "0.3.7"
dependencies = [
"arrow-array",
"arrow-schema",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 266dd25d..9348da21 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "llm-wiki"
-version = "0.3.6"
+version = "0.3.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.json
index 6c878cdb..1860dbe8 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.3.6",
+ "version": "0.3.7",
"identifier": "com.llmwiki.app",
"build": {
"beforeDevCommand": "npm run dev",
diff --git a/src/App.tsx b/src/App.tsx
index ad999129..971909ce 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -5,7 +5,7 @@ import { useWikiStore } from "@/stores/wiki-store"
import { useReviewStore } from "@/stores/review-store"
import { useChatStore } from "@/stores/chat-store"
import { listDirectory, openProject } from "@/commands/fs"
-import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig, loadOutputLanguage } from "@/lib/project-store"
+import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig, loadOutputLanguage, loadProviderConfigs, loadActivePresetId } from "@/lib/project-store"
import { loadReviewItems, loadChatHistory } from "@/lib/persist"
import { setupAutoSave } from "@/lib/auto-save"
import { startClipWatcher } from "@/lib/clip-watcher"
@@ -37,6 +37,32 @@ function App() {
if (savedConfig) {
useWikiStore.getState().setLlmConfig(savedConfig)
}
+ const savedProviderConfigs = await loadProviderConfigs()
+ if (savedProviderConfigs) {
+ useWikiStore.getState().setProviderConfigs(savedProviderConfigs)
+ }
+ const savedActivePreset = await loadActivePresetId()
+ if (savedActivePreset) {
+ useWikiStore.getState().setActivePresetId(savedActivePreset)
+ // Re-resolve the active preset's LlmConfig from (preset defaults
+ // + saved overrides). Without this, preset default updates
+ // (e.g. a corrected Anthropic model ID shipped in a release)
+ // never reach users who are relying on defaults — their stored
+ // `llmConfig` snapshot from a previous launch would keep the
+ // old value. Overrides still win, so an explicit user choice
+ // is preserved.
+ const { LLM_PRESETS } = await import("@/components/settings/llm-presets")
+ const { resolveConfig } = await import("@/components/settings/preset-resolver")
+ const preset = LLM_PRESETS.find((p) => p.id === savedActivePreset)
+ if (preset) {
+ const currentFallback = useWikiStore.getState().llmConfig
+ const override = (savedProviderConfigs ?? {})[savedActivePreset]
+ const resolved = resolveConfig(preset, override, currentFallback)
+ useWikiStore.getState().setLlmConfig(resolved)
+ const { saveLlmConfig } = await import("@/lib/project-store")
+ await saveLlmConfig(resolved)
+ }
+ }
const savedSearchConfig = await loadSearchApiConfig()
if (savedSearchConfig) {
useWikiStore.getState().setSearchApiConfig(savedSearchConfig)
diff --git a/src/components/chat/chat-message.tsx b/src/components/chat/chat-message.tsx
index 28ed566a..5428214b 100644
--- a/src/components/chat/chat-message.tsx
+++ b/src/components/chat/chat-message.tsx
@@ -15,7 +15,6 @@ import type { DisplayMessage } from "@/stores/chat-store"
import type { FileNode } from "@/types/wiki"
import { convertLatexToUnicode } from "@/lib/latex-to-unicode"
-import { enrichWithWikilinks } from "@/lib/enrich-wikilinks"
import { normalizePath, getFileName } from "@/lib/path-utils"
// Module-level cache of source file names
@@ -650,64 +649,6 @@ function processContent(text: string): string {
return result
}
-function SourceRef({ fileName }: { fileName: string }) {
- const project = useWikiStore((s) => s.project)
- const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
- const setFileContent = useWikiStore((s) => s.setFileContent)
- const setActiveView = useWikiStore((s) => s.setActiveView)
-
- const handleClick = useCallback(async (e: React.MouseEvent) => {
- e.preventDefault()
- e.stopPropagation()
- if (!project) return
- const pp = normalizePath(project.path)
-
- // Try exact match first, then search with the name as given
- const candidates = [
- `${pp}/raw/sources/${fileName}`,
- ]
-
- // If fileName has no extension, try to find a matching file
- if (!fileName.includes(".")) {
- for (const sf of cachedSourceFiles) {
- const stem = sf.replace(/\.[^.]+$/, "")
- if (stem === fileName || sf.startsWith(fileName)) {
- candidates.unshift(`${pp}/raw/sources/${sf}`)
- }
- }
- }
-
- setActiveView("wiki")
-
- for (const path of candidates) {
- try {
- const content = await readFile(path)
- setSelectedFile(path)
- setFileContent(content)
- return
- } catch {
- // try next
- }
- }
-
- // Fallback: just set the path even if we can't read it
- setSelectedFile(candidates[0])
- setFileContent(`Unable to load: ${fileName}`)
- }, [project, fileName, setSelectedFile, setFileContent, setActiveView])
-
- return (
- <button
- type="button"
- onClick={handleClick}
- className="inline-flex items-center gap-0.5 rounded bg-accent/50 px-1.5 py-0.5 text-xs font-medium text-primary hover:bg-accent transition-colors"
- title={`Open source: ${fileName}`}
- >
- <Paperclip className="inline h-3 w-3" />
- {fileName}
- </button>
- )
-}
-
function WikiLink({ pageName, children }: { pageName: string; children: React.ReactNode }) {
const project = useWikiStore((s) => s.project)
const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
diff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsx
index 1202507c..ea5bd97d 100644
--- a/src/components/chat/chat-panel.tsx
+++ b/src/components/chat/chat-panel.tsx
@@ -7,13 +7,12 @@ import { useChatStore, chatMessagesToLLM } from "@/stores/chat-store"
import { useWikiStore } from "@/stores/wiki-store"
import { streamChat, type ChatMessage as LLMMessage } from "@/lib/llm-client"
import { executeIngestWrites } from "@/lib/ingest"
-import { listDirectory, readFile, writeFile, deleteFile } from "@/commands/fs"
+import { listDirectory, readFile, deleteFile } from "@/commands/fs"
import { searchWiki } from "@/lib/search"
import { buildRetrievalGraph, getRelatedNodes } from "@/lib/graph-relevance"
-import { useReviewStore } from "@/stores/review-store"
-import type { FileNode } from "@/types/wiki"
import { normalizePath, getFileName, getRelativePath } from "@/lib/path-utils"
import { getOutputLanguage, buildLanguageReminder } from "@/lib/output-language"
+import { isGreeting } from "@/lib/greeting-detector"
// Store the page mapping from the last query so SourceFilesBar can show which pages were cited
export let lastQueryPages: { title: string; path: string }[] = []
@@ -169,7 +168,25 @@ export function ChatPanel() {
const systemMessages: LLMMessage[] = []
let queryRefs: { title: string; path: string }[] = []
let langReminder: string | undefined
- if (project) {
+ // Pure greetings ("hi", "你好", "嗨") don't warrant running the whole
+ // retrieval pipeline — it's slow, costs context, and drags in random
+ // wiki pages the user clearly didn't ask about. Short-circuit with a
+ // minimal system prompt and let the model reply conversationally.
+ const greetingOnly = isGreeting(text)
+ if (project && greetingOnly) {
+ const outLang = getOutputLanguage(text)
+ systemMessages.push({
+ role: "system",
+ content: [
+ `You are a wiki assistant for the project "${project.name}".`,
+ "The user sent a casual greeting — reply briefly and naturally, in one or two sentences.",
+ "Do NOT invent wiki content or pretend to have retrieved pages. Invite the user to ask a concrete question if they want information from the wiki.",
+ "",
+ `Respond in ${outLang}.`,
+ ].join("\n"),
+ })
+ // Skip retrieval; queryRefs stays empty so no "Sources" chip is shown.
+ } else if (project) {
const pp = normalizePath(project.path)
const dataVersion = useWikiStore.getState().dataVersion
const maxCtx = llmConfig.maxContextSize || 204800
@@ -332,16 +349,26 @@ export function ChatPanel() {
.filter((m) => m.role === "user" || m.role === "assistant")
.slice(-maxHistoryMessages)
- // Inject language reminder as system message between history and final user query
+ // Prepend the language reminder onto the final user turn rather than
+ // inserting a second {role:"system"} between history and the final
+ // user message. vLLM / llama.cpp / Ollama drive their chat templates
+ // from HF Jinja, and Qwen3-family templates enforce "system only at
+ // index 0" — a mid-conversation system message gets rejected with
+ // "System message must be at the beginning." (HTTP 400). OpenAI and
+ // Anthropic are more lenient, but keeping a single system at the top
+ // is the safest shape across every OpenAI-compatible backend.
const historyMessages = chatMessagesToLLM(activeConvMessages)
- const llmMessages = langReminder && historyMessages.length > 0
- ? [
- ...systemMessages,
- ...historyMessages.slice(0, -1),
- { role: "system" as const, content: langReminder },
- ...historyMessages.slice(-1),
+ let llmMessages: LLMMessage[] = [...systemMessages, ...historyMessages]
+ if (langReminder && historyMessages.length > 0) {
+ const lastIdx = llmMessages.length - 1
+ const last = llmMessages[lastIdx]
+ if (last && last.role === "user") {
+ llmMessages = [
+ ...llmMessages.slice(0, lastIdx),
+ { role: "user", content: `[${langReminder}]\n\n${last.content}` },
]
- : [...systemMessages, ...historyMessages]
+ }
+ }
const controller = new AbortController()
abortRef.current = controller
@@ -490,68 +517,3 @@ export function ChatPanel() {
)
}
-/**
- * Check if the LLM marked its response as save-worthy.
- * If so, add a review item prompting the user to save it.
- */
-function checkSaveWorthy(response: string, question: string) {
- const match = response.match(/<!--\s*save-worthy:\s*yes\s*\|\s*(.+?)\s*-->/)
- if (!match) return
-
- const reason = match[1]
- const firstLine = response.split("\n").find((l) => l.trim() && !l.startsWith("<!--"))?.replace(/^#+\s*/, "").trim() ?? "Chat answer"
- const title = firstLine.slice(0, 60)
-
- const contentToSave = response
- const questionText = question
-
- useReviewStore.getState().addItem({
- type: "suggestion",
- title: `Save to Wiki: ${title}`,
- description: `${reason}\n\nQuestion: "${questionText.slice(0, 100)}${questionText.length > 100 ? "..." : ""}"`,
- options: [
- { label: "Save to Wiki", action: `save:${encodeContent(contentToSave)}` },
- { label: "Skip", action: "Skip" },
- ],
- })
-}
-
-function encodeContent(text: string): string {
- return btoa(encodeURIComponent(text))
-}
-
-function flattenFileNames(nodes: FileNode[]): string[] {
- const names: string[] = []
- for (const node of nodes) {
- if (node.is_dir && node.children) {
- names.push(...flattenFileNames(node.children))
- } else if (!node.is_dir) {
- names.push(node.name)
- }
- }
- return names
-}
-
-function flattenMdFiles(nodes: FileNode[]): FileNode[] {
- const files: FileNode[] = []
- for (const node of nodes) {
- if (node.is_dir && node.children) {
- files.push(...flattenMdFiles(node.children))
- } else if (!node.is_dir && node.name.endsWith(".md")) {
- files.push(node)
- }
- }
- return files
-}
-
-function flattenAllFiles(nodes: FileNode[]): FileNode[] {
- const files: FileNode[] = []
- for (const node of nodes) {
- if (node.is_dir && node.children) {
- files.push(...flattenAllFiles(node.children))
- } else if (!node.is_dir) {
- files.push(node)
- }
- }
- return files
-}
diff --git a/src/components/editor/wiki-editor.tsx b/src/components/editor/wiki-editor.tsx
index f4bd2105..6c804479 100644
--- a/src/components/editor/wiki-editor.tsx
+++ b/src/components/editor/wiki-editor.tsx
@@ -9,7 +9,6 @@ import { nord } from "@milkdown/theme-nord"
import { Milkdown, MilkdownProvider, useEditor } from "@milkdown/react"
import "@milkdown/theme-nord/style.css"
import "katex/dist/katex.min.css"
-import { convertLatexToUnicode } from "@/lib/latex-to-unicode"
interface WikiEditorInnerProps {
content: string
diff --git a/src/components/graph/graph-view.tsx b/src/components/graph/graph-view.tsx
index 04863b11..12ba1d32 100644
--- a/src/components/graph/graph-view.tsx
+++ b/src/components/graph/graph-view.tsx
@@ -12,7 +12,7 @@ import { readFile } from "@/commands/fs"
import { buildWikiGraph, type GraphNode, type GraphEdge, type CommunityInfo } from "@/lib/wiki-graph"
import { findSurprisingConnections, detectKnowledgeGaps, type SurprisingConnection, type KnowledgeGap } from "@/lib/graph-insights"
import { queueResearch } from "@/lib/deep-research"
-import { optimizeResearchTopic, type OptimizedTopic } from "@/lib/optimize-research-topic"
+import { optimizeResearchTopic } from "@/lib/optimize-research-topic"
import { normalizePath } from "@/lib/path-utils"
const NODE_TYPE_COLORS: Record<string, string> = {
@@ -760,11 +760,6 @@ export function GraphView() {
const isActive = highlightedNodes.size > 0 &&
[...ids].every((id) => highlightedNodes.has(id)) &&
[...highlightedNodes].every((id) => ids.has(id))
- const researchTopic = gap.type === "sparse-community"
- ? `Knowledge area: ${gap.title.replace("Sparse cluster: ", "")}`
- : gap.type === "bridge-node"
- ? `Key concept: ${gap.title.replace("Key bridge: ", "")}`
- : gap.title
return (
<div
key={i}
diff --git a/src/components/layout/activity-panel.tsx b/src/components/layout/activity-panel.tsx
index d0623f22..b59b674e 100644
--- a/src/components/layout/activity-panel.tsx
+++ b/src/components/layout/activity-panel.tsx
@@ -51,15 +51,20 @@ export function ActivityPanel() {
const queueSummary = getQueueSummary()
const hasQueue = queueSummary.total > 0
- // All hooks must be before any conditional return
+ // All hooks must be before any conditional return.
+ // retryTask / cancelTask / cancelAllTasks all operate on the currently
+ // active project implicitly (via module-scoped state in ingest-queue.ts)
+ // — they take NO projectPath argument. An earlier version passed one in
+ // and the extra arg silently became "taskId", making retry a no-op for
+ // every failed task. Keep this minimal.
const handleRetry = useCallback((taskId: string) => {
if (!project) return
- retryTask(normalizePath(project.path), taskId)
+ retryTask(taskId)
}, [project])
const handleCancel = useCallback((taskId: string) => {
if (!project) return
- cancelTask(normalizePath(project.path), taskId)
+ cancelTask(taskId)
}, [project])
const handleCancelAll = useCallback(() => {
@@ -71,7 +76,7 @@ export function ActivityPanel() {
`Partial files from the in-progress task will be removed. ` +
`Failed tasks will be kept so you can retry them.`,
)) return
- cancelAllTasks(normalizePath(project.path))
+ cancelAllTasks()
}, [project, queueSummary.pending, queueSummary.processing])
// Auto-expand when a new task starts running
diff --git a/src/components/layout/app-layout.tsx b/src/components/layout/app-layout.tsx
index ed8344dd..4938b4e9 100644
--- a/src/components/layout/app-layout.tsx
+++ b/src/components/layout/app-layout.tsx
@@ -18,6 +18,7 @@ interface AppLayoutProps {
export function AppLayout({ onSwitchProject }: AppLayoutProps) {
const project = useWikiStore((s) => s.project)
const selectedFile = useWikiStore((s) => s.selectedFile)
+ const activeView = useWikiStore((s) => s.activeView)
const researchPanelOpen = useResearchStore((s) => s.panelOpen)
const setFileTree = useWikiStore((s) => s.setFileTree)
const [leftWidth, setLeftWidth] = useState(220)
@@ -81,26 +82,35 @@ export function AppLayout({ onSwitchProject }: AppLayoutProps) {
[]
)
- const hasRightPanel = !!(selectedFile || researchPanelOpen)
+ // Settings is a full-width admin view — the file tree / activity panel
+ // are irrelevant there and their narrow column makes the settings form
+ // cramped. Hide both the left sidebar (and the file preview on the
+ // right) so the settings screen uses the whole content area.
+ const isSettings = activeView === "settings"
+ const hasRightPanel = !isSettings && !!(selectedFile || researchPanelOpen)
return (
<div className="flex h-screen bg-background text-foreground">
<IconSidebar onSwitchProject={onSwitchProject} />
<div ref={containerRef} className="flex min-w-0 flex-1 overflow-hidden">
- {/* Left: File tree + Activity */}
- <div
- className="flex shrink-0 flex-col overflow-hidden border-r"
- style={{ width: leftWidth }}
- >
- <div className="flex-1 overflow-hidden">
- <SidebarPanel />
- </div>
- <ActivityPanel />
- </div>
- <div
- className="w-1.5 shrink-0 cursor-col-resize bg-border/40 transition-colors hover:bg-primary/30 active:bg-primary/40"
- onMouseDown={startDrag("left")}
- />
+ {!isSettings && (
+ <>
+ {/* Left: File tree + Activity */}
+ <div
+ className="flex shrink-0 flex-col overflow-hidden border-r"
+ style={{ width: leftWidth }}
+ >
+ <div className="flex-1 overflow-hidden">
+ <SidebarPanel />
+ </div>
+ <ActivityPanel />
+ </div>
+ <div
+ className="w-1.5 shrink-0 cursor-col-resize bg-border/40 transition-colors hover:bg-primary/30 active:bg-primary/40"
+ onMouseDown={startDrag("left")}
+ />
+ </>
+ )}
{/* Center: Chat or view (sources/settings/review) */}
<div className="min-w-0 flex-1 overflow-hidden">
diff --git a/src/components/layout/icon-sidebar.tsx b/src/components/layout/icon-sidebar.tsx
index dda1b36b..87a9b1d2 100644
--- a/src/components/layout/icon-sidebar.tsx
+++ b/src/components/layout/icon-sidebar.tsx
@@ -52,7 +52,7 @@ export function IconSidebar({ onSwitchProject }: IconSidebarProps) {
}, [])
return (
- <TooltipProvider delayDuration={300}>
+ <TooltipProvider delay={300}>
<div className="flex h-full w-12 flex-col items-center border-r bg-muted/50 py-2">
{/* Logo */}
<div className="mb-2 flex items-center justify-center">
diff --git a/src/components/layout/research-panel.tsx b/src/components/layout/research-panel.tsx
index 55af44a7..daa689de 100644
--- a/src/components/layout/research-panel.tsx
+++ b/src/components/layout/research-panel.tsx
@@ -6,7 +6,7 @@ import rehypeKatex from "rehype-katex"
import "katex/dist/katex.min.css"
import {
Search, Loader2, CheckCircle2, AlertCircle, ChevronRight, ChevronDown, X,
- ExternalLink, FileText, Send,
+ FileText, Send,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { useResearchStore, type ResearchTask } from "@/stores/research-store"
diff --git a/src/components/layout/sidebar-panel.tsx b/src/components/layout/sidebar-panel.tsx
index ca1890d0..8eaebf96 100644
--- a/src/components/layout/sidebar-panel.tsx
+++ b/src/components/layout/sidebar-panel.tsx
@@ -1,10 +1,8 @@
import { useState } from "react"
-import { useTranslation } from "react-i18next"
import { KnowledgeTree } from "./knowledge-tree"
import { FileTree } from "./file-tree"
export function SidebarPanel() {
- const { t } = useTranslation()
const [mode, setMode] = useState<"knowledge" | "files">("knowledge")
return (
diff --git a/src/components/review/review-view.tsx b/src/components/review/review-view.tsx
index 6f0b0678..1d96b514 100644
--- a/src/components/review/review-view.tsx
+++ b/src/components/review/review-view.tsx
@@ -156,12 +156,17 @@ export function ReviewView() {
} else {
resolveItem(id, action)
}
- } else if (action.startsWith("__create_page__:") && project) {
- // Explicit create page fallback
- const realAction = action.slice("__create_page__:".length)
- await createPageFromReview(id, realAction, items, pp)
- } else if (actionLooksLikeCreate(action) && project) {
- // Create a wiki page from the review item's content
+ } else if (
+ (action.startsWith("__create_page__:") || actionLooksLikeCreate(action))
+ && project
+ ) {
+ // Create a wiki page from the review item's content. Accepts both
+ // the `__create_page__:` sentinel (forced via the "no search API"
+ // fallback branch above) and actions that heuristically look like
+ // a create instruction.
+ const realAction = action.startsWith("__create_page__:")
+ ? action.slice("__create_page__:".length)
+ : action
const item = items.find((i) => i.id === id)
if (item) {
try {
@@ -170,7 +175,7 @@ export function ReviewView() {
const date = new Date().toISOString().slice(0, 10)
// Determine page type from review type or action text
- const pageType = detectPageType(action, item.type)
+ const pageType = detectPageType(realAction, item.type)
const dir = pageType === "query" ? "queries" : pageType === "entity" ? "entities" : pageType === "concept" ? "concepts" : "queries"
const fileName = `${slug}-${date}.md`
const filePath = `${pp}/wiki/${dir}/${fileName}`
diff --git a/src/components/search/search-view.tsx b/src/components/search/search-view.tsx
index 67f865ac..bcdc3725 100644
--- a/src/components/search/search-view.tsx
+++ b/src/components/search/search-view.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useRef, useCallback } from "react"
+import { useState, useCallback } from "react"
import { Search, FileText } from "lucide-react"
import { useWikiStore } from "@/stores/wiki-store"
import { readFile } from "@/commands/fs"
diff --git a/src/components/settings/context-size-selector.tsx b/src/components/settings/context-size-selector.tsx
new file mode 100644
index 00000000..c79c7199
--- /dev/null
+++ b/src/components/settings/context-size-selector.tsx
@@ -0,0 +1,70 @@
+const CONTEXT_PRESETS = [
+ { value: 4096, label: "4K" },
+ { value: 8192, label: "8K" },
+ { value: 16384, label: "16K" },
+ { value: 32768, label: "32K" },
+ { value: 65536, label: "64K" },
+ { value: 131072, label: "128K" },
+ { value: 204800, label: "200K" },
+ { value: 262144, label: "256K" },
+ { value: 524288, label: "512K" },
+ { value: 1000000, label: "1M" },
+]
+
+function formatSize(chars: number): string {
+ if (chars >= 1000000) return `${(chars / 1000000).toFixed(1)}M characters`
+ if (chars >= 1000) return `${Math.round(chars / 1000)}K characters`
+ return `${chars} characters`
+}
+
+export function ContextSizeSelector({
+ value,
+ onChange,
+}: {
+ value: number
+ onChange: (v: number) => void
+}) {
+ const closestIndex = CONTEXT_PRESETS.reduce((best, preset, i) => {
+ return Math.abs(preset.value - value) < Math.abs(CONTEXT_PRESETS[best].value - value)
+ ? i
+ : best
+ }, 0)
+ const pct = (closestIndex / (CONTEXT_PRESETS.length - 1)) * 100
+
+ return (
+ <div>
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-sm font-medium">{formatSize(value)}</span>
+ <span className="text-xs text-muted-foreground">
+ ~{Math.floor((value * 0.6) / 1000)}K chars for wiki content
+ </span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={CONTEXT_PRESETS.length - 1}
+ step={1}
+ value={closestIndex}
+ onChange={(e) => onChange(CONTEXT_PRESETS[parseInt(e.target.value)].value)}
+ className="w-full h-2 rounded-lg appearance-none cursor-pointer accent-primary"
+ style={{
+ background: `linear-gradient(to right, #4f46e5 ${pct}%, #e5e7eb ${pct}%)`,
+ }}
+ />
+ <div className="flex justify-between mt-1">
+ {CONTEXT_PRESETS.map((preset, i) => (
+ <button
+ key={preset.value}
+ type="button"
+ onClick={() => onChange(preset.value)}
+ className={`text-[9px] px-0.5 ${
+ i === closestIndex ? "text-primary font-bold" : "text-muted-foreground/50"
+ }`}
+ >
+ {preset.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/settings/llm-presets.ts b/src/components/settings/llm-presets.ts
new file mode 100644
index 00000000..67970c2d
--- /dev/null
+++ b/src/components/settings/llm-presets.ts
@@ -0,0 +1,318 @@
+/**
+ * Curated LLM provider presets.
+ *
+ * Selecting a preset pre-fills the underlying LlmConfig fields so users
+ * don't have to remember endpoint URLs / API mode per vendor. The
+ * dispatch code in `src/lib/llm-providers.ts` still branches on the
+ * lower-level `provider` field — presets just populate the config.
+ */
+export type CustomApiMode = "chat_completions" | "anthropic_messages"
+
+export type Provider =
+ | "openai"
+ | "anthropic"
+ | "google"
+ | "ollama"
+ | "custom"
+ | "minimax"
+
+export interface LlmPreset {
+ /** Stable id used as the dropdown value. */
+ id: string
+ /** Display label in the dropdown. */
+ label: string
+ /** Short subtitle shown under the label. */
+ hint?: string
+ /** Underlying provider dispatch key (see llm-providers.ts). */
+ provider: Provider
+ /** Suggested base URL. `customEndpoint` for custom, `ollamaUrl` for ollama, ignored for built-ins. */
+ baseUrl?: string
+ /** Suggested default model; user can override. */
+ defaultModel?: string
+ /**
+ * Curated list of model ids the UI shows as clickable chips above the
+ * Model input. The user can still type a custom value — the input stays
+ * free-form. An empty/missing list means "no suggestions, type freely"
+ * (e.g. Ollama Local where the model set is whatever the user pulled).
+ */
+ suggestedModels?: string[]
+ /** Custom providers only: which wire protocol to speak. */
+ apiMode?: CustomApiMode
+ /** Suggested context window; user can override. */
+ suggestedContextSize?: number
+}
+
+export const LLM_PRESETS: LlmPreset[] = [
+ {
+ id: "anthropic",
+ label: "Anthropic (Claude)",
+ hint: "Official Claude API",
+ provider: "anthropic",
+ defaultModel: "claude-sonnet-4-5-20250929",
+ // Cross-referenced with hermes-agent/hermes_cli/models.py:233-242.
+ // Both shortened and dated aliases work on api.anthropic.com.
+ suggestedModels: [
+ "claude-opus-4-7",
+ "claude-opus-4-6",
+ "claude-sonnet-4-6",
+ "claude-sonnet-4-5-20250929",
+ "claude-haiku-4-5-20251001",
+ "claude-opus-4-5-20251101",
+ "claude-sonnet-4-20250514",
+ "claude-3-5-sonnet-20241022",
+ "claude-3-5-haiku-20241022",
+ ],
+ suggestedContextSize: 200000,
+ },
+ {
+ id: "openai",
+ label: "OpenAI (GPT)",
+ hint: "Official OpenAI API",
+ provider: "openai",
+ defaultModel: "gpt-4o",
+ // Current public GPT models on api.openai.com. Reasoning models and
+ // the 4.1 family are both exposed under the chat/completions route.
+ suggestedModels: [
+ "gpt-4o",
+ "gpt-4o-mini",
+ "gpt-4.1",
+ "gpt-4.1-mini",
+ "gpt-4.1-nano",
+ "o3",
+ "o3-mini",
+ "o1",
+ "o1-mini",
+ "gpt-4-turbo",
+ ],
+ suggestedContextSize: 128000,
+ },
+ {
+ id: "google",
+ label: "Google (Gemini)",
+ hint: "Generative Language API",
+ provider: "google",
+ defaultModel: "gemini-2.5-flash",
+ // 2.5 generation is the current stable; 2.0 kept as fallback.
+ suggestedModels: [
+ "gemini-2.5-pro",
+ "gemini-2.5-flash",
+ "gemini-2.5-flash-lite",
+ "gemini-2.0-flash",
+ "gemini-2.0-flash-lite",
+ "gemini-1.5-pro",
+ "gemini-1.5-flash",
+ ],
+ suggestedContextSize: 1000000,
+ },
+ {
+ id: "deepseek",
+ label: "DeepSeek",
+ hint: "api.deepseek.com",
+ provider: "custom",
+ baseUrl: "https://api.deepseek.com/v1",
+ defaultModel: "deepseek-chat",
+ apiMode: "chat_completions",
+ // hermes models.py:243-246
+ suggestedModels: ["deepseek-chat", "deepseek-reasoner"],
+ suggestedContextSize: 64000,
+ },
+ {
+ id: "groq",
+ label: "Groq",
+ hint: "api.groq.com",
+ provider: "custom",
+ baseUrl: "https://api.groq.com/openai/v1",
+ defaultModel: "llama-3.3-70b-versatile",
+ apiMode: "chat_completions",
+ // Groq hosts open-weight models; list stays current-practical picks.
+ suggestedModels: [
+ "llama-3.3-70b-versatile",
+ "llama-3.1-8b-instant",
+ "llama-3.1-70b-versatile",
+ "mixtral-8x7b-32768",
+ "gemma2-9b-it",
+ "moonshotai/kimi-k2-instruct",
+ "openai/gpt-oss-120b",
+ "openai/gpt-oss-20b",
+ "qwen/qwen3-32b",
+ ],
+ suggestedContextSize: 128000,
+ },
+ {
+ id: "xai",
+ label: "xAI (Grok)",
+ hint: "api.x.ai",
+ provider: "custom",
+ baseUrl: "https://api.x.ai/v1",
+ defaultModel: "grok-3",
+ apiMode: "chat_completions",
+ suggestedModels: [
+ "grok-4-latest",
+ "grok-4",
+ "grok-3",
+ "grok-3-mini",
+ "grok-3-fast",
+ "grok-3-mini-fast",
+ "grok-code-fast-1",
+ "grok-2-vision-1212",
+ ],
+ suggestedContextSize: 131072,
+ },
+ {
+ id: "kimi",
+ label: "Kimi (Moonshot)",
+ hint: "api.moonshot.ai",
+ provider: "custom",
+ baseUrl: "https://api.moonshot.ai/v1",
+ defaultModel: "kimi-k2-0905-preview",
+ apiMode: "chat_completions",
+ // hermes models.py:198-212 — "kimi-coding" + "moonshot" sections.
+ suggestedModels: [
+ "kimi-k2-0905-preview",
+ "kimi-k2-turbo-preview",
+ "kimi-k2-thinking",
+ "kimi-k2-thinking-turbo",
+ "moonshot-v1-128k",
+ "moonshot-v1-32k",
+ "moonshot-v1-8k",
+ ],
+ suggestedContextSize: 128000,
+ },
+ {
+ id: "kimi-cn",
+ label: "Kimi (Moonshot, 中国)",
+ hint: "api.moonshot.cn",
+ provider: "custom",
+ baseUrl: "https://api.moonshot.cn/v1",
+ defaultModel: "kimi-k2-0905-preview",
+ apiMode: "chat_completions",
+ suggestedModels: [
+ "kimi-k2-0905-preview",
+ "kimi-k2-turbo-preview",
+ "kimi-k2-thinking",
+ "moonshot-v1-128k",
+ "moonshot-v1-32k",
+ "moonshot-v1-8k",
+ ],
+ suggestedContextSize: 128000,
+ },
+ {
+ id: "zhipu",
+ label: "智谱 GLM (Zhipu)",
+ hint: "open.bigmodel.cn",
+ provider: "custom",
+ baseUrl: "https://open.bigmodel.cn/api/paas/v4",
+ defaultModel: "glm-4-plus",
+ apiMode: "chat_completions",
+ // Zhipu BigModel stable models (current-gen 4.x + 4.6/4.7 preview).
+ suggestedModels: [
+ "glm-4-plus",
+ "glm-4-air",
+ "glm-4-airx",
+ "glm-4-flash",
+ "glm-4-long",
+ "glm-4.5",
+ "glm-4.5-flash",
+ "glm-4.6",
+ "glm-4.7",
+ ],
+ suggestedContextSize: 128000,
+ },
+ {
+ id: "minimax-global",
+ label: "MiniMax (Global)",
+ hint: "api.minimax.io/anthropic",
+ provider: "custom",
+ baseUrl: "https://api.minimax.io/anthropic",
+ defaultModel: "MiniMax-M2.7",
+ apiMode: "anthropic_messages",
+ // hermes models.py:221-226
+ suggestedModels: ["MiniMax-M2.7", "MiniMax-M2.5", "MiniMax-M2.1", "MiniMax-M2"],
+ suggestedContextSize: 200000,
+ },
+ {
+ id: "minimax-cn",
+ label: "MiniMax (中国)",
+ hint: "api.minimaxi.com/anthropic",
+ provider: "custom",
+ baseUrl: "https://api.minimaxi.com/anthropic",
+ defaultModel: "MiniMax-M2.7",
+ apiMode: "anthropic_messages",
+ suggestedModels: ["MiniMax-M2.7", "MiniMax-M2.5", "MiniMax-M2.1", "MiniMax-M2"],
+ suggestedContextSize: 200000,
+ },
+ {
+ id: "ollama-local",
+ label: "Ollama (Local)",
+ hint: "Self-hosted llama.cpp / Ollama",
+ provider: "ollama",
+ baseUrl: "http://localhost:11434",
+ // Intentionally no suggestedModels: local set depends on what the
+ // user has actually pulled / loaded. Kept as free-text input.
+ suggestedContextSize: 32768,
+ },
+ {
+ id: "ollama-cloud",
+ label: "Ollama Cloud",
+ hint: "ollama.com",
+ provider: "custom",
+ baseUrl: "https://ollama.com/v1",
+ apiMode: "chat_completions",
+ // Ollama Cloud catalog rotates frequently — keep short common picks.
+ suggestedModels: [
+ "gpt-oss:120b",
+ "gpt-oss:20b",
+ "qwen3-coder:480b",
+ "kimi-k2:1t",
+ "deepseek-v3.1:671b",
+ ],
+ suggestedContextSize: 128000,
+ },
+ {
+ id: "custom-openai",
+ label: "Custom (OpenAI-compat)",
+ hint: "Any /v1/chat/completions endpoint",
+ provider: "custom",
+ apiMode: "chat_completions",
+ // No suggestedModels: user knows what their gateway exposes.
+ },
+ {
+ id: "custom-anthropic",
+ label: "Custom (Anthropic-compat)",
+ hint: "Any /v1/messages endpoint",
+ provider: "custom",
+ apiMode: "anthropic_messages",
+ },
+]
+
+/**
+ * Best-effort reverse lookup: given the current LlmConfig fields, which
+ * preset does it most likely correspond to? Used so the dropdown can
+ * show the user what they're effectively on.
+ */
+export function matchPreset(params: {
+ provider: Provider
+ customEndpoint: string
+ ollamaUrl: string
+ apiMode?: CustomApiMode
+}): LlmPreset | null {
+ const norm = (u: string) => u.replace(/\/+$/, "").toLowerCase()
+ const { provider, customEndpoint, ollamaUrl, apiMode } = params
+
+ for (const preset of LLM_PRESETS) {
+ if (preset.provider !== provider) continue
+ if (provider === "custom") {
+ if (!preset.baseUrl) continue // skip the generic Custom catch-alls
+ if (norm(preset.baseUrl) !== norm(customEndpoint)) continue
+ if ((preset.apiMode ?? "chat_completions") !== (apiMode ?? "chat_completions"))
+ continue
+ return preset
+ }
+ if (provider === "ollama") {
+ if (preset.baseUrl && norm(preset.baseUrl) !== norm(ollamaUrl)) continue
+ return preset
+ }
+ return preset
+ }
+ return null
+}
diff --git a/src/components/settings/preset-resolver.ts b/src/components/settings/preset-resolver.ts
new file mode 100644
index 00000000..7bbead0a
--- /dev/null
+++ b/src/components/settings/preset-resolver.ts
@@ -0,0 +1,55 @@
+import type { LlmConfig } from "@/stores/wiki-store"
+import type { ProviderOverride } from "@/stores/wiki-store"
+import type { LlmPreset } from "./llm-presets"
+
+/**
+ * Build a full LlmConfig from a preset template + the user's saved
+ * override fields for that preset. Falls back to the preset defaults
+ * (or the existing LlmConfig) when an override is missing.
+ */
+export function resolveConfig(
+ preset: LlmPreset,
+ override: ProviderOverride | undefined,
+ fallback: LlmConfig,
+): LlmConfig {
+ const ov = override ?? {}
+ const apiKey = ov.apiKey ?? ""
+ const model = ov.model ?? preset.defaultModel ?? ""
+ const maxContextSize =
+ ov.maxContextSize ?? preset.suggestedContextSize ?? fallback.maxContextSize
+
+ if (preset.provider === "custom") {
+ return {
+ provider: "custom",
+ apiKey,
+ model,
+ ollamaUrl: fallback.ollamaUrl,
+ customEndpoint: ov.baseUrl ?? preset.baseUrl ?? "",
+ maxContextSize,
+ apiMode: ov.apiMode ?? preset.apiMode ?? "chat_completions",
+ }
+ }
+
+ if (preset.provider === "ollama") {
+ return {
+ provider: "ollama",
+ apiKey: "",
+ model,
+ ollamaUrl: ov.baseUrl ?? preset.baseUrl ?? "http://localhost:11434",
+ customEndpoint: fallback.customEndpoint,
+ maxContextSize,
+ }
+ }
+
+ // openai / anthropic / google / minimax — use fixed endpoint baked into the
+ // provider dispatch. We still let users override baseUrl via apiKey env if
+ // needed by editing manually, but presets for these don't expose it.
+ return {
+ provider: preset.provider,
+ apiKey,
+ model,
+ ollamaUrl: fallback.ollamaUrl,
+ customEndpoint: fallback.customEndpoint,
+ maxContextSize,
+ }
+}
diff --git a/src/components/settings/sections/about-section.tsx b/src/components/settings/sections/about-section.tsx
new file mode 100644
index 00000000..e30005e5
--- /dev/null
+++ b/src/components/settings/sections/about-section.tsx
@@ -0,0 +1,61 @@
+import { useEffect, useState } from "react"
+import { clipServerStatus } from "@/commands/fs"
+
+export function AboutSection() {
+ const [clipStatus, setClipStatus] = useState<string>("...")
+
+ useEffect(() => {
+ let alive = true
+ clipServerStatus()
+ .then((s) => {
+ if (alive) setClipStatus(s)
+ })
+ .catch(() => {
+ if (alive) setClipStatus("unknown")
+ })
+ return () => {
+ alive = false
+ }
+ }, [])
+
+ const rows: Array<{ label: string; value: string; mono?: boolean }> = [
+ { label: "版本", value: `v${__APP_VERSION__}`, mono: true },
+ { label: "Clip Server", value: `${clipStatus} @ 127.0.0.1:19827`, mono: true },
+ ]
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h2 className="text-xl font-semibold">关于</h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ 构建信息和运行时状态。
+ </p>
+ </div>
+
+ <div className="rounded-md border divide-y">
+ {rows.map((r) => (
+ <div key={r.label} className="flex items-center justify-between px-4 py-2.5">
+ <span className="text-sm text-muted-foreground">{r.label}</span>
+ <span className={`text-sm ${r.mono ? "font-mono" : ""}`}>{r.value}</span>
+ </div>
+ ))}
+ </div>
+
+ <div className="rounded-md border p-4 text-sm">
+ <div className="font-medium">LLM Wiki</div>
+ <p className="mt-1 text-xs text-muted-foreground">
+ An LLM-driven personal knowledge base. Source:
+ {" "}
+ <a
+ className="underline underline-offset-2 hover:text-primary"
+ href="https://github.com/nashsu/llm_wiki"
+ target="_blank"
+ rel="noreferrer"
+ >
+ github.com/nashsu/llm_wiki
+ </a>
+ </p>
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/settings/sections/embedding-section.tsx b/src/components/settings/sections/embedding-section.tsx
new file mode 100644
index 00000000..a8bfa279
--- /dev/null
+++ b/src/components/settings/sections/embedding-section.tsx
@@ -0,0 +1,76 @@
+import { Input } from "@/components/ui/input"
+import { Label } from "@/components/ui/label"
+import type { SettingsDraft, DraftSetter } from "../settings-types"
+
+interface Props {
+ draft: SettingsDraft
+ setDraft: DraftSetter
+}
+
+export function EmbeddingSection({ draft, setDraft }: Props) {
+ return (
+ <div className="space-y-6">
+ <div>
+ <h2 className="text-xl font-semibold">向量嵌入</h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ 启用语义搜索。对任何 OpenAI 兼容的 /v1/embeddings endpoint 工作。
+ 本地模型(如 LM Studio、Ollama embedding)不需要 API Key。
+ </p>
+ </div>
+
+ <div className="flex items-center justify-between rounded-md border p-3">
+ <div>
+ <div className="text-sm font-medium">启用向量搜索</div>
+ <div className="text-xs text-muted-foreground">
+ 关掉后搜索只走 token 匹配。
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={() => setDraft("embeddingEnabled", !draft.embeddingEnabled)}
+ className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${
+ draft.embeddingEnabled ? "bg-primary" : "bg-muted"
+ }`}
+ >
+ <span
+ className={`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${
+ draft.embeddingEnabled ? "translate-x-4.5" : "translate-x-0.5"
+ }`}
+ />
+ </button>
+ </div>
+
+ {draft.embeddingEnabled && (
+ <>
+ <div className="space-y-2">
+ <Label>Endpoint</Label>
+ <Input
+ value={draft.embeddingEndpoint}
+ onChange={(e) => setDraft("embeddingEndpoint", e.target.value)}
+ placeholder="http://127.0.0.1:1234/v1/embeddings"
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label>API Key (optional)</Label>
+ <Input
+ type="password"
+ value={draft.embeddingApiKey}
+ onChange={(e) => setDraft("embeddingApiKey", e.target.value)}
+ placeholder="本地模型留空即可"
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label>Model</Label>
+ <Input
+ value={draft.embeddingModel}
+ onChange={(e) => setDraft("embeddingModel", e.target.value)}
+ placeholder="e.g. text-embedding-qwen3-embedding-0.6b"
+ />
+ </div>
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/settings/sections/interface-section.tsx b/src/components/settings/sections/interface-section.tsx
new file mode 100644
index 00000000..954f287c
--- /dev/null
+++ b/src/components/settings/sections/interface-section.tsx
@@ -0,0 +1,51 @@
+import { Label } from "@/components/ui/label"
+import type { SettingsDraft, DraftSetter } from "../settings-types"
+
+interface Props {
+ draft: SettingsDraft
+ setDraft: DraftSetter
+}
+
+const UI_LANGUAGES = [
+ { value: "en", label: "English" },
+ { value: "zh", label: "中文" },
+]
+
+export function InterfaceSection({ draft, setDraft }: Props) {
+ return (
+ <div className="space-y-6">
+ <div>
+ <h2 className="text-xl font-semibold">界面</h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ 应用 UI 的显示语言。切换后立即生效并持久化。
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <Label>UI 语言</Label>
+ <div className="flex flex-wrap gap-2">
+ {UI_LANGUAGES.map((l) => {
+ const active = draft.uiLanguage === l.value
+ return (
+ <button
+ key={l.value}
+ type="button"
+ onClick={() => setDraft("uiLanguage", l.value)}
+ className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
+ active
+ ? "border-primary bg-primary text-primary-foreground"
+ : "border-border hover:bg-accent"
+ }`}
+ >
+ {l.label}
+ </button>
+ )
+ })}
+ </div>
+ <p className="text-xs text-muted-foreground">
+ 只影响按钮、标签这些 UI 文案,不影响 AI 输出语言(那个在"输出偏好"里单独设置)。
+ </p>
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/settings/sections/llm-provider-section.tsx b/src/components/settings/sections/llm-provider-section.tsx
new file mode 100644
index 00000000..96bd17da
--- /dev/null
+++ b/src/components/settings/sections/llm-provider-section.tsx
@@ -0,0 +1,396 @@
+import { useMemo, useState } from "react"
+import { ChevronDown, ChevronRight, AlertCircle, CheckCircle2 } from "lucide-react"
+import { Input } from "@/components/ui/input"
+import { Label } from "@/components/ui/label"
+import { useWikiStore, type ProviderOverride } from "@/stores/wiki-store"
+import { LLM_PRESETS, type LlmPreset } from "../llm-presets"
+import { ContextSizeSelector } from "../context-size-selector"
+import { resolveConfig } from "../preset-resolver"
+import { normalizeEndpoint } from "@/lib/endpoint-normalizer"
+
+export function LlmProviderSection() {
+ const providerConfigs = useWikiStore((s) => s.providerConfigs)
+ const setProviderConfigs = useWikiStore((s) => s.setProviderConfigs)
+ const activePresetId = useWikiStore((s) => s.activePresetId)
+ const setActivePresetId = useWikiStore((s) => s.setActivePresetId)
+ const setLlmConfig = useWikiStore((s) => s.setLlmConfig)
+ const llmConfig = useWikiStore((s) => s.llmConfig)
+
+ const [expanded, setExpanded] = useState<Record<string, boolean>>({})
+ const [savedId, setSavedId] = useState<string | null>(null)
+
+ function toggleExpand(id: string) {
+ setExpanded((prev) => ({ ...prev, [id]: !prev[id] }))
+ }
+
+ async function persist(newConfigs: typeof providerConfigs, newActive: string | null) {
+ const { saveProviderConfigs, saveActivePresetId, saveLlmConfig } = await import(
+ "@/lib/project-store"
+ )
+ await saveProviderConfigs(newConfigs)
+ await saveActivePresetId(newActive)
+ if (newActive) {
+ const preset = LLM_PRESETS.find((p) => p.id === newActive)
+ if (preset) {
+ const resolved = resolveConfig(preset, newConfigs[newActive], llmConfig)
+ setLlmConfig(resolved)
+ await saveLlmConfig(resolved)
+ }
+ }
+ }
+
+ function updateOverride(id: string, patch: ProviderOverride) {
+ const merged: ProviderOverride = { ...(providerConfigs[id] ?? {}), ...patch }
+ const next = { ...providerConfigs, [id]: merged }
+ setProviderConfigs(next)
+ persist(next, activePresetId).catch(() => {})
+ // If this preset is active, refresh the resolved LlmConfig live.
+ if (id === activePresetId) {
+ const preset = LLM_PRESETS.find((p) => p.id === id)
+ if (preset) setLlmConfig(resolveConfig(preset, merged, llmConfig))
+ }
+ setSavedId(id)
+ setTimeout(() => setSavedId((cur) => (cur === id ? null : cur)), 1500)
+ }
+
+ function toggleActive(id: string) {
+ const next = id === activePresetId ? null : id
+ setActivePresetId(next)
+ persist(providerConfigs, next).catch(() => {})
+ }
+
+ return (
+ <div className="space-y-4">
+ <div>
+ <h2 className="text-xl font-semibold">LLM 模型</h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ 每个厂商一条独立配置。打开开关即切换为当前活跃 provider;其他的会自动关闭。
+ 配置改动即时保存,每个厂商的 API Key 独立存储,切换之间不丢失。
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ {LLM_PRESETS.map((preset) => (
+ <PresetRow
+ key={preset.id}
+ preset={preset}
+ override={providerConfigs[preset.id]}
+ isActive={activePresetId === preset.id}
+ isExpanded={!!expanded[preset.id]}
+ savedHere={savedId === preset.id}
+ onToggleActive={() => toggleActive(preset.id)}
+ onToggleExpand={() => toggleExpand(preset.id)}
+ onChange={(patch) => updateOverride(preset.id, patch)}
+ />
+ ))}
+ </div>
+ </div>
+ )
+}
+
+interface PresetRowProps {
+ preset: LlmPreset
+ override: ProviderOverride | undefined
+ isActive: boolean
+ isExpanded: boolean
+ savedHere: boolean
+ onToggleActive: () => void
+ onToggleExpand: () => void
+ onChange: (patch: ProviderOverride) => void
+}
+
+function PresetRow({
+ preset,
+ override,
+ isActive,
+ isExpanded,
+ savedHere,
+ onToggleActive,
+ onToggleExpand,
+ onChange,
+}: PresetRowProps) {
+ const ov = override ?? {}
+ const model = ov.model ?? preset.defaultModel ?? ""
+ const apiKey = ov.apiKey ?? ""
+ const apiMode = ov.apiMode ?? preset.apiMode ?? "chat_completions"
+ const baseUrl = ov.baseUrl ?? preset.baseUrl ?? ""
+ const context = ov.maxContextSize ?? preset.suggestedContextSize ?? 131072
+ const hasConfig = !!apiKey || !!ov.baseUrl || !!ov.model
+ const needsApiKey = preset.provider !== "ollama"
+
+ return (
+ <div
+ className={`rounded-lg border transition-colors ${
+ isActive ? "border-primary/60 bg-primary/5" : "border-border"
+ }`}
+ >
+ {/* Outer row — always visible */}
+ <div className="flex items-center gap-3 px-3 py-2.5">
+ <button
+ type="button"
+ onClick={onToggleExpand}
+ className="shrink-0 rounded p-0.5 text-muted-foreground hover:bg-accent"
+ title={isExpanded ? "收起" : "展开配置"}
+ >
+ {isExpanded ? (
+ <ChevronDown className="h-4 w-4" />
+ ) : (
+ <ChevronRight className="h-4 w-4" />
+ )}
+ </button>
+
+ <button
+ type="button"
+ onClick={onToggleExpand}
+ className="min-w-0 flex-1 text-left"
+ >
+ <div className="flex items-center gap-2">
+ <span className="truncate text-sm font-medium">{preset.label}</span>
+ {hasConfig && !isActive && (
+ <span className="shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
+ 已配置
+ </span>
+ )}
+ {isActive && (
+ <span className="shrink-0 rounded-full bg-primary/20 px-1.5 py-0.5 text-[10px] font-medium text-primary">
+ ● 活跃
+ </span>
+ )}
+ {savedHere && (
+ <span className="shrink-0 text-[10px] text-emerald-600">已保存</span>
+ )}
+ </div>
+ {preset.hint && (
+ <div className="mt-0.5 truncate text-xs text-muted-foreground">
+ {preset.hint}
+ </div>
+ )}
+ </button>
+
+ {/* Toggle switch */}
+ <button
+ type="button"
+ onClick={onToggleActive}
+ className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full border transition-colors ${
+ isActive
+ ? "border-primary bg-primary"
+ : "border-muted-foreground/30 bg-muted-foreground/20 hover:bg-muted-foreground/30"
+ }`}
+ title={isActive ? "点击关闭" : "点击启用(会关闭其他 provider)"}
+ aria-label={isActive ? "Deactivate" : "Activate"}
+ >
+ <span
+ className={`inline-block h-3.5 w-3.5 rounded-full bg-white shadow-sm ring-1 ring-black/10 transition-transform ${
+ isActive ? "translate-x-4" : "translate-x-0.5"
+ }`}
+ />
+ </button>
+ </div>
+
+ {/* Expanded config panel */}
+ {isExpanded && (
+ <div className="space-y-4 border-t bg-background/50 px-4 py-3">
+ {preset.provider === "custom" && (
+ <div className="space-y-2">
+ <Label>API 模式</Label>
+ <div className="flex flex-wrap gap-2">
+ {(
+ [
+ { value: "chat_completions", label: "OpenAI 兼容" },
+ { value: "anthropic_messages", label: "Anthropic 兼容" },
+ ] as const
+ ).map((m) => {
+ const active = apiMode === m.value
+ return (
+ <button
+ key={m.value}
+ type="button"
+ onClick={() => onChange({ apiMode: m.value })}
+ className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
+ active
+ ? "border-primary bg-primary text-primary-foreground"
+ : "border-border hover:bg-accent"
+ }`}
+ >
+ {m.label}
+ </button>
+ )
+ })}
+ </div>
+ </div>
+ )}
+
+ {(preset.provider === "custom" || preset.provider === "ollama") && (
+ <EndpointField
+ value={baseUrl}
+ mode={apiMode}
+ placeholder={preset.baseUrl ?? "https://your-api.example.com/v1"}
+ onChange={(v) => onChange({ baseUrl: v })}
+ />
+ )}
+
+ {needsApiKey && (
+ <div className="space-y-2">
+ <Label>API Key</Label>
+ <Input
+ type="password"
+ value={apiKey}
+ onChange={(e) => onChange({ apiKey: e.target.value })}
+ placeholder={
+ preset.provider === "custom"
+ ? "无 Key 可留空(本地模型)"
+ : "Enter your API key"
+ }
+ />
+ </div>
+ )}
+
+ <div className="space-y-2">
+ <Label>Model</Label>
+ <ModelPicker
+ value={model}
+ suggestions={preset.suggestedModels ?? []}
+ placeholder={preset.defaultModel ?? "e.g. gpt-4o"}
+ onChange={(v) => onChange({ model: v })}
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label>Context window</Label>
+ <ContextSizeSelector
+ value={context}
+ onChange={(v) => onChange({ maxContextSize: v })}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
+
+interface EndpointFieldProps {
+ value: string
+ mode: "chat_completions" | "anthropic_messages"
+ placeholder: string
+ onChange: (value: string) => void
+}
+
+/**
+ * Endpoint input with live feedback + auto-fix on blur. The hint line
+ * below the field tells the user what we'd normalize to (and why) while
+ * they're typing; the input doesn't nag — it just shows the preview. On
+ * blur, if normalization would change the value, we apply it.
+ */
+function EndpointField({ value, mode, placeholder, onChange }: EndpointFieldProps) {
+ const preview = useMemo(() => normalizeEndpoint(value, mode), [value, mode])
+
+ function handleBlur() {
+ if (preview.changed && preview.normalized !== value.trim()) {
+ onChange(preview.normalized)
+ }
+ }
+
+ const showHint = value.trim().length > 0 && (preview.changed || preview.warning)
+
+ return (
+ <div className="space-y-1.5">
+ <Label>Endpoint</Label>
+ <Input
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ onBlur={handleBlur}
+ placeholder={placeholder}
+ />
+ {showHint && (
+ <div
+ className={`flex items-start gap-1.5 rounded-md border px-2 py-1.5 text-xs ${
+ preview.changed
+ ? "border-amber-500/40 bg-amber-500/5 text-amber-700 dark:text-amber-400"
+ : "border-blue-500/40 bg-blue-500/5 text-blue-700 dark:text-blue-400"
+ }`}
+ >
+ {preview.changed ? (
+ <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ ) : (
+ <CheckCircle2 className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ )}
+ <div className="min-w-0 flex-1 space-y-0.5">
+ {preview.changed && (
+ <div>
+ 将使用 <code className="break-all rounded bg-background/60 px-1 py-0.5 font-mono">{preview.normalized || "(empty)"}</code>
+ <span className="ml-1 text-muted-foreground">(离开输入框时自动套用)</span>
+ </div>
+ )}
+ {preview.warning && <div>{preview.warning}</div>}
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
+
+interface ModelPickerProps {
+ value: string
+ suggestions: string[]
+ placeholder: string
+ onChange: (value: string) => void
+}
+
+/**
+ * Model input with a chip-based suggestion row above it. The input stays
+ * free-text so users can always type unlisted models (fine-tunes, preview
+ * IDs, local Ollama tags, etc.). Clicking a chip just fills the input.
+ *
+ * The currently-selected chip (if the value matches one of the suggestions)
+ * gets the accent highlight so users can see at a glance which preset
+ * model is active without reading the text field. Presets with no
+ * `suggestedModels` render the input alone.
+ */
+function ModelPicker({ value, suggestions, placeholder, onChange }: ModelPickerProps) {
+ const hasSuggestions = suggestions.length > 0
+ const isCustom = hasSuggestions && value.length > 0 && !suggestions.includes(value)
+
+ return (
+ <div className="space-y-2">
+ {hasSuggestions && (
+ <div className="flex flex-wrap gap-1.5">
+ {suggestions.map((m) => {
+ const active = m === value
+ return (
+ <button
+ key={m}
+ type="button"
+ onClick={() => onChange(m)}
+ className={`rounded-md border px-2 py-0.5 text-xs font-mono transition-colors ${
+ active
+ ? "border-primary bg-primary text-primary-foreground"
+ : "border-border bg-background hover:bg-accent hover:text-accent-foreground"
+ }`}
+ title={`Use ${m}`}
+ >
+ {m}
+ </button>
+ )
+ })}
+ <button
+ type="button"
+ onClick={() => onChange("")}
+ className={`rounded-md border px-2 py-0.5 text-xs transition-colors ${
+ isCustom
+ ? "border-primary/60 bg-primary/10 text-primary"
+ : "border-dashed border-muted-foreground/40 text-muted-foreground hover:bg-accent hover:text-accent-foreground"
+ }`}
+ title="Type a custom model id"
+ >
+ {isCustom ? `Custom: ${value}` : "Custom…"}
+ </button>
+ </div>
+ )}
+ <Input
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ />
+ </div>
+ )
+}
diff --git a/src/components/settings/sections/output-section.tsx b/src/components/settings/sections/output-section.tsx
new file mode 100644
index 00000000..db80a03d
--- /dev/null
+++ b/src/components/settings/sections/output-section.tsx
@@ -0,0 +1,94 @@
+import { Label } from "@/components/ui/label"
+import type { SettingsDraft, DraftSetter } from "../settings-types"
+
+interface Props {
+ draft: SettingsDraft
+ setDraft: DraftSetter
+}
+
+const LANGUAGE_OPTIONS = [
+ { value: "auto", label: "Auto (detect from input/source)" },
+ { value: "English", label: "English" },
+ { value: "Chinese", label: "简体中文 (Simplified Chinese)" },
+ { value: "Traditional Chinese", label: "繁體中文 (Traditional Chinese)" },
+ { value: "Japanese", label: "日本語 (Japanese)" },
+ { value: "Korean", label: "한국어 (Korean)" },
+ { value: "Vietnamese", label: "Tiếng Việt (Vietnamese)" },
+ { value: "French", label: "Français (French)" },
+ { value: "German", label: "Deutsch (German)" },
+ { value: "Spanish", label: "Español (Spanish)" },
+ { value: "Portuguese", label: "Português (Portuguese)" },
+ { value: "Italian", label: "Italiano (Italian)" },
+ { value: "Russian", label: "Русский (Russian)" },
+ { value: "Arabic", label: "العربية (Arabic)" },
+ { value: "Hindi", label: "हिन्दी (Hindi)" },
+ { value: "Turkish", label: "Türkçe (Turkish)" },
+ { value: "Dutch", label: "Nederlands (Dutch)" },
+ { value: "Polish", label: "Polski (Polish)" },
+ { value: "Swedish", label: "Svenska (Swedish)" },
+ { value: "Indonesian", label: "Bahasa Indonesia (Indonesian)" },
+ { value: "Thai", label: "ไทย (Thai)" },
+]
+
+const HISTORY_OPTIONS = [2, 4, 6, 8, 10, 20]
+
+export function OutputSection({ draft, setDraft }: Props) {
+ return (
+ <div className="space-y-6">
+ <div>
+ <h2 className="text-xl font-semibold">输出偏好</h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ 控制 AI 生成内容的语言和对话上下文长度。
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <Label>AI 输出语言</Label>
+ <p className="text-xs text-muted-foreground">
+ 强制 AI 生成内容(chat 回复、wiki 页面、research 结果、lint 报告)使用指定语言。
+ 选 "Auto" 让 AI 跟随用户输入或源文档的语言。
+ </p>
+ <select
+ value={draft.outputLanguage}
+ onChange={(e) => setDraft("outputLanguage", e.target.value)}
+ className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
+ >
+ {LANGUAGE_OPTIONS.map((l) => (
+ <option key={l.value} value={l.value}>
+ {l.label}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <div className="space-y-2">
+ <Label>对话历史长度</Label>
+ <p className="text-xs text-muted-foreground">
+ 每次请求发给 AI 的历史消息条数。多 = 上下文更完整但更费 token。
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {HISTORY_OPTIONS.map((n) => {
+ const active = draft.maxHistoryMessages === n
+ return (
+ <button
+ key={n}
+ type="button"
+ onClick={() => setDraft("maxHistoryMessages", n)}
+ className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
+ active
+ ? "border-primary bg-primary text-primary-foreground"
+ : "border-border hover:bg-accent"
+ }`}
+ >
+ {n}
+ </button>
+ )
+ })}
+ </div>
+ <p className="text-xs text-muted-foreground">
+ 当前 {draft.maxHistoryMessages} 条消息(约 {draft.maxHistoryMessages / 2} 轮对话)
+ </p>
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/settings/sections/web-search-section.tsx b/src/components/settings/sections/web-search-section.tsx
new file mode 100644
index 00000000..bed91826
--- /dev/null
+++ b/src/components/settings/sections/web-search-section.tsx
@@ -0,0 +1,61 @@
+import { Input } from "@/components/ui/input"
+import { Label } from "@/components/ui/label"
+import type { SettingsDraft, DraftSetter } from "../settings-types"
+
+interface Props {
+ draft: SettingsDraft
+ setDraft: DraftSetter
+}
+
+export function WebSearchSection({ draft, setDraft }: Props) {
+ const options = [
+ { value: "none" as const, label: "Disabled" },
+ { value: "tavily" as const, label: "Tavily" },
+ ]
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h2 className="text-xl font-semibold">网页搜索 (Deep Research)</h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ 允许 AI 在发现知识缺口时自动调用网页搜索补充资料。目前接入 Tavily。
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <Label>搜索 Provider</Label>
+ <div className="flex flex-wrap gap-2">
+ {options.map((p) => {
+ const active = draft.searchProvider === p.value
+ return (
+ <button
+ key={p.value}
+ type="button"
+ onClick={() => setDraft("searchProvider", p.value)}
+ className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
+ active
+ ? "border-primary bg-primary text-primary-foreground"
+ : "border-border hover:bg-accent"
+ }`}
+ >
+ {p.label}
+ </button>
+ )
+ })}
+ </div>
+ </div>
+
+ {draft.searchProvider !== "none" && (
+ <div className="space-y-2">
+ <Label>API Key</Label>
+ <Input
+ type="password"
+ value={draft.searchApiKey}
+ onChange={(e) => setDraft("searchApiKey", e.target.value)}
+ placeholder="Enter your Tavily API key (tavily.com)"
+ />
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/settings/settings-types.ts b/src/components/settings/settings-types.ts
new file mode 100644
index 00000000..a74a8e82
--- /dev/null
+++ b/src/components/settings/settings-types.ts
@@ -0,0 +1,40 @@
+import type { CustomApiMode } from "./llm-presets"
+
+/**
+ * Shape of the draft state each section reads from and writes into.
+ * The parent (SettingsView) owns one instance and hands it to every
+ * section; the Save button at the bottom flushes the whole draft to
+ * stores + disk in one commit.
+ */
+export interface SettingsDraft {
+ // LLM provider
+ provider: "openai" | "anthropic" | "google" | "ollama" | "custom" | "minimax"
+ apiKey: string
+ model: string
+ ollamaUrl: string
+ customEndpoint: string
+ maxContextSize: number
+ apiMode: CustomApiMode | undefined
+
+ // Embedding
+ embeddingEnabled: boolean
+ embeddingEndpoint: string
+ embeddingApiKey: string
+ embeddingModel: string
+
+ // Web search
+ searchProvider: "tavily" | "none"
+ searchApiKey: string
+
+ // Output preferences
+ outputLanguage: string
+ maxHistoryMessages: number
+
+ // UI
+ uiLanguage: string
+}
+
+export type DraftSetter = <K extends keyof SettingsDraft>(
+ key: K,
+ value: SettingsDraft[K],
+) => void
diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsx
index e173261a..95bb918a 100644
--- a/src/components/settings/settings-view.tsx
+++ b/src/components/settings/settings-view.tsx
@@ -1,31 +1,77 @@
+import { useCallback, useEffect, useMemo, useState } from "react"
+import {
+ Bot,
+ Binary,
+ Globe,
+ Languages,
+ Palette,
+ Info,
+} from "lucide-react"
+import i18n from "@/i18n"
+import { Button } from "@/components/ui/button"
import { useWikiStore } from "@/stores/wiki-store"
import { useChatStore } from "@/stores/chat-store"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import { Label } from "@/components/ui/label"
-import { useState, useEffect } from "react"
-import { useTranslation } from "react-i18next"
-import i18n from "@/i18n"
import { saveLanguage } from "@/lib/project-store"
+import type { SettingsDraft, DraftSetter } from "./settings-types"
+import { LlmProviderSection } from "./sections/llm-provider-section"
+import { EmbeddingSection } from "./sections/embedding-section"
+import { WebSearchSection } from "./sections/web-search-section"
+import { OutputSection } from "./sections/output-section"
+import { InterfaceSection } from "./sections/interface-section"
+import { AboutSection } from "./sections/about-section"
+
+type CategoryId =
+ | "llm"
+ | "embedding"
+ | "web-search"
+ | "output"
+ | "interface"
+ | "about"
+
+interface Category {
+ id: CategoryId
+ label: string
+ icon: typeof Bot
+}
-const PROVIDERS = [
- { value: "openai" as const, label: "OpenAI", models: ["gpt-4o", "gpt-4.1", "gpt-4o-mini"] },
- { value: "anthropic" as const, label: "Anthropic", models: ["claude-sonnet-4-5-20250514", "claude-opus-4-5-20250514", "claude-haiku-4-5-20251001"] },
- { value: "google" as const, label: "Google", models: ["gemini-2.5-pro", "gemini-2.5-flash"] },
- { value: "minimax" as const, label: "MiniMax", models: ["MiniMax-M2.7", "MiniMax-M2.7-highspeed"] },
- { value: "ollama" as const, label: "Ollama (Local)", models: [] },
- { value: "custom" as const, label: "Custom", models: [] },
-]
-
-const LANGUAGES = [
- { value: "en", label: "English" },
- { value: "zh", label: "中文" },
+const CATEGORIES: Category[] = [
+ { id: "llm", label: "LLM 模型", icon: Bot },
+ { id: "embedding", label: "向量嵌入", icon: Binary },
+ { id: "web-search", label: "网页搜索", icon: Globe },
+ { id: "output", label: "输出偏好", icon: Languages },
+ { id: "interface", label: "界面", icon: Palette },
+ { id: "about", label: "关于", icon: Info },
]
-const HISTORY_OPTIONS = [2, 4, 6, 8, 10, 20]
+function initialDraft(
+ llm: ReturnType<typeof useWikiStore.getState>["llmConfig"],
+ search: ReturnType<typeof useWikiStore.getState>["searchApiConfig"],
+ embed: ReturnType<typeof useWikiStore.getState>["embeddingConfig"],
+ outputLanguage: ReturnType<typeof useWikiStore.getState>["outputLanguage"],
+ maxHistoryMessages: number,
+ uiLanguage: string,
+): SettingsDraft {
+ return {
+ provider: llm.provider,
+ apiKey: llm.apiKey,
+ model: llm.model,
+ ollamaUrl: llm.ollamaUrl,
+ customEndpoint: llm.customEndpoint,
+ maxContextSize: llm.maxContextSize ?? 204800,
+ apiMode: llm.apiMode,
+ embeddingEnabled: embed.enabled,
+ embeddingEndpoint: embed.endpoint,
+ embeddingApiKey: embed.apiKey,
+ embeddingModel: embed.model,
+ searchProvider: search.provider,
+ searchApiKey: search.apiKey,
+ outputLanguage,
+ maxHistoryMessages,
+ uiLanguage,
+ }
+}
export function SettingsView() {
- const { t } = useTranslation()
const llmConfig = useWikiStore((s) => s.llmConfig)
const setLlmConfig = useWikiStore((s) => s.setLlmConfig)
const searchApiConfig = useWikiStore((s) => s.searchApiConfig)
@@ -37,445 +83,173 @@ export function SettingsView() {
const maxHistoryMessages = useChatStore((s) => s.maxHistoryMessages)
const setMaxHistoryMessages = useChatStore((s) => s.setMaxHistoryMessages)
- const [provider, setProvider] = useState(llmConfig.provider)
- const [apiKey, setApiKey] = useState(llmConfig.apiKey)
- const [model, setModel] = useState(llmConfig.model)
- const [ollamaUrl, setOllamaUrl] = useState(llmConfig.ollamaUrl)
- const [customEndpoint, setCustomEndpoint] = useState(llmConfig.customEndpoint)
- const [maxContextSize, setMaxContextSize] = useState(llmConfig.maxContextSize ?? 204800)
- const [searchProvider, setSearchProvider] = useState(searchApiConfig.provider)
- const [searchApiKey, setSearchApiKey] = useState(searchApiConfig.apiKey)
- const [embeddingEnabled, setEmbeddingEnabled] = useState(embeddingConfig.enabled)
- const [embeddingEndpoint, setEmbeddingEndpoint] = useState(embeddingConfig.endpoint)
- const [embeddingApiKey, setEmbeddingApiKey] = useState(embeddingConfig.apiKey)
- const [embeddingModel, setEmbeddingModel] = useState(embeddingConfig.model)
- const [localOutputLang, setLocalOutputLang] = useState(outputLanguage)
+ const [active, setActive] = useState<CategoryId>("llm")
const [saved, setSaved] = useState(false)
- const [currentLang, setCurrentLang] = useState(i18n.language)
-
- useEffect(() => {
- setProvider(llmConfig.provider)
- setApiKey(llmConfig.apiKey)
- setModel(llmConfig.model)
- setOllamaUrl(llmConfig.ollamaUrl)
- setCustomEndpoint(llmConfig.customEndpoint)
- }, [llmConfig])
-
- useEffect(() => {
- setSearchProvider(searchApiConfig.provider)
- setSearchApiKey(searchApiConfig.apiKey)
- }, [searchApiConfig])
+ const [draft, setDraftState] = useState<SettingsDraft>(() =>
+ initialDraft(
+ llmConfig,
+ searchApiConfig,
+ embeddingConfig,
+ outputLanguage,
+ maxHistoryMessages,
+ i18n.language,
+ ),
+ )
+ // Resync draft from store if it changes out-of-band (e.g. project switch).
useEffect(() => {
- setLocalOutputLang(outputLanguage)
- }, [outputLanguage])
+ setDraftState(
+ initialDraft(
+ llmConfig,
+ searchApiConfig,
+ embeddingConfig,
+ outputLanguage,
+ maxHistoryMessages,
+ i18n.language,
+ ),
+ )
+ }, [
+ llmConfig,
+ searchApiConfig,
+ embeddingConfig,
+ outputLanguage,
+ maxHistoryMessages,
+ ])
+
+ const setDraft: DraftSetter = useCallback((key, value) => {
+ setDraftState((prev) => ({ ...prev, [key]: value }))
+ }, [])
+
+ const handleSave = useCallback(async () => {
+ const {
+ saveLlmConfig,
+ saveSearchApiConfig,
+ saveEmbeddingConfig,
+ saveOutputLanguage,
+ } = await import("@/lib/project-store")
+
+ const newLlm = {
+ provider: draft.provider,
+ apiKey: draft.apiKey,
+ model: draft.model,
+ ollamaUrl: draft.ollamaUrl,
+ customEndpoint: draft.customEndpoint,
+ maxContextSize: draft.maxContextSize,
+ apiMode: draft.provider === "custom" ? draft.apiMode : undefined,
+ }
+ const newSearch = { provider: draft.searchProvider, apiKey: draft.searchApiKey }
+ const newEmbed = {
+ enabled: draft.embeddingEnabled,
+ endpoint: draft.embeddingEndpoint,
+ apiKey: draft.embeddingApiKey,
+ model: draft.embeddingModel,
+ }
+
+ setLlmConfig(newLlm)
+ await saveLlmConfig(newLlm)
+ setSearchApiConfig(newSearch)
+ await saveSearchApiConfig(newSearch)
+ setEmbeddingConfig(newEmbed)
+ await saveEmbeddingConfig(newEmbed)
+ setOutputLanguage(draft.outputLanguage as typeof outputLanguage)
+ await saveOutputLanguage(draft.outputLanguage as typeof outputLanguage)
+ setMaxHistoryMessages(draft.maxHistoryMessages)
+
+ if (draft.uiLanguage !== i18n.language) {
+ await i18n.changeLanguage(draft.uiLanguage)
+ await saveLanguage(draft.uiLanguage)
+ }
- const currentProvider = PROVIDERS.find((p) => p.value === provider)
-
- async function handleSave() {
- const { saveLlmConfig, saveSearchApiConfig, saveEmbeddingConfig, saveOutputLanguage } = await import("@/lib/project-store")
- const newConfig = { provider, apiKey, model, ollamaUrl, customEndpoint, maxContextSize }
- const newSearchConfig = { provider: searchProvider, apiKey: searchApiKey }
- const newEmbeddingConfig = { enabled: embeddingEnabled, endpoint: embeddingEndpoint, apiKey: embeddingApiKey, model: embeddingModel }
- setSearchApiConfig(newSearchConfig)
- await saveSearchApiConfig(newSearchConfig)
- setEmbeddingConfig(newEmbeddingConfig)
- await saveEmbeddingConfig(newEmbeddingConfig)
- setOutputLanguage(localOutputLang)
- await saveOutputLanguage(localOutputLang)
- setLlmConfig(newConfig)
- await saveLlmConfig(newConfig)
setSaved(true)
setTimeout(() => setSaved(false), 2000)
- }
-
- async function handleLanguageChange(lang: string) {
- await i18n.changeLanguage(lang)
- setCurrentLang(lang)
- await saveLanguage(lang)
- }
+ }, [
+ draft,
+ setLlmConfig,
+ setSearchApiConfig,
+ setEmbeddingConfig,
+ setOutputLanguage,
+ setMaxHistoryMessages,
+ outputLanguage,
+ ])
+
+ const body = useMemo(() => {
+ switch (active) {
+ case "llm":
+ // The LLM section manages its own store state (per-provider
+ // configs + active preset) and persists directly — it bypasses
+ // the shared draft / global Save button.
+ return <LlmProviderSection />
+ case "embedding":
+ return <EmbeddingSection draft={draft} setDraft={setDraft} />
+ case "web-search":
+ return <WebSearchSection draft={draft} setDraft={setDraft} />
+ case "output":
+ return <OutputSection draft={draft} setDraft={setDraft} />
+ case "interface":
+ return <InterfaceSection draft={draft} setDraft={setDraft} />
+ case "about":
+ return <AboutSection />
+ }
+ }, [active, draft, setDraft])
return (
- <div className="h-full overflow-auto p-8">
- <div className="mx-auto max-w-xl">
- <h2 className="mb-6 text-2xl font-bold">{t("settings.title")}</h2>
-
- <div className="space-y-6">
- {/* Language section */}
- <div className="space-y-4 rounded-lg border p-4">
- <h3 className="font-semibold">{t("settings.language")}</h3>
- <div className="flex flex-wrap gap-2">
- {LANGUAGES.map((lang) => (
- <button
- key={lang.value}
- onClick={() => handleLanguageChange(lang.value)}
- className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
- currentLang === lang.value
- ? "border-primary bg-primary text-primary-foreground"
- : "border-border hover:bg-accent"
- }`}
- >
- {lang.label}
- </button>
- ))}
- </div>
- <p className="text-xs text-muted-foreground">{t("settings.languageHint")}</p>
- </div>
-
- {/* Target Language section */}
- <div className="space-y-4 rounded-lg border p-4">
- <h3 className="font-semibold">AI Target Language</h3>
- <p className="text-xs text-muted-foreground">
- Force all AI-generated content (chat responses, wiki pages, research results, lint reports) to use the selected target language.
- Choose "Auto" to match the user's input or source document language.
- </p>
- <div className="space-y-2">
- <Label>Language</Label>
- <select
- value={localOutputLang}
- onChange={(e) => setLocalOutputLang(e.target.value as typeof localOutputLang)}
- className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
- >
- <option value="auto">Auto (detect from input/source)</option>
- <option value="English">English</option>
- <option value="Chinese">简体中文 (Simplified Chinese)</option>
- <option value="Traditional Chinese">繁體中文 (Traditional Chinese)</option>
- <option value="Japanese">日本語 (Japanese)</option>
- <option value="Korean">한국어 (Korean)</option>
- <option value="Vietnamese">Tiếng Việt (Vietnamese)</option>
- <option value="French">Français (French)</option>
- <option value="German">Deutsch (German)</option>
- <option value="Spanish">Español (Spanish)</option>
- <option value="Portuguese">Português (Portuguese)</option>
- <option value="Italian">Italiano (Italian)</option>
- <option value="Russian">Русский (Russian)</option>
- <option value="Arabic">العربية (Arabic)</option>
- <option value="Hindi">हिन्दी (Hindi)</option>
- <option value="Turkish">Türkçe (Turkish)</option>
- <option value="Dutch">Nederlands (Dutch)</option>
- <option value="Polish">Polski (Polish)</option>
- <option value="Swedish">Svenska (Swedish)</option>
- <option value="Indonesian">Bahasa Indonesia (Indonesian)</option>
- <option value="Thai">ไทย (Thai)</option>
- </select>
- </div>
- </div>
-
- {/* LLM Provider section */}
- <div className="space-y-4 rounded-lg border p-4">
- <h3 className="font-semibold">{t("settings.llmProvider")}</h3>
-
- <div className="space-y-2">
- <Label>{t("settings.provider")}</Label>
- <div className="flex flex-wrap gap-2">
- {PROVIDERS.map((p) => (
- <button
- key={p.value}
- onClick={() => {
- setProvider(p.value)
- setModel(p.models[0] || "")
- }}
- className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
- provider === p.value
- ? "border-primary bg-primary text-primary-foreground"
- : "border-border hover:bg-accent"
- }`}
- >
- {p.label}
- </button>
- ))}
- </div>
- </div>
-
- {provider === "custom" && (
- <div className="space-y-2">
- <Label htmlFor="customEndpoint">{t("settings.customEndpoint")}</Label>
- <Input
- id="customEndpoint"
- value={customEndpoint}
- onChange={(e) => setCustomEndpoint(e.target.value)}
- placeholder="https://your-api.example.com/v1"
- />
- <p className="text-xs text-muted-foreground">
- {t("settings.customEndpointHint")}
- </p>
- </div>
- )}
-
- {provider === "ollama" && (
- <div className="space-y-2">
- <Label htmlFor="ollamaUrl">{t("settings.ollamaUrl")}</Label>
- <Input
- id="ollamaUrl"
- value={ollamaUrl}
- onChange={(e) => setOllamaUrl(e.target.value)}
- placeholder="http://localhost:11434"
- />
- </div>
- )}
-
- {provider !== "ollama" && (
- <div className="space-y-2">
- <Label htmlFor="apiKey">{t("settings.apiKey")}</Label>
- <Input
- id="apiKey"
- type="password"
- value={apiKey}
- onChange={(e) => setApiKey(e.target.value)}
- placeholder={
- provider === "custom"
- ? t("settings.customApiKey")
- : t("settings.apiKeyPlaceholder", { provider: currentProvider?.label })
- }
- />
- </div>
- )}
-
- <div className="space-y-2">
- <Label htmlFor="model">{t("settings.model")}</Label>
- {currentProvider && currentProvider.models.length > 0 ? (
- <div className="space-y-2">
- <div className="flex flex-wrap gap-2">
- {currentProvider.models.map((m) => (
- <button
- key={m}
- onClick={() => setModel(m)}
- className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
- model === m
- ? "border-primary bg-primary text-primary-foreground"
- : "border-border hover:bg-accent"
- }`}
- >
- {m}
- </button>
- ))}
- </div>
- <Input
- value={model}
- onChange={(e) => setModel(e.target.value)}
- placeholder={t("settings.customModel")}
- />
- </div>
- ) : (
- <Input
- id="model"
- value={model}
- onChange={(e) => setModel(e.target.value)}
- placeholder={t("settings.modelPlaceholder")}
- />
- )}
- </div>
- </div>
-
- {/* Context Window Size */}
- <div className="space-y-4 rounded-lg border p-4">
- <h3 className="font-semibold">Context Window</h3>
- <p className="text-xs text-muted-foreground">
- Maximum context size sent to the LLM. Larger context allows more wiki pages in each query but costs more tokens.
- </p>
-
- <div className="space-y-3">
- <ContextSizeSelector value={maxContextSize} onChange={setMaxContextSize} />
- </div>
- </div>
-
- {/* Web Search API section */}
- <div className="space-y-4 rounded-lg border p-4">
- <h3 className="font-semibold">Web Search (Deep Research)</h3>
- <p className="text-xs text-muted-foreground">
- Enable AI-powered web research to automatically find relevant sources for knowledge gaps.
- </p>
-
- <div className="space-y-2">
- <Label>Search Provider</Label>
- <div className="flex flex-wrap gap-2">
- {[
- { value: "none" as const, label: "Disabled" },
- { value: "tavily" as const, label: "Tavily" },
- ].map((p) => (
- <button
- key={p.value}
- onClick={() => setSearchProvider(p.value)}
- className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
- searchProvider === p.value
- ? "border-primary bg-primary text-primary-foreground"
- : "border-border hover:bg-accent"
- }`}
- >
- {p.label}
- </button>
- ))}
- </div>
- </div>
-
- {searchProvider !== "none" && (
- <div className="space-y-2">
- <Label htmlFor="searchApiKey">API Key</Label>
- <Input
- id="searchApiKey"
- type="password"
- value={searchApiKey}
- onChange={(e) => setSearchApiKey(e.target.value)}
- placeholder="Enter your Tavily API key (tavily.com)"
- />
- </div>
- )}
- </div>
-
- {/* Embedding Search section */}
- <div className="space-y-4 rounded-lg border p-4">
- <div className="flex items-center justify-between">
- <h3 className="font-semibold">Vector Search (Embedding)</h3>
+ <div className="flex h-full overflow-hidden">
+ {/* Sidebar — category nav. Matches the IconSidebar's pill-on-accent
+ pattern so the two navigational surfaces feel like one app. */}
+ <aside className="flex w-56 shrink-0 flex-col border-r bg-muted/30">
+ <div className="px-4 pb-2 pt-4 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
+ Settings
+ </div>
+ <nav className="flex-1 overflow-y-auto px-2 pb-3">
+ {CATEGORIES.map((c) => {
+ const Icon = c.icon
+ const isActive = c.id === active
+ return (
<button
- onClick={() => setEmbeddingEnabled(!embeddingEnabled)}
- className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${
- embeddingEnabled ? "bg-primary" : "bg-muted"
+ key={c.id}
+ type="button"
+ onClick={() => setActive(c.id)}
+ aria-current={isActive ? "page" : undefined}
+ className={`group mb-0.5 flex w-full items-center gap-2.5 rounded-md px-2.5 py-1.5 text-sm transition-colors ${
+ isActive
+ ? "bg-foreground/[0.08] font-medium text-foreground ring-1 ring-border/70"
+ : "text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground"
}`}
>
- <span
- className={`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${
- embeddingEnabled ? "translate-x-4.5" : "translate-x-0.5"
+ <Icon
+ className={`h-4 w-4 shrink-0 transition-colors ${
+ isActive ? "text-primary" : "text-muted-foreground/80 group-hover:text-accent-foreground"
}`}
/>
+ <span className="truncate">{c.label}</span>
</button>
- </div>
- <p className="text-xs text-muted-foreground">
- Enable semantic search using embeddings. Uses the same LLM provider endpoint. Improves search quality for synonym matching and cross-domain discovery.
- </p>
- {embeddingEnabled && (
- <div className="space-y-3">
- <div className="space-y-2">
- <Label>Endpoint</Label>
- <Input
- value={embeddingEndpoint}
- onChange={(e) => setEmbeddingEndpoint(e.target.value)}
- placeholder="e.g. http://127.0.0.1:1234/v1/embeddings"
- />
- </div>
- <div className="space-y-2">
- <Label>API Key (optional)</Label>
- <Input
- type="password"
- value={embeddingApiKey}
- onChange={(e) => setEmbeddingApiKey(e.target.value)}
- placeholder="Leave empty for local models"
- />
- </div>
- <div className="space-y-2">
- <Label>Model</Label>
- <Input
- value={embeddingModel}
- onChange={(e) => setEmbeddingModel(e.target.value)}
- placeholder="e.g. text-embedding-qwen3-embedding-0.6b"
- />
- </div>
- <p className="text-xs text-muted-foreground">
- Embedding service can be different from the chat LLM. Supports any OpenAI-compatible /v1/embeddings endpoint.
- </p>
- </div>
- )}
- </div>
+ )
+ })}
+ </nav>
+ </aside>
+
+ {/* Content */}
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex-1 overflow-y-auto px-8 py-6">
+ <div className="mx-auto max-w-2xl">{body}</div>
+ </div>
- {/* Chat History section */}
- <div className="space-y-4 rounded-lg border p-4">
- <h3 className="font-semibold">Chat History</h3>
- <p className="text-xs text-muted-foreground">
- Number of previous messages included when talking to AI. More = better context but uses more tokens.
- </p>
- <div className="space-y-2">
- <Label>Max conversation messages sent to AI</Label>
- <div className="flex flex-wrap gap-2">
- {HISTORY_OPTIONS.map((n) => (
- <button
- key={n}
- onClick={() => setMaxHistoryMessages(n)}
- className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
- maxHistoryMessages === n
- ? "border-primary bg-primary text-primary-foreground"
- : "border-border hover:bg-accent"
- }`}
- >
- {n}
- </button>
- ))}
- </div>
+ {/* Global Save bar hidden for sections that persist inline:
+ - "llm" saves per-row on every edit (independent per-preset state)
+ - "about" has no editable fields */}
+ {active !== "about" && active !== "llm" && (
+ <div className="shrink-0 border-t bg-background/80 backdrop-blur px-8 py-3">
+ <div className="mx-auto flex max-w-2xl items-center justify-between gap-4">
<p className="text-xs text-muted-foreground">
- Currently: {maxHistoryMessages} messages ({maxHistoryMessages / 2} rounds of conversation)
+ {saved ? "已保存 ✓" : "改动会在保存后应用。"}
</p>
+ <Button onClick={handleSave}>
+ {saved ? "Saved" : "Save"}
+ </Button>
</div>
</div>
-
- <Button onClick={handleSave} className="w-full">
- {saved ? t("settings.saved") : t("settings.save")}
- </Button>
-
- <div className="pt-4 text-center text-xs text-muted-foreground">
- LLM Wiki v{__APP_VERSION__}
- </div>
- </div>
+ )}
</div>
</div>
)
}
-
-// Context size presets matching common model context windows
-const CONTEXT_PRESETS = [
- { value: 4096, label: "4K" },
- { value: 8192, label: "8K" },
- { value: 16384, label: "16K" },
- { value: 32768, label: "32K" },
- { value: 65536, label: "64K" },
- { value: 131072, label: "128K" },
- { value: 204800, label: "200K" },
- { value: 262144, label: "256K" },
- { value: 524288, label: "512K" },
- { value: 1000000, label: "1M" },
-]
-
-function ContextSizeSelector({ value, onChange }: { value: number; onChange: (v: number) => void }) {
- // Find closest preset index
- const closestIndex = CONTEXT_PRESETS.reduce((best, preset, i) => {
- return Math.abs(preset.value - value) < Math.abs(CONTEXT_PRESETS[best].value - value) ? i : best
- }, 0)
-
- return (
- <div>
- <div className="flex items-center justify-between mb-2">
- <span className="text-sm font-medium">{formatSize(value)}</span>
- <span className="text-xs text-muted-foreground">
- ~{Math.floor(value * 0.6 / 1000)}K chars for wiki content
- </span>
- </div>
- <input
- type="range"
- min={0}
- max={CONTEXT_PRESETS.length - 1}
- step={1}
- value={closestIndex}
- onChange={(e) => onChange(CONTEXT_PRESETS[parseInt(e.target.value)].value)}
- className="w-full h-2 rounded-lg appearance-none cursor-pointer accent-primary"
- style={{ background: `linear-gradient(to right, #4f46e5 ${(closestIndex / (CONTEXT_PRESETS.length - 1)) * 100}%, #e5e7eb ${(closestIndex / (CONTEXT_PRESETS.length - 1)) * 100}%)` }}
- />
- <div className="flex justify-between mt-1">
- {CONTEXT_PRESETS.map((preset, i) => (
- <button
- key={preset.value}
- type="button"
- onClick={() => onChange(preset.value)}
- className={`text-[9px] px-0.5 ${
- i === closestIndex ? "text-primary font-bold" : "text-muted-foreground/50"
- }`}
- >
- {preset.label}
- </button>
- ))}
- </div>
- </div>
- )
-}
-
-function formatSize(chars: number): string {
- if (chars >= 1000000) return `${(chars / 1000000).toFixed(1)}M characters`
- if (chars >= 1000) return `${Math.round(chars / 1000)}K characters`
- return `${chars} characters`
-}
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsx
index 5b8d418c..f0298bae 100644
--- a/src/components/sources/sources-view.tsx
+++ b/src/components/sources/sources-view.tsx
@@ -205,10 +205,6 @@ export function SourcesView() {
try {
// Step 1: Find related wiki pages before deleting
const relatedPages = await findRelatedWikiPages(pp, fileName)
- const deletedSlugs = relatedPages.map((p) => {
- const name = getFileName(p).replace(".md", "")
- return name
- }).filter(Boolean)
// Step 2: Delete the source file
await deleteFile(node.path)
diff --git a/src/components/ui/scroll-area.tsx b/src/components/ui/scroll-area.tsx
index 84c1e9fb..72000e5c 100644
--- a/src/components/ui/scroll-area.tsx
+++ b/src/components/ui/scroll-area.tsx
@@ -1,6 +1,5 @@
"use client"
-import * as React from "react"
import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area"
import { cn } from "@/lib/utils"
diff --git a/src/lib/__tests__/llm-providers.test.ts b/src/lib/__tests__/llm-providers.test.ts
index 615f95ea..46d51d99 100644
--- a/src/lib/__tests__/llm-providers.test.ts
+++ b/src/lib/__tests__/llm-providers.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect } from "vitest"
+import { buildAnthropicUrl } from "../llm-providers"
// Inline minimal types to avoid store/zustand dependencies in unit tests
type Provider = "openai" | "anthropic" | "google" | "ollama" | "custom" | "minimax"
@@ -13,21 +14,32 @@ interface LlmConfig {
}
// Re-implement the minimax case logic inline so we can unit-test it
-// without a browser environment or Tauri runtime.
+// without a browser environment or Tauri runtime. Keep this in sync with
+// the `case "minimax":` branch in src/lib/llm-providers.ts.
function buildMiniMaxProviderConfig(config: LlmConfig) {
- const { apiKey, model } = config
+ const { apiKey, model, customEndpoint } = config
+ const base = (customEndpoint || "https://api.minimax.io/anthropic").replace(/\/+$/, "")
+ // MiniMax's /anthropic endpoint requires Authorization: Bearer, NOT
+ // x-api-key. Its CORS preflight rejects x-api-key entirely. See the
+ // requiresBearerAuth() helper in src/lib/llm-providers.ts.
return {
- url: "https://api.minimax.io/v1/chat/completions",
+ url: `${base}/v1/messages`,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
- buildBody: (messages: Array<{ role: string; content: string }>) => ({
- messages,
- stream: true,
- model,
- temperature: 1.0,
- }),
+ buildBody: (messages: Array<{ role: string; content: string }>) => {
+ const systemMessages = messages.filter((m) => m.role === "system")
+ const conversationMessages = messages.filter((m) => m.role !== "system")
+ const system = systemMessages.map((m) => m.content).join("\n") || undefined
+ return {
+ messages: conversationMessages,
+ ...(system !== undefined ? { system } : {}),
+ stream: true,
+ max_tokens: 4096,
+ model,
+ }
+ },
}
}
@@ -42,14 +54,22 @@ const makeConfig = (overrides: Partial<LlmConfig> = {}): LlmConfig => ({
})
describe("MiniMax Provider", () => {
- it("uses the correct base URL", () => {
+ it("uses the Anthropic Messages endpoint under /anthropic", () => {
const cfg = buildMiniMaxProviderConfig(makeConfig())
- expect(cfg.url).toBe("https://api.minimax.io/v1/chat/completions")
+ expect(cfg.url).toBe("https://api.minimax.io/anthropic/v1/messages")
+ })
+
+ it("supports the China regional endpoint via customEndpoint", () => {
+ const cfg = buildMiniMaxProviderConfig(
+ makeConfig({ customEndpoint: "https://api.minimaxi.com/anthropic" }),
+ )
+ expect(cfg.url).toBe("https://api.minimaxi.com/anthropic/v1/messages")
})
- it("sets Authorization header with Bearer token", () => {
+ it("uses Authorization: Bearer (MiniMax rejects x-api-key at CORS layer)", () => {
const cfg = buildMiniMaxProviderConfig(makeConfig({ apiKey: "my-key" }))
expect(cfg.headers.Authorization).toBe("Bearer my-key")
+ expect((cfg.headers as Record<string, string>)["x-api-key"]).toBeUndefined()
})
it("sets Content-Type to application/json", () => {
@@ -57,38 +77,32 @@ describe("MiniMax Provider", () => {
expect(cfg.headers["Content-Type"]).toBe("application/json")
})
- it("includes temperature 1.0 in request body (MiniMax requires temperature > 0)", () => {
- const cfg = buildMiniMaxProviderConfig(makeConfig())
- const body = cfg.buildBody([{ role: "user", content: "hello" }]) as Record<string, unknown>
- expect(body.temperature).toBe(1.0)
- })
-
it("enables streaming", () => {
const cfg = buildMiniMaxProviderConfig(makeConfig())
const body = cfg.buildBody([]) as Record<string, unknown>
expect(body.stream).toBe(true)
})
- it("uses MiniMax-M2.7 model", () => {
- const cfg = buildMiniMaxProviderConfig(makeConfig({ model: "MiniMax-M2.7" }))
+ it("includes max_tokens (required by Anthropic wire)", () => {
+ const cfg = buildMiniMaxProviderConfig(makeConfig())
const body = cfg.buildBody([]) as Record<string, unknown>
- expect(body.model).toBe("MiniMax-M2.7")
+ expect(body.max_tokens).toBe(4096)
})
- it("uses MiniMax-M2.7-highspeed model", () => {
- const cfg = buildMiniMaxProviderConfig(makeConfig({ model: "MiniMax-M2.7-highspeed" }))
+ it("carries the model in the body", () => {
+ const cfg = buildMiniMaxProviderConfig(makeConfig({ model: "MiniMax-M2.7" }))
const body = cfg.buildBody([]) as Record<string, unknown>
- expect(body.model).toBe("MiniMax-M2.7-highspeed")
+ expect(body.model).toBe("MiniMax-M2.7")
})
- it("passes messages in request body", () => {
+ it("separates system messages from conversation (Anthropic convention)", () => {
const cfg = buildMiniMaxProviderConfig(makeConfig())
- const messages = [
+ const body = cfg.buildBody([
+ { role: "system", content: "You are helpful" },
{ role: "user", content: "Hello" },
- { role: "assistant", content: "Hi there" },
- ]
- const body = cfg.buildBody(messages) as Record<string, unknown>
- expect(body.messages).toEqual(messages)
+ ]) as Record<string, unknown>
+ expect(body.system).toBe("You are helpful")
+ expect(body.messages).toEqual([{ role: "user", content: "Hello" }])
})
})
@@ -98,3 +112,47 @@ describe("MiniMax provider registration", () => {
expect(provider).toBe("minimax")
})
})
+
+describe("buildAnthropicUrl — URL suffix handling", () => {
+ it("appends /v1/messages to a bare host", () => {
+ expect(buildAnthropicUrl("https://api.anthropic.com")).toBe(
+ "https://api.anthropic.com/v1/messages",
+ )
+ })
+
+ it("appends /v1/messages to a bare /anthropic proxy base", () => {
+ expect(buildAnthropicUrl("https://api.minimax.io/anthropic")).toBe(
+ "https://api.minimax.io/anthropic/v1/messages",
+ )
+ })
+
+ it("does NOT double the /v1 when base already ends in /v1", () => {
+ expect(buildAnthropicUrl("https://api.anthropic.com/v1")).toBe(
+ "https://api.anthropic.com/v1/messages",
+ )
+ })
+
+ it("does NOT double the /v1 when proxy base ends in /anthropic/v1", () => {
+ expect(buildAnthropicUrl("https://api.minimax.io/anthropic/v1")).toBe(
+ "https://api.minimax.io/anthropic/v1/messages",
+ )
+ })
+
+ it("preserves a full /v1/messages URL", () => {
+ expect(buildAnthropicUrl("https://api.anthropic.com/v1/messages")).toBe(
+ "https://api.anthropic.com/v1/messages",
+ )
+ })
+
+ it("handles arbitrary version segments like /api/paas/v4", () => {
+ expect(buildAnthropicUrl("https://open.bigmodel.cn/api/paas/v4")).toBe(
+ "https://open.bigmodel.cn/api/paas/v4/messages",
+ )
+ })
+
+ it("strips trailing slashes", () => {
+ expect(buildAnthropicUrl("https://api.anthropic.com/v1/")).toBe(
+ "https://api.anthropic.com/v1/messages",
+ )
+ })
+})
diff --git a/src/lib/deep-research.ts b/src/lib/deep-research.ts
index fdc3fb7e..d850ea50 100644
--- a/src/lib/deep-research.ts
+++ b/src/lib/deep-research.ts
@@ -7,8 +7,6 @@ import { useResearchStore } from "@/stores/research-store"
import { normalizePath } from "@/lib/path-utils"
import { buildLanguageDirective } from "@/lib/output-language"
-let processing = false
-
/**
* Queue a deep research task. Automatically starts processing if under concurrency limit.
*/
diff --git a/src/lib/endpoint-normalizer.test.ts b/src/lib/endpoint-normalizer.test.ts
new file mode 100644
index 00000000..5b1094c4
--- /dev/null
+++ b/src/lib/endpoint-normalizer.test.ts
@@ -0,0 +1,128 @@
+import { describe, it, expect } from "vitest"
+import { normalizeEndpoint } from "./endpoint-normalizer"
+
+describe("normalizeEndpoint — chat_completions mode", () => {
+ it("leaves a well-formed URL untouched", () => {
+ const r = normalizeEndpoint("https://api.openai.com/v1", "chat_completions")
+ expect(r.normalized).toBe("https://api.openai.com/v1")
+ expect(r.changed).toBe(false)
+ expect(r.warning).toBeUndefined()
+ })
+
+ it("strips trailing slash", () => {
+ const r = normalizeEndpoint("https://api.openai.com/v1/", "chat_completions")
+ expect(r.normalized).toBe("https://api.openai.com/v1")
+ expect(r.changed).toBe(true)
+ })
+
+ it("strips pasted /chat/completions", () => {
+ const r = normalizeEndpoint(
+ "https://api.openai.com/v1/chat/completions",
+ "chat_completions",
+ )
+ expect(r.normalized).toBe("https://api.openai.com/v1")
+ expect(r.changed).toBe(true)
+ expect(r.warning).toMatch(/chat\/completions/)
+ })
+
+ it("strips pasted /chat/completions with trailing slash", () => {
+ const r = normalizeEndpoint(
+ "https://api.openai.com/v1/chat/completions/",
+ "chat_completions",
+ )
+ expect(r.normalized).toBe("https://api.openai.com/v1")
+ })
+
+ it("strips pasted /embeddings", () => {
+ const r = normalizeEndpoint(
+ "https://api.openai.com/v1/embeddings",
+ "chat_completions",
+ )
+ expect(r.normalized).toBe("https://api.openai.com/v1")
+ })
+
+ it("preserves non-/v1 version segments (Zhipu, Arcee, etc.)", () => {
+ const r = normalizeEndpoint(
+ "https://open.bigmodel.cn/api/paas/v4",
+ "chat_completions",
+ )
+ expect(r.normalized).toBe("https://open.bigmodel.cn/api/paas/v4")
+ expect(r.changed).toBe(false)
+ })
+
+ it("strips /chat/completions while keeping a non-/v1 version segment", () => {
+ const r = normalizeEndpoint(
+ "https://open.bigmodel.cn/api/paas/v4/chat/completions",
+ "chat_completions",
+ )
+ expect(r.normalized).toBe("https://open.bigmodel.cn/api/paas/v4")
+ })
+
+ it("warns when the URL is a bare host with no version path", () => {
+ const r = normalizeEndpoint("https://api.openai.com", "chat_completions")
+ // Don't auto-add /v1 — different providers use different segments.
+ expect(r.normalized).toBe("https://api.openai.com")
+ expect(r.warning).toMatch(/v1|version/i)
+ })
+
+ it("warns when protocol is missing", () => {
+ const r = normalizeEndpoint("api.openai.com/v1", "chat_completions")
+ expect(r.warning).toMatch(/https?:\/\//i)
+ })
+
+ it("handles empty / whitespace input", () => {
+ expect(normalizeEndpoint("", "chat_completions").normalized).toBe("")
+ expect(normalizeEndpoint(" ", "chat_completions").normalized).toBe("")
+ })
+
+ it("strips enclosing whitespace", () => {
+ const r = normalizeEndpoint(" https://api.openai.com/v1 ", "chat_completions")
+ expect(r.normalized).toBe("https://api.openai.com/v1")
+ })
+
+ it("handles localhost with a port and version segment", () => {
+ const r = normalizeEndpoint("http://localhost:8080/v1", "chat_completions")
+ expect(r.normalized).toBe("http://localhost:8080/v1")
+ expect(r.changed).toBe(false)
+ })
+
+ it("strips /chat/completions on a localhost llama.cpp URL", () => {
+ const r = normalizeEndpoint(
+ "http://192.168.1.50:8080/v1/chat/completions",
+ "chat_completions",
+ )
+ expect(r.normalized).toBe("http://192.168.1.50:8080/v1")
+ })
+})
+
+describe("normalizeEndpoint — anthropic_messages mode", () => {
+ it("keeps a bare /anthropic base as-is (dispatch appends /v1/messages)", () => {
+ const r = normalizeEndpoint("https://api.minimax.io/anthropic", "anthropic_messages")
+ expect(r.normalized).toBe("https://api.minimax.io/anthropic")
+ expect(r.changed).toBe(false)
+ })
+
+ it("keeps a full /v1/messages URL as-is (dispatch uses it verbatim)", () => {
+ const r = normalizeEndpoint(
+ "https://api.anthropic.com/v1/messages",
+ "anthropic_messages",
+ )
+ expect(r.normalized).toBe("https://api.anthropic.com/v1/messages")
+ expect(r.changed).toBe(false)
+ })
+
+ it("strips trailing slash on an anthropic base", () => {
+ const r = normalizeEndpoint("https://api.minimax.io/anthropic/", "anthropic_messages")
+ expect(r.normalized).toBe("https://api.minimax.io/anthropic")
+ expect(r.changed).toBe(true)
+ })
+
+ it("strips stray /chat/completions (user pasted the wrong shape)", () => {
+ const r = normalizeEndpoint(
+ "https://api.anthropic.com/v1/chat/completions",
+ "anthropic_messages",
+ )
+ expect(r.warning).toMatch(/chat\/completions/)
+ expect(r.normalized).toBe("https://api.anthropic.com/v1")
+ })
+})
diff --git a/src/lib/endpoint-normalizer.ts b/src/lib/endpoint-normalizer.ts
new file mode 100644
index 00000000..22d3c2ac
--- /dev/null
+++ b/src/lib/endpoint-normalizer.ts
@@ -0,0 +1,98 @@
+/**
+ * Clean up user-entered LLM endpoint URLs. Catches the two most common
+ * mistakes:
+ *
+ * 1. User pastes the full path (e.g. ".../v1/chat/completions") — our
+ * dispatch would then append ANOTHER "/chat/completions" on top,
+ * producing a 404. Always strip trailing path segments that belong
+ * on the request, not on the base.
+ *
+ * 2. User forgets the version segment entirely (e.g. "https://host.com"
+ * with no /v1). We can't auto-add it because providers use different
+ * segments (OpenAI `/v1`, Zhipu `/api/paas/v4`, Groq `/openai/v1`) —
+ * but we CAN flag it so the user sees the hint.
+ *
+ * Auto-fixes apply deterministically on blur; hints explain what happened.
+ * Warnings are shown inline but never block saving — some self-hosted
+ * gateways really do mount the API at a bare host.
+ */
+
+export type EndpointMode = "chat_completions" | "anthropic_messages"
+
+export interface NormalizedEndpoint {
+ /** The cleaned-up URL to store. Empty string for empty input. */
+ normalized: string
+ /** True if normalization changed the input (show a "will use" hint). */
+ changed: boolean
+ /** Human-readable hint / warning. Undefined when the input is fine. */
+ warning?: string
+}
+
+// Path tails that are always wrong as a base URL and can be safely
+// stripped regardless of mode — these belong on the request, not on the
+// configured endpoint.
+const ALWAYS_WRONG_TAILS = /\/+(chat\/completions|embeddings)\/?$/i
+// `/messages` is ambiguous: in anthropic_messages mode our dispatch uses
+// it verbatim when present, so we must preserve it. Only strip when the
+// configured mode is chat_completions.
+const MESSAGES_TAIL = /\/+messages\/?$/i
+
+export function normalizeEndpoint(raw: string, mode: EndpointMode): NormalizedEndpoint {
+ const trimmed = (raw ?? "").trim()
+ if (!trimmed) return { normalized: "", changed: false }
+
+ // Detect missing protocol — we never auto-add https:// because that
+ // would mask the user's typo; just flag it.
+ const missingProtocol = !/^https?:\/\//i.test(trimmed)
+ if (missingProtocol) {
+ return {
+ normalized: trimmed.replace(/\/+$/, ""),
+ changed: trimmed !== trimmed.replace(/\/+$/, ""),
+ warning: "URL should start with http:// or https://",
+ }
+ }
+
+ let url = trimmed
+ const notes: string[] = []
+
+ // Strip trailing slashes (cheap, always safe)
+ url = url.replace(/\/+$/, "")
+
+ // Strip request-path tails users paste by accident. Works in both
+ // modes for /chat/completions and /embeddings (wrong shape for either
+ // wire). /messages is only wrong in chat_completions mode — in
+ // anthropic_messages mode the dispatch uses it verbatim.
+ if (ALWAYS_WRONG_TAILS.test(url)) {
+ const match = url.match(ALWAYS_WRONG_TAILS)
+ url = url.replace(ALWAYS_WRONG_TAILS, "")
+ if (match) notes.push(`stripped trailing "${match[0].replace(/^\/+/, "").replace(/\/+$/, "")}" — this is appended per-request, not part of the base URL`)
+ } else if (mode === "chat_completions" && MESSAGES_TAIL.test(url)) {
+ const match = url.match(MESSAGES_TAIL)
+ url = url.replace(MESSAGES_TAIL, "")
+ if (match) notes.push(`stripped trailing "${match[0].replace(/^\/+/, "").replace(/\/+$/, "")}" — this is an Anthropic-wire path, not a chat/completions base`)
+ }
+
+ // After stripping, check for the "bare host, no version segment" case.
+ // Only hint for chat_completions — anthropic_messages endpoints sit at
+ // various non-/v1 paths (MiniMax `/anthropic`, Anthropic native `/`)
+ // and we can't reliably flag them.
+ if (mode === "chat_completions") {
+ try {
+ const u = new URL(url)
+ const pathname = u.pathname.replace(/\/+$/, "")
+ const hasVersionSegment = /\/(v\d+|paas\/v\d+|openai\/v\d+|api\/v\d+)$/i.test(pathname)
+ if (!hasVersionSegment && !notes.length) {
+ notes.push('URL has no version segment (expected e.g. "/v1"). Double-check the provider\'s docs.')
+ }
+ } catch {
+ // Malformed URL — leave alone, browser will fail loudly at fetch time.
+ }
+ }
+
+ const changed = url !== trimmed
+ return {
+ normalized: url,
+ changed,
+ warning: notes.length ? notes.join(" ") : undefined,
+ }
+}
diff --git a/src/lib/graph-insights.ts b/src/lib/graph-insights.ts
index e9d18dd2..2bb7385c 100644
--- a/src/lib/graph-insights.ts
+++ b/src/lib/graph-insights.ts
@@ -31,7 +31,7 @@ export interface KnowledgeGap {
export function findSurprisingConnections(
nodes: GraphNode[],
edges: GraphEdge[],
- communities: CommunityInfo[],
+ _communities: CommunityInfo[],
limit: number = 5,
): SurprisingConnection[] {
const nodeMap = new Map(nodes.map((n) => [n.id, n]))
diff --git a/src/lib/graph-relevance.ts b/src/lib/graph-relevance.ts
index 057f00a2..c7a578d9 100644
--- a/src/lib/graph-relevance.ts
+++ b/src/lib/graph-relevance.ts
@@ -234,8 +234,8 @@ export async function buildRetrievalGraph(
type: raw.type,
path: raw.path,
sources: Object.freeze([...raw.sources]),
- outLinks: Object.freeze(outLinksMap.get(raw.id) ?? new Set()),
- inLinks: Object.freeze(inLinksMap.get(raw.id) ?? new Set()),
+ outLinks: Object.freeze(outLinksMap.get(raw.id) ?? new Set<string>()),
+ inLinks: Object.freeze(inLinksMap.get(raw.id) ?? new Set<string>()),
})
}
diff --git a/src/lib/greeting-detector.test.ts b/src/lib/greeting-detector.test.ts
new file mode 100644
index 00000000..07ec4ac7
--- /dev/null
+++ b/src/lib/greeting-detector.test.ts
@@ -0,0 +1,106 @@
+import { describe, it, expect } from "vitest"
+import { isGreeting } from "./greeting-detector"
+
+describe("isGreeting — positive cases", () => {
+ const GREETINGS = [
+ // English
+ "hi",
+ "Hi",
+ "HELLO",
+ "hello!",
+ "hey",
+ "hey there",
+ "hi there!",
+ "yo",
+ "sup",
+ "howdy",
+ "good morning",
+ "Good Morning!",
+ "good afternoon",
+ "good evening",
+ "good night",
+ "what's up",
+ "whats up",
+ "wassup",
+ // Chinese
+ "你好",
+ "你好!",
+ "你好。",
+ "您好",
+ "嗨",
+ "嗨~",
+ "哈喽",
+ "哈啰",
+ "哈囉",
+ "喂",
+ "早",
+ "早啊",
+ "早上好",
+ "中午好",
+ "下午好",
+ "晚上好",
+ "晚安",
+ "在吗",
+ "在吗?",
+ "在不在",
+ "有人吗",
+ // Japanese
+ "こんにちは",
+ "こんばんは",
+ "おはよう",
+ "やあ",
+ "どうも",
+ // Korean
+ "안녕",
+ "안녕하세요",
+ // European casuals
+ "hola",
+ "bonjour",
+ "salut",
+ "hallo",
+ "ciao",
+ // Whitespace tolerance
+ " hello ",
+ " 你好 ",
+ ]
+
+ for (const text of GREETINGS) {
+ it(`treats ${JSON.stringify(text)} as a greeting`, () => {
+ expect(isGreeting(text)).toBe(true)
+ })
+ }
+})
+
+describe("isGreeting — negative cases", () => {
+ const NON_GREETINGS = [
+ // Empty / whitespace
+ "",
+ " ",
+ // Greeting followed by a real question (integrated queries)
+ "hello, how do I train a transformer?",
+ "你好,请问怎么写 LangGraph 的 node?",
+ "hi, could you summarize the page on attention mechanisms",
+ "嗨,帮我查一下向量检索的那几篇",
+ // Substantive questions
+ "what is attention",
+ "解释一下 MoE",
+ "summarize the purpose page",
+ // Single word that contains a greeting substring but isn't one
+ "hibernation",
+ "hello world program",
+ "heyday",
+ // Long message that happens to start with a greeting
+ "hi everyone I wanted to ask about the new retrieval pipeline design",
+ // Generic affirmation / farewell (not greeting)
+ "ok",
+ "thanks",
+ "bye",
+ "再见",
+ ]
+
+ for (const text of NON_GREETINGS) {
+ it(`rejects ${JSON.stringify(text)}`, () => {
+ expect(isGreeting(text)).toBe(false)
+ })
+ }
+})
diff --git a/src/lib/greeting-detector.ts b/src/lib/greeting-detector.ts
new file mode 100644
index 00000000..747a5409
--- /dev/null
+++ b/src/lib/greeting-detector.ts
@@ -0,0 +1,60 @@
+/**
+ * Pure-rule detector for "nothing but a greeting" — lets the chat path
+ * skip the wiki retrieval pipeline for casual openers like "hi", "你好",
+ * "嗨" that have no information need. Cheap, deterministic, no LLM call.
+ *
+ * Matches are *whole-string* (after trim + trailing-punctuation strip),
+ * not substring — so "hello, how do I train a transformer?" is NOT a
+ * greeting. A hard length cap keeps pathological inputs out of the
+ * regex loop and protects against false positives on long messages
+ * that happen to start with "hi".
+ */
+
+const MAX_GREETING_LEN = 20
+
+// Trailing punctuation / emoji-ish tails that users tack onto openers.
+// Leading-period not included on purpose — a message starting with "." is
+// almost never a greeting.
+const TRAILING_PUNCT = /[\s!!。.??~,,、;;::\u3002\uFF01\uFF1F]+$/u
+
+const GREETING_PATTERNS: RegExp[] = [
+ // ── English ──────────────────────────────────────────────────────
+ /^(hi|hello|hey|yo|sup|howdy|hiya|heya|hullo)( there| y'all| you| folks| everyone)?$/,
+ /^good (morning|afternoon|evening|day|night)$/,
+ /^(what'?s up|wassup|whaddup)$/,
+ /^greetings$/,
+
+ // ── Chinese (简体 + 繁體) ──────────────────────────────────────
+ // Standalone greetings with optional trailing filler particle.
+ /^(你好|您好|大家好|嗨|哈喽|哈啰|哈囉|哈罗|喂)[啊呀吖呢么呗哦哈]?$/,
+ // Time-of-day greetings.
+ /^(早|早啊|早安|早上好|中午好|下午好|晚上好|晚安)[啊呀吖呢么呗哦哈]?$/,
+ // "Are you there?" openers.
+ /^(在吗|在嗎|在不在|有人吗|有人嗎|有人在吗|有人在嗎)$/,
+
+ // ── Japanese ────────────────────────────────────────────────────
+ /^(こんにちは|こんばんは|おはよう|おはようございます|やあ|どうも|はじめまして)$/,
+
+ // ── Korean ──────────────────────────────────────────────────────
+ /^(안녕|안녕하세요|안녕하십니까)$/,
+
+ // ── European casual openers ─────────────────────────────────────
+ /^(hola|bonjour|salut|coucou|hallo|servus|hej|hejsan|ciao|saluton|ola|olá|privet|привет)$/,
+]
+
+export function isGreeting(text: string): boolean {
+ if (!text) return false
+
+ // Strip outer whitespace + trailing punctuation, lowercase for ASCII
+ // matching. CJK chars are unaffected by toLowerCase().
+ const normalized = text
+ .trim()
+ .replace(TRAILING_PUNCT, "")
+ .trim()
+ .toLowerCase()
+
+ if (!normalized) return false
+ if (normalized.length > MAX_GREETING_LEN) return false
+
+ return GREETING_PATTERNS.some((re) => re.test(normalized))
+}
diff --git a/src/lib/llm-client.test.ts b/src/lib/llm-client.test.ts
new file mode 100644
index 00000000..f0fcc222
--- /dev/null
+++ b/src/lib/llm-client.test.ts
@@ -0,0 +1,52 @@
+import { describe, it, expect } from "vitest"
+import { isFetchNetworkError } from "./llm-client"
+
+/**
+ * Guards for cross-webview error detection. Tauri renders the frontend
+ * with WebKit on macOS/Linux and Edge WebView2 (Chromium) on Windows,
+ * and each backend phrases fetch failures differently. These tests pin
+ * down that every real-world error shape gets classified as a network
+ * error so the user sees a helpful message instead of a raw stack.
+ */
+describe("isFetchNetworkError — cross-webview fetch failures", () => {
+ it("recognises WebKit's 'Load failed' (macOS / Linux GTK)", () => {
+ const e = new Error("Load failed")
+ expect(isFetchNetworkError(e)).toBe(true)
+ })
+
+ it("recognises Chromium/Edge's TypeError: Failed to fetch (Windows)", () => {
+ // Real Chromium throws a TypeError with this exact shape.
+ const e = new TypeError("Failed to fetch")
+ expect(isFetchNetworkError(e)).toBe(true)
+ })
+
+ it("recognises any TypeError (Chromium fetch failure class)", () => {
+ // Chromium also throws TypeError with messages like "NetworkError
+ // when attempting to fetch resource." — the name alone is enough.
+ const e = new TypeError("NetworkError when attempting to fetch resource.")
+ expect(isFetchNetworkError(e)).toBe(true)
+ })
+
+ it("recognises messages containing 'network error' (mid-stream drops)", () => {
+ const e = new Error("The network error occurred while reading")
+ expect(isFetchNetworkError(e)).toBe(true)
+ })
+
+ it("rejects AbortError (user cancelled)", () => {
+ const e = new Error("The operation was aborted.")
+ e.name = "AbortError"
+ expect(isFetchNetworkError(e)).toBe(false)
+ })
+
+ it("rejects plain application errors (HTTP 4xx surfaced as Error)", () => {
+ const e = new Error("HTTP 401: Unauthorized")
+ expect(isFetchNetworkError(e)).toBe(false)
+ })
+
+ it("rejects non-Error values (strings, null, objects)", () => {
+ expect(isFetchNetworkError("boom")).toBe(false)
+ expect(isFetchNetworkError(null)).toBe(false)
+ expect(isFetchNetworkError(undefined)).toBe(false)
+ expect(isFetchNetworkError({ message: "Load failed" })).toBe(false)
+ })
+})
diff --git a/src/lib/llm-client.ts b/src/lib/llm-client.ts
index ecbcd3ad..2733aac3 100644
--- a/src/lib/llm-client.ts
+++ b/src/lib/llm-client.ts
@@ -11,6 +11,32 @@ export interface StreamCallbacks {
const DECODER = new TextDecoder()
+/**
+ * Detect fetch-level network failures across Tauri's different webview
+ * backends. Each platform phrases the same failure class differently:
+ *
+ * macOS / iOS (WebKit): Error, message === "Load failed"
+ * Windows (Edge WebView2): TypeError, message === "Failed to fetch"
+ * Linux (WebKitGTK): Error, message === "Load failed"
+ *
+ * They all collapse DNS / TLS / connection-refused / CORS-preflight into
+ * a single opaque error with no structured detail. The only reliable
+ * cross-platform signal is "it's not an AbortError and it's one of these
+ * generic network error shapes", which this helper centralizes.
+ */
+export function isFetchNetworkError(err: unknown): boolean {
+ if (!(err instanceof Error)) return false
+ if (err.name === "AbortError") return false
+ // Chromium / Edge WebView2
+ if (err.name === "TypeError") return true
+ // WebKit (macOS / Linux GTK)
+ if (err.message === "Load failed") return true
+ // Chromium mid-stream drop
+ if (err.message === "Failed to fetch") return true
+ if (err.message.includes("network error")) return true
+ return false
+}
+
function parseLines(chunk: Uint8Array, buffer: string): [string[], string] {
const text = buffer + DECODER.decode(chunk, { stream: true })
const lines = text.split("\n")
@@ -34,15 +60,23 @@ export async function streamChat(
const { onToken, onDone, onError } = callbacks
const providerConfig = getProviderConfig(config)
- // Create a combined signal: user abort OR 15-minute timeout
- const timeoutMs = 15 * 60 * 1000 // 15 minutes — some models with large context need a long time
+ // Combined abort: (a) user cancel, (b) our long-horizon timeout.
+ // The long timeout is a backstop for truly stuck requests; it's NOT
+ // what fires when a user sees "Timeout" after 2 seconds — that is
+ // almost always a fast network failure (DNS, TLS, 404, refused) that
+ // WebKit surfaces as a generic "Load failed". We track whether the
+ // backstop actually fired so we can tell the two apart in the error.
+ const timeoutMs = 30 * 60 * 1000 // 30 min — generous backstop for huge-context reasoning models
let combinedSignal = signal
let timeoutController: AbortController | undefined
+ let timeoutFired = false
if (typeof AbortSignal.timeout === "function") {
- // Combine user signal with timeout
timeoutController = new AbortController()
- const timeoutId = setTimeout(() => timeoutController?.abort(), timeoutMs)
+ const timeoutId = setTimeout(() => {
+ timeoutFired = true
+ timeoutController?.abort()
+ }, timeoutMs)
if (signal) {
signal.addEventListener("abort", () => {
@@ -66,14 +100,30 @@ export async function streamChat(
keepalive: false,
})
} catch (err) {
- if (err instanceof Error && (err.name === "AbortError" || err.message === "Load failed")) {
- // Check if it was user-initiated abort
- if (signal?.aborted) {
- onDone()
+ if (signal?.aborted) {
+ onDone()
+ return
+ }
+ if (err instanceof Error && err.name === "AbortError") {
+ // Backstop timeout aborted the request (we tracked this via
+ // timeoutFired); treat it as a real timeout rather than a cancel.
+ 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
+ }
+ if (isFetchNetworkError(err)) {
+ if (timeoutFired) {
+ onError(new Error(`Request timed out after ${Math.round(timeoutMs / 60000)} min. Try a faster model or a smaller context.`))
return
}
- // Otherwise it's a timeout or network error
- onError(new Error("Request timed out or network error. The model may need more time — try again or use a faster model."))
+ // Fast fetch failure: DNS, TLS handshake, connection refused,
+ // wrong endpoint, CORS preflight rejection, etc. All webviews
+ // collapse this class of failure into an opaque error — point
+ // users at the likely cause (endpoint / key / connectivity).
+ onError(new Error(`Network error reaching ${providerConfig.url}. Check endpoint URL, API key, and connectivity.`))
return
}
onError(err instanceof Error ? err : new Error(String(err)))
@@ -129,8 +179,10 @@ export async function streamChat(
onDone()
return
}
- if (err instanceof Error && err.message === "Load failed") {
- // WebKit network error during streaming — connection dropped
+ if (isFetchNetworkError(err)) {
+ // Stream reader threw a network error mid-response (connection
+ // dropped, server closed early, network blip). Same message
+ // regardless of whether the webview is WebKit or Chromium.
onError(new Error("Connection lost during streaming. Try again."))
return
}
diff --git a/src/lib/llm-providers.ts b/src/lib/llm-providers.ts
index 339c68f2..23702aee 100644
--- a/src/lib/llm-providers.ts
+++ b/src/lib/llm-providers.ts
@@ -63,11 +63,11 @@ function parseGoogleLine(line: string): string | null {
}
}
-function buildOpenAiBody(messages: ChatMessage[]): unknown {
+function buildOpenAiBody(messages: ChatMessage[]): Record<string, unknown> {
return { messages, stream: true }
}
-function buildAnthropicBody(messages: ChatMessage[]): unknown {
+function buildAnthropicBody(messages: ChatMessage[]): Record<string, unknown> {
const systemMessages = messages.filter((m) => m.role === "system")
const conversationMessages = messages.filter((m) => m.role !== "system")
const system = systemMessages.map((m) => m.content).join("\n") || undefined
@@ -80,7 +80,60 @@ function buildAnthropicBody(messages: ChatMessage[]): unknown {
}
}
-function buildGoogleBody(messages: ChatMessage[]): unknown {
+/**
+ * Some Anthropic-compatible third-party endpoints (MiniMax global + CN)
+ * serve the Messages API but authenticate with `Authorization: Bearer`
+ * instead of Anthropic-native `x-api-key`. See hermes-agent
+ * `agent/anthropic_adapter.py:_requires_bearer_auth` for reference.
+ *
+ * This also matters for CORS: MiniMax's preflight lists `Authorization`
+ * in `Access-Control-Allow-Headers` but NOT `x-api-key`, so sending the
+ * Anthropic-native header gets blocked by the browser before the request
+ * even leaves.
+ */
+function requiresBearerAuth(url: string): boolean {
+ const normalized = url.toLowerCase().replace(/\/+$/, "")
+ return (
+ normalized.startsWith("https://api.minimax.io/anthropic") ||
+ normalized.startsWith("https://api.minimaxi.com/anthropic")
+ )
+}
+
+/**
+ * Build the final POST URL for an Anthropic-wire endpoint given whatever
+ * base the user provided. Handles every shape we've seen in the wild:
+ *
+ * .../v1/messages → as-is (user pasted the full path)
+ * .../v1 → append /messages (don't double the /v1)
+ * .../api/paas/v4 → append /messages (arbitrary version segment)
+ * .../anthropic → append /v1/messages (MiniMax-style proxy base)
+ * .../ → append /v1/messages (bare host)
+ *
+ * A bug where this naively appended "/v1/messages" caused requests to
+ * ".../v1/v1/messages" (404) whenever a user typed a URL ending in /v1.
+ */
+export function buildAnthropicUrl(base: string): string {
+ const trimmed = base.replace(/\/+$/, "")
+ if (/\/v\d+\/messages$/i.test(trimmed)) return trimmed
+ if (/\/v\d+$/i.test(trimmed)) return `${trimmed}/messages`
+ return `${trimmed}/v1/messages`
+}
+
+function buildAnthropicHeaders(apiKey: string, url: string): Record<string, string> {
+ const base: Record<string, string> = {
+ "Content-Type": JSON_CONTENT_TYPE,
+ }
+ if (requiresBearerAuth(url)) {
+ base.Authorization = `Bearer ${apiKey}`
+ } else {
+ base["x-api-key"] = apiKey
+ base["anthropic-version"] = "2023-06-01"
+ base["anthropic-dangerous-direct-browser-access"] = "true"
+ }
+ return base
+}
+
+function buildGoogleBody(messages: ChatMessage[]): Record<string, unknown> {
const systemMessages = messages.filter((m) => m.role === "system")
const conversationMessages = messages.filter((m) => m.role !== "system")
@@ -120,21 +173,18 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {
parseStream: parseOpenAiLine,
}
- case "anthropic":
+ case "anthropic": {
+ const url = buildAnthropicUrl("https://api.anthropic.com")
return {
- url: "https://api.anthropic.com/v1/messages",
- headers: {
- "Content-Type": JSON_CONTENT_TYPE,
- "x-api-key": apiKey,
- "anthropic-version": "2023-06-01",
- "anthropic-dangerous-direct-browser-access": "true",
- },
+ url,
+ headers: buildAnthropicHeaders(apiKey, url),
buildBody: (messages) => ({
...buildAnthropicBody(messages),
model,
}),
parseStream: parseAnthropicLine,
}
+ }
case "google":
return {
@@ -147,9 +197,19 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {
parseStream: parseGoogleLine,
}
- case "ollama":
+ case "ollama": {
+ // Defense-in-depth for the same reason as the custom branch: if a
+ // user pasted the full path as their Ollama URL, don't tack on
+ // another copy. Also strip a bare trailing "/v1" so the user can
+ // enter either form ("http://host:11434" or "http://host:11434/v1").
+ let ollamaBase = ollamaUrl.replace(/\/+$/, "")
+ if (/\/v1\/chat\/completions$/i.test(ollamaBase)) {
+ ollamaBase = ollamaBase.replace(/\/v1\/chat\/completions$/i, "")
+ } else if (/\/v1$/i.test(ollamaBase)) {
+ ollamaBase = ollamaBase.replace(/\/v1$/i, "")
+ }
return {
- url: `${ollamaUrl}/v1/chat/completions`,
+ url: `${ollamaBase}/v1/chat/completions`,
headers: {
"Content-Type": JSON_CONTENT_TYPE,
},
@@ -170,25 +230,54 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {
},
parseStream: parseOpenAiLine,
}
+ }
- case "minimax":
+ case "minimax": {
+ // MiniMax's real API is Anthropic Messages at /anthropic, not
+ // OpenAI chat completions. customEndpoint can point at either the
+ // global (.io) or China (.minimaxi.com) regional endpoint; default
+ // to the global one when unset. Auth uses Bearer (see
+ // buildAnthropicHeaders / requiresBearerAuth above).
+ const url = buildAnthropicUrl(customEndpoint || "https://api.minimax.io/anthropic")
return {
- url: "https://api.minimax.io/v1/chat/completions",
- headers: {
- "Content-Type": JSON_CONTENT_TYPE,
- Authorization: `Bearer ${apiKey}`,
- },
+ url,
+ headers: buildAnthropicHeaders(apiKey, url),
buildBody: (messages) => ({
- ...buildOpenAiBody(messages),
+ ...buildAnthropicBody(messages),
model,
- temperature: 1.0,
}),
- parseStream: parseOpenAiLine,
+ parseStream: parseAnthropicLine,
}
+ }
- case "custom":
+ case "custom": {
+ // Custom endpoints can speak either OpenAI's /chat/completions
+ // wire or Anthropic's /v1/messages wire. The field `apiMode` on
+ // the config picks which. Default (missing) = chat_completions
+ // so pre-0.3.7 configs keep working unchanged.
+ const mode = config.apiMode ?? "chat_completions"
+ if (mode === "anthropic_messages") {
+ const url = buildAnthropicUrl(customEndpoint)
+ return {
+ url,
+ headers: buildAnthropicHeaders(apiKey, url),
+ buildBody: (messages) => ({
+ ...buildAnthropicBody(messages),
+ model,
+ }),
+ parseStream: parseAnthropicLine,
+ }
+ }
+ // Defense-in-depth: settings-side EndpointField normalizes URLs on
+ // blur, but older configs saved before that shipped may still carry
+ // a pasted "/chat/completions" tail. Don't double-append in that
+ // case, or we'd POST to ".../chat/completions/chat/completions".
+ const base = customEndpoint.replace(/\/+$/, "")
+ const url = /\/chat\/completions$/i.test(base)
+ ? base
+ : `${base}/chat/completions`
return {
- url: `${customEndpoint}/chat/completions`,
+ url,
headers: {
"Content-Type": JSON_CONTENT_TYPE,
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
@@ -199,6 +288,7 @@ export function getProviderConfig(config: LlmConfig): ProviderConfig {
}),
parseStream: parseOpenAiLine,
}
+ }
default: {
const exhaustive: never = provider
diff --git a/src/lib/project-identity.ts b/src/lib/project-identity.ts
index 43e129b0..12352b42 100644
--- a/src/lib/project-identity.ts
+++ b/src/lib/project-identity.ts
@@ -70,7 +70,7 @@ export async function ensureProjectId(projectPath: string): Promise<string> {
// ── Global registry (Tauri plugin-store) ──────────────────────────────────
async function getStore() {
- return load(STORE_NAME, { autoSave: true })
+ return load(STORE_NAME, { autoSave: true, defaults: {} })
}
export async function loadRegistry(): Promise<ProjectRegistry> {
diff --git a/src/lib/project-store.ts b/src/lib/project-store.ts
index 42dabe21..4672990f 100644
--- a/src/lib/project-store.ts
+++ b/src/lib/project-store.ts
@@ -1,13 +1,13 @@
import { load } from "@tauri-apps/plugin-store"
import type { WikiProject } from "@/types/wiki"
-import type { LlmConfig, SearchApiConfig, EmbeddingConfig, OutputLanguage } from "@/stores/wiki-store"
+import type { LlmConfig, SearchApiConfig, EmbeddingConfig, OutputLanguage, ProviderConfigs } from "@/stores/wiki-store"
const STORE_NAME = "app-state.json"
const RECENT_PROJECTS_KEY = "recentProjects"
const LAST_PROJECT_KEY = "lastProject"
async function getStore() {
- return load(STORE_NAME, { autoSave: true })
+ return load(STORE_NAME, { autoSave: true, defaults: {} })
}
export async function getRecentProjects(): Promise<WikiProject[]> {
@@ -39,6 +39,8 @@ export async function addToRecentProjects(
}
const LLM_CONFIG_KEY = "llmConfig"
+const PROVIDER_CONFIGS_KEY = "providerConfigs"
+const ACTIVE_PRESET_KEY = "activePresetId"
export async function saveLlmConfig(config: LlmConfig): Promise<void> {
const store = await getStore()
@@ -50,6 +52,26 @@ export async function loadLlmConfig(): Promise<LlmConfig | null> {
return (await store.get<LlmConfig>(LLM_CONFIG_KEY)) ?? null
}
+export async function saveProviderConfigs(configs: ProviderConfigs): Promise<void> {
+ const store = await getStore()
+ await store.set(PROVIDER_CONFIGS_KEY, configs)
+}
+
+export async function loadProviderConfigs(): Promise<ProviderConfigs | null> {
+ const store = await getStore()
+ return (await store.get<ProviderConfigs>(PROVIDER_CONFIGS_KEY)) ?? null
+}
+
+export async function saveActivePresetId(id: string | null): Promise<void> {
+ const store = await getStore()
+ await store.set(ACTIVE_PRESET_KEY, id)
+}
+
+export async function loadActivePresetId(): Promise<string | null> {
+ const store = await getStore()
+ return (await store.get<string | null>(ACTIVE_PRESET_KEY)) ?? null
+}
+
const SEARCH_API_KEY = "searchApiConfig"
export async function saveSearchApiConfig(config: SearchApiConfig): Promise<void> {
diff --git a/src/lib/wiki-graph.ts b/src/lib/wiki-graph.ts
index 94fd6cbf..8194a1c7 100644
--- a/src/lib/wiki-graph.ts
+++ b/src/lib/wiki-graph.ts
@@ -223,7 +223,7 @@ export async function buildWikiGraph(
if (targetId === null) continue
if (targetId === sourceId) continue
- rawEdges.push({ source: sourceId, target: targetId })
+ rawEdges.push({ source: sourceId, target: targetId, weight: 1 })
linkCounts.set(sourceId, (linkCounts.get(sourceId) ?? 0) + 1)
linkCounts.set(targetId, (linkCounts.get(targetId) ?? 0) + 1)
diff --git a/src/stores/activity-store.ts b/src/stores/activity-store.ts
index 5647659a..b61bcd48 100644
--- a/src/stores/activity-store.ts
+++ b/src/stores/activity-store.ts
@@ -20,7 +20,7 @@ interface ActivityState {
let counter = 0
-export const useActivityStore = create<ActivityState>((set, get) => ({
+export const useActivityStore = create<ActivityState>((set) => ({
items: [],
addItem: (item) => {
diff --git a/src/stores/review-store.property.test.ts b/src/stores/review-store.property.test.ts
index d53d8bfe..a30132b4 100644
--- a/src/stores/review-store.property.test.ts
+++ b/src/stores/review-store.property.test.ts
@@ -42,9 +42,9 @@ describe("review-store addItems — dedupe invariants", () => {
type: b.type,
title: b.title,
description: b.description,
- options: b.options,
- affectedPages: b.affectedPages ?? undefined,
- searchQueries: b.searchQueries ?? undefined,
+ options: [...b.options],
+ affectedPages: b.affectedPages ? [...b.affectedPages] : undefined,
+ searchQueries: b.searchQueries ? [...b.searchQueries] : undefined,
}))
useReviewStore.getState().addItems(input)
}
diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.ts
index a2762d6e..a5da187d 100644
--- a/src/stores/wiki-store.ts
+++ b/src/stores/wiki-store.ts
@@ -1,6 +1,14 @@
import { create } from "zustand"
import type { WikiProject, FileNode } from "@/types/wiki"
+/**
+ * Wire protocol used when `provider === "custom"`. Other providers have a
+ * fixed protocol (openai → OpenAI chat; anthropic → Anthropic messages;
+ * etc.), so this field is ignored for them. `undefined` defaults to
+ * `chat_completions` for backward compatibility with pre-0.3.7 configs.
+ */
+export type CustomApiMode = "chat_completions" | "anthropic_messages"
+
interface LlmConfig {
provider: "openai" | "anthropic" | "google" | "ollama" | "custom" | "minimax"
apiKey: string
@@ -8,6 +16,7 @@ interface LlmConfig {
ollamaUrl: string
customEndpoint: string
maxContextSize: number // max context window in characters
+ apiMode?: CustomApiMode
}
interface SearchApiConfig {
@@ -50,6 +59,21 @@ type OutputLanguage =
| "Indonesian"
| "Thai"
+/**
+ * Per-preset saved fields. Each entry survives turning the preset off
+ * and coming back — users don't have to re-enter an API key when they
+ * briefly switch to a different provider.
+ */
+export interface ProviderOverride {
+ apiKey?: string
+ model?: string
+ baseUrl?: string // customEndpoint for custom presets, ollamaUrl for ollama
+ apiMode?: CustomApiMode
+ maxContextSize?: number
+}
+
+export type ProviderConfigs = Record<string, ProviderOverride>
+
interface WikiState {
project: WikiProject | null
fileTree: FileNode[]
@@ -58,6 +82,10 @@ interface WikiState {
chatExpanded: boolean
activeView: "wiki" | "sources" | "search" | "graph" | "lint" | "review" | "settings"
llmConfig: LlmConfig
+ /** Per-provider-preset stored overrides (API key, model, endpoint, …). */
+ providerConfigs: ProviderConfigs
+ /** Which preset is currently active. `null` = no LLM configured. */
+ activePresetId: string | null
searchApiConfig: SearchApiConfig
embeddingConfig: EmbeddingConfig
outputLanguage: OutputLanguage
@@ -70,6 +98,8 @@ interface WikiState {
setChatExpanded: (expanded: boolean) => void
setActiveView: (view: WikiState["activeView"]) => void
setLlmConfig: (config: LlmConfig) => void
+ setProviderConfigs: (configs: ProviderConfigs) => void
+ setActivePresetId: (id: string | null) => void
setSearchApiConfig: (config: SearchApiConfig) => void
setEmbeddingConfig: (config: EmbeddingConfig) => void
setOutputLanguage: (lang: OutputLanguage) => void
@@ -91,6 +121,8 @@ export const useWikiStore = create<WikiState>((set) => ({
ollamaUrl: "http://localhost:11434",
customEndpoint: "",
},
+ providerConfigs: {},
+ activePresetId: null,
dataVersion: 0,
@@ -115,6 +147,8 @@ export const useWikiStore = create<WikiState>((set) => ({
outputLanguage: "auto",
setLlmConfig: (llmConfig) => set({ llmConfig }),
+ setProviderConfigs: (providerConfigs) => set({ providerConfigs }),
+ setActivePresetId: (activePresetId) => set({ activePresetId }),
setSearchApiConfig: (searchApiConfig) => set({ searchApiConfig }),
setEmbeddingConfig: (embeddingConfig) => set({ embeddingConfig }),
setOutputLanguage: (outputLanguage) => set({ outputLanguage }),
diff --git a/src/test-helpers/mock-stream-chat.ts b/src/test-helpers/mock-stream-chat.ts
index 02df759a..c76b35d4 100644
--- a/src/test-helpers/mock-stream-chat.ts
+++ b/src/test-helpers/mock-stream-chat.ts
@@ -8,7 +8,8 @@
*/
import { vi, type Mock } from "vitest"
import type { LlmConfig } from "@/stores/wiki-store"
-import type { ChatMessage, StreamCallbacks } from "@/lib/llm-providers"
+import type { ChatMessage } from "@/lib/llm-providers"
+import type { StreamCallbacks } from "@/lib/llm-client"
import { createDeferred, type Deferred } from "./deferred"
interface PendingCall {