Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(desktop): run factory reset off the main thread (#9461)
Akarshan Biswas913e7db74bea
diff --git a/src-tauri/src/core/app/settings_store.rs b/src-tauri/src/core/app/settings_store.rsindex 3a4adbfea..cd8aac9a9 100644--- a/src-tauri/src/core/app/settings_store.rs+++ b/src-tauri/src/core/app/settings_store.rs@@ -37,12 +37,16 @@ struct SettingsMap {/// Keys changed since the last flush, for the dev-build write log. Only/// populated under `debug_assertions`.pending_keys: BTreeSet<String>,+ /// Set once a factory reset has deleted `settings.json`. From then on the+ /// store refuses writes, so neither the webview nor the exit flush can+ /// recreate the file before the app restarts.+ discarded: bool,}impl SettingsMap {/// Returns true if the value changed (i.e. a flush is warranted).fn set(&mut self, key: String, value: String) -> bool {- if self.map.get(&key).is_some_and(|v| *v == value) {+ if self.discarded || self.map.get(&key).is_some_and(|v| *v == value) {return false;}#[cfg(debug_assertions)]@@ -53,7 +57,7 @@ impl SettingsMap {/// Returns true if a key was actually removed.fn remove(&mut self, key: &str) -> bool {- if self.map.remove(key).is_none() {+ if self.discarded || self.map.remove(key).is_none() {return false;}#[cfg(debug_assertions)]@@ -61,6 +65,15 @@ impl SettingsMap {true}+ /// Drop everything, pending writes included, and refuse further changes.+ fn discard(&mut self) {+ self.map.clear();+ self.pending_keys.clear();+ self.dirty = false;+ self.flush_at = None;+ self.discarded = true;+ }+fn mark_dirty(&mut self) {self.dirty = true;self.flush_at = Some(Instant::now() + FLUSH_DEBOUNCE);@@ -95,6 +108,11 @@ type Store = (Mutex<SettingsMap>, Condvar);static STORE: OnceLock<Store> = OnceLock::new();+/// Serializes disk writes against [`discard_settings`]. Writers drop the map+/// lock during I/O so `settings_set` never waits on the disk; this lock is+/// what lets a discard wait out a write already in flight.+static WRITE: Mutex<()> = Mutex::new(());+fn settings_file_path() -> PathBuf {resolve_jan_data_folder().join(CONFIGURATION_FILE_NAME)}@@ -125,6 +143,7 @@ fn store() -> &'static Store {dirty: false,flush_at: None,pending_keys: BTreeSet::new(),+ discarded: false,};std::thread::Builder::new().name("settings-flush".into())@@ -135,7 +154,32 @@ fn store() -> &'static Store {}fn lock(store: &Store) -> std::sync::MutexGuard<'_, SettingsMap> {- store.0.lock().unwrap_or_else(|e| e.into_inner())+ lock_map(&store.0)+}++fn lock_map(map: &Mutex<SettingsMap>) -> std::sync::MutexGuard<'_, SettingsMap> {+ map.lock().unwrap_or_else(|e| e.into_inner())+}++/// Write a flush snapshot to disk unless the store was discarded after the+/// snapshot was taken. Returns whether it wrote. A failed write re-arms the+/// flush so it is retried, except after a discard, where a retry would write+/// an empty `{}` file in place of the deleted one.+fn persist(+ state: &Mutex<SettingsMap>,+ path: &PathBuf,+ snapshot: &BTreeMap<String, String>,+) -> Result<bool, String> {+ let _write = WRITE.lock().unwrap_or_else(|e| e.into_inner());+ if lock_map(state).discarded {+ return Ok(false);+ }+ write_map_atomic(path, snapshot).map(|()| true).inspect_err(|_| {+ let mut guard = lock_map(state);+ if !guard.discarded {+ guard.dirty = true;+ }+ })}/// Background thread: waits for dirty state, honors the debounce deadline@@ -162,12 +206,10 @@ fn flush_loop() {}let (snapshot, keys) = guard.take_flush_batch();drop(guard);- if let Err(e) = write_map_atomic(&settings_file_path(), &snapshot) {- log::warn!("settings flush failed: {}", e);- // Re-arm so a later write (or exit flush) retries.- lock(store).dirty = true;- } else {- log_flushed_keys(&keys);+ match persist(&store.0, &settings_file_path(), &snapshot) {+ Ok(true) => log_flushed_keys(&keys),+ Ok(false) => {}+ Err(e) => log::warn!("settings flush failed: {}", e),}}}@@ -183,14 +225,24 @@ pub fn flush_settings() {}let (snapshot, keys) = guard.take_flush_batch();drop(guard);- if let Err(e) = write_map_atomic(&settings_file_path(), &snapshot) {- log::warn!("settings exit flush failed: {}", e);- lock(store).dirty = true;- } else {- log_flushed_keys(&keys);+ match persist(&store.0, &settings_file_path(), &snapshot) {+ Ok(true) => log_flushed_keys(&keys),+ Ok(false) => {}+ Err(e) => log::warn!("settings exit flush failed: {}", e),}}+/// Forget the in-memory settings and stop persisting them for the rest of+/// this process. Factory reset calls this after deleting `settings.json`;+/// without it a pending debounced write or the exit flush would write the+/// pre-reset settings straight back.+pub fn discard_settings() {+ let store = store();+ // Wait out a write already in flight; any later one sees `discarded`.+ let _write = WRITE.lock().unwrap_or_else(|e| e.into_inner());+ lock(store).discard();+}+#[tauri::command]pub fn settings_get(key: String) -> Option<String> {let store = store();@@ -229,6 +281,7 @@ mod tests {dirty: false,flush_at: None,pending_keys: BTreeSet::new(),+ discarded: false,}}@@ -275,6 +328,41 @@ mod tests {assert_eq!(keys, vec!["a".to_string(), "b".to_string()]);}+ #[test]+ fn discard_empties_the_map_and_ignores_later_writes() {+ let mut m = new_map();+ m.set("a".into(), "1".into());+ m.mark_dirty();+ m.discard();+ assert!(m.map.is_empty());+ assert!(!m.dirty);+ assert!(m.flush_at.is_none());+ assert!(m.pending_keys.is_empty());+ // A webview write racing the factory-reset restart must not bring a+ // wiped settings.json back.+ assert!(!m.set("b".into(), "2".into()));+ assert!(!m.remove("a"));+ assert!(m.map.is_empty());+ }++ #[test]+ fn persist_skips_the_write_once_discarded() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("settings.json");+ let mut map = BTreeMap::new();+ map.insert("theme".to_string(), "\"dark\"".to_string());+ let state = Mutex::new(new_map());++ assert_eq!(persist(&state, &path, &map), Ok(true));+ assert!(path.is_file());++ // A flush that snapshotted before the reset must not recreate the file.+ fs::remove_file(&path).unwrap();+ state.lock().unwrap().discard();+ assert_eq!(persist(&state, &path, &map), Ok(false));+ assert!(!path.exists());+ }+#[test]fn set_preserves_other_keys() {let mut m = new_map();diff --git a/src-tauri/src/core/setup.rs b/src-tauri/src/core/setup.rsindex 44ed324f1..d8a713d1b 100644--- a/src-tauri/src/core/setup.rs+++ b/src-tauri/src/core/setup.rs@@ -392,24 +392,14 @@ pub fn setup_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<TrayIcon<R>>button_state: MouseButtonState::Up,..} => {- // let's show and focus the main window when the tray is clicked- let app = tray.app_handle();- if let Some(window) = app.get_webview_window("main") {- let _ = window.unminimize();- let _ = window.show();- let _ = window.set_focus();- }+ crate::core::system::commands::show_main_window(tray.app_handle());}_ => {log::debug!("unhandled event {event:?}");}}).on_menu_event(|app, event| match event.id.as_ref() {- "open" => {- let window = app.get_webview_window("main").unwrap();- window.show().unwrap();- window.set_focus().unwrap();- }+ "open" => crate::core::system::commands::show_main_window(app),"quit" => {app.exit(0);}diff --git a/src-tauri/src/core/system/commands.rs b/src-tauri/src/core/system/commands.rsindex 70ac972f6..10af6c4d5 100644--- a/src-tauri/src/core/system/commands.rs+++ b/src-tauri/src/core/system/commands.rs@@ -20,60 +20,171 @@ fn is_safe_to_delete(path: &std::path::Path) -> bool {count >= 3}-fn remove_dir(data_folder: &std::path::Path, name: &str) {- let path = data_folder.join(name);- if path.is_dir() {- log::info!("Removing directory: {}", path.display());- if let Err(e) = fs::remove_dir_all(&path) {- log::warn!("Failed to remove {}: {e}", path.display());- }+/// Name prefix of the folder a reset moves its targets into. The sweep only+/// ever deletes a recorded path whose name carries it.+const RESET_TRASH_PREFIX: &str = ".reset-trash-";++/// Records the trash folder awaiting deletion. Lives in the app config dir,+/// which survives the reset, so a trash folder under a custom data folder is+/// still found after the reset points the config back at the default.+const PENDING_TRASH_FILE: &str = ".pending-reset-trash";++/// Data-folder entries a reset with these choices removes.+fn reset_targets(keep_app_data: bool, keep_models_and_configs: bool) -> Vec<&'static str> {+ // Extensions, logs and caches go on every reset.+ let mut targets = JAN_DATA_DIRS_COMMON.to_vec();+ if !keep_app_data {+ targets.extend(JAN_DATA_DIRS_CONVERSATIONS);+ }+ if !keep_models_and_configs {+ targets.extend(JAN_DATA_DIRS_MODELS);+ targets.extend(JAN_DATA_FILES_CONFIGS);+ }+ // The settings files span every category; only a full wipe drops them.+ if !keep_app_data && !keep_models_and_configs {+ targets.extend(JAN_DATA_FILES_SETTINGS);}+ targets}-fn remove_file(data_folder: &std::path::Path, name: &str) {- let path = data_folder.join(name);- if path.is_file() {- log::info!("Removing file: {}", path.display());- if let Err(e) = fs::remove_file(&path) {- log::warn!("Failed to remove {}: {e}", path.display());+/// Move each target out of the data folder into `trash`.+///+/// A rename within one folder is atomic and instant, so the reset is decided+/// in milliseconds and an exit that cannot be refused (a native macOS quit+/// skips `ExitRequested`) leaves the data either untouched or fully staged,+/// never half-deleted. The slow deletion of `trash` happens later.+fn stage_for_deletion(data_folder: &std::path::Path, targets: &[&str], trash: &std::path::Path) {+ for name in targets {+ let path = data_folder.join(name);+ if fs::symlink_metadata(&path).is_err() {+ continue;+ }+ if let Err(e) = fs::create_dir_all(trash) {+ log::warn!("Failed to create {}: {e}", trash.display());+ }+ log::info!("Staging for deletion: {}", path.display());+ let dest = trash.join(name);+ if let Err(e) = rename_with_retry(&path, &dest) {+ log::warn!("Failed to move {}: {e}; staging its contents", path.display());+ let left = stage_contents(&path, &dest);+ if left > 0 {+ log::warn!("{left} locked entries stay in {}", path.display());+ }}}}-/// Delete conversations and user data (threads, assistants).-fn delete_conversations(data_folder: &std::path::Path) {- log::info!("Deleting conversations (threads, assistants)");- for dir in JAN_DATA_DIRS_CONVERSATIONS {- remove_dir(data_folder, dir);+/// Rename, retrying briefly: a lock held by a process the reset just stopped,+/// an indexer or antivirus is usually released within moments.+fn rename_with_retry(from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> {+ const ATTEMPTS: u32 = 3;+ let mut attempt = 1;+ loop {+ match fs::rename(from, to) {+ Err(_) if attempt < ATTEMPTS => {+ std::thread::sleep(std::time::Duration::from_millis(250));+ attempt += 1;+ }+ result => return result,+ }}}-/// Delete downloaded models, engine binaries, and configuration files-/// (engine settings, MCP config, etc.).-fn delete_models_and_configs(data_folder: &std::path::Path) {- log::info!("Deleting models, engines, and configurations");- for dir in JAN_DATA_DIRS_MODELS {- remove_dir(data_folder, dir);+/// Move what can be moved from `from` into `to`, one entry at a time, and+/// return how many entries had to stay. Windows refuses to move a folder with+/// a file open anywhere in it, and deleting it in place stops at the first+/// such file, so this leaves behind only the files that are actually locked.+fn stage_contents(from: &std::path::Path, to: &std::path::Path) -> usize {+ let is_dir = fs::symlink_metadata(from).is_ok_and(|m| m.is_dir());+ if !is_dir {+ if let Err(e) = fs::remove_file(from) {+ log::warn!("Failed to remove {}: {e}", from.display());+ return 1;+ }+ return 0;}- for file in JAN_DATA_FILES_CONFIGS {- remove_file(data_folder, file);+ let entries = match fs::create_dir_all(to).and_then(|()| fs::read_dir(from)) {+ Ok(entries) => entries,+ Err(e) => {+ log::warn!("Failed to stage {}: {e}", from.display());+ return 1;+ }+ };+ let mut left = 0;+ for entry in entries.flatten() {+ let src = entry.path();+ let dest = to.join(entry.file_name());+ if fs::rename(&src, &dest).is_err() {+ left += stage_contents(&src, &dest);+ }}+ if left == 0 {+ if let Err(e) = fs::remove_dir(from) {+ log::warn!("Failed to remove {}: {e}", from.display());+ left = 1;+ }+ }+ left}-/// Delete extensions, logs, caches — always cleaned during any reset.-fn delete_common_data(data_folder: &std::path::Path) {- log::info!("Deleting common data (extensions, logs, caches)");- for dir in JAN_DATA_DIRS_COMMON {- remove_dir(data_folder, dir);+fn remove_path(path: &std::path::Path) -> std::io::Result<()> {+ let removed = if path.is_dir() {+ fs::remove_dir_all(path)+ } else {+ fs::remove_file(path)+ };+ if let Err(e) = &removed {+ log::warn!("Failed to remove {}: {e}", path.display());}+ removed}-/// Delete cross-category settings (store.json) — only during a full wipe-/// when the user is not keeping any data.-fn delete_settings(data_folder: &std::path::Path) {- log::info!("Deleting cross-category settings (store.json)");- for file in JAN_DATA_FILES_SETTINGS {- remove_file(data_folder, file);+fn pending_trash_record<R: Runtime>(app_handle: &tauri::AppHandle<R>) -> Option<PathBuf> {+ get_configuration_file_path(app_handle.clone())+ .parent()+ .map(|dir| dir.join(PENDING_TRASH_FILE))+}++fn record_pending_trash(record: &std::path::Path, trash: &std::path::Path) -> std::io::Result<()> {+ fs::write(record, trash.to_string_lossy().as_bytes())+}++/// Delete the trash folder a factory reset left behind, then forget it.+fn sweep_pending_trash(record: &std::path::Path) {+ let Ok(recorded) = fs::read_to_string(record) else {+ return;+ };+ let trash = PathBuf::from(recorded.trim());+ let is_reset_trash = trash+ .file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with(RESET_TRASH_PREFIX));+ if is_reset_trash && is_safe_to_delete(&trash) {+ if trash.exists() {+ log::info!("Deleting factory reset leftovers: {}", trash.display());+ // A partial failure (a file locked on Windows) keeps the record,+ // so the next start retries instead of losing the folder for good.+ if remove_path(&trash).is_err() && trash.exists() {+ return;+ }+ }+ } else {+ log::warn!("Ignoring unexpected reset trash path: {}", trash.display());+ }+ // A reset during the sweep records its own trash; leave that record.+ if fs::read_to_string(record).ok().as_deref() != Some(recorded.as_str()) {+ return;+ }+ if let Err(e) = fs::remove_file(record) {+ log::warn!("Failed to remove {}: {e}", record.display());+ }+}++/// Finish a factory reset's deletion on the first start after it. Blocking:+/// run it off the main thread.+pub fn sweep_reset_trash<R: Runtime>(app_handle: &tauri::AppHandle<R>) {+ if let Some(record) = pending_trash_record(app_handle) {+ sweep_pending_trash(&record);}}@@ -222,28 +333,91 @@ fn write_env_to_shell(env_file_path: &str, env_vars: &[(String, String)]) -> ResOk(())}+/// Set by the first `factory_reset` and never cleared: the reset ends in a+/// restart, so a second call (double click, retry from the hidden webview)+/// must not start another teardown that interleaves with it.+static FACTORY_RESET_STARTED: std::sync::atomic::AtomicBool =+ std::sync::atomic::AtomicBool::new(false);++/// Whether a factory reset is wiping data. The event loop stays live during+/// the wipe, so the app lifecycle handlers use this to keep the hidden+/// windows hidden and the process alive until the reset restarts it.+pub fn factory_reset_in_progress() -> bool {+ FACTORY_RESET_STARTED.load(std::sync::atomic::Ordering::SeqCst)+}++/// Bring the main window back, unless a factory reset hid it to wipe data.+/// Every user-facing "show Jan" path (tray click, tray menu, macOS dock+/// reopen) goes through here so none of them hands back a live webview over a+/// half-deleted data folder.+pub fn show_main_window<R: Runtime>(app: &AppHandle<R>) {+ if factory_reset_in_progress() {+ log::info!("Not showing the window while a factory reset is running");+ return;+ }+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.unminimize();+ let _ = window.show();+ let _ = window.set_focus();+ }+}++/// Whether an exit request must be refused because a reset is running, so a+/// quit during the teardown cannot cut the reset short. The reset's own+/// `restart()` arrives as `RESTART_EXIT_CODE` and must go through. Not every+/// exit reaches this check (a native macOS quit does not); the staged+/// deletion is what keeps those from leaving a half-wiped folder.+pub fn exit_blocked_by_reset(reset_in_progress: bool, code: Option<i32>) -> bool {+ reset_in_progress && code != Some(tauri::RESTART_EXIT_CODE)+}++/// Wipe the selected data categories and restart the app.+///+/// Async so it runs on the async runtime: as a sync command it ran on the main+/// thread, and the teardown below (MCP servers, engine worker, `remove_dir_all`+/// of the models folder) froze the event loop for up to ~30s with the window+/// stuck on screen.#[tauri::command]-pub fn factory_reset<R: Runtime>(+pub async fn factory_reset<R: Runtime>(app_handle: tauri::AppHandle<R>,state: State<'_, AppState>,keep_app_data: Option<bool>,keep_models_and_configs: Option<bool>,clear_web_data: Option<bool>,-) {+) -> Result<(), String> {let keep_app_data = keep_app_data.unwrap_or(false);let keep_models_and_configs = keep_models_and_configs.unwrap_or(false);let clear_web_data = clear_web_data.unwrap_or(false);+ // Refuse before touching anything, so a refused reset leaves the app+ // running and visible and the frontend sees the error.+ let data_folder = get_jan_data_folder_path(app_handle.clone());+ if data_folder.exists() && !is_safe_to_delete(&data_folder) {+ log::error!(+ "Refusing factory reset: path is too close to filesystem root: {}",+ data_folder.display()+ );+ return Err(format!(+ "Refusing to reset {}: too close to the filesystem root",+ data_folder.display()+ ));+ }+ if FACTORY_RESET_STARTED.swap(true, std::sync::atomic::Ordering::SeqCst) {+ log::warn!("Factory reset already in progress; ignoring repeat request");+ return Ok(());+ }++ // Hide rather than close: now that the event loop keeps running, closing+ // the last window would start a normal app exit in the middle of the wipe.#[cfg(not(any(target_os = "ios", target_os = "android")))]{let windows = app_handle.webview_windows();for (label, window) in windows.iter() {- window.close().unwrap_or_else(|_| {- log::warn!("Failed to close window: {label:?}");+ window.hide().unwrap_or_else(|_| {+ log::warn!("Failed to hide window: {label:?}");});}}- let data_folder = get_jan_data_folder_path(app_handle.clone());log::info!("Factory reset (keep_app_data={}, keep_models_and_configs={}, clear_web_data={}), data folder: {:?}",keep_app_data,@@ -252,79 +426,86 @@ pub fn factory_reset<R: Runtime>(data_folder);- tauri::async_runtime::block_on(async {- let _ =- stop_mcp_servers_with_context(&app_handle, &state, ShutdownContext::FactoryReset).await;+ let _ = stop_mcp_servers_with_context(&app_handle, &state, ShutdownContext::FactoryReset).await;- {- let mut active_servers = state.mcp_active_servers.lock().await;- active_servers.clear();- }+ {+ let mut active_servers = state.mcp_active_servers.lock().await;+ active_servers.clear();+ }- use crate::core::mcp::lockfile::cleanup_own_locks;- if let Err(e) = cleanup_own_locks(&app_handle) {- log::warn!("Failed to cleanup lock files: {}", e);+ use crate::core::mcp::lockfile::cleanup_own_locks;+ if let Err(e) = cleanup_own_locks(&app_handle) {+ log::warn!("Failed to cleanup lock files: {}", e);+ }+ let _ = cleanup_llama_processes(app_handle.clone()).await;++ let full_wipe = !keep_app_data && !keep_models_and_configs;+ if data_folder.exists() {+ // Discard before moving: the in-memory copy would otherwise be+ // flushed back by a pending debounced write or the exit-time flush.+ if full_wipe {+ crate::core::app::settings_store::discard_settings();}- let _ = cleanup_llama_processes(app_handle.clone()).await;-- if data_folder.exists() {- if !is_safe_to_delete(&data_folder) {- log::error!(- "Refusing factory reset: path is too close to filesystem root: {}",- data_folder.display()- );- return;- }-- // Always clean common data (extensions, logs, caches)- delete_common_data(&data_folder);-- // Delete conversations (threads, assistants) unless user chose to keep it- if !keep_app_data {- delete_conversations(&data_folder);- }-- // Delete models and configs unless user chose to keep them- if !keep_models_and_configs {- delete_models_and_configs(&data_folder);- }-- // store.json spans all categories; only wipe it when nothing is kept- if !keep_app_data && !keep_models_and_configs {- delete_settings(&data_folder);+ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis())+ .unwrap_or(0);+ let trash = data_folder.join(format!("{RESET_TRASH_PREFIX}{stamp}"));+ // Record first, so a trash folder is never left that no sweep knows of.+ let recorded = pending_trash_record(&app_handle)+ .map(|record| record_pending_trash(&record, &trash))+ .transpose();+ let targets = reset_targets(keep_app_data, keep_models_and_configs);+ let folder = data_folder.clone();+ let staged = tauri::async_runtime::spawn_blocking(move || {+ stage_for_deletion(&folder, &targets, &trash);+ // Without a record the next start cannot find the trash, so it+ // has to go now, slow as that is.+ if !matches!(recorded, Ok(Some(()))) {+ log::warn!("Could not record reset trash; deleting it now");+ if trash.exists() {+ let _ = remove_path(&trash);+ }}+ })+ .await;+ if let Err(e) = staged {+ log::error!("Factory reset data deletion failed: {e}");}+ }- // Reset app configuration to defaults unless user chose to keep configs- if !keep_models_and_configs {- let default_config = AppConfiguration {- data_folder: default_data_folder_path(app_handle.clone()),- };- let _ = update_app_configuration(app_handle.clone(), default_config);- }+ // Reset app configuration to defaults unless user chose to keep configs+ if !keep_models_and_configs {+ let default_config = AppConfiguration {+ data_folder: default_data_folder_path(app_handle.clone()),+ };+ let _ = update_app_configuration(app_handle.clone(), default_config);+ }- // Persisted UI state (model-provider, setup flag) lives in webview- // localStorage, not the data folder. Renderer-side removal races the- // restart flush, and the on-disk localStorage location is- // platform-specific (esp. macOS WKWebView), so instead drop a sentinel- // that the frontend consumes on next startup to clear localStorage via- // the webview API before stores hydrate. File-level profile deletion- // (Linux cookies/cache) stays as a best-effort supplement.- let full_wipe = !keep_app_data && !keep_models_and_configs;- if !keep_app_data || !keep_models_and_configs || clear_web_data {- write_webdata_reset_sentinel(- &app_handle,- keep_app_data,- keep_models_and_configs,- clear_web_data,- );- }- if clear_web_data || full_wipe {- clear_webview_profile(&app_handle, &data_folder);- }+ // Persisted UI state (model-provider, setup flag) lives in webview+ // localStorage, not the data folder. Renderer-side removal races the+ // restart flush, and the on-disk localStorage location is+ // platform-specific (esp. macOS WKWebView), so instead drop a sentinel+ // that the frontend consumes on next startup to clear localStorage via+ // the webview API before stores hydrate. File-level profile deletion+ // (Linux cookies/cache) stays as a best-effort supplement.+ if !keep_app_data || !keep_models_and_configs || clear_web_data {+ write_webdata_reset_sentinel(+ &app_handle,+ keep_app_data,+ keep_models_and_configs,+ clear_web_data,+ );+ }+ if clear_web_data || full_wipe {+ clear_webview_profile(&app_handle, &data_folder);+ }- app_handle.restart();- });+ // The staged data is deleted by the next start (`sweep_reset_trash`).+ // Not `restart()`: off the main thread it parks this runtime worker+ // forever while the exit handler blocks on the same runtime for cleanup.+ app_handle.request_restart();+ Ok(())}#[tauri::command]@@ -679,6 +860,15 @@ mod tests {use std::fs;use tempfile::tempdir;+ #[test]+ fn a_running_reset_blocks_exits_but_not_its_own_restart() {+ assert!(exit_blocked_by_reset(true, Some(0)));+ assert!(exit_blocked_by_reset(true, None));+ assert!(!exit_blocked_by_reset(true, Some(tauri::RESTART_EXIT_CODE)));+ assert!(!exit_blocked_by_reset(false, Some(0)));+ assert!(!exit_blocked_by_reset(false, None));+ }+fn create_all_data(dir: &std::path::Path) {for subdir in JAN_DATA_SUBDIRS {fs::create_dir_all(dir.join(subdir)).unwrap();@@ -697,114 +887,194 @@ mod tests {names.iter().all(|n| dir.join(n).exists())}+ /// Stage a reset with these choices into a trash folder under `d`.+ fn stage(d: &std::path::Path, keep_app_data: bool, keep_models: bool) -> PathBuf {+ let trash = d.join(format!("{RESET_TRASH_PREFIX}test"));+ stage_for_deletion(d, &reset_targets(keep_app_data, keep_models), &trash);+ trash+ }++ #[test]+ fn keeping_both_categories_stages_only_common_data() {+ let tmp = tempdir().unwrap();+ let d = tmp.path();+ create_all_data(d);++ let trash = stage(d, true, true);++ assert!(!exists_any(d, JAN_DATA_DIRS_COMMON));+ assert!(exists_all(&trash, JAN_DATA_DIRS_COMMON));+ assert!(exists_all(d, JAN_DATA_DIRS_CONVERSATIONS));+ assert!(exists_all(d, JAN_DATA_DIRS_MODELS));+ assert!(exists_all(d, JAN_DATA_FILES));+ }+#[test]- fn test_delete_conversations_only_removes_conversation_dirs() {+ fn keeping_models_stages_conversations_but_not_settings() {let tmp = tempdir().unwrap();let d = tmp.path();create_all_data(d);- delete_conversations(d);+ stage(d, false, true);assert!(!exists_any(d, JAN_DATA_DIRS_CONVERSATIONS));assert!(exists_all(d, JAN_DATA_DIRS_MODELS));- assert!(exists_all(d, JAN_DATA_DIRS_COMMON));- assert!(d.join("settings.json").exists());- assert!(d.join("mcp_config.json").exists());+ assert!(exists_all(d, JAN_DATA_FILES_CONFIGS));+ assert!(exists_all(d, JAN_DATA_FILES_SETTINGS));}#[test]- fn test_delete_models_and_configs_only_removes_model_dirs_and_config_files() {+ fn keeping_app_data_stages_models_and_configs_but_not_settings() {let tmp = tempdir().unwrap();let d = tmp.path();create_all_data(d);- delete_models_and_configs(d);+ stage(d, true, false);assert!(!exists_any(d, JAN_DATA_DIRS_MODELS));assert!(!exists_any(d, JAN_DATA_FILES_CONFIGS));assert!(exists_all(d, JAN_DATA_DIRS_CONVERSATIONS));- assert!(exists_all(d, JAN_DATA_DIRS_COMMON));- assert!(d.join("settings.json").exists());+ assert!(exists_all(d, JAN_DATA_FILES_SETTINGS));}#[test]- fn test_delete_common_data_only_removes_common_dirs() {+ fn full_wipe_stages_every_known_entry() {let tmp = tempdir().unwrap();let d = tmp.path();create_all_data(d);- delete_common_data(d);+ let trash = stage(d, false, false);- assert!(!exists_any(d, JAN_DATA_DIRS_COMMON));- assert!(exists_all(d, JAN_DATA_DIRS_CONVERSATIONS));- assert!(exists_all(d, JAN_DATA_DIRS_MODELS));- assert!(d.join("settings.json").exists());- assert!(d.join("mcp_config.json").exists());+ assert!(!exists_any(d, JAN_DATA_SUBDIRS));+ assert!(!exists_any(d, JAN_DATA_FILES));+ assert!(exists_all(&trash, JAN_DATA_SUBDIRS));+ assert!(exists_all(&trash, JAN_DATA_FILES));}#[test]- fn test_delete_settings_only_removes_settings_json() {+ fn staging_with_nothing_to_move_creates_no_trash() {let tmp = tempdir().unwrap();- let d = tmp.path();- create_all_data(d);+ let trash = stage(tmp.path(), false, false);+ assert!(!trash.exists());+ }- delete_settings(d);+ #[test]+ fn sweep_deletes_recorded_trash_and_clears_the_record() {+ let tmp = tempdir().unwrap();+ let d = tmp.path().join("data");+ fs::create_dir_all(&d).unwrap();+ create_all_data(&d);+ let record = tmp.path().join(PENDING_TRASH_FILE);+ let trash = d.join(format!("{RESET_TRASH_PREFIX}1"));+ record_pending_trash(&record, &trash).unwrap();+ stage_for_deletion(&d, &reset_targets(false, false), &trash);++ sweep_pending_trash(&record);++ assert!(!trash.exists());+ assert!(!record.exists());+ }- assert!(!d.join("settings.json").exists());- assert!(exists_all(d, JAN_DATA_DIRS_CONVERSATIONS));- assert!(exists_all(d, JAN_DATA_DIRS_MODELS));- assert!(exists_all(d, JAN_DATA_DIRS_COMMON));- assert!(d.join("mcp_config.json").exists());+ /// A read-only directory holding one file: its entries can be neither moved+ /// nor removed, which stands in for a file held open on Windows. `None`+ /// when permissions are not enforced (running as root).+ #[cfg(unix)]+ fn locked_dir(parent: &std::path::Path) -> Option<PathBuf> {+ use std::os::unix::fs::PermissionsExt;+ let locked = parent.join("locked");+ fs::create_dir_all(&locked).unwrap();+ fs::write(locked.join("held.bin"), "data").unwrap();+ fs::set_permissions(&locked, fs::Permissions::from_mode(0o555)).unwrap();+ if fs::write(locked.join("probe"), "").is_ok() {+ unlock(&locked);+ return None;+ }+ Some(locked)+ }++ #[cfg(unix)]+ fn unlock(dir: &std::path::Path) {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(dir, fs::Permissions::from_mode(0o755)).unwrap();}+ #[cfg(unix)]#[test]- fn test_settings_json_survives_when_keeping_any_category() {- // Simulate: keep_app_data=true, keep_models_and_configs=false+ fn staging_contents_leaves_only_the_locked_entries() {let tmp = tempdir().unwrap();- let d = tmp.path();- create_all_data(d);+ let models = tmp.path().join("llamacpp");+ fs::create_dir_all(models.join("free")).unwrap();+ fs::write(models.join("free").join("a.gguf"), "data").unwrap();+ fs::write(models.join("b.gguf"), "data").unwrap();+ let Some(locked) = locked_dir(&models) else {+ return;+ };+ let dest = tmp.path().join("trash").join("llamacpp");- delete_common_data(d);- delete_models_and_configs(d);- // settings.json should NOT be deleted because keep_app_data=true- assert!(d.join("settings.json").exists());+ let left = stage_contents(&models, &dest);+ unlock(&locked);- // Simulate: keep_app_data=false, keep_models_and_configs=true- let tmp2 = tempdir().unwrap();- let d2 = tmp2.path();- create_all_data(d2);+ assert_eq!(left, 1);+ assert!(dest.join("free").join("a.gguf").exists());+ assert!(dest.join("b.gguf").exists());+ assert!(!models.join("free").exists());+ assert!(!models.join("b.gguf").exists());+ assert!(locked.join("held.bin").exists());+ }- delete_common_data(d2);- delete_conversations(d2);- // settings.json should NOT be deleted because keep_models_and_configs=true- assert!(d2.join("settings.json").exists());+ #[test]+ fn staging_contents_removes_the_emptied_folder() {+ let tmp = tempdir().unwrap();+ let models = tmp.path().join("llamacpp");+ fs::create_dir_all(models.join("free")).unwrap();+ fs::write(models.join("free").join("a.gguf"), "data").unwrap();+ let dest = tmp.path().join("trash").join("llamacpp");++ assert_eq!(stage_contents(&models, &dest), 0);+ assert!(!models.exists());+ assert!(dest.join("free").join("a.gguf").exists());}+ #[cfg(unix)]#[test]- fn test_full_wipe_deletes_settings_json() {+ fn sweep_keeps_the_record_until_the_trash_is_gone() {let tmp = tempdir().unwrap();- let d = tmp.path();- create_all_data(d);+ let record = tmp.path().join(PENDING_TRASH_FILE);+ let trash = tmp.path().join("data").join(format!("{RESET_TRASH_PREFIX}1"));+ fs::create_dir_all(&trash).unwrap();+ let Some(locked) = locked_dir(&trash) else {+ return;+ };+ record_pending_trash(&record, &trash).unwrap();- delete_common_data(d);- delete_conversations(d);- delete_models_and_configs(d);- delete_settings(d);+ sweep_pending_trash(&record);+ assert!(trash.exists());+ assert!(record.exists());- assert!(!d.join("settings.json").exists());- assert!(!exists_any(d, JAN_DATA_SUBDIRS));- assert!(!exists_any(d, JAN_DATA_FILES));+ unlock(&locked);+ sweep_pending_trash(&record);+ assert!(!trash.exists());+ assert!(!record.exists());}#[test]- fn test_delete_on_nonexistent_dirs_does_not_panic() {+ fn sweep_never_deletes_a_path_that_is_not_reset_trash() {let tmp = tempdir().unwrap();- let d = tmp.path();- // Nothing created — should not panic- delete_conversations(d);- delete_models_and_configs(d);- delete_common_data(d);- delete_settings(d);+ let keep = tmp.path().join("data").join("threads");+ fs::create_dir_all(&keep).unwrap();+ let record = tmp.path().join(PENDING_TRASH_FILE);+ record_pending_trash(&record, &keep).unwrap();++ sweep_pending_trash(&record);++ assert!(keep.exists());+ assert!(!record.exists());+ }++ #[test]+ fn sweep_without_a_record_is_a_no_op() {+ let tmp = tempdir().unwrap();+ sweep_pending_trash(&tmp.path().join(PENDING_TRASH_FILE));}#[test]diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 952b528d2..0a9b96506 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -373,6 +373,15 @@ pub fn run() {app.handle().plugin(tauri_plugin_updater::Builder::new().build())?;+ // A factory reset only moves data aside and restarts; deleting it,+ // which can take a while for a big models folder, happens here.+ {+ let handle = app.handle().clone();+ tauri::async_runtime::spawn_blocking(move || {+ core::system::commands::sweep_reset_trash(&handle);+ });+ }+// Reap engines a previous Jan left running: the llama-server router of// a 0.8.4 that was updated in place, or an mlx-server whose app was// killed. Neither can be stopped by the version that started it.@@ -507,12 +516,20 @@ pub fn run() {}#[cfg(target_os = "macos")]if let RunEvent::Reopen { .. } = &event {- if let Some(window) = app.get_webview_window("main") {- let _ = window.show();- let _ = window.set_focus();- }+ core::system::commands::show_main_window(app);}if let RunEvent::ExitRequested { api, code, .. } = &event {+ // Quitting mid-reset would drop the reset and its restart; it ends+ // in its own restart. A native macOS quit never gets here, which+ // is why the reset stages its deletion atomically.+ if core::system::commands::exit_blocked_by_reset(+ core::system::commands::factory_reset_in_progress(),+ *code,+ ) {+ log::warn!("Ignoring exit request while a factory reset is running");+ api.prevent_exit();+ return;+ }if SHUTTING_DOWN.load(Ordering::SeqCst) || !is_llamacpp_engine_running(app) {return;}diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex 6ecac28bd..64873a242 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -292,6 +292,7 @@"failedToRelocateDataFolder": "Failed to relocate data folder","couldNotRelocateToRoot": "Cannot relocate data folder to root directory. Please choose another location.","couldNotResetRootDirectory": "Cannot reset data folder when it's set to a root directory. Please delete the data folder manually.",+ "factoryResetFailed": "Factory reset failed","failedToRelocateDataFolderDesc": "Failed to relocate data folder. Please try again.","devVersion": "Development version detected","noUpdateAvailable": "You're running the latest version",diff --git a/web-app/src/routes/settings/__tests__/general.test.tsx b/web-app/src/routes/settings/__tests__/general.test.tsxindex 6e293fe77..bf5bd24b1 100644--- a/web-app/src/routes/settings/__tests__/general.test.tsx+++ b/web-app/src/routes/settings/__tests__/general.test.tsx@@ -183,10 +183,12 @@ vi.mock('@/services/models/default', () => ({})),}))+const mockFactoryReset = vi.hoisted(() => vi.fn())+vi.mock('@/hooks/useServiceHub', () => ({useServiceHub: () => ({app: () => ({- factoryReset: vi.fn(),+ factoryReset: mockFactoryReset,getJanDataFolder: vi.fn().mockResolvedValue('/test/data/folder'),relocateJanDataFolder: vi.fn(),}),@@ -439,6 +441,26 @@ describe('General Settings Route', () => {expect(screen.getByTestId('dialog-content')).toBeInTheDocument()})+ it('reports a failed factory reset with its reason and resumes polling', async () => {+ const { toast } = await import('sonner')+ const { useHardware } = await import('@/hooks/useHardware')+ mockFactoryReset.mockRejectedValueOnce('Refusing to reset /home/jan')+ const Component = GeneralRoute.component as React.ComponentType+ await act(async () => {+ render(<Component />)+ })++ await act(async () => {+ fireEvent.click(screen.getByLabelText('settings:general.reset'))+ })++ expect(toast.error).toHaveBeenCalledWith(+ 'settings:general.factoryResetFailed',+ { description: 'Refusing to reset /home/jan' }+ )+ expect(useHardware.getState().pollingPaused).toBe(false)+ })+it('should render external links', async () => {const Component = GeneralRoute.component as React.ComponentTypeawait act(async () => {diff --git a/web-app/src/routes/settings/general.tsx b/web-app/src/routes/settings/general.tsxindex 461a416f5..4d685da7a 100644--- a/web-app/src/routes/settings/general.tsx+++ b/web-app/src/routes/settings/general.tsx@@ -58,7 +58,7 @@ function General() {}}const { checkForUpdate } = useAppUpdater()- const { pausePolling } = useHardware()+ const { pausePolling, resumePolling } = useHardware()const [janDataFolder, setJanDataFolder] = useState<string | undefined>()const [isCopied, setIsCopied] = useState(false)const [selectedNewPath, setSelectedNewPath] = useState<string | null>(null)@@ -81,7 +81,18 @@ function General() {return}pausePolling()- await serviceHub.app().factoryReset(options)+ try {+ await serviceHub.app().factoryReset(options)+ } catch (error) {+ // Model unloads and the backend can both fail here; the backend also+ // refuses data folders the isRootDir check above does not list. Its+ // message says why, so show that rather than guessing a cause.+ console.error('Factory reset failed:', error)+ resumePolling()+ toast.error(t('settings:general.factoryResetFailed'), {+ description: error instanceof Error ? error.message : String(error),+ })+ }}const handleOpenLogs = async () => {diff --git a/web-app/src/services/app/__tests__/tauri.coverage.test.ts b/web-app/src/services/app/__tests__/tauri.coverage.test.tsindex e7345346c..9c18b43c2 100644--- a/web-app/src/services/app/__tests__/tauri.coverage.test.ts+++ b/web-app/src/services/app/__tests__/tauri.coverage.test.ts@@ -86,32 +86,19 @@ describe('TauriAppService – coverage', () => {})})- it('prunes model + setup localStorage on a full wipe', async () => {+ it('leaves localStorage alone when the backend refuses the reset', async () => {const { invoke } = await import('@tauri-apps/api/core')- vi.mocked(invoke).mockResolvedValue(undefined)+ vi.mocked(invoke).mockRejectedValue('Refusing to reset /home/jan')localStorage.setItem('model-provider', '{"providers":[]}')- localStorage.setItem('last-used-model', 'ghost')localStorage.setItem('setup-completed', 'true')- localStorage.setItem('threads', '[]')-- await svc.factoryReset({ keepAppData: false, keepModelsAndConfigs: false })- expect(localStorage.getItem('model-provider')).toBeNull()- expect(localStorage.getItem('last-used-model')).toBeNull()- expect(localStorage.getItem('setup-completed')).toBeNull()- expect(localStorage.getItem('threads')).toBeNull()- })-- it('keeps model localStorage when models are preserved', async () => {- const { invoke } = await import('@tauri-apps/api/core')- vi.mocked(invoke).mockResolvedValue(undefined)- localStorage.setItem('model-provider', '{"providers":[]}')- localStorage.setItem('setup-completed', 'true')-- await svc.factoryReset({ keepAppData: false, keepModelsAndConfigs: true })+ await expect(+ svc.factoryReset({ keepAppData: false, keepModelsAndConfigs: false })+ ).rejects.toBe('Refusing to reset /home/jan')+ // Pruning happens on the next startup from the Rust sentinel, which a+ // refused reset never writes.expect(localStorage.getItem('model-provider')).toBe('{"providers":[]}')- // setup flag only cleared on a full wipeexpect(localStorage.getItem('setup-completed')).toBe('true')})diff --git a/web-app/src/services/app/tauri.ts b/web-app/src/services/app/tauri.tsindex 560ac8010..a3311ba4e 100644--- a/web-app/src/services/app/tauri.ts+++ b/web-app/src/services/app/tauri.ts@@ -6,7 +6,6 @@ import { invoke } from '@tauri-apps/api/core'import { AppConfiguration } from '@janhq/core'import type { FactoryResetOptions, LogEntry } from './types'import { DefaultAppService } from './default'-import { pruneLocalStorageByFlags } from './reset-localstorage'export class TauriAppService extends DefaultAppService {/**@@ -20,9 +19,10 @@ export class TauriAppService extends DefaultAppService {* snapshot/restore is needed.** localStorage still holds a frozen pre-migration snapshot (kept so a- * downgraded build can read it). The reliable clear happens on next startup- * via a Rust sentinel (see `main.tsx`) — renderer-side removal here is a- * best-effort supplement that races the restart flush.+ * downgraded build can read it). It is cleared on the next startup via a+ * Rust sentinel (see `main.tsx`), never here: the backend can still refuse+ * the reset, and on success the process restarts right after the invoke+ * resolves, so clearing here would race the restart flush.*/async factoryReset(options?: FactoryResetOptions): Promise<void> {const { EngineManager } = await import('@janhq/core')@@ -37,8 +37,6 @@ export class TauriAppService extends DefaultAppService {const keepModelsAndConfigs = options?.keepModelsAndConfigs ?? falseconst clearWebData = options?.clearWebData ?? false- pruneLocalStorageByFlags({ keepAppData, keepModelsAndConfigs })-if (!keepAppData && !keepModelsAndConfigs && !clearWebData) {await invoke('factory_reset')} else {