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): replace a thread's messages.jsonl atomically

Akarshan Biswasa3a5f231c5e0
diff --git a/src-tauri/src/core/threads/commands.rs b/src-tauri/src/core/threads/commands.rs
index 3ab5a1e66..62d2a0e41 100644
--- a/src-tauri/src/core/threads/commands.rs
+++ b/src-tauri/src/core/threads/commands.rs
@@ -176,6 +176,51 @@ pub async fn write_thread_extra<R: Runtime>(
write_atomic(&path, &data)
}
+/// Replaces a thread's whole messages.jsonl atomically (temp file + rename)
+/// under the thread's lock. Unlike `create_message` it never appends, so
+/// writing the same batch twice leaves identical bytes: the Cowork migration
+/// relies on that to retry after a crash between this write and the thread.json
+/// commit without duplicating the transcript. `create` has the same meaning as
+/// in `write_thread_extra`. The batch is refused unless every message carries a
+/// unique string id and this thread's id, the invariants `create_message` and
+/// `modify_message` maintain for the log.
+#[tauri::command]
+pub async fn replace_thread_messages<R: Runtime>(
+ app_handle: tauri::AppHandle<R>,
+ thread_id: String,
+ messages: Vec<serde_json::Value>,
+ create: Option<bool>,
+) -> Result<(), String> {
+ if should_use_sqlite() {
+ return Err("Replacing thread messages is not supported on mobile".to_string());
+ }
+ let mut seen = std::collections::HashSet::new();
+ for message in &messages {
+ let id = message
+ .get("id")
+ .and_then(|v| v.as_str())
+ .ok_or("Every message needs a string id")?;
+ if !seen.insert(id) {
+ return Err(format!("Duplicate message id {id:?}"));
+ }
+ if message.get("thread_id").and_then(|v| v.as_str()) != Some(thread_id.as_str()) {
+ return Err(format!("Message {id:?} does not belong to thread {thread_id:?}"));
+ }
+ }
+ let data_folder = get_jan_data_folder_path(app_handle);
+ let path = get_messages_path(&data_folder, &thread_id)?;
+ let lock = get_lock_for_thread(&thread_id).await;
+ let _guard = lock.lock().await;
+ if create.unwrap_or(false) {
+ ensure_thread_dir_exists(&data_folder, &thread_id)?;
+ } else if !get_thread_metadata_path(&data_folder, &thread_id)?.exists() {
+ return Err(format!(
+ "Thread '{thread_id}' has no thread.json; refusing to create it from a messages write"
+ ));
+ }
+ write_messages_to_file(&messages, &path)
+}
+
/// Modifies an existing thread's metadata by overwriting its thread.json file.
/// Returns an error if the thread directory does not exist.
#[tauri::command]
diff --git a/src-tauri/src/core/threads/tests.rs b/src-tauri/src/core/threads/tests.rs
index 51a2125f4..c07f4eb0c 100644
--- a/src-tauri/src/core/threads/tests.rs
+++ b/src-tauri/src/core/threads/tests.rs
@@ -1050,3 +1050,140 @@ async fn test_create_thread_write_leaves_no_temp_files() {
.collect();
assert_eq!(names, vec![THREADS_FILE.to_string()]);
}
+
+fn migrated_message(thread_id: &str, id: &str, text: &str) -> serde_json::Value {
+ json!({
+ "id": id,
+ "object": "thread.message",
+ "thread_id": thread_id,
+ "role": "user",
+ "content": [{"type": "text", "text": {"value": text, "annotations": []}}],
+ "status": "ready",
+ "created_at": 1,
+ "completed_at": 1
+ })
+}
+
+#[tokio::test]
+async fn test_replace_thread_messages_replaces_instead_of_appending() {
+ let (app, _data_dir) = mock_app_with_temp_data_dir();
+ let data_folder = get_jan_data_folder_path(app.handle().clone());
+ let batch = vec![
+ migrated_message("replace-thread", "replace-thread-msg-0", "one"),
+ migrated_message("replace-thread", "replace-thread-msg-1", "two"),
+ ];
+
+ // The migration writes before thread.json exists, so it must be allowed to
+ // create the directory.
+ replace_thread_messages(
+ app.handle().clone(),
+ "replace-thread".into(),
+ batch.clone(),
+ Some(true),
+ )
+ .await
+ .unwrap();
+ let path = get_messages_path(&data_folder, "replace-thread").unwrap();
+ let first = fs::read(&path).unwrap();
+
+ // A retry after a crash writes the same batch again: same bytes, no duplicates.
+ replace_thread_messages(
+ app.handle().clone(),
+ "replace-thread".into(),
+ batch.clone(),
+ Some(true),
+ )
+ .await
+ .unwrap();
+ assert_eq!(fs::read(&path).unwrap(), first);
+ let listed = list_messages(app.handle().clone(), "replace-thread".into())
+ .await
+ .unwrap();
+ assert_eq!(listed, batch);
+
+ // A shorter batch replaces the file whole.
+ replace_thread_messages(
+ app.handle().clone(),
+ "replace-thread".into(),
+ batch[..1].to_vec(),
+ Some(true),
+ )
+ .await
+ .unwrap();
+ let listed = list_messages(app.handle().clone(), "replace-thread".into())
+ .await
+ .unwrap();
+ assert_eq!(listed, batch[..1].to_vec());
+
+ // No temp file is left beside it, and the thread is still uncommitted.
+ let names: Vec<String> = fs::read_dir(path.parent().unwrap())
+ .unwrap()
+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
+ .collect();
+ assert_eq!(names, vec![MESSAGES_FILE.to_string()]);
+ let threads = list_threads(app.handle().clone()).await.unwrap();
+ assert!(threads.iter().all(|t| t["id"] != "replace-thread"));
+}
+
+#[tokio::test]
+async fn test_replace_thread_messages_creates_the_directory_only_on_request() {
+ let (app, _data_dir) = mock_app_with_temp_data_dir();
+ let data_folder = get_jan_data_folder_path(app.handle().clone());
+ let batch = vec![migrated_message("late-thread", "late-thread-msg-0", "x")];
+
+ // Without thread.json a late write (for example after a delete) must not
+ // resurrect a thread directory.
+ let err = replace_thread_messages(
+ app.handle().clone(),
+ "late-thread".into(),
+ batch.clone(),
+ None,
+ )
+ .await
+ .unwrap_err();
+ assert!(err.contains("thread.json"), "{err}");
+ assert!(!get_thread_dir(&data_folder, "late-thread").unwrap().exists());
+
+ // Once the thread is committed a plain replace is allowed.
+ let mut thread = create_test_thread("Late");
+ thread["id"] = json!("late-thread");
+ create_thread(app.handle().clone(), thread).await.unwrap();
+ replace_thread_messages(app.handle().clone(), "late-thread".into(), batch.clone(), None)
+ .await
+ .unwrap();
+ let listed = list_messages(app.handle().clone(), "late-thread".into())
+ .await
+ .unwrap();
+ assert_eq!(listed, batch);
+}
+
+#[tokio::test]
+async fn test_replace_thread_messages_rejects_a_batch_that_would_corrupt_the_log() {
+ let (app, _data_dir) = mock_app_with_temp_data_dir();
+ let ok = migrated_message("guard-thread", "guard-thread-msg-0", "x");
+
+ // A message for another thread, a missing id and a repeated id would each
+ // break the per-thread log create_message and modify_message maintain.
+ let foreign = migrated_message("other-thread", "other-msg-0", "x");
+ let mut anonymous = ok.clone();
+ anonymous.as_object_mut().unwrap().remove("id");
+ for bad in [
+ vec![ok.clone(), foreign],
+ vec![ok.clone(), anonymous],
+ vec![ok.clone(), ok.clone()],
+ ] {
+ assert!(replace_thread_messages(
+ app.handle().clone(),
+ "guard-thread".into(),
+ bad,
+ Some(true),
+ )
+ .await
+ .is_err());
+ }
+ // Nothing was written for a refused batch.
+ let listed = list_messages(app.handle().clone(), "guard-thread".into())
+ .await
+ .unwrap();
+ assert!(listed.is_empty());
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index e1c2b1629..9d3454079 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -127,6 +127,7 @@ macro_rules! invoke_commands_with_extras {
core::threads::commands::modify_thread,
core::threads::commands::read_thread_extra,
core::threads::commands::write_thread_extra,
+ core::threads::commands::replace_thread_messages,
core::threads::commands::delete_thread,
core::threads::commands::list_messages,
core::threads::commands::create_message,