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
Add project file sync watcher
nash_su1b7f47e5c657
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 0c3e8851..f58ae219 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2512,6 +2512,15 @@ dependencies = ["windows-sys 0.52.0",]+[[package]]+name = "fsevent-sys"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2"+dependencies = [+ "libc",+]+[[package]]name = "fsst"version = "4.0.0"@@ -3445,6 +3454,26 @@ dependencies = ["cfb",]+[[package]]+name = "inotify"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd5b3eaf1a28b758ac0faa5a4254e8ab2705605496f1b1f3fbbc3988ad73d199"+dependencies = [+ "bitflags 2.11.0",+ "inotify-sys",+ "libc",+]++[[package]]+name = "inotify-sys"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb"+dependencies = [+ "libc",+]+[[package]]name = "inout"version = "0.1.4"@@ -3696,6 +3725,26 @@ dependencies = ["unicode-segmentation",]+[[package]]+name = "kqueue"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a"+dependencies = [+ "kqueue-sys",+ "libc",+]++[[package]]+name = "kqueue-sys"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7b65860415f949f23fa882e669f2dbd4a0f0eeb1acdd56790b30494afd7da2f"+dependencies = [+ "bitflags 2.11.0",+ "libc",+]+[[package]]name = "kuchikiki"version = "0.8.8-speedreader"@@ -4431,6 +4480,8 @@ dependencies = ["futures","image","lancedb",+ "md-5",+ "notify","pdfium-render","serde","serde_json",@@ -4444,6 +4495,7 @@ dependencies = ["tiny_http","tokio","uuid",+ "walkdir","which","zip 2.4.2",]@@ -4704,6 +4756,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"dependencies = ["libc",+ "log","wasi 0.11.1+wasi-snapshot-preview1","windows-sys 0.61.2",]@@ -4853,6 +4906,33 @@ dependencies = ["memchr",]+[[package]]+name = "notify"+version = "8.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3"+dependencies = [+ "bitflags 2.11.0",+ "fsevent-sys",+ "inotify",+ "kqueue",+ "libc",+ "log",+ "mio",+ "notify-types",+ "walkdir",+ "windows-sys 0.60.2",+]++[[package]]+name = "notify-types"+version = "2.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a"+dependencies = [+ "bitflags 2.11.0",+]+[[package]]name = "nu-ansi-term"version = "0.50.3"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex acb8e038..6573f56c 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -56,6 +56,9 @@ uuid = { version = "1", features = ["v4"] }image = { version = "0.25", default-features = false, features = ["png"] }base64 = "0.22"sha2 = "0.10"+md-5 = "0.10"+notify = "8"+walkdir = "2"[dev-dependencies]tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread"] }diff --git a/src-tauri/src/commands/file_sync.rs b/src-tauri/src/commands/file_sync.rsnew file mode 100644index 00000000..ab662ba5--- /dev/null+++ b/src-tauri/src/commands/file_sync.rs@@ -0,0 +1,1227 @@+use std::collections::{BTreeMap, BTreeSet};+use std::fs;+use std::io::Read;+use std::panic::AssertUnwindSafe;+use std::path::{Component, Path, PathBuf};+use std::sync::mpsc;+use std::sync::{Arc, Mutex, OnceLock};+use std::time::Duration;++use md5::{Digest, Md5};+use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};+use serde::{Deserialize, Serialize};+use tauri::{AppHandle, Emitter, State};+use walkdir::WalkDir;++use crate::panic_guard::run_guarded;++const SNAPSHOT_FILE: &str = ".llm-wiki/file-snapshot.json";+const QUEUE_FILE: &str = ".llm-wiki/file-change-queue.json";+const EVENT_QUEUE_UPDATED: &str = "file-sync://queue-updated";+const EVENT_CHANGED: &str = "file-sync://changed";+const MAX_HASH_BYTES: u64 = 32 * 1024 * 1024;+const MAX_RETRY_COUNT: u32 = 3;+const APP_WRITE_IGNORE_MS: i64 = 4_000;+const QUEUE_EMIT_EVERY: usize = 25;++static QUEUE_LOCKS: OnceLock<Mutex<BTreeMap<String, Arc<Mutex<()>>>>> = OnceLock::new();+static APP_WRITE_IGNORES: OnceLock<Mutex<BTreeMap<String, i64>>> = OnceLock::new();++#[derive(Default)]+pub struct FileSyncState {+ inner: Mutex<FileSyncInner>,+}++#[derive(Default)]+struct FileSyncInner {+ watcher: Option<RecommendedWatcher>,+ project_id: Option<String>,+ project_path: Option<PathBuf>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FileMeta {+ hash: Option<String>,+ size: u64,+ mtime_ms: i64,+}++#[derive(Debug, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+struct FileSnapshot {+ version: u32,+ updated_at: i64,+ files: BTreeMap<String, FileMeta>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum FileChangeKind {+ Created,+ Modified,+ Deleted,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum FileChangeStatus {+ Pending,+ Processing,+ Done,+ Failed,+ Superseded,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FileChangeTask {+ id: String,+ project_id: String,+ path: String,+ kind: FileChangeKind,+ status: FileChangeStatus,+ hash_before: Option<String>,+ hash_after: Option<String>,+ size: Option<u64>,+ mtime_ms: Option<i64>,+ created_at: i64,+ updated_at: i64,+ retry_count: u32,+ error: Option<String>,+ needs_rerun: bool,+}++#[derive(Debug, Default, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FileChangeQueue {+ version: u32,+ tasks: Vec<FileChangeTask>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+struct FileSyncPayload {+ project_id: String,+ tasks: Vec<FileChangeTask>,+}++#[tauri::command]+pub fn start_project_file_watcher(+ app: AppHandle,+ state: State<FileSyncState>,+ project_id: String,+ project_path: String,+) -> Result<FileChangeQueue, String> {+ run_guarded("start_project_file_watcher", || {+ let root = PathBuf::from(project_path);+ ensure_sync_dir(&root)?;+ with_queue_lock(&root, || reset_processing_tasks(&root, &project_id))?;+ enqueue_rescan_changes(&root, &project_id)?;+ process_queue(&app, &root, &project_id)?;++ let (tx, rx) = mpsc::sync_channel::<PathBuf>(8_192);+ let app_for_thread = app.clone();+ let root_for_thread = root.clone();+ let project_for_thread = project_id.clone();+ std::thread::spawn(move || {+ let mut pending = BTreeSet::<PathBuf>::new();+ loop {+ match rx.recv_timeout(Duration::from_millis(700)) {+ Ok(path) => {+ pending.insert(path);+ while let Ok(path) = rx.try_recv() {+ pending.insert(path);+ }+ }+ Err(mpsc::RecvTimeoutError::Timeout) => {+ if pending.is_empty() {+ continue;+ }+ let paths = pending.iter().cloned().collect::<Vec<_>>();+ pending.clear();+ let result = std::panic::catch_unwind(AssertUnwindSafe(|| {+ handle_changed_paths(+ &app_for_thread,+ &root_for_thread,+ &project_for_thread,+ paths,+ )+ }));+ match result {+ Ok(Ok(())) => {}+ Ok(Err(err)) => eprintln!("[file-sync] change handling failed: {err}"),+ Err(_) => eprintln!("[file-sync] watcher worker recovered from panic"),+ }+ }+ Err(mpsc::RecvTimeoutError::Disconnected) => break,+ }+ }+ });++ let tx_for_watcher = tx.clone();+ let root_for_overflow = root.clone();+ let mut watcher = RecommendedWatcher::new(+ move |res: notify::Result<Event>| {+ if let Ok(event) = res {+ for path in event.paths {+ if tx_for_watcher.try_send(path).is_err() {+ let _ = tx_for_watcher.try_send(root_for_overflow.clone());+ break;+ }+ }+ }+ },+ Config::default(),+ )+ .map_err(|e| format!("Failed to create file watcher: {e}"))?;+ watcher+ .watch(&root, RecursiveMode::Recursive)+ .map_err(|e| format!("Failed to watch '{}': {e}", root.display()))?;++ {+ let mut inner = state.inner.lock().map_err(|_| "file sync state poisoned")?;+ inner.watcher = Some(watcher);+ inner.project_id = Some(project_id.clone());+ inner.project_path = Some(root.clone());+ }++ let queue = with_queue_lock(&root, || read_queue(&root))?;+ emit_queue(&app, &project_id, &queue);+ Ok(queue)+ })+}++#[tauri::command]+pub fn stop_project_file_watcher(state: State<FileSyncState>) -> Result<(), String> {+ run_guarded("stop_project_file_watcher", || {+ let mut inner = state.inner.lock().map_err(|_| "file sync state poisoned")?;+ inner.watcher = None;+ inner.project_id = None;+ inner.project_path = None;+ Ok(())+ })+}++#[tauri::command]+pub fn rescan_project_files(+ app: AppHandle,+ project_id: String,+ project_path: String,+) -> Result<FileChangeQueue, String> {+ run_guarded("rescan_project_files", || {+ let root = PathBuf::from(project_path);+ ensure_sync_dir(&root)?;+ enqueue_rescan_changes(&root, &project_id)?;+ process_queue(&app, &root, &project_id)?;+ let queue = with_queue_lock(&root, || read_queue(&root))?;+ emit_queue(&app, &project_id, &queue);+ Ok(queue)+ })+}++#[tauri::command]+pub fn get_file_change_queue(project_path: String) -> Result<FileChangeQueue, String> {+ run_guarded("get_file_change_queue", || {+ let root = PathBuf::from(project_path);+ with_queue_lock(&root, || read_queue(&root))+ })+}++#[tauri::command]+pub fn retry_file_change_task(+ app: AppHandle,+ project_id: String,+ project_path: String,+ task_id: String,+) -> Result<FileChangeQueue, String> {+ run_guarded("retry_file_change_task", || {+ let root = PathBuf::from(project_path);+ with_queue_lock(&root, || {+ let mut queue = read_queue(&root)?;+ let now = now_ms();+ for task in &mut queue.tasks {+ if task.id == task_id && task.project_id == project_id {+ task.status = FileChangeStatus::Pending;+ task.error = None;+ task.retry_count = 0;+ task.needs_rerun = false;+ task.updated_at = now;+ }+ }+ write_queue(&root, &queue)+ })?;+ process_queue(&app, &root, &project_id)?;+ let queue = with_queue_lock(&root, || read_queue(&root))?;+ emit_queue(&app, &project_id, &queue);+ Ok(queue)+ })+}++#[tauri::command]+pub fn ignore_file_change_task(+ app: AppHandle,+ project_id: String,+ project_path: String,+ task_id: String,+) -> Result<FileChangeQueue, String> {+ run_guarded("ignore_file_change_task", || {+ let root = PathBuf::from(project_path);+ let queue = with_queue_lock(&root, || {+ let mut queue = read_queue(&root)?;+ queue+ .tasks+ .retain(|task| !(task.id == task_id && task.project_id == project_id));+ write_queue(&root, &queue)?;+ read_queue(&root)+ })?;+ emit_queue(&app, &project_id, &queue);+ Ok(queue)+ })+}++pub fn mark_app_write_path(path: &Path) {+ let key = path_key(path);+ let now = now_ms();+ let mut ignores = APP_WRITE_IGNORES+ .get_or_init(|| Mutex::new(BTreeMap::new()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ ignores.retain(|_, expires_at| *expires_at > now);+ ignores.insert(key, now + APP_WRITE_IGNORE_MS);+}++fn handle_changed_paths(+ app: &AppHandle,+ root: &Path,+ project_id: &str,+ paths: Vec<PathBuf>,+) -> Result<(), String> {+ let mut rels = BTreeSet::<String>::new();+ let mut app_written_rels = BTreeSet::<String>::new();+ let snapshot = with_queue_lock(root, || read_snapshot(root))?;+ for path in paths {+ if is_app_write_ignored(&path) {+ collect_known_paths(root, &path, &snapshot, &mut app_written_rels);+ continue;+ }+ if path.is_dir() {+ for entry in WalkDir::new(&path).into_iter().filter_map(Result::ok) {+ if entry.file_type().is_file() && !is_app_write_ignored(entry.path()) {+ if let Some(rel) = relative_watch_path(root, entry.path()) {+ rels.insert(rel);+ }+ }+ }+ } else if let Some(rel) = relative_watch_path(root, &path) {+ rels.insert(rel);+ } else if !path.exists() {+ collect_known_paths(root, &path, &snapshot, &mut rels);+ }+ }+ if !app_written_rels.is_empty() {+ sync_snapshot_paths(root, app_written_rels)?;+ }+ if rels.is_empty() {+ return Ok(());+ }+ enqueue_paths(root, project_id, rels)?;+ process_queue(app, root, project_id)?;+ let queue = with_queue_lock(root, || read_queue(root))?;+ emit_queue(app, project_id, &queue);+ Ok(())+}++fn collect_known_paths(+ root: &Path,+ path: &Path,+ snapshot: &FileSnapshot,+ rels: &mut BTreeSet<String>,+) {+ if path.is_dir() {+ for entry in WalkDir::new(path).into_iter().filter_map(Result::ok) {+ if entry.file_type().is_file() {+ if let Some(rel) = relative_watch_path(root, entry.path()) {+ rels.insert(rel);+ }+ }+ }+ return;+ }++ let Ok(rel_path) = path.strip_prefix(root) else {+ return;+ };+ let Some(rel) = normalize_rel_path(rel_path) else {+ return;+ };+ if !path.exists() {+ for known in snapshot.files.keys() {+ if known == &rel || known.starts_with(&format!("{rel}/")) {+ rels.insert(known.clone());+ }+ }+ return;+ }++ if should_watch_rel(&rel) {+ rels.insert(rel);+ }+}++fn sync_snapshot_paths(root: &Path, rels: BTreeSet<String>) -> Result<(), String> {+ let metas = rels+ .into_iter()+ .map(|rel| read_meta(root, &rel).map(|meta| (rel, meta)))+ .collect::<Result<Vec<_>, _>>()?;++ with_queue_lock(root, || {+ let mut snapshot = read_snapshot(root)?;+ for (rel, meta) in metas {+ match meta {+ Some(meta) => {+ snapshot.files.insert(rel, meta);+ }+ None => {+ snapshot.files.remove(&rel);+ }+ }+ }+ snapshot.version = 1;+ snapshot.updated_at = now_ms();+ write_snapshot(root, &snapshot)+ })+}++fn enqueue_rescan_changes(root: &Path, project_id: &str) -> Result<(), String> {+ let mut rels = BTreeSet::<String>::new();+ for entry in WalkDir::new(root).into_iter().filter_map(Result::ok) {+ if entry.file_type().is_file() {+ if let Some(rel) = relative_watch_path(root, entry.path()) {+ rels.insert(rel);+ }+ }+ }++ let snapshot = with_queue_lock(root, || read_snapshot(root))?;+ for rel in snapshot.files.keys() {+ if !root.join(rel).exists() {+ rels.insert(rel.clone());+ }+ }+ enqueue_paths(root, project_id, rels)+}++fn enqueue_paths(root: &Path, project_id: &str, rels: BTreeSet<String>) -> Result<(), String> {+ let snapshot = with_queue_lock(root, || read_snapshot(root))?;+ let now = now_ms();+ let mut changes = Vec::new();++ for rel in rels {+ let old = snapshot.files.get(&rel).cloned();+ // Intentional TOCTOU trade-off: `read_meta` can be expensive+ // because it may hash file contents, so it runs outside the queue+ // lock. If another worker updates the snapshot before this task is+ // enqueued, the task may be redundant; processing it is harmless and+ // self-corrects by writing the current on-disk meta back to snapshot.+ let new = read_meta(root, &rel)?;+ if old.as_ref().map(|m| (&m.hash, m.size)) == new.as_ref().map(|m| (&m.hash, m.size)) {+ continue;+ }++ let kind = match (&old, &new) {+ (None, Some(_)) => FileChangeKind::Created,+ (Some(_), None) => FileChangeKind::Deleted,+ (Some(_), Some(_)) => FileChangeKind::Modified,+ (None, None) => continue,+ };+ changes.push((rel, kind, old, new));+ }++ if changes.is_empty() {+ return Ok(());+ }++ with_queue_lock(root, || {+ let mut queue = read_queue(root)?;+ for (rel, kind, old, new) in changes {+ upsert_task(&mut queue, project_id, &rel, kind, old, new, now);+ }+ write_queue(root, &queue)+ })+}++fn upsert_task(+ queue: &mut FileChangeQueue,+ project_id: &str,+ rel: &str,+ kind: FileChangeKind,+ old: Option<FileMeta>,+ new: Option<FileMeta>,+ now: i64,+) {+ if let Some(task) = queue.tasks.iter_mut().find(|t| {+ t.project_id == project_id+ && normalize_key(&t.path) == normalize_key(rel)+ && matches!(+ t.status,+ FileChangeStatus::Pending | FileChangeStatus::Processing | FileChangeStatus::Failed+ )+ }) {+ task.kind = merge_kind(&task.kind, &kind);+ task.hash_after = new.as_ref().and_then(|m| m.hash.clone());+ task.size = new.as_ref().map(|m| m.size);+ task.mtime_ms = new.as_ref().map(|m| m.mtime_ms);+ task.updated_at = now;+ if task.status == FileChangeStatus::Failed {+ if task.retry_count < MAX_RETRY_COUNT {+ task.status = FileChangeStatus::Pending;+ task.error = None;+ } else {+ task.error = Some(format!("Retry limit reached ({MAX_RETRY_COUNT})"));+ }+ } else if task.status == FileChangeStatus::Processing {+ task.needs_rerun = true;+ task.error = None;+ } else {+ task.error = None;+ }+ return;+ }++ queue.tasks.push(FileChangeTask {+ id: format!("change_{}_{}", now, stable_path_hash(rel)),+ project_id: project_id.to_string(),+ path: rel.to_string(),+ kind,+ status: FileChangeStatus::Pending,+ hash_before: old.and_then(|m| m.hash),+ hash_after: new.as_ref().and_then(|m| m.hash.clone()),+ size: new.as_ref().map(|m| m.size),+ mtime_ms: new.as_ref().map(|m| m.mtime_ms),+ created_at: now,+ updated_at: now,+ retry_count: 0,+ error: None,+ needs_rerun: false,+ });+}++fn process_queue(app: &AppHandle, root: &Path, project_id: &str) -> Result<(), String> {+ process_queue_inner(+ root,+ project_id,+ |queue| emit_queue(app, project_id, queue),+ |tasks| emit_changed_batch(app, project_id, tasks),+ )+}++fn process_queue_inner(+ root: &Path,+ project_id: &str,+ mut on_queue: impl FnMut(&FileChangeQueue),+ mut on_changed: impl FnMut(Vec<FileChangeTask>),+) -> Result<(), String> {+ let mut changed_tasks = Vec::<FileChangeTask>::new();+ let mut processed_since_emit = 0_usize;+ let mut emitted_processing = false;+ loop {+ let pick_result = with_queue_lock(root, || {+ let mut queue = read_queue(root)?;+ let Some(idx) = queue.tasks.iter().position(|task| {+ task.project_id == project_id && task.status == FileChangeStatus::Pending+ }) else {+ return Ok(None);+ };++ queue.tasks[idx].status = FileChangeStatus::Processing;+ queue.tasks[idx].updated_at = now_ms();+ let task = queue.tasks[idx].clone();+ write_queue(root, &queue)?;+ Ok(Some((task, queue)))+ });+ let picked = match pick_result {+ Ok(result) => result,+ Err(err) => {+ on_changed(changed_tasks);+ return Err(err);+ }+ };+ let Some((task, queue)) = picked else {+ let queue = match with_queue_lock(root, || read_queue(root)) {+ Ok(queue) => queue,+ Err(err) => {+ on_changed(changed_tasks);+ return Err(err);+ }+ };+ on_changed(changed_tasks);+ on_queue(&queue);+ return Ok(());+ };+ if !emitted_processing {+ emitted_processing = true;+ on_queue(&queue);+ }++ let meta_result = read_meta(root, &task.path);+ let mut emit_after_update = false;+ let update_result = with_queue_lock(root, || {+ let mut queue = read_queue(root)?;+ if let Some(current) = queue.tasks.iter_mut().find(|t| t.id == task.id) {+ if current.status != FileChangeStatus::Processing+ || current.updated_at != task.updated_at+ {+ if current.status == FileChangeStatus::Processing && current.needs_rerun {+ current.status = FileChangeStatus::Pending;+ current.needs_rerun = false;+ current.updated_at = now_ms();+ }+ } else {+ match meta_result {+ Ok(meta) => {+ write_task_meta_to_snapshot(root, &task, meta)?;+ if current.needs_rerun {+ current.status = FileChangeStatus::Pending;+ current.needs_rerun = false;+ } else {+ current.status = FileChangeStatus::Done;+ }+ current.error = None;+ }+ Err(err) => {+ current.status = FileChangeStatus::Failed;+ current.error = Some(err);+ current.retry_count += 1;+ }+ }+ current.updated_at = now_ms();+ changed_tasks.push(task.clone());+ processed_since_emit += 1;+ if processed_since_emit >= QUEUE_EMIT_EVERY {+ processed_since_emit = 0;+ emit_after_update = true;+ }+ }+ }+ queue+ .tasks+ .retain(|task| task.status != FileChangeStatus::Done);+ write_queue(root, &queue)?;+ read_queue(root)+ });+ let queue = match update_result {+ Ok(queue) => queue,+ Err(err) => {+ on_changed(changed_tasks);+ return Err(err);+ }+ };+ if emit_after_update {+ on_queue(&queue);+ }+ }+}++#[cfg(test)]+fn apply_task_to_snapshot(root: &Path, task: &FileChangeTask) -> Result<(), String> {+ let meta = read_meta(root, &task.path)?;+ with_queue_lock(root, || write_task_meta_to_snapshot(root, task, meta))+}++fn write_task_meta_to_snapshot(+ root: &Path,+ task: &FileChangeTask,+ meta: Option<FileMeta>,+) -> Result<(), String> {+ let mut snapshot = read_snapshot(root)?;+ match meta {+ Some(meta) => {+ snapshot.files.insert(task.path.clone(), meta);+ }+ None => {+ snapshot.files.remove(&task.path);+ }+ }+ snapshot.version = 1;+ snapshot.updated_at = now_ms();+ write_snapshot(root, &snapshot)+}++fn reset_processing_tasks(root: &Path, project_id: &str) -> Result<(), String> {+ let mut queue = read_queue(root)?;+ let mut changed = false;+ queue.tasks.retain(|task| task.project_id == project_id);+ for task in &mut queue.tasks {+ if task.status == FileChangeStatus::Processing {+ task.status = FileChangeStatus::Pending;+ task.needs_rerun = false;+ task.error = None;+ task.updated_at = now_ms();+ changed = true;+ }+ }+ if changed {+ write_queue(root, &queue)?;+ }+ Ok(())+}++fn read_meta(root: &Path, rel: &str) -> Result<Option<FileMeta>, String> {+ let path = root.join(rel);+ if !path.exists() {+ return Ok(None);+ }+ let meta = fs::metadata(&path).map_err(|e| format!("metadata failed for {rel}: {e}"))?;+ if !meta.is_file() {+ return Ok(None);+ }+ let size = meta.len();+ let mtime_ms = meta+ .modified()+ .ok()+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| d.as_millis() as i64)+ .unwrap_or(0);+ let hash = if size <= MAX_HASH_BYTES {+ Some(md5_file(&path)?)+ } else {+ None+ };+ Ok(Some(FileMeta {+ hash,+ size,+ mtime_ms,+ }))+}++fn md5_file(path: &Path) -> Result<String, String> {+ let mut file =+ fs::File::open(path).map_err(|e| format!("open failed for '{}': {e}", path.display()))?;+ let mut hasher = Md5::new();+ let mut buf = [0_u8; 64 * 1024];+ loop {+ let n = file+ .read(&mut buf)+ .map_err(|e| format!("read failed for '{}': {e}", path.display()))?;+ if n == 0 {+ break;+ }+ hasher.update(&buf[..n]);+ }+ Ok(format!("{:x}", hasher.finalize()))+}++fn relative_watch_path(root: &Path, path: &Path) -> Option<String> {+ let rel = path.strip_prefix(root).ok()?;+ let rel = normalize_rel_path(rel)?;+ if should_watch_rel(&rel) {+ Some(rel)+ } else {+ None+ }+}++fn normalize_rel_path(path: &Path) -> Option<String> {+ let mut parts = Vec::new();+ for component in path.components() {+ match component {+ Component::Normal(s) => parts.push(s.to_string_lossy().to_string()),+ _ => return None,+ }+ }+ Some(parts.join("/"))+}++fn should_watch_rel(rel: &str) -> bool {+ if rel.is_empty() {+ return false;+ }+ let lower = rel.to_lowercase();+ if lower.contains("/.llm-wiki/")+ || lower.starts_with(".llm-wiki/")+ || lower.starts_with(".cache/")+ || lower.starts_with(".obsidian/")+ || lower.starts_with(".idea/")+ || lower.starts_with(".vscode/")+ // App-managed generated media is intentionally ignored here. The+ // source markdown references drive graph/index refresh; media bytes+ // themselves are not analyzed by the wiki pipeline.+ || lower.starts_with("wiki/media/")+ || lower.ends_with(".tmp")+ || lower.ends_with(".swp")+ || lower.ends_with('~')+ || lower.ends_with(".ds_store")+ || lower.ends_with(".crdownload")+ || lower.ends_with(".part")+ || lower.ends_with(".partial")+ {+ return false;+ }+ let name = lower.rsplit('/').next().unwrap_or(&lower);+ if name.starts_with("~$") || (name.starts_with(".~lock.") && name.ends_with('#')) {+ return false;+ }+ rel == "purpose.md"+ || rel == "schema.md"+ || (rel.starts_with("wiki/") && rel.ends_with(".md"))+ || rel.starts_with("raw/sources/")+}++fn merge_kind(existing: &FileChangeKind, incoming: &FileChangeKind) -> FileChangeKind {+ match (existing, incoming) {+ (FileChangeKind::Deleted, FileChangeKind::Created)+ | (FileChangeKind::Created, FileChangeKind::Deleted)+ | (_, FileChangeKind::Modified) => FileChangeKind::Modified,+ (_, kind) => kind.clone(),+ }+}++fn emit_queue(app: &AppHandle, project_id: &str, queue: &FileChangeQueue) {+ let payload = FileSyncPayload {+ project_id: project_id.to_string(),+ tasks: queue.tasks.clone(),+ };+ let _ = app.emit(EVENT_QUEUE_UPDATED, payload);+}++fn emit_changed_batch(app: &AppHandle, project_id: &str, tasks: Vec<FileChangeTask>) {+ if tasks.is_empty() {+ return;+ }+ let payload = FileSyncPayload {+ project_id: project_id.to_string(),+ tasks,+ };+ let _ = app.emit(EVENT_CHANGED, payload);+}++fn ensure_sync_dir(root: &Path) -> Result<(), String> {+ fs::create_dir_all(root.join(".llm-wiki"))+ .map_err(|e| format!("Failed to create .llm-wiki: {e}"))+}++fn read_snapshot(root: &Path) -> Result<FileSnapshot, String> {+ read_json(root.join(SNAPSHOT_FILE)).map(|mut s: FileSnapshot| {+ if s.version == 0 {+ s.version = 1;+ }+ s+ })+}++fn write_snapshot(root: &Path, snapshot: &FileSnapshot) -> Result<(), String> {+ write_json(root.join(SNAPSHOT_FILE), snapshot)+}++fn read_queue(root: &Path) -> Result<FileChangeQueue, String> {+ read_json(root.join(QUEUE_FILE)).map(|mut q: FileChangeQueue| {+ if q.version == 0 {+ q.version = 1;+ }+ q+ })+}++fn write_queue(root: &Path, queue: &FileChangeQueue) -> Result<(), String> {+ write_json(root.join(QUEUE_FILE), queue)+}++fn read_json<T>(path: PathBuf) -> Result<T, String>+where+ T: Default + for<'de> Deserialize<'de>,+{+ if !path.exists() {+ return Ok(T::default());+ }+ let text = fs::read_to_string(&path)+ .map_err(|e| format!("Failed to read '{}': {e}", path.display()))?;+ serde_json::from_str(&text).map_err(|e| format!("Failed to parse '{}': {e}", path.display()))+}++fn write_json<T: Serialize>(path: PathBuf, value: &T) -> Result<(), String> {+ if let Some(parent) = path.parent() {+ fs::create_dir_all(parent)+ .map_err(|e| format!("Failed to create '{}': {e}", parent.display()))?;+ }+ let text =+ serde_json::to_string_pretty(value).map_err(|e| format!("JSON encode failed: {e}"))?;+ fs::write(&path, text).map_err(|e| format!("Failed to write '{}': {e}", path.display()))+}++fn stable_path_hash(path: &str) -> String {+ let mut hasher = Md5::new();+ hasher.update(path.as_bytes());+ let digest = format!("{:x}", hasher.finalize());+ digest[..12].to_string()+}++fn normalize_key(path: &str) -> String {+ if cfg!(windows) {+ path.to_lowercase()+ } else {+ path.to_string()+ }+}++fn now_ms() -> i64 {+ chrono::Utc::now().timestamp_millis()+}++fn queue_lock_for(root: &Path) -> Arc<Mutex<()>> {+ let key = path_key(root);+ let mut locks = QUEUE_LOCKS+ .get_or_init(|| Mutex::new(BTreeMap::new()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ locks+ .entry(key)+ .or_insert_with(|| Arc::new(Mutex::new(())))+ .clone()+}++fn with_queue_lock<T>(root: &Path, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {+ let lock = queue_lock_for(root);+ let _guard = lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());+ f()+}++fn path_key(path: &Path) -> String {+ if let Ok(canonical) = path.canonicalize() {+ return normalize_path_key(&canonical);+ }++ let mut existing = path.to_path_buf();+ let mut suffix = Vec::new();+ while !existing.exists() {+ let Some(name) = existing.file_name().map(|name| name.to_os_string()) else {+ return normalize_path_key(path);+ };+ suffix.push(name);+ if !existing.pop() {+ return normalize_path_key(path);+ }+ }++ let Ok(mut canonical) = existing.canonicalize() else {+ return normalize_path_key(path);+ };+ for part in suffix.iter().rev() {+ canonical.push(part);+ }+ normalize_path_key(&canonical)+}++fn normalize_path_key(path: &Path) -> String {+ path.to_string_lossy().replace('\\', "/")+}++fn is_app_write_ignored(path: &Path) -> bool {+ let key = path_key(path);+ let now = now_ms();+ let mut ignores = APP_WRITE_IGNORES+ .get_or_init(|| Mutex::new(BTreeMap::new()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ ignores.retain(|_, expires_at| *expires_at > now);+ ignores+ .keys()+ .any(|ignored| key == *ignored || key.starts_with(&format!("{ignored}/")))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn temp_root(name: &str) -> PathBuf {+ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let root = std::env::temp_dir().join(format!("llm-wiki-file-sync-{name}-{stamp}"));+ fs::create_dir_all(root.join("raw/sources")).unwrap();+ root+ }++ #[test]+ fn md5_detects_same_size_content_changes() {+ let root = temp_root("same-size");+ let rel = "raw/sources/a.md";+ fs::write(root.join(rel), "aaaa").unwrap();++ ensure_sync_dir(&root).unwrap();+ enqueue_rescan_changes(&root, "p1").unwrap();+ let first = read_queue(&root).unwrap().tasks[0].clone();+ apply_task_to_snapshot(&root, &first).unwrap();+ write_queue(+ &root,+ &FileChangeQueue {+ version: 1,+ tasks: vec![],+ },+ )+ .unwrap();++ fs::write(root.join(rel), "bbbb").unwrap();+ enqueue_paths(&root, "p1", BTreeSet::from([rel.to_string()])).unwrap();+ let queue = read_queue(&root).unwrap();++ assert_eq!(queue.tasks.len(), 1);+ assert_eq!(queue.tasks[0].kind, FileChangeKind::Modified);+ assert_ne!(queue.tasks[0].hash_before, queue.tasks[0].hash_after);++ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn repeated_changes_upsert_one_pending_task() {+ let root = temp_root("dedupe");+ let rel = "raw/sources/a.md";+ fs::write(root.join(rel), "one").unwrap();++ ensure_sync_dir(&root).unwrap();+ enqueue_paths(&root, "p1", BTreeSet::from([rel.to_string()])).unwrap();+ fs::write(root.join(rel), "two").unwrap();+ enqueue_paths(&root, "p1", BTreeSet::from([rel.to_string()])).unwrap();++ let queue = read_queue(&root).unwrap();+ assert_eq!(queue.tasks.len(), 1);+ assert_eq!(queue.tasks[0].status, FileChangeStatus::Pending);+ assert_eq!(queue.tasks[0].path, rel);++ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn directory_delete_expands_snapshot_children() {+ let root = temp_root("dir-delete");+ let a = "raw/sources/folder/a.md";+ let b = "raw/sources/folder/b.md";+ fs::create_dir_all(root.join("raw/sources/folder")).unwrap();+ fs::write(root.join(a), "a").unwrap();+ fs::write(root.join(b), "b").unwrap();++ ensure_sync_dir(&root).unwrap();+ sync_snapshot_paths(&root, BTreeSet::from([a.to_string(), b.to_string()])).unwrap();+ fs::remove_dir_all(root.join("raw/sources/folder")).unwrap();++ let mut rels = BTreeSet::new();+ let snapshot = read_snapshot(&root).unwrap();+ collect_known_paths(+ &root,+ &root.join("raw/sources/folder"),+ &snapshot,+ &mut rels,+ );++ assert_eq!(rels, BTreeSet::from([a.to_string(), b.to_string()]));++ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn app_written_paths_update_snapshot_without_queueing() {+ let root = temp_root("app-write");+ let rel = "raw/sources/a.md";+ let path = root.join(rel);+ fs::write(&path, "old").unwrap();++ ensure_sync_dir(&root).unwrap();+ sync_snapshot_paths(&root, BTreeSet::from([rel.to_string()])).unwrap();+ fs::write(&path, "new").unwrap();+ mark_app_write_path(&path);++ let mut app_written_rels = BTreeSet::new();+ let snapshot = read_snapshot(&root).unwrap();+ if is_app_write_ignored(&path) {+ collect_known_paths(&root, &path, &snapshot, &mut app_written_rels);+ }+ sync_snapshot_paths(&root, app_written_rels).unwrap();++ let queue = read_queue(&root).unwrap();+ let snapshot = read_snapshot(&root).unwrap();+ assert!(queue.tasks.is_empty());+ assert_eq!(+ snapshot.files.get(rel).and_then(|m| m.hash.clone()),+ read_meta(&root, rel).unwrap().and_then(|m| m.hash)+ );++ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn retry_limit_keeps_failed_task_failed_on_new_changes() {+ let root = temp_root("retry-limit");+ let rel = "raw/sources/a.md";+ fs::write(root.join(rel), "one").unwrap();++ ensure_sync_dir(&root).unwrap();+ let mut queue = FileChangeQueue {+ version: 1,+ tasks: vec![FileChangeTask {+ id: "t1".into(),+ project_id: "p1".into(),+ path: rel.into(),+ kind: FileChangeKind::Modified,+ status: FileChangeStatus::Failed,+ hash_before: None,+ hash_after: None,+ size: None,+ mtime_ms: None,+ created_at: 1,+ updated_at: 1,+ retry_count: MAX_RETRY_COUNT,+ error: Some("failed".into()),+ needs_rerun: false,+ }],+ };+ upsert_task(+ &mut queue,+ "p1",+ rel,+ FileChangeKind::Modified,+ None,+ read_meta(&root, rel).unwrap(),+ now_ms(),+ );++ assert_eq!(queue.tasks.len(), 1);+ assert_eq!(queue.tasks[0].status, FileChangeStatus::Failed);+ assert_eq!(queue.tasks[0].retry_count, MAX_RETRY_COUNT);++ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn watch_rules_exclude_temporary_and_app_dirs() {+ assert!(should_watch_rel("raw/sources/doc.md"));+ assert!(should_watch_rel("wiki/concepts/topic.md"));+ assert!(!should_watch_rel(".llm-wiki/file-change-queue.json"));+ assert!(!should_watch_rel("raw/sources/~$Document.docx"));+ assert!(!should_watch_rel("raw/sources/.~lock.Document.odt#"));+ assert!(!should_watch_rel("raw/sources/download.crdownload"));+ assert!(!should_watch_rel(".vscode/settings.json"));+ assert!(!should_watch_rel("wiki/media/image.png"));+ }++ #[test]+ fn queue_lock_recovers_after_poison() {+ let root = temp_root("poison");+ let lock = queue_lock_for(&root);+ let _ = std::thread::spawn(move || {+ let _guard = lock.lock().unwrap();+ panic!("poison file sync lock");+ })+ .join();++ let result = with_queue_lock(&root, || Ok(42));+ assert_eq!(result.unwrap(), 42);++ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn concurrent_enqueue_paths_do_not_drop_tasks() {+ let root = temp_root("concurrent");+ ensure_sync_dir(&root).unwrap();+ let mut handles = Vec::new();+ for i in 0..16 {+ let root = root.clone();+ let rel = format!("raw/sources/{i}.md");+ fs::write(root.join(&rel), format!("content {i}")).unwrap();+ handles.push(std::thread::spawn(move || {+ enqueue_paths(&root, "p1", BTreeSet::from([rel])).unwrap();+ }));+ }+ for handle in handles {+ handle.join().unwrap();+ }++ let queue = with_queue_lock(&root, || read_queue(&root)).unwrap();+ assert_eq!(queue.tasks.len(), 16);++ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn path_key_is_stable_after_leaf_deletion() {+ let root = temp_root("path-key");+ let path = root.join("raw/sources/a.md");+ fs::write(&path, "content").unwrap();+ let before = path_key(&path);+ fs::remove_file(&path).unwrap();+ let after = path_key(&path);++ assert_eq!(before, after);++ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn process_queue_updates_snapshot_and_removes_done_tasks() {+ let root = temp_root("process-e2e");+ let rel = "raw/sources/a.md";+ fs::write(root.join(rel), "content").unwrap();++ ensure_sync_dir(&root).unwrap();+ enqueue_paths(&root, "p1", BTreeSet::from([rel.to_string()])).unwrap();++ let mut queue_emits = 0;+ let mut changed_emits = 0;+ process_queue_inner(+ &root,+ "p1",+ |_| queue_emits += 1,+ |tasks| {+ if !tasks.is_empty() {+ changed_emits += 1;+ }+ },+ )+ .unwrap();++ let queue = with_queue_lock(&root, || read_queue(&root)).unwrap();+ let snapshot = with_queue_lock(&root, || read_snapshot(&root)).unwrap();+ assert!(queue.tasks.is_empty());+ assert!(snapshot.files.contains_key(rel));+ assert!(queue_emits >= 1);+ assert_eq!(changed_emits, 1);++ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn process_queue_flushes_changed_tasks_before_returning_error() {+ let root = temp_root("flush-on-error");+ ensure_sync_dir(&root).unwrap();+ let rels = (0..26)+ .map(|i| {+ let rel = format!("raw/sources/{i}.md");+ fs::write(root.join(&rel), format!("content {i}")).unwrap();+ rel+ })+ .collect::<BTreeSet<_>>();+ enqueue_paths(&root, "p1", rels).unwrap();++ let snapshot_path = root.join(SNAPSHOT_FILE);+ let mut queue_emits = 0;+ let mut changed_count = 0;+ let result = process_queue_inner(+ &root,+ "p1",+ |_| {+ queue_emits += 1;+ if queue_emits == 2 {+ fs::remove_file(&snapshot_path).unwrap();+ fs::create_dir_all(&snapshot_path).unwrap();+ }+ },+ |tasks| changed_count += tasks.len(),+ );++ assert!(result.is_err());+ assert_eq!(changed_count, QUEUE_EMIT_EVERY);++ let _ = fs::remove_dir_all(root);+ }+}diff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rsindex 544efc18..c4937390 100644--- a/src-tauri/src/commands/fs.rs+++ b/src-tauri/src/commands/fs.rs@@ -4,6 +4,7 @@ use std::path::Path;use calamine::{Reader, open_workbook_auto, Data};+use crate::commands::file_sync;use crate::panic_guard::run_guarded;use crate::types::wiki::FileNode;@@ -899,8 +900,11 @@ pub async fn write_file(path: String, contents: String) -> Result<(), String> {fs::create_dir_all(parent).map_err(|e| format!("Failed to create parent dirs for '{}': {}", path, e))?;}+ file_sync::mark_app_write_path(p);fs::write(&path, contents)- .map_err(|e| format!("Failed to write file '{}': {}", path, e))+ .map_err(|e| format!("Failed to write file '{}': {}", path, e))?;+ file_sync::mark_app_write_path(p);+ Ok(())})}).await@@ -1002,8 +1006,10 @@ pub async fn copy_file(source: String, destination: String) -> Result<(), Stringfs::create_dir_all(parent).map_err(|e| format!("Failed to create parent dirs: {}", e))?;}+ file_sync::mark_app_write_path(dest);fs::copy(&source, &destination).map_err(|e| format!("Failed to copy '{}' to '{}': {}", source, destination, e))?;+ file_sync::mark_app_write_path(dest);Ok(())})})@@ -1019,6 +1025,7 @@ pub async fn copy_directory(source: String, destination: String) -> Result<Vec<Srun_guarded("copy_directory", || {let src = Path::new(&source);let dest = Path::new(&destination);+ file_sync::mark_app_write_path(dest);if !src.is_dir() {return Err(format!("'{}' is not a directory", source));@@ -1053,6 +1060,7 @@ pub async fn copy_directory(source: String, destination: String) -> Result<Vec<Sfs::copy(&path, &dest_path).map_err(|e| {format!("Failed to copy '{}': {}", path.display(), e)})?;+ file_sync::mark_app_write_path(&dest_path);files.push(dest_path.to_string_lossy().replace('\\', "/"));}}@@ -1072,13 +1080,16 @@ pub async fn delete_file(path: String) -> Result<(), String> {tauri::async_runtime::spawn_blocking(move || {run_guarded("delete_file", || {let p = Path::new(&path);+ file_sync::mark_app_write_path(p);if p.is_dir() {fs::remove_dir_all(&path)- .map_err(|e| format!("Failed to delete directory '{}': {}", path, e))+ .map_err(|e| format!("Failed to delete directory '{}': {}", path, e))?;} else {fs::remove_file(&path)- .map_err(|e| format!("Failed to delete file '{}': {}", path, e))+ .map_err(|e| format!("Failed to delete file '{}': {}", path, e))?;}+ file_sync::mark_app_write_path(p);+ Ok(())})}).awaitdiff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 22502381..4b1004ed 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -1,5 +1,6 @@pub mod claude_cli;pub mod extract_images;+pub mod file_sync;pub mod fs;pub mod project;pub mod vectorstore;diff --git a/src-tauri/src/commands/project.rs b/src-tauri/src/commands/project.rsindex 2f138359..694dbe56 100644--- a/src-tauri/src/commands/project.rs+++ b/src-tauri/src/commands/project.rs@@ -2,6 +2,8 @@ use std::fs;use std::path::Path;use chrono::Local;+use tauri::AppHandle;+use tauri_plugin_opener::OpenerExt;use crate::panic_guard::run_guarded;use crate::types::wiki::WikiProject;@@ -241,26 +243,7 @@ pub fn open_project(path: String) -> Result<WikiProject, String> {run_guarded("open_project", || {let root = Path::new(&path);- if !root.exists() {- return Err(format!("Path does not exist: '{}'", path));- }- if !root.is_dir() {- return Err(format!("Path is not a directory: '{}'", path));- }-- // Validate that this looks like a wiki project- if !root.join("schema.md").exists() {- return Err(format!(- "Not a valid wiki project (missing schema.md): '{}'",- path- ));- }- if !root.join("wiki").is_dir() {- return Err(format!(- "Not a valid wiki project (missing wiki/ directory): '{}'",- path- ));- }+ validate_wiki_project_root(root)?;// Derive project name from the directory namelet name = root@@ -277,6 +260,56 @@ pub fn open_project(path: String) -> Result<WikiProject, String> {})}+#[tauri::command]+pub fn open_project_folder(app: AppHandle, path: String) -> Result<(), String> {+ run_guarded("open_project_folder", || {+ let root = Path::new(&path);+ validate_wiki_project_root(root)?;++ let canonical = root+ .canonicalize()+ .map_err(|e| format!("Failed to resolve project path '{}': {}", path, e))?;+ let canonical = canonical.to_string_lossy().to_string();++ match app.opener().open_path(canonical.clone(), None::<&str>) {+ Ok(()) => Ok(()),+ Err(open_err) => app+ .opener()+ .reveal_item_in_dir(canonical)+ .map_err(|reveal_err| {+ format!(+ "Failed to open project folder: {}; reveal fallback also failed: {}",+ open_err, reveal_err+ )+ }),+ }+ })+}++fn validate_wiki_project_root(root: &Path) -> Result<(), String> {+ if !root.exists() {+ return Err(format!("Path does not exist: '{}'", root.display()));+ }+ if !root.is_dir() {+ return Err(format!("Path is not a directory: '{}'", root.display()));+ }++ if !root.join("schema.md").exists() {+ return Err(format!(+ "Not a valid wiki project (missing schema.md): '{}'",+ root.display()+ ));+ }+ if !root.join("wiki").is_dir() {+ return Err(format!(+ "Not a valid wiki project (missing wiki/ directory): '{}'",+ root.display()+ ));+ }++ Ok(())+}+fn write_file_inner(path: std::path::PathBuf, contents: &str) -> Result<(), String> {if let Some(parent) = path.parent() {fs::create_dir_all(parent)diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 207cee6a..7d849c8b 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -73,6 +73,7 @@ pub fn run() {// frontend-generated stream id. Populated by claude_cli_spawn,// drained on process exit or by claude_cli_kill.app.manage(commands::claude_cli::ClaudeCliState::default());+ app.manage(commands::file_sync::FileSyncState::default());Ok(())}).invoke_handler(tauri::generate_handler![@@ -89,6 +90,7 @@ pub fn run() {commands::fs::read_file_as_base64,commands::project::create_project,commands::project::open_project,+ commands::project::open_project_folder,clip_server_status,commands::vectorstore::vector_upsert,commands::vectorstore::vector_search,@@ -107,6 +109,12 @@ pub fn run() {commands::extract_images::extract_office_images_cmd,commands::extract_images::extract_and_save_pdf_images_cmd,commands::extract_images::extract_and_save_office_images_cmd,+ commands::file_sync::start_project_file_watcher,+ commands::file_sync::stop_project_file_watcher,+ commands::file_sync::rescan_project_files,+ commands::file_sync::get_file_change_queue,+ commands::file_sync::retry_file_change_task,+ commands::file_sync::ignore_file_change_task,set_proxy_env,]).on_window_event(|window, event| {diff --git a/src/App.tsx b/src/App.tsxindex f3a6fdc6..39e7137e 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, loadMultimodalConfig, loadOutputLanguage, loadProviderConfigs, loadActivePresetId, loadProxyConfig } from "@/lib/project-store"+import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig, loadMultimodalConfig, loadOutputLanguage, loadProviderConfigs, loadActivePresetId, loadProxyConfig, loadProjectFileSyncEnabled } from "@/lib/project-store"import { loadReviewItems, loadChatHistory } from "@/lib/persist"import { setupAutoSave } from "@/lib/auto-save"import { startClipWatcher } from "@/lib/clip-watcher"@@ -264,17 +264,30 @@ function App() {// Restore ingest queue (resume interrupted tasks). Keyed by the// project's stable UUID so the queue still finds the right project// even if the filesystem path changed since the task was enqueued.- import("@/lib/ingest-queue").then(({ restoreQueue }) => {- restoreQueue(proj.id, proj.path).catch((err) =>- console.error("Failed to restore ingest queue:", err)- )- })+ // Await this before starting file sync: watcher events for raw/sources+ // may enqueue ingest tasks and require an active project queue.+ try {+ const { restoreQueue } = await import("@/lib/ingest-queue")+ await restoreQueue(proj.id, proj.path)+ } catch (err) {+ console.error("Failed to restore ingest queue:", err)+ }// Same handshake for the dedup-merge queue.import("@/lib/dedup-queue").then(({ restoreQueue }) => {restoreQueue(proj.id, proj.path).catch((err) =>console.error("Failed to restore dedup queue:", err))})+ import("@/lib/project-file-sync").then(async ({ startProjectFileSync, stopProjectFileSync }) => {+ const enabled = await loadProjectFileSyncEnabled(proj.id)+ if (enabled) {+ startProjectFileSync(proj).catch((err) =>+ console.error("Failed to start project file sync:", err)+ )+ } else {+ stopProjectFileSync().catch(() => {})+ }+ }).catch((err) => console.error("Failed to configure project file sync:", err))// Notify local clip server of the current project + all recent projectsfetch("http://127.0.0.1:19827/project", {method: "POST",diff --git a/src/commands/file-sync.ts b/src/commands/file-sync.tsnew file mode 100644index 00000000..f12e0374--- /dev/null+++ b/src/commands/file-sync.ts@@ -0,0 +1,69 @@+import { invoke } from "@tauri-apps/api/core"++export type FileChangeKind = "created" | "modified" | "deleted"+export type FileChangeStatus = "pending" | "processing" | "done" | "failed" | "superseded"++export interface FileChangeTask {+ id: string+ projectId: string+ path: string+ kind: FileChangeKind+ status: FileChangeStatus+ hashBefore?: string | null+ hashAfter?: string | null+ size?: number | null+ mtimeMs?: number | null+ createdAt: number+ updatedAt: number+ retryCount: number+ error?: string | null+ needsRerun: boolean+}++export interface FileChangeQueue {+ version: number+ tasks: FileChangeTask[]+}++export interface FileSyncPayload {+ projectId: string+ tasks: FileChangeTask[]+}++export function startProjectFileWatcher(+ projectId: string,+ projectPath: string,+): Promise<FileChangeQueue> {+ return invoke<FileChangeQueue>("start_project_file_watcher", { projectId, projectPath })+}++export function stopProjectFileWatcher(): Promise<void> {+ return invoke<void>("stop_project_file_watcher")+}++export function rescanProjectFiles(+ projectId: string,+ projectPath: string,+): Promise<FileChangeQueue> {+ return invoke<FileChangeQueue>("rescan_project_files", { projectId, projectPath })+}++export function getFileChangeQueue(projectPath: string): Promise<FileChangeQueue> {+ return invoke<FileChangeQueue>("get_file_change_queue", { projectPath })+}++export function retryFileChangeTask(+ projectId: string,+ projectPath: string,+ taskId: string,+): Promise<FileChangeQueue> {+ return invoke<FileChangeQueue>("retry_file_change_task", { projectId, projectPath, taskId })+}++export function ignoreFileChangeTask(+ projectId: string,+ projectPath: string,+ taskId: string,+): Promise<FileChangeQueue> {+ return invoke<FileChangeQueue>("ignore_file_change_task", { projectId, projectPath, taskId })+}diff --git a/src/commands/fs.ts b/src/commands/fs.tsindex bc0ac9e5..64e53b06 100644--- a/src/commands/fs.ts+++ b/src/commands/fs.ts@@ -83,6 +83,10 @@ export async function openProject(path: string): Promise<WikiProject> {return { id, name: raw.name, path: raw.path }}+export async function openProjectFolder(path: string): Promise<void> {+ return invoke<void>("open_project_folder", { path })+}+export async function clipServerStatus(): Promise<string> {return invoke<string>("clip_server_status")}diff --git a/src/components/layout/activity-panel.tsx b/src/components/layout/activity-panel.tsxindex b59b674e..77a581d0 100644--- a/src/components/layout/activity-panel.tsx+++ b/src/components/layout/activity-panel.tsx@@ -6,8 +6,15 @@ import {} from "lucide-react"import { useActivityStore, type ActivityItem } from "@/stores/activity-store"import { useWikiStore } from "@/stores/wiki-store"+import { useFileSyncStore } from "@/stores/file-sync-store"import { normalizePath, getFileName, isAbsolutePath } from "@/lib/path-utils"import { getQueue, getQueueSummary, retryTask, cancelTask, cancelAllTasks, type IngestTask } from "@/lib/ingest-queue"+import {+ ignoreFileChangeTask,+ rescanProjectFiles,+ retryFileChangeTask,+ type FileChangeTask,+} from "@/commands/file-sync"const FILE_TYPE_ICONS: Record<string, typeof FileText> = {sources: BookOpen,@@ -33,6 +40,9 @@ export function ActivityPanel() {const items = useActivityStore((s) => s.items)const clearDone = useActivityStore((s) => s.clearDone)const project = useWikiStore((s) => s.project)+ const fileSyncTasks = useFileSyncStore((s) => s.tasks)+ const setFileSyncTasks = useFileSyncStore((s) => s.setTasks)+ const fileSyncError = useFileSyncStore((s) => s.lastError)const [expanded, setExpanded] = useState(false)const [queueTasks, setQueueTasks] = useState<IngestTask[]>([])const prevRunningRef = useRef(0)@@ -50,6 +60,10 @@ export function ActivityPanel() {const queueSummary = getQueueSummary()const hasQueue = queueSummary.total > 0+ const hasFileSync = fileSyncTasks.length > 0 || Boolean(fileSyncError)+ const fileSyncPending = fileSyncTasks.filter((t) => t.status === "pending").length+ const fileSyncProcessing = fileSyncTasks.filter((t) => t.status === "processing").length+ const fileSyncFailed = fileSyncTasks.filter((t) => t.status === "failed").length// All hooks must be before any conditional return.// retryTask / cancelTask / cancelAllTasks all operate on the currently@@ -57,12 +71,12 @@ export function ActivityPanel() {// — 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) => {+ const handleIngestRetry = useCallback((taskId: string) => {if (!project) returnretryTask(taskId)}, [project])- const handleCancel = useCallback((taskId: string) => {+ const handleIngestCancel = useCallback((taskId: string) => {if (!project) returncancelTask(taskId)}, [project])@@ -79,18 +93,48 @@ export function ActivityPanel() {cancelAllTasks()}, [project, queueSummary.pending, queueSummary.processing])+ const handleFileSyncRescan = useCallback(() => {+ if (!project) return+ rescanProjectFiles(project.id, normalizePath(project.path))+ .then((queue) => {+ setFileSyncTasks(queue.tasks)+ useFileSyncStore.getState().setLastError(null)+ })+ .catch((err) => useFileSyncStore.getState().setLastError(String(err)))+ }, [project, setFileSyncTasks])++ const handleFileSyncRetry = useCallback((taskId: string) => {+ if (!project) return+ retryFileChangeTask(project.id, normalizePath(project.path), taskId)+ .then((queue) => {+ setFileSyncTasks(queue.tasks)+ useFileSyncStore.getState().setLastError(null)+ })+ .catch((err) => useFileSyncStore.getState().setLastError(String(err)))+ }, [project, setFileSyncTasks])++ const handleFileSyncIgnore = useCallback((taskId: string) => {+ if (!project) return+ ignoreFileChangeTask(project.id, normalizePath(project.path), taskId)+ .then((queue) => {+ setFileSyncTasks(queue.tasks)+ useFileSyncStore.getState().setLastError(null)+ })+ .catch((err) => useFileSyncStore.getState().setLastError(String(err)))+ }, [project, setFileSyncTasks])+// Auto-expand when a new task starts runninguseEffect(() => {if (runningCount > 0 && prevRunningRef.current === 0) {setExpanded(true)}- if (hasQueue && !expanded) {+ if ((hasQueue || hasFileSync) && !expanded) {setExpanded(true)}prevRunningRef.current = runningCount- }, [runningCount, hasQueue, expanded])+ }, [runningCount, hasQueue, hasFileSync, expanded])- if (!hasItems && !hasQueue) return null+ if (!hasItems && !hasQueue && !hasFileSync) return nullconst latestItem = items[0]@@ -104,11 +148,17 @@ export function ActivityPanel() {statusText = `Processing: ${latestItem?.title ?? "..."}`} else if (queueSummary.failed > 0) {statusText = `${queueSummary.failed} failed task${queueSummary.failed > 1 ? "s" : ""}`+ } else if (fileSyncProcessing > 0 || fileSyncPending > 0) {+ statusText = `File sync: ${fileSyncProcessing + fileSyncPending} pending`+ } else if (fileSyncFailed > 0) {+ statusText = `File sync: ${fileSyncFailed} failed`+ } else if (fileSyncError) {+ statusText = "File sync failed"} else {statusText = `Done: ${latestItem?.title ?? "All tasks complete"}`}- const isActive = runningCount > 0 || queueSummary.processing > 0 || queueSummary.pending > 0+ const isActive = runningCount > 0 || queueSummary.processing > 0 || queueSummary.pending > 0 || fileSyncProcessing > 0 || fileSyncPending > 0return (<div className="border-t bg-muted/30">@@ -118,7 +168,7 @@ export function ActivityPanel() {>{isActive ? (<Loader2 className="h-3 w-3 animate-spin shrink-0" />- ) : queueSummary.failed > 0 ? (+ ) : queueSummary.failed > 0 || fileSyncFailed > 0 || fileSyncError ? (<AlertCircle className="h-3 w-3 shrink-0 text-destructive" />) : (<CheckCircle2 className="h-3 w-3 shrink-0 text-emerald-500" />@@ -133,6 +183,32 @@ export function ActivityPanel() {{expanded && (<div className="max-h-64 overflow-y-auto border-t">+ {hasFileSync && (+ <div className="border-b border-border/50 px-3 py-1.5">+ <div className="mb-1 flex items-center justify-between gap-2 text-[10px] text-muted-foreground">+ <span>File Sync</span>+ <button+ onClick={handleFileSyncRescan}+ className="rounded px-1.5 py-0.5 text-[10px] hover:bg-accent hover:text-foreground"+ title="Scan project files for external changes"+ >+ Rescan+ </button>+ </div>+ {fileSyncError && (+ <div className="mb-1 truncate text-[10px] text-destructive">{fileSyncError}</div>+ )}+ {fileSyncTasks.map((task) => (+ <FileSyncRow+ key={task.id}+ task={task}+ onRetry={handleFileSyncRetry}+ onIgnore={handleFileSyncIgnore}+ />+ ))}+ </div>+ )}+{/* Queue progress bar */}{hasQueue && (queueSummary.processing > 0 || queueSummary.pending > 0) && (<div className="px-3 py-1.5 border-b border-border/50">@@ -162,13 +238,13 @@ export function ActivityPanel() {{/* Queue tasks */}{queueTasks.filter((t) => t.status === "processing").map((task) => (- <QueueRow key={task.id} task={task} onRetry={handleRetry} onCancel={handleCancel} />+ <QueueRow key={task.id} task={task} onRetry={handleIngestRetry} onCancel={handleIngestCancel} />))}{queueTasks.filter((t) => t.status === "pending").map((task) => (- <QueueRow key={task.id} task={task} onRetry={handleRetry} onCancel={handleCancel} />+ <QueueRow key={task.id} task={task} onRetry={handleIngestRetry} onCancel={handleIngestCancel} />))}{queueTasks.filter((t) => t.status === "failed").map((task) => (- <QueueRow key={task.id} task={task} onRetry={handleRetry} onCancel={handleCancel} />+ <QueueRow key={task.id} task={task} onRetry={handleIngestRetry} onCancel={handleIngestCancel} />))}{/* Activity items */}@@ -181,7 +257,7 @@ export function ActivityPanel() {<ActivityRowkey={item.id}item={item}- onCancel={matchingTask ? () => handleCancel(matchingTask.id) : undefined}+ onCancel={matchingTask ? () => handleIngestCancel(matchingTask.id) : undefined}/>)})}@@ -244,6 +320,48 @@ function QueueRow({ task, onRetry, onCancel }: { task: IngestTask; onRetry: (id:)}+function FileSyncRow({ task, onRetry, onIgnore }: { task: FileChangeTask; onRetry: (id: string) => void; onIgnore: (id: string) => void }) {+ const fileName = getFileName(task.path)+ const kindLabel = task.kind.charAt(0).toUpperCase() + task.kind.slice(1)++ return (+ <div className="py-1.5 text-xs">+ <div className="flex items-center gap-2">+ <div className="shrink-0">+ {task.status === "processing" && <Loader2 className="h-3 w-3 animate-spin text-primary" />}+ {task.status === "pending" && <Clock className="h-3 w-3 text-muted-foreground" />}+ {task.status === "failed" && <AlertCircle className="h-3 w-3 text-destructive" />}+ </div>+ <div className="min-w-0 flex-1">+ <div className="truncate font-medium">{fileName}</div>+ <div className="truncate text-[10px] text-muted-foreground/70">{kindLabel} - {task.path}</div>+ {task.status === "failed" && task.error && (+ <div className="mt-0.5 truncate text-[10px] text-destructive">{task.error}</div>+ )}+ </div>+ {task.status === "failed" && (+ <div className="flex shrink-0 items-center gap-1">+ <button+ onClick={() => onRetry(task.id)}+ className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"+ title="Retry"+ >+ <RotateCcw className="h-3 w-3" />+ </button>+ <button+ onClick={() => onIgnore(task.id)}+ className="rounded p-0.5 text-muted-foreground hover:bg-destructive/20 hover:text-destructive"+ title="Ignore"+ >+ <X className="h-3 w-3" />+ </button>+ </div>+ )}+ </div>+ </div>+ )+}+function ActivityRow({ item, onCancel }: { item: ActivityItem; onCancel?: () => void }) {const setSelectedFile = useWikiStore((s) => s.setSelectedFile)const project = useWikiStore((s) => s.project)diff --git a/src/components/layout/file-tree.tsx b/src/components/layout/file-tree.tsxindex 45dfcd9a..185cae63 100644--- a/src/components/layout/file-tree.tsx+++ b/src/components/layout/file-tree.tsx@@ -1,9 +1,11 @@import { useState } from "react"-import { ChevronRight, ChevronDown, File, Folder } from "lucide-react"+import { ChevronRight, ChevronDown, File, Folder, FolderOpen } from "lucide-react"+import { message } from "@tauri-apps/plugin-dialog"import { ScrollArea } from "@/components/ui/scroll-area"import { useWikiStore } from "@/stores/wiki-store"import type { FileNode } from "@/types/wiki"import { useTranslation } from "react-i18next"+import { openProjectFolder } from "@/commands/fs"function TreeNode({ node, depth }: { node: FileNode; depth: number }) {const [expanded, setExpanded] = useState(depth < 1)@@ -57,6 +59,27 @@ export function FileTree() {const fileTree = useWikiStore((s) => s.fileTree)const project = useWikiStore((s) => s.project)+ const handleOpenProjectFolder = async () => {+ if (!project) return++ try {+ await openProjectFolder(project.path)+ } catch (err) {+ console.error("[FileTree] open project folder failed:", err)+ await message(+ t("fileTree.openProjectFolderFailed", {+ defaultValue: "Failed to open the project folder.",+ }),+ {+ title: t("fileTree.openProjectFolder", {+ defaultValue: "Open project folder",+ }),+ kind: "error",+ },+ )+ }+ }+if (!project) {return (<div className="flex h-full items-center justify-center p-4 text-sm text-muted-foreground">@@ -66,15 +89,30 @@ export function FileTree() {}return (- <ScrollArea className="h-full min-w-0 overflow-hidden">- <div className="p-2">- <div className="mb-2 px-2 text-xs font-semibold uppercase text-muted-foreground">- {project.name}+ <div className="flex h-full min-w-0 flex-col overflow-hidden">+ <ScrollArea className="min-h-0 flex-1 overflow-hidden">+ <div className="p-2">+ <div className="mb-2 px-2 text-xs font-semibold uppercase text-muted-foreground">+ {project.name}+ </div>+ {fileTree.map((node) => (+ <TreeNode key={node.path} node={node} depth={0} />+ ))}</div>- {fileTree.map((node) => (- <TreeNode key={node.path} node={node} depth={0} />- ))}+ </ScrollArea>+ <div className="shrink-0 border-t p-2">+ <button+ type="button"+ onClick={() => void handleOpenProjectFolder()}+ className="flex w-full items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-accent-foreground"+ title={project.path}+ >+ <FolderOpen className="h-3.5 w-3.5 shrink-0" />+ <span className="truncate">+ {t("fileTree.openProjectFolder", { defaultValue: "Open project folder" })}+ </span>+ </button></div>- </ScrollArea>+ </div>)}diff --git a/src/components/settings/sections/maintenance-section.tsx b/src/components/settings/sections/maintenance-section.tsxindex dc7ccc5c..4b5151ad 100644--- a/src/components/settings/sections/maintenance-section.tsx+++ b/src/components/settings/sections/maintenance-section.tsx@@ -25,6 +25,12 @@ import {type DedupTask,} from "@/lib/dedup-queue"import type { DuplicateGroup } from "@/lib/dedup"+import type { SettingsDraft, DraftSetter } from "../settings-types"++interface Props {+ draft: SettingsDraft+ setDraft: DraftSetter+}interface GroupUiEntry {group: DuplicateGroup@@ -43,7 +49,7 @@ function findTaskForGroup(return tasks.find((t) => groupKey(t.group.slugs) === key)}-export function MaintenanceSection() {+export function MaintenanceSection({ draft, setDraft }: Props) {const { t } = useTranslation()const llmConfig = useWikiStore((s) => s.llmConfig)const project = useWikiStore((s) => s.project)@@ -207,6 +213,39 @@ export function MaintenanceSection() {</p></div>+ <div className="rounded-lg border border-border/60 bg-muted/20 p-4">+ <label className="flex items-start gap-3">+ <input+ id="project-file-sync"+ type="checkbox"+ checked={draft.projectFileSyncEnabled}+ onChange={(e) => setDraft("projectFileSyncEnabled", e.target.checked)}+ disabled={!projectReady}+ className="mt-1 h-4 w-4"+ />+ <div className="space-y-1">+ <span className="text-sm font-semibold">+ {t("settings.sections.maintenance.fileSync.title", {+ defaultValue: "Monitor project folder for external changes",+ })}+ </span>+ <p className="text-xs leading-relaxed text-muted-foreground">+ {t("settings.sections.maintenance.fileSync.description", {+ defaultValue:+ "Automatically refresh the file tree when files change outside the app. New or modified ingestable files under raw/sources are added to the ingest queue.",+ })}+ </p>+ {!projectReady && (+ <p className="text-xs text-muted-foreground">+ {t("settings.sections.maintenance.fileSync.noProject", {+ defaultValue: "Open a project to change this project-level setting.",+ })}+ </p>+ )}+ </div>+ </label>+ </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/settings-types.ts b/src/components/settings/settings-types.tsindex c5ffa4d7..30030386 100644--- a/src/components/settings/settings-types.ts+++ b/src/components/settings/settings-types.ts@@ -52,6 +52,9 @@ export interface SettingsDraft {// UIuiLanguage: string++ // Project sync+ projectFileSyncEnabled: boolean}export type DraftSetter = <K extends keyof SettingsDraft>(diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsxindex 7f9de82c..1d15de0b 100644--- a/src/components/settings/settings-view.tsx+++ b/src/components/settings/settings-view.tsx@@ -18,7 +18,7 @@ import { Button } from "@/components/ui/button"import { useWikiStore } from "@/stores/wiki-store"import { useChatStore } from "@/stores/chat-store"import { useUpdateStore, hasAvailableUpdate } from "@/stores/update-store"-import { saveLanguage } from "@/lib/project-store"+import { loadProjectFileSyncEnabled, 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"@@ -73,6 +73,7 @@ function initialDraft(proxy: ReturnType<typeof useWikiStore.getState>["proxyConfig"],maxHistoryMessages: number,uiLanguage: string,+ projectFileSyncEnabled: boolean,): SettingsDraft {return {provider: llm.provider,@@ -104,6 +105,7 @@ function initialDraft(proxyUrl: proxy.url,proxyBypassLocal: proxy.bypassLocal,uiLanguage,+ projectFileSyncEnabled,}}@@ -134,6 +136,7 @@ export function SettingsView() {const [active, setActive] = useState<CategoryId>("llm")const [saved, setSaved] = useState(false)+ const [projectFileSyncEnabled, setProjectFileSyncEnabled] = useState(true)const [draft, setDraftState] = useState<SettingsDraft>(() =>initialDraft(llmConfig,@@ -143,9 +146,26 @@ export function SettingsView() {proxyConfig,maxHistoryMessages,i18n.language,+ projectFileSyncEnabled,),)+ useEffect(() => {+ let cancelled = false+ loadProjectFileSyncEnabled(project?.id).then((enabled) => {+ if (cancelled) return+ setProjectFileSyncEnabled(enabled)+ setDraftState((prev) => ({ ...prev, projectFileSyncEnabled: enabled }))+ }).catch(() => {+ if (cancelled) return+ setProjectFileSyncEnabled(true)+ setDraftState((prev) => ({ ...prev, projectFileSyncEnabled: true }))+ })+ return () => {+ cancelled = true+ }+ }, [project?.id])+// Resync draft from store if it changes out-of-band (e.g. project switch).// IMPORTANT: keep the current draft.uiLanguage instead of re-reading// `i18n.language`. handleSave calls multiple zustand setters before it@@ -164,6 +184,7 @@ export function SettingsView() {proxyConfig,maxHistoryMessages,prev.uiLanguage,+ projectFileSyncEnabled,),)}, [@@ -173,6 +194,7 @@ export function SettingsView() {outputLanguage,proxyConfig,maxHistoryMessages,+ projectFileSyncEnabled,])const setDraft: DraftSetter = useCallback((key, value) => {@@ -186,6 +208,7 @@ export function SettingsView() {saveMultimodalConfig,saveOutputLanguage,saveProxyConfig,+ saveProjectFileSyncEnabled,} = await import("@/lib/project-store")const newLlm = {@@ -240,6 +263,18 @@ export function SettingsView() {await saveOutputLanguage(draft.outputLanguage as typeof outputLanguage, project?.id)setProxyConfig(newProxy)await saveProxyConfig(newProxy)+ await saveProjectFileSyncEnabled(draft.projectFileSyncEnabled, project?.id)+ setProjectFileSyncEnabled(draft.projectFileSyncEnabled)+ if (project) {+ const { startProjectFileSync, stopProjectFileSync } = await import("@/lib/project-file-sync")+ if (draft.projectFileSyncEnabled) {+ await startProjectFileSync(project).catch((err) =>+ console.error("Failed to start project file sync:", err)+ )+ } else {+ await stopProjectFileSync()+ }+ }// Apply the proxy env vars LIVE so the next outbound request// picks them up — no app restart needed. tauri-plugin-http// builds a fresh reqwest client per fetch and reqwest reads@@ -289,7 +324,7 @@ export function SettingsView() {case "interface":return <InterfaceSection draft={draft} setDraft={setDraft} />case "maintenance":- return <MaintenanceSection />+ return <MaintenanceSection draft={draft} setDraft={setDraft} />case "changelog":return <ChangelogSection />case "about":@@ -356,8 +391,8 @@ export function SettingsView() {{/* Global Save bar hidden for sections that persist inline:- "llm" saves per-row on every edit (independent per-preset state)- - "about" / "maintenance" have no draft-bound fields */}- {active !== "about" && active !== "llm" && active !== "maintenance" && (+ - "about" has no draft-bound 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">diff --git a/src/lib/ingest-queue.integration.test.ts b/src/lib/ingest-queue.integration.test.tsindex 2b155033..a434d147 100644--- a/src/lib/ingest-queue.integration.test.ts+++ b/src/lib/ingest-queue.integration.test.ts@@ -98,6 +98,24 @@ describe("ingest-queue persistence — write", () => {expect(parsed[0].sourcePath).toBe("raw/sources/a.md")})+ it("deduplicates repeated pending tasks for the same source", async () => {+ await enqueueBatch(TEST_ID_A, [+ { sourcePath: "raw/sources/a.md", folderContext: "" },+ { sourcePath: `${tmp.path}/raw/sources/a.md`, folderContext: "" },+ ])+ await waitFor(async () => {+ try {+ const parsed = JSON.parse(await readQueueFile())+ return parsed.length === 1+ } catch {+ return false+ }+ })+ const parsed = JSON.parse(await readQueueFile())+ expect(parsed).toHaveLength(1)+ expect(parsed[0].sourcePath).toBe("raw/sources/a.md")+ })+it("persists Unicode source paths without corruption", async () => {await enqueueBatch(TEST_ID_A, [{ sourcePath: "raw/sources/注意力机制.pdf", folderContext: "AI研究 > 论文" },diff --git a/src/lib/ingest-queue.ts b/src/lib/ingest-queue.tsindex 7b2b42dd..d8d1b1b9 100644--- a/src/lib/ingest-queue.ts+++ b/src/lib/ingest-queue.ts@@ -80,6 +80,70 @@ function generateId(): string {return `ingest-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`}+function normalizeSourcePathForQueue(sourcePath: string): string {+ const normalized = normalizePath(sourcePath)+ if (currentProjectPath && normalized.startsWith(`${currentProjectPath}/`)) {+ return normalized.slice(currentProjectPath.length + 1)+ }+ return normalized+}++function sameQueuedSourcePath(a: string, b: string): boolean {+ return normalizeSourcePathForQueue(a) === normalizeSourcePathForQueue(b)+}++function upsertQueuedIngestTask(+ projectId: string,+ sourcePath: string,+ folderContext: string,+): string {+ const normalizedSourcePath = normalizeSourcePathForQueue(sourcePath)+ const pendingOrFailed = queue.find((t) =>+ t.projectId === projectId &&+ (t.status === "pending" || t.status === "failed") &&+ sameQueuedSourcePath(t.sourcePath, normalizedSourcePath)+ )++ if (pendingOrFailed) {+ pendingOrFailed.sourcePath = normalizedSourcePath+ pendingOrFailed.folderContext = folderContext || pendingOrFailed.folderContext+ pendingOrFailed.status = "pending"+ pendingOrFailed.error = null+ pendingOrFailed.retryCount = 0+ return pendingOrFailed.id+ }++ const processing = queue.find((t) =>+ t.projectId === projectId &&+ t.status === "processing" &&+ sameQueuedSourcePath(t.sourcePath, normalizedSourcePath)+ )+ const pendingRerun = processing+ ? queue.find((t) =>+ t.projectId === projectId &&+ t.status === "pending" &&+ sameQueuedSourcePath(t.sourcePath, normalizedSourcePath)+ )+ : null++ if (pendingRerun) {+ return pendingRerun.id+ }++ const task: IngestTask = {+ id: generateId(),+ projectId,+ sourcePath: normalizedSourcePath,+ folderContext,+ status: "pending",+ addedAt: Date.now(),+ error: null,+ retryCount: 0,+ }+ queue.push(task)+ return task.id+}+/*** Delete files written by a cancelled / failed ingest, AND drop the* matching pages' chunks from LanceDB. Called from the cancel paths@@ -123,23 +187,12 @@ export async function enqueueIngest()}- const task: IngestTask = {- id: generateId(),- projectId,- sourcePath,- folderContext,- status: "pending",- addedAt: Date.now(),- error: null,- retryCount: 0,- }-- queue.push(task)+ const id = upsertQueuedIngestTask(projectId, sourcePath, folderContext)await saveQueue(currentProjectPath)processNext(currentProjectId)- return task.id+ return id}/**@@ -158,18 +211,7 @@ export async function enqueueBatch(const ids: string[] = []for (const file of files) {- const task: IngestTask = {- id: generateId(),- projectId,- sourcePath: file.sourcePath,- folderContext: file.folderContext,- status: "pending",- addedAt: Date.now(),- error: null,- retryCount: 0,- }- queue.push(task)- ids.push(task.id)+ ids.push(upsertQueuedIngestTask(projectId, file.sourcePath, file.folderContext))}await saveQueue(currentProjectPath)diff --git a/src/lib/project-file-sync.test.ts b/src/lib/project-file-sync.test.tsnew file mode 100644index 00000000..31fac8bb--- /dev/null+++ b/src/lib/project-file-sync.test.ts@@ -0,0 +1,246 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++const mocks = vi.hoisted(() => {+ const resolvers: Array<(value: { version: number; tasks: Array<{ id: string; projectId: string; path: string; kind: "modified"; status: "pending"; createdAt: number; updatedAt: number; retryCount: number; needsRerun: boolean }> }) => void> = []+ const listeners: Record<string, (event: { payload: unknown }) => void> = {}+ return {+ listen: vi.fn(async (event: string, cb: (event: { payload: unknown }) => void) => {+ listeners[event] = cb+ return vi.fn(() => {+ delete listeners[event]+ })+ }),+ emit: (event: string, payload: unknown) => listeners[event]?.({ payload }),+ stopProjectFileWatcher: vi.fn(async () => undefined),+ startProjectFileWatcher: vi.fn(() => new Promise((resolve) => {+ resolvers.push(resolve)+ })),+ resolveStart: (index: number, projectId: string) => resolvers[index]?.({+ version: 1,+ tasks: [{+ id: "t1",+ projectId,+ path: "raw/sources/a.md",+ kind: "modified",+ status: "pending",+ createdAt: 1,+ updatedAt: 1,+ retryCount: 0,+ needsRerun: false,+ }],+ }),+ clearResolvers: () => {+ resolvers.length = 0+ },+ listDirectory: vi.fn(async (_path?: string) => [] as Array<{+ name: string+ path: string+ is_dir: boolean+ children?: Array<{ name: string; path: string; is_dir: boolean }>+ }>),+ readFile: vi.fn(async (_path?: string) => ""),+ writeFile: vi.fn(async () => undefined),+ deleteFile: vi.fn(async () => undefined),+ findRelatedWikiPages: vi.fn(async () => []),+ enqueueBatch: vi.fn(async () => []),+ removeFromIngestCache: vi.fn(async () => undefined),+ removePageEmbedding: vi.fn(async () => undefined),+ cascadeDeleteWikiPagesWithRefs: vi.fn(async () => ({ deletedPaths: [], rewrittenFiles: 0 })),+ }+})++vi.mock("@tauri-apps/api/event", () => ({+ listen: mocks.listen,+}))++vi.mock("@/commands/file-sync", () => ({+ startProjectFileWatcher: mocks.startProjectFileWatcher,+ stopProjectFileWatcher: mocks.stopProjectFileWatcher,+}))++vi.mock("@/commands/fs", () => ({+ listDirectory: mocks.listDirectory,+ readFile: mocks.readFile,+ writeFile: mocks.writeFile,+ deleteFile: mocks.deleteFile,+ findRelatedWikiPages: mocks.findRelatedWikiPages,+}))++vi.mock("@/lib/ingest-queue", () => ({+ enqueueBatch: mocks.enqueueBatch,+}))++vi.mock("@/lib/ingest-cache", () => ({+ removeFromIngestCache: mocks.removeFromIngestCache,+}))++vi.mock("@/lib/embedding", () => ({+ removePageEmbedding: mocks.removePageEmbedding,+}))++vi.mock("@/lib/wiki-page-delete", () => ({+ cascadeDeleteWikiPagesWithRefs: mocks.cascadeDeleteWikiPagesWithRefs,+}))++describe("project file sync", () => {+ beforeEach(async () => {+ vi.useRealTimers()+ vi.clearAllMocks()+ mocks.clearResolvers()+ const { useWikiStore } = await import("@/stores/wiki-store")+ const { useFileSyncStore } = await import("@/stores/file-sync-store")+ await import("@/lib/project-file-sync").then((m) => m.stopProjectFileSync())+ useWikiStore.getState().setProject(null)+ useFileSyncStore.getState().clear()+ })++ it("does not apply a stale start result after the active project changes", async () => {+ const { startProjectFileSync, stopProjectFileSync } = await import("@/lib/project-file-sync")+ const { useWikiStore } = await import("@/stores/wiki-store")+ const { useFileSyncStore } = await import("@/stores/file-sync-store")++ const projectA = { id: "A", name: "A", path: "/tmp/a" }+ useWikiStore.getState().setProject(projectA)+ const start = startProjectFileSync(projectA)++ await vi.waitFor(() => {+ expect(mocks.startProjectFileWatcher).toHaveBeenCalledTimes(1)+ })+ const projectB = { id: "B", name: "B", path: "/tmp/b" }+ useWikiStore.getState().setProject(projectB)+ await stopProjectFileSync()+ mocks.resolveStart(0, "A")+ await start++ expect(useFileSyncStore.getState().tasks).toEqual([])+ })++ it("enqueues created and modified raw source files for ingest", async () => {+ vi.useFakeTimers()+ const { startProjectFileSync } = await import("@/lib/project-file-sync")+ const { useWikiStore } = await import("@/stores/wiki-store")++ const project = { id: "A", name: "A", path: "/tmp/a" }+ useWikiStore.getState().setProject(project)+ void startProjectFileSync(project)++ await vi.waitFor(() => {+ expect(mocks.listen).toHaveBeenCalledTimes(2)+ })++ mocks.emit("file-sync://changed", {+ projectId: "A",+ tasks: [+ {+ id: "t1",+ projectId: "A",+ path: "raw/sources/report.pdf",+ kind: "created",+ status: "done",+ createdAt: 1,+ updatedAt: 1,+ retryCount: 0,+ needsRerun: false,+ },+ {+ id: "t2",+ projectId: "A",+ path: "raw/sources/image.png",+ kind: "created",+ status: "done",+ createdAt: 1,+ updatedAt: 1,+ retryCount: 0,+ needsRerun: false,+ },+ {+ id: "t3",+ projectId: "A",+ path: "wiki/index.md",+ kind: "modified",+ status: "done",+ createdAt: 1,+ updatedAt: 1,+ retryCount: 0,+ needsRerun: false,+ },+ ],+ })++ await vi.advanceTimersByTimeAsync(250)++ expect(mocks.enqueueBatch).toHaveBeenCalledWith("A", [+ { sourcePath: "raw/sources/report.pdf", folderContext: "" },+ ])+ })++ it("removes an externally deleted raw source from every wiki page sources field", async () => {+ vi.useFakeTimers()+ const { startProjectFileSync } = await import("@/lib/project-file-sync")+ const { useWikiStore } = await import("@/stores/wiki-store")++ const project = { id: "A", name: "A", path: "/tmp/a" }+ useWikiStore.getState().setProject(project)+ mocks.listDirectory.mockImplementation(async (path?: string) => {+ if (path === "/tmp/a/wiki") {+ return [+ {+ name: "concepts",+ path: "/tmp/a/wiki/concepts",+ is_dir: true,+ children: [+ {+ name: "mind.md",+ path: "/tmp/a/wiki/concepts/mind.md",+ is_dir: false,+ },+ ],+ },+ ]+ }+ return []+ })+ mocks.readFile.mockImplementation(async (path?: string) => {+ if (path === "/tmp/a/wiki/concepts/mind.md") {+ return [+ "---",+ 'sources: ["life_is_a_mind_game.md", "other.md"]',+ "---",+ "# Mind",+ ].join("\n")+ }+ if (path === "/tmp/a/wiki/log.md") return "# Wiki Log\n"+ return ""+ })++ void startProjectFileSync(project)+ await vi.waitFor(() => {+ expect(mocks.listen).toHaveBeenCalledTimes(2)+ })++ mocks.emit("file-sync://changed", {+ projectId: "A",+ tasks: [+ {+ id: "t1",+ projectId: "A",+ path: "raw/sources/life_is_a_mind_game.md",+ kind: "deleted",+ status: "done",+ createdAt: 1,+ updatedAt: 1,+ retryCount: 0,+ needsRerun: false,+ },+ ],+ })++ await vi.advanceTimersByTimeAsync(250)+ await vi.waitFor(() => {+ expect(mocks.writeFile).toHaveBeenCalledWith(+ "/tmp/a/wiki/concepts/mind.md",+ expect.stringContaining('sources: ["other.md"]'),+ )+ })+ })+})diff --git a/src/lib/project-file-sync.ts b/src/lib/project-file-sync.tsnew file mode 100644index 00000000..4abafed3--- /dev/null+++ b/src/lib/project-file-sync.ts@@ -0,0 +1,393 @@+import { listen, type UnlistenFn } from "@tauri-apps/api/event"+import { deleteFile, findRelatedWikiPages, readFile, listDirectory, writeFile } from "@/commands/fs"+import {+ startProjectFileWatcher,+ stopProjectFileWatcher,+ type FileSyncPayload,+} from "@/commands/file-sync"+import { useFileSyncStore } from "@/stores/file-sync-store"+import { useWikiStore } from "@/stores/wiki-store"+import { normalizePath } from "@/lib/path-utils"+import type { WikiProject } from "@/types/wiki"+import { enqueueBatch } from "@/lib/ingest-queue"+import type { FileChangeTask } from "@/commands/file-sync"+import { decidePageFate } from "@/lib/source-delete-decision"+import { parseSources, writeSources } from "@/lib/sources-merge"+import { removeFromIngestCache } from "@/lib/ingest-cache"+import { getFileStem } from "@/lib/path-utils"+import { removePageEmbedding } from "@/lib/embedding"+import {+ buildDeletedKeys,+ cleanIndexListing,+ stripDeletedWikilinks,+} from "@/lib/wiki-cleanup"+import {+ parseFrontmatterArray,+ writeFrontmatterArray,+} from "@/lib/sources-merge"+import type { FileNode } from "@/types/wiki"++let unlistenQueue: UnlistenFn | null = null+let unlistenChanged: UnlistenFn | null = null+let startSeq = 0+let refreshTimer: ReturnType<typeof setTimeout> | null = null+let pendingRefreshPaths = new Set<string>()+let pendingChangeTasks = new Map<string, FileChangeTask>()++const INGESTABLE_SOURCE_EXTENSIONS = new Set([+ "md",+ "mdx",+ "txt",+ "pdf",+ "docx",+ "pptx",+ "xlsx",+ "xls",+ "csv",+ "json",+ "html",+ "htm",+ "rtf",+ "xml",+ "yaml",+ "yml",+])++export async function startProjectFileSync(project: WikiProject): Promise<void> {+ await stopProjectFileSync()+ const seq = ++startSeq+ useFileSyncStore.getState().setRunning(true)+ useFileSyncStore.getState().setLastError(null)++ unlistenQueue = await listen<FileSyncPayload>("file-sync://queue-updated", (event) => {+ if (event.payload.projectId !== useWikiStore.getState().project?.id) return+ useFileSyncStore.getState().setTasks(event.payload.tasks)+ })++ unlistenChanged = await listen<FileSyncPayload>("file-sync://changed", (event) => {+ const current = useWikiStore.getState().project+ if (!current || event.payload.projectId !== current.id) return+ scheduleRefreshAfterFileChanges(event.payload.tasks)+ })++ try {+ const queue = await startProjectFileWatcher(project.id, normalizePath(project.path))+ if (seq !== startSeq || project.id !== useWikiStore.getState().project?.id) return+ useFileSyncStore.getState().setTasks(queue.tasks)+ } catch (err) {+ unlistenQueue?.()+ unlistenChanged?.()+ unlistenQueue = null+ unlistenChanged = null+ useFileSyncStore.getState().setLastError(String(err))+ throw err+ } finally {+ if (seq === startSeq) {+ useFileSyncStore.getState().setRunning(false)+ }+ }+}++export async function stopProjectFileSync(): Promise<void> {+ startSeq+++ unlistenQueue?.()+ unlistenChanged?.()+ unlistenQueue = null+ unlistenChanged = null+ if (refreshTimer) {+ clearTimeout(refreshTimer)+ refreshTimer = null+ }+ pendingRefreshPaths.clear()+ pendingChangeTasks.clear()+ useFileSyncStore.getState().clear()+ try {+ await stopProjectFileWatcher()+ } catch {+ // App startup/project switching should not fail just because a stale+ // watcher has already been dropped by the backend.+ }+}++function scheduleRefreshAfterFileChanges(tasks: FileChangeTask[]): void {+ for (const task of tasks) {+ pendingRefreshPaths.add(task.path)+ pendingChangeTasks.set(task.path, task)+ }+ if (refreshTimer) return+ refreshTimer = setTimeout(() => {+ refreshTimer = null+ const project = useWikiStore.getState().project+ if (!project) {+ pendingRefreshPaths.clear()+ pendingChangeTasks.clear()+ return+ }+ const paths = [...pendingRefreshPaths]+ const tasks = [...pendingChangeTasks.values()]+ pendingRefreshPaths.clear()+ pendingChangeTasks.clear()+ void refreshAfterFileChanges(project, paths)+ void enqueueRawSourceChanges(project, tasks)+ void cleanupDeletedFiles(project, tasks)+ }, 250)+}++async function refreshAfterFileChanges(project: WikiProject, relativePaths: string[]): Promise<void> {+ const pp = normalizePath(project.path)+ const store = useWikiStore.getState()+ try {+ const tree = await listDirectory(pp)+ useWikiStore.getState().setFileTree(tree)+ } catch (err) {+ console.warn("[file-sync] failed to refresh file tree:", err)+ }++ store.bumpDataVersion()++ const selected = store.selectedFile ? normalizePath(store.selectedFile) : null+ if (!selected) return++ const selectedRel = selected.startsWith(`${pp}/`) ? selected.slice(pp.length + 1) : selected+ if (!relativePaths.includes(selectedRel)) return++ try {+ const content = await readFile(selected)+ useWikiStore.getState().setFileContent(content)+ } catch {+ useWikiStore.getState().setSelectedFile(null)+ useWikiStore.getState().setFileContent("")+ }+}++async function enqueueRawSourceChanges(project: WikiProject, tasks: FileChangeTask[]): Promise<void> {+ const files = tasks+ .filter((task) => task.projectId === project.id)+ .filter((task) => task.kind === "created" || task.kind === "modified")+ .filter((task) => isIngestableRawSource(task.path))+ .map((task) => ({+ sourcePath: task.path,+ folderContext: folderContextForRawSource(task.path),+ }))++ if (files.length === 0) return++ try {+ await enqueueBatch(project.id, files)+ } catch (err) {+ console.error("[file-sync] failed to enqueue raw source ingest:", err)+ }+}++function isIngestableRawSource(relativePath: string): boolean {+ const path = normalizePath(relativePath)+ if (!path.startsWith("raw/sources/")) return false+ const fileName = path.split("/").pop() ?? ""+ if (!fileName || fileName.startsWith(".")) return false+ const ext = fileName.includes(".") ? fileName.split(".").pop()?.toLowerCase() : ""+ return ext ? INGESTABLE_SOURCE_EXTENSIONS.has(ext) : false+}++function folderContextForRawSource(relativePath: string): string {+ const rel = normalizePath(relativePath).slice("raw/sources/".length)+ const parts = rel.split("/")+ parts.pop()+ return parts.join(" > ")+}++async function cleanupDeletedFiles(project: WikiProject, tasks: FileChangeTask[]): Promise<void> {+ const deleted = tasks+ .filter((task) => task.projectId === project.id && task.kind === "deleted")+ .map((task) => normalizePath(task.path))++ if (deleted.length === 0) return++ const rawSources = deleted.filter(isRawSourcePathForCascade)+ const wikiPages = deleted.filter(isWikiPageForCascade)++ for (const rel of rawSources) {+ try {+ await cleanupExternallyDeletedRawSource(project.path, rel)+ } catch (err) {+ console.error(`[file-sync] failed to clean deleted raw source ${rel}:`, err)+ }+ }++ if (wikiPages.length > 0) {+ try {+ await cleanupExternallyDeletedWikiPages(project.path, wikiPages)+ } catch (err) {+ console.error("[file-sync] failed to clean deleted wiki pages:", err)+ }+ }+}++function isRawSourcePathForCascade(relativePath: string): boolean {+ const path = normalizePath(relativePath)+ if (!path.startsWith("raw/sources/")) return false+ if (path.includes("/.cache/")) return false+ const fileName = path.split("/").pop() ?? ""+ return Boolean(fileName && !fileName.startsWith("."))+}++function isWikiPageForCascade(relativePath: string): boolean {+ const path = normalizePath(relativePath)+ if (!path.startsWith("wiki/") || !path.endsWith(".md")) return false+ if (path === "wiki/index.md" || path === "wiki/log.md" || path === "wiki/overview.md") {+ return false+ }+ return !path.startsWith("wiki/media/")+}++async function cleanupExternallyDeletedRawSource(+ projectPath: string,+ relativePath: string,+): Promise<void> {+ const pp = normalizePath(projectPath)+ const fileName = relativePath.split("/").pop() ?? ""+ if (!fileName) return++ const relatedPages = await findRelatedWikiPages(pp, fileName)+ const candidatePages = new Set(relatedPages)+ try {+ const wikiTree = await listDirectory(`${pp}/wiki`)+ for (const file of flattenMd(wikiTree)) {+ try {+ const content = await readFile(file.path)+ if (parseSources(content).some((source) => sourceMatchesDeletedFile(source, fileName))) {+ candidatePages.add(file.path)+ }+ } catch {+ // Ignore unreadable pages; the related-pages pass may still cover them.+ }+ }+ } catch (err) {+ console.warn("[file-sync] failed to scan wiki sources during source delete cleanup:", err)+ }++ const pagesToDelete: string[] = []+ let keptCount = 0++ for (const pagePath of candidatePages) {+ try {+ const content = await readFile(pagePath)+ const decision = decidePageFate(parseSources(content), fileName)+ if (decision.action === "keep") {+ await writeFile(pagePath, writeSources(content, decision.updatedSources))+ keptCount+++ } else if (decision.action === "delete") {+ pagesToDelete.push(pagePath)+ }+ } catch (err) {+ console.warn(`[file-sync] failed to process related page ${pagePath}:`, err)+ }+ }++ if (pagesToDelete.length > 0) {+ const { cascadeDeleteWikiPagesWithRefs } = await import("@/lib/wiki-page-delete")+ await cascadeDeleteWikiPagesWithRefs(pp, pagesToDelete)+ }++ try {+ await deleteFile(`${pp}/raw/sources/.cache/${fileName}.txt`)+ } catch {+ // cache may not exist+ }++ try {+ await removeFromIngestCache(pp, fileName)+ } catch {+ // non-critical+ }++ try {+ const logPath = `${pp}/wiki/log.md`+ const logContent = await readFile(logPath).catch(() => "# Wiki Log\n")+ const date = new Date().toISOString().slice(0, 10)+ const logEntry = `\n## [${date}] external delete | ${fileName}\n\nDetected deleted source file and cleaned ${pagesToDelete.length} wiki pages.${keptCount > 0 ? ` ${keptCount} shared pages kept (have other sources).` : ""}\n`+ await writeFile(logPath, logContent.trimEnd() + logEntry)+ } catch {+ // non-critical+ }+}++async function cleanupExternallyDeletedWikiPages(+ projectPath: string,+ relativePaths: string[],+): Promise<void> {+ const pp = normalizePath(projectPath)+ const deletedInfos = relativePaths+ .map((path) => ({ slug: getFileStem(path), title: "" }))+ .filter((info) => info.slug.length > 0 && !info.slug.startsWith("."))++ if (deletedInfos.length === 0) return++ for (const info of deletedInfos) {+ await removePageEmbedding(pp, info.slug)+ try {+ await deleteFile(`${pp}/wiki/media/${info.slug}`)+ } catch {+ // only source-summary pages usually own media; absence is normal+ }+ }++ const deletedKeys = buildDeletedKeys(deletedInfos)+ const deletedSlugSet = new Set(deletedInfos.map((info) => normalizeCleanupKey(info.slug)))+ const wikiTree = await listDirectory(`${pp}/wiki`)+ const allMd = flattenMd(wikiTree)++ for (const file of allMd) {+ let content: string+ try {+ content = await readFile(file.path)+ } catch {+ continue+ }++ let updated = content+ if (file.path === `${pp}/wiki/index.md` || file.name === "index.md") {+ updated = cleanIndexListing(updated, deletedKeys)+ }+ updated = stripDeletedWikilinks(updated, deletedKeys)++ const related = parseFrontmatterArray(updated, "related")+ if (related.length > 0) {+ const filtered = related.filter((s) => !deletedSlugSet.has(normalizeCleanupKey(s)))+ if (filtered.length !== related.length) {+ updated = writeFrontmatterArray(updated, "related", filtered)+ }+ }++ if (updated !== content) {+ try {+ await writeFile(file.path, updated)+ } catch (err) {+ console.warn(`[file-sync] failed to rewrite ${file.path}:`, err)+ }+ }+ }+}++function flattenMd(nodes: readonly FileNode[]): FileNode[] {+ const out: FileNode[] = []+ function walk(items: readonly FileNode[]): void {+ for (const item of items) {+ if (item.is_dir) {+ if (item.children) walk(item.children)+ } else if (item.name.endsWith(".md")) {+ out.push(item)+ }+ }+ }+ walk(nodes)+ return out+}++function sourceMatchesDeletedFile(source: string, fileName: string): boolean {+ const normalizedSource = normalizePath(source).split("/").pop()?.toLowerCase() ?? ""+ return normalizedSource === fileName.toLowerCase()+}++function normalizeCleanupKey(value: string): string {+ return value.toLowerCase().replace(/[\s\-_]+/g, "")+}diff --git a/src/lib/project-store.ts b/src/lib/project-store.tsindex 4b80ee8c..31a7c2f6 100644--- a/src/lib/project-store.ts+++ b/src/lib/project-store.ts@@ -166,6 +166,7 @@ export async function loadLanguage(): Promise<string | null> {const OUTPUT_LANGUAGE_KEY = "outputLanguage"const PROJECT_OUTPUT_LANGUAGE_KEY = "projectOutputLanguages"+const PROJECT_FILE_SYNC_KEY = "projectFileSyncEnabled"export async function saveOutputLanguage(lang: OutputLanguage, projectId?: string): Promise<void> {const store = await getStore()@@ -185,6 +186,29 @@ export async function loadOutputLanguage(projectId?: string): Promise<OutputLangreturn (await store.get<OutputLanguage>(OUTPUT_LANGUAGE_KEY)) ?? null}+export async function saveProjectFileSyncEnabled(enabled: boolean, projectId?: string): Promise<void> {+ const store = await getStore()+ if (projectId) {+ const existing = (await store.get<Record<string, boolean>>(PROJECT_FILE_SYNC_KEY)) ?? {}+ await store.set(PROJECT_FILE_SYNC_KEY, { ...existing, [projectId]: enabled })+ return+ }+ const existing = (await store.get<Record<string, boolean>>(PROJECT_FILE_SYNC_KEY)) ?? {}+ await store.set(PROJECT_FILE_SYNC_KEY, { ...existing, default: enabled })+}++export async function loadProjectFileSyncEnabled(projectId?: string): Promise<boolean> {+ const store = await getStore()+ const settings = await store.get<Record<string, boolean>>(PROJECT_FILE_SYNC_KEY)+ if (projectId && settings && typeof settings[projectId] === "boolean") {+ return settings[projectId]+ }+ if (settings && typeof settings.default === "boolean") {+ return settings.default+ }+ return true+}+// ── Update-check persistence ──────────────────────────────────────────────// Small slice of state the UI-layer update store hydrates from on boot.// Only fields that should persist across launches: the user's "enablediff --git a/src/lib/reset-project-state.ts b/src/lib/reset-project-state.tsindex 0da2420b..32353f69 100644--- a/src/lib/reset-project-state.ts+++ b/src/lib/reset-project-state.ts@@ -40,10 +40,11 @@ export async function resetProjectState(): Promise<void> {// Module-level caches — load in parallel and clear each, surfacing any// failure instead of swallowing it.- const [queueMod, dedupQueueMod, graphMod] = await Promise.allSettled([+ const [queueMod, dedupQueueMod, graphMod, fileSyncMod] = await Promise.allSettled([import("@/lib/ingest-queue"),import("@/lib/dedup-queue"),import("@/lib/graph-relevance"),+ import("@/lib/project-file-sync"),])if (queueMod.status === "fulfilled") {@@ -79,4 +80,14 @@ export async function resetProjectState(): Promise<void> {} else {console.warn("[Reset Project State] Failed to load graph-relevance:", graphMod.reason)}++ if (fileSyncMod.status === "fulfilled") {+ try {+ await fileSyncMod.value.stopProjectFileSync()+ } catch (err) {+ console.warn("[Reset Project State] stopProjectFileSync failed:", err)+ }+ } else {+ console.warn("[Reset Project State] Failed to load project-file-sync:", fileSyncMod.reason)+ }}diff --git a/src/stores/file-sync-store.ts b/src/stores/file-sync-store.tsnew file mode 100644index 00000000..ef94ddde--- /dev/null+++ b/src/stores/file-sync-store.ts@@ -0,0 +1,22 @@+import { create } from "zustand"+import type { FileChangeTask } from "@/commands/file-sync"++interface FileSyncState {+ tasks: FileChangeTask[]+ running: boolean+ lastError: string | null+ setTasks: (tasks: FileChangeTask[]) => void+ setRunning: (running: boolean) => void+ setLastError: (error: string | null) => void+ clear: () => void+}++export const useFileSyncStore = create<FileSyncState>((set) => ({+ tasks: [],+ running: false,+ lastError: null,+ setTasks: (tasks) => set({ tasks }),+ setRunning: (running) => set({ running }),+ setLastError: (lastError) => set({ lastError }),+ clear: () => set({ tasks: [], running: false, lastError: null }),+}))