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

feat: make file history opt-in and bounded

nash_sud81949fca34b
diff --git a/src-tauri/src/agent/tools.rs b/src-tauri/src/agent/tools.rs
index 202b3e19..f4e31d52 100644
--- a/src-tauri/src/agent/tools.rs
+++ b/src-tauri/src/agent/tools.rs
@@ -2828,6 +2828,11 @@ mod tests {
let root = std::env::temp_dir().join(format!("llm-wiki-context-{}", Uuid::new_v4()));
fs::create_dir_all(root.join(".llm-wiki")).unwrap();
fs::create_dir_all(root.join("wiki/entities")).unwrap();
+ fs::write(
+ root.join(".llm-wiki/history-settings.json"),
+ r#"{"enabled":true,"maxVersionsPerFile":10}"#,
+ )
+ .unwrap();
let alpha = root.join("wiki/entities/alpha.md");
let beta = root.join("wiki/entities/beta.md");
fs::write(
diff --git a/src-tauri/src/commands/file_history.rs b/src-tauri/src/commands/file_history.rs
index 44a910b1..6e86b125 100644
--- a/src-tauri/src/commands/file_history.rs
+++ b/src-tauri/src/commands/file_history.rs
@@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;
const MAX_HISTORY_CONTENT_BYTES: usize = 512 * 1024;
+const DEFAULT_ENTRIES_PER_FILE: usize = 10;
const MAX_ENTRIES_PER_FILE: usize = 30;
const MAX_HISTORY_STORE_BYTES: u64 = 128 * 1024 * 1024;
const MAX_HISTORY_STORE_FILES: usize = 2_048;
@@ -31,6 +32,54 @@ pub struct FileHistoryStats {
pub entries: usize,
}
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase", default)]
+pub struct FileHistorySettings {
+ pub enabled: bool,
+ pub max_versions_per_file: usize,
+}
+
+impl Default for FileHistorySettings {
+ fn default() -> Self {
+ Self {
+ enabled: false,
+ max_versions_per_file: DEFAULT_ENTRIES_PER_FILE,
+ }
+ }
+}
+
+impl FileHistorySettings {
+ fn normalized(mut self) -> Self {
+ self.max_versions_per_file = self.max_versions_per_file.min(MAX_ENTRIES_PER_FILE);
+ self
+ }
+}
+
+fn history_settings_path(root: &Path) -> PathBuf {
+ root.join(".llm-wiki/history-settings.json")
+}
+
+fn validate_optional_regular_file(path: &Path, label: &str) -> Result<(), String> {
+ match fs::symlink_metadata(path) {
+ Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => Ok(()),
+ Ok(_) => Err(format!("{label} must be a regular file, not a symlink")),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(error.to_string()),
+ }
+}
+
+fn read_history_settings(root: &Path) -> FileHistorySettings {
+ let path = history_settings_path(root);
+ if validate_optional_regular_file(&path, "History settings").is_err() {
+ return FileHistorySettings::default();
+ }
+ fs::read_to_string(path)
+ .ok()
+ .and_then(|raw| serde_json::from_str::<FileHistorySettings>(&raw).ok())
+ .unwrap_or_default()
+ .normalized()
+}
+
/// Return provenance only, never historical content, for Agent retrieval
/// briefings. Reading the same bounded store as the timeline keeps attribution
/// consistent without expanding prompt size or exposing rollback snapshots.
@@ -38,7 +87,8 @@ pub fn latest_file_version(path: &Path) -> Option<(i64, String, String)> {
let root = project_root_for(path)?;
let _guard = HISTORY_LOCK.lock().ok()?;
checked_history_dir(&root, false).ok()?;
- let raw = fs::read_to_string(history_path(&root, path)).ok()?;
+ let store_path = checked_history_file(&root, path).ok()?;
+ let raw = fs::read_to_string(store_path).ok()?;
let entries: Vec<FileHistoryEntry> = serde_json::from_str(&raw).ok()?;
entries
.last()
@@ -48,7 +98,10 @@ pub fn latest_file_version(path: &Path) -> Option<(i64, String, 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() {
+ let metadata_dir = dir.join(".llm-wiki");
+ if fs::symlink_metadata(&metadata_dir)
+ .is_ok_and(|metadata| metadata.is_dir() && !metadata.file_type().is_symlink())
+ {
return Some(dir.to_path_buf());
}
cursor = dir.parent();
@@ -72,6 +125,12 @@ fn history_dir(root: &Path) -> PathBuf {
root.join(".llm-wiki/history")
}
+fn checked_history_file(root: &Path, path: &Path) -> Result<PathBuf, String> {
+ let store_path = history_path(root, path);
+ validate_optional_regular_file(&store_path, "History file")?;
+ Ok(store_path)
+}
+
fn checked_history_dir(root: &Path, create: bool) -> Result<PathBuf, String> {
let canonical_root = root.canonicalize().map_err(|e| e.to_string())?;
let metadata_dir = canonical_root.join(".llm-wiki");
@@ -104,6 +163,10 @@ fn history_files_oldest_first(root: &Path) -> Vec<(PathBuf, u64, std::time::Syst
let mut files: Vec<_> = entries
.flatten()
.filter_map(|entry| {
+ let file_type = entry.file_type().ok()?;
+ if !file_type.is_file() || file_type.is_symlink() {
+ return None;
+ }
let metadata = entry.metadata().ok()?;
if !metadata.is_file()
|| entry.path().extension().and_then(|ext| ext.to_str()) != Some("json")
@@ -141,29 +204,63 @@ fn prune_history_store(root: &Path, protected_path: &Path) {
}
}
+fn prune_entries_per_file(root: &Path, max_versions: usize) -> Result<(), String> {
+ let dir = checked_history_dir(root, false)?;
+ if !dir.exists() {
+ return Ok(());
+ }
+ if max_versions == 0 {
+ fs::remove_dir_all(&dir).map_err(|e| e.to_string())?;
+ return Ok(());
+ }
+ for (path, _, _) in history_files_oldest_first(root) {
+ let raw = match fs::read_to_string(&path) {
+ Ok(raw) => raw,
+ Err(_) => continue,
+ };
+ let mut entries: Vec<FileHistoryEntry> = match serde_json::from_str(&raw) {
+ Ok(entries) => entries,
+ Err(_) => continue,
+ };
+ if entries.len() > max_versions {
+ entries.drain(..entries.len() - max_versions);
+ let serialized = serde_json::to_string(&entries).map_err(|e| e.to_string())?;
+ fs::write(&path, serialized).map_err(|e| e.to_string())?;
+ }
+ }
+ Ok(())
+}
+
pub fn record_file_version(path: &Path, author: &str, tool: &str) {
- let Ok(metadata) = fs::metadata(path) else {
+ let Some(root) = project_root_for(path) else {
return;
};
- if !metadata.is_file() || metadata.len() as usize > MAX_HISTORY_CONTENT_BYTES {
+ if path.starts_with(root.join(".llm-wiki")) {
return;
}
- let Ok(content) = fs::read_to_string(path) else {
+ let Ok(_guard) = HISTORY_LOCK.lock() else {
return;
};
- let Some(root) = project_root_for(path) else {
+ let settings = read_history_settings(&root);
+ if !settings.enabled || settings.max_versions_per_file == 0 {
+ return;
+ }
+ let Ok(metadata) = fs::metadata(path) else {
return;
};
- if path.starts_with(root.join(".llm-wiki")) {
+ if !metadata.is_file() || metadata.len() as usize > MAX_HISTORY_CONTENT_BYTES {
return;
}
- let Ok(_guard) = HISTORY_LOCK.lock() else {
+ let Ok(content) = fs::read_to_string(path) else {
return;
};
let Ok(dir) = checked_history_dir(&root, true) else {
return;
};
- let Some(file_name) = history_path(&root, path).file_name().map(ToOwned::to_owned) else {
+ let Ok(checked_store_path) = checked_history_file(&root, path) else {
+ return;
+ };
+ let Some(file_name) = checked_store_path.file_name().map(ToOwned::to_owned) else {
return;
};
let store_path = dir.join(file_name);
@@ -182,8 +279,8 @@ pub fn record_file_version(path: &Path, author: &str, tool: &str) {
tool: tool.to_string(),
content,
});
- if entries.len() > MAX_ENTRIES_PER_FILE {
- entries.drain(..entries.len() - MAX_ENTRIES_PER_FILE);
+ if entries.len() > settings.max_versions_per_file {
+ entries.drain(..entries.len() - settings.max_versions_per_file);
}
if let Ok(raw) = serde_json::to_string(&entries) {
if fs::write(&store_path, raw).is_ok() {
@@ -192,11 +289,56 @@ pub fn record_file_version(path: &Path, author: &str, tool: &str) {
}
}
+#[tauri::command]
+pub async fn get_file_history_settings(
+ project_path: String,
+) -> Result<FileHistorySettings, String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ let root = checked_project_root(&project_path)?;
+ Ok(read_history_settings(&root))
+ })
+ .await
+ .map_err(|e| e.to_string())?
+}
+
+#[tauri::command]
+pub async fn set_file_history_settings(
+ project_path: String,
+ settings: FileHistorySettings,
+) -> Result<FileHistorySettings, String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ let root = checked_project_root(&project_path)?;
+ let mut settings = settings.normalized();
+ if settings.enabled && settings.max_versions_per_file == 0 {
+ settings.max_versions_per_file = DEFAULT_ENTRIES_PER_FILE;
+ }
+ let _guard = HISTORY_LOCK.lock().map_err(|e| e.to_string())?;
+ let previous = read_history_settings(&root);
+ let settings_path = history_settings_path(&root);
+ let had_settings = validate_optional_regular_file(&settings_path, "History settings")
+ .is_ok()
+ && fs::read_to_string(&settings_path)
+ .ok()
+ .and_then(|raw| serde_json::from_str::<FileHistorySettings>(&raw).ok())
+ .is_some();
+ let raw = serde_json::to_string_pretty(&settings).map_err(|e| e.to_string())?;
+ validate_optional_regular_file(&settings_path, "History settings")?;
+ fs::write(settings_path, raw).map_err(|e| e.to_string())?;
+ if !had_settings || settings.max_versions_per_file < previous.max_versions_per_file {
+ prune_entries_per_file(&root, settings.max_versions_per_file)?;
+ }
+ Ok(settings)
+ })
+ .await
+ .map_err(|e| e.to_string())?
+}
+
fn checked_project_root(project_path: &str) -> Result<PathBuf, String> {
let root = Path::new(project_path)
.canonicalize()
.map_err(|e| e.to_string())?;
- if !root.join(".llm-wiki").is_dir() {
+ let metadata = fs::symlink_metadata(root.join(".llm-wiki")).map_err(|e| e.to_string())?;
+ if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err("History project must contain .llm-wiki".to_string());
}
Ok(root)
@@ -224,8 +366,8 @@ pub async fn list_file_history(
let (root, file) = checked_file(&project_path, &file_path)?;
let _guard = HISTORY_LOCK.lock().map_err(|e| e.to_string())?;
checked_history_dir(&root, false)?;
- let raw =
- fs::read_to_string(history_path(&root, &file)).unwrap_or_else(|_| "[]".to_string());
+ let store_path = checked_history_file(&root, &file)?;
+ let raw = fs::read_to_string(store_path).unwrap_or_else(|_| "[]".to_string());
let mut entries: Vec<FileHistoryEntry> = serde_json::from_str(&raw).unwrap_or_default();
entries.reverse();
Ok(entries)
@@ -245,17 +387,46 @@ pub async fn restore_file_history(
let content = {
let _guard = HISTORY_LOCK.lock().map_err(|e| e.to_string())?;
checked_history_dir(&root, false)?;
- let raw = fs::read_to_string(history_path(&root, &file)).map_err(|e| e.to_string())?;
- let entries: Vec<FileHistoryEntry> =
+ let store_path = checked_history_file(&root, &file)?;
+ let raw = fs::read_to_string(&store_path).map_err(|e| e.to_string())?;
+ let mut entries: Vec<FileHistoryEntry> =
serde_json::from_str(&raw).map_err(|e| e.to_string())?;
let entry = entries
- .into_iter()
+ .iter()
.find(|entry| entry.id == entry_id)
+ .cloned()
.ok_or_else(|| "History entry not found".to_string())?;
+ let current = fs::read_to_string(&file).map_err(|e| e.to_string())?;
+ if current.len() > MAX_HISTORY_CONTENT_BYTES {
+ return Err(format!(
+ "Current file is too large to back up safely before restore (maximum {} bytes)",
+ MAX_HISTORY_CONTENT_BYTES
+ ));
+ }
+ if current != entry.content
+ && !entries
+ .last()
+ .is_some_and(|existing| existing.content == current)
+ {
+ entries.push(FileHistoryEntry {
+ id: Uuid::new_v4().to_string(),
+ path: file.to_string_lossy().replace('\\', "/"),
+ timestamp: Utc::now().timestamp_millis(),
+ author: "human".to_string(),
+ tool: "before.history.restore".to_string(),
+ content: current,
+ });
+ let retention = read_history_settings(&root).max_versions_per_file.max(1);
+ if entries.len() > retention {
+ entries.drain(..entries.len() - retention);
+ }
+ let updated = serde_json::to_string(&entries).map_err(|e| e.to_string())?;
+ fs::write(&store_path, updated).map_err(|e| e.to_string())?;
+ prune_history_store(&root, &store_path);
+ }
fs::write(&file, &entry.content).map_err(|e| e.to_string())?;
entry.content
};
- record_file_version(&file, "human", "history.restore");
Ok(content)
})
.await
@@ -304,11 +475,38 @@ pub async fn clear_file_history(project_path: String) -> Result<(), String> {
mod tests {
use super::*;
+ fn enable_history(root: &Path, max_versions_per_file: usize) {
+ let settings = FileHistorySettings {
+ enabled: true,
+ max_versions_per_file,
+ };
+ fs::write(
+ history_settings_path(root),
+ serde_json::to_string(&settings).unwrap(),
+ )
+ .unwrap();
+ }
+
+ #[test]
+ fn history_is_disabled_by_default() {
+ 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, "current").unwrap();
+
+ record_file_version(&file, "agent", "test.write");
+
+ assert!(!history_dir(&root).exists());
+ let _ = fs::remove_dir_all(root);
+ }
+
#[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();
+ enable_history(&root, 10);
let file = root.join("wiki/page.md");
fs::write(&file, "before").unwrap();
record_file_version(&file, "baseline", "before.test");
@@ -340,7 +538,8 @@ mod tests {
)
.await
.unwrap();
- assert_eq!(restored.first().unwrap().tool, "history.restore");
+ assert_eq!(restored.first().unwrap().content, "after");
+ assert_eq!(restored.first().unwrap().tool, "test.write");
let _ = fs::remove_dir_all(root);
}
@@ -349,6 +548,7 @@ mod tests {
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();
+ enable_history(&root, 10);
let file = root.join("wiki/page.md");
fs::write(&file, "current").unwrap();
record_file_version(&file, "agent", "test.write");
@@ -383,6 +583,7 @@ mod tests {
std::env::temp_dir().join(format!("llm-wiki-history-outside-{}", Uuid::new_v4()));
fs::create_dir_all(root.join(".llm-wiki")).unwrap();
fs::create_dir_all(root.join("wiki")).unwrap();
+ enable_history(&root, 10);
fs::create_dir_all(&outside).unwrap();
symlink(&outside, root.join(".llm-wiki/history")).unwrap();
let file = root.join("wiki/page.md");
@@ -394,4 +595,286 @@ mod tests {
let _ = fs::remove_dir_all(root);
let _ = fs::remove_dir_all(outside);
}
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn refuses_metadata_directory_symlink_escape_for_settings() {
+ use std::os::unix::fs::symlink;
+
+ let root = std::env::temp_dir().join(format!("llm-wiki-history-{}", Uuid::new_v4()));
+ let outside =
+ std::env::temp_dir().join(format!("llm-wiki-history-outside-{}", Uuid::new_v4()));
+ fs::create_dir_all(&root).unwrap();
+ fs::create_dir_all(&outside).unwrap();
+ symlink(&outside, root.join(".llm-wiki")).unwrap();
+
+ let result = set_file_history_settings(
+ root.to_string_lossy().into_owned(),
+ FileHistorySettings {
+ enabled: true,
+ max_versions_per_file: 10,
+ },
+ )
+ .await;
+
+ assert!(result.is_err());
+ assert!(!outside.join("history-settings.json").exists());
+ let _ = fs::remove_dir_all(root);
+ let _ = fs::remove_dir_all(outside);
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn refuses_symlinked_settings_and_history_files() {
+ use std::os::unix::fs::symlink;
+
+ let root = std::env::temp_dir().join(format!("llm-wiki-history-{}", Uuid::new_v4()));
+ let outside =
+ std::env::temp_dir().join(format!("llm-wiki-history-outside-{}", Uuid::new_v4()));
+ fs::create_dir_all(root.join(".llm-wiki/history")).unwrap();
+ fs::create_dir_all(root.join("wiki")).unwrap();
+ fs::create_dir_all(&outside).unwrap();
+ let outside_settings = outside.join("settings.json");
+ fs::write(&outside_settings, "untouched settings").unwrap();
+ symlink(&outside_settings, history_settings_path(&root)).unwrap();
+
+ let settings_result = set_file_history_settings(
+ root.to_string_lossy().into_owned(),
+ FileHistorySettings {
+ enabled: true,
+ max_versions_per_file: 10,
+ },
+ )
+ .await;
+ assert!(settings_result.is_err());
+ assert_eq!(
+ fs::read_to_string(&outside_settings).unwrap(),
+ "untouched settings"
+ );
+
+ fs::remove_file(history_settings_path(&root)).unwrap();
+ enable_history(&root, 10);
+ let file = root.join("wiki/page.md");
+ fs::write(&file, "current").unwrap();
+ let outside_history = outside.join("history.json");
+ fs::write(&outside_history, "untouched history").unwrap();
+ symlink(&outside_history, history_path(&root, &file)).unwrap();
+
+ record_file_version(&file, "agent", "test.write");
+ let list_result = list_file_history(
+ root.to_string_lossy().into_owned(),
+ file.to_string_lossy().into_owned(),
+ )
+ .await;
+ assert!(list_result.is_err());
+ assert_eq!(
+ fs::read_to_string(&outside_history).unwrap(),
+ "untouched history"
+ );
+ let _ = fs::remove_dir_all(root);
+ let _ = fs::remove_dir_all(outside);
+ }
+
+ #[tokio::test]
+ async fn settings_clamp_and_prune_existing_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();
+ enable_history(&root, 10);
+ let file = root.join("wiki/page.md");
+ for version in 0..5 {
+ fs::write(&file, format!("version {version}")).unwrap();
+ record_file_version(&file, "agent", "test.write");
+ }
+
+ let saved = set_file_history_settings(
+ root.to_string_lossy().into_owned(),
+ FileHistorySettings {
+ enabled: true,
+ max_versions_per_file: 2,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(saved.max_versions_per_file, 2);
+ let entries = list_file_history(
+ root.to_string_lossy().into_owned(),
+ file.to_string_lossy().into_owned(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(entries.len(), 2);
+ assert_eq!(entries[0].content, "version 4");
+
+ fs::write(history_dir(&root).join("corrupt.json"), "not json").unwrap();
+
+ set_file_history_settings(
+ root.to_string_lossy().into_owned(),
+ FileHistorySettings {
+ enabled: false,
+ max_versions_per_file: 0,
+ },
+ )
+ .await
+ .unwrap();
+ assert!(!history_path(&root, &file).exists());
+ assert!(!history_dir(&root).join("corrupt.json").exists());
+ let _ = fs::remove_dir_all(root);
+ }
+
+ #[tokio::test]
+ async fn disabled_history_preserves_entries_and_restore_backs_up_current_content() {
+ 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();
+ enable_history(&root, 10);
+ let file = root.join("wiki/page.md");
+ fs::write(&file, "old").unwrap();
+ record_file_version(&file, "agent", "test.write");
+ let old = list_file_history(
+ root.to_string_lossy().into_owned(),
+ file.to_string_lossy().into_owned(),
+ )
+ .await
+ .unwrap()
+ .remove(0);
+ set_file_history_settings(
+ root.to_string_lossy().into_owned(),
+ FileHistorySettings {
+ enabled: false,
+ max_versions_per_file: 10,
+ },
+ )
+ .await
+ .unwrap();
+ fs::write(&file, "unsnapshotted current content").unwrap();
+ record_file_version(&file, "agent", "ignored.while.disabled");
+
+ restore_file_history(
+ root.to_string_lossy().into_owned(),
+ file.to_string_lossy().into_owned(),
+ old.id,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(fs::read_to_string(&file).unwrap(), "old");
+ let entries = list_file_history(
+ root.to_string_lossy().into_owned(),
+ file.to_string_lossy().into_owned(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(entries.len(), 2);
+ assert_eq!(entries[0].content, "unsnapshotted current content");
+ assert_eq!(entries[0].tool, "before.history.restore");
+ let _ = fs::remove_dir_all(root);
+ }
+
+ #[tokio::test]
+ async fn restore_refuses_when_current_content_is_too_large_to_back_up() {
+ 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();
+ enable_history(&root, 10);
+ let file = root.join("wiki/page.md");
+ fs::write(&file, "old").unwrap();
+ record_file_version(&file, "agent", "test.write");
+ let old = list_file_history(
+ root.to_string_lossy().into_owned(),
+ file.to_string_lossy().into_owned(),
+ )
+ .await
+ .unwrap()
+ .remove(0);
+ let oversized = "x".repeat(MAX_HISTORY_CONTENT_BYTES + 1);
+ fs::write(&file, &oversized).unwrap();
+
+ let result = restore_file_history(
+ root.to_string_lossy().into_owned(),
+ file.to_string_lossy().into_owned(),
+ old.id,
+ )
+ .await;
+
+ assert!(result.is_err());
+ assert_eq!(fs::read_to_string(&file).unwrap(), oversized);
+ let _ = fs::remove_dir_all(root);
+ }
+
+ #[tokio::test]
+ async fn settings_clamp_to_thirty_and_recording_honors_custom_limit() {
+ 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 saved = set_file_history_settings(
+ root.to_string_lossy().into_owned(),
+ FileHistorySettings {
+ enabled: true,
+ max_versions_per_file: 100,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(saved.max_versions_per_file, 30);
+
+ set_file_history_settings(
+ root.to_string_lossy().into_owned(),
+ FileHistorySettings {
+ enabled: true,
+ max_versions_per_file: 2,
+ },
+ )
+ .await
+ .unwrap();
+ let file = root.join("wiki/page.md");
+ for version in 0..4 {
+ fs::write(&file, format!("version {version}")).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);
+ assert_eq!(entries[0].content, "version 3");
+ assert_eq!(entries[1].content, "version 2");
+ let _ = fs::remove_dir_all(root);
+ }
+
+ #[tokio::test]
+ async fn first_settings_save_prunes_legacy_history_to_default_limit() {
+ 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();
+ enable_history(&root, 30);
+ let file = root.join("wiki/page.md");
+ for version in 0..15 {
+ fs::write(&file, format!("version {version}")).unwrap();
+ record_file_version(&file, "agent", "test.write");
+ }
+ fs::remove_file(history_settings_path(&root)).unwrap();
+
+ set_file_history_settings(
+ root.to_string_lossy().into_owned(),
+ FileHistorySettings {
+ enabled: true,
+ max_versions_per_file: 10,
+ },
+ )
+ .await
+ .unwrap();
+
+ let entries = list_file_history(
+ root.to_string_lossy().into_owned(),
+ file.to_string_lossy().into_owned(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(entries.len(), 10);
+ assert_eq!(entries[0].content, "version 14");
+ let _ = fs::remove_dir_all(root);
+ }
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 72e059f9..63720471 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -627,6 +627,8 @@ pub fn run() {
commands::file_history::list_file_history,
commands::file_history::restore_file_history,
commands::file_history::get_file_history_stats,
+ commands::file_history::get_file_history_settings,
+ commands::file_history::set_file_history_settings,
commands::file_history::clear_file_history,
commands::fs::list_directory,
commands::fs::copy_file,
diff --git a/src/commands/fs.ts b/src/commands/fs.ts
index f35c1c2f..a0e4b9f5 100644
--- a/src/commands/fs.ts
+++ b/src/commands/fs.ts
@@ -156,6 +156,22 @@ export interface FileHistoryStats {
entries: number
}
+export interface FileHistorySettings {
+ enabled: boolean
+ maxVersionsPerFile: number
+}
+
+export async function getFileHistorySettings(projectPath: string): Promise<FileHistorySettings> {
+ return invoke<FileHistorySettings>("get_file_history_settings", { projectPath })
+}
+
+export async function setFileHistorySettings(
+ projectPath: string,
+ settings: FileHistorySettings,
+): Promise<FileHistorySettings> {
+ return invoke<FileHistorySettings>("set_file_history_settings", { projectPath, settings })
+}
+
export async function getFileHistoryStats(projectPath: string): Promise<FileHistoryStats> {
return invoke<FileHistoryStats>("get_file_history_stats", { projectPath })
}
diff --git a/src/components/settings/sections/maintenance-section.tsx b/src/components/settings/sections/maintenance-section.tsx
index ea95a86e..95c0935a 100644
--- a/src/components/settings/sections/maintenance-section.tsx
+++ b/src/components/settings/sections/maintenance-section.tsx
@@ -34,8 +34,11 @@ import type { DuplicateGroup } from "@/lib/dedup"
import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"
import {
clearFileHistory,
+ getFileHistorySettings,
getFileHistoryStats,
openProject,
+ setFileHistorySettings,
+ type FileHistorySettings,
type FileHistoryStats,
} from "@/commands/fs"
import { addToRecentProjects } from "@/lib/project-store"
@@ -69,6 +72,7 @@ export function MaintenanceSection() {
const [projectToolStatus, setProjectToolStatus] = useState<string | null>(null)
const [projectToolBusy, setProjectToolBusy] = useState(false)
const [historyStats, setHistoryStats] = useState<FileHistoryStats | null>(null)
+ const [historySettings, setHistorySettingsState] = useState<FileHistorySettings | null>(null)
const [historyBusy, setHistoryBusy] = useState(false)
const [historyError, setHistoryError] = useState<string | null>(null)
@@ -77,10 +81,15 @@ export function MaintenanceSection() {
setHistoryStats(null)
return
}
+ const projectPath = project.path
try {
setHistoryError(null)
- setHistoryStats(await getFileHistoryStats(project.path))
+ const stats = await getFileHistoryStats(projectPath)
+ if (useWikiStore.getState().project?.path === projectPath) {
+ setHistoryStats(stats)
+ }
} catch (error) {
+ if (useWikiStore.getState().project?.path !== projectPath) return
console.warn("[Maintenance] failed to load file history stats:", error)
setHistoryError(String(error))
setHistoryStats(null)
@@ -91,19 +100,91 @@ export function MaintenanceSection() {
void refreshHistoryStats()
}, [refreshHistoryStats])
+ useEffect(() => {
+ let active = true
+ setHistorySettingsState(null)
+ setHistoryBusy(false)
+ setHistoryError(null)
+ if (!project) return () => { active = false }
+ void getFileHistorySettings(project.path)
+ .then((settings) => {
+ if (active) setHistorySettingsState(settings)
+ })
+ .catch((error) => {
+ if (active) setHistoryError(String(error))
+ })
+ return () => { active = false }
+ }, [project])
+
+ const updateHistorySettings = useCallback(async (next: FileHistorySettings) => {
+ if (!project) return
+ const projectPath = project.path
+ setHistoryBusy(true)
+ try {
+ setHistoryError(null)
+ const saved = await setFileHistorySettings(projectPath, next)
+ if (useWikiStore.getState().project?.path !== projectPath) return
+ setHistorySettingsState(saved)
+ setHistoryStats(await getFileHistoryStats(projectPath))
+ } catch (error) {
+ if (useWikiStore.getState().project?.path !== projectPath) return
+ setHistoryError(String(error))
+ try {
+ setHistorySettingsState(await getFileHistorySettings(projectPath))
+ } catch {
+ // Keep the original settings error visible.
+ }
+ } finally {
+ if (useWikiStore.getState().project?.path === projectPath) {
+ setHistoryBusy(false)
+ }
+ }
+ }, [project])
+
+ const commitHistoryRetention = useCallback(async (value: number) => {
+ if (!historySettings) return
+ if (value === 0 && !window.confirm(t("settings.sections.maintenance.history.zeroConfirm"))) {
+ if (project) {
+ const projectPath = project.path
+ try {
+ const settings = await getFileHistorySettings(projectPath)
+ if (useWikiStore.getState().project?.path === projectPath) {
+ setHistorySettingsState(settings)
+ }
+ } catch (error) {
+ if (useWikiStore.getState().project?.path === projectPath) {
+ setHistoryError(String(error))
+ }
+ }
+ }
+ return
+ }
+ await updateHistorySettings({
+ ...historySettings,
+ enabled: value === 0 ? false : historySettings.enabled,
+ maxVersionsPerFile: value,
+ })
+ }, [historySettings, project, t, updateHistorySettings])
+
const handleClearHistory = useCallback(async () => {
if (!project || !window.confirm(t("settings.sections.maintenance.history.confirm"))) return
+ const projectPath = project.path
setHistoryBusy(true)
try {
setHistoryError(null)
- await clearFileHistory(project.path)
- await refreshHistoryStats()
+ await clearFileHistory(projectPath)
+ if (useWikiStore.getState().project?.path !== projectPath) return
+ setHistoryStats(await getFileHistoryStats(projectPath))
} catch (error) {
- setHistoryError(String(error))
+ if (useWikiStore.getState().project?.path === projectPath) {
+ setHistoryError(String(error))
+ }
} finally {
- setHistoryBusy(false)
+ if (useWikiStore.getState().project?.path === projectPath) {
+ setHistoryBusy(false)
+ }
}
- }, [project, refreshHistoryStats, t])
+ }, [project, t])
const handleRebuildIndex = useCallback(async () => {
if (!project) return
@@ -329,6 +410,69 @@ export function MaintenanceSection() {
<p className="text-xs text-muted-foreground">
{t("settings.sections.maintenance.history.description")}
</p>
+ {historySettings && (
+ <div className="space-y-3 rounded-md border border-border/60 bg-background/60 p-3">
+ <div className="flex items-center justify-between gap-4">
+ <div>
+ <Label htmlFor="file-history-enabled">
+ {t("settings.sections.maintenance.history.enabled")}
+ </Label>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {t("settings.sections.maintenance.history.enabledHint")}
+ </p>
+ </div>
+ <button
+ id="file-history-enabled"
+ type="button"
+ role="switch"
+ aria-checked={historySettings.enabled}
+ disabled={!project || historyBusy}
+ onClick={() => void updateHistorySettings({
+ ...historySettings,
+ enabled: !historySettings.enabled,
+ })}
+ className={`relative h-6 w-11 shrink-0 rounded-full border transition-colors disabled:opacity-50 ${historySettings.enabled ? "border-primary bg-primary" : "border-border bg-muted"}`}
+ >
+ <span className={`absolute top-0.5 h-[18px] w-[18px] rounded-full bg-background shadow-sm transition-transform ${historySettings.enabled ? "left-[22px]" : "left-0.5"}`} />
+ </button>
+ </div>
+ <div className="space-y-2">
+ <div className="flex items-center justify-between gap-3">
+ <Label htmlFor="file-history-retention">
+ {t("settings.sections.maintenance.history.retention")}
+ </Label>
+ <span className="text-xs font-medium tabular-nums">
+ {t("settings.sections.maintenance.history.retentionValue", {
+ count: historySettings.maxVersionsPerFile,
+ })}
+ </span>
+ </div>
+ <input
+ id="file-history-retention"
+ type="range"
+ min={0}
+ max={30}
+ step={1}
+ value={historySettings.maxVersionsPerFile}
+ disabled={!project || historyBusy}
+ onChange={(event) => setHistorySettingsState({
+ ...historySettings,
+ maxVersionsPerFile: Number(event.target.value),
+ })}
+ onPointerUp={(event) => void commitHistoryRetention(Number(event.currentTarget.value))}
+ onKeyUp={(event) => {
+ if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) {
+ void commitHistoryRetention(Number(event.currentTarget.value))
+ }
+ }}
+ className="h-2 w-full cursor-pointer appearance-none rounded-lg bg-muted accent-primary disabled:cursor-not-allowed disabled:opacity-50"
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.maintenance.history.retentionHint")}
+ </p>
+ </div>
+ </div>
+ )}
{historyStats && (
<p className="text-xs text-muted-foreground">
{t("settings.sections.maintenance.history.usage", {
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 6e2a5de4..b1b2e549 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -872,7 +872,13 @@
},
"history": {
"title": "File version history",
- "description": "Rollback snapshots are stored in .llm-wiki/history. Current files are not stored here. The app automatically retains at most 30 versions per file and bounds total project history size.",
+ "description": "Optional rollback snapshots are stored in .llm-wiki/history. Current files are not stored here.",
+ "enabled": "Record file version history",
+ "enabledHint": "Disabled by default. Turning it off stops new snapshots without deleting existing history.",
+ "retention": "Versions retained per file",
+ "retentionValue": "{{count}} / 30",
+ "retentionHint": "Choose 0–30 versions. Setting this to 0 removes existing snapshots; the default is 10 when history is enabled.",
+ "zeroConfirm": "Set retained versions to 0 and delete all existing rollback snapshots? Current project files will not be deleted.",
"usage": "{{size}} across {{files}} history files ({{entries}} versions)",
"clear": "Clear version history",
"confirm": "Clear all rollback snapshots for this project? Current project files will not be deleted."
diff --git a/src/i18n/it.json b/src/i18n/it.json
index 113dedbd..17cee631 100644
--- a/src/i18n/it.json
+++ b/src/i18n/it.json
@@ -872,7 +872,13 @@
},
"history": {
"title": "Cronologia delle versioni dei file",
- "description": "Gli snapshot di rollback sono salvati in .llm-wiki/history. I file attuali non vengono conservati qui. L'app mantiene automaticamente al massimo 30 versioni per file e limita la dimensione totale della cronologia del progetto.",
+ "description": "Gli snapshot di rollback opzionali sono salvati in .llm-wiki/history. I file attuali non vengono conservati qui.",
+ "enabled": "Registra la cronologia versioni",
+ "enabledHint": "Disattivata per impostazione predefinita. Disattivarla interrompe i nuovi snapshot senza eliminare quelli esistenti.",
+ "retention": "Versioni conservate per file",
+ "retentionValue": "{{count}} / 30",
+ "retentionHint": "Scegli da 0 a 30 versioni. Impostando 0 si eliminano gli snapshot esistenti; quando la cronologia è attiva il valore predefinito è 10.",
+ "zeroConfirm": "Impostare le versioni conservate a 0 ed eliminare tutti gli snapshot esistenti? I file attuali del progetto non verranno eliminati.",
"usage": "{{size}} in {{files}} file di cronologia ({{entries}} versioni)",
"clear": "Cancella la cronologia delle versioni",
"confirm": "Cancellare tutti gli snapshot di rollback di questo progetto? I file attuali del progetto non verranno eliminati."
diff --git a/src/i18n/ru.json b/src/i18n/ru.json
index 5d908c04..ea20068d 100644
--- a/src/i18n/ru.json
+++ b/src/i18n/ru.json
@@ -872,7 +872,13 @@
},
"history": {
"title": "История версий файлов",
- "description": "Снимки для отката хранятся в .llm-wiki/history. Текущие файлы здесь не сохраняются. Приложение автоматически хранит не более 30 версий каждого файла и ограничивает общий размер истории проекта.",
+ "description": "Необязательные снимки для отката хранятся в .llm-wiki/history. Текущие файлы здесь не сохраняются.",
+ "enabled": "Записывать историю версий файлов",
+ "enabledHint": "По умолчанию отключено. Отключение прекращает создание новых снимков, не удаляя существующие.",
+ "retention": "Версий на один файл",
+ "retentionValue": "{{count}} / 30",
+ "retentionHint": "Можно выбрать от 0 до 30 версий. Значение 0 удаляет существующие снимки; по умолчанию сохраняется 10.",
+ "zeroConfirm": "Установить число версий в 0 и удалить все существующие снимки? Текущие файлы проекта удалены не будут.",
"usage": "{{size}} в {{files}} файлах истории (версий: {{entries}})",
"clear": "Очистить историю версий",
"confirm": "Удалить все снимки для отката в этом проекте? Текущие файлы проекта удалены не будут."
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index 7ba8a799..f4868e2e 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -872,7 +872,13 @@
},
"history": {
"title": "文件版本历史",
- "description": "回滚快照保存在 .llm-wiki/history,当前文件不存放在这里。应用会为每个文件最多保留 30 个版本,并限制项目历史的总容量。",
+ "description": "可选的回滚快照保存在 .llm-wiki/history,当前文件不存放在这里。",
+ "enabled": "记录文件版本历史",
+ "enabledHint": "默认关闭。关闭后仅停止生成新快照,不会删除已有历史。",
+ "retention": "每个文件保留版本数",
+ "retentionValue": "{{count}} / 30",
+ "retentionHint": "可设置为 0–30。设为 0 会清除已有快照;启用历史时默认保留 10 个版本。",
+ "zeroConfirm": "确定将保留版本数设为 0 并删除全部已有回滚快照吗?当前项目文件不会被删除。",
"usage": "{{files}} 个历史文件、{{entries}} 个版本,共占用 {{size}}",
"clear": "清空版本历史",
"confirm": "确定清空此项目的全部回滚快照吗?当前项目文件不会被删除。"