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.

feat(threads): stable thread_missing error and locked atomic modify

Akarshan Biswaseea92ece395a
diff --git a/src-tauri/src/core/threads/commands.rs b/src-tauri/src/core/threads/commands.rs
index 03dd6be71..8a7298378 100644
--- a/src-tauri/src/core/threads/commands.rs
+++ b/src-tauri/src/core/threads/commands.rs
@@ -121,6 +121,15 @@ pub async fn create_thread<R: Runtime>(
Ok(thread)
}
+/// Stable prefix of errors meaning the thread no longer exists on disk. The web
+/// layer matches it to tell a deleted thread (stop writing, mark unavailable)
+/// from a transient failure (keep dirty, retry).
+pub const THREAD_MISSING_ERROR_CODE: &str = "thread_missing";
+
+fn thread_missing_error(detail: impl std::fmt::Display) -> String {
+ format!("{THREAD_MISSING_ERROR_CODE}: {detail}")
+}
+
/// Sidecar files a thread directory may hold besides thread.json and
/// messages.jsonl. Allowlisted so the commands can never address an arbitrary
/// file name.
@@ -219,9 +228,9 @@ pub async fn write_thread_extra<R: Runtime>(
ensure_uncommitted_dir_is_ours(&data_folder, &thread_id, None)?;
ensure_thread_dir_exists(&data_folder, &thread_id)?;
} else if !get_thread_metadata_path(&data_folder, &thread_id)?.exists() {
- return Err(format!(
+ return Err(thread_missing_error(format!(
"Thread '{thread_id}' has no thread.json; refusing to create it from a sidecar write"
- ));
+ )));
}
let data = serde_json::to_vec(&value).map_err(|e| e.to_string())?;
write_atomic(&path, &data)
@@ -273,15 +282,18 @@ pub async fn replace_thread_messages<R: Runtime>(
ensure_uncommitted_dir_is_ours(&data_folder, &thread_id, Some(body.as_bytes()))?;
ensure_thread_dir_exists(&data_folder, &thread_id)?;
} else if !get_thread_metadata_path(&data_folder, &thread_id)?.exists() {
- return Err(format!(
+ return Err(thread_missing_error(format!(
"Thread '{thread_id}' has no thread.json; refusing to create it from a messages write"
- ));
+ )));
}
write_atomic(&path, body.as_bytes())
}
-/// Modifies an existing thread's metadata by overwriting its thread.json file.
-/// Returns an error if the thread directory does not exist.
+/// Modifies an existing thread's metadata by replacing its thread.json.
+/// Runs under the thread's lock and writes atomically, so it cannot interleave
+/// with a delete or a sidecar/messages write, and a crash leaves either the old
+/// or the new record. Fails with the `thread_missing:` code when thread.json is
+/// absent; it never creates a thread.
#[tauri::command]
pub async fn modify_thread<R: Runtime>(
app_handle: tauri::AppHandle<R>,
@@ -298,14 +310,18 @@ pub async fn modify_thread<R: Runtime>(
.get("id")
.and_then(|id| id.as_str())
.ok_or("Missing thread id")?;
+ let lock = get_lock_for_thread(thread_id).await;
+ let _guard = lock.lock().await;
let thread_dir = get_thread_dir(&data_folder, thread_id)?;
if !thread_dir.exists() {
- return Err("Thread directory does not exist".to_string());
+ return Err(thread_missing_error("Thread directory does not exist"));
}
let path = get_thread_metadata_path(&data_folder, thread_id)?;
+ if !path.is_file() {
+ return Err(thread_missing_error("Thread does not exist"));
+ }
let data = serde_json::to_string_pretty(&thread).map_err(|e| e.to_string())?;
- fs::write(path, data).map_err(|e| e.to_string())?;
- Ok(())
+ write_atomic(&path, data.as_bytes())
}
/// Deletes a thread and all its associated files by removing its directory.
@@ -321,7 +337,12 @@ pub async fn delete_thread<R: Runtime>(
// Use file-based storage on desktop
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)?;
+ 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);
}
diff --git a/src-tauri/src/core/threads/tests.rs b/src-tauri/src/core/threads/tests.rs
index 06a2ee728..6d2a1437b 100644
--- a/src-tauri/src/core/threads/tests.rs
+++ b/src-tauri/src/core/threads/tests.rs
@@ -824,6 +824,108 @@ async fn test_thread_commands_refuse_ids_outside_threads_dir() {
assert!(!outside.path().join("thread.json").exists());
}
+#[tokio::test]
+async fn test_modify_thread_missing_thread_uses_stable_error_code() {
+ let (app, _data_dir) = mock_app_with_temp_data_dir();
+ let err = modify_thread(app.handle().clone(), json!({"id": "ghost-modify"}))
+ .await
+ .unwrap_err();
+ assert!(err.starts_with("thread_missing:"), "{err}");
+
+ // A bare directory without thread.json is also "missing", and must not be
+ // turned into a thread by a modify.
+ let data_folder = get_jan_data_folder_path(app.handle().clone());
+ ensure_thread_dir_exists(&data_folder, "ghost-modify-dir").unwrap();
+ let err = modify_thread(app.handle().clone(), json!({"id": "ghost-modify-dir"}))
+ .await
+ .unwrap_err();
+ assert!(err.starts_with("thread_missing:"), "{err}");
+ assert!(!get_thread_metadata_path(&data_folder, "ghost-modify-dir")
+ .unwrap()
+ .exists());
+}
+
+#[tokio::test]
+async fn test_write_thread_extra_and_messages_missing_thread_use_stable_error_code() {
+ let (app, _data_dir) = mock_app_with_temp_data_dir();
+ let err = write_thread_extra(
+ app.handle().clone(),
+ "ghost-extra".into(),
+ "cowork".into(),
+ json!({}),
+ None,
+ )
+ .await
+ .unwrap_err();
+ assert!(err.starts_with("thread_missing:"), "{err}");
+ let err = replace_thread_messages(app.handle().clone(), "ghost-extra".into(), vec![], None)
+ .await
+ .unwrap_err();
+ assert!(err.starts_with("thread_missing:"), "{err}");
+ let data_folder = get_jan_data_folder_path(app.handle().clone());
+ assert!(!get_thread_dir(&data_folder, "ghost-extra").unwrap().exists());
+}
+
+#[tokio::test]
+async fn test_thread_json_writes_leave_no_temp_files() {
+ let (app, _data_dir) = mock_app_with_temp_data_dir();
+ let mut thread = create_test_thread("Atomic");
+ thread["id"] = json!("atomic-thread");
+ create_thread(app.handle().clone(), thread.clone())
+ .await
+ .unwrap();
+ thread["title"] = json!("Atomic 2");
+ modify_thread(app.handle().clone(), thread).await.unwrap();
+
+ let data_folder = get_jan_data_folder_path(app.handle().clone());
+ let dir = get_thread_dir(&data_folder, "atomic-thread").unwrap();
+ let names: Vec<String> = fs::read_dir(&dir)
+ .unwrap()
+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
+ .collect();
+ assert!(names.iter().all(|n| !n.ends_with(".tmp")), "{names:?}");
+ let on_disk: serde_json::Value =
+ serde_json::from_str(&fs::read_to_string(dir.join(THREADS_FILE)).unwrap()).unwrap();
+ assert_eq!(on_disk["title"], "Atomic 2");
+}
+
+#[tokio::test]
+async fn test_modify_thread_waits_for_the_thread_lock() {
+ let (app, _data_dir) = mock_app_with_temp_data_dir();
+ let mut thread = create_test_thread("Locked");
+ thread["id"] = json!("locked-modify");
+ create_thread(app.handle().clone(), thread.clone())
+ .await
+ .unwrap();
+
+ let lock = get_lock_for_thread("locked-modify").await;
+ let guard = lock.lock().await;
+ thread["title"] = json!("Locked 2");
+ let handle = app.handle().clone();
+ let pending = tokio::spawn(async move { modify_thread(handle, thread).await });
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ assert!(!pending.is_finished(), "modify_thread must take the thread lock");
+ drop(guard);
+ pending.await.unwrap().unwrap();
+}
+
+#[tokio::test]
+async fn test_delete_thread_waits_for_the_thread_lock() {
+ let (app, _data_dir) = mock_app_with_temp_data_dir();
+ let mut thread = create_test_thread("Locked delete");
+ thread["id"] = json!("locked-delete");
+ create_thread(app.handle().clone(), thread).await.unwrap();
+
+ let lock = get_lock_for_thread("locked-delete").await;
+ let guard = lock.lock().await;
+ let handle = app.handle().clone();
+ let pending = tokio::spawn(async move { delete_thread(handle, "locked-delete".into()).await });
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ assert!(!pending.is_finished(), "delete_thread must take the thread lock");
+ drop(guard);
+ pending.await.unwrap().unwrap();
+}
+
#[tokio::test]
async fn test_create_thread_honours_valid_supplied_id() {
let (app, _data_dir) = mock_app_with_temp_data_dir();