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 persistent file history and restore
nash_su4b977708d792
diff --git a/src-tauri/src/agent/tools.rs b/src-tauri/src/agent/tools.rsindex bc74d7fe..f22af309 100644--- a/src-tauri/src/agent/tools.rs+++ b/src-tauri/src/agent/tools.rs@@ -670,7 +670,9 @@ fn write_wiki_page_with_activity(}let existed_before = path.is_file();let previous_content = workspace_rollback_snapshot(&path);+ crate::commands::file_history::record_file_version(&path, "baseline", "before.wiki.write_page");fs::write(&path, content).map_err(|err| format!("Failed to write wiki page: {err}"))?;+ crate::commands::file_history::record_file_version(&path, "agent", "wiki.write_page");Ok(WikiWriteOutput {reference: AgentReference {title: extract_markdown_title(content).unwrap_or_else(|| {@@ -710,7 +712,13 @@ fn write_workspace_file(}let existed_before = path.is_file();let previous_content = workspace_rollback_snapshot(&path);+ crate::commands::file_history::record_file_version(+ &path,+ "baseline",+ "before.workspace.write_file",+ );fs::write(&path, content).map_err(|err| format!("workspace.write_file failed: {err}"))?;+ crate::commands::file_history::record_file_version(&path, "agent", "workspace.write_file");Ok(WorkspaceWriteOutput {path: format!("{AGENT_WORKSPACE_DIR}/{rel}"),bytes: content.len(),@@ -738,6 +746,11 @@ fn append_workspace_file(}let existed_before = path.is_file();let previous_content = workspace_rollback_snapshot(&path);+ crate::commands::file_history::record_file_version(+ &path,+ "baseline",+ "before.workspace.append_file",+ );OpenOptions::new().create(true).append(true)@@ -747,6 +760,7 @@ fn append_workspace_file(file.write_all(content.as_bytes())}).map_err(|err| format!("workspace.append_file failed: {err}"))?;+ crate::commands::file_history::record_file_version(&path, "agent", "workspace.append_file");let bytes = fs::metadata(&path).map(|metadata| metadata.len() as usize).unwrap_or(content.len());diff --git a/src-tauri/src/commands/file_history.rs b/src-tauri/src/commands/file_history.rsnew file mode 100644index 00000000..c3bf5ae1--- /dev/null+++ b/src-tauri/src/commands/file_history.rs@@ -0,0 +1,189 @@+use std::fs;+use std::path::{Path, PathBuf};+use std::sync::Mutex;++use chrono::Utc;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++const MAX_HISTORY_CONTENT_BYTES: usize = 2 * 1024 * 1024;+const MAX_ENTRIES_PER_FILE: usize = 50;+static HISTORY_LOCK: Mutex<()> = Mutex::new(());++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FileHistoryEntry {+ pub id: String,+ pub path: String,+ pub timestamp: i64,+ pub author: String,+ pub tool: String,+ pub content: String,+}++fn project_root_for(path: &Path) -> Option<PathBuf> {+ let mut cursor = path.parent();+ while let Some(dir) = cursor {+ if dir.join(".llm-wiki").is_dir() {+ return Some(dir.to_path_buf());+ }+ cursor = dir.parent();+ }+ None+}++fn history_path(root: &Path, path: &Path) -> PathBuf {+ let relative = path.strip_prefix(root).unwrap_or(path).to_string_lossy();+ // Fixed FNV-1a keeps history addresses stable across Rust/toolchain upgrades.+ let mut hash = 0xcbf29ce484222325_u64;+ for byte in relative.as_bytes() {+ hash ^= u64::from(*byte);+ hash = hash.wrapping_mul(0x100000001b3);+ }+ let key = format!("{hash:016x}");+ root.join(".llm-wiki/history").join(format!("{key}.json"))+}++pub fn record_file_version(path: &Path, author: &str, tool: &str) {+ let Ok(metadata) = fs::metadata(path) else {+ return;+ };+ if !metadata.is_file() || metadata.len() as usize > MAX_HISTORY_CONTENT_BYTES {+ return;+ }+ let Ok(content) = fs::read_to_string(path) else {+ return;+ };+ let Some(root) = project_root_for(path) else {+ return;+ };+ if path.starts_with(root.join(".llm-wiki")) {+ return;+ }+ let Ok(_guard) = HISTORY_LOCK.lock() else {+ return;+ };+ let store_path = history_path(&root, path);+ let mut entries: Vec<FileHistoryEntry> = fs::read_to_string(&store_path)+ .ok()+ .and_then(|raw| serde_json::from_str(&raw).ok())+ .unwrap_or_default();+ if entries.last().is_some_and(|entry| entry.content == content) {+ return;+ }+ entries.push(FileHistoryEntry {+ id: Uuid::new_v4().to_string(),+ path: path.to_string_lossy().replace('\\', "/"),+ timestamp: Utc::now().timestamp_millis(),+ author: author.to_string(),+ tool: tool.to_string(),+ content,+ });+ if entries.len() > MAX_ENTRIES_PER_FILE {+ entries.drain(..entries.len() - MAX_ENTRIES_PER_FILE);+ }+ if let Some(parent) = store_path.parent() {+ let _ = fs::create_dir_all(parent);+ }+ if let Ok(raw) = serde_json::to_string(&entries) {+ let _ = fs::write(store_path, raw);+ }+}++fn checked_file(project_path: &str, file_path: &str) -> Result<(PathBuf, PathBuf), String> {+ let root = Path::new(project_path)+ .canonicalize()+ .map_err(|e| e.to_string())?;+ let file = Path::new(file_path)+ .canonicalize()+ .map_err(|e| e.to_string())?;+ if !file.starts_with(&root) || file.starts_with(root.join(".llm-wiki")) {+ return Err("History path must stay inside the project".to_string());+ }+ Ok((root, file))+}++#[tauri::command]+pub async fn list_file_history(+ project_path: String,+ file_path: String,+) -> Result<Vec<FileHistoryEntry>, String> {+ tauri::async_runtime::spawn_blocking(move || {+ let (root, file) = checked_file(&project_path, &file_path)?;+ let raw =+ fs::read_to_string(history_path(&root, &file)).unwrap_or_else(|_| "[]".to_string());+ let mut entries: Vec<FileHistoryEntry> = serde_json::from_str(&raw).unwrap_or_default();+ entries.reverse();+ Ok(entries)+ })+ .await+ .map_err(|e| e.to_string())?+}++#[tauri::command]+pub async fn restore_file_history(+ project_path: String,+ file_path: String,+ entry_id: String,+) -> Result<String, String> {+ tauri::async_runtime::spawn_blocking(move || {+ let (root, file) = checked_file(&project_path, &file_path)?;+ let raw = fs::read_to_string(history_path(&root, &file)).map_err(|e| e.to_string())?;+ let entries: Vec<FileHistoryEntry> =+ serde_json::from_str(&raw).map_err(|e| e.to_string())?;+ let entry = entries+ .into_iter()+ .find(|entry| entry.id == entry_id)+ .ok_or_else(|| "History entry not found".to_string())?;+ fs::write(&file, &entry.content).map_err(|e| e.to_string())?;+ record_file_version(&file, "human", "history.restore");+ Ok(entry.content)+ })+ .await+ .map_err(|e| e.to_string())?+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn records_and_restores_append_only_versions() {+ let root = std::env::temp_dir().join(format!("llm-wiki-history-{}", Uuid::new_v4()));+ fs::create_dir_all(root.join(".llm-wiki")).unwrap();+ fs::create_dir_all(root.join("wiki")).unwrap();+ let file = root.join("wiki/page.md");+ fs::write(&file, "before").unwrap();+ record_file_version(&file, "baseline", "before.test");+ fs::write(&file, "after").unwrap();+ record_file_version(&file, "agent", "test.write");++ let entries = list_file_history(+ root.to_string_lossy().into_owned(),+ file.to_string_lossy().into_owned(),+ )+ .await+ .unwrap();+ assert_eq!(entries.len(), 2);+ let old = entries+ .iter()+ .find(|entry| entry.content == "before")+ .unwrap();+ restore_file_history(+ root.to_string_lossy().into_owned(),+ file.to_string_lossy().into_owned(),+ old.id.clone(),+ )+ .await+ .unwrap();+ assert_eq!(fs::read_to_string(&file).unwrap(), "before");+ let restored = list_file_history(+ root.to_string_lossy().into_owned(),+ file.to_string_lossy().into_owned(),+ )+ .await+ .unwrap();+ assert_eq!(restored.first().unwrap().tool, "history.restore");+ let _ = fs::remove_dir_all(root);+ }+}diff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rsindex a1be56a8..e8acf3e2 100644--- a/src-tauri/src/commands/fs.rs+++ b/src-tauri/src/commands/fs.rs@@ -979,8 +979,14 @@ pub async fn write_file(path: String, contents: String) -> Result<(), String> {.map_err(|e| format!("Failed to create parent dirs for '{}': {}", path, e))?;}file_sync::mark_app_write_path(p);+ crate::commands::file_history::record_file_version(+ p,+ "baseline",+ "before.ui.write_file",+ );fs::write(&path, contents).map_err(|e| format!("Failed to write file '{}': {}", path, e))?;+ crate::commands::file_history::record_file_version(p, "human", "ui.write_file");file_sync::mark_app_write_path(p);Ok(())})@@ -1039,6 +1045,11 @@ pub async fn write_file_atomic(path: String, contents: String) -> Result<(), Strfile_sync::mark_app_write_path(&tmp_path);file_sync::mark_app_write_path(p);+ crate::commands::file_history::record_file_version(+ p,+ "baseline",+ "before.ui.write_file_atomic",+ );fs::write(&tmp_path, contents).map_err(|e| {format!("Failed to write temp file '{}': {}", tmp_path.display(), e)})?;@@ -1052,6 +1063,7 @@ pub async fn write_file_atomic(path: String, contents: String) -> Result<(), Stre)})?;+ crate::commands::file_history::record_file_version(p, "human", "ui.write_file_atomic");file_sync::mark_app_write_path(p);Ok(())})diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex e13992d0..bad19e3b 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -3,6 +3,7 @@ mod cli_resolver;pub mod codex_cli;pub mod external_search;pub mod extract_images;+pub mod file_history;pub mod file_sync;pub mod fs;pub mod project;diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 9fef26a0..e8d7ffd7 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -622,6 +622,8 @@ pub fn run() {commands::fs::write_file,commands::fs::write_file_base64,commands::fs::write_file_atomic,+ commands::file_history::list_file_history,+ commands::file_history::restore_file_history,commands::fs::list_directory,commands::fs::copy_file,commands::fs::copy_directory,diff --git a/src/commands/fs.ts b/src/commands/fs.tsindex b20699c8..451e54f6 100644--- a/src/commands/fs.ts+++ b/src/commands/fs.ts@@ -141,6 +141,23 @@ export async function getFileMd5(path: string): Promise<string> {return invoke<string>("get_file_md5", { path })}+export interface FileHistoryEntry {+ id: string+ path: string+ timestamp: number+ author: string+ tool: string+ content: string+}++export async function listFileHistory(projectPath: string, filePath: string): Promise<FileHistoryEntry[]> {+ return invoke<FileHistoryEntry[]>("list_file_history", { projectPath, filePath })+}++export async function restoreFileHistory(projectPath: string, filePath: string, entryId: string): Promise<string> {+ return invoke<string>("restore_file_history", { projectPath, filePath, entryId })+}+function assertAbsoluteFsPath(operation: string, path: string): void {if (!isAbsolutePath(path)) {throw new Error(`${operation} requires an absolute path: ${path}`)diff --git a/src/components/editor/file-history-panel.tsx b/src/components/editor/file-history-panel.tsxnew file mode 100644index 00000000..b6c1cfcb--- /dev/null+++ b/src/components/editor/file-history-panel.tsx@@ -0,0 +1,53 @@+import { useState } from "react"+import { Clock3, RotateCcw, X } from "lucide-react"+import { listFileHistory, restoreFileHistory, type FileHistoryEntry } from "@/commands/fs"+import { summarizeAgentFileChange } from "@/lib/agent-file-activity"+import { useWikiStore } from "@/stores/wiki-store"++export function FileHistoryButton({ filePath, currentContent }: { filePath: string; currentContent: string }) {+ const project = useWikiStore((state) => state.project)+ const openFileInPreview = useWikiStore((state) => state.openFileInPreview)+ const [open, setOpen] = useState(false)+ const [entries, setEntries] = useState<FileHistoryEntry[]>([])+ const [selected, setSelected] = useState<FileHistoryEntry | null>(null)+ const [loading, setLoading] = useState(false)+ if (!project) return null++ const show = async () => {+ setOpen(true)+ setLoading(true)+ try {+ setEntries(await listFileHistory(project.path, filePath))+ } finally {+ setLoading(false)+ }+ }+ const diff = selected ? summarizeAgentFileChange({+ id: selected.id, path: filePath, tool: selected.tool,+ beforeContent: selected.content, afterContent: currentContent,+ }).diff : ""++ return <>+ <button type="button" onClick={() => void show()} className="absolute right-3 top-3 z-20 rounded-md border bg-background/90 p-1.5 text-muted-foreground shadow-sm hover:text-foreground" title="File history"><Clock3 className="h-4 w-4" /></button>+ {open && <div className="absolute inset-0 z-40 flex bg-background">+ <aside className="w-72 shrink-0 border-r p-3">+ <div className="mb-3 flex items-center justify-between"><strong className="text-sm">File history</strong><button type="button" onClick={() => setOpen(false)}><X className="h-4 w-4" /></button></div>+ <div className="space-y-1 overflow-auto">+ {loading && <p className="text-xs text-muted-foreground">Loading...</p>}+ {!loading && entries.length === 0 && <p className="text-xs text-muted-foreground">No recorded versions yet.</p>}+ {entries.map((entry) => <button key={entry.id} type="button" onClick={() => setSelected(entry)} className={`w-full rounded border px-2 py-2 text-left text-xs ${selected?.id === entry.id ? "border-primary bg-primary/5" : "border-transparent hover:bg-muted"}`}>+ <div className="font-medium">{entry.author} · {entry.tool}</div>+ <div className="mt-1 text-[10px] text-muted-foreground">{new Date(entry.timestamp).toLocaleString()}</div>+ </button>)}+ </div>+ </aside>+ <main className="min-w-0 flex-1 overflow-auto p-4">+ {selected ? <><div className="mb-3 flex justify-end"><button type="button" className="inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs hover:bg-muted" onClick={async () => {+ const content = await restoreFileHistory(project.path, filePath, selected.id)+ openFileInPreview(filePath, content)+ setOpen(false)+ }}><RotateCcw className="h-3.5 w-3.5" />Restore this version</button></div><pre className="whitespace-pre-wrap break-words rounded-md bg-muted/40 p-3 font-mono text-xs">{diff}</pre></> : <div className="grid h-full place-items-center text-sm text-muted-foreground">Select a version to compare.</div>}+ </main>+ </div>}+ </>+}diff --git a/src/components/editor/file-preview.tsx b/src/components/editor/file-preview.tsxindex 48116131..8b3ada24 100644--- a/src/components/editor/file-preview.tsx+++ b/src/components/editor/file-preview.tsx@@ -34,6 +34,7 @@ import { parseFrontmatter } from "@/lib/frontmatter"import { FrontmatterPanel } from "@/components/editor/frontmatter-panel"import { useWikiStore } from "@/stores/wiki-store"import { MermaidDiagram, unwrapMermaidPre } from "@/components/mermaid-diagram"+import { FileHistoryButton } from "@/components/editor/file-history-panel"interface FilePreviewProps {filePath: string@@ -41,6 +42,13 @@ interface FilePreviewProps {}export function FilePreview({ filePath, textContent }: FilePreviewProps) {+ return <div className="relative h-full min-h-0">+ <FilePreviewContent filePath={filePath} textContent={textContent} />+ <FileHistoryButton filePath={filePath} currentContent={textContent} />+ </div>+}++function FilePreviewContent({ filePath, textContent }: FilePreviewProps) {const category = getFileCategory(filePath)const fileName = getFileName(filePath)const extension = getFileExtension(filePath)