YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(app): recover current Windows store access errors (#6948)
Ezra Ellettee194687fd9bb
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.tomlindex 5b3e18820..abcee12f1 100644--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml@@ -123,6 +123,7 @@ once_cell = "1.20.0"tauri-plugin-sentry = "0.5.0"sentry = { version = "0.42", features = ["tracing"] }regex = "1"+tempfile = "3"raw-window-handle = "0.6"notify = "8.0.0"@@ -332,9 +333,6 @@ jemalloc = ["tikv-jemallocator"][dev-dependencies]-# Used by apps/screenpipe-app-tauri/src-tauri/src/enterprise/sync.rs tests (compiled in only when the-# enterprise-build feature is on).-tempfile = "3"wiremock = "0.6"serial_test = "3"tower = { version = "0.4", features = ["util"] }diff --git a/apps/screenpipe-app-tauri/src-tauri/src/store.rs b/apps/screenpipe-app-tauri/src-tauri/src/store.rsindex 65c881e23..51a53cbd0 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/store.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/store.rs@@ -83,7 +83,27 @@ fn reset_windows_store_file_permissions(path: &Path) -> anyhow::Result<()> {std::fs::set_permissions(path, permissions)?;}+ // Cloud-backed and virtual filesystems may reject `icacls /reset` even+ // though the current process can already update the file. Do not make a+ // Windows-specific ACL utility a startup dependency for a writable store.+ if std::fs::OpenOptions::new().write(true).open(path).is_ok() {+ return Ok(());+ }+const CREATE_NO_WINDOW: u32 = 0x0800_0000;+ let status = std::process::Command::new("icacls.exe")+ .arg(path)+ .args(["/inheritance:e", "/Q"])+ .creation_flags(CREATE_NO_WINDOW)+ .status()?;+ if !status.success() {+ return Err(anyhow::anyhow!(+ "failed to enable inherited settings permissions for {}: icacls exited with {}",+ path.display(),+ status+ ));+ }+let status = std::process::Command::new("icacls.exe").arg(path).args(["/reset", "/Q"])@@ -96,32 +116,33 @@ fn reset_windows_store_file_permissions(path: &Path) -> anyhow::Result<()> {status));}+ std::fs::OpenOptions::new().write(true).open(path)?;Ok(())}/// Repair only the settings files whose permissions may have been carried-/// forward from an older installation. The canonical bytes are captured-/// before any mutation and atomically republished afterward so store.bin-/// inherits the directory's current ACL without risking settings loss.+/// forward from an older installation. `icacls /reset` reapplies the+/// directory's inherited ACL in place, so the canonical bytes never need to+/// be replaced while the old ACL may still deny delete/replace access.#[cfg(windows)]fn normalize_windows_store_permissions(store_path: &Path) -> anyhow::Result<()> {- let canonical = match read_store_file(store_path) {- Ok(bytes) => Some(bytes),- Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,- Err(error) => return Err(error.into()),- };+ reset_windows_store_file_permissions(store_path)?;for path in [- store_path.to_path_buf(),store_path.with_extension(LAST_GOOD_SUFFIX),store_path.with_extension(LAST_GOOD_PREV_SUFFIX),] {- reset_windows_store_file_permissions(&path)?;+ if let Err(error) = reset_windows_store_file_permissions(&path) {+ // Snapshots are recovery aids. A stale sidecar ACL must not stop+ // an otherwise readable and writable canonical settings store.+ tracing::warn!(+ "failed to repair settings recovery sidecar permissions at {}: {}",+ path.display(),+ error+ );+ }}- if let Some(bytes) = canonical {- durable_write(store_path, &bytes)?;- }Ok(())}@@ -288,10 +309,7 @@ pub(crate) fn durable_write(path: &Path, bytes: &[u8]) -> std::io::Result<()> {f.write_all(bytes)?;f.sync_all()?; // contents + metadata to stable storage before the rename}- if let Err(e) = retry_windows_store_io(|| std::fs::rename(&tmp, path)) {- let _ = std::fs::remove_file(&tmp);- return Err(e);- }+ replace_store_temp(&tmp, path)?;// fsync the directory so the rename itself survives a crash. Best-effort:// not all platforms allow opening a dir for sync (Windows), and rename is// already atomic there via MoveFileEx.@@ -304,6 +322,34 @@ pub(crate) fn durable_write(path: &Path, bytes: &[u8]) -> std::io::Result<()> {Ok(())}+#[cfg(not(windows))]+fn replace_store_temp(tmp: &Path, path: &Path) -> std::io::Result<()> {+ std::fs::rename(tmp, path)+}++#[cfg(windows)]+fn replace_store_temp(tmp: &Path, path: &Path) -> std::io::Result<()> {+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);+ let mut delay = std::time::Duration::from_millis(1);+ let mut temporary = tempfile::TempPath::try_from_path(tmp)?;++ loop {+ match temporary.persist(path) {+ Ok(()) => return Ok(()),+ Err(error) => {+ if error.error.kind() != std::io::ErrorKind::PermissionDenied+ || std::time::Instant::now() >= deadline+ {+ return Err(error.error);+ }+ temporary = error.path;+ std::thread::sleep(delay);+ delay = (delay * 2).min(std::time::Duration::from_millis(50));+ }+ }+ }+}+/// Like [`durable_write`], but skip the temp/fsync/rename if `path` already/// holds exactly `bytes`. Identical re-encrypt IPC used to fsync a 262KB/// store.bin onto itself on the AppKit main thread (~100% of a core).@@ -418,7 +464,7 @@ fn restore_snapshot_over(store_path: &Path, why: &str) -> bool {pre_restore_note = format!("pre-restore copy at {}", pre_restore.display());}- if let Err(e) = durable_write(store_path, &data) {+ if let Err(e) = retry_windows_store_io(|| durable_write(store_path, &data)) {tracing::error!("settings recovery: failed to restore {} from {}: {}",store_path.display(),@@ -760,6 +806,39 @@ fn save_store_to_disk<R: tauri::Runtime>(retry_windows_store_io(|| store.save()).map_err(|e| e.to_string())}+fn save_store_with_permission_repair(+ app: &AppHandle,+ store: &tauri_plugin_store::Store<tauri::Wry>,+) -> Result<(), String> {+ match save_store_to_disk(store) {+ Ok(()) => Ok(()),+ Err(first_error) => {+ #[cfg(not(windows))]+ {+ let _ = app;+ return Err(first_error);+ }++ #[cfg(windows)]+ {+ let store_path = get_base_dir(app, None)+ .map_err(|error| error.to_string())?+ .join("store.bin");+ tracing::warn!(+ "settings save failed; repairing Windows store permissions and retrying: {}",+ first_error+ );+ normalize_windows_store_permissions(&store_path).map_err(|repair_error| {+ format!(+ "settings save failed ({first_error}); permission repair also failed: {repair_error}"+ )+ })?;+ save_store_to_disk(store)+ }+ }+ }+}+/// Flush the process-shared store to durable, encrypted storage before a/// restart. Native restart surfaces (for example the tray) cannot drain a/// webview-local settings queue, but every frontend and backend store handle@@ -1186,7 +1265,7 @@ impl OnboardingStore {let mut onboarding = Self::get(app)?.unwrap_or_default();update(&mut onboarding);store.set("onboarding", json!(onboarding));- save_store_to_disk(store.as_ref())?;+ save_store_with_permission_repair(app, store.as_ref())?;reencrypt_store_file(app);Ok(())}@@ -1197,7 +1276,7 @@ impl OnboardingStore {};store.set("onboarding", json!(self));- save_store_to_disk(store.as_ref())?;+ save_store_with_permission_repair(app, store.as_ref())?;reencrypt_store_file(app);Ok(())}@@ -2483,7 +2562,7 @@ impl SettingsStore {};store.set("settings", json!(self));- save_store_to_disk(store.as_ref())?;+ save_store_with_permission_repair(app, store.as_ref())?;reencrypt_store_file(app);Ok(())}