Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(threads): move a thread aside before deleting it (#9671)

Thinh Le51419d397e16
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index bc2d0a894..99eadbe70 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -48,8 +48,10 @@ use crate::core::agent::session_log::{
use crate::core::app::commands::resolve_jan_data_folder;
use crate::core::threads::{
constants::THREADS_FILE,
- helpers::{read_messages_from_file, update_thread_metadata},
- utils::{ensure_data_dirs, get_data_dir, get_thread_dir, get_thread_metadata_path},
+ helpers::{read_messages_from_file, remove_thread_dir, update_thread_metadata},
+ utils::{
+ ensure_data_dirs, get_data_dir, get_thread_dir, get_thread_metadata_path, DELETING_PREFIX,
+ },
};
// ── Thread operations ──────────────────────────────────────────────────────
@@ -66,7 +68,12 @@ pub fn list_threads_in(base: &std::path::Path) -> Result<Vec<serde_json::Value>,
}
for entry in fs::read_dir(&data_dir).map_err(|e| e.to_string())? {
let path = entry.map_err(|e| e.to_string())?.path();
- if path.is_dir() {
+ // A deleted thread whose files could not all be removed yet.
+ let deleting = path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .is_some_and(|n| n.starts_with(DELETING_PREFIX));
+ if path.is_dir() && !deleting {
let metadata_path = path.join(THREADS_FILE);
if metadata_path.exists() {
let data = fs::read_to_string(&metadata_path).map_err(|e| e.to_string())?;
@@ -365,13 +372,8 @@ pub fn cli_list_messages_in(
/// Delete a thread directory.
pub fn cli_delete_thread(thread_id: &str) -> Result<(), String> {
- use std::fs;
-
let data_folder = resolve_jan_data_folder();
- let thread_dir = get_thread_dir(&data_folder, thread_id)?;
- if thread_dir.exists() {
- fs::remove_dir_all(thread_dir).map_err(|e| e.to_string())?;
- }
+ remove_thread_dir(&data_folder, thread_id)?;
crate::core::agent::git::cleanup_snapshot_index(thread_id);
Ok(())
}
diff --git a/src-tauri/src/core/threads/commands.rs b/src-tauri/src/core/threads/commands.rs
index 0b16fb5c7..fa57bf97d 100644
--- a/src-tauri/src/core/threads/commands.rs
+++ b/src-tauri/src/core/threads/commands.rs
@@ -6,15 +6,16 @@ use uuid::Uuid;
#[cfg(any(target_os = "android", target_os = "ios"))]
use super::db;
use super::helpers::{
- get_lock_for_thread, read_messages_from_file, should_use_sqlite, sweep_stale_temps,
- update_thread_metadata, write_atomic, write_atomic_durable, write_messages_to_file,
- STALE_TEMP_AGE,
+ get_lock_for_thread, read_messages_from_file, remove_thread_dir, should_use_sqlite,
+ sweep_stale_temps, update_thread_metadata, write_atomic, write_atomic_durable,
+ write_messages_to_file, STALE_TEMP_AGE,
};
use super::{
constants::THREADS_FILE,
utils::{
ensure_data_dirs, ensure_thread_dir_exists, get_data_dir, get_messages_path,
- get_thread_dir, get_thread_metadata_path, validate_thread_id, PERMANENT_PREFIX,
+ get_thread_dir, get_thread_metadata_path, validate_thread_id, DELETING_PREFIX,
+ PERMANENT_PREFIX,
},
};
use crate::core::app::commands::get_jan_data_folder_path;
@@ -46,17 +47,23 @@ pub async fn list_threads<R: Runtime>(
let entry = entry.map_err(|e| e.to_string())?;
let path = entry.path();
if path.is_dir() {
+ let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
+ continue;
+ };
+ // What a delete moved aside but could not fully remove: retried here.
+ if name.starts_with(DELETING_PREFIX) {
+ let _ = fs::remove_dir_all(&path);
+ continue;
+ }
// A write killed mid-replace leaves its temp file in the thread.
// Swept here, at listing (startup), and only when no write of this
// process holds the thread; the age bound spares any other writer.
- if let Some(id) = path.file_name().and_then(|n| n.to_str()) {
- let lock = get_lock_for_thread(id).await;
- let guard = lock.try_lock();
- if guard.is_ok() {
- sweep_stale_temps(&path, STALE_TEMP_AGE, now);
- }
- drop(guard);
+ let lock = get_lock_for_thread(name).await;
+ let guard = lock.try_lock();
+ if guard.is_ok() {
+ sweep_stale_temps(&path, STALE_TEMP_AGE, now);
}
+ drop(guard);
let thread_metadata_path = path.join(THREADS_FILE);
if thread_metadata_path.exists() {
let data = fs::read_to_string(&thread_metadata_path).map_err(|e| e.to_string())?;
@@ -342,7 +349,10 @@ pub async fn modify_thread<R: Runtime>(
write_atomic(&path, data.as_bytes())
}
-/// Deletes a thread and all its associated files by removing its directory.
+/// Deletes a thread and all its associated files (see `remove_thread_dir`).
+/// A failed delete is reported with the thread intact: the caller would
+/// otherwise drop the conversation from the UI while its files return on
+/// restart.
#[tauri::command]
pub async fn delete_thread<R: Runtime>(
app_handle: tauri::AppHandle<R>,
@@ -357,18 +367,11 @@ pub async fn delete_thread<R: Runtime>(
let data_folder = get_jan_data_folder_path(app_handle);
// `get_thread_dir` validates the id before anything is keyed on it. The
// lock orders the removal against an in-flight write-through (sidecar,
- // messages, modify), which would otherwise race `remove_dir_all`.
- let thread_dir = get_thread_dir(&data_folder, &thread_id)?;
+ // messages, modify), which would otherwise race the rename.
+ get_thread_dir(&data_folder, &thread_id)?;
let lock = get_lock_for_thread(&thread_id).await;
let _guard = lock.lock().await;
- // A failed removal is reported: the caller would otherwise drop the
- // conversation from the UI while its files stay and return on restart.
- match fs::remove_dir_all(&thread_dir) {
- Ok(()) => {}
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
- Err(e) => return Err(format!("could not delete thread {thread_id}: {e}")),
- }
- Ok(())
+ remove_thread_dir(&data_folder, &thread_id)
}
/// Lists all messages for a given thread by reading and parsing its messages.jsonl file.
diff --git a/src-tauri/src/core/threads/helpers.rs b/src-tauri/src/core/threads/helpers.rs
index e38650018..442e9aecd 100644
--- a/src-tauri/src/core/threads/helpers.rs
+++ b/src-tauri/src/core/threads/helpers.rs
@@ -8,7 +8,9 @@ use std::sync::Arc;
use std::sync::OnceLock;
use tokio::sync::Mutex;
-use super::utils::{get_messages_path, get_thread_metadata_path};
+use super::utils::{
+ get_data_dir, get_messages_path, get_thread_dir, get_thread_metadata_path, DELETING_PREFIX,
+};
// Global per-thread locks for message file writes
pub static MESSAGE_LOCKS: OnceLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> = OnceLock::new();
@@ -18,6 +20,33 @@ pub fn should_use_sqlite() -> bool {
cfg!(any(target_os = "android", target_os = "ios"))
}
+/// Removes a thread's directory. The app calls it under the thread lock.
+///
+/// The directory is first renamed aside, which either succeeds whole or leaves
+/// the thread untouched: on Windows a file another program holds open fails it,
+/// and the error is reported with every file still in place. Removing a
+/// directory in place could instead fail halfway and leave a thread without
+/// some of its files. Once renamed the thread is gone; what the removal cannot
+/// delete (a file whose ACL forbids it) stays under the hidden name and is
+/// retried by the next `list_threads`. A thread that does not exist is not an
+/// error.
+pub fn remove_thread_dir(data_folder: &Path, thread_id: &str) -> Result<(), String> {
+ let thread_dir = get_thread_dir(data_folder, thread_id)?;
+ let aside = get_data_dir(data_folder)
+ .join(format!("{DELETING_PREFIX}{thread_id}-{}", uuid::Uuid::new_v4()));
+ match fs::rename(&thread_dir, &aside) {
+ Ok(()) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Err(e) => return Err(format!("could not delete thread {thread_id}: {e}")),
+ }
+ if let Err(e) = fs::remove_dir_all(&aside) {
+ log::warn!(
+ "thread {thread_id} deleted; some of its files remain until the next listing: {e}"
+ );
+ }
+ Ok(())
+}
+
/// Get a lock for a specific thread to ensure thread-safe message file operations
pub async fn get_lock_for_thread(thread_id: &str) -> Arc<Mutex<()>> {
let locks = MESSAGE_LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
diff --git a/src-tauri/src/core/threads/tests.rs b/src-tauri/src/core/threads/tests.rs
index c2700463c..254299bd1 100644
--- a/src-tauri/src/core/threads/tests.rs
+++ b/src-tauri/src/core/threads/tests.rs
@@ -6,7 +6,7 @@ use super::helpers::{
};
use super::utils::{
ensure_data_dirs, ensure_thread_dir_exists, get_data_dir, get_messages_path, get_thread_dir,
- get_thread_metadata_path, validate_thread_id, PERMANENT_PREFIX,
+ get_thread_metadata_path, validate_thread_id, DELETING_PREFIX, PERMANENT_PREFIX,
};
use crate::core::app::commands::get_jan_data_folder_path;
use futures_util::future;
@@ -974,26 +974,65 @@ async fn test_create_thread_refuses_an_invalid_id_and_mints_one_when_missing() {
#[cfg(unix)]
#[tokio::test]
-async fn test_delete_thread_reports_a_failed_removal() {
+async fn test_delete_thread_failing_to_move_keeps_every_file() {
use std::os::unix::fs::PermissionsExt;
let (app, data_dir) = mock_app_with_temp_data_dir();
let mut thread = create_test_thread("Locked");
thread["id"] = json!("locked-thread");
create_thread(app.handle().clone(), thread).await.unwrap();
- let dir = data_dir.join(THREADS_DIR).join("locked-thread");
- std::fs::create_dir_all(dir.join("inner")).unwrap();
- std::fs::write(dir.join("inner/file"), "x").unwrap();
- // Removing entries of a read-only directory fails.
- std::fs::set_permissions(dir.join("inner"), std::fs::Permissions::from_mode(0o500)).unwrap();
+ let threads = data_dir.join(THREADS_DIR);
+ let dir = threads.join("locked-thread");
+ std::fs::write(dir.join("cowork.json"), "{}").unwrap();
+ // Renaming an entry of a read-only directory fails, like a file held open
+ // on Windows.
+ std::fs::set_permissions(&threads, std::fs::Permissions::from_mode(0o500)).unwrap();
let result = delete_thread(app.handle().clone(), "locked-thread".to_string()).await;
- std::fs::set_permissions(dir.join("inner"), std::fs::Permissions::from_mode(0o700)).unwrap();
+ std::fs::set_permissions(&threads, std::fs::Permissions::from_mode(0o700)).unwrap();
assert!(result.is_err(), "{result:?}");
+ for file in [THREADS_FILE, "cowork.json"] {
+ assert!(dir.join(file).exists(), "{file} survives a failed delete");
+ }
+}
- // A thread that is already gone is not an error.
- delete_thread(app.handle().clone(), "locked-thread".to_string())
+#[cfg(unix)]
+#[tokio::test]
+async fn test_delete_thread_with_an_undeletable_file_still_removes_the_thread() {
+ use std::os::unix::fs::PermissionsExt;
+ let (app, data_dir) = mock_app_with_temp_data_dir();
+ let mut thread = create_test_thread("Stuck");
+ thread["id"] = json!("stuck-thread");
+ create_thread(app.handle().clone(), thread).await.unwrap();
+ let threads = data_dir.join(THREADS_DIR);
+ let inner = threads.join("stuck-thread").join("inner");
+ std::fs::create_dir_all(&inner).unwrap();
+ std::fs::write(inner.join("file"), "x").unwrap();
+ // Removing entries of a read-only directory fails.
+ std::fs::set_permissions(&inner, std::fs::Permissions::from_mode(0o500)).unwrap();
+
+ delete_thread(app.handle().clone(), "stuck-thread".to_string())
.await
.unwrap();
- delete_thread(app.handle().clone(), "locked-thread".to_string())
+ let leftovers = || {
+ std::fs::read_dir(&threads)
+ .unwrap()
+ .map(|e| e.unwrap().path())
+ .filter(|p| p.file_name().unwrap().to_str().unwrap().starts_with(DELETING_PREFIX))
+ .collect::<Vec<_>>()
+ };
+ let stuck = leftovers();
+ assert_eq!(stuck.len(), 1);
+ assert!(!threads.join("stuck-thread").exists());
+ let listed = list_threads(app.handle().clone()).await.unwrap();
+ assert!(listed.iter().all(|t| t["id"] != "stuck-thread"));
+
+ // Once the file can be removed, the next listing finishes the delete.
+ std::fs::set_permissions(stuck[0].join("inner"), std::fs::Permissions::from_mode(0o700))
+ .unwrap();
+ list_threads(app.handle().clone()).await.unwrap();
+ assert!(leftovers().is_empty());
+
+ // A thread that is already gone is not an error.
+ delete_thread(app.handle().clone(), "stuck-thread".to_string())
.await
.unwrap();
}
diff --git a/src-tauri/src/core/threads/utils.rs b/src-tauri/src/core/threads/utils.rs
index 166eeffc0..e41b5c300 100644
--- a/src-tauri/src/core/threads/utils.rs
+++ b/src-tauri/src/core/threads/utils.rs
@@ -15,6 +15,10 @@ pub fn get_data_dir(data_folder: &Path) -> PathBuf {
data_folder.join(THREADS_DIR)
}
+/// Prefix of a thread directory a delete has moved aside before removing it.
+/// `.` is never part of a valid thread id, so no listing reads it as a thread.
+pub const DELETING_PREFIX: &str = ".deleting-";
+
/// Names Windows maps to a device in every directory, in any case and also
/// with an extension (`nul.txt`). Checked on every OS so an id accepted on one
/// works on all of them.