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(tauri): refuse an invalid supplied thread id and report a failed thread delete

thinhlpg1b2b85492d35
diff --git a/src-tauri/src/core/threads/commands.rs b/src-tauri/src/core/threads/commands.rs
index 8a7298378..29a34e488 100644
--- a/src-tauri/src/core/threads/commands.rs
+++ b/src-tauri/src/core/threads/commands.rs
@@ -64,8 +64,11 @@ pub async fn list_threads<R: Runtime>(
/// Creates a new thread and persists its metadata.
/// Ensures the thread directory exists and writes thread.json.
///
-/// A caller-supplied `id` is kept when it is a valid thread id; a missing or
-/// invalid id gets a fresh UUID. Creation is idempotent: when thread.json
+/// A caller-supplied `id` is kept; a missing or empty id gets a fresh UUID. An
+/// id that is supplied but not a valid thread id is refused with a
+/// `PERMANENT:` error rather than silently swapped, since the caller (the
+/// Cowork migration, a chat with a minted ULID) addresses the thread by the
+/// id it sent. Creation is idempotent: when thread.json
/// already exists for the id, that record is returned untouched. thread.json
/// is written atomically because it is the commit marker of a thread.
///
@@ -95,11 +98,13 @@ pub async fn create_thread<R: Runtime>(
// Use file-based storage on desktop
let data_folder = get_jan_data_folder_path(app_handle);
ensure_data_dirs(&data_folder)?;
- let supplied = thread
- .get("id")
- .and_then(|v| v.as_str())
- .filter(|id| validate_thread_id(id).is_ok())
- .map(str::to_string);
+ let supplied = match thread.get("id").and_then(|v| v.as_str()) {
+ Some(id) if !id.is_empty() => {
+ validate_thread_id(id)?;
+ Some(id.to_string())
+ }
+ _ => None,
+ };
let uuid = supplied.unwrap_or_else(|| Uuid::new_v4().to_string());
// Hold the thread lock across the existence check and the write so two
// creates for one id cannot both pass the check and overwrite each other.
@@ -343,8 +348,12 @@ pub async fn delete_thread<R: Runtime>(
let thread_dir = get_thread_dir(&data_folder, &thread_id)?;
let lock = get_lock_for_thread(&thread_id).await;
let _guard = lock.lock().await;
- if thread_dir.exists() {
- let _ = fs::remove_dir_all(thread_dir);
+ // 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(())
}
diff --git a/src-tauri/src/core/threads/tests.rs b/src-tauri/src/core/threads/tests.rs
index 6d2a1437b..c2700463c 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,
+ get_thread_metadata_path, validate_thread_id, PERMANENT_PREFIX,
};
use crate::core::app::commands::get_jan_data_folder_path;
use futures_util::future;
@@ -953,19 +953,49 @@ async fn test_create_thread_keeps_ulid_ids_from_the_web_app() {
}
#[tokio::test]
-async fn test_create_thread_invalid_or_missing_id_gets_uuid() {
- let (app, _data_dir) = mock_app_with_temp_data_dir();
+async fn test_create_thread_refuses_an_invalid_id_and_mints_one_when_missing() {
+ let (app, data_dir) = mock_app_with_temp_data_dir();
let mut bad = create_test_thread("Bad id");
bad["id"] = json!("../escape");
- let created = create_thread(app.handle().clone(), bad).await.unwrap();
- let id = created["id"].as_str().unwrap();
- assert_ne!(id, "../escape");
- assert!(validate_thread_id(id).is_ok());
+ let err = create_thread(app.handle().clone(), bad).await.unwrap_err();
+ assert!(err.starts_with(PERMANENT_PREFIX), "{err}");
+ assert!(!data_dir.join("escape").exists());
let created = create_thread(app.handle().clone(), create_test_thread("No id"))
.await
.unwrap();
assert!(validate_thread_id(created["id"].as_str().unwrap()).is_ok());
+
+ let mut empty = create_test_thread("Empty id");
+ empty["id"] = json!("");
+ let created = create_thread(app.handle().clone(), empty).await.unwrap();
+ assert!(validate_thread_id(created["id"].as_str().unwrap()).is_ok());
+}
+
+#[cfg(unix)]
+#[tokio::test]
+async fn test_delete_thread_reports_a_failed_removal() {
+ 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 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();
+ assert!(result.is_err(), "{result:?}");
+
+ // A thread that is already gone is not an error.
+ delete_thread(app.handle().clone(), "locked-thread".to_string())
+ .await
+ .unwrap();
+ delete_thread(app.handle().clone(), "locked-thread".to_string())
+ .await
+ .unwrap();
}
#[tokio::test]