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
feat: add project maintenance and provider controls
nash_sub509a092f857
diff --git a/src-tauri/src/agent/tools.rs b/src-tauri/src/agent/tools.rsindex 24b61c98..1397d944 100644--- a/src-tauri/src/agent/tools.rs+++ b/src-tauri/src/agent/tools.rs@@ -351,6 +351,8 @@ pub struct WebSearchProviderOverride {#[serde(default)]pub api_key: Option<String>,#[serde(default)]+ pub base_url: Option<String>,+ #[serde(default)]pub ollama_url: Option<String>,#[serde(default)]pub sear_xng_url: Option<String>,@@ -1183,7 +1185,7 @@ pub async fn run_web_search(.build().map_err(|err| format!("Failed to build web search client: {err}"))?;let raw = match provider.as_str() {- "firecrawl" => firecrawl_search(&client, query, max_results).await?,+ "firecrawl" => firecrawl_search(&client, query, &config, max_results).await?,"searxng" => searxng_search(&client, query, &config, max_results).await?,"tavily" => tavily_search(&client, query, &config, max_results).await?,"ollama" => ollama_search(&client, query, &config, max_results).await?,@@ -1595,11 +1597,28 @@ struct WebSearchItem {async fn firecrawl_search(client: &reqwest::Client,query: &str,+ config: &WebSearchConfig,max_results: usize,) -> Result<Vec<WebSearchItem>, String> {- let response = client- .post("https://api.firecrawl.dev/v2/search")- .header("Accept", "application/json")+ let override_cfg = config+ .provider_configs+ .as_ref()+ .and_then(|values| values.get("firecrawl"));+ let base = override_cfg+ .and_then(|value| value.base_url.as_deref())+ .filter(|value| !value.trim().is_empty())+ .unwrap_or("https://api.firecrawl.dev")+ .trim_end_matches('/');+ let mut request = client+ .post(format!("{base}/v2/search"))+ .header("Accept", "application/json");+ if let Some(key) = override_cfg+ .and_then(|value| value.api_key.as_deref())+ .filter(|value| !value.trim().is_empty())+ {+ request = request.bearer_auth(key.trim());+ }+ let response = request.json(&json!({ "query": query, "limit": max_results })).send().await@@ -1968,7 +1987,7 @@ fn friendly_firecrawl_error(error: &str) -> String {.to_ascii_lowercase().contains("ip address looks suspicious"){- "Firecrawl Search rejected this IP for key-free access. Add a Firecrawl API key when that backend supports authenticated search, or choose another Web Search provider.".to_string()+ "Firecrawl Search rejected this IP for key-free access. Add a Firecrawl API key in Settings or choose another Web Search provider.".to_string()} else {format!("Firecrawl search failed: {error}")}diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex e2d9e24e..5adf4416 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -8,5 +8,6 @@ pub mod file_history;pub mod file_sync;pub mod fs;pub mod project;+pub mod project_maintenance;pub mod search;pub mod vectorstore;diff --git a/src-tauri/src/commands/project_maintenance.rs b/src-tauri/src/commands/project_maintenance.rsnew file mode 100644index 00000000..b2b2bdeb--- /dev/null+++ b/src-tauri/src/commands/project_maintenance.rs@@ -0,0 +1,293 @@+use serde::Serialize;+use std::collections::BTreeMap;+use std::fs::{self, File};+use std::io::Write;+use std::path::{Component, Path, PathBuf};+use walkdir::WalkDir;+use zip::write::SimpleFileOptions;++const MAX_ARCHIVE_BYTES: u64 = 4 * 1024 * 1024 * 1024;+const MAX_ARCHIVE_ENTRIES: usize = 100_000;++fn safe_relative(path: &Path) -> bool {+ !path.is_absolute()+ && path+ .components()+ .all(|part| matches!(part, Component::Normal(_)))+}++#[cfg(test)]+mod tests {+ use super::*;+ use uuid::Uuid;++ fn temp(name: &str) -> PathBuf {+ std::env::temp_dir().join(format!("llm-wiki-{name}-{}", Uuid::new_v4()))+ }++ #[test]+ fn rebuilds_index_from_page_frontmatter() {+ let root = temp("rebuild-index");+ fs::create_dir_all(root.join("wiki/entities")).unwrap();+ fs::create_dir_all(root.join("wiki/concepts")).unwrap();+ fs::write(+ root.join("wiki/entities/a.md"),+ "---\ntype: entity\ntitle: Alpha\n---\nBody",+ )+ .unwrap();+ fs::write(+ root.join("wiki/concepts/a.md"),+ "---\ntype: concept\ntitle: Also Alpha\n---\nBody",+ )+ .unwrap();+ let result = rebuild_wiki_index_inner(root.to_string_lossy().into_owned()).unwrap();+ let index = fs::read_to_string(root.join("wiki/index.md")).unwrap();+ assert_eq!(result.pages, 2);+ assert!(index.contains("## entity"));+ assert!(index.contains("[[entities/a|Alpha]]"));+ assert!(index.contains("[[concepts/a|Also Alpha]]"));+ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn archive_round_trip_preserves_hidden_project_state() {+ let source = temp("export-source");+ let target = temp("export-target");+ let archive = temp("archive").with_extension("zip");+ fs::create_dir_all(source.join("wiki")).unwrap();+ fs::create_dir_all(source.join(".llm-wiki")).unwrap();+ fs::write(source.join("wiki/index.md"), "# Index").unwrap();+ fs::write(source.join(".llm-wiki/ingest-cache.json"), "{}").unwrap();+ export_project_archive_inner(+ source.to_string_lossy().into_owned(),+ archive.to_string_lossy().into_owned(),+ )+ .unwrap();+ import_project_archive_inner(+ archive.to_string_lossy().into_owned(),+ target.to_string_lossy().into_owned(),+ )+ .unwrap();+ assert_eq!(+ fs::read_to_string(target.join(".llm-wiki/ingest-cache.json")).unwrap(),+ "{}"+ );+ let _ = fs::remove_dir_all(source);+ let _ = fs::remove_dir_all(target);+ let _ = fs::remove_file(archive);+ }+}++#[tauri::command]+pub async fn export_project_archive(+ project_path: String,+ destination: String,+) -> Result<(), String> {+ tauri::async_runtime::spawn_blocking(move || {+ export_project_archive_inner(project_path, destination)+ })+ .await+ .map_err(|error| format!("Project export task failed: {error}"))?+}++fn export_project_archive_inner(project_path: String, destination: String) -> Result<(), String> {+ if !Path::new(&project_path).is_absolute() || !Path::new(&destination).is_absolute() {+ return Err("Project and archive paths must be absolute".into());+ }+ let root = PathBuf::from(&project_path)+ .canonicalize()+ .map_err(|e| e.to_string())?;+ let output = PathBuf::from(destination);+ if output.starts_with(&root) {+ return Err("Export destination must be outside the project directory".into());+ }+ let file = File::create(&output).map_err(|e| e.to_string())?;+ let mut zip = zip::ZipWriter::new(file);+ let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);+ for entry in WalkDir::new(&root).follow_links(false) {+ let entry = entry.map_err(|error| format!("Failed to enumerate project: {error}"))?;+ if entry.path() == root || entry.file_type().is_symlink() {+ continue;+ }+ let rel = entry+ .path()+ .strip_prefix(&root)+ .map_err(|e| e.to_string())?;+ let name = rel.to_string_lossy().replace('\\', "/");+ if entry.file_type().is_dir() {+ zip.add_directory(format!("{name}/"), options)+ .map_err(|e| e.to_string())?;+ } else {+ zip.start_file(name, options).map_err(|e| e.to_string())?;+ let mut source = File::open(entry.path()).map_err(|e| e.to_string())?;+ std::io::copy(&mut source, &mut zip).map_err(|e| e.to_string())?;+ }+ }+ zip.finish().map_err(|e| e.to_string())?;+ Ok(())+}++#[tauri::command]+pub async fn import_project_archive(+ archive_path: String,+ destination: String,+) -> Result<String, String> {+ tauri::async_runtime::spawn_blocking(move || {+ import_project_archive_inner(archive_path, destination)+ })+ .await+ .map_err(|error| format!("Project import task failed: {error}"))?+}++fn import_project_archive_inner(+ archive_path: String,+ destination: String,+) -> Result<String, String> {+ if !Path::new(&archive_path).is_absolute() || !Path::new(&destination).is_absolute() {+ return Err("Archive and destination paths must be absolute".into());+ }+ let file = File::open(archive_path).map_err(|e| e.to_string())?;+ let mut archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;+ if archive.len() > MAX_ARCHIVE_ENTRIES {+ return Err("Project archive contains too many entries".into());+ }+ let mut expanded = 0u64;+ let mut has_project_index = false;+ for index in 0..archive.len() {+ let entry = archive.by_index(index).map_err(|e| e.to_string())?;+ if entry+ .unix_mode()+ .is_some_and(|mode| mode & 0o170000 == 0o120000)+ {+ return Err(format!(+ "Archive contains an unsupported symbolic link: {}",+ entry.name()+ ));+ }+ let rel = Path::new(entry.name());+ if !safe_relative(rel) {+ return Err(format!("Unsafe archive path: {}", entry.name()));+ }+ has_project_index |= rel == Path::new("wiki/index.md") && !entry.is_dir();+ expanded = expanded.saturating_add(entry.size());+ if expanded > MAX_ARCHIVE_BYTES {+ return Err("Project archive exceeds 4 GB expanded limit".into());+ }+ }+ if !has_project_index {+ return Err("Archive is not an LLM Wiki project (wiki/index.md is missing)".into());+ }+ let root = PathBuf::from(destination);+ if root.exists()+ && fs::read_dir(&root)+ .map_err(|e| e.to_string())?+ .next()+ .is_some()+ {+ return Err("Import destination must be empty".into());+ }+ fs::create_dir_all(&root).map_err(|e| e.to_string())?;+ for index in 0..archive.len() {+ let mut entry = archive.by_index(index).map_err(|e| e.to_string())?;+ let rel = Path::new(entry.name());+ let target = root.join(rel);+ if entry.is_dir() {+ fs::create_dir_all(&target).map_err(|e| e.to_string())?;+ continue;+ }+ if let Some(parent) = target.parent() {+ fs::create_dir_all(parent).map_err(|e| e.to_string())?;+ }+ let mut output = File::create(target).map_err(|e| e.to_string())?;+ std::io::copy(&mut entry, &mut output).map_err(|e| e.to_string())?;+ }+ Ok(root.to_string_lossy().into_owned())+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct RebuildIndexResult {+ pub pages: usize,+ pub groups: usize,+}++fn frontmatter_value(content: &str, key: &str) -> Option<String> {+ let normalized = content.replace("\r\n", "\n");+ let body = normalized.strip_prefix("---\n")?.split_once("\n---")?.0;+ body.lines()+ .find_map(|line| {+ let (name, value) = line.split_once(':')?;+ (name.trim() == key).then(|| value.trim().trim_matches(['\"', '\'']).to_string())+ })+ .filter(|value| !value.is_empty())+}++#[tauri::command]+pub async fn rebuild_wiki_index(project_path: String) -> Result<RebuildIndexResult, String> {+ tauri::async_runtime::spawn_blocking(move || rebuild_wiki_index_inner(project_path))+ .await+ .map_err(|error| format!("Index rebuild task failed: {error}"))?+}++fn rebuild_wiki_index_inner(project_path: String) -> Result<RebuildIndexResult, String> {+ let wiki = PathBuf::from(project_path).join("wiki");+ let mut groups: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new();+ for entry in WalkDir::new(&wiki).follow_links(false) {+ let entry = entry.map_err(|error| format!("Failed to enumerate wiki pages: {error}"))?;+ if !entry.file_type().is_file()+ || entry.path().extension().and_then(|v| v.to_str()) != Some("md")+ {+ continue;+ }+ let stem = entry+ .path()+ .file_stem()+ .and_then(|v| v.to_str())+ .unwrap_or_default();+ if matches!(+ stem.to_ascii_lowercase().as_str(),+ "index" | "overview" | "log"+ ) {+ continue;+ }+ let content = fs::read_to_string(entry.path()).map_err(|e| e.to_string())?;+ let kind = frontmatter_value(&content, "type").unwrap_or_else(|| "other".into());+ let title = frontmatter_value(&content, "title").unwrap_or_else(|| stem.to_string());+ let target = entry+ .path()+ .strip_prefix(&wiki)+ .map_err(|e| e.to_string())?+ .with_extension("")+ .to_string_lossy()+ .replace('\\', "/");+ groups.entry(kind).or_default().push((target, title));+ }+ for pages in groups.values_mut() {+ pages.sort_by(|a, b| a.1.to_lowercase().cmp(&b.1.to_lowercase()));+ }+ let count = groups.values().map(Vec::len).sum();+ let mut output = String::from("# Wiki Index\n\n");+ for (kind, pages) in &groups {+ output.push_str(&format!("## {}\n\n", kind));+ for (slug, title) in pages {+ output.push_str(&format!("- [[{}|{}]]\n", slug, title));+ }+ output.push('\n');+ }+ let index_path = wiki.join("index.md");+ let temporary_path = wiki.join(".index.md.rebuild.tmp");+ let mut file = File::create(&temporary_path).map_err(|e| e.to_string())?;+ file.write_all(output.as_bytes())+ .map_err(|e| e.to_string())?;+ file.sync_all().map_err(|e| e.to_string())?;+ drop(file);+ #[cfg(windows)]+ if index_path.exists() {+ fs::remove_file(&index_path).map_err(|e| e.to_string())?;+ }+ fs::rename(&temporary_path, &index_path).map_err(|e| e.to_string())?;+ Ok(RebuildIndexResult {+ pages: count,+ groups: groups.len(),+ })+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 4517777d..1ca9af50 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -642,6 +642,9 @@ pub fn run() {commands::project::open_project,commands::project::open_project_folder,commands::project::open_path_in_project,+ commands::project_maintenance::export_project_archive,+ commands::project_maintenance::import_project_archive,+ commands::project_maintenance::rebuild_wiki_index,commands::search::search_project,commands::search::embedding_fetch,commands::search::get_page_links,diff --git a/src/components/chat/chat-message.tsx b/src/components/chat/chat-message.tsxindex 9d0af23b..1e864ec9 100644--- a/src/components/chat/chat-message.tsx+++ b/src/components/chat/chat-message.tsx@@ -1413,7 +1413,7 @@ function MarkdownContent({ content }: { content: string }) {<div>{thinking && <ThinkingBlock content={thinking} />}<div- className="chat-markdown prose prose-sm max-w-none dark:prose-invert prose-p:my-1 prose-headings:my-2 prose-ul:my-1 prose-ol:my-1 prose-li:my-0 prose-pre:my-2 prose-code:text-xs prose-code:before:content-none prose-code:after:content-none"+ className="chat-markdown prose max-w-none dark:prose-invert prose-code:before:content-none prose-code:after:content-none"dir={direction}lang={htmlLang}style={{ textAlign: "start" }}diff --git a/src/components/layout/app-layout.tsx b/src/components/layout/app-layout.tsxindex 65499e73..b5684f4b 100644--- a/src/components/layout/app-layout.tsx+++ b/src/components/layout/app-layout.tsx@@ -10,17 +10,25 @@ import { ActivityPanel } from "./activity-panel"import { useResearchStore } from "@/stores/research-store"import { ErrorBoundary } from "@/components/error-boundary"import { getAppLayoutVisibility } from "./app-layout-visibility"+import { PanelLeftOpen } from "lucide-react"+import { useTranslation } from "react-i18next"++const LEFT_PANEL_COLLAPSED_KEY = "llm-wiki:left-panel-collapsed"interface AppLayoutProps {onSwitchProject: () => void}export function AppLayout({ onSwitchProject }: AppLayoutProps) {+ const { t } = useTranslation()const project = useWikiStore((s) => s.project)const activeView = useWikiStore((s) => s.activeView)const researchPanelOpen = useResearchStore((s) => s.panelOpen)const [leftWidth, setLeftWidth] = useState(220)const [rightWidth, setRightWidth] = useState(400)+ const [leftCollapsed, setLeftCollapsed] = useState(+ () => localStorage.getItem(LEFT_PANEL_COLLAPSED_KEY) === "true",+ )const isDraggingLeft = useRef(false)const isDraggingRight = useRef(false)const containerRef = useRef<HTMLDivElement>(null)@@ -82,6 +90,13 @@ export function AppLayout({ onSwitchProject }: AppLayoutProps) {// activity strip, and optional right research panel there so those// screens use the whole work area.const { showLeftPanel, hasRightPanel } = getAppLayoutVisibility(activeView, researchPanelOpen)+ const toggleLeftPanel = () => {+ setLeftCollapsed((value) => {+ const next = !value+ localStorage.setItem(LEFT_PANEL_COLLAPSED_KEY, String(next))+ return next+ })+ }return (// Outer column layout: full-width update banner on top (when an@@ -94,7 +109,7 @@ export function AppLayout({ onSwitchProject }: AppLayoutProps) {<div className="flex min-h-0 flex-1"><IconSidebar onSwitchProject={onSwitchProject} /><div ref={containerRef} className="relative flex min-w-0 flex-1 overflow-hidden">- {showLeftPanel && (+ {showLeftPanel && !leftCollapsed && (<>{/* Left: File tree + Activity */}<div@@ -102,7 +117,7 @@ export function AppLayout({ onSwitchProject }: AppLayoutProps) {style={{ width: leftWidth }}><div className="flex-1 overflow-hidden">- <SidebarPanel />+ <SidebarPanel onCollapse={toggleLeftPanel} /></div><ActivityPanel /></div>@@ -113,6 +128,20 @@ export function AppLayout({ onSwitchProject }: AppLayoutProps) {</>)}+ {showLeftPanel && leftCollapsed && (+ <div className="flex w-9 shrink-0 justify-center border-r bg-muted/20 pt-2">+ <button+ type="button"+ onClick={toggleLeftPanel}+ className="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ title={t("layout.showSidebar", "Show sidebar")}+ aria-label={t("layout.showSidebar", "Show sidebar")}+ >+ <PanelLeftOpen className="h-4 w-4" />+ </button>+ </div>+ )}+{/* Center: Chat, wiki preview, or tool view */}<div className="min-w-0 flex-1 overflow-hidden"><ErrorBoundary>diff --git a/src/components/layout/sidebar-panel.tsx b/src/components/layout/sidebar-panel.tsxindex 5cffb260..611e3396 100644--- a/src/components/layout/sidebar-panel.tsx+++ b/src/components/layout/sidebar-panel.tsx@@ -1,9 +1,14 @@import { useState } from "react"import { useTranslation } from "react-i18next"+import { PanelLeftClose } from "lucide-react"import { KnowledgeTree } from "./knowledge-tree"import { FileTree } from "./file-tree"-export function SidebarPanel() {+interface SidebarPanelProps {+ onCollapse?: () => void+}++export function SidebarPanel({ onCollapse }: SidebarPanelProps) {const { t } = useTranslation()const [mode, setMode] = useState<"knowledge" | "files">("knowledge")@@ -30,6 +35,17 @@ export function SidebarPanel() {>{t("sidebar.files")}</button>+ {onCollapse && (+ <button+ type="button"+ onClick={onCollapse}+ className="flex w-9 shrink-0 items-center justify-center border-l text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ title={t("layout.hideSidebar", "Hide sidebar")}+ aria-label={t("layout.hideSidebar", "Hide sidebar")}+ >+ <PanelLeftClose className="h-4 w-4" />+ </button>+ )}</div><div className="flex-1 overflow-hidden">{mode === "knowledge" ? <KnowledgeTree /> : <FileTree />}diff --git a/src/components/settings/preset-resolver.ts b/src/components/settings/preset-resolver.tsindex 252abcb4..52f7ec0e 100644--- a/src/components/settings/preset-resolver.ts+++ b/src/components/settings/preset-resolver.ts@@ -40,6 +40,10 @@ export function resolveConfig(typeof ov.codexCliTimeoutMinutes === "number" && Number.isFinite(ov.codexCliTimeoutMinutes)? Math.max(1, Math.min(240, Math.floor(ov.codexCliTimeoutMinutes))): undefined+ const requestTimeoutMinutes =+ typeof ov.requestTimeoutMinutes === "number" && Number.isFinite(ov.requestTimeoutMinutes)+ ? Math.max(1, Math.min(1440, Math.floor(ov.requestTimeoutMinutes)))+ : fallback.requestTimeoutMinutesif (preset.provider === "custom") {return {@@ -52,6 +56,7 @@ export function resolveConfig(apiMode: ov.apiMode ?? preset.apiMode ?? "chat_completions",reasoning,localCliIsolation: false,+ requestTimeoutMinutes,}}@@ -65,6 +70,7 @@ export function resolveConfig(maxContextSize,reasoning,localCliIsolation: false,+ requestTimeoutMinutes,}}@@ -80,6 +86,7 @@ export function resolveConfig(maxContextSize,reasoning,localCliIsolation: false,+ requestTimeoutMinutes,}}@@ -96,6 +103,7 @@ export function resolveConfig(reasoning,localCliIsolation,codexCliTimeoutMinutes: preset.provider === "codex-cli" ? codexCliTimeoutMinutes : undefined,+ requestTimeoutMinutes,}}@@ -111,5 +119,6 @@ export function resolveConfig(maxContextSize,reasoning,localCliIsolation: false,+ requestTimeoutMinutes,}}diff --git a/src/components/settings/sections/llm-provider-section.tsx b/src/components/settings/sections/llm-provider-section.tsxindex 7d6b9995..b68ec3eb 100644--- a/src/components/settings/sections/llm-provider-section.tsx+++ b/src/components/settings/sections/llm-provider-section.tsx@@ -140,6 +140,7 @@ function PresetRow({const reasoning = ov.reasoning ?? { mode: "auto" as const }const localCliIsolation = ov.localCliIsolation === trueconst codexCliTimeoutMinutes = Math.max(1, Math.min(240, ov.codexCliTimeoutMinutes ?? 10))+ const requestTimeoutMinutes = Math.max(1, Math.min(1440, ov.requestTimeoutMinutes ?? 30))const isLocalCliProvider = preset.provider === "claude-code" || preset.provider === "codex-cli"const [testState, setTestState] = useState<ProviderTestState>({ kind: "idle" })const hasConfig = !!apiKey || !!ov.baseUrl || !!ov.model || !!ov.azureApiVersion || !!ov.azureModelFamily@@ -431,6 +432,24 @@ function PresetRow({/></div>+ {!isLocalCliProvider && (+ <div className="space-y-2">+ <Label>{t("settings.sections.llm.requestTimeout", "Request timeout (minutes)")}</Label>+ <Input+ type="number"+ min={1}+ max={1440}+ value={requestTimeoutMinutes}+ onChange={(e) => onChange({+ requestTimeoutMinutes: Math.max(1, Math.min(1440, Number(e.target.value) || 30)),+ })}+ />+ <p className="text-xs text-muted-foreground">+ {t("settings.sections.llm.requestTimeoutHint", "Increase this for slow local CPU models. The default is 30 minutes.")}+ </p>+ </div>+ )}+<ReasoningControlsvalue={reasoning}onChange={(reasoning) => onChange({ reasoning })}diff --git a/src/components/settings/sections/maintenance-section.tsx b/src/components/settings/sections/maintenance-section.tsxindex e0eaef02..440daadb 100644--- a/src/components/settings/sections/maintenance-section.tsx+++ b/src/components/settings/sections/maintenance-section.tsx@@ -1,5 +1,7 @@import { useCallback, useEffect, useMemo, useState } from "react"import { useTranslation } from "react-i18next"+import { invoke } from "@tauri-apps/api/core"+import { open, save } from "@tauri-apps/plugin-dialog"import {Wrench,Loader2,@@ -9,6 +11,8 @@ import {Trash2,RotateCcw,Clock,+ Archive,+ ListRestart,} from "lucide-react"import { Button } from "@/components/ui/button"import { Label } from "@/components/ui/label"@@ -27,6 +31,9 @@ import {type DedupTask,} from "@/lib/dedup-queue"import type { DuplicateGroup } from "@/lib/dedup"+import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"+import { openProject } from "@/commands/fs"+import { addToRecentProjects } from "@/lib/project-store"interface GroupUiEntry {group: DuplicateGroup@@ -54,6 +61,43 @@ export function MaintenanceSection() {const [scanError, setScanError] = useState<string | null>(null)const [groups, setGroups] = useState<GroupUiEntry[]>([])const [scanCompleted, setScanCompleted] = useState(false)+ const [projectToolStatus, setProjectToolStatus] = useState<string | null>(null)+ const [projectToolBusy, setProjectToolBusy] = useState(false)++ const handleRebuildIndex = useCallback(async () => {+ if (!project) return+ setProjectToolBusy(true)+ try {+ const result = await invoke<{ pages: number; groups: number }>("rebuild_wiki_index", { projectPath: project.path })+ await refreshProjectFileTree(project.path, { bumpDataVersion: true })+ setProjectToolStatus(t("settings.sections.maintenance.projectData.rebuilt", { pages: result.pages, groups: result.groups }))+ } catch (error) { setProjectToolStatus(String(error)) } finally { setProjectToolBusy(false) }+ }, [project, t])++ const handleExportProject = useCallback(async () => {+ if (!project) return+ const destination = await save({ defaultPath: `${project.name}.llmwiki.zip`, filters: [{ name: "LLM Wiki project", extensions: ["zip"] }] })+ if (!destination) return+ setProjectToolBusy(true)+ try {+ await invoke("export_project_archive", { projectPath: project.path, destination })+ setProjectToolStatus(t("settings.sections.maintenance.projectData.exported", { path: destination }))+ } catch (error) { setProjectToolStatus(String(error)) } finally { setProjectToolBusy(false) }+ }, [project, t])++ const handleImportProject = useCallback(async () => {+ const archive = await open({ multiple: false, filters: [{ name: "LLM Wiki project", extensions: ["zip"] }] })+ if (!archive || Array.isArray(archive)) return+ const destination = await open({ directory: true, multiple: false, createDirectories: true })+ if (!destination || Array.isArray(destination)) return+ setProjectToolBusy(true)+ try {+ const path = await invoke<string>("import_project_archive", { archivePath: archive, destination })+ const imported = await openProject(path)+ await addToRecentProjects(imported)+ setProjectToolStatus(t("settings.sections.maintenance.projectData.imported", { name: imported.name }))+ } catch (error) { setProjectToolStatus(String(error)) } finally { setProjectToolBusy(false) }+ }, [t])// Poll the queue at 1Hz so the UI reflects pending → processing →// failed transitions and cross-window queue activity (e.g. a merge@@ -223,6 +267,17 @@ export function MaintenanceSection() {</p></div>+ <div className="space-y-3 rounded-lg border border-border/60 bg-muted/20 p-4">+ <div className="flex items-center gap-2"><ListRestart className="h-4 w-4 text-muted-foreground" /><h3 className="text-sm font-semibold">{t("settings.sections.maintenance.projectData.title")}</h3></div>+ <p className="text-xs text-muted-foreground">{t("settings.sections.maintenance.projectData.description")}</p>+ <div className="flex flex-wrap gap-2">+ <Button variant="outline" onClick={() => void handleRebuildIndex()} disabled={!project || projectToolBusy}>{t("settings.sections.maintenance.projectData.rebuild")}</Button>+ <Button variant="outline" onClick={() => void handleExportProject()} disabled={!project || projectToolBusy}><Archive className="h-4 w-4" />{t("settings.sections.maintenance.projectData.export")}</Button>+ <Button variant="outline" onClick={() => void handleImportProject()} disabled={projectToolBusy}>{t("settings.sections.maintenance.projectData.import")}</Button>+ </div>+ {projectToolStatus && <p className="text-xs text-muted-foreground">{projectToolStatus}</p>}+ </div>+<div className="space-y-3 rounded-lg border border-border/60 bg-muted/20 p-4"><div className="flex items-center gap-2"><Wrench className="h-4 w-4 text-muted-foreground" />diff --git a/src/components/settings/sections/web-search-section.tsx b/src/components/settings/sections/web-search-section.tsxindex a37b6147..d3be2c2a 100644--- a/src/components/settings/sections/web-search-section.tsx+++ b/src/components/settings/sections/web-search-section.tsx@@ -16,6 +16,7 @@ import {SEARXNG_CATEGORY_OPTIONS,SERPAPI_ENGINE_OPTIONS,resolveSearchConfig,+ DEFAULT_FIRECRAWL_URL,webSearch,} from "@/lib/web-search"@@ -51,7 +52,7 @@ const SEARCH_PROVIDERS = [{id: "firecrawl",label: "Firecrawl",- hint: "Anonymous Firecrawl Search API",+ hint: "Anonymous or authenticated Firecrawl Search API",configKind: "none",},{@@ -356,7 +357,30 @@ export function WebSearchSection() {{isExpanded && (<div className="space-y-4 border-t bg-background/50 px-4 py-3">- {provider.configKind === "url" ? (+ {provider.id === "firecrawl" ? (+ <div className="grid gap-3 md:grid-cols-2">+ <div className="space-y-2">+ <Label>{t("settings.apiKey")} ({t("common.optional", "optional")})</Label>+ <Input+ type="password"+ value={override?.apiKey ?? ""}+ onChange={(e) => updateProvider("firecrawl", { apiKey: e.target.value })}+ placeholder="fc-..."+ />+ </div>+ <div className="space-y-2">+ <Label>{t("settings.sections.webSearch.instanceUrl")}</Label>+ <Input+ value={override?.baseUrl ?? ""}+ onChange={(e) => updateProvider("firecrawl", { baseUrl: e.target.value })}+ placeholder={DEFAULT_FIRECRAWL_URL}+ />+ </div>+ <p className="text-xs text-muted-foreground md:col-span-2">+ {t("settings.sections.webSearch.firecrawlHint")}+ </p>+ </div>+ ) : provider.configKind === "url" ? (<div className="space-y-2"><Label>{t("settings.sections.webSearch.instanceUrl")}</Label><Input@@ -368,7 +392,7 @@ export function WebSearchSection() {{t("settings.sections.webSearch.searxngJsonHint")}</p></div>- ) : provider.configKind !== "none" ? (+ ) : (<div className="space-y-2"><Label>{t("settings.apiKey")}</Label><Input@@ -383,10 +407,6 @@ export function WebSearchSection() {</p>)}</div>- ) : (- <p className="text-xs text-muted-foreground">- {t("settings.sections.webSearch.firecrawlHint")}- </p>)}{provider.id === "serpapi" && (diff --git a/src/i18n/en.json b/src/i18n/en.jsonindex 601165ed..7c8c8100 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -560,7 +560,7 @@"savedBadge": "Saved","instanceUrl": "Instance URL","ollamaHint": "Uses the official Ollama Web Search API (`https://ollama.com/api/web_search`). An Ollama API key is required.",- "firecrawlHint": "Uses Firecrawl's anonymous Search API (`https://api.firecrawl.dev/v2/search`). No API key is required here, but Firecrawl may block suspicious IP addresses.",+ "firecrawlHint": "Leave API key blank for anonymous search, or add a Firecrawl API key for authenticated quota. Base URL supports compatible self-hosted endpoints.","searxngJsonHint": "The instance must allow JSON search responses (`format=json`).","searchCategories": "Search categories","searxngCategoriesHint": "Categories are sent as the SearXNG `categories` parameter.",@@ -721,6 +721,16 @@"description": "Tools for cleaning up the wiki — detect and merge duplicate entities/concepts that the LLM created under different names across re-ingests.","noProject": "Open a project first.","noLlm": "Configure an LLM provider first.",+ "projectData": {+ "title": "Project data",+ "description": "Rebuild navigation from existing pages, or move a complete project including its hidden processing state.",+ "rebuild": "Rebuild index",+ "export": "Export project",+ "import": "Import project",+ "rebuilt": "Rebuilt index with {{pages}} pages in {{groups}} groups.",+ "exported": "Project exported to {{path}}",+ "imported": "Imported {{name}}. Switch projects to open it."+ },"dedup": {"title": "Detect duplicate entities / concepts","description": "Asks the LLM to scan all entity / concept pages and group ones that likely refer to the same topic under different names (English vs Chinese, plural vs singular, abbreviation vs full form). You confirm each group before merging. Merges are queued and run one at a time so cross-references stay consistent.",diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex 1fdedd50..d8364535 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -560,7 +560,7 @@"savedBadge": "已保存","instanceUrl": "实例 URL","ollamaHint": "使用官方 Ollama Web Search API(`https://ollama.com/api/web_search`),需要填写 Ollama API Key。",- "firecrawlHint": "使用 Firecrawl 的匿名搜索 API(`https://api.firecrawl.dev/v2/search`),这里不需要 API Key;但 Firecrawl 可能会拦截可疑 IP。",+ "firecrawlHint": "API Key 留空时使用匿名搜索;填写 Firecrawl API Key 后使用认证额度。Base URL 也可指向兼容的自托管端点。","searxngJsonHint": "实例必须允许 JSON 搜索响应(`format=json`)。","searchCategories": "搜索分类","searxngCategoriesHint": "分类会作为 SearXNG 的 `categories` 参数发送。",@@ -721,6 +721,16 @@"description": "清理 wiki 的工具 —— 检测并合并 LLM 在多次再导入时用不同名字创建的重复实体 / 概念。","noProject": "请先打开一个项目。","noLlm": "请先配置 LLM 服务。",+ "projectData": {+ "title": "项目数据",+ "description": "根据现有页面重建导航,或完整迁移项目及其隐藏的处理状态。",+ "rebuild": "重建索引",+ "export": "导出项目",+ "import": "导入项目",+ "rebuilt": "已使用 {{pages}} 个页面、{{groups}} 个分组重建索引。",+ "exported": "项目已导出到 {{path}}",+ "imported": "已导入 {{name}},请切换项目后打开。"+ },"dedup": {"title": "检测重复实体 / 概念","description": "让 LLM 扫描全部 entity / concept 页面,把可能指向同一主题但用了不同名字的页面分组(中英对照、单复数、缩写与全称等)。每一组都需要你确认后才会合并。合并任务会进入串行队列依次执行,避免交叉引用被并发改写覆盖。",diff --git a/src/index.css b/src/index.cssindex 3787e14a..fb57c899 100644--- a/src/index.css+++ b/src/index.css@@ -5,6 +5,24 @@@custom-variant dark (&:is(.dark *));+/* Chat answers need stronger document hierarchy than compact tool output. Keep+ this scoped so wiki pages and generated artifact previews retain their own+ typography. */+.chat-markdown { font-size: 0.925rem; line-height: 1.7; }+.chat-markdown > :first-child { margin-top: 0; }+.chat-markdown > :last-child { margin-bottom: 0; }+.chat-markdown h1 { margin: 1.4em 0 0.55em; font-size: 1.45rem; line-height: 1.25; font-weight: 700; }+.chat-markdown h2 { margin: 1.3em 0 0.5em; padding-bottom: 0.3em; border-bottom: 1px solid var(--border); font-size: 1.2rem; line-height: 1.3; font-weight: 650; }+.chat-markdown h3 { margin: 1.15em 0 0.4em; font-size: 1.05rem; line-height: 1.35; font-weight: 650; }+.chat-markdown p { margin: 0.65em 0; }+.chat-markdown ul, .chat-markdown ol { margin: 0.65em 0; padding-inline-start: 1.5rem; }+.chat-markdown li { margin: 0.3em 0; }+.chat-markdown blockquote { margin: 0.9em 0; border-inline-start: 3px solid var(--primary); background: var(--muted); padding: 0.65rem 0.9rem; color: var(--muted-foreground); }+.chat-markdown table { display: block; max-width: 100%; overflow-x: auto; margin: 1em 0; border-collapse: collapse; }+.chat-markdown th { background: var(--muted); font-weight: 600; }+.chat-markdown th, .chat-markdown td { border: 1px solid var(--border); padding: 0.5rem 0.7rem; text-align: start; }+.chat-markdown pre { margin: 0.9em 0; }+@theme inline {--font-heading: var(--font-sans);--font-sans: 'Geist Variable', sans-serif;diff --git a/src/lib/llm-client.test.ts b/src/lib/llm-client.test.tsindex 91e6d865..56c18f3a 100644--- a/src/lib/llm-client.test.ts+++ b/src/lib/llm-client.test.ts@@ -154,6 +154,22 @@ describe("streamChat — mid-stream abort mapping", () => {expect(onDone).not.toHaveBeenCalled()})+ it("uses the provider's configured request timeout", async () => {+ const { response, getReject, readCalled } = pendingStreamResponse()+ mockHttpFetch.mockResolvedValue(response)+ const onError = vi.fn()+ const promise = streamChat(+ { ...cfg, requestTimeoutMinutes: 90 },+ [{ role: "user", content: "hi" }],+ { onToken: vi.fn(), onDone: vi.fn(), onError },+ )+ await readCalled+ await vi.advanceTimersByTimeAsync(90 * 60 * 1000)+ getReject()("Request cancelled")+ await promise+ expect(onError.mock.calls[0][0].message).toMatch(/timed out after 90 min/)+ })+it("treats a bare-string abort as a silent cancel when the backstop did NOT fire", async () => {const { response, getReject, readCalled } = pendingStreamResponse()mockHttpFetch.mockResolvedValue(response)diff --git a/src/lib/llm-client.ts b/src/lib/llm-client.tsindex d8b36177..34bcc3b0 100644--- a/src/lib/llm-client.ts+++ b/src/lib/llm-client.ts@@ -93,7 +93,8 @@ export async function streamChat(// 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+ const timeoutMinutes = Math.max(1, Math.min(1440, config.requestTimeoutMinutes ?? 30))+ const timeoutMs = timeoutMinutes * 60 * 1000let combinedSignal = signallet timeoutController: AbortController | undefinedlet timeoutFired = falsediff --git a/src/lib/web-search.ts b/src/lib/web-search.tsindex e87e54c1..5f029dde 100644--- a/src/lib/web-search.ts+++ b/src/lib/web-search.ts@@ -15,6 +15,8 @@ export interface WebSearchResult {source: string}+export const DEFAULT_FIRECRAWL_URL = "https://api.firecrawl.dev"+export const SERPAPI_ENGINE_OPTIONS: { value: SerpApiEngine; label: string; hint: string }[] = [{ value: "google", label: "Google Web", hint: "SerpApi Google Search API organic results" },{ value: "google_news", label: "Google News", hint: "News-focused results" },diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.tsindex 4a2654da..2846842d 100644--- a/src/stores/wiki-store.ts+++ b/src/stores/wiki-store.ts@@ -43,6 +43,8 @@ interface LlmConfig {localCliIsolation?: boolean/** Codex CLI provider only. Overall subprocess timeout in minutes. */codexCliTimeoutMinutes?: number+ /** HTTP LLM request backstop. Defaults to 30 minutes for legacy configs. */+ requestTimeoutMinutes?: number}export type SearchProvider =@@ -80,6 +82,7 @@ export type SearXngCategory =export interface SearchProviderOverride {apiKey?: string+ baseUrl?: stringserpApiEngine?: SerpApiEnginesearXngUrl?: stringsearXngCategories?: SearXngCategory[]@@ -315,6 +318,7 @@ export interface ProviderOverride {reasoning?: ReasoningConfiglocalCliIsolation?: booleancodexCliTimeoutMinutes?: number+ requestTimeoutMinutes?: number}export type ProviderConfigs = Record<string, ProviderOverride>