Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(threads): keep a caller-supplied thread id and add per-thread sidecars
Akarshan Biswase7bc1c2bf739
diff --git a/src-tauri/src/core/threads/commands.rs b/src-tauri/src/core/threads/commands.rsindex b6eaa8f02..3ab5a1e66 100644--- a/src-tauri/src/core/threads/commands.rs+++ b/src-tauri/src/core/threads/commands.rs@@ -7,13 +7,13 @@ use uuid::Uuid;use super::db;use super::helpers::{get_lock_for_thread, read_messages_from_file, should_use_sqlite, update_thread_metadata,- write_messages_to_file,+ write_atomic, write_messages_to_file,};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,+ get_thread_dir, get_thread_metadata_path, validate_thread_id,},};use crate::core::app::commands::get_jan_data_folder_path;@@ -61,8 +61,14 @@ pub async fn list_threads<R: Runtime>(Ok(threads)}-/// Creates a new thread, assigns it a unique ID, and persists its metadata.+/// 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 migrated+/// Cowork session keeps its id so its sandbox stays linked). A missing or+/// invalid id gets a fresh UUID. 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.#[tauri::command]pub async fn create_thread<R: Runtime>(app_handle: tauri::AppHandle<R>,@@ -76,18 +82,100 @@ pub async fn create_thread<R: Runtime>(// Use file-based storage on desktoplet data_folder = get_jan_data_folder_path(app_handle);ensure_data_dirs(&data_folder)?;- let uuid = Uuid::new_v4().to_string();+ let supplied = thread+ .get("id")+ .and_then(|v| v.as_str())+ .filter(|id| validate_thread_id(id).is_ok())+ .map(str::to_string);+ 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.+ let lock = get_lock_for_thread(&uuid).await;+ let _guard = lock.lock().await;+ let path = get_thread_metadata_path(&data_folder, &uuid)?;+ if path.exists() {+ let data = fs::read_to_string(&path).map_err(|e| e.to_string())?;+ return serde_json::from_str(&data).map_err(|e| e.to_string());+ }thread["id"] = serde_json::Value::String(uuid.clone());let thread_dir = get_thread_dir(&data_folder, &uuid)?;if !thread_dir.exists() {fs::create_dir_all(&thread_dir).map_err(|e| e.to_string())?;}- let path = get_thread_metadata_path(&data_folder, &uuid)?;let data = serde_json::to_string_pretty(&thread).map_err(|e| e.to_string())?;- fs::write(path, data).map_err(|e| e.to_string())?;+ write_atomic(&path, data.as_bytes())?;Ok(thread)}+/// Sidecar files a thread directory may hold besides thread.json and+/// messages.jsonl. Allowlisted so the commands can never address an arbitrary+/// file name.+const THREAD_EXTRA_NAMES: &[&str] = &["cowork"];++fn thread_extra_path(+ data_folder: &std::path::Path,+ thread_id: &str,+ name: &str,+) -> Result<std::path::PathBuf, String> {+ if !THREAD_EXTRA_NAMES.contains(&name) {+ return Err(format!("Unsupported thread extra: {name:?}"));+ }+ Ok(get_thread_dir(data_folder, thread_id)?.join(format!("{name}.json")))+}++/// Reads a per-thread sidecar (for example the Cowork transcript).+/// Returns `Ok(None)` when the sidecar does not exist.+#[tauri::command]+pub async fn read_thread_extra<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ thread_id: String,+ name: String,+) -> Result<Option<serde_json::Value>, String> {+ if should_use_sqlite() {+ return Err("Thread sidecars are not supported on mobile".to_string());+ }+ let data_folder = get_jan_data_folder_path(app_handle);+ let path = thread_extra_path(&data_folder, &thread_id, &name)?;+ if !path.exists() {+ return Ok(None);+ }+ let data = fs::read_to_string(&path).map_err(|e| e.to_string())?;+ serde_json::from_str(&data)+ .map(Some)+ .map_err(|e| e.to_string())+}++/// Writes a per-thread sidecar atomically (temp file + rename) under the+/// thread's lock. The thread directory is only created when `create` is true+/// (the migration writes the sidecar before thread.json commits the thread): a+/// late write for a thread that was deleted must fail instead of resurrecting a+/// directory holding a lone sidecar.+#[tauri::command]+pub async fn write_thread_extra<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ thread_id: String,+ name: String,+ value: serde_json::Value,+ create: Option<bool>,+) -> Result<(), String> {+ if should_use_sqlite() {+ return Err("Thread sidecars are not supported on mobile".to_string());+ }+ let data_folder = get_jan_data_folder_path(app_handle);+ let path = thread_extra_path(&data_folder, &thread_id, &name)?;+ 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 sidecar write"+ ));+ }+ let data = serde_json::to_vec(&value).map_err(|e| e.to_string())?;+ write_atomic(&path, &data)+}+/// 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.rsindex b1f17366e..51a2125f4 100644--- a/src-tauri/src/core/threads/tests.rs+++ b/src-tauri/src/core/threads/tests.rs@@ -823,3 +823,230 @@ async fn test_thread_commands_refuse_ids_outside_threads_dir() {assert!(!outside.path().join("messages.jsonl").exists());assert!(!outside.path().join("thread.json").exists());}++#[tokio::test]+async fn test_create_thread_honours_valid_supplied_id() {+ let (app, _data_dir) = mock_app_with_temp_data_dir();+ let mut thread = create_test_thread("Supplied id");+ thread["id"] = json!("0b6f1c1e-5a0e-4a53-9c1e-7f7d2a3b4c5d");+ let created = create_thread(app.handle().clone(), thread).await.unwrap();+ assert_eq!(created["id"], "0b6f1c1e-5a0e-4a53-9c1e-7f7d2a3b4c5d");++ let data_folder = get_jan_data_folder_path(app.handle().clone());+ assert!(+ get_thread_metadata_path(&data_folder, "0b6f1c1e-5a0e-4a53-9c1e-7f7d2a3b4c5d")+ .unwrap()+ .is_file()+ );+}++#[tokio::test]+async fn test_create_thread_keeps_ulid_ids_from_the_web_app() {+ // The web app mints ULIDs; they are valid thread ids and must round-trip.+ let (app, _data_dir) = mock_app_with_temp_data_dir();+ let mut thread = create_test_thread("Ulid");+ thread["id"] = json!("01HZX3Y9K2M4N6P8Q0R2S4T6V8");+ let created = create_thread(app.handle().clone(), thread).await.unwrap();+ assert_eq!(created["id"], "01HZX3Y9K2M4N6P8Q0R2S4T6V8");+}++#[tokio::test]+async fn test_create_thread_invalid_or_missing_id_gets_uuid() {+ 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 created = create_thread(app.handle().clone(), create_test_thread("No id"))+ .await+ .unwrap();+ assert!(validate_thread_id(created["id"].as_str().unwrap()).is_ok());+}++#[tokio::test]+async fn test_create_thread_with_existing_id_is_idempotent() {+ let (app, _data_dir) = mock_app_with_temp_data_dir();+ let mut first = create_test_thread("Original");+ first["id"] = json!("idem-thread-1");+ create_thread(app.handle().clone(), first).await.unwrap();++ let mut second = create_test_thread("Overwrite attempt");+ second["id"] = json!("idem-thread-1");+ let again = create_thread(app.handle().clone(), second).await.unwrap();+ assert_eq!(again["title"], "Original");++ let threads = list_threads(app.handle().clone()).await.unwrap();+ let stored = threads.iter().find(|t| t["id"] == "idem-thread-1").unwrap();+ assert_eq!(stored["title"], "Original");+}++#[tokio::test]+async fn test_concurrent_create_thread_with_same_id_keeps_the_first_record() {+ let (app, _data_dir) = mock_app_with_temp_data_dir();+ let creates = (0..8).map(|n| {+ let mut thread = create_test_thread(&format!("Racer {n}"));+ thread["id"] = json!("race-thread-1");+ create_thread(app.handle().clone(), thread)+ });+ let results = future::join_all(creates).await;+ let titles: std::collections::HashSet<String> = results+ .into_iter()+ .map(|r| r.unwrap()["title"].as_str().unwrap().to_string())+ .collect();+ // Every caller sees the one record that won; none sees its own overwrite.+ assert_eq!(titles.len(), 1, "{titles:?}");++ let data_folder = get_jan_data_folder_path(app.handle().clone());+ let path = get_thread_metadata_path(&data_folder, "race-thread-1").unwrap();+ let on_disk: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap();+ assert_eq!(+ on_disk["title"].as_str().unwrap(),+ titles.into_iter().next().unwrap()+ );+}++#[tokio::test]+async fn test_thread_extra_roundtrip_and_allowlist() {+ let (app, _data_dir) = mock_app_with_temp_data_dir();+ let mut thread = create_test_thread("Extra");+ thread["id"] = json!("extra-thread-1");+ create_thread(app.handle().clone(), thread).await.unwrap();++ let absent = read_thread_extra(+ app.handle().clone(),+ "extra-thread-1".into(),+ "cowork".into(),+ )+ .await+ .unwrap();+ assert!(absent.is_none());++ let value = json!({"turns": [{"role": "user", "content": "hi"}], "messages": [], "n": 1.5});+ write_thread_extra(+ app.handle().clone(),+ "extra-thread-1".into(),+ "cowork".into(),+ value.clone(),+ None,+ )+ .await+ .unwrap();+ let back = read_thread_extra(+ app.handle().clone(),+ "extra-thread-1".into(),+ "cowork".into(),+ )+ .await+ .unwrap();+ assert_eq!(back, Some(value));++ // A name outside the allowlist, or an id that escapes the threads dir, is refused.+ assert!(write_thread_extra(+ app.handle().clone(),+ "extra-thread-1".into(),+ "thread".into(),+ json!({}),+ None,+ )+ .await+ .is_err());+ assert!(+ read_thread_extra(app.handle().clone(), "../x".into(), "cowork".into())+ .await+ .is_err()+ );+}++#[tokio::test]+async fn test_write_thread_extra_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());++ // Without thread.json a late write (for example after a delete) must not+ // resurrect a directory holding a lone sidecar.+ let err = write_thread_extra(+ app.handle().clone(),+ "ghost-thread".into(),+ "cowork".into(),+ json!({"turns": []}),+ None,+ )+ .await+ .unwrap_err();+ assert!(err.contains("thread.json"), "{err}");+ assert!(!get_thread_dir(&data_folder, "ghost-thread").unwrap().exists());++ // The migration opts in: the sidecar lands first, thread.json is the commit marker.+ write_thread_extra(+ app.handle().clone(),+ "ghost-thread".into(),+ "cowork".into(),+ json!({"turns": []}),+ Some(true),+ )+ .await+ .unwrap();+ assert!(get_thread_dir(&data_folder, "ghost-thread").unwrap().exists());++ // A directory holding only the sidecar is not a thread yet.+ let listed = list_threads(app.handle().clone()).await.unwrap();+ assert!(listed.iter().all(|t| t["id"] != "ghost-thread"));+}++#[tokio::test]+async fn test_deleted_thread_cannot_be_resurrected_by_sidecar_write() {+ let (app, _data_dir) = mock_app_with_temp_data_dir();+ let mut thread = create_test_thread("Doomed");+ thread["id"] = json!("doomed-thread");+ create_thread(app.handle().clone(), thread).await.unwrap();+ write_thread_extra(+ app.handle().clone(),+ "doomed-thread".into(),+ "cowork".into(),+ json!({"turns": []}),+ None,+ )+ .await+ .unwrap();+ delete_thread(app.handle().clone(), "doomed-thread".into())+ .await+ .unwrap();++ assert!(write_thread_extra(+ app.handle().clone(),+ "doomed-thread".into(),+ "cowork".into(),+ json!({}),+ None,+ )+ .await+ .is_err());+ assert!(read_thread_extra(+ app.handle().clone(),+ "doomed-thread".into(),+ "cowork".into(),+ )+ .await+ .unwrap()+ .is_none());+}++#[tokio::test]+async fn test_create_thread_write_leaves_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).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_eq!(names, vec![THREADS_FILE.to_string()]);+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 207c34d6e..e1c2b1629 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -125,6 +125,8 @@ macro_rules! invoke_commands_with_extras {core::threads::commands::list_threads,core::threads::commands::create_thread,core::threads::commands::modify_thread,+ core::threads::commands::read_thread_extra,+ core::threads::commands::write_thread_extra,core::threads::commands::delete_thread,core::threads::commands::list_messages,core::threads::commands::create_message,