From e1f1ef0b02c1f48373aecd6b14cc4417ad383003 Mon Sep 17 00:00:00 2001 From: Yuri Karamian Date: Tue, 29 Sep 2026 14:05:46 +0200 Subject: [PATCH] Harden v1.3.6 data safety and editor lifecycle Protect file mutations, backup restoration, and WebDAV synchronization from data loss. Preserve editor drafts across concurrent saves, external changes, and window or vault transitions. Integrate toolbar customization inline and extend regression coverage. --- src-tauri/Cargo.lock | 2 + src-tauri/Cargo.toml | 4 + .../java/com/helixnotes/app/MainActivity.kt | 10 + src-tauri/src/backup.rs | 1139 ++++++++++++++--- src-tauri/src/commands.rs | 451 ++++--- src-tauri/src/history.rs | 189 ++- src-tauri/src/lib.rs | 18 +- src-tauri/src/state.rs | 162 ++- src-tauri/src/sync.rs | 806 ++++++++---- src-tauri/src/types.rs | 5 +- src-tauri/src/vault/import.rs | 442 +++++-- src-tauri/src/vault/operations.rs | 965 ++++++++++++-- src-tauri/src/vault/watcher.rs | 34 +- src/lib/api.ts | 32 +- src/lib/components/AppLayout.svelte | 337 +++-- src/lib/components/Editor.svelte | 390 ++++-- src/lib/components/NoteList.svelte | 69 +- src/lib/components/NoteWindow.svelte | 72 +- src/lib/components/SettingsPanel.svelte | 154 ++- src/lib/components/Sidebar.svelte | 154 +-- src/lib/components/VaultPicker.svelte | 9 +- src/lib/stores/app.ts | 16 + src/lib/types.ts | 7 +- src/lib/utils/revision-save.test.mjs | 67 + src/lib/utils/revision-save.ts | 23 +- src/routes/+page.svelte | 19 +- 26 files changed, 4292 insertions(+), 1284 deletions(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 7455b99..0330d16 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1782,9 +1782,11 @@ dependencies = [ "arboard", "chrono", "dirs", + "fs4", "futures", "gray_matter", "image", + "libc", "log", "notify", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index e3700fc..c763be6 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -51,10 +51,14 @@ rayon = "1" quick-xml = "0.41" urlencoding = "2" sha2 = "0.10" +fs4 = { version = "0.8", default-features = false } rustls = { version = "0.23", default-features = false, features = ["ring", "logging", "std", "tls12"] } [target.'cfg(target_os = "macos")'.dependencies] objc2-app-kit = "0.3.2" +[target.'cfg(target_os = "android")'.dependencies] +libc = "0.2" + [target.'cfg(target_os = "ios")'.dependencies] tauri-plugin-ios-vault-access = { path = "plugins/ios-vault-access" } diff --git a/src-tauri/gen/android/app/src/main/java/com/helixnotes/app/MainActivity.kt b/src-tauri/gen/android/app/src/main/java/com/helixnotes/app/MainActivity.kt index d70193d..cfdd649 100644 --- a/src-tauri/gen/android/app/src/main/java/com/helixnotes/app/MainActivity.kt +++ b/src-tauri/gen/android/app/src/main/java/com/helixnotes/app/MainActivity.kt @@ -35,6 +35,16 @@ class MainActivity : TauriActivity() { webView.settings.layoutAlgorithm = android.webkit.WebSettings.LayoutAlgorithm.NORMAL } + override fun onPause() { + // Give the editor a chance to persist its current document before Android + // suspends the WebView. The save remains best-effort when the process is killed. + webView?.evaluateJavascript( + "window.dispatchEvent(new Event('app-lifecycle-flush'))", + null + ) + super.onPause() + } + override fun onResume() { super.onResume() if (hasStoragePermission()) { diff --git a/src-tauri/src/backup.rs b/src-tauri/src/backup.rs index 93ef7e2..8433ce4 100644 --- a/src-tauri/src/backup.rs +++ b/src-tauri/src/backup.rs @@ -1,14 +1,85 @@ -use std::fs; -use std::io::{Read, Write}; -use std::path::{Path, PathBuf}; +use std::collections::HashMap; +use std::fs::{self, File}; +use std::io::{self, Read}; +use std::path::{Component, Path, PathBuf}; use chrono::Utc; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use tempfile::Builder; +use uuid::Uuid; use walkdir::WalkDir; use zip::write::SimpleFileOptions; use zip::ZipArchive; use crate::types::BackupEntry; +// Only pathological entry counts and paths are rejected; byte capacity is disk-based. +const MAX_ENTRIES: usize = 1_000_000; +const MAX_PATH_BYTES: usize = 4096; +const MAX_NAME_BYTES: usize = 256 * 1024 * 1024; +const MAX_PATH_COMPONENTS: usize = 64; +const MANIFEST: &str = ".helixnotes-backup.json"; + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct BackupManifest { + version: u32, + vault: String, + attachments: bool, +} + +fn vault_id(vault: &Path) -> Result { + let canonical = fs::canonicalize(vault).map_err(|e| e.to_string())?; + Ok(format!( + "{:x}", + Sha256::digest(canonical.as_os_str().as_encoded_bytes()) + )) +} + +fn options() -> SimpleFileOptions { + SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated) + .compression_level(Some(6)) +} + +fn is_published_backup(path: &Path) -> bool { + path.file_name().is_some_and(|name| { + let name = name.to_string_lossy(); + name.starts_with("helixnotes-backup-") && name.ends_with(".zip") + }) +} + +fn excluded_path(path: &Path, vault: &Path, backup_dir: &Path, attachments: bool) -> bool { + if path == vault { + return false; + } + if path.starts_with(backup_dir) { + return true; + } + // Old configured backup folders may remain inside the vault after relocation. + // Never recursively archive previously published backups from those folders. + if path.is_file() && is_published_backup(path) { + return true; + } + let relative = path.strip_prefix(vault).expect("walker stays in vault"); + let mut parts = relative.components(); + let first = parts.next().expect("non-root entry").as_os_str(); + if first == ".helixnotes" { + return match parts.next() { + None => !attachments, + Some(part) if part.as_os_str() == "attachments" && attachments => { + parts.any(|part| part.as_os_str().to_string_lossy().starts_with('.')) + } + _ => true, + }; + } + relative.components().any(|part| match part { + Component::Normal(name) => name.to_string_lossy().starts_with('.'), + _ => false, + }) +} + /// Returns the default backup directory (~/.config/helixnotes/backups/) pub fn default_backup_dir() -> Result { let config_dir = dirs::config_dir().ok_or("Cannot find config directory")?; @@ -33,157 +104,172 @@ pub fn get_backup_dir(custom: &Option) -> Result { } } -/// Create a backup zip of the vault +/// Create a complete ZIP in an exclusive temporary file before publishing it. pub fn create_backup( vault_path: &str, backup_dir: &Path, include_attachments: bool, ) -> Result { - let vault = Path::new(vault_path); + let vault = fs::canonicalize(vault_path).map_err(|e| e.to_string())?; if !vault.is_dir() { return Err("Vault directory does not exist".to_string()); } - - if !backup_dir.exists() { - fs::create_dir_all(backup_dir).map_err(|e| e.to_string())?; + fs::create_dir_all(backup_dir).map_err(|e| e.to_string())?; + let output = fs::canonicalize(backup_dir).map_err(|e| e.to_string())?; + if output == vault { + return Err("Backup directory must not be the vault root".to_string()); } - + let id = vault_id(&vault)?; let now = Utc::now(); let timestamp = now.format("%Y-%m-%dT%H-%M-%S").to_string(); - let filename = format!("helixnotes-backup-{}.zip", timestamp); - let backup_path = backup_dir.join(&filename); - - let file = fs::File::create(&backup_path) - .map_err(|e| format!("Failed to create backup file: {}", e))?; + let filename = format!("helixnotes-backup-{timestamp}-{id}-{}.zip", Uuid::new_v4()); + let backup_path = output.join(&filename); + let temporary = Builder::new() + .prefix(".helixnotes-backup-") + .suffix(".tmp") + .tempfile_in(&output) + .map_err(|e| format!("Failed to create temporary backup: {e}"))?; + let file = temporary.reopen().map_err(|e| e.to_string())?; let mut zip = zip::ZipWriter::new(file); - let options = SimpleFileOptions::default() - .compression_method(zip::CompressionMethod::Deflated) - .compression_level(Some(6)); - - let helixnotes_dir = vault.join(".helixnotes"); - let attachments_dir = helixnotes_dir.join("attachments"); - - for entry in WalkDir::new(vault).into_iter().filter_map(|e| e.ok()) { - let path = entry.path(); - - // Handle .helixnotes/ directory - if path.starts_with(&helixnotes_dir) { - if include_attachments { - // Include attachments/ but skip everything else - if !path.starts_with(&attachments_dir) && path != helixnotes_dir { - continue; + let result = (|| -> Result<(), String> { + zip.start_file(MANIFEST, options()) + .map_err(|e| e.to_string())?; + serde_json::to_writer( + &mut zip, + &BackupManifest { + version: 1, + vault: id, + attachments: include_attachments, + }, + ) + .map_err(|e| e.to_string())?; + let mut walker = WalkDir::new(&vault).into_iter(); + while let Some(item) = walker.next() { + let entry = item.map_err(|e| format!("Unreadable vault entry: {e}"))?; + let path = entry.path(); + if excluded_path(path, &vault, &output, include_attachments) { + if entry.file_type().is_dir() { + walker.skip_current_dir(); } - if path == helixnotes_dir { - continue; - } - } else { - // Skip .helixnotes entirely continue; } - } - - // Skip hidden files/directories (except .helixnotes which we handle above) - if path != vault { - if let Some(name) = path.file_name() { - let name_str = name.to_string_lossy(); - if name_str.starts_with('.') && name_str != ".helixnotes" { - continue; - } + if path == vault { + continue; } - } - - let relative = path.strip_prefix(vault).map_err(|e| e.to_string())?; - - if path.is_dir() { - let dir_name = format!("{}/", relative.to_string_lossy()); - if dir_name != "/" { - zip.add_directory(&dir_name, options) + if entry.file_type().is_symlink() { + return Err(format!("Cannot back up symlink: {}", path.display())); + } + let relative = path.strip_prefix(&vault).map_err(|e| e.to_string())?; + let name = relative + .to_str() + .ok_or("Non-UTF-8 vault path")? + .replace('\\', "/"); + checked_entry_name(&name)?; + if name == MANIFEST { + return Err("Vault path conflicts with backup metadata".to_string()); + } + if entry.file_type().is_dir() { + zip.add_directory(format!("{name}/"), options()) .map_err(|e| e.to_string())?; + } else if entry.file_type().is_file() { + let size = entry.metadata().map_err(|e| e.to_string())?.len(); + zip.start_file(name, options().large_file(size >= u32::MAX as u64)) + .map_err(|e| e.to_string())?; + let mut source = File::open(path).map_err(|e| e.to_string())?; + let copied = io::copy(&mut (&mut source).take(size.saturating_add(1)), &mut zip) + .map_err(|e| e.to_string())?; + if copied != size { + return Err(format!( + "Vault file changed while backing up: {}", + path.display() + )); + } + } else { + return Err(format!("Unsupported vault entry: {}", path.display())); } - } else { - let name = relative.to_string_lossy().to_string(); - zip.start_file(&name, options).map_err(|e| e.to_string())?; - let mut f = fs::File::open(path).map_err(|e| e.to_string())?; - let mut buffer = Vec::new(); - f.read_to_end(&mut buffer).map_err(|e| e.to_string())?; - zip.write_all(&buffer).map_err(|e| e.to_string())?; } - } - - zip.finish().map_err(|e| e.to_string())?; - + let finished = zip.finish().map_err(|e| e.to_string())?; + finished.sync_all().map_err(|e| e.to_string())?; + Ok(()) + })(); + result?; + // persist_noclobber does not replace an existing backup even on UUID collision. + temporary + .persist_noclobber(&backup_path) + .map_err(|e| format!("Failed to publish backup: {}", e.error))?; let meta = fs::metadata(&backup_path).map_err(|e| e.to_string())?; - Ok(BackupEntry { - filename: filename.clone(), + filename, path: backup_path.to_string_lossy().to_string(), size: meta.len(), created: now.to_rfc3339(), }) } -/// List all backups in the backup directory -pub fn list_backups(backup_dir: &Path) -> Result, String> { +fn archive_name(filename: &str, id: &str) -> Option<(String, bool)> { + let stem = filename + .strip_prefix("helixnotes-backup-")? + .strip_suffix(".zip")?; + let timestamp = stem.get(..19)?; + let suffix = stem.get(19..)?; + let parsed = chrono::NaiveDateTime::parse_from_str(timestamp, "%Y-%m-%dT%H-%M-%S").ok()?; + if suffix.is_empty() { + return Some((parsed.and_utc().to_rfc3339(), false)); // pre-manifest legacy + } + let suffix = suffix.strip_prefix('-')?; + let (vault_hash, uuid) = suffix.split_once('-')?; + if vault_hash.len() != 64 || !vault_hash.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return None; + } + Uuid::parse_str(uuid).ok()?; + Some((parsed.and_utc().to_rfc3339(), vault_hash == id)) +} + +fn list_owned_backups( + backup_dir: &Path, + vault_path: &str, +) -> Result, String> { if !backup_dir.exists() { return Ok(Vec::new()); } - - let mut entries: Vec = Vec::new(); - + let id = vault_id(Path::new(vault_path))?; + let mut entries = Vec::new(); for entry in fs::read_dir(backup_dir).map_err(|e| e.to_string())? { let entry = entry.map_err(|e| e.to_string())?; let path = entry.path(); - - if path.extension().is_some_and(|ext| ext == "zip") { - let filename = path - .file_name() - .unwrap_or_default() - .to_string_lossy() - .to_string(); - let meta = fs::metadata(&path).map_err(|e| e.to_string())?; - - // Parse timestamp from filename: helixnotes-backup-YYYY-MM-DDTHH-MM-SS.zip - let created = if let Some(ts) = filename - .strip_prefix("helixnotes-backup-") - .and_then(|s| s.strip_suffix(".zip")) - { - // ts = "2026-02-08T18-09-15" → "2026-02-08T18:09:15Z" - if let Some(t_pos) = ts.find('T') { - let date_part = &ts[..t_pos]; - let time_part = &ts[t_pos + 1..]; - let time_colons = time_part.replace('-', ":"); - format!("{}T{}Z", date_part, time_colons) - } else { - meta.modified() - .map(|t| { - let dt: chrono::DateTime = t.into(); - dt.to_rfc3339() - }) - .unwrap_or_default() - } - } else { - meta.modified() - .map(|t| { - let dt: chrono::DateTime = t.into(); - dt.to_rfc3339() - }) - .unwrap_or_default() - }; - - entries.push(BackupEntry { - filename, - path: path.to_string_lossy().to_string(), - size: meta.len(), - created, - }); + let meta = fs::symlink_metadata(&path).map_err(|e| e.to_string())?; + if !meta.file_type().is_file() { + continue; + } + let filename = entry.file_name().to_string_lossy().to_string(); + if let Some((created, owned)) = archive_name(&filename, &id) { + entries.push(( + BackupEntry { + filename, + path: path.to_string_lossy().to_string(), + size: meta.len(), + created, + }, + owned, + )); } } - - // Sort newest first - entries.sort_by(|a, b| b.created.cmp(&a.created)); + entries.sort_by(|a, b| { + b.0.created + .cmp(&a.0.created) + .then_with(|| b.0.filename.cmp(&a.0.filename)) + }); Ok(entries) } +/// List backups from every vault; only automatic pruning uses vault identity. +pub fn list_backups(backup_dir: &Path, vault_path: &str) -> Result, String> { + Ok(list_owned_backups(backup_dir, vault_path)? + .into_iter() + .map(|(entry, _)| entry) + .collect()) +} + fn validated_backup_file(backup_dir: &Path, backup_path: &str) -> Result { let backup_dir = fs::canonicalize(backup_dir).map_err(|error| error.to_string())?; let backup = fs::canonicalize(backup_path).map_err(|error| error.to_string())?; @@ -198,64 +284,461 @@ fn validated_backup_file(backup_dir: &Path, backup_path: &str) -> Result Result { + let trimmed = name.strip_suffix('/').unwrap_or(name); + if trimmed.is_empty() + || trimmed.len() > MAX_PATH_BYTES + || name.contains('\\') + || name.contains('\0') + || name.contains(':') + { + return Err(format!("Invalid backup entry path: {name:?}")); + } + let parts: Vec<_> = trimmed.split('/').collect(); + if parts.len() > MAX_PATH_COMPONENTS + || parts + .iter() + .any(|part| part.is_empty() || *part == "." || *part == "..") + { + return Err(format!("Unsafe backup entry path: {name:?}")); + } + let path = Path::new(trimmed); + if path + .components() + .any(|part| !matches!(part, Component::Normal(_))) + { + return Err(format!("Unsafe backup entry path: {name:?}")); + } + Ok(path.to_path_buf()) +} + +fn remove_entry(path: &Path) -> io::Result<()> { + if fs::symlink_metadata(path)?.file_type().is_dir() { + fs::remove_dir_all(path) + } else { + fs::remove_file(path) + } +} + +fn historical_backups( + vault: &Path, + backup_dir: &Path, + attachments: bool, +) -> Result, String> { + let mut paths = Vec::new(); + let mut walker = WalkDir::new(vault).into_iter(); + while let Some(item) = walker.next() { + let item = item.map_err(|e| format!("Unreadable vault entry: {e}"))?; + let path = item.path(); + if path == vault { + continue; + } + if path.starts_with(backup_dir) { + if item.file_type().is_dir() { + walker.skip_current_dir(); + } + continue; + } + let relative = path.strip_prefix(vault).map_err(|e| e.to_string())?; + let hidden = relative + .components() + .any(|component| component.as_os_str().to_string_lossy().starts_with('.')); + if hidden && !(attachments && relative.starts_with(".helixnotes/attachments")) { + if item.file_type().is_dir() { + // Continue into .helixnotes only to find historical attachment backups. + if attachments && relative == Path::new(".helixnotes") { + continue; + } + walker.skip_current_dir(); + } + continue; + } + if item.file_type().is_file() && is_published_backup(path) { + paths.push(relative.to_path_buf()); + } + } + Ok(paths) +} + +fn install_staged( + vault: &Path, + contents: &Path, + previous: &Path, + backup_dir: &Path, + attachments: bool, +) -> Result<(), String> { + let nested = backup_dir + .strip_prefix(vault) + .ok() + .filter(|p| !p.as_os_str().is_empty()); + let held = previous + .parent() + .expect("staging parent") + .join("held-backups"); + let previous_entries = previous.join("entries"); + let previous_attachments = previous.join("internal-attachments"); + let history = historical_backups(vault, backup_dir, attachments)?; + let held_history = previous + .parent() + .expect("staging parent") + .join("held-history"); + let mut stashed_history = Vec::new(); + let mut restored_history = Vec::new(); + let mut held_output = false; + let mut displaced = Vec::new(); + let mut installed = Vec::new(); + let attachments_path = vault.join(".helixnotes/attachments"); + let mut displaced_attachments = false; + let mut installed_attachments = false; + let operation = (|| -> io::Result<()> { + fs::create_dir(&previous_entries)?; + fs::create_dir(&held_history)?; + for relative in &history { + let destination = held_history.join(relative); + fs::create_dir_all(destination.parent().expect("history parent"))?; + fs::rename(vault.join(relative), destination)?; + stashed_history.push(relative.clone()); + } + if let Some(relative) = nested { + if backup_dir.exists() { + fs::rename(backup_dir, &held)?; + held_output = true; + } + // Restoring into a vault with nested backup output must not overwrite it. + let target = contents.join(relative); + if target.exists() { + return Err(io::Error::other( + "Archive contains the backup output directory", + )); + } + } + for entry in fs::read_dir(vault)? { + let entry = entry?; + let name = entry.file_name(); + if name.to_string_lossy().starts_with('.') { + continue; + } + fs::rename(entry.path(), previous_entries.join(&name))?; + displaced.push(name); + } + if attachments { + if fs::symlink_metadata(&attachments_path).is_ok() { + fs::rename(&attachments_path, &previous_attachments)?; + displaced_attachments = true; + } + fs::create_dir_all(vault.join(".helixnotes"))?; + } + for entry in fs::read_dir(contents)? { + let entry = entry?; + let name = entry.file_name(); + if name == ".helixnotes" { + continue; + } + fs::rename(entry.path(), vault.join(&name))?; + installed.push(name); + } + if attachments { + fs::rename(contents.join(".helixnotes/attachments"), &attachments_path)?; + installed_attachments = true; + } + if let Some(relative) = nested { + if held_output { + let destination = vault.join(relative); + fs::create_dir_all(destination.parent().expect("nested backup parent"))?; + fs::rename(&held, destination)?; + held_output = false; + } + } + for relative in &stashed_history { + let destination = vault.join(relative); + fs::create_dir_all(destination.parent().expect("history parent"))?; + fs::rename(held_history.join(relative), &destination)?; + restored_history.push(relative.clone()); + } + Ok(()) + })(); + if let Err(error) = operation { + let mut failures = Vec::new(); + for relative in &restored_history { + if let Err(e) = fs::rename(vault.join(relative), held_history.join(relative)) { + failures.push(format!( + "retain historical backup {}: {e}", + relative.display() + )); + } + } + // A later failure can happen after the configured output was reinstalled. + // Re-hold it before removing any newly installed top-level directory. + if nested.is_some() && !held_output { + if let Err(e) = fs::rename(backup_dir, &held) { + failures.push(format!("retain configured backup output: {e}")); + } else { + held_output = true; + } + } + if !failures.is_empty() { + return Err(format!( + "Restore failed: {error}; rollback incomplete (originals retained in {}): {}", + previous.parent().expect("staging parent").display(), + failures.join("; ") + )); + } + if installed_attachments { + if let Err(e) = remove_entry(&attachments_path) { + failures.push(format!("remove new attachments: {e}")); + } + } + for name in installed { + if let Err(e) = remove_entry(&vault.join(&name)) { + failures.push(format!("remove new entry {:?}: {e}", name)); + } + } + for relative in &stashed_history { + let mut parent = vault.join(relative).parent().map(Path::to_path_buf); + while let Some(path) = parent { + if path == vault { + break; + } + let _ = fs::remove_dir(&path); // remove only now-empty staging parents + parent = path.parent().map(Path::to_path_buf); + } + } + for name in displaced { + if let Err(e) = fs::rename(previous_entries.join(&name), vault.join(&name)) { + failures.push(format!("restore original {:?}: {e}", name)); + } + } + if displaced_attachments { + if let Err(e) = fs::rename(&previous_attachments, &attachments_path) { + failures.push(format!("restore attachments: {e}")); + } + } + if held_output { + if let Some(relative) = nested { + let destination = vault.join(relative); + if let Err(e) = + fs::create_dir_all(destination.parent().expect("nested backup parent")) + .and_then(|_| fs::rename(&held, destination)) + { + failures.push(format!("restore backup output: {e}")); + } + } + } + for relative in &stashed_history { + let destination = vault.join(relative); + if let Err(e) = fs::create_dir_all(destination.parent().expect("history parent")) + .and_then(|_| fs::rename(held_history.join(relative), destination)) + { + failures.push(format!( + "restore historical backup {}: {e}", + relative.display() + )); + } + } + if failures.is_empty() { + return Err(format!( + "Restore installation failed; previous vault recovered: {error}" + )); + } + return Err(format!( + "Restore failed: {error}; rollback incomplete (originals retained in {}): {}", + previous.parent().expect("staging parent").display(), + failures.join("; ") + )); + } + Ok(()) +} + +/// Validate and extract everything alongside the vault; install only after success. +/// Limits: 1,000,000 entries, 4 KiB / 64 components per path, 256 MiB +/// combined entry names, and extracted bytes within available sibling-filesystem +/// space, reserving 5% of free space (up to 64 MiB). pub fn restore_backup( vault_path: &str, backup_dir: &Path, backup_path: &str, ) -> Result<(), String> { - let vault = Path::new(vault_path); - let backup = validated_backup_file(backup_dir, backup_path)?; + let vault = fs::canonicalize(vault_path).map_err(|e| e.to_string())?; + if !vault.is_dir() { + return Err("Vault directory does not exist".to_string()); + } + let output = fs::canonicalize(backup_dir).map_err(|e| e.to_string())?; + let backup = validated_backup_file(&output, backup_path)?; + let stage = Builder::new() + .prefix(".helixnotes-restore-") + .tempdir_in(vault.parent().ok_or("Vault has no parent")?) + .map_err(|e| e.to_string())?; + let contents = stage.path().join("contents"); + let previous = stage.path().join("previous"); + fs::create_dir(&contents).map_err(|e| e.to_string())?; + fs::create_dir(&previous).map_err(|e| e.to_string())?; + let free = fs4::available_space(stage.path()).map_err(|e| e.to_string())?; + let reserve = (free / 20).min(64 * 1024 * 1024); // 5%, capped at 64 MiB + let extraction_budget = free - reserve; - let file = fs::File::open(backup).map_err(|e| format!("Failed to open backup: {}", e))?; - let mut archive = - ZipArchive::new(file).map_err(|e| format!("Invalid backup archive: {}", e))?; - - // Clear existing notes (but keep .helixnotes/ internals except attachments) - for entry in fs::read_dir(vault).map_err(|e| e.to_string())? { - let entry = entry.map_err(|e| e.to_string())?; - let path = entry.path(); - let name = path - .file_name() - .unwrap_or_default() - .to_string_lossy() - .to_string(); - - // Keep hidden dirs (.helixnotes) - we'll handle attachments separately - if name.starts_with('.') { + let mut archive = ZipArchive::new(File::open(&backup).map_err(|e| e.to_string())?) + .map_err(|e| format!("Invalid backup archive: {e}"))?; + if archive.len() > MAX_ENTRIES { + return Err("Backup exceeds the 1,000,000 entry limit".to_string()); + } + let mut declared = 0u64; + let mut name_bytes = 0usize; + for index in 0..archive.len() { + let item = archive.by_index(index).map_err(|e| e.to_string())?; + name_bytes = name_bytes + .checked_add(item.name().len()) + .ok_or("Backup entry names overflow")?; + if name_bytes > MAX_NAME_BYTES { + return Err("Backup entry names exceed the 256 MiB limit".to_string()); + } + declared = declared + .checked_add(item.size()) + .ok_or("Backup size overflow")?; + if declared > extraction_budget { + return Err("Insufficient free space to stage the complete backup".to_string()); + } + } + let mut seen = HashMap::new(); + let mut total = 0u64; + let mut manifest = None; + let mut legacy_attachments = false; + for index in 0..archive.len() { + let mut item = archive.by_index(index).map_err(|e| e.to_string())?; + let name = item.name().to_string(); + let relative = checked_entry_name(&name)?; + let directory = item.is_dir(); + if !directory && is_published_backup(&relative) { + return Err(format!("Archive contains historical backup output: {name}")); + } + let mode = item.unix_mode().unwrap_or(0) & 0o170000; + if (mode != 0 && mode != if directory { 0o040000 } else { 0o100000 }) + || (directory && item.size() != 0) + { + return Err(format!("Unsupported archive entry: {name}")); + } + if seen.insert(relative.clone(), !directory).is_some() { + return Err(format!("Duplicate archive entry: {name}")); + } + let mut parts = relative.components(); + let first = parts.next().expect("checked path"); + let internal = first.as_os_str() == ".helixnotes"; + if internal { + match parts.next() { + None if directory => {} + Some(component) if component.as_os_str() == "attachments" => { + legacy_attachments = true; + } + _ => return Err(format!("Archive contains unsupported app metadata: {name}")), + } + } else if first.as_os_str().to_string_lossy().starts_with('.') + && relative != Path::new(MANIFEST) + { + return Err(format!("Archive contains hidden metadata: {name}")); + } + if relative != Path::new(MANIFEST) + && relative + .components() + .skip(if internal { 2 } else { 1 }) + .any(|part| part.as_os_str().to_string_lossy().starts_with('.')) + { + return Err(format!("Archive contains hidden metadata: {name}")); + } + if let Ok(output_relative) = output.strip_prefix(&vault) { + if !output_relative.as_os_str().is_empty() + && (relative.starts_with(output_relative) + || (!directory && output_relative.starts_with(&relative))) + { + return Err("Archive contains the configured backup output path".to_string()); + } + } + total = total + .checked_add(item.size()) + .ok_or("Backup size overflow")?; + if total > extraction_budget { + return Err("Backup exceeds available staging space".to_string()); + } + if relative == Path::new(MANIFEST) { + if directory || item.size() > 4096 { + return Err("Invalid backup manifest".to_string()); + } + let declared_size = item.size(); + let mut bounded = (&mut item).take(declared_size.saturating_add(1)); + let parsed: BackupManifest = serde_json::from_reader(&mut bounded) + .map_err(|e| format!("Invalid backup manifest: {e}"))?; + if bounded.limit() != 1 { + return Err("Backup manifest length mismatch".to_string()); + } + manifest = Some(parsed); continue; } - - if path.is_dir() { - fs::remove_dir_all(&path).map_err(|e| e.to_string())?; + let dest = contents.join(&relative); + if directory { + fs::create_dir_all(&dest).map_err(|e| e.to_string())?; } else { - fs::remove_file(&path).map_err(|e| e.to_string())?; - } - } - - // Clear existing attachments so backup's attachments replace them - let attachments_dir = vault.join(".helixnotes").join("attachments"); - if attachments_dir.exists() { - fs::remove_dir_all(&attachments_dir).map_err(|e| e.to_string())?; - } - - // Extract archive - for i in 0..archive.len() { - let mut file = archive.by_index(i).map_err(|e| e.to_string())?; - let outpath = vault.join(file.mangled_name()); - - if file.is_dir() { - fs::create_dir_all(&outpath).map_err(|e| e.to_string())?; - } else { - if let Some(parent) = outpath.parent() { + if let Some(parent) = dest.parent() { fs::create_dir_all(parent).map_err(|e| e.to_string())?; } - let mut outfile = fs::File::create(&outpath).map_err(|e| e.to_string())?; - std::io::copy(&mut file, &mut outfile).map_err(|e| e.to_string())?; + let mut target = File::create(&dest).map_err(|e| e.to_string())?; + let declared_size = item.size(); + let copied = io::copy( + &mut (&mut item).take(declared_size.saturating_add(1)), + &mut target, + ) + .map_err(|e| format!("Backup extraction failed: {e}"))?; + if copied != item.size() { + return Err(format!("Backup entry length mismatch: {name}")); + } } } - - Ok(()) + for (file, is_file) in &seen { + if *is_file + && file + .ancestors() + .skip(1) + .any(|parent| seen.get(parent) == Some(&true)) + { + return Err(format!( + "Archive entry conflicts with a file: {}", + file.display() + )); + } + } + let attachments = if let Some(meta) = manifest { + if meta.version != 1 + || meta.vault.len() != 64 + || !meta.vault.bytes().all(|byte| byte.is_ascii_hexdigit()) + { + return Err("Unsupported backup manifest version or vault identity".to_string()); + } + if !meta.attachments && legacy_attachments { + return Err("Backup has attachments despite metadata declaring none".to_string()); + } + meta.attachments + } else { + legacy_attachments + }; + if attachments { + fs::create_dir_all(contents.join(".helixnotes/attachments")).map_err(|e| e.to_string())?; + if let Ok(relative) = output.strip_prefix(&vault) { + if relative.starts_with(".helixnotes/attachments") { + return Err("Cannot replace attachments containing the backup output".to_string()); + } + } + let internals = vault.join(".helixnotes"); + if fs::symlink_metadata(&internals).is_ok_and(|meta| !meta.file_type().is_dir()) { + return Err("Vault app metadata directory is not a real directory".to_string()); + } + } + drop(archive); + let result = install_staged(&vault, &contents, &previous, &output, attachments); + if result + .as_ref() + .is_err_and(|message| message.contains("rollback incomplete")) + { + // Keep originals available for manual recovery if an extraordinary rollback fails. + let _ = stage.keep(); + } + result } /// Delete a single backup file @@ -264,26 +747,34 @@ pub fn delete_backup(backup_dir: &Path, backup_path: &str) -> Result<(), String> fs::remove_file(path).map_err(|error| error.to_string()) } -/// Remove old backups keeping only the newest `max_count` -pub fn cleanup_old_backups(backup_dir: &Path, max_count: u32) -> Result<(), String> { - let mut backups = list_backups(backup_dir)?; - - // backups are already sorted newest-first - if backups.len() as u32 > max_count { - let to_remove = backups.split_off(max_count as usize); - for entry in to_remove { +/// Prune only identifiable backups for this vault; ambiguous legacy archives remain. +pub fn cleanup_old_backups( + backup_dir: &Path, + vault_path: &str, + max_count: u32, +) -> Result<(), String> { + let mut owned: Vec<_> = list_owned_backups(backup_dir, vault_path)? + .into_iter() + .filter_map(|(entry, owned)| owned.then_some(entry)) + .collect(); + if owned.len() > max_count as usize { + for entry in owned.drain(max_count as usize..) { delete_backup(backup_dir, &entry.path)?; } } - Ok(()) } #[cfg(test)] mod tests { - use super::delete_backup; - use std::fs; + use super::{cleanup_old_backups, create_backup, delete_backup, list_backups, restore_backup}; + use std::fs::{self, File}; + use std::io::Write; + use std::path::Path; + use tempfile::tempdir; use uuid::Uuid; + use zip::write::SimpleFileOptions; + use zip::{ZipArchive, ZipWriter}; #[test] fn delete_backup_rejects_files_outside_backup_directory() { @@ -299,4 +790,308 @@ mod tests { assert!(outside.exists()); fs::remove_dir_all(root).unwrap(); } + + fn vault_string(path: &Path) -> String { + path.to_str().unwrap().to_string() + } + + #[test] + fn backups_are_vault_scoped_and_not_published_until_complete() { + let root = tempdir().unwrap(); + let output = root.path().join("backups"); + let first = root.path().join("first"); + let second = root.path().join("second"); + fs::create_dir_all(&first).unwrap(); + fs::create_dir_all(&second).unwrap(); + fs::write(first.join("note.md"), "one").unwrap(); + fs::write(second.join("note.md"), "two").unwrap(); + let a = create_backup(&vault_string(&first), &output, false).unwrap(); + let b = create_backup(&vault_string(&second), &output, false).unwrap(); + assert_ne!(a.filename, b.filename); + assert_eq!( + list_backups(&output, &vault_string(&first)).unwrap().len(), + 2 + ); + assert_eq!( + list_backups(&output, &vault_string(&second)).unwrap().len(), + 2 + ); + cleanup_old_backups(&output, &vault_string(&first), 0).unwrap(); + assert!(!Path::new(&a.path).exists()); + assert!(Path::new(&b.path).exists()); + + #[cfg(unix)] + { + std::os::unix::fs::symlink("missing", first.join("broken.md")).unwrap(); + assert!(create_backup(&vault_string(&first), &output, false).is_err()); + assert_eq!( + list_backups(&output, &vault_string(&first)).unwrap().len(), + 1 + ); + assert_eq!(fs::read_dir(&output).unwrap().count(), 1); + } + } + + #[test] + fn nested_output_and_hidden_subtrees_are_not_archived() { + let root = tempdir().unwrap(); + let vault = root.path().join("vault"); + let output = vault.join("archives"); + fs::create_dir_all(&output).unwrap(); + fs::create_dir_all(vault.join(".private/notes")).unwrap(); + fs::create_dir_all(vault.join("former-archives")).unwrap(); + fs::write( + vault.join("former-archives/helixnotes-backup-2026-01-02T03-04-05.zip"), + "former", + ) + .unwrap(); + fs::write(vault.join("note.md"), "visible").unwrap(); + fs::write(vault.join(".private/notes/secret.md"), "secret").unwrap(); + fs::write(output.join("old.zip"), "old").unwrap(); + let backup = create_backup(&vault_string(&vault), &output, false).unwrap(); + let mut zip = ZipArchive::new(File::open(&backup.path).unwrap()).unwrap(); + assert!(zip.by_name("note.md").is_ok()); + assert!(zip.by_name("archives/old.zip").is_err()); + assert!(zip + .by_name("former-archives/helixnotes-backup-2026-01-02T03-04-05.zip") + .is_err()); + assert!(zip.by_name(".private/notes/secret.md").is_err()); + drop(zip); + fs::write(vault.join("note.md"), "changed").unwrap(); + restore_backup(&vault_string(&vault), &output, &backup.path).unwrap(); + assert_eq!( + fs::read_to_string(vault.join("note.md")).unwrap(), + "visible" + ); + assert_eq!(fs::read_to_string(output.join("old.zip")).unwrap(), "old"); + assert_eq!( + fs::read_to_string( + vault.join("former-archives/helixnotes-backup-2026-01-02T03-04-05.zip") + ) + .unwrap(), + "former" + ); + assert!(Path::new(&backup.path).exists()); + } + + #[test] + fn omitted_attachments_survive_restore_and_included_attachments_replace_them() { + let root = tempdir().unwrap(); + let vault = root.path().join("vault"); + let output = root.path().join("backups"); + let attachments = vault.join(".helixnotes/attachments"); + fs::create_dir_all(&attachments).unwrap(); + fs::write(vault.join("note.md"), "old").unwrap(); + fs::write(attachments.join("picture.png"), "original").unwrap(); + fs::create_dir_all(vault.join("attachments")).unwrap(); + fs::write(vault.join("attachments/notebook.md"), "top-level original").unwrap(); + fs::write(vault.join(".helixnotes/settings.json"), "keep").unwrap(); + + let omitted = create_backup(&vault_string(&vault), &output, false).unwrap(); + let mut omitted_zip = ZipArchive::new(File::open(&omitted.path).unwrap()).unwrap(); + let omitted_manifest: super::BackupManifest = + serde_json::from_reader(omitted_zip.by_name(super::MANIFEST).unwrap()).unwrap(); + assert!(!omitted_manifest.attachments); + drop(omitted_zip); + fs::write(vault.join("note.md"), "changed").unwrap(); + fs::write(attachments.join("picture.png"), "live").unwrap(); + restore_backup(&vault_string(&vault), &output, &omitted.path).unwrap(); + assert_eq!(fs::read_to_string(vault.join("note.md")).unwrap(), "old"); + assert_eq!( + fs::read_to_string(attachments.join("picture.png")).unwrap(), + "live" + ); + fs::write(vault.join("attachments/notebook.md"), "top-level snapshot").unwrap(); + + let included = create_backup(&vault_string(&vault), &output, true).unwrap(); + let mut included_zip = ZipArchive::new(File::open(&included.path).unwrap()).unwrap(); + let included_manifest: super::BackupManifest = + serde_json::from_reader(included_zip.by_name(super::MANIFEST).unwrap()).unwrap(); + assert!(included_manifest.attachments); + drop(included_zip); + fs::write(vault.join("note.md"), "newer").unwrap(); + fs::write(attachments.join("picture.png"), "latest").unwrap(); + fs::write(vault.join("attachments/notebook.md"), "top-level changed").unwrap(); + fs::write(attachments.join("extra.png"), "extra").unwrap(); + restore_backup(&vault_string(&vault), &output, &included.path).unwrap(); + assert_eq!(fs::read_to_string(vault.join("note.md")).unwrap(), "old"); + assert_eq!( + fs::read_to_string(attachments.join("picture.png")).unwrap(), + "live" + ); + assert_eq!( + fs::read_to_string(vault.join("attachments/notebook.md")).unwrap(), + "top-level snapshot" + ); + assert!(!attachments.join("extra.png").exists()); + assert_eq!( + fs::read_to_string(vault.join(".helixnotes/settings.json")).unwrap(), + "keep" + ); + } + + #[test] + fn checksum_failure_preserves_notes_and_attachments() { + let root = tempdir().unwrap(); + let vault = root.path().join("vault"); + let output = root.path().join("backups"); + fs::create_dir_all(vault.join(".helixnotes/attachments")).unwrap(); + fs::create_dir_all(&output).unwrap(); + fs::write(vault.join("note.md"), "live-note").unwrap(); + fs::write(vault.join(".helixnotes/attachments/photo"), "live-photo").unwrap(); + let archive_path = output.join("legacy.zip"); + let mut zip = ZipWriter::new(File::create(&archive_path).unwrap()); + let options = + SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + zip.start_file("note.md", options).unwrap(); + zip.write_all(b"archived-note").unwrap(); + zip.start_file(".helixnotes/attachments/photo", options) + .unwrap(); + zip.write_all(b"archived-photo").unwrap(); + zip.finish().unwrap(); + let mut bytes = fs::read(&archive_path).unwrap(); + let start = bytes + .windows(13) + .position(|window| window == b"archived-note") + .unwrap(); + bytes[start] = b'X'; + fs::write(&archive_path, bytes).unwrap(); + assert!( + restore_backup(&vault_string(&vault), &output, &vault_string(&archive_path)).is_err() + ); + assert_eq!( + fs::read_to_string(vault.join("note.md")).unwrap(), + "live-note" + ); + assert_eq!( + fs::read_to_string(vault.join(".helixnotes/attachments/photo")).unwrap(), + "live-photo" + ); + } + + #[test] + fn understated_manifest_size_cannot_bypass_extraction_bound() { + let root = tempdir().unwrap(); + let vault = root.path().join("vault"); + let output = root.path().join("backups"); + fs::create_dir_all(&vault).unwrap(); + fs::create_dir_all(&output).unwrap(); + fs::write(vault.join("note.md"), "live-note").unwrap(); + let archive_path = output.join("malformed.zip"); + let mut zip = ZipWriter::new(File::create(&archive_path).unwrap()); + zip.start_file( + super::MANIFEST, + SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored), + ) + .unwrap(); + zip.write_all(br#"{"version":1,"vault":"source","attachments":false}"#) + .unwrap(); + zip.write_all(&[b' '; 64 * 1024]).unwrap(); + zip.finish().unwrap(); + let mut bytes = fs::read(&archive_path).unwrap(); + let central = bytes + .windows(4) + .position(|part| part == b"PK\x01\x02") + .unwrap(); + bytes[22..26].copy_from_slice(&96u32.to_le_bytes()); + bytes[central + 24..central + 28].copy_from_slice(&96u32.to_le_bytes()); + fs::write(&archive_path, bytes).unwrap(); + + assert!( + restore_backup(&vault_string(&vault), &output, &vault_string(&archive_path)).is_err() + ); + assert_eq!( + fs::read_to_string(vault.join("note.md")).unwrap(), + "live-note" + ); + } + + #[test] + fn legacy_archives_without_attachments_keep_existing_attachments() { + let root = tempdir().unwrap(); + let vault = root.path().join("vault"); + let output = root.path().join("backups"); + fs::create_dir_all(vault.join(".helixnotes/attachments")).unwrap(); + fs::create_dir_all(&output).unwrap(); + fs::write(vault.join("note.md"), "live").unwrap(); + fs::write(vault.join(".helixnotes/attachments/photo"), "untouched").unwrap(); + let archive_path = output.join("legacy.zip"); + let mut zip = ZipWriter::new(File::create(&archive_path).unwrap()); + zip.start_file("note.md", SimpleFileOptions::default()) + .unwrap(); + zip.write_all(b"restored").unwrap(); + zip.finish().unwrap(); + restore_backup(&vault_string(&vault), &output, &vault_string(&archive_path)).unwrap(); + assert_eq!( + fs::read_to_string(vault.join("note.md")).unwrap(), + "restored" + ); + assert_eq!( + fs::read_to_string(vault.join(".helixnotes/attachments/photo")).unwrap(), + "untouched" + ); + } + + #[test] + fn unsafe_archives_do_not_modify_the_vault() { + let root = tempdir().unwrap(); + let vault = root.path().join("vault"); + let output = root.path().join("backups"); + fs::create_dir_all(vault.join(".helixnotes")).unwrap(); + fs::create_dir_all(&output).unwrap(); + fs::write(vault.join("note.md"), "original").unwrap(); + fs::write(vault.join(".helixnotes/settings.json"), "settings").unwrap(); + for bad_name in [ + "../escape.md", + ".helixnotes/settings.json", + "dir/../../escape.md", + ] { + let archive_path = output.join("unsafe.zip"); + let mut zip = ZipWriter::new(File::create(&archive_path).unwrap()); + zip.start_file("note.md", SimpleFileOptions::default()) + .unwrap(); + zip.write_all(b"replacement").unwrap(); + zip.start_file(bad_name, SimpleFileOptions::default()) + .unwrap(); + zip.write_all(b"unsafe").unwrap(); + zip.finish().unwrap(); + assert!( + restore_backup(&vault_string(&vault), &output, &vault_string(&archive_path)) + .is_err() + ); + assert_eq!( + fs::read_to_string(vault.join("note.md")).unwrap(), + "original" + ); + assert_eq!( + fs::read_to_string(vault.join(".helixnotes/settings.json")).unwrap(), + "settings" + ); + assert!(!root.path().join("escape.md").exists()); + } + } + + #[test] + fn explicit_restore_into_a_different_vault_accepts_selected_backup() { + let root = tempdir().unwrap(); + let source = root.path().join("source"); + let recovered = root.path().join("recovered"); + let output = root.path().join("backups"); + fs::create_dir_all(&source).unwrap(); + fs::create_dir_all(&recovered).unwrap(); + fs::write(source.join("note.md"), "source content").unwrap(); + fs::write(recovered.join("note.md"), "stale content").unwrap(); + let entry = create_backup(&vault_string(&source), &output, false).unwrap(); + assert!(list_backups(&output, &vault_string(&recovered)) + .unwrap() + .iter() + .any(|candidate| candidate.path == entry.path)); + cleanup_old_backups(&output, &vault_string(&recovered), 0).unwrap(); + assert!(Path::new(&entry.path).exists()); + restore_backup(&vault_string(&recovered), &output, &entry.path).unwrap(); + assert_eq!( + fs::read_to_string(recovered.join("note.md")).unwrap(), + "source content" + ); + } } diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index a6f83a6..b669b85 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -2,10 +2,10 @@ use crate::asset_scope; use crate::search::SearchIndex; use crate::state::AppState; use crate::types::*; -use crate::vault::{operations, watcher}; +use crate::vault::operations; use std::path::{Path, PathBuf}; use std::sync::Arc; -use tauri::{AppHandle, Manager, Runtime, State}; +use tauri::{AppHandle, Emitter, Manager, Runtime, State}; use tauri_plugin_fs::FsExt; fn index_note_bg(search: Option>, path: &str) { @@ -27,6 +27,45 @@ fn remove_note_bg(search: Option>, path: &str) { } } +#[derive(Clone, serde::Serialize)] +struct PathMovedEvent<'a> { + vault_path: &'a str, + old_path: &'a str, + new_path: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + old_raw: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + new_raw: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + old_title: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + new_title: Option<&'a str>, +} + +fn emit_path_move( + app: &AppHandle, + vault: &str, + old: &str, + new: &str, + renamed: Option<&operations::RenamedNote>, +) { + // Called before releasing note_save; watcher reconciliation takes that lock too. + if let Err(error) = app.emit( + "vault-path-moved", + PathMovedEvent { + vault_path: vault, + old_path: old, + new_path: new, + old_raw: renamed.map(|note| note.old_raw.as_str()), + new_raw: renamed.map(|note| note.new_raw.as_str()), + old_title: renamed.map(|note| note.old_title.as_str()), + new_title: renamed.map(|note| note.new_title.as_str()), + }, + ) { + log::error!("Could not notify note windows about a moved path: {error}"); + } +} + // ── Vault Management ── #[cfg(target_os = "ios")] @@ -62,13 +101,12 @@ fn open_vault_path( // Stage the search index and watcher before replacing the active runtime. let search = state.search_index_for_vault(&path)?; - let new_watcher = watcher::start_watcher(app.clone(), path.clone())?; asset_scope::allow_vault_assets(&app, Path::new(&path))?; + state.ensure_vault_watcher(&app, &path)?; // Update config. External vaults use the bookmark as their stable identity; // the resolved path is refreshed whenever the vault opens. let mut search_slot = state.search_index.lock().map_err(|e| e.to_string())?; - let mut watcher_slot = state.watcher.lock().map_err(|e| e.to_string())?; let mut config = state.config.lock().map_err(|e| e.to_string())?; let mut next = config.clone(); let active_bookmark_id = external @@ -108,16 +146,18 @@ fn open_vault_path( } next.active_vault = Some(path); next.active_bookmark_id = active_bookmark_id; - save_app_config(&next)?; + if let Err(error) = save_app_config(&next) { + drop(config); + drop(search_slot); + let _ = state.retain_vault_watchers(); + return Err(error); + } let old_search = search_slot.replace(search.clone()); - let old_watcher = watcher_slot.replace(new_watcher); *config = next; drop(config); - drop(watcher_slot); drop(search_slot); - // Watcher shutdown and index disposal may block; never do either while a - // global state slot is locked. - drop(old_watcher); + // Index disposal and watcher shutdown must not hold global state slots. + state.retain_vault_watchers()?; drop(old_search); Ok(search) @@ -286,7 +326,6 @@ fn remove_vault_path( .search_index .lock() .map_err(|error| error.to_string())?; - let mut watcher_slot = state.watcher.lock().map_err(|error| error.to_string())?; let mut config = state.config.lock().map_err(|error| error.to_string())?; let target = if let Some(bookmark_id) = bookmark_id.as_deref() { config @@ -312,6 +351,8 @@ fn remove_vault_path( let Some((target_path, target_bookmark, is_active)) = target else { return Ok(()); }; + #[cfg(desktop)] + AppState::ensure_no_detached_windows(app, &target_path)?; let old = config.clone(); let mut next = old.clone(); @@ -343,12 +384,10 @@ fn remove_vault_path( let _ = (app, &target_bookmark); let old_search = if is_active { search_slot.take() } else { None }; - let old_watcher = if is_active { watcher_slot.take() } else { None }; *config = next; drop(config); - drop(watcher_slot); drop(search_slot); - drop(old_watcher); + state.retain_vault_watchers()?; drop(old_search); Ok(()) @@ -361,9 +400,26 @@ pub fn get_app_config(state: State<'_, AppState>) -> Result { } #[tauri::command] -pub fn get_pending_open_file(state: State<'_, AppState>) -> Result, String> { - let mut pending = state.pending_open_file.lock().map_err(|e| e.to_string())?; - Ok(pending.take()) +pub fn get_pending_open_file( + state: State<'_, AppState>, +) -> Result, String> { + state.peek_pending_open_file() +} + +#[tauri::command] +pub fn ack_pending_open_file(state: State<'_, AppState>, id: u64) -> Result<(), String> { + if !state.ack_pending_open_file(id)? { + return Err("File-open request is no longer pending".to_string()); + } + Ok(()) +} + +#[cfg(desktop)] +#[tauri::command] +pub fn cancel_window_close(state: State<'_, AppState>) { + state + .quitting + .store(false, std::sync::atomic::Ordering::Relaxed); } /// Finish a desktop close request only after the frontend has flushed its editor. @@ -637,7 +693,8 @@ pub async fn create_notebook( } #[tauri::command] -pub async fn rename_notebook( +pub async fn rename_notebook( + app: AppHandle, state: State<'_, AppState>, vault_path: String, path: String, @@ -646,6 +703,7 @@ pub async fn rename_notebook( let search = state.vault_snapshot(&vault_path)?; let _write_guard = state.note_save.lock().await; let renamed = operations::rename_notebook(&vault_path, &path, &new_name)?; + emit_path_move(&app, &vault_path, &path, &renamed, None); if let Some(search) = search { if let Err(error) = search.queue_vault_refresh(&vault_path) { log::error!("Failed to queue renamed notebook search refresh: {error}"); @@ -655,7 +713,8 @@ pub async fn rename_notebook( } #[tauri::command] -pub async fn move_notebook( +pub async fn move_notebook( + app: AppHandle, state: State<'_, AppState>, vault_path: String, notebook_path: String, @@ -665,32 +724,8 @@ pub async fn move_notebook( let _write_guard = state.note_save.lock().await; let vault_path = vault_path.as_str(); - let old_relative = Path::new(¬ebook_path) - .strip_prefix(vault_path) - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_default(); - let new_full_path = operations::move_notebook(vault_path, ¬ebook_path, &dest_parent)?; - - let new_relative = Path::new(&new_full_path) - .strip_prefix(vault_path) - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_default(); - - // Update Quick Access paths for all notes inside the moved notebook - if let Ok(mut qa) = operations::load_quick_access(vault_path) { - let old_prefix = format!("{}/", old_relative); - let mut changed = false; - for path in qa.iter_mut() { - if path.starts_with(&old_prefix) { - *path = format!("{}/{}", new_relative, &path[old_prefix.len()..]); - changed = true; - } - } - if changed { - let _ = operations::save_quick_access(vault_path, &qa); - } - } + emit_path_move(&app, vault_path, ¬ebook_path, &new_full_path, None); // Reconcile renamed paths without blocking the move on a full rebuild. if let Some(search) = search { @@ -759,7 +794,8 @@ pub async fn save_note( path: String, meta: NoteMeta, body: String, -) -> Result<(), String> { + expected_raw: String, +) -> Result { let search = state.vault_snapshot(&vault_path)?; let max_versions = state .config @@ -773,7 +809,8 @@ pub async fn save_note( tauri::async_runtime::spawn_blocking(move || { // Keep ordering even if the calling window closes while its save runs. let _save_guard = save_guard; - if let Some(saved) = operations::save_note(&vault_path, &path, &meta, &body)? { + if let Some(saved) = operations::save_note(&vault_path, &path, &meta, &body, &expected_raw)? + { crate::history::maybe_snapshot( &vault_path, &saved.id, @@ -782,7 +819,7 @@ pub async fn save_note( ); index_note_bg(search, &path); } - Ok(()) + operations::read_vault_note(&vault_path, &path) }) .await .map_err(|error| error.to_string())? @@ -840,7 +877,8 @@ pub async fn create_daily_note( } #[tauri::command] -pub async fn rename_note( +pub async fn rename_note( + app: AppHandle, state: State<'_, AppState>, vault_path: String, path: String, @@ -849,12 +887,13 @@ pub async fn rename_note( let search = state.vault_snapshot(&vault_path)?; let _write_guard = state.note_save.lock().await; let renamed = operations::rename_note(&path, &new_title, &vault_path)?; + emit_path_move(&app, &vault_path, &path, &renamed.path, Some(&renamed)); if let Some(search) = search { if let Err(error) = search.queue_vault_refresh(&vault_path) { log::error!("Failed to queue renamed note search refresh: {error}"); } } - Ok(renamed) + Ok(renamed.path) } #[tauri::command] @@ -874,7 +913,8 @@ pub async fn delete_note( } #[tauri::command] -pub async fn move_note( +pub async fn move_note( + app: AppHandle, state: State<'_, AppState>, vault_path: String, note_path: String, @@ -884,29 +924,9 @@ pub async fn move_note( let _write_guard = state.note_save.lock().await; let vault_path = vault_path.as_str(); - // Compute old relative path before move - let old_relative = Path::new(¬e_path) - .strip_prefix(vault_path) - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_default(); - let new_full_path = operations::move_note(vault_path, ¬e_path, &dest_notebook)?; + emit_path_move(&app, vault_path, ¬e_path, &new_full_path, None); - // Update quick access if the moved note was in it - if !old_relative.is_empty() { - if let Ok(mut qa) = operations::load_quick_access(vault_path) { - if let Some(pos) = qa.iter().position(|p| *p == old_relative) { - let new_relative = Path::new(&new_full_path) - .strip_prefix(vault_path) - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_default(); - if !new_relative.is_empty() { - qa[pos] = new_relative; - let _ = operations::save_quick_access(vault_path, &qa); - } - } - } - } index_note_bg(search.clone(), ¬e_path); index_note_bg(search, &new_full_path); @@ -1394,6 +1414,7 @@ pub async fn set_task_done( let NoteContent { meta, content: body, + raw, .. } = operations::read_vault_note(&vault_path, ¬e_path)?; let mut lines: Vec = body.lines().map(|l| l.to_string()).collect(); @@ -1416,7 +1437,7 @@ pub async fn set_task_done( if body.ends_with('\n') && !new_body.ends_with('\n') { new_body.push('\n'); } - if operations::save_note(&vault_path, ¬e_path, &meta, &new_body)?.is_some() { + if operations::save_note(&vault_path, ¬e_path, &meta, &new_body, &raw)?.is_some() { index_note_bg(search, ¬e_path); } Ok(()) @@ -1455,6 +1476,7 @@ pub async fn set_task_priority( let NoteContent { meta, content: body, + raw, .. } = operations::read_vault_note(&vault_path, ¬e_path)?; let mut lines: Vec = body.lines().map(|l| l.to_string()).collect(); @@ -1476,7 +1498,7 @@ pub async fn set_task_priority( if body.ends_with('\n') && !new_body.ends_with('\n') { new_body.push('\n'); } - if operations::save_note(&vault_path, ¬e_path, &meta, &new_body)?.is_some() { + if operations::save_note(&vault_path, ¬e_path, &meta, &new_body, &raw)?.is_some() { index_note_bg(search, ¬e_path); } Ok(()) @@ -1514,6 +1536,7 @@ pub async fn set_task_due( let NoteContent { meta, content: body, + raw, .. } = operations::read_vault_note(&vault_path, ¬e_path)?; let mut lines: Vec = body.lines().map(|l| l.to_string()).collect(); @@ -1535,7 +1558,7 @@ pub async fn set_task_due( if body.ends_with('\n') && !new_body.ends_with('\n') { new_body.push('\n'); } - if operations::save_note(&vault_path, ¬e_path, &meta, &new_body)?.is_some() { + if operations::save_note(&vault_path, ¬e_path, &meta, &new_body, &raw)?.is_some() { index_note_bg(search, ¬e_path); } Ok(()) @@ -2393,6 +2416,7 @@ pub fn import_obsidian(app: AppHandle) -> Result<(), String> { fn do_import_obsidian(app: AppHandle, vault_path: &str) -> Result { let state = app.state::(); + let _maintenance_guard = state.vault_maintenance.blocking_lock(); let _write_guard = state.note_save.blocking_lock(); ensure_cleanup_idle(&state)?; state @@ -3057,89 +3081,67 @@ pub fn write_bytes_to(app: AppHandle, destination: String, data: Vec) -> Res // ── Backup ── #[tauri::command] -pub fn create_backup(app: AppHandle) -> Result<(), String> { - let (vault_path, backup_dir, include_attachments, max_count) = { +pub fn create_backup(app: AppHandle, vault_path: String) -> Result<(), String> { + let (backup_dir, include_attachments, max_count, bookmark_id) = { let state = app.state::(); + state.validate_vault(&vault_path)?; let config = state.config.lock().map_err(|e| e.to_string())?; - let vault_path = config.active_vault.clone().ok_or("No active vault")?; - let backup_dir = crate::backup::get_backup_dir(&config.backup_location)?; + let bookmark_id = config + .vaults + .iter() + .find(|vault| vault.path == vault_path) + .and_then(|vault| vault.bookmark_id.clone()); ( - vault_path, - backup_dir, + crate::backup::get_backup_dir(&config.backup_location)?, config.backup_include_attachments, config.backup_max_count, + bookmark_id, ) }; std::thread::spawn(move || { use tauri::Emitter; - match crate::backup::create_backup(&vault_path, &backup_dir, include_attachments) { - Ok(entry) => { - // Update last backup time - let state = app.state::(); - if let Ok(mut config) = state.config.lock() { - config.last_backup_time = Some(entry.created.clone()); - let _ = save_app_config(&config); - } - // Cleanup old backups - let _ = crate::backup::cleanup_old_backups(&backup_dir, max_count); - let _ = app.emit( - "backup-done", - serde_json::json!({ - "success": true, - "entry": entry, - }), - ); - } - Err(e) => { - let _ = app.emit( - "backup-done", - serde_json::json!({ - "success": false, - "error": e, - }), - ); - } - } - }); - Ok(()) -} - -#[tauri::command] -pub fn list_backups(state: State<'_, AppState>) -> Result, String> { - let config = state.config.lock().map_err(|e| e.to_string())?; - let backup_dir = crate::backup::get_backup_dir(&config.backup_location)?; - crate::backup::list_backups(&backup_dir) -} - -#[tauri::command] -pub fn restore_backup(app: AppHandle, backup_path: String) -> Result<(), String> { - let (vault_path, backup_dir) = { let state = app.state::(); - let config = state.config.lock().map_err(|e| e.to_string())?; - ( - config.active_vault.clone().ok_or("No active vault")?, - crate::backup::get_backup_dir(&config.backup_location)?, - ) - }; - - std::thread::spawn(move || { - use tauri::Emitter; - match crate::backup::restore_backup(&vault_path, &backup_dir, &backup_path) { - Ok(()) => { + let _maintenance = state.vault_maintenance.blocking_lock(); + let result = { + let _writes = state.note_save.blocking_lock(); + crate::backup::create_backup(&vault_path, &backup_dir, include_attachments) + }; + match result { + Ok(entry) => { + if let Ok(mut config) = state.config.lock() { + let mut next = config.clone(); + if let Some(vault) = next.vaults.iter_mut().find(|candidate| { + vault_matches_identity(candidate, &vault_path, bookmark_id.as_deref()) + }) { + vault.last_backup_time = Some(entry.created.clone()); + match save_app_config(&next) { + Ok(()) => *config = next, + Err(error) => { + log::error!("Could not persist backup timestamp: {error}") + } + } + } + } + if let Err(error) = + crate::backup::cleanup_old_backups(&backup_dir, &vault_path, max_count) + { + log::error!("Could not prune completed backups: {error}"); + } let _ = app.emit( - "restore-done", + "backup-done", serde_json::json!({ - "success": true, + "vault_path": vault_path, "bookmark_id": bookmark_id, + "success": true, "entry": entry, }), ); } - Err(e) => { + Err(error) => { let _ = app.emit( - "restore-done", + "backup-done", serde_json::json!({ - "success": false, - "error": e, + "vault_path": vault_path, "bookmark_id": bookmark_id, + "success": false, "error": error, }), ); } @@ -3149,9 +3151,98 @@ pub fn restore_backup(app: AppHandle, backup_path: String) -> Result<(), String> } #[tauri::command] -pub fn delete_backup(state: State<'_, AppState>, backup_path: String) -> Result<(), String> { - let config = state.config.lock().map_err(|error| error.to_string())?; - let backup_dir = crate::backup::get_backup_dir(&config.backup_location)?; +pub async fn list_backups( + state: State<'_, AppState>, + vault_path: String, +) -> Result, String> { + state.validate_vault(&vault_path)?; + let backup_dir = { + let config = state.config.lock().map_err(|e| e.to_string())?; + crate::backup::get_backup_dir(&config.backup_location)? + }; + tauri::async_runtime::spawn_blocking(move || { + crate::backup::list_backups(&backup_dir, &vault_path) + }) + .await + .map_err(|error| error.to_string())? +} + +#[tauri::command] +pub fn restore_backup( + app: AppHandle, + vault_path: String, + backup_path: String, +) -> Result<(), String> { + let backup_dir = { + let state = app.state::(); + state.validate_vault(&vault_path)?; + let config = state.config.lock().map_err(|e| e.to_string())?; + crate::backup::get_backup_dir(&config.backup_location)? + }; + + std::thread::spawn(move || { + use std::sync::atomic::Ordering; + use tauri::Emitter; + let state = app.state::(); + let _maintenance = state.vault_maintenance.blocking_lock(); + let result = { + let _writes = state.note_save.blocking_lock(); + state.importing.store(true, Ordering::Release); + let result = crate::backup::restore_backup(&vault_path, &backup_dir, &backup_path); + state.importing.store(false, Ordering::Release); + result + }; + match result { + Ok(()) => { + if let Ok(Some(search)) = state.vault_snapshot(&vault_path) { + if let Err(error) = search.queue_vault_refresh(&vault_path) { + log::error!("Could not refresh restored vault search: {error}"); + } + } + let _ = app.emit( + "file-changed", + FileEvent { + vault_path: vault_path.clone(), + event_type: "modify".into(), + path: vault_path.clone(), + note: None, + }, + ); + let _ = app.emit( + "vault-restored", + serde_json::json!({ "vault_path": vault_path }), + ); + let _ = app.emit( + "restore-done", + serde_json::json!({ + "vault_path": vault_path, "success": true, + }), + ); + } + Err(error) => { + let _ = app.emit( + "restore-done", + serde_json::json!({ + "vault_path": vault_path, "success": false, "error": error, + }), + ); + } + } + }); + Ok(()) +} + +#[tauri::command] +pub fn delete_backup( + state: State<'_, AppState>, + vault_path: String, + backup_path: String, +) -> Result<(), String> { + state.validate_vault(&vault_path)?; + let backup_dir = { + let config = state.config.lock().map_err(|error| error.to_string())?; + crate::backup::get_backup_dir(&config.backup_location)? + }; crate::backup::delete_backup(&backup_dir, &backup_path) } @@ -3499,13 +3590,13 @@ pub fn sync_now(app: AppHandle) -> Result<(), String> { } let _ = app.emit( "sync-done", - serde_json::json!({ "success": true, "summary": summary, "last_sync_time": ts }), + serde_json::json!({ "vault_path": vault, "bookmark_id": bookmark_id, "success": true, "summary": summary, "last_sync_time": ts }), ); } Err(e) => { let _ = app.emit( "sync-error", - serde_json::json!({ "success": false, "error": e }), + serde_json::json!({ "vault_path": vault, "success": false, "error": e }), ); } } @@ -3933,6 +4024,62 @@ mod mutation_order_tests { use super::*; use futures::FutureExt; + #[tokio::test] + async fn concurrent_editors_reject_stale_baselines_and_accept_the_saved_revision() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path().to_string_lossy().into_owned(); + operations::ensure_vault_structure(&root).unwrap(); + let entry = operations::create_note(&root, None, "Shared").unwrap(); + let initial = operations::read_note(&root, &entry.path).unwrap(); + let app = tauri::test::mock_builder() + .manage(AppState::new(AppConfig { + active_vault: Some(root.clone()), + ..AppConfig::default() + })) + .build(tauri::test::mock_context(tauri::test::noop_assets())) + .unwrap(); + let state = app.state::(); + let held = state.note_save.lock().await; + let mut first = Box::pin(save_note( + app.state(), + root.clone(), + entry.path.clone(), + initial.meta.clone(), + "# Shared\n\nFirst editor's content".into(), + initial.raw.clone(), + )); + let mut stale = Box::pin(save_note( + app.state(), + root.clone(), + entry.path.clone(), + initial.meta.clone(), + "# Shared\n\nStale editor's content".into(), + initial.raw, + )); + assert!(first.as_mut().now_or_never().is_none()); + assert!(stale.as_mut().now_or_never().is_none()); + drop(held); + let accepted = first.await.unwrap(); + assert!(stale.await.is_err()); + assert_eq!(std::fs::read_to_string(&entry.path).unwrap(), accepted.raw); + assert_eq!(accepted.content, "# Shared\n\nFirst editor's content"); + let subsequent = save_note( + app.state(), + root.clone(), + entry.path.clone(), + accepted.meta, + "# Shared\n\nNext accepted edit".into(), + accepted.raw, + ) + .await + .unwrap(); + assert_eq!(subsequent.content, "# Shared\n\nNext accepted edit"); + assert_eq!( + std::fs::read_to_string(&entry.path).unwrap(), + subsequent.raw + ); + } + #[tokio::test] async fn detached_history_quick_access_titles_and_graph_keep_their_origin() { let first = tempfile::tempdir().unwrap(); @@ -4094,6 +4241,7 @@ mod mutation_order_tests { alpha.path.clone(), alpha.meta.clone(), "# Shared\n\nQueued save".into(), + std::fs::read_to_string(&alpha.path).unwrap(), )); assert!(creating.as_mut().now_or_never().is_none()); assert!(saving.as_mut().now_or_never().is_none()); @@ -4126,6 +4274,7 @@ mod mutation_order_tests { alpha.path.clone(), alpha.meta, "# Shared\n\nDetached save".into(), + std::fs::read_to_string(&alpha.path).unwrap(), ) .await .unwrap(); @@ -4222,6 +4371,7 @@ mod mutation_order_tests { Some("builtin:briefcase".into()), )); let mut renaming = Box::pin(rename_notebook( + app.handle().clone(), app.state(), path.clone(), vault.path().join("Projects").to_string_lossy().into_owned(), @@ -4233,6 +4383,7 @@ mod mutation_order_tests { changing.await.unwrap(); let renamed = renaming.await.unwrap(); move_notebook( + app.handle().clone(), app.state(), path.clone(), renamed, @@ -4298,6 +4449,7 @@ mod mutation_order_tests { note.path.clone(), note.meta, "# Draft\n\nSaved before search is ready.".into(), + std::fs::read_to_string(¬e.path).unwrap(), ) .await .unwrap(); @@ -4324,13 +4476,21 @@ mod mutation_order_tests { let saving = state.note_save.lock().await; let mut moving = Box::pin(move_note( + app.handle().clone(), app.state(), vault_path.clone(), entry.path.clone(), archive.to_string_lossy().into_owned(), )); assert!(moving.as_mut().now_or_never().is_none()); - operations::save_note(&vault_path, &entry.path, &entry.meta, "Latest saved text").unwrap(); + operations::save_note( + &vault_path, + &entry.path, + &entry.meta, + "Latest saved text", + &std::fs::read_to_string(&entry.path).unwrap(), + ) + .unwrap(); drop(saving); let moved_path = moving.await.unwrap(); assert!(!Path::new(&entry.path).exists()); @@ -4349,6 +4509,7 @@ mod mutation_order_tests { &moved_path, &moved.meta, "Latest text before trash", + &moved.raw, ) .unwrap(); drop(saving); diff --git a/src-tauri/src/history.rs b/src-tauri/src/history.rs index c005a07..350edeb 100644 --- a/src-tauri/src/history.rs +++ b/src-tauri/src/history.rs @@ -24,6 +24,63 @@ fn history_dir(vault_path: &str, note_id: &str) -> Result { .join(safe_path_component(note_id, "note ID")?)) } +fn snapshot_path(dir: &Path, raw_content: &str) -> Result<(), String> { + use std::io::Write; + let mut temporary = tempfile::Builder::new() + .prefix(".helixnotes-history-") + .tempfile_in(dir) + .map_err(|error| error.to_string())?; + temporary + .write_all(raw_content.as_bytes()) + .map_err(|error| error.to_string())?; + temporary + .as_file() + .sync_all() + .map_err(|error| error.to_string())?; + let mut instant = Utc::now(); + loop { + // Fractional seconds keep timestamps valid RFC3339 for the UI while + // allowing multiple versions within one second. + let timestamp = instant.format("%Y-%m-%dT%H-%M-%S%.3f"); + let path = dir.join(format!("{timestamp}.md")); + match temporary.persist_noclobber(&path) { + Ok(_) => return Ok(()), + Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => { + temporary = error.file; + instant += chrono::Duration::milliseconds(1); + } + Err(error) => return Err(error.error.to_string()), + } + } +} + +fn version_timestamp(filename: &str) -> String { + match (filename.get(..13), filename.get(14..16), filename.get(17..)) { + (Some(hour), Some(minute), Some(rest)) + if filename.as_bytes().get(10) == Some(&b'T') + && filename.as_bytes().get(13) == Some(&b'-') + && filename.as_bytes().get(16) == Some(&b'-') => + { + format!("{hour}:{minute}:{rest}Z") + } + _ => filename.to_string(), + } +} + +fn snapshot_filename(timestamp: &str) -> String { + let time = timestamp.strip_suffix('Z').unwrap_or(timestamp); + match (time.get(..13), time.get(14..16), time.get(17..)) { + (Some(hour), Some(minute), Some(rest)) + if time.as_bytes().get(10) == Some(&b'T') + && time.as_bytes().get(13) == Some(&b':') + && time.as_bytes().get(16) == Some(&b':') => + { + format!("{hour}-{minute}-{rest}.md") + } + _ => format!("{timestamp}.md"), + } +} + /// Save a version snapshot if enough time has passed since the last one. /// Minimum interval: 5 minutes between snapshots. pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_versions: u32) { @@ -32,31 +89,34 @@ pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_ve return; }; - // Check if we should create a snapshot (5 min cooldown) + // Old second-resolution and new fractional-second names share the first + // 19 ASCII bytes. Ignore arbitrary files (including malformed Unicode). if let Ok(entries) = fs::read_dir(&dir) { - let mut files: Vec = entries - .filter_map(|e| e.ok()) - .filter_map(|e| e.file_name().to_str().map(|s| s.to_string())) - .filter(|n| n.ends_with(".md")) - .collect(); - files.sort(); - - if let Some(last) = files.last() { - if let Some(ts) = last.strip_suffix(".md") { - // Parse timestamp: 2026-02-08T18-30-00.md - if let Some(t_pos) = ts.find('T') { - let date_part = &ts[..t_pos]; - let time_part = &ts[t_pos + 1..]; - let time_colons = time_part.replace('-', ":"); - let iso = format!("{}T{}Z", date_part, time_colons); - if let Ok(last_time) = iso.parse::>() { - let elapsed = Utc::now() - last_time; - if elapsed.num_minutes() < 5 { - return; // Too soon, skip - } - } + let latest = entries + .filter_map(|entry| { + let name = entry.ok()?.file_name(); + let name = name.to_str()?; + if !name.ends_with(".md") { + return None; } - } + let (Some(hour), Some(minute), Some(second)) = + (name.get(..13), name.get(14..16), name.get(17..19)) + else { + return None; + }; + if name.as_bytes().get(10) != Some(&b'T') + || name.as_bytes().get(13) != Some(&b'-') + || name.as_bytes().get(16) != Some(&b'-') + { + return None; + } + format!("{hour}:{minute}:{second}Z") + .parse::>() + .ok() + }) + .max(); + if latest.is_some_and(|last| (Utc::now() - last).num_minutes() < 5) { + return; } } @@ -66,12 +126,8 @@ pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_ve return; } - let timestamp = Utc::now().format("%Y-%m-%dT%H-%M-%S").to_string(); - let filename = format!("{}.md", timestamp); - let path = dir.join(&filename); - - if let Err(e) = fs::write(&path, raw_content) { - eprintln!("Failed to write version snapshot: {}", e); + if let Err(error) = snapshot_path(&dir, raw_content) { + eprintln!("Failed to write version snapshot: {error}"); return; } @@ -91,11 +147,7 @@ pub fn force_snapshot( let dir = history_dir(vault_path, note_id)?; fs::create_dir_all(&dir).map_err(|error| error.to_string())?; - let timestamp = Utc::now().format("%Y-%m-%dT%H-%M-%S").to_string(); - let filename = format!("{}.md", timestamp); - let path = dir.join(&filename); - - fs::write(&path, raw_content).map_err(|error| error.to_string())?; + snapshot_path(&dir, raw_content)?; if max_versions > 0 { prune_versions(&dir, max_versions)?; @@ -123,16 +175,7 @@ pub fn list_versions(vault_path: &str, note_id: &str) -> Result Result Result { safe_path_component(timestamp, "version timestamp")?; - // Convert ISO timestamp back to filename: 2026-02-08T18:30:00Z → 2026-02-08T18-30-00.md - let filename = if let Some(t_pos) = timestamp.find('T') { - let date_part = ×tamp[..t_pos]; - let time_part = timestamp[t_pos + 1..].trim_end_matches('Z'); - let time_dashes = time_part.replace(':', "-"); - format!("{date_part}T{time_dashes}.md") - } else { - format!("{}.md", timestamp) - }; + // Accept both legacy second-resolution names and unique suffixes. + let filename = snapshot_filename(timestamp); let path = history_dir(vault_path, note_id)?.join(&filename); fs::read_to_string(&path).map_err(|e| format!("Version not found: {}", e)) @@ -206,4 +242,51 @@ mod tests { fs::remove_dir_all(vault).unwrap(); } + #[test] + fn rapid_forced_versions_are_individually_retrievable_and_prunable() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path().to_str().unwrap(); + for index in 0..200 { + super::force_snapshot(root, "note", &format!("snapshot {index}"), 0).unwrap(); + } + let versions = list_versions(root, "note").unwrap(); + assert_eq!(versions.len(), 200); + let contents: std::collections::HashSet<_> = versions + .iter() + .map(|version| get_version(root, "note", &version.timestamp).unwrap()) + .collect(); + assert_eq!(contents.len(), 200); + assert!(contents.contains("snapshot 0")); + assert!(contents.contains("snapshot 199")); + + super::force_snapshot(root, "note", "latest", 10).unwrap(); + let retained = list_versions(root, "note").unwrap(); + assert_eq!(retained.len(), 10); + assert_eq!( + get_version(root, "note", &retained[0].timestamp).unwrap(), + "latest" + ); + } + + #[test] + fn legacy_versions_remain_readable_and_recent_unique_versions_observe_cooldown() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path().to_str().unwrap(); + let history = vault.path().join(".helixnotes/history/note"); + fs::create_dir_all(&history).unwrap(); + fs::write(history.join("2026-01-01T00-00-00.md"), "legacy").unwrap(); + fs::write(history.join("2026-01-01T1é-00-00.md"), "unusual filename").unwrap(); + super::force_snapshot(root, "note", "new", 0).unwrap(); + super::maybe_snapshot(root, "note", "too soon", 0); + let versions = list_versions(root, "note").unwrap(); + assert_eq!(versions.len(), 3); + assert_eq!( + get_version(root, "note", "2026-01-01T00:00:00Z").unwrap(), + "legacy" + ); + assert_eq!( + get_version(root, "note", &versions[0].timestamp).unwrap(), + "new" + ); + } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index ff57988..2b5d813 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -146,9 +146,9 @@ pub fn run() { asset_scope::allow_external_note_assets(app.handle(), &resolved); } let app_state = app.state::(); - let _ = app_state.pending_open_file.lock().map(|mut p| { - *p = Some(resolved_str.to_string()); - }); + if let Err(error) = app_state.enqueue_open_file(resolved_str.to_string()) { + log::error!("Could not queue startup file: {error}"); + } } } } @@ -253,6 +253,9 @@ pub fn run() { commands::get_install_type, commands::is_mobile_platform, commands::get_pending_open_file, + commands::ack_pending_open_file, + #[cfg(desktop)] + commands::cancel_window_close, ]) .register_asynchronous_uri_scheme_protocol("imgproxy", |_ctx, request, responder| { let path = request.uri().path().to_string(); @@ -307,7 +310,14 @@ pub fn run() { } let _ = asset_scope::allow_external_note_assets(app, &resolved); } - let _ = app.emit("open-file", resolved_str.to_string()); + if let Err(error) = app + .state::() + .enqueue_open_file(resolved_str.to_string()) + { + log::error!("Could not queue open file: {error}"); + } else { + let _ = app.emit("open-file-pending", ()); + } } } })); diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index baf3f0a..9abf444 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -1,30 +1,145 @@ use crate::search::{SearchIndex, SearchIndexShutdown}; use crate::types::AppConfig; use crate::vault::watcher::VaultWatcher; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::atomic::AtomicBool; use std::sync::{Arc, Mutex, Weak}; +use tauri::AppHandle; +#[cfg(desktop)] +use tauri::{Manager, Runtime, Url}; + +#[cfg(desktop)] +fn is_detached_window_for_vault(label: &str, url: &Url, target_path: &str) -> bool { + label.starts_with("note-") + && url + .query_pairs() + .any(|(key, value)| key == "vault" && value == target_path) +} struct CachedSearchIndex { index: Weak, shutdown: Arc, } +#[derive(Clone, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PendingOpenFile { + pub id: u64, + pub path: String, +} + +#[derive(Default)] +struct PendingOpenFiles { + next_id: u64, + requests: VecDeque, +} + pub struct AppState { pub config: Mutex, pub search_index: Mutex>>, search_indexes: Mutex>, - pub watcher: Mutex>, + pub watchers: Mutex>, pub vault_transition: tokio::sync::Mutex<()>, + pub vault_maintenance: Arc>, pub note_save: Arc>, pub importing: AtomicBool, pub syncing: AtomicBool, #[cfg(desktop)] pub quitting: AtomicBool, - pub pending_open_file: Mutex>, + pending_open_files: Mutex, } impl AppState { + pub fn enqueue_open_file(&self, path: String) -> Result<(), String> { + let mut pending = self + .pending_open_files + .lock() + .map_err(|error| error.to_string())?; + pending.next_id += 1; + let id = pending.next_id; + pending.requests.push_back(PendingOpenFile { id, path }); + Ok(()) + } + + pub fn peek_pending_open_file(&self) -> Result, String> { + let pending = self + .pending_open_files + .lock() + .map_err(|error| error.to_string())?; + Ok(pending.requests.front().cloned()) + } + + pub fn ack_pending_open_file(&self, id: u64) -> Result { + let mut pending = self + .pending_open_files + .lock() + .map_err(|error| error.to_string())?; + if pending + .requests + .front() + .is_some_and(|request| request.id == id) + { + pending.requests.pop_front(); + Ok(true) + } else { + Ok(false) + } + } + + pub fn ensure_vault_watcher(&self, app: &AppHandle, vault_path: &str) -> Result<(), String> { + let mut watchers = self.watchers.lock().map_err(|error| error.to_string())?; + if !watchers.contains_key(vault_path) { + let watcher = crate::vault::watcher::start_watcher(app.clone(), vault_path.to_owned())?; + watchers.insert(vault_path.to_owned(), watcher); + } + Ok(()) + } + + pub fn retain_vault_watchers(&self) -> Result<(), String> { + let configured: HashSet = { + let config = self.config.lock().map_err(|error| error.to_string())?; + config + .vaults + .iter() + .map(|vault| vault.path.clone()) + .chain(config.active_vault.clone()) + .collect() + }; + let removed = { + let mut watchers = self.watchers.lock().map_err(|error| error.to_string())?; + let removed: Vec = watchers + .keys() + .filter(|path| !configured.contains(*path)) + .cloned() + .collect(); + removed + .into_iter() + .filter_map(|path| watchers.remove(&path)) + .collect::>() + }; + drop(removed); + Ok(()) + } + + #[cfg(desktop)] + pub fn ensure_no_detached_windows( + app: &AppHandle, + target_path: &str, + ) -> Result<(), String> { + for (label, window) in app.webview_windows() { + if is_detached_window_for_vault( + &label, + &window.url().map_err(|error| error.to_string())?, + target_path, + ) { + return Err( + "Close this vault's detached note windows before forgetting it.".into(), + ); + } + } + Ok(()) + } + // A refresh worker may outlive a vault switch. Reuse its writer when opening // that vault again instead of competing for Tantivy's exclusive writer lock. pub fn search_index_for_vault(&self, vault_path: &str) -> Result, String> { @@ -118,14 +233,15 @@ impl AppState { config: Mutex::new(config), search_index: Mutex::new(None), search_indexes: Mutex::new(HashMap::new()), - watcher: Mutex::new(None), + watchers: Mutex::new(HashMap::new()), vault_transition: tokio::sync::Mutex::new(()), + vault_maintenance: Arc::new(tokio::sync::Mutex::new(())), note_save: Arc::new(tokio::sync::Mutex::new(())), importing: AtomicBool::new(false), syncing: AtomicBool::new(false), #[cfg(desktop)] quitting: AtomicBool::new(false), - pending_open_file: Mutex::new(None), + pending_open_files: Mutex::new(PendingOpenFiles::default()), } } } @@ -134,6 +250,42 @@ impl AppState { mod tests { use super::*; + #[test] + fn pending_open_requests_survive_reads_and_only_acknowledge_head() { + let state = AppState::new(AppConfig::default()); + state.enqueue_open_file("one.md".into()).unwrap(); + state.enqueue_open_file("two.md".into()).unwrap(); + let first = state.peek_pending_open_file().unwrap().unwrap(); + assert_eq!(first.path, "one.md"); + assert_eq!( + state.peek_pending_open_file().unwrap().unwrap().id, + first.id + ); + assert!(!state.ack_pending_open_file(first.id + 1).unwrap()); + assert_eq!( + state.peek_pending_open_file().unwrap().unwrap().id, + first.id + ); + assert!(state.ack_pending_open_file(first.id).unwrap()); + let second = state.peek_pending_open_file().unwrap().unwrap(); + assert_eq!(second.path, "two.md"); + assert!(!state.ack_pending_open_file(first.id).unwrap()); + assert!(state.ack_pending_open_file(second.id).unwrap()); + assert!(state.peek_pending_open_file().unwrap().is_none()); + } + + #[test] + fn detached_window_owner_matches_encoded_vault_path_only() { + let url = Url::parse("tauri://localhost/?note=a.md&vault=%2Fvaults%2FA%26B").unwrap(); + assert!(is_detached_window_for_vault( + "note-123", + &url, + "/vaults/A&B" + )); + assert!(!is_detached_window_for_vault("note-123", &url, "/vaults/A")); + assert!(!is_detached_window_for_vault("main", &url, "/vaults/A&B")); + } + #[test] fn close_policy_respects_live_settings_window_type_and_explicit_quit() { let mut state = AppState::new(AppConfig { diff --git a/src-tauri/src/sync.rs b/src-tauri/src/sync.rs index 9fd9e35..a862743 100644 --- a/src-tauri/src/sync.rs +++ b/src-tauri/src/sync.rs @@ -43,29 +43,49 @@ pub struct SyncSummary { #[derive(Default, Serialize, Deserialize)] struct SyncManifest { + #[serde(default)] + identity: String, files: HashMap, // relpath (forward-slash) -> entry } #[derive(Clone, Serialize, Deserialize)] struct ManifestEntry { local_hash: String, // sha256 of local content at last sync - remote_etag: String, // remote etag at last sync + remote_etag: String, // strong remote etag at last sync, or empty + #[serde(default)] + remote_hash: String, // sha256 of remote content when no strong etag is available } fn manifest_path(vault: &str) -> PathBuf { helixnotes_dir(vault).join("sync_state.json") } -fn load_manifest(vault: &str) -> SyncManifest { - fs::read_to_string(manifest_path(vault)) - .ok() - .and_then(|s| serde_json::from_str(&s).ok()) - .unwrap_or_default() +fn load_manifest(vault: &str) -> Result { + match fs::read(manifest_path(vault)) { + Ok(bytes) => serde_json::from_slice(&bytes) + .map_err(|e| format!("Invalid sync manifest; sync stopped to protect your notes: {e}")), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(SyncManifest::default()), + Err(error) => Err(format!("Cannot read sync manifest: {error}")), + } } -fn save_manifest(vault: &str, m: &SyncManifest) { - if let Ok(s) = serde_json::to_string(m) { - let _ = fs::write(manifest_path(vault), s); +fn save_manifest(vault: &str, m: &SyncManifest) -> Result<(), String> { + let bytes = serde_json::to_vec(m).map_err(|e| e.to_string())?; + let target = manifest_path(vault); + fs::create_dir_all(target.parent().unwrap()).map_err(|e| e.to_string())?; + crate::vault::operations::replace_file_atomically(&target, &bytes) +} + +fn baseline_for_endpoint(manifest: SyncManifest, identity: &str) -> SyncManifest { + if manifest.identity == identity { + manifest + } else { + // Legacy manifests without an identity are also untrusted: they may + // belong to another server. Reconcile as two independent snapshots. + SyncManifest { + identity: identity.to_string(), + files: HashMap::new(), + } } } @@ -92,11 +112,13 @@ fn sha256_reader( } } -fn normalize_etag(s: &str) -> String { - s.trim() - .trim_start_matches("W/") - .trim_matches('"') - .to_string() +fn strong_etag(s: &str) -> String { + let s = s.trim(); + if s.starts_with("W/") || s.len() < 2 || !s.starts_with('"') || !s.ends_with('"') { + String::new() + } else { + s.to_string() + } } /// Percent-encode each path segment, keeping the `/` separators. @@ -202,23 +224,38 @@ fn scan_local(vault: &str) -> Result, String> { let vault_path = Path::new(vault); let mut map = HashMap::new(); let mut buffer = [0; HASH_BUFFER_SIZE]; - for entry in WalkDir::new(vault_path).into_iter().filter_map(|e| e.ok()) { + for entry in WalkDir::new(vault_path) { + let entry = entry.map_err(|e| format!("Cannot scan local vault: {e}"))?; let p = entry.path(); - if !p.is_file() { + // WalkDir deliberately does not follow links. A note replaced by a + // link (or a linked directory of notes) must not look like a deletion + // and authorize a remote DELETE. Do not traverse outside the vault. + if entry.file_type().is_symlink() { + return Err(format!( + "Cannot sync vault containing symbolic link {}", + p.display() + )); + } + if entry.file_type().is_dir() { continue; } - let rel = match p.strip_prefix(vault_path) { - Ok(r) => r.to_string_lossy().replace('\\', "/"), - Err(_) => continue, - }; + if !entry.file_type().is_file() { + return Err(format!( + "Cannot sync unsupported filesystem entry {}", + p.display() + )); + } + let rel = p + .strip_prefix(vault_path) + .map_err(|e| e.to_string())? + .to_string_lossy() + .replace('\\', "/"); if !is_synced_relpath(&rel) { continue; } - let hash = - match fs::File::open(p).and_then(|mut file| sha256_reader(&mut file, &mut buffer)) { - Ok(hash) => hash, - Err(_) => continue, - }; + let hash = fs::File::open(p) + .and_then(|mut file| sha256_reader(&mut file, &mut buffer)) + .map_err(|e| format!("Cannot read local file {}: {e}", p.display()))?; map.insert( rel, LocalFile { @@ -248,25 +285,38 @@ struct WebdavClient { impl WebdavClient { fn new(cfg: WebdavConfig) -> Result { - let base = cfg.url.trim().trim_end_matches('/').to_string(); - if !base.starts_with("http://") && !base.starts_with("https://") { + let mut url = + reqwest::Url::parse(cfg.url.trim()).map_err(|e| format!("Invalid WebDAV URL: {e}"))?; + if !matches!(url.scheme(), "http" | "https") { return Err("WebDAV URL must start with http:// or https://".to_string()); } - let base_url = reqwest::Url::parse(&base).map_err(|e| format!("Invalid URL: {e}"))?; - let base_path = base_url.path().trim_end_matches('/').to_string(); + if url.query().is_some() + || url.fragment().is_some() + || !url.username().is_empty() + || url.password().is_some() + { + return Err("WebDAV URL must not contain credentials, query, or fragment".to_string()); + } + let path = url.path().trim_end_matches('/').to_string(); + url.set_path(if path.is_empty() { "/" } else { &path }); + let base = url.to_string().trim_end_matches('/').to_string(); let client = reqwest::blocking::Client::builder() .timeout(std::time::Duration::from_secs(60)) .build() .map_err(|e| e.to_string())?; Ok(Self { base, - base_path, + base_path: url.path().trim_end_matches('/').to_string(), client, user: cfg.username, pass: cfg.password, }) } + fn identity(&self) -> String { + sha256_hex(format!("{}\n{}", self.base, self.user).as_bytes()) + } + fn url_for(&self, relpath: &str) -> String { if relpath.is_empty() { self.base.clone() @@ -327,57 +377,102 @@ impl WebdavClient { Ok(files) } - fn get(&self, relpath: &str) -> Result, String> { - let resp = self + fn get(&self, relpath: &str, expected_etag: &str) -> Result, String> { + let mut request = self .client .get(self.url_for(relpath)) - .basic_auth(&self.user, Some(&self.pass)) - .send() - .map_err(|e| e.to_string())?; + .basic_auth(&self.user, Some(&self.pass)); + if !expected_etag.is_empty() { + request = request.header("If-Match", expected_etag); + } + let resp = request.send().map_err(|e| e.to_string())?; + if resp.status().as_u16() == 412 { + return Err(format!( + "Remote file {relpath} changed during sync; retry sync" + )); + } if !resp.status().is_success() { return Err(format!( - "GET {} failed: HTTP {}", - relpath, + "GET {relpath} failed: HTTP {}", resp.status().as_u16() )); } - Ok(resp.bytes().map_err(|e| e.to_string())?.to_vec()) - } - - fn put(&self, relpath: &str, bytes: &[u8]) -> Result, String> { - let resp = self - .client - .put(self.url_for(relpath)) - .basic_auth(&self.user, Some(&self.pass)) - .body(bytes.to_vec()) - .send() - .map_err(|e| e.to_string())?; - if !resp.status().is_success() { - return Err(format!( - "PUT {} failed: HTTP {}", - relpath, - resp.status().as_u16() - )); - } - Ok(resp + let response_etag = resp .headers() .get("etag") .and_then(|h| h.to_str().ok()) - .map(normalize_etag)) + .map(strong_etag) + .unwrap_or_default(); + if !expected_etag.is_empty() && !response_etag.is_empty() && response_etag != expected_etag + { + return Err(format!( + "Remote file {relpath} changed during sync; retry sync" + )); + } + let bytes = resp.bytes().map_err(|e| e.to_string())?.to_vec(); + if !expected_etag.is_empty() && self.etag_for(relpath)? != expected_etag { + return Err(format!( + "Remote file {relpath} changed during sync; retry sync" + )); + } + Ok(bytes) } - fn delete(&self, relpath: &str) -> Result<(), String> { + fn put(&self, relpath: &str, bytes: &[u8], prior_etag: Option<&str>) -> Result<(), String> { + let mut request = self + .client + .put(self.url_for(relpath)) + .basic_auth(&self.user, Some(&self.pass)) + .body(bytes.to_vec()); + request = match prior_etag { + Some(etag) if !etag.is_empty() => request.header("If-Match", etag), + Some(_) => { + return Err(format!( + "Cannot safely overwrite {relpath}: server provides no strong ETag" + )) + } + None => request.header("If-None-Match", "*"), + }; + let resp = request.send().map_err(|e| e.to_string())?; + if resp.status().as_u16() == 412 { + return Err(format!( + "Remote file {relpath} changed during sync; retry sync" + )); + } + if !resp.status().is_success() { + return Err(format!( + "PUT {relpath} failed: HTTP {}", + resp.status().as_u16() + )); + } + Ok(()) + } + + fn delete(&self, relpath: &str, etag: &str) -> Result<(), String> { + if etag.is_empty() { + return Err(format!( + "Cannot safely delete {relpath}: server provides no strong ETag" + )); + } let resp = self .client .delete(self.url_for(relpath)) .basic_auth(&self.user, Some(&self.pass)) + .header("If-Match", etag) .send() .map_err(|e| e.to_string())?; - let s = resp.status(); - if s.is_success() || s.as_u16() == 404 { + if resp.status().as_u16() == 412 || resp.status().as_u16() == 404 { + return Err(format!( + "Remote file {relpath} changed during sync; retry sync" + )); + } + if resp.status().is_success() { Ok(()) } else { - Err(format!("DELETE {} failed: HTTP {}", relpath, s.as_u16())) + Err(format!( + "DELETE {relpath} failed: HTTP {}", + resp.status().as_u16() + )) } } @@ -390,16 +485,13 @@ impl WebdavClient { .send() .map_err(|e| e.to_string())?; let s = resp.status().as_u16(); - // 201 created; 405 already exists; 301 redirect-to-existing; - // 403 some servers (openmediavault et al.) return 403 instead of 405. if resp.status().is_success() || s == 405 || s == 301 || s == 403 { Ok(()) } else { - Err(format!("MKCOL {} failed: HTTP {}", relpath, s)) + Err(format!("MKCOL {relpath} failed: HTTP {s}")) } } - /// Ensure every ancestor collection of `relpath` exists on the remote. fn ensure_dirs(&self, relpath: &str, created: &mut HashSet) -> Result<(), String> { let parts: Vec<&str> = relpath.split('/').collect(); if parts.len() <= 1 { @@ -418,29 +510,30 @@ impl WebdavClient { Ok(()) } - /// Read a file's authoritative remote etag via a Depth-0 PROPFIND. The PUT-response - /// etag is unreliable across WebDAV servers (some omit it, some differ in format from - /// the getetag PROPFIND returns), so we always source the manifest etag from PROPFIND - /// to keep it consistent with future listings. (issue #147) - fn etag_for(&self, relpath: &str) -> String { - self.propfind(relpath, "0") - .ok() - .and_then(|es| es.into_iter().find(|e| !e.is_dir).map(|e| e.etag)) - .unwrap_or_default() + fn etag_for(&self, relpath: &str) -> Result { + self.propfind(relpath, "0")? + .into_iter() + .find(|e| e.relpath == relpath && !e.is_dir) + .map(|e| e.etag) + .ok_or_else(|| format!("Remote file {relpath} disappeared during sync; retry sync")) } - /// PUT a file (creating parent collections first), then read back its authoritative - /// etag via PROPFIND. Returns the PROPFIND etag (empty if the server exposes no - /// getetag), NOT the PUT-response etag, which is unreliable across servers. (issue #147) fn upload( &self, relpath: &str, bytes: &[u8], + prior_etag: Option<&str>, created: &mut HashSet, ) -> Result { self.ensure_dirs(relpath, created)?; - self.put(relpath, bytes)?; // PUT-response etag intentionally discarded - Ok(self.etag_for(relpath)) + self.put(relpath, bytes, prior_etag)?; + let etag = self.etag_for(relpath)?; + if self.get(relpath, &etag)?.as_slice() != bytes { + return Err(format!( + "Remote file {relpath} changed after upload; retry sync" + )); + } + Ok(etag) } } @@ -552,7 +645,7 @@ fn parse_multistatus(xml: &str, base_path: &str) -> Result, Str if let Some(rel) = href_to_relpath(&h, base_path)? { entries.push(RemoteEntry { relpath: rel, - etag: etag.take().map(|s| normalize_etag(&s)).unwrap_or_default(), + etag: etag.take().map(|s| strong_etag(&s)).unwrap_or_default(), is_dir, }); } @@ -570,6 +663,26 @@ fn parse_multistatus(xml: &str, base_path: &str) -> Result, Str // ───────────────────────── sync engine ───────────────────────── +fn read_scanned_local(file: &LocalFile) -> Result, String> { + let bytes = + fs::read(&file.path).map_err(|e| format!("Cannot read {}: {e}", file.path.display()))?; + if sha256_hex(&bytes) != file.hash { + return Err(format!( + "Sync stopped because {} changed locally during sync", + file.path.display() + )); + } + Ok(bytes) +} + +fn manifest_entry(hash: String, etag: &str) -> ManifestEntry { + ManifestEntry { + remote_hash: hash.clone(), + local_hash: hash, + remote_etag: etag.to_string(), + } +} + fn apply_changes( client: &WebdavClient, vault: &str, @@ -580,11 +693,13 @@ fn apply_changes( write_guard: &tokio::sync::Mutex<()>, ) -> Result<(SyncManifest, SyncSummary), String> { let vault_path = Path::new(vault); - let mut new_m = SyncManifest::default(); + let mut new_m = SyncManifest { + identity: client.identity(), + files: HashMap::new(), + }; let mut sum = SyncSummary::default(); let mut created: HashSet = HashSet::new(); let stamp = chrono::Local::now().format("%Y-%m-%d %H-%M-%S").to_string(); - let mut keys: HashSet<&String> = HashSet::new(); keys.extend(local.keys()); keys.extend(remote.keys()); @@ -594,179 +709,135 @@ fn apply_changes( let l = local.get(key); let r = remote.get(key); let m = manifest.files.get(key); - match (l, r) { - (Some(lf), Some(re)) => { - let local_changed = match m { - Some(entry) => entry.local_hash != lf.hash, - None => true, - }; - let remote_changed = match m { - Some(entry) => &entry.remote_etag != re, - None => true, - }; + (Some(lf), Some(etag)) => { + // On ETag-less servers, a listing cannot tell us if content changed. + // Read every time and compare to the last accepted remote content hash. + let remote_bytes = + if etag.is_empty() || m.is_none_or(|old| old.remote_etag != *etag) { + Some(client.get(key, etag)?) + } else { + None + }; + let remote_hash = remote_bytes.as_ref().map(|bytes| sha256_hex(bytes)); + let remote_changed = m.is_none_or(|old| { + old.remote_etag != *etag + || (etag.is_empty() + && (old.remote_hash.is_empty() + || remote_hash.as_deref() != Some(old.remote_hash.as_str()))) + }); + let local_changed = m.is_none_or(|old| old.local_hash != lf.hash); if !local_changed && !remote_changed { new_m.files.insert( key.clone(), ManifestEntry { local_hash: lf.hash.clone(), - remote_etag: re.clone(), + remote_etag: etag.clone(), + remote_hash: m.unwrap().remote_hash.clone(), }, ); } else if local_changed && !remote_changed { - let bytes = fs::read(&lf.path).map_err(|e| e.to_string())?; - let etag = client.upload(key, &bytes, &mut created)?; - new_m.files.insert( - key.clone(), - ManifestEntry { - local_hash: lf.hash.clone(), - remote_etag: etag, - }, - ); + let bytes = read_scanned_local(lf)?; + let new_etag = client.upload(key, &bytes, Some(etag), &mut created)?; + new_m + .files + .insert(key.clone(), manifest_entry(lf.hash.clone(), &new_etag)); sum.uploaded += 1; - } else if !local_changed && remote_changed { - let bytes = client.get(key)?; - write_local_if_unchanged( - write_guard, - vault_path, - key, - &bytes, - Some(&lf.hash), - changes, - )?; - new_m.files.insert( - key.clone(), - ManifestEntry { - local_hash: sha256_hex(&bytes), - remote_etag: re.clone(), - }, - ); - sum.downloaded += 1; } else { - // both changed: compare contents; identical => no real conflict. - let rbytes = client.get(key)?; - let rhash = sha256_hex(&rbytes); - if rhash == lf.hash { - new_m.files.insert( - key.clone(), - ManifestEntry { - local_hash: lf.hash.clone(), - remote_etag: re.clone(), - }, - ); + let bytes = match remote_bytes { + Some(bytes) => bytes, + None => client.get(key, etag)?, + }; + let hash = remote_hash.unwrap_or_else(|| sha256_hex(&bytes)); + if hash == lf.hash { + new_m.files.insert(key.clone(), manifest_entry(hash, etag)); + } else if !local_changed { + write_local_if_unchanged( + write_guard, + vault_path, + key, + &bytes, + Some(&lf.hash), + changes, + )?; + new_m.files.insert(key.clone(), manifest_entry(hash, etag)); + sum.downloaded += 1; } else { - // keep-both: remote becomes canonical; local saved as a conflict copy. + // Keep both, but only replace the canonical note after the + // previous local bytes have been safely copied aside. let ckey = conflict_relpath(key, &stamp); let lbytes = { let _guard = write_guard.blocking_lock(); - require_unchanged_local(&lf.path, Some(&lf.hash))?; require_unchanged_local(&vault_path.join(&ckey), None)?; - let lbytes = fs::read(&lf.path).map_err(|e| e.to_string())?; - // Preserve the local bytes before replacing their canonical path. + let lbytes = read_scanned_local(lf)?; write_local(vault_path, &ckey, &lbytes, changes)?; - write_local(vault_path, key, &rbytes, changes)?; + write_local(vault_path, key, &bytes, changes)?; lbytes }; - new_m.files.insert( - key.clone(), - ManifestEntry { - local_hash: rhash, - remote_etag: re.clone(), - }, - ); - let cetag = client.upload(&ckey, &lbytes, &mut created)?; - new_m.files.insert( - ckey, - ManifestEntry { - local_hash: sha256_hex(&lbytes), - remote_etag: cetag, - }, - ); + new_m.files.insert(key.clone(), manifest_entry(hash, etag)); + let cetag = client.upload(&ckey, &lbytes, None, &mut created)?; + new_m + .files + .insert(ckey, manifest_entry(sha256_hex(&lbytes), &cetag)); sum.conflicts += 1; } } } (Some(lf), None) => match m { None => { - // new local -> upload - let bytes = fs::read(&lf.path).map_err(|e| e.to_string())?; - let etag = client.upload(key, &bytes, &mut created)?; - new_m.files.insert( - key.clone(), - ManifestEntry { - local_hash: lf.hash.clone(), - remote_etag: etag, - }, - ); + let bytes = read_scanned_local(lf)?; + let etag = client.upload(key, &bytes, None, &mut created)?; + new_m + .files + .insert(key.clone(), manifest_entry(lf.hash.clone(), &etag)); sum.uploaded += 1; } - Some(me) => { - if me.local_hash != lf.hash { - // remote deleted but local edited -> resurrect (upload) - let bytes = fs::read(&lf.path).map_err(|e| e.to_string())?; - let etag = client.upload(key, &bytes, &mut created)?; - new_m.files.insert( - key.clone(), - ManifestEntry { - local_hash: lf.hash.clone(), - remote_etag: etag, - }, - ); - sum.uploaded += 1; - } else { - // remote deleted, local unchanged -> delete local - let _guard = write_guard.blocking_lock(); - require_unchanged_local(&lf.path, Some(&lf.hash))?; - fs::remove_file(&lf.path).map_err(|e| e.to_string())?; - changes.insert(lf.path.clone(), "remove"); - sum.deleted_local += 1; - } + Some(me) if me.local_hash != lf.hash => { + let bytes = read_scanned_local(lf)?; + let etag = client.upload(key, &bytes, None, &mut created)?; + new_m + .files + .insert(key.clone(), manifest_entry(lf.hash.clone(), &etag)); + sum.uploaded += 1; + } + Some(_) => { + let _guard = write_guard.blocking_lock(); + require_unchanged_local(&lf.path, Some(&lf.hash))?; + fs::remove_file(&lf.path).map_err(|e| e.to_string())?; + changes.insert(lf.path.clone(), "remove"); + sum.deleted_local += 1; } }, - (None, Some(re)) => match m { - None => { - // new remote -> download - let bytes = client.get(key)?; + (None, Some(etag)) => { + let bytes = if etag.is_empty() || m.is_none_or(|old| old.remote_etag != *etag) { + Some(client.get(key, etag)?) + } else { + None + }; + let remote_hash = bytes.as_ref().map(|bytes| sha256_hex(bytes)); + let remote_changed = m.is_none_or(|old| { + old.remote_etag != *etag + || (etag.is_empty() + && (old.remote_hash.is_empty() + || remote_hash.as_deref() != Some(old.remote_hash.as_str()))) + }); + if remote_changed { + let bytes = match bytes { + Some(bytes) => bytes, + None => client.get(key, etag)?, + }; write_local_if_unchanged(write_guard, vault_path, key, &bytes, None, changes)?; new_m.files.insert( key.clone(), - ManifestEntry { - local_hash: sha256_hex(&bytes), - remote_etag: re.clone(), - }, + manifest_entry(remote_hash.unwrap_or_else(|| sha256_hex(&bytes)), etag), ); sum.downloaded += 1; + } else { + client.delete(key, etag)?; + sum.deleted_remote += 1; } - Some(me) => { - if &me.remote_etag != re { - // local deleted but remote changed -> resurrect (download) - let bytes = client.get(key)?; - write_local_if_unchanged( - write_guard, - vault_path, - key, - &bytes, - None, - changes, - )?; - new_m.files.insert( - key.clone(), - ManifestEntry { - local_hash: sha256_hex(&bytes), - remote_etag: re.clone(), - }, - ); - sum.downloaded += 1; - } else { - // local deleted, remote unchanged -> delete remote - client.delete(key)?; - sum.deleted_remote += 1; - } - } - }, - (None, None) => { - // gone on both sides -> drop from manifest } + (None, None) => {} } } Ok((new_m, sum)) @@ -789,12 +860,16 @@ pub fn run_sync( use std::sync::atomic::Ordering; let state = app.state::(); + let _maintenance = state.vault_maintenance.blocking_lock(); // Keep the original vault's index even if the user switches vaults while // WebDAV is working. No config lock is held during network or file I/O. let search = state.vault_snapshot(&vault)?; let client = WebdavClient::new(cfg)?; - let _ = app.emit("sync-progress", serde_json::json!({ "status": "listing" })); + let _ = app.emit( + "sync-progress", + serde_json::json!({ "vault_path": vault, "status": "listing" }), + ); let remote: HashMap = client .list()? .into_iter() @@ -802,7 +877,10 @@ pub fn run_sync( .collect(); let (local, manifest) = { let _guard = state.note_save.blocking_lock(); - (scan_local(&vault)?, load_manifest(&vault)) + ( + scan_local(&vault)?, + baseline_for_endpoint(load_manifest(&vault)?, &client.identity()), + ) }; // Safety guard (issue #102): never treat an empty remote listing as "everything was @@ -819,7 +897,10 @@ pub fn run_sync( ); } - let _ = app.emit("sync-progress", serde_json::json!({ "status": "syncing" })); + let _ = app.emit( + "sync-progress", + serde_json::json!({ "vault_path": vault, "status": "syncing" }), + ); let mut changes = HashMap::new(); // Mute the watcher across local writes; its deferred batch also preserves // external edits that arrive while the network operation is in progress. @@ -873,7 +954,7 @@ pub fn run_sync( } let (new_manifest, summary) = applied?; - save_manifest(&vault, &new_manifest); + save_manifest(&vault, &new_manifest)?; Ok(summary) } @@ -1056,6 +1137,44 @@ mod tests { assert_eq!(actual, expected); } + #[cfg(unix)] + #[test] + fn previously_synced_note_replaced_by_link_is_not_scanned_as_deleted() { + use std::os::unix::fs::symlink; + let vault = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + let root = vault.path().to_str().unwrap(); + let note = vault.path().join("note.md"); + fs::write(¬e, b"accepted").unwrap(); + let baseline = scan_local(root).unwrap(); + assert_eq!(baseline["note.md"].hash, sha256_hex(b"accepted")); + + let external = outside.path().join("outside.md"); + fs::write(&external, b"external").unwrap(); + fs::remove_file(¬e).unwrap(); + symlink(&external, ¬e).unwrap(); + assert!(scan_local(root).err().unwrap().contains("symbolic link")); + assert_eq!(fs::read(&external).unwrap(), b"external"); + + fs::remove_file(¬e).unwrap(); + symlink(outside.path().join("missing.md"), ¬e).unwrap(); + assert!(scan_local(root).err().unwrap().contains("symbolic link")); + + fs::remove_file(¬e).unwrap(); + fs::create_dir_all(outside.path().join("Notebook")).unwrap(); + fs::write(outside.path().join("Notebook/note.md"), b"external").unwrap(); + symlink( + outside.path().join("Notebook"), + vault.path().join("Notebook"), + ) + .unwrap(); + assert!(scan_local(root).err().unwrap().contains("symbolic link")); + assert_eq!( + fs::read(outside.path().join("Notebook/note.md")).unwrap(), + b"external" + ); + } + #[test] fn syncs_notebook_icon_mapping_and_assets_only() { for path in [ @@ -1086,13 +1205,15 @@ mod tests { let modified = fs::metadata(&path).unwrap().modified().unwrap(); let vault_path = vault.path().to_str().unwrap(); let local = scan_local(vault_path).unwrap(); - let remote = HashMap::from([("note.md".to_string(), "etag".to_string())]); + let remote = HashMap::from([("note.md".to_string(), "\"etag\"".to_string())]); let manifest = SyncManifest { + identity: String::new(), files: HashMap::from([( "note.md".to_string(), ManifestEntry { local_hash: local["note.md"].hash.clone(), - remote_etag: "etag".to_string(), + remote_etag: "\"etag\"".to_string(), + remote_hash: String::new(), }, )]), }; @@ -1132,11 +1253,13 @@ mod tests { let vault_path = vault.path().to_str().unwrap(); let local = scan_local(vault_path).unwrap(); let manifest = SyncManifest { + identity: String::new(), files: HashMap::from([( "note.md".to_string(), ManifestEntry { local_hash: local["note.md"].hash.clone(), - remote_etag: "etag".to_string(), + remote_etag: "\"etag\"".to_string(), + remote_hash: String::new(), }, )]), }; @@ -1207,4 +1330,235 @@ mod tests { let event = changed_entry(path, "modify", vault.path()); assert_eq!(event.note.unwrap().preview, "remote content"); } + fn webdav_test_client( + responses: Vec<(&'static str, &'static str)>, + ) -> (WebdavClient, std::thread::JoinHandle>) { + use std::io::Write; + use std::net::TcpListener; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}/vault", listener.local_addr().unwrap()); + let worker = std::thread::spawn(move || { + let mut requests = Vec::new(); + for (status, body) in responses { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(std::time::Duration::from_secs(5))) + .unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 4096]; + let header_end = loop { + let len = stream.read(&mut chunk).unwrap(); + assert!(len > 0); + request.extend_from_slice(&chunk[..len]); + if let Some(offset) = request.windows(4).position(|part| part == b"\r\n\r\n") { + break offset + 4; + } + }; + let headers = String::from_utf8_lossy(&request[..header_end]).into_owned(); + let content_length: usize = headers + .lines() + .find_map(|line| { + line.to_ascii_lowercase() + .strip_prefix("content-length:") + .and_then(|value| value.trim().parse().ok()) + }) + .unwrap_or(0); + while request.len() < header_end + content_length { + let len = stream.read(&mut chunk).unwrap(); + assert!(len > 0); + request.extend_from_slice(&chunk[..len]); + } + requests.push(headers); + let response = format!( + "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + stream.write_all(response.as_bytes()).unwrap(); + } + requests + }); + ( + WebdavClient::new(WebdavConfig { + url, + username: "alice".into(), + password: "secret".into(), + }) + .unwrap(), + worker, + ) + } + + #[test] + fn corrupt_manifest_and_unreadable_vault_stop_without_treating_files_as_deleted() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path().to_str().unwrap(); + fs::create_dir_all(helixnotes_dir(root)).unwrap(); + fs::write(manifest_path(root), b"{invalid").unwrap(); + assert!(load_manifest(root) + .err() + .unwrap() + .contains("Invalid sync manifest")); + fs::write(manifest_path(root), b"{\"files\":{}}").unwrap(); + assert!(scan_local(&vault.path().join("missing").to_string_lossy()).is_err()); + fs::write(vault.path().join("note.md"), b"local").unwrap(); + let old = load_manifest(root).unwrap(); + let rebased = baseline_for_endpoint(old, "new account"); + assert!(rebased.files.is_empty()); + fs::remove_dir_all(helixnotes_dir(root)).unwrap(); + fs::write(helixnotes_dir(root), b"not a directory").unwrap(); + assert!(save_manifest(root, &rebased).is_err()); + assert_eq!(fs::read(vault.path().join("note.md")).unwrap(), b"local"); + } + + #[test] + fn endpoint_identity_rebases_without_credentials_or_deletion_history() { + let first = WebdavClient::new(WebdavConfig { + url: "HTTPS://Example.org:443/team/".into(), + username: "alice".into(), + password: "one".into(), + }) + .unwrap(); + let same = WebdavClient::new(WebdavConfig { + url: "https://example.org/team".into(), + username: "alice".into(), + password: "other".into(), + }) + .unwrap(); + let other = WebdavClient::new(WebdavConfig { + url: "https://example.org/team".into(), + username: "bob".into(), + password: "one".into(), + }) + .unwrap(); + let different_folder = WebdavClient::new(WebdavConfig { + url: "https://example.org/another".into(), + username: "alice".into(), + password: "one".into(), + }) + .unwrap(); + assert_eq!(first.identity(), same.identity()); + assert_ne!(same.identity(), other.identity()); + assert_ne!(same.identity(), different_folder.identity()); + let manifest = SyncManifest { + identity: first.identity(), + files: HashMap::from([( + "note.md".into(), + manifest_entry(sha256_hex(b"old"), "\"old\""), + )]), + }; + let vault = tempfile::tempdir().unwrap(); + let root = vault.path().to_str().unwrap(); + save_manifest(root, &manifest).unwrap(); + let persisted = fs::read_to_string(manifest_path(root)).unwrap(); + assert!(!persisted.contains("one") && !persisted.contains("alice")); + assert_eq!(load_manifest(root).unwrap().identity, same.identity()); + assert_eq!( + baseline_for_endpoint(manifest, &other.identity()) + .files + .len(), + 0 + ); + assert!( + baseline_for_endpoint(load_manifest(root).unwrap(), &different_folder.identity()) + .files + .is_empty() + ); + } + + #[test] + fn etagless_remote_content_change_refreshes_local_and_refuses_remote_deletion() { + let vault = tempfile::tempdir().unwrap(); + fs::write(vault.path().join("note.md"), b"old").unwrap(); + let root = vault.path().to_str().unwrap(); + let local = scan_local(root).unwrap(); + let manifest = SyncManifest { + identity: String::new(), + files: HashMap::from([("note.md".into(), manifest_entry(sha256_hex(b"old"), ""))]), + }; + let (client, requests) = webdav_test_client(vec![("200 OK", "new")]); + let mut changes = HashMap::new(); + let (next, summary) = apply_changes( + &client, + root, + &local, + &HashMap::from([("note.md".into(), String::new())]), + &manifest, + &mut changes, + &tokio::sync::Mutex::new(()), + ) + .unwrap(); + assert_eq!(summary.downloaded, 1); + assert_eq!(fs::read(vault.path().join("note.md")).unwrap(), b"new"); + assert_eq!(next.files["note.md"].remote_hash, sha256_hex(b"new")); + assert!(requests.join().unwrap()[0].starts_with("GET /vault/note.md ")); + let (client, requests) = webdav_test_client(vec![("200 OK", "new")]); + let error = apply_changes( + &client, + root, + &HashMap::new(), + &HashMap::from([("note.md".into(), String::new())]), + &next, + &mut HashMap::new(), + &tokio::sync::Mutex::new(()), + ) + .err() + .unwrap(); + assert!(error.contains("Cannot safely delete")); + assert_eq!(requests.join().unwrap().len(), 1); // GET only, never DELETE + } + + #[test] + fn changed_get_etag_never_installs_stale_snapshot() { + let (client, requests) = webdav_test_client(vec![("200 OK\r\nETag: \"new\"", "newer")]); + assert!(client + .get("note.md", "\"old\"") + .unwrap_err() + .contains("retry")); + let requests = requests.join().unwrap(); + assert_eq!(requests.len(), 1); + assert!(requests[0] + .to_ascii_lowercase() + .contains("if-match: \"old\"")); + } + + #[test] + fn conditional_writes_preserve_concurrent_remote_content() { + let (client, requests) = webdav_test_client(vec![("412 Precondition Failed", "")]); + assert!(client + .put("note.md", b"edited", Some("\"old\"")) + .unwrap_err() + .contains("retry")); + let requests = requests.join().unwrap(); + assert!(requests[0] + .to_ascii_lowercase() + .contains("if-match: \"old\"")); + + let (client, requests) = webdav_test_client(vec![("412 Precondition Failed", "")]); + assert!(client + .delete("note.md", "\"old\"") + .unwrap_err() + .contains("retry")); + assert!(requests.join().unwrap()[0] + .to_ascii_lowercase() + .contains("if-match: \"old\"")); + + let (client, requests) = webdav_test_client(vec![("412 Precondition Failed", "")]); + assert!(client + .put("new.md", b"new", None) + .unwrap_err() + .contains("retry")); + assert!(requests.join().unwrap()[0] + .to_ascii_lowercase() + .contains("if-none-match: *")); + let (client, requests) = webdav_test_client(vec![]); + assert!(client + .put("note.md", b"edited", Some("")) + .unwrap_err() + .contains("no strong ETag")); + assert!(client + .delete("note.md", "") + .unwrap_err() + .contains("no strong ETag")); + assert!(requests.join().unwrap().is_empty()); + } } diff --git a/src-tauri/src/types.rs b/src-tauri/src/types.rs index fde1d94..44b6384 100644 --- a/src-tauri/src/types.rs +++ b/src-tauri/src/types.rs @@ -104,6 +104,8 @@ pub struct VaultConfig { pub sync_interval_minutes: u32, #[serde(default)] pub last_sync_time: Option, + #[serde(default)] + pub last_backup_time: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -220,8 +222,6 @@ pub struct AppConfig { #[serde(default)] pub backup_location: Option, #[serde(default)] - pub last_backup_time: Option, - #[serde(default)] pub backup_include_attachments: bool, #[serde(default = "default_max_versions")] pub max_versions_per_note: u32, @@ -366,7 +366,6 @@ impl Default for AppConfig { backup_frequency: "24h".to_string(), backup_max_count: 10, backup_location: None, - last_backup_time: None, backup_include_attachments: false, max_versions_per_note: 20, ai_provider: None, diff --git a/src-tauri/src/vault/import.rs b/src-tauri/src/vault/import.rs index a9b41a8..37cd4e0 100644 --- a/src-tauri/src/vault/import.rs +++ b/src-tauri/src/vault/import.rs @@ -1,5 +1,7 @@ use std::collections::{HashMap, HashSet}; -use std::path::Path; +use std::fs::OpenOptions; +use std::io; +use std::path::{Path, PathBuf}; use chrono::Utc; use gray_matter::engine::YAML; @@ -9,23 +11,16 @@ use uuid::Uuid; use crate::types::{ImportResult, NoteMeta}; use crate::vault::frontmatter; +use crate::vault::operations::replace_file_atomically; pub fn import(vault_path: &str) -> Result { let vault = Path::new(vault_path); - let file_index = build_file_index(vault); + let file_index = build_file_index(vault)?; - let md_files: Vec<_> = walkdir::WalkDir::new(vault) + let md_files: Vec<_> = scanned_files(vault)? .into_iter() - .filter_map(|e| e.ok()) - .filter(|e| { - let p = e.path(); - p.is_file() - && p.extension().and_then(|x| x.to_str()) == Some("md") - && !p.to_string_lossy().contains("/.helixnotes/") - && !p.to_string_lossy().contains("/.trash/") - }) - .map(|e| e.path().to_path_buf()) + .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("md")) .collect(); let wiki_embed_re = @@ -46,10 +41,8 @@ pub fn import(vault_path: &str) -> Result { }; for path in &md_files { - let raw = match std::fs::read_to_string(path) { - Ok(c) => c, - Err(_) => continue, - }; + let raw = std::fs::read_to_string(path) + .map_err(|e| format!("Reading {}: {e}", path.display()))?; let note_dir = path.parent().unwrap_or(Path::new("")); let mut content = raw.clone(); @@ -193,7 +186,8 @@ pub fn import(vault_path: &str) -> Result { } if changed { - let _ = std::fs::write(path, &content); + replace_file_atomically(path, content.as_bytes()) + .map_err(|e| format!("Writing {}: {e}", path.display()))?; result.files_converted += 1; } } @@ -203,30 +197,65 @@ pub fn import(vault_path: &str) -> Result { if !moved.is_empty() { rewrite_attachment_refs(vault, &moved)?; + for old_rel in moved.keys() { + let src_path = vault.join(old_rel); + std::fs::remove_file(&src_path) + .map_err(|e| format!("Removing {} after copying: {e}", src_path.display()))?; + } } - cleanup_empty_dirs(vault); + cleanup_empty_dirs(vault)?; Ok(result) } -fn build_file_index(vault: &Path) -> HashMap { - let mut index = HashMap::new(); - for entry in walkdir::WalkDir::new(vault) +fn is_excluded_dir(path: &Path) -> bool { + matches!( + path.file_name().and_then(|name| name.to_str()), + Some(".helixnotes" | ".obsidian" | ".trash" | ".stfolder" | ".claude") + ) +} + +fn vault_entries( + vault: &Path, +) -> impl Iterator> + '_ { + walkdir::WalkDir::new(vault) .into_iter() - .filter_map(|e| e.ok()) - { - let path = entry.path(); - if !path.is_file() { + .filter_entry(|entry| { + entry.depth() == 0 || !entry.file_type().is_dir() || !is_excluded_dir(entry.path()) + }) +} + +fn scanned_files(vault: &Path) -> Result, String> { + vault_entries(vault) + .filter_map(|entry| match entry { + Ok(entry) if entry.file_type().is_file() => Some(Ok(entry.into_path())), + Ok(_) => None, + Err(e) => Some(Err(e)), + }) + .collect::, _>>() + .map_err(|e| format!("Scanning {}: {e}", vault.display())) +} + +fn vault_relative(path: &Path, vault: &Path) -> Result { + path.strip_prefix(vault) + .map(|rel| rel.to_string_lossy().replace('\\', "/")) + .map_err(|e| format!("Relativizing {}: {e}", path.display())) +} + +fn build_file_index(vault: &Path) -> Result, String> { + let mut index = HashMap::new(); + for entry in vault_entries(vault) { + let entry = entry.map_err(|e| format!("Scanning {}: {e}", vault.display()))?; + if !entry.file_type().is_file() { continue; } + let path = entry.path(); if let Some(name) = path.file_name().and_then(|n| n.to_str()) { - if let Ok(rel) = path.strip_prefix(vault) { - index.insert(name.to_string(), rel.to_string_lossy().to_string()); - } + index.insert(name.to_string(), vault_relative(path, vault)?); } } - index + Ok(index) } fn rename_deprecated_properties(raw: &str) -> String { @@ -565,52 +594,102 @@ fn fix_md_link_refs( .to_string() } +fn ensure_attachment_parent( + vault: &Path, + canonical_vault: &Path, + parent: &Path, +) -> Result<(), String> { + let relative = parent + .strip_prefix(vault) + .map_err(|e| format!("Invalid attachment destination {}: {e}", parent.display()))?; + let mut current = vault.to_path_buf(); + let mut relative_path = PathBuf::new(); + for component in relative.components() { + current.push(component); + relative_path.push(component); + match std::fs::create_dir(¤t) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(format!("Creating {}: {e}", current.display())), + } + let canonical = std::fs::canonicalize(¤t) + .map_err(|e| format!("Resolving {}: {e}", current.display()))?; + if !current.is_dir() || canonical != canonical_vault.join(&relative_path) { + return Err(format!( + "Attachment destination escapes vault: {}", + current.display() + )); + } + } + Ok(()) +} + fn move_attachments(vault: &Path) -> Result, String> { let attachments_dir = vault.join(".helixnotes").join("attachments"); - let _ = std::fs::create_dir_all(&attachments_dir); - - let attachment_files: Vec<_> = walkdir::WalkDir::new(vault) + let attachment_files: Vec<_> = scanned_files(vault)? .into_iter() - .filter_map(|e| e.ok()) - .filter(|e| { - let p = e.path(); - if !p.is_file() { - return false; - } - if p.extension().and_then(|x| x.to_str()) == Some("md") { - return false; - } - let path_str = p.to_string_lossy(); - !path_str.contains("/.helixnotes/") - && !path_str.contains("/.obsidian/") - && !path_str.contains("/.trash/") - && !path_str.contains("/.stfolder") - && !path_str.contains("/.claude/") - }) - .map(|e| e.path().to_path_buf()) + .filter(|p| p.extension().and_then(|x| x.to_str()) != Some("md")) .collect(); + let canonical_vault = + std::fs::canonicalize(vault).map_err(|e| format!("Resolving {}: {e}", vault.display()))?; - let mut moved: HashMap = HashMap::new(); + let mut moved = HashMap::new(); + for src_path in attachment_files { + let old_rel = vault_relative(&src_path, vault)?; + let preferred = attachments_dir.join(&old_rel); + let parent = preferred.parent().expect("attachment has a parent"); + ensure_attachment_parent(vault, &canonical_vault, parent)?; - for src_path in &attachment_files { - let old_rel = match src_path.strip_prefix(vault) { - Ok(r) => r.to_string_lossy().to_string(), - Err(_) => continue, + // Reserve the destination atomically: neither rename nor std::fs::copy protects + // a pre-existing attachment (or one created concurrently) from replacement. + let mut suffix = 0u64; + let (dest_path, mut dest) = loop { + let candidate = if suffix == 0 { + preferred.clone() + } else { + let stem = preferred.file_stem().unwrap_or_default().to_string_lossy(); + let ext = preferred + .extension() + .map(|ext| format!(".{}", ext.to_string_lossy())) + .unwrap_or_default(); + preferred.with_file_name(format!("{stem}-{suffix}{ext}")) + }; + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&candidate) + { + Ok(file) => break (candidate, file), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { + suffix = suffix + .checked_add(1) + .ok_or("Too many attachment collisions")?; + } + Err(e) => return Err(format!("Creating {}: {e}", candidate.display())), + } }; - let new_rel = format!(".helixnotes/attachments/{}", old_rel); - let dest_path = vault.join(&new_rel); - - if let Some(parent) = dest_path.parent() { - let _ = std::fs::create_dir_all(parent); - } - - if std::fs::rename(src_path, &dest_path).is_ok() - || std::fs::copy(src_path, &dest_path) - .and_then(|_| std::fs::remove_file(src_path)) - .is_ok() - { - moved.insert(old_rel, new_rel); + let copied = (|| -> io::Result<()> { + let mut src = std::fs::File::open(&src_path)?; + io::copy(&mut src, &mut dest)?; + dest.sync_all()?; + Ok(()) + })(); + drop(dest); + if let Err(e) = copied { + std::fs::remove_file(&dest_path).map_err(|cleanup| { + format!( + "Copying {} to {}: {e}; removing incomplete copy: {cleanup}", + src_path.display(), + dest_path.display() + ) + })?; + return Err(format!( + "Copying {} to {}: {e}", + src_path.display(), + dest_path.display() + )); } + moved.insert(old_rel, vault_relative(&dest_path, vault)?); } Ok(moved) } @@ -618,24 +697,14 @@ fn move_attachments(vault: &Path) -> Result, String> { fn rewrite_attachment_refs(vault: &Path, moved: &HashMap) -> Result<(), String> { let md_ref = Regex::new(r"(!?\[[^\]]*\])\(([^)]+)\)").map_err(|e| e.to_string())?; - let md_files: Vec<_> = walkdir::WalkDir::new(vault) + let md_files: Vec<_> = scanned_files(vault)? .into_iter() - .filter_map(|e| e.ok()) - .filter(|e| { - let p = e.path(); - p.is_file() - && p.extension().and_then(|x| x.to_str()) == Some("md") - && !p.to_string_lossy().contains("/.helixnotes/") - && !p.to_string_lossy().contains("/.trash/") - }) - .map(|e| e.path().to_path_buf()) + .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("md")) .collect(); for path in &md_files { - let content = match std::fs::read_to_string(path) { - Ok(c) => c, - Err(_) => continue, - }; + let content = std::fs::read_to_string(path) + .map_err(|e| format!("Reading {}: {e}", path.display()))?; let note_dir = path.parent().unwrap_or(Path::new("")); let new_content = md_ref @@ -643,28 +712,29 @@ fn rewrite_attachment_refs(vault: &Path, moved: &HashMap) -> Res let prefix = &caps[1]; let href = &caps[2]; let decoded_href = percent_decode(href); + let (reference, suffix) = decoded_href + .find(['#', '?']) + .map(|index| decoded_href.split_at(index)) + .unwrap_or((&decoded_href, "")); - if decoded_href.starts_with("http") || decoded_href.starts_with("data:") { + if reference.starts_with("http") + || reference.starts_with("data:") + || reference.starts_with('/') + { return format!("{}({})", prefix, href); } - let abs_from_note = note_dir.join(&decoded_href); - let rel_from_note = abs_from_note + let rel_from_note = note_dir .strip_prefix(vault) .ok() - .map(|r| r.to_string_lossy().to_string()); - let rel_from_vault = decoded_href.clone(); - + .and_then(|base| resolve_relative_ref(base, reference)); let old_vault_rel = rel_from_note .as_ref() .filter(|r| moved.contains_key(r.as_str())) .cloned() .or_else(|| { - if moved.contains_key(&rel_from_vault) { - Some(rel_from_vault) - } else { - None - } + resolve_relative_ref(Path::new(""), reference) + .filter(|r| moved.contains_key(r.as_str())) }); if let Some(old_rel) = old_vault_rel { @@ -675,7 +745,12 @@ fn rewrite_attachment_refs(vault: &Path, moved: &HashMap) -> Res note_dir.to_str().unwrap_or(""), ) .unwrap_or(new_rel.clone()); - return format!("{}({})", prefix, new_note_rel.replace(' ', "%20")); + return format!( + "{}({}{})", + prefix, + new_note_rel.replace('\\', "/").replace(' ', "%20"), + suffix + ); } } format!("{}({})", prefix, href) @@ -683,33 +758,59 @@ fn rewrite_attachment_refs(vault: &Path, moved: &HashMap) -> Res .to_string(); if new_content != content { - let _ = std::fs::write(path, new_content); + replace_file_atomically(path, new_content.as_bytes()) + .map_err(|e| format!("Writing {}: {e}", path.display()))?; } } Ok(()) } -fn cleanup_empty_dirs(root: &Path) { - let mut dirs: Vec<_> = walkdir::WalkDir::new(root) - .into_iter() - .filter_map(|e| e.ok()) - .filter(|e| e.path().is_dir()) - .map(|e| e.path().to_path_buf()) - .collect(); +fn resolve_relative_ref(base: &Path, reference: &str) -> Option { + let mut rel = base.to_path_buf(); + for component in Path::new(&reference.replace('\\', "/")).components() { + match component { + std::path::Component::Normal(name) => rel.push(name), + std::path::Component::ParentDir => { + if !rel.pop() { + return None; + } + } + std::path::Component::CurDir => {} + _ => return None, + } + } + Some(rel.to_string_lossy().replace('\\', "/")) +} + +fn cleanup_empty_dirs(root: &Path) -> Result<(), String> { + let mut dirs: Vec<_> = vault_entries(root) + .filter_map(|entry| match entry { + Ok(entry) if entry.file_type().is_dir() => Some(Ok(entry.into_path())), + Ok(_) => None, + Err(e) => Some(Err(e)), + }) + .collect::, _>>() + .map_err(|e| format!("Scanning {}: {e}", root.display()))?; dirs.sort_by_key(|path| std::cmp::Reverse(path.components().count())); for dir in dirs { - let dir_str = dir.to_string_lossy(); - if dir_str.contains("/.helixnotes") || dir_str.contains("/.obsidian") || dir == root { + if dir == root { continue; } - if let Ok(mut entries) = std::fs::read_dir(&dir) { - if entries.next().is_none() { - let _ = std::fs::remove_dir(&dir); - } + let mut entries = + std::fs::read_dir(&dir).map_err(|e| format!("Reading {}: {e}", dir.display()))?; + if entries + .next() + .transpose() + .map_err(|e| format!("Reading {}: {e}", dir.display()))? + .is_none() + { + std::fs::remove_dir(&dir) + .map_err(|e| format!("Removing empty directory {}: {e}", dir.display()))?; } } + Ok(()) } fn split_anchor(reference: &str) -> (&str, Option<&str>) { @@ -778,7 +879,7 @@ fn pathdiff(target: &str, base: &str) -> Result { for component in &target_components[common..] { result.push(component); } - Ok(result.to_string_lossy().to_string()) + Ok(result.to_string_lossy().replace('\\', "/")) } fn percent_decode(s: &str) -> String { @@ -1013,6 +1114,131 @@ mod tests { assert_eq!(result, raw); } + #[test] + fn import_keeps_colliding_attachments_and_rewrites_note_relative_links() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path(); + let note_dir = root.join("Notes"); + let stored = root.join(".helixnotes/attachments/Notes"); + std::fs::create_dir_all(¬e_dir).unwrap(); + std::fs::create_dir_all(&stored).unwrap(); + std::fs::write(note_dir.join("pic.png"), b"NEW").unwrap(); + std::fs::write(stored.join("pic.png"), b"OLD").unwrap(); + std::fs::write(stored.join("pic-1.png"), b"OLDER").unwrap(); + std::fs::write( + note_dir.join("Entry.md"), + "# Entry\n\n![picture](pic.png) [picture](./pic.png#preview)", + ) + .unwrap(); + + let result = import(root.to_str().unwrap()).unwrap(); + + assert_eq!(result.attachments_moved, 1); + assert_eq!(std::fs::read(stored.join("pic.png")).unwrap(), b"OLD"); + assert_eq!(std::fs::read(stored.join("pic-1.png")).unwrap(), b"OLDER"); + assert_eq!(std::fs::read(stored.join("pic-2.png")).unwrap(), b"NEW"); + assert!(!note_dir.join("pic.png").exists()); + let note = std::fs::read_to_string(note_dir.join("Entry.md")).unwrap(); + assert!(note.contains("![picture](../.helixnotes/attachments/Notes/pic-2.png)")); + assert!(note.contains("[picture](../.helixnotes/attachments/Notes/pic-2.png#preview)")); + } + + #[test] + fn import_prunes_metadata_directories_at_every_depth() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path(); + for hidden in [".helixnotes", ".obsidian", ".trash", ".stfolder", ".claude"] { + for base in [root.to_path_buf(), root.join("Notebook")] { + let hidden_dir = base.join(hidden).join("history"); + std::fs::create_dir_all(&hidden_dir).unwrap(); + std::fs::write(hidden_dir.join("Secret.md"), "==untouched==").unwrap(); + std::fs::write(hidden_dir.join("asset.bin"), b"untouched").unwrap(); + } + } + let visible_dir = root.join("Notebook/stfolder-visible"); + std::fs::create_dir_all(&visible_dir).unwrap(); + std::fs::write(visible_dir.join("asset.bin"), b"visible").unwrap(); + std::fs::write( + root.join("Note.md"), + "# Note\n\n![file](Notebook/stfolder-visible/asset.bin)", + ) + .unwrap(); + + let result = import(root.to_str().unwrap()).unwrap(); + + assert_eq!(result.attachments_moved, 1); + assert_eq!( + std::fs::read(root.join(".helixnotes/attachments/Notebook/stfolder-visible/asset.bin")) + .unwrap(), + b"visible" + ); + for hidden in [".helixnotes", ".obsidian", ".trash", ".stfolder", ".claude"] { + for base in [root.to_path_buf(), root.join("Notebook")] { + let hidden_dir = base.join(hidden).join("history"); + assert_eq!( + std::fs::read_to_string(hidden_dir.join("Secret.md")).unwrap(), + "==untouched==" + ); + assert_eq!( + std::fs::read(hidden_dir.join("asset.bin")).unwrap(), + b"untouched" + ); + } + } + } + + #[test] + fn destination_io_failure_leaves_original_attachment_in_place() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path(); + std::fs::create_dir(root.join(".helixnotes")).unwrap(); + std::fs::write(root.join(".helixnotes/attachments"), b"existing metadata").unwrap(); + std::fs::write(root.join("asset.bin"), b"original").unwrap(); + + assert!(import(root.to_str().unwrap()).is_err()); + assert_eq!(std::fs::read(root.join("asset.bin")).unwrap(), b"original"); + assert_eq!( + std::fs::read(root.join(".helixnotes/attachments")).unwrap(), + b"existing metadata" + ); + } + + #[test] + fn readonly_note_does_not_lose_original_or_attachment() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path(); + let note = root.join("Note.md"); + let original = "# Note\n\n![asset](asset.bin)"; + std::fs::write(¬e, original).unwrap(); + std::fs::write(root.join("asset.bin"), b"original").unwrap(); + let original_permissions = std::fs::metadata(¬e).unwrap().permissions(); + let mut permissions = original_permissions.clone(); + permissions.set_readonly(true); + std::fs::set_permissions(¬e, permissions).unwrap(); + + let result = import(root.to_str().unwrap()); + + assert!(result.is_err()); + assert_eq!(std::fs::read_to_string(¬e).unwrap(), original); + assert_eq!(std::fs::read(root.join("asset.bin")).unwrap(), b"original"); + std::fs::set_permissions(¬e, original_permissions).unwrap(); + } + + #[cfg(unix)] + #[test] + fn attachment_directory_symlink_cannot_escape_vault() { + let vault = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + let root = vault.path(); + std::fs::create_dir(root.join(".helixnotes")).unwrap(); + std::os::unix::fs::symlink(outside.path(), root.join(".helixnotes/attachments")).unwrap(); + std::fs::write(root.join("asset.bin"), b"original").unwrap(); + + assert!(import(root.to_str().unwrap()).is_err()); + assert_eq!(std::fs::read(root.join("asset.bin")).unwrap(), b"original"); + assert!(!outside.path().join("asset.bin").exists()); + } + #[test] fn test_split_anchor_same_note() { let (file, anchor) = split_anchor("#Heading"); diff --git a/src-tauri/src/vault/operations.rs b/src-tauri/src/vault/operations.rs index 185cd75..5f04084 100644 --- a/src-tauri/src/vault/operations.rs +++ b/src-tauri/src/vault/operations.rs @@ -118,6 +118,168 @@ fn safe_child_name(name: &str) -> Result<&str, String> { Ok(name) } +// A normal rename can replace an existing file (or an empty directory). +// Use the OS's exclusive rename primitive instead; checking exists first is racy. +#[cfg(target_os = "linux")] +fn rename_exclusive(src: &Path, dest: &Path) -> std::io::Result<()> { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + unsafe extern "C" { + fn renameat2( + olddirfd: i32, + oldpath: *const std::ffi::c_char, + newdirfd: i32, + newpath: *const std::ffi::c_char, + flags: u32, + ) -> i32; + } + let old = CString::new(src.as_os_str().as_bytes()) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidInput, error))?; + let new = CString::new(dest.as_os_str().as_bytes()) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidInput, error))?; + // AT_FDCWD and RENAME_NOREPLACE + if unsafe { renameat2(-100, old.as_ptr(), -100, new.as_ptr(), 1) } == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } +} + +#[cfg(target_os = "android")] +fn rename_exclusive(src: &Path, dest: &Path) -> std::io::Result<()> { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + let old = CString::new(src.as_os_str().as_bytes()) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidInput, error))?; + let new = CString::new(dest.as_os_str().as_bytes()) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidInput, error))?; + // Bionic exports renameat2 only on newer Android releases (minSdk is 24). + // The kernel syscall is available independently; ENOSYS safely rejects + // the move on old kernels rather than falling back to a clobbering rename. + if unsafe { + libc::syscall( + libc::SYS_renameat2, + libc::AT_FDCWD, + old.as_ptr(), + libc::AT_FDCWD, + new.as_ptr(), + libc::RENAME_NOREPLACE, + ) + } == 0 + { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } +} + +#[cfg(any(target_os = "macos", target_os = "ios"))] +fn rename_exclusive(src: &Path, dest: &Path) -> std::io::Result<()> { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + unsafe extern "C" { + fn renameatx_np( + olddirfd: i32, + oldpath: *const std::ffi::c_char, + newdirfd: i32, + newpath: *const std::ffi::c_char, + flags: u32, + ) -> i32; + } + let old = CString::new(src.as_os_str().as_bytes()) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidInput, error))?; + let new = CString::new(dest.as_os_str().as_bytes()) + .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidInput, error))?; + // AT_FDCWD and RENAME_EXCL + if unsafe { renameatx_np(-2, old.as_ptr(), -2, new.as_ptr(), 4) } == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } +} + +#[cfg(windows)] +fn rename_exclusive(src: &Path, dest: &Path) -> std::io::Result<()> { + use std::os::windows::ffi::OsStrExt; + #[link(name = "Kernel32")] + unsafe extern "system" { + fn MoveFileW(old: *const u16, new: *const u16) -> i32; + } + let old: Vec = src.as_os_str().encode_wide().chain(Some(0)).collect(); + let new: Vec = dest.as_os_str().encode_wide().chain(Some(0)).collect(); + if unsafe { MoveFileW(old.as_ptr(), new.as_ptr()) } != 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } +} + +fn move_without_replacing(src: &Path, dest: &Path) -> Result<(), String> { + if src == dest { + return Ok(()); + } + // Case-insensitive volumes resolve two differently-spelled paths to the + // same object. Move via a unique sibling to permit a case-only rename. + let same_object = fs::canonicalize(dest) + .and_then(|target| fs::canonicalize(src).map(|source| source == target)) + .unwrap_or(false); + if same_object { + let parent = src.parent().ok_or("Item has no parent directory")?; + let staging = loop { + let candidate = parent.join(format!(".helixnotes-rename-{}", Uuid::new_v4())); + match rename_exclusive(src, &candidate) { + Ok(()) => break candidate, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error.to_string()), + } + }; + if let Err(error) = rename_exclusive(&staging, dest) { + return Err(match rename_exclusive(&staging, src) { + Ok(()) => error.to_string(), + Err(rollback) => { + format!("{error}; item remains at {}: {rollback}", staging.display()) + } + }); + } + return Ok(()); + } + rename_exclusive(src, dest).map_err(|error| error.to_string()) +} + +fn trash_name(original: &str) -> String { + format!( + "{}_{}_{}", + Utc::now().format("%Y%m%d%H%M%S%3f"), + Uuid::new_v4(), + original + ) +} + +fn original_trash_name(name: &str) -> &str { + let (prefix, rest) = if name.len() > 18 + && name.as_bytes()[..17].iter().all(u8::is_ascii_digit) + && name.as_bytes()[17] == b'_' + { + (18, &name[18..]) + } else if name.len() > 15 + && name.as_bytes()[..14].iter().all(u8::is_ascii_digit) + && name.as_bytes()[14] == b'_' + { + (15, &name[15..]) + } else { + return name; + }; + if prefix == 18 + && rest.len() > 37 + && rest.as_bytes()[36] == b'_' + && Uuid::parse_str(&rest[..36]).is_ok() + { + &rest[37..] + } else { + rest + } +} + pub fn ensure_vault_structure(vault_path: &str) -> Result<(), String> { let hn_dir = helixnotes_dir(vault_path); fs::create_dir_all(hn_dir.join("trash")).map_err(|e| e.to_string())?; @@ -601,11 +763,17 @@ pub fn save_note( path: &str, meta: &NoteMeta, body: &str, + expected_raw: &str, ) -> Result, String> { let validated = ensure_note_path(vault_path, Path::new(path))?; // Replace the actual file, not a symlink pointing to it. let target = canonicalize_path(&validated, "note path")?; let existing = read_note_content(&target, path)?; + if existing.raw != expected_raw { + return Err( + "Save conflict: note changed on disk. Your edits have not been written.".to_string(), + ); + } let mut updated_meta = meta.clone(); // A stale editor may still have an empty ID after the first save. @@ -867,13 +1035,23 @@ pub fn create_daily_note( }; let dir = Path::new(vault_path).join("Daily"); - fs::create_dir_all(&dir).map_err(|e| e.to_string())?; - + if fs::symlink_metadata(&dir).is_err() { + fs::create_dir(&dir).map_err(|e| e.to_string())?; + } + let dir = ensure_vault_content_dir(vault_path, &dir)?; let file_path = dir.join(format!("{}.md", date_str)); let vault_root = Path::new(vault_path); - // If today's note already exists, return it - if file_path.exists() { + // Return a genuine existing daily note, but never follow an outside link. + if fs::symlink_metadata(&file_path).is_ok() { + if fs::symlink_metadata(&file_path) + .map_err(|e| e.to_string())? + .file_type() + .is_symlink() + { + return Err("Daily note destination is a symlink".to_string()); + } + ensure_note_path(vault_path, &file_path)?; return read_note_entry(&file_path, vault_root); } @@ -888,7 +1066,25 @@ pub fn create_daily_note( }; let raw = frontmatter::update_note_raw(&meta, "\n"); - fs::write(&file_path, raw).map_err(|e| e.to_string())?; + match fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&file_path) + { + Ok(mut file) => file.write_all(raw.as_bytes()).map_err(|e| e.to_string())?, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + if fs::symlink_metadata(&file_path) + .map_err(|e| e.to_string())? + .file_type() + .is_symlink() + { + return Err("Daily note destination is a symlink".to_string()); + } + ensure_note_path(vault_path, &file_path)?; + return read_note_entry(&file_path, vault_root); + } + Err(error) => return Err(error.to_string()), + } let relative = file_path .strip_prefix(vault_root) @@ -950,11 +1146,14 @@ pub fn delete_note(vault_path: &str, note_path: &str) -> Result<(), String> { .to_string_lossy() .to_string(); - let timestamp = Utc::now().format("%Y%m%d%H%M%S%3f"); - let trash_name = format!("{}_{}", timestamp, filename); - let dest = trash_dir.join(&trash_name); - - fs::rename(src, dest).map_err(|e| e.to_string())?; + loop { + let candidate = trash_dir.join(trash_name(&filename)); + match rename_exclusive(src, &candidate) { + Ok(()) => break, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error.to_string()), + } + } Ok(()) } @@ -971,24 +1170,52 @@ pub fn delete_notebook(vault_path: &str, notebook_path: &str) -> Result<(), Stri .to_string_lossy() .to_string(); - let timestamp = Utc::now().format("%Y%m%d%H%M%S%3f"); - let trash_name = format!("{}_{}", timestamp, dirname); - let dest = trash_dir.join(&trash_name); - - // Save original relative path in a sidecar .meta file for restore let relative = src .strip_prefix(vault_path) .unwrap_or(src) .to_string_lossy() .to_string(); - let meta_path = trash_dir.join(format!("{}.meta", trash_name)); - let _ = fs::write(&meta_path, &relative); - - fs::rename(src, dest).map_err(|e| e.to_string())?; - Ok(()) + loop { + let trash_name = trash_name(&dirname); + let dest = trash_dir.join(&trash_name); + let meta_path = trash_dir.join(format!("{trash_name}.meta")); + let mut sidecar = match fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&meta_path) + { + Ok(file) => file, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error.to_string()), + }; + if let Err(error) = sidecar.write_all(relative.as_bytes()) { + drop(sidecar); + let _ = fs::remove_file(&meta_path); + return Err(error.to_string()); + } + drop(sidecar); + match rename_exclusive(src, &dest) { + Ok(()) => return Ok(()), + Err(error) => { + let _ = fs::remove_file(&meta_path); + if error.kind() == std::io::ErrorKind::AlreadyExists { + continue; + } + return Err(error.to_string()); + } + } + } } -pub fn rename_note(path: &str, new_title: &str, vault_path: &str) -> Result { +pub struct RenamedNote { + pub path: String, + pub old_raw: String, + pub new_raw: String, + pub old_title: String, + pub new_title: String, +} + +pub fn rename_note(path: &str, new_title: &str, vault_path: &str) -> Result { let validated = ensure_note_path(vault_path, Path::new(path))?; let src = validated.as_path(); @@ -1014,10 +1241,29 @@ pub fn rename_note(path: &str, new_title: &str, vault_path: &str) -> Result { + if let Some(previous) = previous_quick_access { + match save_quick_access(vault_path, &previous) { + Ok(()) => error, + Err(rollback) => { + format!("{error}; Quick Access rollback failed: {rollback}") + } + } + } else { + error + } + } + Err(rollback) => format!( + "{error}; note remains at {}: {rollback}", + new_path.display() + ), + }); + } + return Err(error); } let new_path_str = new_path.to_string_lossy().to_string(); @@ -1031,7 +1277,13 @@ pub fn rename_note(path: &str, new_title: &str, vault_path: &str) -> Result Result Resu let filename = src.file_name().unwrap_or_default(); let dest = dest_dir.join(filename); - fs::rename(src, &dest).map_err(|e| e.to_string())?; + move_note_with_quick_access(vault_path, src, &dest)?; Ok(dest.to_string_lossy().to_string()) } @@ -1210,9 +1462,7 @@ pub fn move_notebook( return Err("Cannot move a notebook into itself or its descendants".to_string()); } - if dest.exists() { - return Err("A notebook with that name already exists in the destination".to_string()); - } + // Destination reservation is performed atomically by move_notebook_with_icons. move_notebook_with_icons(vault_path, src, &dest)?; Ok(dest.to_string_lossy().to_string()) @@ -1263,14 +1513,7 @@ pub fn get_trash_contents(vault_path: &str) -> Result { }) .count(); let dirname = path.file_name().unwrap_or_default().to_string_lossy(); - // Strip timestamp prefix to get original notebook name - let name = if dirname.len() > 18 && dirname.chars().nth(17) == Some('_') { - dirname[18..].to_string() - } else if dirname.len() > 15 && dirname.chars().nth(14) == Some('_') { - dirname[15..].to_string() - } else { - dirname.to_string() - }; + let name = original_trash_name(&dirname).to_string(); let modified = fs::metadata(&path) .and_then(|m| m.modified()) .map(DateTime::::from) @@ -1306,19 +1549,13 @@ pub fn restore_note( }; let dest_dir = ensure_vault_content_dir(vault_path, &requested_dest)?; - // Strip timestamp prefix from trash filename (17-char with millis or 14-char legacy) + // Support both legacy timestamps and timestamp/UUID destinations. let filename = src.file_name().unwrap_or_default().to_string_lossy(); - let original_name = if filename.len() > 18 && filename.chars().nth(17) == Some('_') { - &filename[18..] - } else if filename.len() > 15 && filename.chars().nth(14) == Some('_') { - &filename[15..] - } else { - &filename - }; + let original_name = original_trash_name(&filename); let parent = src.parent().map(|p| p.to_path_buf()); let dest = dest_dir.join(original_name); - fs::rename(src, &dest).map_err(|e| e.to_string())?; + move_without_replacing(src, &dest)?; // Clean up empty parent directory (deleted notebook folder) in trash cleanup_empty_trash_dir(vault_path, parent.as_deref()); @@ -1335,33 +1572,43 @@ pub fn restore_notebook(vault_path: &str, trash_path: &str) -> Result 18 && dirname.chars().nth(17) == Some('_') { - &dirname[18..] - } else if dirname.len() > 15 && dirname.chars().nth(14) == Some('_') { - &dirname[15..] - } else { - &dirname - }; - name.to_string() + // The sidecar is paired with the exact trash entry name, including its UUID. + let meta_path = src.with_file_name(format!("{}.meta", dirname)); + let relative = match fs::read_to_string(&meta_path) { + Ok(original) => original, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + // Legacy notebooks without sidecars were restored to the vault root. + original_trash_name(&dirname).to_string() + } + Err(error) => return Err(error.to_string()), }; - let dest = Path::new(vault_path).join(safe_relative_path(&relative)?); - - // Recreate parent directories if needed - if let Some(parent) = dest.parent() { - fs::create_dir_all(parent).map_err(|e| e.to_string())?; + let relative = safe_relative_path(&relative)?; + let dest = Path::new(vault_path).join(relative); + // Validate every existing ancestor before creating children: a symlink + // inside the vault may otherwise redirect this restore outside the vault. + let vault = canonicalize_path(Path::new(vault_path), "vault path")?; + let mut ancestor = PathBuf::from(vault_path); + for component in relative + .components() + .take(relative.components().count() - 1) + { + ancestor.push(component); + if fs::symlink_metadata(&ancestor).is_ok() { + let canonical = canonicalize_path(&ancestor, "notebook destination")?; + if !canonical.starts_with(&vault) || canonical.starts_with(vault.join(".helixnotes")) { + return Err("Path must stay inside the active vault".to_string()); + } + if !canonical.is_dir() { + return Err("Notebook destination parent is not a directory".to_string()); + } + } else { + fs::create_dir(&ancestor).map_err(|e| e.to_string())?; + } } - - fs::rename(src, &dest).map_err(|e| e.to_string())?; + let parent = dest.parent().ok_or("Notebook has no parent directory")?; + ensure_vault_content_dir(vault_path, parent)?; + move_without_replacing(src, &dest)?; // Clean up .meta file let _ = fs::remove_file(&meta_path); Ok(dest.to_string_lossy().to_string()) @@ -1373,6 +1620,10 @@ pub fn permanent_delete(vault_path: &str, path: &str) -> Result<(), String> { let parent = p.parent().map(|pp| pp.to_path_buf()); if p.is_dir() { fs::remove_dir_all(p).map_err(|e| e.to_string())?; + if let Some(name) = p.file_name() { + let sidecar = p.with_file_name(format!("{}.meta", name.to_string_lossy())); + let _ = fs::remove_file(sidecar); + } } else { fs::remove_file(p).map_err(|e| e.to_string())?; } @@ -1405,8 +1656,7 @@ pub fn load_vault_state(vault_path: &str) -> Result { pub fn save_vault_state(vault_path: &str, state: &VaultState) -> Result<(), String> { let state_path = helixnotes_dir(vault_path).join("state.json"); let data = serde_json::to_string_pretty(state).map_err(|e| e.to_string())?; - fs::write(&state_path, data).map_err(|e| e.to_string())?; - Ok(()) + replace_file_atomically(&state_path, data.as_bytes()) } pub fn get_all_tags(vault_path: &str) -> Result, String> { @@ -1548,29 +1798,45 @@ fn move_notebook_with_icons(vault_path: &str, src: &Path, dest: &Path) -> Result .map_err(|error| error.to_string())? .to_string_lossy(), ); + let quick_access = quick_access_migration(vault_path, src, dest, true)?; let prefix = format!("{old_key}/"); - let mut changed = false; - let migrated = icons - .into_iter() - .map(|(key, value)| { - let key = if key == old_key { - changed = true; - new_key.clone() - } else if let Some(suffix) = key.strip_prefix(&prefix) { - changed = true; - format!("{new_key}/{suffix}") - } else { - key - }; - (key, value) - }) - .collect(); - fs::rename(src, dest).map_err(|error| error.to_string())?; - if changed { - if let Err(error) = save_notebook_icons(vault_path, &migrated) { - return Err(match fs::rename(dest, src) { + let mut migrated = None; + for (key, value) in &icons { + let new_icon_key = if key == &old_key { + new_key.clone() + } else if let Some(suffix) = key.strip_prefix(&prefix) { + format!("{new_key}/{suffix}") + } else { + continue; + }; + let mapping = migrated.get_or_insert_with(|| icons.clone()); + mapping.remove(key); + mapping.insert(new_icon_key, value.clone()); + } + move_without_replacing(src, dest)?; + if let Some(migrated) = &migrated { + if let Err(error) = save_notebook_icons(vault_path, migrated) { + return Err(match move_without_replacing(dest, src) { Ok(()) => error, - Err(rollback) => format!("{error}; notebook move rollback failed: {rollback}"), + Err(rollback) => format!( + "{error}; notebook remains at {}: {rollback}", + dest.display() + ), + }); + } + } + if let Some((_, updated)) = quick_access { + if let Err(error) = save_quick_access(vault_path, &updated) { + return Err(match move_without_replacing(dest, src) { + Ok(()) if migrated.is_some() => match save_notebook_icons(vault_path, &icons) { + Ok(()) => error, + Err(rollback) => format!("{error}; notebook icon rollback failed: {rollback}"), + }, + Ok(()) => error, + Err(rollback) => format!( + "{error}; notebook remains at {}: {rollback}", + dest.display() + ), }); } } @@ -1739,6 +2005,76 @@ pub(crate) fn attachment_metadata_references( } } +type QuickAccessChange = (Vec, Vec); + +fn quick_access_migration( + vault_path: &str, + src: &Path, + dest: &Path, + notebook: bool, +) -> Result, String> { + if src == dest { + return Ok(None); + } + let previous = load_quick_access(vault_path)?; + if previous.is_empty() { + return Ok(None); + } + let old = normalize_notebook_icon_key( + &src.strip_prefix(vault_path) + .map_err(|error| error.to_string())? + .to_string_lossy(), + ); + let new = normalize_notebook_icon_key( + &dest + .strip_prefix(vault_path) + .map_err(|error| error.to_string())? + .to_string_lossy(), + ); + let mut updated: Option> = None; + for (index, entry) in previous.iter().enumerate() { + let normalized: std::borrow::Cow<'_, str> = if entry.contains('\\') { + std::borrow::Cow::Owned(entry.replace('\\', "/")) + } else { + std::borrow::Cow::Borrowed(entry.as_str()) + }; + let mapped = if notebook { + normalized + .strip_prefix(&old) + .and_then(|suffix| suffix.strip_prefix('/')) + .map(|suffix| format!("{new}/{suffix}")) + } else if normalized.as_ref() == old { + Some(new.clone()) + } else { + None + }; + if let Some(mapped) = mapped { + updated.get_or_insert_with(|| previous.clone())[index] = mapped; + } + } + Ok(updated.map(|updated| (previous, updated))) +} + +fn move_note_with_quick_access( + vault_path: &str, + src: &Path, + dest: &Path, +) -> Result>, String> { + let migration = quick_access_migration(vault_path, src, dest, false)?; + move_without_replacing(src, dest)?; + if let Some((previous, updated)) = migration { + if let Err(error) = save_quick_access(vault_path, &updated) { + return Err(match move_without_replacing(dest, src) { + Ok(()) => error, + Err(rollback) => format!("{error}; note remains at {}: {rollback}", dest.display()), + }); + } + Ok(Some(previous)) + } else { + Ok(None) + } +} + pub fn load_quick_access(vault_path: &str) -> Result, String> { let qa_path = helixnotes_dir(vault_path).join("quick_access.json"); if qa_path.exists() { @@ -1752,8 +2088,7 @@ pub fn load_quick_access(vault_path: &str) -> Result, String> { pub fn save_quick_access(vault_path: &str, paths: &[String]) -> Result<(), String> { let qa_path = helixnotes_dir(vault_path).join("quick_access.json"); let data = serde_json::to_string_pretty(paths).map_err(|e| e.to_string())?; - fs::write(&qa_path, data).map_err(|e| e.to_string())?; - Ok(()) + replace_file_atomically(&qa_path, data.as_bytes()) } pub fn add_quick_access(vault_path: &str, note_relative: &str) -> Result<(), String> { @@ -2387,6 +2722,7 @@ mod tests { path.to_str().unwrap(), ¬e.meta, "New body.", + ¬e.raw, ) .unwrap(); let mobile = super::read_note_entry_metadata_only(&path, vault.path()).unwrap(); @@ -2410,9 +2746,11 @@ mod tests { meta.modified = chrono::Utc::now(); let serialized_body = format!("{}\n", note.content); - assert!(save_note(&vault_path, ¬e_path, &meta, &serialized_body) - .unwrap() - .is_none()); + assert!( + save_note(&vault_path, ¬e_path, &meta, &serialized_body, original) + .unwrap() + .is_none() + ); assert_eq!(fs::read_to_string(&path).unwrap(), original); assert_eq!(fs::metadata(&path).unwrap().modified().unwrap(), before); } @@ -2428,9 +2766,11 @@ mod tests { let note = read_note(&vault_path, ¬e_path).unwrap(); let body = format!("{} \n", note.content); - assert!(save_note(&vault_path, ¬e_path, ¬e.meta, &body) - .unwrap() - .is_some()); + assert!( + save_note(&vault_path, ¬e_path, ¬e.meta, &body, ¬e.raw) + .unwrap() + .is_some() + ); assert!(fs::read_to_string(&path) .unwrap() .ends_with("Final line. \n")); @@ -2447,15 +2787,27 @@ mod tests { let meta = read_note(&vault_path, ¬e_path).unwrap().meta; assert!(meta.id.is_empty()); - let first = save_note(&vault_path, ¬e_path, &meta, "# Note\n\nFirst change.\n") - .unwrap() - .unwrap(); + let first = save_note( + &vault_path, + ¬e_path, + &meta, + "# Note\n\nFirst change.\n", + original, + ) + .unwrap() + .unwrap(); Uuid::parse_str(&first.id).unwrap(); assert_eq!(first.previous_raw, original); let first_raw = fs::read_to_string(&path).unwrap(); - let second = save_note(&vault_path, ¬e_path, &meta, "# Note\n\nSecond change.\n") - .unwrap() - .unwrap(); + let second = save_note( + &vault_path, + ¬e_path, + &meta, + "# Note\n\nSecond change.\n", + &first_raw, + ) + .unwrap() + .unwrap(); assert_eq!(second.id, first.id); assert_eq!(second.previous_raw, first_raw); @@ -2522,4 +2874,397 @@ mod tests { assert!(replace_file_atomically(&path, b"must not save").is_err()); assert_eq!(fs::read_to_string(&path).unwrap(), "saved"); } + #[test] + fn stale_save_does_not_overwrite_external_edits_even_when_requested_body_is_unchanged() { + let vault = tempfile::tempdir().unwrap(); + let path = vault.path().join("Note.md"); + fs::write(&path, "---\nid: original\ntitle: Note\n---\nOriginal\n").unwrap(); + let vault_path = vault.path().to_str().unwrap(); + let note = read_note(vault_path, path.to_str().unwrap()).unwrap(); + let external = "---\nid: original\ntitle: Note\naliases: [External]\n---\nOriginal\n"; + fs::write(&path, external).unwrap(); + let error = save_note( + vault_path, + path.to_str().unwrap(), + ¬e.meta, + ¬e.content, + ¬e.raw, + ) + .err() + .unwrap(); + assert!(error.starts_with("Save conflict:")); + assert_eq!(fs::read_to_string(&path).unwrap(), external); + } + + #[test] + fn rename_reports_exact_old_and_saved_baselines_to_open_editors() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path(); + let old_path = root.join("Before.md"); + let old_raw = "---\nid: stable\ntitle: Before\naliases: [Legacy]\n---\nBody.\n"; + fs::write(&old_path, old_raw).unwrap(); + let result = + super::rename_note(old_path.to_str().unwrap(), "After", root.to_str().unwrap()) + .unwrap(); + assert_eq!(result.path, root.join("After.md").to_string_lossy()); + assert_eq!(result.old_raw, old_raw); + assert_eq!(result.old_title, "Before"); + assert_eq!(result.new_title, "After"); + assert_eq!(result.new_raw, fs::read_to_string(&result.path).unwrap()); + assert!(result.new_raw.contains("aliases:")); + assert!(!old_path.exists()); + } + + #[test] + fn favorites_follow_note_and_notebook_renames_and_moves_with_mixed_separators() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path(); + let vault_path = root.to_str().unwrap(); + super::ensure_vault_structure(vault_path).unwrap(); + fs::create_dir(root.join("Drafts")).unwrap(); + fs::create_dir(root.join("DraftsExtra")).unwrap(); + fs::create_dir(root.join("Archive")).unwrap(); + fs::create_dir(root.join("Group")).unwrap(); + fs::write(root.join("Drafts/First.md"), "---\ntitle: First\n---\nbody").unwrap(); + fs::write(root.join("DraftsExtra/Keep.md"), "other").unwrap(); + super::save_quick_access( + vault_path, + &["Drafts\\First.md".into(), "DraftsExtra/Keep.md".into()], + ) + .unwrap(); + let renamed = super::rename_note( + root.join("Drafts/First.md").to_str().unwrap(), + "Second", + vault_path, + ) + .unwrap(); + assert_eq!( + super::load_quick_access(vault_path).unwrap(), + ["Drafts/Second.md", "DraftsExtra/Keep.md",] + ); + let moved = super::move_note( + vault_path, + &renamed.path, + root.join("Archive").to_str().unwrap(), + ) + .unwrap(); + assert_eq!( + super::load_quick_access(vault_path).unwrap()[0], + "Archive/Second.md" + ); + let note_after_move = fs::read_to_string(&moved).unwrap(); + + super::save_quick_access( + vault_path, + &[ + "Archive\\Second.md".into(), + "Archive/Sub\\Other.md".into(), + "DraftsExtra/Keep.md".into(), + ], + ) + .unwrap(); + set_notebook_icon(vault_path, "Archive", Some("builtin:folder")).unwrap(); + let renamed_book = super::rename_notebook( + vault_path, + root.join("Archive").to_str().unwrap(), + "Journal", + ) + .unwrap(); + assert_eq!( + super::load_quick_access(vault_path).unwrap(), + [ + "Journal/Second.md", + "Journal/Sub/Other.md", + "DraftsExtra/Keep.md", + ] + ); + super::move_notebook( + vault_path, + &renamed_book, + root.join("Group").to_str().unwrap(), + ) + .unwrap(); + assert_eq!( + super::load_quick_access(vault_path).unwrap(), + [ + "Group/Journal/Second.md", + "Group/Journal/Sub/Other.md", + "DraftsExtra/Keep.md", + ] + ); + assert_eq!( + fs::read_to_string(root.join("Group/Journal/Second.md")).unwrap(), + note_after_move + ); + assert_eq!( + load_notebook_icons(vault_path).unwrap()["Group/Journal"], + "builtin:folder" + ); + } + + #[cfg(unix)] + #[test] + fn failed_favorites_save_rolls_back_note_and_notebook_paths() { + use std::os::unix::fs::PermissionsExt; + let vault = tempfile::tempdir().unwrap(); + let root = vault.path(); + let vault_path = root.to_str().unwrap(); + super::ensure_vault_structure(vault_path).unwrap(); + fs::create_dir(root.join("Book")).unwrap(); + fs::create_dir(root.join("Target")).unwrap(); + let note = root.join("Book/Note.md"); + let original = "---\ntitle: Note\n---\noriginal"; + fs::write(¬e, original).unwrap(); + super::save_quick_access(vault_path, &["Book/Note.md".into()]).unwrap(); + let favorites = helixnotes_dir(vault_path).join("quick_access.json"); + let before = fs::read(&favorites).unwrap(); + fs::set_permissions(&favorites, fs::Permissions::from_mode(0o440)).unwrap(); + + assert!(super::rename_note(note.to_str().unwrap(), "Changed", vault_path).is_err()); + assert!(super::move_note( + vault_path, + note.to_str().unwrap(), + root.join("Target").to_str().unwrap() + ) + .is_err()); + assert!( + super::rename_notebook(vault_path, root.join("Book").to_str().unwrap(), "Renamed") + .is_err() + ); + assert!(super::move_notebook( + vault_path, + root.join("Book").to_str().unwrap(), + root.join("Target").to_str().unwrap() + ) + .is_err()); + assert_eq!(fs::read_to_string(¬e).unwrap(), original); + assert!(!root.join("Book/Changed.md").exists()); + assert!(!root.join("Target/Note.md").exists()); + assert!(!root.join("Renamed").exists()); + assert!(!root.join("Target/Book").exists()); + assert_eq!(fs::read(&favorites).unwrap(), before); + } + + #[test] + fn rename_move_and_restore_reject_collisions_without_changing_either_note() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path(); + let vault_path = root.to_str().unwrap(); + super::ensure_vault_structure(vault_path).unwrap(); + let src = root.join("Source.md"); + let existing = root.join("Taken.md"); + fs::write(&src, "---\ntitle: Source\n---\nSOURCE").unwrap(); + fs::write(&existing, "DESTINATION").unwrap(); + assert!(super::rename_note(src.to_str().unwrap(), "Taken", vault_path).is_err()); + assert_eq!( + fs::read_to_string(&src).unwrap(), + "---\ntitle: Source\n---\nSOURCE" + ); + assert_eq!(fs::read_to_string(&existing).unwrap(), "DESTINATION"); + + let target_dir = root.join("Target"); + fs::create_dir(&target_dir).unwrap(); + fs::write(target_dir.join("Source.md"), "TARGET").unwrap(); + assert!(super::move_note( + vault_path, + src.to_str().unwrap(), + target_dir.to_str().unwrap() + ) + .is_err()); + assert_eq!( + fs::read_to_string(&src).unwrap(), + "---\ntitle: Source\n---\nSOURCE" + ); + assert_eq!( + fs::read_to_string(target_dir.join("Source.md")).unwrap(), + "TARGET" + ); + + super::delete_note(vault_path, src.to_str().unwrap()).unwrap(); + let trash = super::get_trash_contents(vault_path).unwrap().notes; + assert_eq!(trash.len(), 1); + fs::write(&src, "REPLACEMENT").unwrap(); + assert!(super::restore_note(vault_path, &trash[0].path, None).is_err()); + assert_eq!(fs::read_to_string(&src).unwrap(), "REPLACEMENT"); + assert_eq!( + fs::read_to_string(&trash[0].path).unwrap(), + "---\ntitle: Source\n---\nSOURCE" + ); + } + + #[test] + fn rapid_repeated_trash_preserves_all_same_named_notes_and_restores_original_name() { + let vault = tempfile::tempdir().unwrap(); + let vault_path = vault.path().to_str().unwrap(); + super::ensure_vault_structure(vault_path).unwrap(); + let note = vault.path().join("Repeat.md"); + for index in 0..200 { + fs::write(¬e, format!("---\ntitle: Repeat\n---\nCopy {index}")).unwrap(); + super::delete_note(vault_path, note.to_str().unwrap()).unwrap(); + } + let trash = super::get_trash_contents(vault_path).unwrap(); + assert_eq!(trash.notes.len(), 200); + let contents: std::collections::HashSet<_> = trash + .notes + .iter() + .map(|entry| fs::read_to_string(&entry.path).unwrap()) + .collect(); + assert_eq!(contents.len(), 200); + let restored = super::restore_note(vault_path, &trash.notes[0].path, None).unwrap(); + assert_eq!(restored, note.to_string_lossy()); + assert!(fs::read_to_string(&restored).unwrap().contains("Copy ")); + } + + #[test] + fn notebook_trash_sidecars_survive_repeated_deletion_and_restore_collisions() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path(); + let vault_path = root.to_str().unwrap(); + super::ensure_vault_structure(vault_path).unwrap(); + fs::create_dir(root.join("Parent")).unwrap(); + for index in 0..30 { + fs::create_dir(root.join("Parent/Book")).unwrap(); + fs::write(root.join("Parent/Book/Note.md"), format!("Book {index}")).unwrap(); + super::delete_notebook(vault_path, root.join("Parent/Book").to_str().unwrap()).unwrap(); + } + let trash = super::get_trash_contents(vault_path).unwrap(); + assert_eq!(trash.notebooks.len(), 30); + assert!(trash + .notebooks + .iter() + .all(|entry| entry.name == "Book" && entry.note_count == 1)); + fs::create_dir(root.join("Parent/Book")).unwrap(); + fs::write(root.join("Parent/Book/Note.md"), "current").unwrap(); + let old = &trash.notebooks[0].path; + assert!(super::restore_notebook(vault_path, old).is_err()); + assert_eq!( + fs::read_to_string(root.join("Parent/Book/Note.md")).unwrap(), + "current" + ); + assert!(std::path::Path::new(old).exists()); + fs::remove_dir_all(root.join("Parent/Book")).unwrap(); + let restored = super::restore_notebook(vault_path, old).unwrap(); + assert_eq!(restored, root.join("Parent/Book").to_string_lossy()); + assert!(fs::read_to_string(root.join("Parent/Book/Note.md")) + .unwrap() + .starts_with("Book ")); + } + + #[test] + fn notebook_rename_and_move_reject_existing_directories_without_losing_icons() { + let vault = tempfile::tempdir().unwrap(); + let root = vault.path(); + let vault_path = root.to_str().unwrap(); + super::ensure_vault_structure(vault_path).unwrap(); + let book = create_notebook(vault_path, None, "Book").unwrap(); + fs::write(root.join("Book/Only.md"), "original").unwrap(); + set_notebook_icon(vault_path, "Book", Some("builtin:star")).unwrap(); + fs::create_dir(root.join("Taken")).unwrap(); + assert!(super::rename_notebook(vault_path, &book.path, "Taken").is_err()); + fs::create_dir(root.join("Target")).unwrap(); + fs::create_dir(root.join("Target/Book")).unwrap(); + assert!(super::move_notebook( + vault_path, + &book.path, + root.join("Target").to_str().unwrap() + ) + .is_err()); + assert_eq!( + fs::read_to_string(root.join("Book/Only.md")).unwrap(), + "original" + ); + assert_eq!( + load_notebook_icons(vault_path).unwrap()["Book"], + "builtin:star" + ); + } + + #[test] + fn legacy_trash_names_restore_without_a_sidecar() { + let vault = tempfile::tempdir().unwrap(); + let vault_path = vault.path().to_str().unwrap(); + super::ensure_vault_structure(vault_path).unwrap(); + let trash = helixnotes_dir(vault_path).join("trash"); + let old_note = trash.join("20260101000000_Old.md"); + fs::write(&old_note, "---\ntitle: Old\n---\nlegacy note").unwrap(); + let restored_note = + super::restore_note(vault_path, old_note.to_str().unwrap(), None).unwrap(); + assert_eq!(restored_note, vault.path().join("Old.md").to_string_lossy()); + assert!(fs::read_to_string(&restored_note) + .unwrap() + .contains("legacy note")); + + let old_notebook = trash.join("20260101000000000_Old Book"); + fs::create_dir(&old_notebook).unwrap(); + fs::write(old_notebook.join("Keep.md"), "legacy book").unwrap(); + let restored_book = restore_notebook(vault_path, old_notebook.to_str().unwrap()).unwrap(); + assert_eq!( + restored_book, + vault.path().join("Old Book").to_string_lossy() + ); + assert_eq!( + fs::read_to_string(vault.path().join("Old Book/Keep.md")).unwrap(), + "legacy book" + ); + } + + #[cfg(unix)] + #[test] + fn daily_and_restored_notebook_cannot_follow_symlinks_out_of_vault() { + use std::os::unix::fs::symlink; + let root = tempfile::tempdir().unwrap(); + let vault = root.path().join("vault"); + let outside = root.path().join("outside"); + fs::create_dir(&vault).unwrap(); + fs::create_dir(&outside).unwrap(); + let vault_path = vault.to_str().unwrap(); + super::ensure_vault_structure(vault_path).unwrap(); + symlink(&outside, vault.join("Daily")).unwrap(); + assert!(super::create_daily_note(vault_path, Some("2026-01-01"), "iso").is_err()); + assert!(!outside.join("2026-01-01.md").exists()); + fs::remove_file(vault.join("Daily")).unwrap(); + let existing = vault.join("Daily/2026-01-01.md"); + fs::create_dir(vault.join("Daily")).unwrap(); + fs::write(outside.join("2026-01-01.md"), "outside").unwrap(); + symlink(outside.join("2026-01-01.md"), &existing).unwrap(); + assert!(super::create_daily_note(vault_path, Some("2026-01-01"), "iso").is_err()); + assert_eq!( + fs::read_to_string(outside.join("2026-01-01.md")).unwrap(), + "outside" + ); + + let trash = helixnotes_dir(vault_path).join("trash"); + let notebook = trash.join("20260101000000000_Stashed"); + fs::create_dir(¬ebook).unwrap(); + fs::write(notebook.join("Keep.md"), "safe").unwrap(); + fs::write( + trash.join("20260101000000000_Stashed.meta"), + "Escape/Stashed", + ) + .unwrap(); + symlink(&outside, vault.join("Escape")).unwrap(); + assert!(restore_notebook(vault_path, notebook.to_str().unwrap()).is_err()); + assert!(notebook.join("Keep.md").exists()); + assert!(!outside.join("Stashed").exists()); + } + + #[test] + fn vault_state_save_replaces_file_without_truncating_open_reader() { + let vault = tempfile::tempdir().unwrap(); + let vault_path = vault.path().to_str().unwrap(); + super::ensure_vault_structure(vault_path).unwrap(); + let state = helixnotes_dir(vault_path).join("state.json"); + fs::write(&state, b"old vault state").unwrap(); + let mut reader = fs::File::open(&state).unwrap(); + let new_state = crate::types::VaultState { + last_open_note: Some("Daily/2026-01-01.md".into()), + ..Default::default() + }; + super::save_vault_state(vault_path, &new_state).unwrap(); + let mut old = String::new(); + reader.read_to_string(&mut old).unwrap(); + assert_eq!(old, "old vault state"); + let saved = super::load_vault_state(vault_path).unwrap(); + assert_eq!(saved.last_open_note, new_state.last_open_note); + } } diff --git a/src-tauri/src/vault/watcher.rs b/src-tauri/src/vault/watcher.rs index cfef5e8..f624d96 100644 --- a/src-tauri/src/vault/watcher.rs +++ b/src-tauri/src/vault/watcher.rs @@ -133,6 +133,7 @@ pub fn start_watcher(app: AppHandle, vault_path: String) -> Result Result(); + // Native note mutations hold note_save through their path event. + // Read and emit only after they finish, so the watcher cannot + // publish an intermediate rename or stale note contents. + let _save_guard = state.note_save.blocking_lock(); // Keep the batch while muted, rather than losing concurrent external // edits. Nothing is indexed or emitted until local imports finish. if state.importing.load(std::sync::atomic::Ordering::Relaxed) { continue; } - let search = { - // Match the runtime commit's lock order so an old watcher cannot - // send its final batch into the newly selected vault's index. - let Ok(search) = state.search_index.lock() else { - continue; - }; - let active = state - .config - .lock() - .ok() - .is_some_and(|config| config.active_vault.as_deref() == Some(&vault_path)); - if !active { - continue; + // Each watcher belongs to its own vault. A detached note window may + // still need changes from a vault that is no longer active; never + // index those changes into the main window's active search index. + if state.validate_vault(&vault_path).is_err() { + continue; + } + if search.is_none() { + match state.vault_snapshot(&vault_path) { + Ok(index) => search = index, + Err(error) => { + log::error!("Could not open search index for watched vault: {error}"); + continue; + } } - search.clone() - }; + } let mut refresh_vault = false; for (path, event_type) in changes.drain() { if path.extension().and_then(|extension| extension.to_str()) == Some("md") diff --git a/src/lib/api.ts b/src/lib/api.ts index 4f70ff1..0aa17a0 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -20,6 +20,7 @@ import type { ExternalVaultResult, StartupView, ToolbarLayout, + PendingOpenFile, } from "./types"; export async function openVault(path: string): Promise { @@ -46,6 +47,10 @@ export async function completeWindowClose(): Promise { return invoke("complete_window_close"); } +export async function cancelWindowClose(): Promise { + return invoke("cancel_window_close"); +} + export async function setTheme(theme: string): Promise { return invoke("set_theme", { theme }); } @@ -153,8 +158,9 @@ export async function saveNote( path: string, meta: NoteMeta, body: string, -): Promise { - return invoke("save_note", { vaultPath, path, meta, body }); + expectedRaw: string, +): Promise { + return invoke("save_note", { vaultPath, path, meta, body, expectedRaw }); } export async function createNote( @@ -448,20 +454,20 @@ export async function copyPngToClipboard(data: Uint8Array): Promise { // ── Backup ── -export async function createBackup(): Promise { - return invoke("create_backup"); +export async function createBackup(vaultPath: string): Promise { + return invoke("create_backup", { vaultPath }); } -export async function listBackups(): Promise { - return invoke("list_backups"); +export async function listBackups(vaultPath: string): Promise { + return invoke("list_backups", { vaultPath }); } -export async function restoreBackup(backupPath: string): Promise { - return invoke("restore_backup", { backupPath }); +export async function restoreBackup(vaultPath: string, backupPath: string): Promise { + return invoke("restore_backup", { vaultPath, backupPath }); } -export async function deleteBackup(backupPath: string): Promise { - return invoke("delete_backup", { backupPath }); +export async function deleteBackup(vaultPath: string, backupPath: string): Promise { + return invoke("delete_backup", { vaultPath, backupPath }); } export async function setBackupSettings( @@ -599,6 +605,10 @@ export async function isMobilePlatform(): Promise { return invoke("is_mobile_platform"); } -export async function getPendingOpenFile(): Promise { +export async function getPendingOpenFile(): Promise { return invoke("get_pending_open_file"); } + +export async function ackPendingOpenFile(id: number): Promise { + return invoke("ack_pending_open_file", { id }); +} diff --git a/src/lib/components/AppLayout.svelte b/src/lib/components/AppLayout.svelte index f3d451c..e7296a9 100644 --- a/src/lib/components/AppLayout.svelte +++ b/src/lib/components/AppLayout.svelte @@ -65,7 +65,7 @@ const appWindow = getCurrentWindow(); const isMac = navigator.platform.startsWith('Mac'); const isMobile = $derived($platformIsMobile); - import { loadVaultState, saveVaultState, readNote, deleteNote, createDailyNote, createBackup, getPendingOpenFile, addQuickAccess, removeQuickAccess, getQuickAccess, setTheme, syncNow, getAppConfig, setTaskDone, setTaskPriority, setTaskDue } from '$lib/api'; + import { loadVaultState, saveVaultState, readNote, deleteNote, createDailyNote, createBackup, getPendingOpenFile, ackPendingOpenFile, addQuickAccess, removeQuickAccess, getQuickAccess, setTheme, syncNow, setTaskDone, setTaskPriority, setTaskDue } from '$lib/api'; import { darkThemes, isAndroid } from '$lib/platform'; import { openNoteWindow } from '$lib/utils/window'; import { normalizeStartupView, resolveStartupTarget } from '$lib/utils/startup-view'; @@ -74,7 +74,7 @@ import { isPathInDirectory, isTrashedNote } from '$lib/utils/paths'; import { get } from 'svelte/store'; import type { VaultState, FileEvent, NotebookEntry, NoteEntry, TaskItem, SearchResult } from '$lib/types'; - import { completeWindowClose } from '$lib/api'; + import { completeWindowClose, cancelWindowClose } from '$lib/api'; import type { StartupTarget } from '$lib/utils/startup-view'; function findNotebookByPath(list: NotebookEntry[], relPath: string): NotebookEntry | null { @@ -92,6 +92,7 @@ let pendingSearchReveal = $state<{ path: string; token: number } | null>(null); let unlistenFileChange: (() => void) | null = null; let unlistenClose: (() => void) | null = null; + let unlistenVaultRestored: (() => void) | null = null; let fileRefreshTimer: ReturnType | null = null; const ownerVault = get(appConfig)?.active_vault ?? null; activateVaultData(ownerVault); @@ -102,6 +103,11 @@ let persistTimer: ReturnType | null = null; let removePopstateListener: (() => void) | null = null; const backupListeners = new Set<() => void>(); + let backupInFlight = false; + let pendingOpenDrain: Promise | null = null; + let unlistenPendingOpen: (() => void) | null = null; + let pendingOpenNotification = false; + let removeMobileFlushListeners: (() => void) | null = null; const recentChanges = new Map(); let initialRefreshPending = true; let fileRefreshPending = false; @@ -215,23 +221,38 @@ } async function checkScheduledBackup() { - if (!ownerIsCurrent()) return; + if (!ownerIsCurrent() || backupInFlight) return; const config = get(appConfig); - if (!config?.backup_enabled) return; + const vault = activeVaultConfig(config); + if (!config?.backup_enabled || !vault) return; const interval = parseFrequencyMs(config.backup_frequency); - const last = config.last_backup_time ? new Date(config.last_backup_time).getTime() : 0; - if (Date.now() - last >= interval) { - const unlisten = await listen('backup-done', (event: any) => { - if (ownerIsCurrent() && event.payload?.success) { - const cur = get(appConfig); - if (cur) appConfig.set({ ...cur, last_backup_time: new Date().toISOString() }); + const last = vault.last_backup_time ? new Date(vault.last_backup_time).getTime() : 0; + if (Date.now() - last < interval) return; + backupInFlight = true; + let unlisten: (() => void) | null = null; + try { + unlisten = await listen<{ vault_path: string; bookmark_id?: string | null; success: boolean; entry?: { created: string } }>('backup-done', (event) => { + if (event.payload.vault_path !== ownerVault || (event.payload.bookmark_id ?? null) !== (vault.bookmark_id ?? null)) return; + if (ownerIsCurrent() && event.payload.success && event.payload.entry?.created) { + const current = get(appConfig); + const active = activeVaultConfig(current); + if (current && active) appConfig.set({ + ...current, + vaults: current.vaults.map((v) => v === active ? { ...v, last_backup_time: event.payload.entry!.created } : v) + }); } - unlisten(); - backupListeners.delete(unlisten); + backupInFlight = false; + unlisten?.(); + if (unlisten) backupListeners.delete(unlisten); }); - if (!ownerIsCurrent()) { unlisten(); return; } + if (!ownerIsCurrent()) { unlisten(); backupInFlight = false; return; } backupListeners.add(unlisten); - try { await createBackup(); } catch (_) { unlisten(); backupListeners.delete(unlisten); } + await createBackup(ownerVault!); + } catch (error) { + console.error('Failed to start scheduled backup:', error); + unlisten?.(); + if (unlisten) backupListeners.delete(unlisten); + backupInFlight = false; } } @@ -259,9 +280,31 @@ } // Track note navigation in history stack + async function handlePathsMoved(oldPath: string, newPath: string) { + if (!ownerIsCurrent()) return; + navHistory.remap(oldPath, newPath); + const path = $activeNotePath; + if (!path || (path !== oldPath && !path.startsWith(oldPath + '/') && !path.startsWith(oldPath + '\\'))) return; + const migrated = newPath + path.slice(oldPath.length); + const previous = $activeNote; + let content = previous ? { ...previous, path: migrated } : null; + try { + content = await readNote(ownerVault!, migrated); + } catch (error) { + console.error('Failed to reload relocated note:', error); + } + if (!ownerIsCurrent() || $activeNotePath !== path || $activeNote !== previous || !content) return; + $activeNote = content; + $activeNotePath = migrated; + editor?.loadNote(migrated, content.content); + } + $effect(() => { const path = $activeNotePath; - if (path) navHistory.push(path); + if (path) { + navHistory.push(path); + if (stateReady) queueMicrotask(drainPendingOpenFiles); + } }); async function navigateHistory(direction: -1 | 1) { @@ -285,48 +328,56 @@ } } - async function handleOpenFile(filePath: string, token = beginNavigation()) { - if (!navigationIsCurrent(token)) return; - if (!filePath || !filePath.endsWith('.md')) return; + async function handleOpenFile(filePath: string, token = beginNavigation()): Promise { + if (!navigationIsCurrent(token) || !filePath || !filePath.endsWith('.md')) return false; + if (filePath === $activeNotePath) return true; // Never replace an open draft with a stale disk read. const isExternal = !isPathInDirectory(filePath, ownerVault); - - // External .md → viewer mode (skipped on Android) - if (isExternal) { - if (isAndroid) return; - try { - const content = await readNote(ownerVault!, filePath); - if (!navigationIsCurrent(token)) return; - if (editor && !(await editor.flushSave())) return; - if (!navigationIsCurrent(token)) return; - $viewerNote = { path: filePath, content: content.content }; - $activeNote = content; - $activeNotePath = filePath; - $editorDirty = false; - $readOnly = true; - $focusMode = true; - editor?.loadNote(filePath, content.content); - } catch (e) { - console.error('Failed to open external file:', e); - } - return; - } - - // Vault file: normal flow + if (isExternal && isAndroid) return false; + if (editor && !(await editor.flushSave())) return false; + if (!navigationIsCurrent(token)) return false; try { const content = await readNote(ownerVault!, filePath); - if (!navigationIsCurrent(token)) return; - if (editor && !(await editor.flushSave())) return; - if (!navigationIsCurrent(token)) return; - $viewerNote = null; + if (!navigationIsCurrent(token)) return false; + $viewerNote = isExternal ? { path: filePath, content: content.content } : null; $activeNote = content; $activeNotePath = filePath; $editorDirty = false; + if (isExternal) { + $readOnly = true; + $focusMode = true; + } editor?.loadNote(filePath, content.content); - } catch (e) { - console.error('Failed to open file:', e); + return true; + } catch (error) { + console.error('Failed to open file:', error); + return false; } } + function drainPendingOpenFiles() { + if (pendingOpenDrain) { pendingOpenNotification = true; return; } + if (!stateReady || !ownerIsCurrent()) return; + pendingOpenDrain = (async () => { + try { + while (ownerIsCurrent()) { + const pending = await getPendingOpenFile(); + if (!pending || !ownerIsCurrent()) break; + if (!(await handleOpenFile(pending.path))) break; + if (!ownerIsCurrent()) break; + await ackPendingOpenFile(pending.id); + } + } catch (error) { + console.error('Failed to open pending file:', error); + } finally { + pendingOpenDrain = null; + if (pendingOpenNotification) { + pendingOpenNotification = false; + queueMicrotask(drainPendingOpenFiles); + } + } + })(); + } + async function restoreLastNote(path: string, token: number) { const canRestore = () => navigationIsCurrent(token) && !$activeNotePath && !$editorDirty && !$viewerNote; if (!canRestore() || isTrashedNote(path, ownerVault)) return; @@ -524,76 +575,37 @@ } async function updateActiveNoteMetadata(patch: Pick): Promise { - if (!ownerIsCurrent() || !$activeNote || !editor) return false; + if (!ownerIsCurrent() || !$activeNote || !editor || editor.isMutationPending()) return false; $activeNote = { ...$activeNote, meta: { ...$activeNote.meta, ...patch } }; editor.markEdited(); return editor.forceSave(); } - // Toggle a task done from the Tasks view. If the task's note is open in the editor, - // flush first then reload after the file edit (so we never clobber unsaved edits). - async function toggleTask(task: TaskItem) { - const done = !task.completed; - const isActive = task.note_path === $activeNotePath; - if (isActive && editor && !(await editor.forceSave())) return; + // An active task mutation is serialized against both editing surfaces. The editor + // briefly becomes read-only while the native command changes the disk note. + async function changeTask(task: TaskItem, operation: () => Promise) { if (!ownerIsCurrent()) return; try { - await setTaskDone(ownerVault!, task.note_path, task.line, task.raw_line, done); - } catch (e) { - console.error('Failed to toggle task:', e); - } - if (isActive && ownerIsCurrent() && $activeNotePath === task.note_path) { - const previous = $activeNote; - try { - const content = await readNote(ownerVault!, task.note_path); - if (!ownerIsCurrent() || $activeNotePath !== task.note_path || $activeNote !== previous || $editorDirty) return; - $activeNote = content; - $editorDirty = false; - editor?.loadNote(task.note_path, content.content); - } catch (_) {} + if (task.note_path === $activeNotePath && editor) { + await editor.applyNativeTaskChange(task.note_path, operation); + } else { + await operation(); + } + } catch (error) { + console.error('Failed to update task:', error); } } + async function toggleTask(task: TaskItem) { + await changeTask(task, () => setTaskDone(ownerVault!, task.note_path, task.line, task.raw_line, !task.completed)); + } + async function changeTaskPriority(task: TaskItem, priority: string | null) { - const isActive = task.note_path === $activeNotePath; - if (isActive && editor && !(await editor.forceSave())) return; - if (!ownerIsCurrent()) return; - try { - await setTaskPriority(ownerVault!, task.note_path, task.line, task.raw_line, priority); - } catch (e) { - console.error('Failed to set task priority:', e); - } - if (isActive && ownerIsCurrent() && $activeNotePath === task.note_path) { - const previous = $activeNote; - try { - const content = await readNote(ownerVault!, task.note_path); - if (!ownerIsCurrent() || $activeNotePath !== task.note_path || $activeNote !== previous || $editorDirty) return; - $activeNote = content; - $editorDirty = false; - editor?.loadNote(task.note_path, content.content); - } catch (_) {} - } + await changeTask(task, () => setTaskPriority(ownerVault!, task.note_path, task.line, task.raw_line, priority)); } async function changeTaskDue(task: TaskItem, due: string | null) { - const isActive = task.note_path === $activeNotePath; - if (isActive && editor && !(await editor.forceSave())) return; - if (!ownerIsCurrent()) return; - try { - await setTaskDue(ownerVault!, task.note_path, task.line, task.raw_line, due); - } catch (e) { - console.error('Failed to set task due date:', e); - } - if (isActive && ownerIsCurrent() && $activeNotePath === task.note_path) { - const previous = $activeNote; - try { - const content = await readNote(ownerVault!, task.note_path); - if (!ownerIsCurrent() || $activeNotePath !== task.note_path || $activeNote !== previous || $editorDirty) return; - $activeNote = content; - $editorDirty = false; - editor?.loadNote(task.note_path, content.content); - } catch (_) {} - } + await changeTask(task, () => setTaskDue(ownerVault!, task.note_path, task.line, task.raw_line, due)); } async function handleDailyNote() { @@ -853,22 +865,67 @@ persistState(); }); + let activeRefreshRequest = 0; + async function refreshActiveNote(path: string, restored = false) { + if (path !== $activeNotePath || !$activeNote || !ownerIsCurrent()) return; + const request = ++activeRefreshRequest; + const openingNote = $activeNote; + try { + const content = await readNote(ownerVault!, path); + if (!ownerIsCurrent() || request !== activeRefreshRequest || $activeNotePath !== path) return; + if ($editorDirty) { + if (restored && content.raw !== editor?.getAcceptedRaw()) editor?.flagExternalConflict(); + return; + } + if ($activeNote !== openingNote || content.raw === openingNote.raw) return; + $activeNote = content; + if ($viewerNote?.path === path) $viewerNote = { path, content: content.content }; + editor?.loadNote(path, content.content); + } catch (error) { + if (restored && ownerIsCurrent() && request === activeRefreshRequest && $activeNotePath === path) { + if ($editorDirty) editor?.flagExternalConflict(); + else { + $activeNotePath = null; + $activeNote = null; + $viewerNote = null; + } + } else if (!restored) console.error('Failed to refresh active note:', error); + } + } + onMount(async () => { if (!ownerIsCurrent() || !ownerVault) return; const startupToken = beginNavigation(); + if (isMobile) { + const flush = () => { + if (ownerIsCurrent()) void editor?.flushSave(); + }; + const onVisibilityChange = () => { + if (document.visibilityState === 'hidden') flush(); + }; + document.addEventListener('visibilitychange', onVisibilityChange); + window.addEventListener('pagehide', flush); + window.addEventListener('app-lifecycle-flush', flush); + removeMobileFlushListeners = () => { + document.removeEventListener('visibilitychange', onVisibilityChange); + window.removeEventListener('pagehide', flush); + window.removeEventListener('app-lifecycle-flush', flush); + }; + } if (!isMobile) { unlistenClose = await appWindow.onCloseRequested(async (event) => { // Always prevent Tauri's implicit JS destroy(), which bypasses the tray policy. event.preventDefault(); - if (!ownerIsCurrent()) return; + if (!ownerIsCurrent()) { await cancelWindowClose(); return; } try { - if (editor && !(await editor.flushSave())) return; - if (!ownerIsCurrent()) return; + if (editor && !(await editor.flushSave())) { await cancelWindowClose(); return; } + if (!ownerIsCurrent()) { await cancelWindowClose(); return; } await persistVaultState(); - if (!ownerIsCurrent()) return; + if (!ownerIsCurrent()) { await cancelWindowClose(); return; } await completeWindowClose(); } catch (error) { console.error('Failed to close window:', error); + try { await cancelWindowClose(); } catch (cancelError) { console.error('Failed to cancel window close:', cancelError); } } }); if (!ownerIsCurrent()) { unlistenClose(); return; } @@ -894,12 +951,22 @@ // Body/modified/preview changes do not change notebook counts or the tag index. if (!previous) scheduleFileRefresh(true); else if (!sameNoteTags(previous, note)) scheduleFileRefresh(false); + if (payload.path === $activeNotePath) void refreshActiveNote(payload.path); }); if (!ownerIsCurrent()) { unlistenFileChange(); return; } - // Listen for file open events (from single-instance or OS file associations) - unlistenOpenFile = await listen('open-file', async (event) => { - if (!ownerIsCurrent()) return; - await handleOpenFile(event.payload); + unlistenPendingOpen = await listen('open-file-pending', () => { + drainPendingOpenFiles(); + }); + if (!ownerIsCurrent()) { unlistenPendingOpen(); return; } + unlistenVaultRestored = await listen<{ vault_path: string }>('vault-restored', ({ payload }) => { + if (!ownerIsCurrent() || payload.vault_path !== ownerVault) return; + const path = $activeNotePath; + if (path && isPathInDirectory(path, ownerVault)) void refreshActiveNote(path, true); + scheduleFileRefresh(true); + }); + if (!ownerIsCurrent()) { unlistenVaultRestored(); return; } + unlistenOpenFile = await listen('open-file', (event) => { + if (ownerIsCurrent()) void handleOpenFile(event.payload); }); if (!ownerIsCurrent()) { unlistenOpenFile(); return; } @@ -973,36 +1040,33 @@ initialRefreshPending = false; if (fileRefreshPending) scheduleFileRefresh(refreshLists); - // Check for pending file from first-launch CLI args - try { - const pending = await getPendingOpenFile(); - if (!ownerIsCurrent()) return; - if (pending && navigationIsCurrent(startupToken)) await handleOpenFile(pending); - } catch (_) {} - if (!ownerIsCurrent()) return; + // Startup state is ready; open any queued OS request before optional sync. + stateReady = true; + drainPendingOpenFiles(); // Scheduled backup: check on startup and every 5 minutes checkScheduledBackup(); backupInterval = setInterval(checkScheduledBackup, 5 * 60 * 1000); // ── WebDAV sync: global status + auto-sync triggers ── - let syncConfigRequest = 0; - unlistenSync.push(await listen('sync-progress', () => { - if (ownerIsCurrent()) syncState.set({ running: true, error: null }); + unlistenSync.push(await listen<{ vault_path: string }>('sync-progress', ({ payload }) => { + if (ownerIsCurrent() && payload.vault_path === ownerVault) syncState.set({ running: true, error: null }); })); if (!ownerIsCurrent()) { unlistenSync.pop()?.(); return; } - unlistenSync.push(await listen('sync-done', async () => { - if (!ownerIsCurrent()) return; - const request = ++syncConfigRequest; + unlistenSync.push(await listen<{ vault_path: string; bookmark_id?: string | null; success: boolean; last_sync_time?: string | null }>('sync-done', ({ payload }) => { + if (!ownerIsCurrent() || payload.vault_path !== ownerVault) return; syncState.set({ running: false, error: null }); - try { - const config = await getAppConfig(); - if (ownerIsCurrent() && request === syncConfigRequest && config.active_vault === ownerVault) appConfig.set(config); - } catch {} + if (!payload.success || !payload.last_sync_time) return; + const current = get(appConfig); + const active = activeVaultConfig(current); + if (current && active && (payload.bookmark_id ?? null) === (active.bookmark_id ?? null)) appConfig.set({ + ...current, + vaults: current.vaults.map((v) => v === active ? { ...v, last_sync_time: payload.last_sync_time } : v) + }); })); if (!ownerIsCurrent()) { unlistenSync.pop()?.(); return; } - unlistenSync.push(await listen('sync-error', (event: any) => { - if (ownerIsCurrent()) syncState.set({ running: false, error: event.payload?.error ?? 'Sync failed' }); + unlistenSync.push(await listen<{ vault_path: string; error?: string }>('sync-error', ({ payload }) => { + if (ownerIsCurrent() && payload.vault_path === ownerVault) syncState.set({ running: false, error: payload.error ?? 'Sync failed' }); })); if (!ownerIsCurrent()) { unlistenSync.pop()?.(); return; } @@ -1024,9 +1088,9 @@ if (onChangeSyncTimer) clearTimeout(onChangeSyncTimer); onChangeSyncTimer = setTimeout(() => { if (ownerIsCurrent() && !get(syncState).running) syncNow().catch(() => {}); }, 15000); } + if (!d) drainPendingOpenFiles(); prevDirty = d; }); - stateReady = true; persistState(); }); @@ -1038,9 +1102,12 @@ backupListeners.forEach((unlisten) => unlisten()); backupListeners.clear(); unlistenFileChange?.(); + unlistenVaultRestored?.(); + unlistenPendingOpen?.(); unlistenClose?.(); if (fileRefreshTimer) clearTimeout(fileRefreshTimer); unlistenOpenFile?.(); + removeMobileFlushListeners?.(); if (backupInterval) clearInterval(backupInterval); if (syncInterval) clearInterval(syncInterval); if (onChangeSyncTimer) clearTimeout(onChangeSyncTimer); @@ -1195,10 +1262,10 @@
- editor?.flushSave() ?? Promise.resolve(true)} /> + editor?.flushSave() ?? Promise.resolve(true)} onBeforePathMutation={() => editor?.beginPathMutation() ?? Promise.resolve(() => {})} onPathsMoved={handlePathsMoved} />
- editor?.flushSave() ?? Promise.resolve(true)} onBeforeNoteDuplicate={() => editor?.forceSave() ?? Promise.resolve(true)} onUpdateActiveNote={updateActiveNoteMetadata} onTagsChanged={handleTagsChanged} onRefreshTags={() => { if (!isMobile) void sidebar?.refreshTags(); }} onNoteMoved={() => sidebar?.refresh()} onNoteCreated={(token) => { editor?.focusTitle(token); }} onToggleTask={toggleTask} onSetTaskPriority={changeTaskPriority} onSetTaskDue={changeTaskDue} /> + editor?.flushSave() ?? Promise.resolve(true)} onBeforeNoteDuplicate={() => editor?.forceSave() ?? Promise.resolve(true)} onBeforePathMutation={() => editor?.beginPathMutation() ?? Promise.resolve(() => {})} onPathsMoved={handlePathsMoved} onUpdateActiveNote={updateActiveNoteMetadata} onTagsChanged={handleTagsChanged} onRefreshTags={() => { if (!isMobile) void sidebar?.refreshTags(); }} onNoteMoved={() => sidebar?.refresh()} onNoteCreated={(token) => { editor?.focusTitle(token); }} onToggleTask={toggleTask} onSetTaskPriority={changeTaskPriority} onSetTaskDue={changeTaskDue} />
@@ -1250,7 +1317,7 @@
{#if !$focusMode} {#if !$sidebarCollapsed} @@ -1259,7 +1326,7 @@ {#if !$notelistCollapsed}
- editor?.flushSave() ?? Promise.resolve(true)} onBeforeNoteDuplicate={() => editor?.forceSave() ?? Promise.resolve(true)} onUpdateActiveNote={updateActiveNoteMetadata} onTagsChanged={handleTagsChanged} onRefreshTags={() => { if (!isMobile) void sidebar?.refreshTags(); }} onNoteMoved={() => sidebar?.refresh()} onNoteCreated={(token) => { editor?.focusTitle(token); }} onToggleTask={toggleTask} onSetTaskPriority={changeTaskPriority} onSetTaskDue={changeTaskDue} /> + editor?.flushSave() ?? Promise.resolve(true)} onBeforeNoteDuplicate={() => editor?.forceSave() ?? Promise.resolve(true)} onBeforePathMutation={() => editor?.beginPathMutation() ?? Promise.resolve(() => {})} onPathsMoved={handlePathsMoved} onUpdateActiveNote={updateActiveNoteMetadata} onTagsChanged={handleTagsChanged} onRefreshTags={() => { if (!isMobile) void sidebar?.refreshTags(); }} onNoteMoved={() => sidebar?.refresh()} onNoteCreated={(token) => { editor?.focusTitle(token); }} onToggleTask={toggleTask} onSetTaskPriority={changeTaskPriority} onSetTaskDue={changeTaskDue} />
diff --git a/src/lib/components/Editor.svelte b/src/lib/components/Editor.svelte index 12c1896..a02bab5 100644 --- a/src/lib/components/Editor.svelte +++ b/src/lib/components/Editor.svelte @@ -39,8 +39,8 @@ import { openFile, openUrl, copyFileTo, copyImageToClipboard as copyImageToClipboardCmd, writeBytesTo, copyPngToClipboard, copyTextToClipboard } from '$lib/api'; import { save as saveDialog } from '@tauri-apps/plugin-dialog'; import { activeNote, activeNotePath, appConfig, editorDirty, sourceMode, focusMode, readOnly, quickAccessPaths, notes, navHistory, canGoBack, canGoForward, viewerNote, viewMode, notebooks, outlineWidth } from '$lib/stores/app'; - import { saveNote, saveImage, saveAttachment, readClipboardImage, addQuickAccess, removeQuickAccess, getQuickAccess, getNoteVersions, getNoteVersionContent, createVersion, aiAsk, getAllNoteTitles, readNote, renameNote, setToolbarLayout } from '$lib/api'; - import type { VersionEntry, AiStreamEvent, NoteTitleEntry, TaskItem as TaskRecord, FileEvent, SearchTarget, ToolbarLayout } from '$lib/types'; + import { saveNote, createNote, saveImage, saveAttachment, readClipboardImage, addQuickAccess, removeQuickAccess, getQuickAccess, getNoteVersions, getNoteVersionContent, createVersion, aiAsk, getAllNoteTitles, readNote, renameNote, setToolbarLayout } from '$lib/api'; + import type { NoteContent, VersionEntry, AiStreamEvent, NoteTitleEntry, TaskItem as TaskRecord, FileEvent, SearchTarget, ToolbarLayout } from '$lib/types'; import { listen } from '@tauri-apps/api/event'; import { debounce } from '$lib/utils/debounce'; import { RevisionSaveQueue, type SaveRevision } from '$lib/utils/revision-save'; @@ -123,6 +123,8 @@ let isLoadingNote = false; let trashingNote = $state(false); let renamingNote: SaveRevision | null = null; + let externalOperationBusy = $state(false); + let pathMigrationPending = false; let lastSourceMode = $sourceMode; let linkContextMenu = $state<{ x: number; y: number; href: string; anchor: HTMLAnchorElement } | null>(null); let hiddenTitleHeading: HiddenTitleHeading | null = null; @@ -148,8 +150,6 @@ let moreButton = $state(); let morePanel = $state(); let moreOpen = $state(false); - let moreOpenedByHover = false; - let moreCloseTimer: ReturnType | null = null; let formattingTrigger: HTMLButtonElement | null = null; const morePanelId = $props.id(); let toolbarDraft = $state(null); @@ -881,6 +881,10 @@ addAttributes() { return { ...this.parent?.(), + src: { + default: null, + parseHTML: (element: HTMLElement) => resolveImageSrc(element.getAttribute('src') ?? ''), + }, size: { default: 'full', parseHTML: (element: HTMLElement) => element.getAttribute('data-size') || 'full', @@ -3135,7 +3139,12 @@ return convertFileSrc(src, 'imgproxy'); } // Decode URL encoding and undo the extra leading slash added to Windows drive paths. - let decoded = normalizeLocalAssetPath(decodeURIComponent(src)); + let decoded: string; + try { + decoded = normalizeLocalAssetPath(decodeURIComponent(src)); + } catch { + decoded = normalizeLocalAssetPath(src); + } // Keep repairing legacy POSIX paths that were saved with duplicate leading slashes. if (/^\/{2,}/.test(decoded)) decoded = decoded.replace(/^\/{2,}/, '/'); if (decoded.startsWith('/') || /^[A-Za-z]:\//.test(decoded)) { @@ -3165,9 +3174,32 @@ return src; } + function normalizeImageHtml(html: string): string { + if (!/(); - let saveError = $state<{ message: string; path: string; vault: string } | null>(null); + let saveError = $state<{ message: string; path: string; vault: string; conflict: boolean } | null>(null); let saveAttempt = 0; let retryingSave = $state(false); @@ -3193,7 +3225,7 @@ } function canInsert(origin: EditorOrigin): boolean { - return isOriginCurrent(origin) && !!origin.vault && !trashPreview && !$readOnly && !$viewerNote; + return !externalOperationBusy && !pathMigrationPending && isOriginCurrent(origin) && !!origin.vault && !trashPreview && !$readOnly && !$viewerNote; } export function markEdited(): void { @@ -3211,7 +3243,7 @@ console.error('Save failed:', error); if (origin.path && origin.vault && isCurrentSaveAttempt(origin, attempt)) { const message = error instanceof Error ? error.message : String(error); - saveError = { message: message.trim() || 'The note could not be saved.', path: origin.path, vault: origin.vault }; + saveError = { message: message.trim() || 'The note could not be saved.', path: origin.path, vault: origin.vault, conflict: /conflict|modified outside/i.test(message) }; } return false; } @@ -3227,8 +3259,63 @@ } } + async function saveConflictCopy() { + if (!saveError?.conflict || !$activeNote || !$activeNotePath || !$appConfig?.active_vault || retryingSave) return; + const origin = captureOrigin(); + const vault = origin.vault!; + const originalPath = origin.path!; + let body = getCurrentBody(); + const meta = { ...$activeNote.meta, tags: [...$activeNote.meta.tags] }; + retryingSave = true; + try { + await saves.idle(); + if (!isOriginCurrent(origin, true)) return; + const parent = originalPath.slice(vault.length + 1).replace(/[/\\][^/\\]+$/, ''); + const notebook = parent === originalPath.slice(vault.length + 1) ? null : parent.replace(/\\/g, '/'); + const entry = await createNote(vault, notebook, `${meta.title} (conflict copy)`); + for (const match of body.matchAll(/blob:[^)\s"']+/g)) { + const url = match[0]; + let relativePath = savedBlobImages.get(url); + if (!relativePath) { + relativePath = await saveBlobImage(vault, url); + savedBlobImages.set(url, relativePath); + } + body = body.replaceAll(url, relativePath); + } + const copy = await readNote(vault, entry.path); + await saveNote(vault, entry.path, { ...copy.meta, pinned: meta.pinned, tags: meta.tags }, body, copy.raw); + if (!isOriginCurrent(origin, true)) return; + const current = await readNote(vault, entry.path); + if (!isOriginCurrent(origin, true)) return; + $activeNotePath = entry.path; + $activeNote = current; + loadNote(entry.path, current.content); + } catch (error) { + console.error('Failed to save conflict copy:', error); + } finally { + retryingSave = false; + } + } + + async function reloadConflictedNote() { + if (!saveError?.conflict || !$activeNotePath || !$appConfig?.active_vault) return; + if (!window.confirm('Discard your unsaved draft and reload this note from disk? Choose Save a copy to keep the draft.')) return; + const origin = captureOrigin(); + try { + await saves.idle(); + if (!isOriginCurrent(origin, true)) return; + const content = await readNote(origin.vault!, origin.path!); + if (!isOriginCurrent(origin, true)) return; + $activeNote = content; + loadNote(origin.path!, content.content); + } catch (error) { + console.error('Failed to reload conflicted note:', error); + } + } + export function forceSave(allowWhileTrashing = false): Promise { saves.cancelScheduled(); + if (externalOperationBusy || pathMigrationPending) return Promise.resolve(false); if (get(viewerNote) || !$activeNote || !$activeNotePath) return Promise.resolve(true); if ((renamingNote && saves.isCurrentSession(renamingNote)) || (trashingNote && !allowWhileTrashing)) return Promise.resolve(false); if (!$editorDirty) return Promise.resolve(true); @@ -3261,7 +3348,8 @@ } } const blobImages = savedBlobImages; - return saves.save(snapshot, async () => { + let savedContent: NoteContent | null = null; + return saves.save(snapshot, async (expectedRaw) => { for (const url of blobUrls) { let relativePath = blobImages.get(url); if (!relativePath) { @@ -3271,11 +3359,12 @@ body = body.replaceAll(url, relativePath); replaceSavedBlob(origin, url, relativePath); } - await saveNote(vault, path, meta, body); + savedContent = await saveNote(vault, path, meta, body, expectedRaw); + return savedContent.raw; }).then((current) => { if (isCurrentSaveAttempt(origin, attempt)) saveError = null; if (!current || !isOriginCurrent(origin, true)) return false; - if ($activeNote) $activeNote = { ...$activeNote, content: body }; + if (savedContent) $activeNote = savedContent; $editorDirty = false; return true; }).catch((error) => reportSaveError(error, origin, attempt)); @@ -3308,6 +3397,21 @@ return $sourceMode ? restoreTitleH1(source.state.doc.toString()) : editorToMarkdown(); } + export function getAcceptedRaw(): string { + return saves.raw; + } + + export function flagExternalConflict() { + if (!$editorDirty || !$activeNotePath || !$appConfig?.active_vault) return; + saveError = { path: $activeNotePath, vault: $appConfig.active_vault, + message: 'The file changed on disk. Save a copy of your draft or explicitly reload the disk version.', + conflict: true }; + } + + export function isMutationPending(): boolean { + return externalOperationBusy || pathMigrationPending; + } + // ── Tag editing (active note) ── function toggleTagMenu(e: MouseEvent) { if (trashPreview) return; @@ -3339,7 +3443,7 @@ untrack(() => { if (editor) { if (ro && $editorDirty) forceSave(); - editor.setEditable(!ro); + editor.setEditable(!ro && !externalOperationBusy); } }); }); @@ -3551,6 +3655,47 @@ return forceSave(); } + /** Keep both editing surfaces stable while a native task mutation edits this note. */ + export async function applyNativeTaskChange(path: string, operation: () => Promise): Promise { + if (externalOperationBusy || path !== $activeNotePath || !(await flushSave())) return; + if (externalOperationBusy || $editorDirty || path !== $activeNotePath || !$appConfig?.active_vault) return; + const vault = $appConfig.active_vault; + const snapshot = saves.capture(); + externalOperationBusy = true; + source.configure(true, !isMobile && ($appConfig?.show_line_numbers ?? false)); + editor?.setEditable(false); + try { + await operation(); + const content = await readNote(vault, path); + if (path === $activeNotePath && vault === $appConfig?.active_vault) { + if (saves.isCurrent(snapshot) && !$editorDirty) { + $activeNote = content; + loadNote(path, content.content); + } else { + flagExternalConflict(); + } + } + } finally { + externalOperationBusy = false; + source.configure($readOnly || !!$viewerNote, !isMobile && ($appConfig?.show_line_numbers ?? false)); + editor?.setEditable(!$readOnly && !$viewerNote); + } + } + + export async function beginPathMutation(): Promise<(() => void) | null> { + if (externalOperationBusy) return null; + const path = $activeNotePath; + if (!(await flushSave()) || externalOperationBusy || path !== $activeNotePath) return null; + externalOperationBusy = true; + source.configure(true, !isMobile && ($appConfig?.show_line_numbers ?? false)); + editor?.setEditable(false); + return () => { + externalOperationBusy = false; + source.configure($readOnly || !!$viewerNote, !isMobile && ($appConfig?.show_line_numbers ?? false)); + editor?.setEditable(!$readOnly && !$viewerNote); + }; + } + function rememberLoadedNoteScroll() { if (!loadedPath) return; const previous = noteScrollPositions.get(loadedPath) ?? { rich: 0, source: 0 }; @@ -3581,7 +3726,7 @@ endToolbarCustomization(); cancelCounts(); closeNoteSearch(false); - saves.startSession(); + saves.startSession($activeNote?.raw ?? content); saveError = null; retryingSave = false; closeAiMenu(); @@ -3625,7 +3770,7 @@ const shouldBeReadOnly = isViewer || isTrashedNote(path, $appConfig?.active_vault) ? true : (isNewNote ? false : ($appConfig?.default_view_mode ?? false)); $readOnly = shouldBeReadOnly; - if (editor) editor.setEditable(!shouldBeReadOnly); + if (editor) editor.setEditable(!shouldBeReadOnly && !externalOperationBusy); const editorBody = editorElement?.closest('.editor-body') as HTMLElement | null; if ($sourceMode) { source.load(stripTitleH1(content)); @@ -4168,52 +4313,23 @@ toolbarCapture = null; } - function cancelMoreClose() { - if (moreCloseTimer !== null) clearTimeout(moreCloseTimer); - moreCloseTimer = null; - } - function closeMore() { - cancelMoreClose(); moreOpen = false; - moreOpenedByHover = false; } function openMore(focus = false) { - cancelMoreClose(); if (!moreOpen) closeFormattingDropdowns(); moreOpen = true; if (focus) void tick().then(() => morePanel?.querySelector('button:not(:disabled)')?.focus({ preventScroll: true })); } - function hoverMore(event: PointerEvent) { - if (isMobile || toolbarDraft || event.pointerType !== 'mouse') return; - cancelMoreClose(); - if (!moreOpen) { - moreOpenedByHover = true; - openMore(); - } - } - - function leaveMore(event: PointerEvent) { - if (isMobile || toolbarDraft || event.pointerType !== 'mouse') return; - const target = event.relatedTarget as Node | null; - if (target && (morePanel?.contains(target) || moreButton?.contains(target))) return; - cancelMoreClose(); - moreCloseTimer = setTimeout(() => { - moreCloseTimer = null; - if (!anyDropdownOpen && !morePanel?.contains(document.activeElement)) closeMore(); - }, 160); - } - function toggleMore(event: MouseEvent) { event.stopPropagation(); if (toolbarDraft) return; - if (moreOpen && !moreOpenedByHover) { + if (moreOpen) { closeAllDropdowns(); } else { openMore(event.detail === 0); - moreOpenedByHover = false; } } @@ -4274,14 +4390,13 @@ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); openMore(true); - moreOpenedByHover = false; } } // Fixed descendants escape the scrolling button strip/list without moving // Svelte-owned DOM. Reposition on scrolling, resizing and IME viewport changes. - function positionFormattingPopup(node: HTMLElement, more = false) { - const trigger = more ? moreButton : formattingTrigger; + function positionFormattingPopup(node: HTMLElement) { + const trigger = formattingTrigger; let frame = 0; const position = () => { frame = 0; @@ -4295,7 +4410,7 @@ const bottom = Math.min(formattingBar.getBoundingClientRect().top - 4, viewportBottom); node.style.maxWidth = `${Math.max(0, rightEdge - leftEdge)}px`; node.style.maxHeight = `${Math.max(0, bottom - topEdge)}px`; - node.style.left = `${Math.max(leftEdge, Math.min(more ? anchor.right - node.offsetWidth : anchor.left, rightEdge - node.offsetWidth))}px`; + node.style.left = `${Math.max(leftEdge, Math.min(anchor.left, rightEdge - node.offsetWidth))}px`; node.style.top = `${Math.max(topEdge, bottom - node.offsetHeight)}px`; }; const schedule = () => { if (!frame) frame = requestAnimationFrame(position); }; @@ -4843,17 +4958,7 @@ }); html = html.replace(/
    (\s*
  • $1'); - // Post-process: resolve image src paths and parse size attribute - html = html.replace(/]*\/?>/gi, (_, imgSrc, altRaw) => { - let alt = altRaw || ''; - let size = 'full'; - const sizeMatch = alt.match(/^(.*?)\|size=(small|medium|full)$/); - if (sizeMatch) { - alt = sizeMatch[1]; - size = sizeMatch[2]; - } - return `${alt}`; - }); + html = normalizeImageHtml(html); // Post-process: turn Obsidian callout blockquotes (> [!type] ...) into callout blocks. if (html.includes('[!')) { @@ -5239,6 +5344,7 @@ // Keeps semantic marks (bold, italic, links, headings, alignment) - drops only the // inline visual styles that fight the app's theme (color, bg-color, font-family, font-size). transformPastedHTML: (html: string) => { + html = normalizeImageHtml(html); if (!/style=| console.error('Failed to listen for note changes:', e)); + type PathMovedEvent = { + vault_path: string; old_path: string; new_path: string; + old_raw?: string | null; new_raw?: string | null; old_title?: string | null; new_title?: string | null; + }; + let unlistenPathMoved: (() => void) | null = null; + listen('vault-path-moved', ({ payload }) => { + if (editorDisposed || externalOperationBusy || payload.vault_path !== $appConfig?.active_vault) return; + const path = $activeNotePath; + if (!path || (path !== payload.old_path + && !path.startsWith(payload.old_path + '/') && !path.startsWith(payload.old_path + '\\'))) return; + const migrated = payload.new_path + path.slice(payload.old_path.length); + const previous = $activeNote; + if (!previous) return; + const session = saves.capture(); + const oldRaw = saves.raw; + pathMigrationPending = true; + loadedPath = migrated; + $activeNotePath = migrated; + $activeNote = { ...previous, path: migrated }; + navHistory.remap(payload.old_path, payload.new_path); + void (async () => { + try { + await saves.idle(); + const content = await readNote(payload.vault_path, migrated); + if (editorDisposed || !saves.isCurrentSession(session) || $activeNotePath !== migrated) return; + const renamedRaw = typeof payload.old_raw === 'string'; + const baselineMatches = renamedRaw ? oldRaw === payload.old_raw && saves.raw === oldRaw + && (typeof payload.new_raw !== 'string' || payload.new_raw === content.raw) + : saves.raw === content.raw; + if ($editorDirty) { + if (!baselineMatches) { flagExternalConflict(); return; } + if (renamedRaw) saves.adoptMovedRaw(oldRaw, content.raw); + if (typeof payload.old_title === 'string' && typeof payload.new_title === 'string' + && $activeNote?.meta.title === payload.old_title) { + $activeNote = { ...$activeNote, meta: { ...$activeNote.meta, title: payload.new_title } }; + } + } else { + $activeNote = content; + loadNote(migrated, content.content); + } + } catch (error) { + console.error('Failed to refresh relocated note:', error); + flagExternalConflict(); + } finally { + pathMigrationPending = false; + if ($editorDirty && !saveError?.conflict && $activeNotePath === migrated) { + saves.schedule(() => { void forceSave(); }); + } + } + })(); + }).then(fn => { + if (editorDisposed) fn(); + else unlistenPathMoved = fn; + }).catch(error => console.error('Failed to listen for relocated notes:', error)); + let unlistenToolbarLayout: (() => void) | null = null; listen('toolbar-layout-changed', (event) => { const preference = JSON.stringify(event.payload); @@ -6548,6 +6709,7 @@ clearTargetReveal(); destroyEditor(); unlistenFileChange?.(); + unlistenPathMoved?.(); unlistenToolbarLayout?.(); if (infoPathCopyTimer) clearTimeout(infoPathCopyTimer); }); @@ -6895,7 +7057,7 @@ -
    +
    {#if !$activeNote}
    @@ -6933,7 +7095,7 @@ { if (!$activeNote) return; @@ -7162,12 +7324,20 @@ {/if}
    {/if} + {#if externalOperationBusy} +
    Updating note location or task… Editing will resume shortly.
    + {/if} {#if saveError && $editorDirty && !$viewerNote && saveError.path === $activeNotePath && saveError.vault === $appConfig?.active_vault} {/if} {#if searchRevealNotice} @@ -7239,12 +7409,12 @@
    {#if isMobile} - +
    { closeLinkContextMenu(); handleEditorClick(e); }} onkeydown={(e) => { if (e.key === 'Escape') closeLinkContextMenu(); }}>
    {:else} {#if $sourceMode} - + {:else}
    { closeLinkContextMenu(); handleEditorClick(e); }} onkeydown={(e) => { if (e.key === 'Escape') closeLinkContextMenu(); }} oncontextmenu={handleEditorContextMenu}>
    @@ -7428,6 +7598,7 @@
    0 ? `bottom: ${keyboardHeight}px;` : ''} @@ -7458,11 +7629,11 @@ {/if}
    {#if !isMobile} - {#if moreOpen} -