The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: update Rust edition to 2021 across the codebase
Steven Enamakel192c7cf96156
diff --git a/crates/openhuman-app/profiling/src/main.rs b/crates/openhuman-app/profiling/src/main.rsindex 5f2faf676d..60d801ca98 100644--- a/crates/openhuman-app/profiling/src/main.rs+++ b/crates/openhuman-app/profiling/src/main.rs@@ -657,157 +657,5 @@ fn finish_stack_capture(child: Option<&mut Child>, prior_error: Option<String>)}#[cfg(test)]-mod tests {- use super::*;-- fn process(- pid: u32,- parent_pid: Option<u32>,- name: &str,- command: &str,- memory_bytes: u64,- cpu_percent: f32,- ) -> ProcessSample {- ProcessSample {- pid,- parent_pid,- name: name.into(),- command: command.into(),- memory_bytes,- cpu_percent,- }- }-- #[test]- fn classifies_cef_roles() {- assert_eq!(- classify_process(- &process(2, Some(1), "OpenHuman Helper", "--type=renderer", 1, 1.0),- 1- ),- Component::CefRenderer- );- assert_eq!(- classify_process(- &process(3, Some(1), "OpenHuman Helper", "--type=gpu-process", 1, 1.0),- 1- ),- Component::CefGpu- );- assert_eq!(- classify_process(- &process(4, Some(1), "OpenHuman Helper", "--type=utility", 1, 1.0),- 1- ),- Component::CefUtility- );- }-- #[test]- fn groups_only_host_process_tree() {- let processes = vec![- process(10, Some(1), "OpenHuman", "OpenHuman", 100, 20.0),- process(11, Some(10), "Helper", "--type=renderer", 40, 30.0),- process(12, Some(11), "Helper", "--type=utility", 10, 5.0),- process(99, Some(1), "unrelated", "unrelated", 1_000, 100.0),- ];-- let grouped = group_process_tree(10, &processes).unwrap();- assert_eq!(grouped.len(), 3);- assert_eq!(- grouped.iter().map(|value| value.memory_bytes).sum::<u64>(),- 150- );- assert_eq!(- grouped.iter().map(|value| value.cpu_percent).sum::<f32>(),- 55.0- );- }-- #[test]- fn report_separates_rust_binary_from_desktop_total() {- let samples = vec![TimeSample {- elapsed_ms: 250,- components: vec![- ComponentSample {- component: Component::TauriHostAndEmbeddedCore,- process_count: 1,- memory_bytes: 100,- cpu_percent: 20.0,- },- ComponentSample {- component: Component::CefRenderer,- process_count: 2,- memory_bytes: 50,- cpu_percent: 30.0,- },- ],- }];- let report = build_report(ProfileCapture {- host_pid: 10,- duration: Duration::from_secs(1),- interval: Duration::from_millis(250),- logical_cpu_count: 8,- samples,- rust_cpu_modules: Vec::new(),- cpu_stack_report: None,- cpu_stack_error: None,- })- .unwrap();-- assert_eq!(report.rust_binary.mean_memory_bytes, 100);- assert_eq!(report.desktop_total.mean_memory_bytes, 150);- assert_eq!(report.desktop_total.peak_process_count, 3);- assert!(render_markdown(&report).contains("Tauri host + embedded Rust core"));- }-- #[test]- fn parser_requires_pid_and_clamps_cpu_interval() {- assert!(parse_args(Vec::<String>::new()).is_err());- let args = parse_args([- "--pid".into(),- "123".into(),- "--duration".into(),- "2".into(),- "--interval-ms".into(),- "1".into(),- "--no-stacks".into(),- ])- .unwrap();- assert_eq!(args.pid, 123);- assert_eq!(args.duration, Duration::from_secs(2));- assert_eq!(args.interval, MINIMUM_CPU_UPDATE_INTERVAL);- assert!(!args.capture_stacks);- }-- #[test]- fn parses_recursive_stack_counts_into_openhuman_modules() {- let sample = r#"-Total number in stack (recursive counted multiple, when >=5):- 81 openhuman_core::agent::run (in OpenHuman) + 10- 34 <openhuman_core::agent::Tool as core::future::Future>::poll (in OpenHuman) + 2- 17 openhuman_core::memory::search (in OpenHuman) + 4- 9 openhuman::core_process::ensure_running (in OpenHuman) + 1- 200 tokio::runtime::park (in OpenHuman) + 3--Sort by top of stack, same collapsed (when >= 5):-"#;- assert_eq!(- parse_rust_module_cpu(sample),- vec![- RustModuleCpu {- module: "openhuman_core::agent".into(),- recursive_samples: 115,- },- RustModuleCpu {- module: "openhuman_core::memory".into(),- recursive_samples: 17,- },- RustModuleCpu {- module: "openhuman::core_process".into(),- recursive_samples: 9,- },- ]- );- }-}+#[path = "main_tests.rs"]+mod tests;diff --git a/crates/openhuman-app/profiling/src/main_tests.rs b/crates/openhuman-app/profiling/src/main_tests.rsnew file mode 100644index 0000000000..a9f37b2673--- /dev/null+++ b/crates/openhuman-app/profiling/src/main_tests.rs@@ -0,0 +1,152 @@+use super::*;++fn process(+ pid: u32,+ parent_pid: Option<u32>,+ name: &str,+ command: &str,+ memory_bytes: u64,+ cpu_percent: f32,+) -> ProcessSample {+ ProcessSample {+ pid,+ parent_pid,+ name: name.into(),+ command: command.into(),+ memory_bytes,+ cpu_percent,+ }+}++#[test]+fn classifies_cef_roles() {+ assert_eq!(+ classify_process(+ &process(2, Some(1), "OpenHuman Helper", "--type=renderer", 1, 1.0),+ 1+ ),+ Component::CefRenderer+ );+ assert_eq!(+ classify_process(+ &process(3, Some(1), "OpenHuman Helper", "--type=gpu-process", 1, 1.0),+ 1+ ),+ Component::CefGpu+ );+ assert_eq!(+ classify_process(+ &process(4, Some(1), "OpenHuman Helper", "--type=utility", 1, 1.0),+ 1+ ),+ Component::CefUtility+ );+}++#[test]+fn groups_only_host_process_tree() {+ let processes = vec![+ process(10, Some(1), "OpenHuman", "OpenHuman", 100, 20.0),+ process(11, Some(10), "Helper", "--type=renderer", 40, 30.0),+ process(12, Some(11), "Helper", "--type=utility", 10, 5.0),+ process(99, Some(1), "unrelated", "unrelated", 1_000, 100.0),+ ];++ let grouped = group_process_tree(10, &processes).unwrap();+ assert_eq!(grouped.len(), 3);+ assert_eq!(+ grouped.iter().map(|value| value.memory_bytes).sum::<u64>(),+ 150+ );+ assert_eq!(+ grouped.iter().map(|value| value.cpu_percent).sum::<f32>(),+ 55.0+ );+}++#[test]+fn report_separates_rust_binary_from_desktop_total() {+ let samples = vec![TimeSample {+ elapsed_ms: 250,+ components: vec![+ ComponentSample {+ component: Component::TauriHostAndEmbeddedCore,+ process_count: 1,+ memory_bytes: 100,+ cpu_percent: 20.0,+ },+ ComponentSample {+ component: Component::CefRenderer,+ process_count: 2,+ memory_bytes: 50,+ cpu_percent: 30.0,+ },+ ],+ }];+ let report = build_report(ProfileCapture {+ host_pid: 10,+ duration: Duration::from_secs(1),+ interval: Duration::from_millis(250),+ logical_cpu_count: 8,+ samples,+ rust_cpu_modules: Vec::new(),+ cpu_stack_report: None,+ cpu_stack_error: None,+ })+ .unwrap();++ assert_eq!(report.rust_binary.mean_memory_bytes, 100);+ assert_eq!(report.desktop_total.mean_memory_bytes, 150);+ assert_eq!(report.desktop_total.peak_process_count, 3);+ assert!(render_markdown(&report).contains("Tauri host + embedded Rust core"));+}++#[test]+fn parser_requires_pid_and_clamps_cpu_interval() {+ assert!(parse_args(Vec::<String>::new()).is_err());+ let args = parse_args([+ "--pid".into(),+ "123".into(),+ "--duration".into(),+ "2".into(),+ "--interval-ms".into(),+ "1".into(),+ "--no-stacks".into(),+ ])+ .unwrap();+ assert_eq!(args.pid, 123);+ assert_eq!(args.duration, Duration::from_secs(2));+ assert_eq!(args.interval, MINIMUM_CPU_UPDATE_INTERVAL);+ assert!(!args.capture_stacks);+}++#[test]+fn parses_recursive_stack_counts_into_openhuman_modules() {+ let sample = r#"+Total number in stack (recursive counted multiple, when >=5):+ 81 openhuman_core::agent::run (in OpenHuman) + 10+ 34 <openhuman_core::agent::Tool as core::future::Future>::poll (in OpenHuman) + 2+ 17 openhuman_core::memory::search (in OpenHuman) + 4+ 9 openhuman::core_process::ensure_running (in OpenHuman) + 1+ 200 tokio::runtime::park (in OpenHuman) + 3++Sort by top of stack, same collapsed (when >= 5):+"#;+ assert_eq!(+ parse_rust_module_cpu(sample),+ vec![+ RustModuleCpu {+ module: "openhuman_core::agent".into(),+ recursive_samples: 115,+ },+ RustModuleCpu {+ module: "openhuman_core::memory".into(),+ recursive_samples: 17,+ },+ RustModuleCpu {+ module: "openhuman::core_process".into(),+ recursive_samples: 9,+ },+ ]+ );+}diff --git a/crates/openhuman-app/src/app_update.rs b/crates/openhuman-app/src/app_update.rsindex edabedb962..05fef22a72 100644--- a/crates/openhuman-app/src/app_update.rs+++ b/crates/openhuman-app/src/app_update.rs@@ -68,67 +68,5 @@ pub fn is_transient_updater_err(err: &tauri_plugin_updater::Error) -> bool {}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn transient_with_attempts_left_retries() {- assert_eq!(- classify(1, MAX_DOWNLOAD_ATTEMPTS, true),- RetryDecision::Retry- );- assert_eq!(- classify(2, MAX_DOWNLOAD_ATTEMPTS, true),- RetryDecision::Retry- );- }-- #[test]- fn transient_on_last_attempt_gives_up() {- assert_eq!(- classify(MAX_DOWNLOAD_ATTEMPTS, MAX_DOWNLOAD_ATTEMPTS, true),- RetryDecision::GiveUp- );- }-- #[test]- fn transient_past_budget_gives_up() {- assert_eq!(- classify(MAX_DOWNLOAD_ATTEMPTS + 1, MAX_DOWNLOAD_ATTEMPTS, true),- RetryDecision::GiveUp- );- }-- #[test]- fn non_transient_never_retries() {- // Fatal on the very first attempt, regardless of remaining budget.- assert_eq!(- classify(1, MAX_DOWNLOAD_ATTEMPTS, false),- RetryDecision::GiveUp- );- assert_eq!(- classify(2, MAX_DOWNLOAD_ATTEMPTS, false),- RetryDecision::GiveUp- );- }-- #[test]- fn single_attempt_budget_never_retries() {- // max == 1 means no retries even for a transient error.- assert_eq!(classify(1, 1, true), RetryDecision::GiveUp);- }-- #[test]- fn backoff_is_monotonic_and_bounded() {- let b1 = backoff_for(1);- let b2 = backoff_for(2);- assert!(b2 > b1, "backoff must grow with attempt");- assert_eq!(b1, Duration::from_secs(2));- // Worst-case wait across the full budget stays small (2s + 4s = 6s).- let total: Duration = (1..MAX_DOWNLOAD_ATTEMPTS).map(backoff_for).sum();- assert!(- total <= Duration::from_secs(10),- "total backoff stays bounded"- );- }-}+#[path = "app_update_tests.rs"]+mod tests;diff --git a/crates/openhuman-app/src/app_update_tests.rs b/crates/openhuman-app/src/app_update_tests.rsnew file mode 100644index 0000000000..0940f53a26--- /dev/null+++ b/crates/openhuman-app/src/app_update_tests.rs@@ -0,0 +1,62 @@+use super::*;++#[test]+fn transient_with_attempts_left_retries() {+ assert_eq!(+ classify(1, MAX_DOWNLOAD_ATTEMPTS, true),+ RetryDecision::Retry+ );+ assert_eq!(+ classify(2, MAX_DOWNLOAD_ATTEMPTS, true),+ RetryDecision::Retry+ );+}++#[test]+fn transient_on_last_attempt_gives_up() {+ assert_eq!(+ classify(MAX_DOWNLOAD_ATTEMPTS, MAX_DOWNLOAD_ATTEMPTS, true),+ RetryDecision::GiveUp+ );+}++#[test]+fn transient_past_budget_gives_up() {+ assert_eq!(+ classify(MAX_DOWNLOAD_ATTEMPTS + 1, MAX_DOWNLOAD_ATTEMPTS, true),+ RetryDecision::GiveUp+ );+}++#[test]+fn non_transient_never_retries() {+ // Fatal on the very first attempt, regardless of remaining budget.+ assert_eq!(+ classify(1, MAX_DOWNLOAD_ATTEMPTS, false),+ RetryDecision::GiveUp+ );+ assert_eq!(+ classify(2, MAX_DOWNLOAD_ATTEMPTS, false),+ RetryDecision::GiveUp+ );+}++#[test]+fn single_attempt_budget_never_retries() {+ // max == 1 means no retries even for a transient error.+ assert_eq!(classify(1, 1, true), RetryDecision::GiveUp);+}++#[test]+fn backoff_is_monotonic_and_bounded() {+ let b1 = backoff_for(1);+ let b2 = backoff_for(2);+ assert!(b2 > b1, "backoff must grow with attempt");+ assert_eq!(b1, Duration::from_secs(2));+ // Worst-case wait across the full budget stays small (2s + 4s = 6s).+ let total: Duration = (1..MAX_DOWNLOAD_ATTEMPTS).map(backoff_for).sum();+ assert!(+ total <= Duration::from_secs(10),+ "total backoff stays bounded"+ );+}diff --git a/crates/openhuman-app/src/artifact_commands.rs b/crates/openhuman-app/src/artifact_commands.rsindex 6c04920783..157c86efc8 100644--- a/crates/openhuman-app/src/artifact_commands.rs+++ b/crates/openhuman-app/src/artifact_commands.rs@@ -184,169 +184,5 @@ fn split_stem_ext(filename: &str) -> (String, String) {}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn sanitize_rejects_path_separators() {- assert!(sanitize_filename("../etc/passwd").is_err());- assert!(sanitize_filename("a\\b.pptx").is_err());- assert!(sanitize_filename("a/b.pptx").is_err());- assert!(sanitize_filename("").is_err());- assert!(sanitize_filename(".").is_err());- assert!(sanitize_filename("..").is_err());- assert!(sanitize_filename("ok.pptx\0").is_err());- }-- #[test]- fn sanitize_accepts_plain_names() {- assert_eq!(- sanitize_filename("Quarterly Update.pptx").unwrap(),- "Quarterly Update.pptx"- );- assert_eq!(sanitize_filename(" trim me ").unwrap(), "trim me");- }-- #[test]- fn validate_source_rejects_relative_and_empty() {- assert!(validate_source("").is_err());- assert!(validate_source("relative/path.pptx").is_err());- assert!(validate_source("/definitely/not/here.pptx").is_err());- }-- #[test]- fn assert_artifact_source_accepts_file_under_artifacts_root() {- let temp = tempfile::tempdir().unwrap();- let root = temp.path();- let art = root.join("users/u1/workspace/artifacts/a-1");- std::fs::create_dir_all(&art).unwrap();- let file = art.join("deck.pptx");- std::fs::write(&file, b"x").unwrap();- assert!(assert_artifact_source(&file, root).is_ok());- }-- #[test]- fn assert_artifact_source_rejects_file_without_artifacts_component() {- let temp = tempfile::tempdir().unwrap();- let root = temp.path();- let other = root.join("users/u1/secrets");- std::fs::create_dir_all(&other).unwrap();- let file = other.join("token.txt");- std::fs::write(&file, b"x").unwrap();- assert!(assert_artifact_source(&file, root).is_err());- }-- #[test]- fn assert_artifact_source_rejects_file_outside_root() {- let root_dir = tempfile::tempdir().unwrap();- let outside_dir = tempfile::tempdir().unwrap();- // Even with an `artifacts` segment, a path outside the root is denied.- let art = outside_dir.path().join("artifacts");- std::fs::create_dir_all(&art).unwrap();- let file = art.join("evil.pptx");- std::fs::write(&file, b"x").unwrap();- assert!(assert_artifact_source(&file, root_dir.path()).is_err());- }-- #[tokio::test]- async fn copy_to_path_copies_bytes() {- let temp = tempfile::tempdir().unwrap();- let src = temp.path().join("src.pptx");- let dst = temp.path().join("dst.pptx");- std::fs::write(&src, b"deck-bytes").unwrap();- let n = copy_to_path(&src, &dst).await.unwrap();- assert_eq!(n, b"deck-bytes".len() as u64);- assert_eq!(std::fs::read(&dst).unwrap(), b"deck-bytes");- }-- #[tokio::test]- async fn download_rejects_bad_source() {- // Source validation runs before the Downloads directory is touched,- // so these resolve without writing anything.- assert!(- download_artifact_to_downloads(String::new(), "x.pptx".to_string())- .await- .is_err()- );- assert!(- download_artifact_to_downloads("relative".to_string(), "x.pptx".to_string())- .await- .is_err()- );- }-- #[test]- fn split_stem_ext_pairs() {- assert_eq!(- split_stem_ext("file.pptx"),- ("file".to_string(), "pptx".to_string())- );- assert_eq!(- split_stem_ext("noext"),- ("noext".to_string(), String::new())- );- assert_eq!(- split_stem_ext(".hidden"),- (".hidden".to_string(), String::new())- );- assert_eq!(- split_stem_ext("trailing."),- ("trailing.".to_string(), String::new())- );- assert_eq!(- split_stem_ext("a.b.c"),- ("a.b".to_string(), "c".to_string())- );- }-- #[test]- fn pick_unique_inserts_collision_suffix() {- let temp = tempfile::tempdir().unwrap();- let dir = temp.path();- let first = pick_unique_path(dir, "deck.pptx");- assert_eq!(first, dir.join("deck.pptx"));-- std::fs::write(&first, b"").unwrap();- let second = pick_unique_path(dir, "deck.pptx");- assert_eq!(second, dir.join("deck (1).pptx"));-- std::fs::write(&second, b"").unwrap();- let third = pick_unique_path(dir, "deck.pptx");- assert_eq!(third, dir.join("deck (2).pptx"));- }-- #[test]- fn pick_unique_handles_no_extension() {- let temp = tempfile::tempdir().unwrap();- let dir = temp.path();- let first = pick_unique_path(dir, "noext");- assert_eq!(first, dir.join("noext"));- std::fs::write(&first, b"").unwrap();- let second = pick_unique_path(dir, "noext");- assert_eq!(second, dir.join("noext (1)"));- }-- #[tokio::test]- async fn download_rejects_invalid_inputs() {- assert!(- download_artifact_to_downloads(String::new(), "x.pptx".to_string())- .await- .is_err()- );- assert!(- download_artifact_to_downloads("/tmp/x".to_string(), String::new())- .await- .is_err()- );- assert!(- download_artifact_to_downloads("relative".to_string(), "x.pptx".to_string())- .await- .is_err()- );- assert!(- download_artifact_to_downloads("/nope".to_string(), "../escape.pptx".to_string())- .await- .is_err()- );- }-}+#[path = "artifact_commands_tests.rs"]+mod tests;diff --git a/crates/openhuman-app/src/artifact_commands_tests.rs b/crates/openhuman-app/src/artifact_commands_tests.rsnew file mode 100644index 0000000000..f32279986d--- /dev/null+++ b/crates/openhuman-app/src/artifact_commands_tests.rs@@ -0,0 +1,164 @@+use super::*;++#[test]+fn sanitize_rejects_path_separators() {+ assert!(sanitize_filename("../etc/passwd").is_err());+ assert!(sanitize_filename("a\\b.pptx").is_err());+ assert!(sanitize_filename("a/b.pptx").is_err());+ assert!(sanitize_filename("").is_err());+ assert!(sanitize_filename(".").is_err());+ assert!(sanitize_filename("..").is_err());+ assert!(sanitize_filename("ok.pptx\0").is_err());+}++#[test]+fn sanitize_accepts_plain_names() {+ assert_eq!(+ sanitize_filename("Quarterly Update.pptx").unwrap(),+ "Quarterly Update.pptx"+ );+ assert_eq!(sanitize_filename(" trim me ").unwrap(), "trim me");+}++#[test]+fn validate_source_rejects_relative_and_empty() {+ assert!(validate_source("").is_err());+ assert!(validate_source("relative/path.pptx").is_err());+ assert!(validate_source("/definitely/not/here.pptx").is_err());+}++#[test]+fn assert_artifact_source_accepts_file_under_artifacts_root() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path();+ let art = root.join("users/u1/workspace/artifacts/a-1");+ std::fs::create_dir_all(&art).unwrap();+ let file = art.join("deck.pptx");+ std::fs::write(&file, b"x").unwrap();+ assert!(assert_artifact_source(&file, root).is_ok());+}++#[test]+fn assert_artifact_source_rejects_file_without_artifacts_component() {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path();+ let other = root.join("users/u1/secrets");+ std::fs::create_dir_all(&other).unwrap();+ let file = other.join("token.txt");+ std::fs::write(&file, b"x").unwrap();+ assert!(assert_artifact_source(&file, root).is_err());+}++#[test]+fn assert_artifact_source_rejects_file_outside_root() {+ let root_dir = tempfile::tempdir().unwrap();+ let outside_dir = tempfile::tempdir().unwrap();+ // Even with an `artifacts` segment, a path outside the root is denied.+ let art = outside_dir.path().join("artifacts");+ std::fs::create_dir_all(&art).unwrap();+ let file = art.join("evil.pptx");+ std::fs::write(&file, b"x").unwrap();+ assert!(assert_artifact_source(&file, root_dir.path()).is_err());+}++#[tokio::test]+async fn copy_to_path_copies_bytes() {+ let temp = tempfile::tempdir().unwrap();+ let src = temp.path().join("src.pptx");+ let dst = temp.path().join("dst.pptx");+ std::fs::write(&src, b"deck-bytes").unwrap();+ let n = copy_to_path(&src, &dst).await.unwrap();+ assert_eq!(n, b"deck-bytes".len() as u64);+ assert_eq!(std::fs::read(&dst).unwrap(), b"deck-bytes");+}++#[tokio::test]+async fn download_rejects_bad_source() {+ // Source validation runs before the Downloads directory is touched,+ // so these resolve without writing anything.+ assert!(+ download_artifact_to_downloads(String::new(), "x.pptx".to_string())+ .await+ .is_err()+ );+ assert!(+ download_artifact_to_downloads("relative".to_string(), "x.pptx".to_string())+ .await+ .is_err()+ );+}++#[test]+fn split_stem_ext_pairs() {+ assert_eq!(+ split_stem_ext("file.pptx"),+ ("file".to_string(), "pptx".to_string())+ );+ assert_eq!(+ split_stem_ext("noext"),+ ("noext".to_string(), String::new())+ );+ assert_eq!(+ split_stem_ext(".hidden"),+ (".hidden".to_string(), String::new())+ );+ assert_eq!(+ split_stem_ext("trailing."),+ ("trailing.".to_string(), String::new())+ );+ assert_eq!(+ split_stem_ext("a.b.c"),+ ("a.b".to_string(), "c".to_string())+ );+}++#[test]+fn pick_unique_inserts_collision_suffix() {+ let temp = tempfile::tempdir().unwrap();+ let dir = temp.path();+ let first = pick_unique_path(dir, "deck.pptx");+ assert_eq!(first, dir.join("deck.pptx"));++ std::fs::write(&first, b"").unwrap();+ let second = pick_unique_path(dir, "deck.pptx");+ assert_eq!(second, dir.join("deck (1).pptx"));++ std::fs::write(&second, b"").unwrap();+ let third = pick_unique_path(dir, "deck.pptx");+ assert_eq!(third, dir.join("deck (2).pptx"));+}++#[test]+fn pick_unique_handles_no_extension() {+ let temp = tempfile::tempdir().unwrap();+ let dir = temp.path();+ let first = pick_unique_path(dir, "noext");+ assert_eq!(first, dir.join("noext"));+ std::fs::write(&first, b"").unwrap();+ let second = pick_unique_path(dir, "noext");+ assert_eq!(second, dir.join("noext (1)"));+}++#[tokio::test]+async fn download_rejects_invalid_inputs() {+ assert!(+ download_artifact_to_downloads(String::new(), "x.pptx".to_string())+ .await+ .is_err()+ );+ assert!(+ download_artifact_to_downloads("/tmp/x".to_string(), String::new())+ .await+ .is_err()+ );+ assert!(+ download_artifact_to_downloads("relative".to_string(), "x.pptx".to_string())+ .await+ .is_err()+ );+ assert!(+ download_artifact_to_downloads("/nope".to_string(), "../escape.pptx".to_string())+ .await+ .is_err()+ );+}diff --git a/crates/openhuman-app/src/claude_code.rs b/crates/openhuman-app/src/claude_code.rsindex 8f7be5269b..7aea56a008 100644--- a/crates/openhuman-app/src/claude_code.rs+++ b/crates/openhuman-app/src/claude_code.rs@@ -142,81 +142,5 @@ pub fn claude_code_login_launch() -> Result<String, String> {}#[cfg(test)]-mod tests {- use super::*;-- /// Every launcher must reach the `auth` subcommand. `claude login` is not a- /// command — `claude` takes a positional `[prompt]`, so it silently became a- /// prompt instead of starting the OAuth flow.- fn assert_reaches_auth_login(rendered: &str, what: &str) {- assert!(- rendered.contains("claude auth login"),- "{what} must invoke `claude auth login`, got: {rendered}"- );- assert!(- !rendered.contains("claude login"),- "{what} still constructs the obsolete `claude login`, got: {rendered}"- );- }-- #[test]- fn login_command_line_is_the_auth_subcommand() {- assert_eq!(login_command_line(), "claude auth login --claudeai");- }-- #[test]- fn argv_keeps_auth_and_login_as_separate_words() {- // Split-argument terminals pass these straight to execvp, so `auth` and- // `login` have to be distinct argv entries rather than one "auth login".- assert_eq!(- CLAUDE_LOGIN_ARGV,- &["claude", "auth", "login", "--claudeai"]- );- }-- #[test]- fn windows_launcher_reaches_auth_login() {- assert_reaches_auth_login(&windows_launch_args().join(" "), "the Windows launcher");- }-- #[test]- fn windows_launcher_keeps_the_empty_start_title() {- // `start` reads a bare first argument as the window title, which would- // swallow `cmd` and open an empty shell.- let args = windows_launch_args();- assert_eq!(args[1], "start");- assert_eq!(args[2], "", "the empty title placeholder must survive");- }-- #[test]- fn macos_launcher_reaches_auth_login() {- assert_reaches_auth_login(&macos_launch_script(), "the macOS AppleScript");- }-- #[test]- fn macos_script_quotes_the_command_for_do_script() {- assert!(macos_launch_script().contains(r#"do script "claude auth login --claudeai""#));- }-- #[test]- fn every_linux_candidate_reaches_auth_login() {- let candidates = linux_launch_candidates();- assert_eq!(candidates.len(), 5, "all five emulators stay covered");- for (term, args) in candidates {- assert_reaches_auth_login(&args.join(" "), term);- }- }-- #[test]- fn xfce4_terminal_gets_one_string_and_the_others_get_argv() {- let candidates = linux_launch_candidates();- for (term, args) in candidates {- match term {- // -e plus a single command string- "xfce4-terminal" => assert_eq!(args.len(), 2, "xfce4-terminal takes one string"),- // separator plus four argv words- _ => assert_eq!(args.len(), 5, "{term} takes the command as argv"),- }- }- }-}+#[path = "claude_code_tests.rs"]+mod tests;diff --git a/crates/openhuman-app/src/claude_code_tests.rs b/crates/openhuman-app/src/claude_code_tests.rsnew file mode 100644index 0000000000..f1401eef0c--- /dev/null+++ b/crates/openhuman-app/src/claude_code_tests.rs@@ -0,0 +1,76 @@+use super::*;++/// Every launcher must reach the `auth` subcommand. `claude login` is not a+/// command — `claude` takes a positional `[prompt]`, so it silently became a+/// prompt instead of starting the OAuth flow.+fn assert_reaches_auth_login(rendered: &str, what: &str) {+ assert!(+ rendered.contains("claude auth login"),+ "{what} must invoke `claude auth login`, got: {rendered}"+ );+ assert!(+ !rendered.contains("claude login"),+ "{what} still constructs the obsolete `claude login`, got: {rendered}"+ );+}++#[test]+fn login_command_line_is_the_auth_subcommand() {+ assert_eq!(login_command_line(), "claude auth login --claudeai");+}++#[test]+fn argv_keeps_auth_and_login_as_separate_words() {+ // Split-argument terminals pass these straight to execvp, so `auth` and+ // `login` have to be distinct argv entries rather than one "auth login".+ assert_eq!(+ CLAUDE_LOGIN_ARGV,+ &["claude", "auth", "login", "--claudeai"]+ );+}++#[test]+fn windows_launcher_reaches_auth_login() {+ assert_reaches_auth_login(&windows_launch_args().join(" "), "the Windows launcher");+}++#[test]+fn windows_launcher_keeps_the_empty_start_title() {+ // `start` reads a bare first argument as the window title, which would+ // swallow `cmd` and open an empty shell.+ let args = windows_launch_args();+ assert_eq!(args[1], "start");+ assert_eq!(args[2], "", "the empty title placeholder must survive");+}++#[test]+fn macos_launcher_reaches_auth_login() {+ assert_reaches_auth_login(&macos_launch_script(), "the macOS AppleScript");+}++#[test]+fn macos_script_quotes_the_command_for_do_script() {+ assert!(macos_launch_script().contains(r#"do script "claude auth login --claudeai""#));+}++#[test]+fn every_linux_candidate_reaches_auth_login() {+ let candidates = linux_launch_candidates();+ assert_eq!(candidates.len(), 5, "all five emulators stay covered");+ for (term, args) in candidates {+ assert_reaches_auth_login(&args.join(" "), term);+ }+}++#[test]+fn xfce4_terminal_gets_one_string_and_the_others_get_argv() {+ let candidates = linux_launch_candidates();+ for (term, args) in candidates {+ match term {+ // -e plus a single command string+ "xfce4-terminal" => assert_eq!(args.len(), 2, "xfce4-terminal takes one string"),+ // separator plus four argv words+ _ => assert_eq!(args.len(), 5, "{term} takes the command as argv"),+ }+ }+}diff --git a/crates/openhuman-app/src/core_rpc.rs b/crates/openhuman-app/src/core_rpc.rsindex 4ec3132ac2..32729dbfa2 100644--- a/crates/openhuman-app/src/core_rpc.rs+++ b/crates/openhuman-app/src/core_rpc.rs@@ -77,77 +77,5 @@ pub(crate) async fn post_json_rpc(}#[cfg(test)]-mod tests {- use super::redact_url_for_log;- use super::relay_bearer_header;-- #[test]- fn bearer_header_present_for_real_token() {- assert_eq!(- relay_bearer_header(Some("tok123")).as_deref(),- Some("Bearer tok123")- );- // Surrounding whitespace is trimmed before formatting.- assert_eq!(- relay_bearer_header(Some(" tok123 ")).as_deref(),- Some("Bearer tok123")- );- }-- #[test]- fn bearer_header_absent_for_missing_or_blank_token() {- assert_eq!(relay_bearer_header(None), None);- assert_eq!(relay_bearer_header(Some("")), None);- assert_eq!(relay_bearer_header(Some(" ")), None);- }-- #[test]- fn redact_strips_credentials_query_and_path() {- // Userinfo, query, fragment, and path must not survive into logs; only- // the scheme://host[:port] surface is kept for transport diagnostics.- assert_eq!(- redact_url_for_log("http://user:[email protected]:7788/rpc/secret?token=t0k#frag"),- "http://192.168.1.74:7788/"- );- assert_eq!(- redact_url_for_log("https://core.example.com/rpc"),- "https://core.example.com/"- );- // An unparseable URL degrades to the coarse sentinel.- assert_eq!(redact_url_for_log("not a url"), "<invalid relay url>");- }-- /// A non-loopback `http` URL carrying a bearer must be refused, and the- /// surfaced error must carry the redacted `scheme://host[:port]` form —- /// never the raw secret-bearing userinfo, path, or query (CWE-532).- #[cfg(feature = "gateways")]- #[tokio::test]- async fn insecure_transport_refusal_redacts_url() {- let err = match super::post_json_rpc(- "http://user:[email protected]:7788/rpc/secret?token=t0k",- Some("bearer-tok"),- "body".to_string(),- )- .await- {- Err(e) => e,- Ok(_) => panic!("insecure non-loopback + bearer must be refused"),- };- assert!(- !err.contains("pass"),- "raw userinfo leaked into refusal error: {err}"- );- assert!(- !err.contains("t0k"),- "raw query token leaked into refusal error: {err}"- );- assert!(- !err.contains("/secret"),- "raw path leaked into refusal error: {err}"- );- assert!(- err.contains("http://192.168.1.74:7788/"),- "redacted host should remain for diagnostics: {err}"- );- }-}+#[path = "core_rpc_tests.rs"]+mod tests;diff --git a/crates/openhuman-app/src/core_rpc_tests.rs b/crates/openhuman-app/src/core_rpc_tests.rsnew file mode 100644index 0000000000..10b4f5223d--- /dev/null+++ b/crates/openhuman-app/src/core_rpc_tests.rs@@ -0,0 +1,72 @@+use super::redact_url_for_log;+use super::relay_bearer_header;++#[test]+fn bearer_header_present_for_real_token() {+ assert_eq!(+ relay_bearer_header(Some("tok123")).as_deref(),+ Some("Bearer tok123")+ );+ // Surrounding whitespace is trimmed before formatting.+ assert_eq!(+ relay_bearer_header(Some(" tok123 ")).as_deref(),+ Some("Bearer tok123")+ );+}++#[test]+fn bearer_header_absent_for_missing_or_blank_token() {+ assert_eq!(relay_bearer_header(None), None);+ assert_eq!(relay_bearer_header(Some("")), None);+ assert_eq!(relay_bearer_header(Some(" ")), None);+}++#[test]+fn redact_strips_credentials_query_and_path() {+ // Userinfo, query, fragment, and path must not survive into logs; only+ // the scheme://host[:port] surface is kept for transport diagnostics.+ assert_eq!(+ redact_url_for_log("http://user:[email protected]:7788/rpc/secret?token=t0k#frag"),+ "http://192.168.1.74:7788/"+ );+ assert_eq!(+ redact_url_for_log("https://core.example.com/rpc"),+ "https://core.example.com/"+ );+ // An unparseable URL degrades to the coarse sentinel.+ assert_eq!(redact_url_for_log("not a url"), "<invalid relay url>");+}++/// A non-loopback `http` URL carrying a bearer must be refused, and the+/// surfaced error must carry the redacted `scheme://host[:port]` form —+/// never the raw secret-bearing userinfo, path, or query (CWE-532).+#[cfg(feature = "gateways")]+#[tokio::test]+async fn insecure_transport_refusal_redacts_url() {+ let err = match super::post_json_rpc(+ "http://user:[email protected]:7788/rpc/secret?token=t0k",+ Some("bearer-tok"),+ "body".to_string(),+ )+ .await+ {+ Err(e) => e,+ Ok(_) => panic!("insecure non-loopback + bearer must be refused"),+ };+ assert!(+ !err.contains("pass"),+ "raw userinfo leaked into refusal error: {err}"+ );+ assert!(+ !err.contains("t0k"),+ "raw query token leaked into refusal error: {err}"+ );+ assert!(+ !err.contains("/secret"),+ "raw path leaked into refusal error: {err}"+ );+ assert!(+ err.contains("http://192.168.1.74:7788/"),+ "redacted host should remain for diagnostics: {err}"+ );+}diff --git a/crates/openhuman-app/src/deep_link_ipc.rs b/crates/openhuman-app/src/deep_link_ipc.rsindex 7d1b25d94b..26e3c99913 100644--- a/crates/openhuman-app/src/deep_link_ipc.rs+++ b/crates/openhuman-app/src/deep_link_ipc.rs@@ -336,155 +336,5 @@ pub(crate) fn drain_pending_urls<R: tauri::Runtime>(app: &tauri::AppHandle<R>) {}#[cfg(test)]-mod tests {- use super::*;- use std::io::{self, Write};-- struct FailingWriter {- remaining: usize,- }-- impl Write for FailingWriter {- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {- if self.remaining == 0 {- return Err(io::Error::new(- io::ErrorKind::BrokenPipe,- "test broken pipe",- ));- }-- let written = buf.len().min(self.remaining);- self.remaining -= written;- Ok(written)- }-- fn flush(&mut self) -> io::Result<()> {- Ok(())- }- }-- #[test]- fn socket_path_uses_xdg_runtime_dir() {- std::env::set_var("XDG_RUNTIME_DIR", "/run/user/1234");- let path = socket_path();- assert_eq!(- path,- PathBuf::from("/run/user/1234/com.openhuman.app-deeplink.sock")- );- }-- #[test]- fn socket_path_fallback_has_uid() {- std::env::remove_var("XDG_RUNTIME_DIR");- let path = socket_path();- let name = path.file_name().unwrap().to_string_lossy();- assert!(- name.contains("com_openhuman_app_deeplink"),- "path {path:?} should contain identifier"- );- // Should NOT be inside /run/user since XDG_RUNTIME_DIR is unset.- assert!(- !path.starts_with("/run/user"),- "path should use temp_dir fallback"- );- }-- #[test]- fn extract_deep_link_urls_filters_correctly() {- // Exercise the REAL production filter through the args-slice seam- // (mirrors the Windows sibling test) instead of re-implementing the- // predicate inline — so a regression in the filter actually fails here.- let urls = collect_deep_link_urls_from_args([- "OpenHuman",- "openhuman://auth?token=abc",- "--some-flag",- "openhuman://other",- "https://example.com",- ]);- assert_eq!(- urls,- vec!["openhuman://auth?token=abc", "openhuman://other"]- );- }-- #[test]- fn write_urls_reports_broken_pipe_after_partial_write() {- let urls = vec!["openhuman://auth?token=test".to_string()];- let mut writer = FailingWriter { remaining: 5 };-- let result = write_urls(&mut writer, &urls);-- assert_eq!(result.unwrap_err().kind(), io::ErrorKind::BrokenPipe);- }-- #[test]- fn write_urls_writes_all_urls_with_newlines() {- let urls = vec![- "openhuman://auth?token=first".to_string(),- "openhuman://auth?token=second".to_string(),- ];- let mut writer = Vec::new();-- write_urls(&mut writer, &urls).unwrap();-- assert_eq!(- writer,- b"openhuman://auth?token=first\nopenhuman://auth?token=second\n"- );- }-- #[test]- fn failed_forward_is_not_reported_as_forwarded() {- let urls = vec!["openhuman://auth?token=test".to_string()];- let mut writer = FailingWriter { remaining: 5 };-- let result = forward_connected_stream(&mut writer, &urls);-- assert!(matches!(result, ForwardResult::ForwardFailed));- }-- #[test]- fn no_primary_returns_no_primary() {- let tmp = tempfile::TempDir::new().unwrap();- let sock_path = tmp.path().join("missing-deeplink.sock");- let urls = vec!["openhuman://auth?token=test".to_string()];-- let result = try_forward_urls(&urls, &sock_path);-- assert!(matches!(result, ForwardResult::NoPrimary));- }-- #[test]- fn round_trip_bind_connect_forward() {- use std::io::BufRead;-- // Use a temp path for this test to avoid collisions.- let tmp = tempfile::TempDir::new().unwrap();- let sock_path = tmp.path().join("test-deeplink.sock");-- let listener = UnixListener::bind(&sock_path).unwrap();- let received = Arc::new(Mutex::new(Vec::<String>::new()));- let received_clone = Arc::clone(&received);-- std::thread::spawn(move || {- if let Ok(stream) = listener.accept().map(|(s, _)| s) {- stream.set_read_timeout(Some(Duration::from_secs(2))).ok();- let reader = BufReader::new(stream);- for line in reader.lines().flatten() {- if line.starts_with("openhuman://") {- received_clone.lock().unwrap().push(line);- }- }- }- });-- let urls = vec!["openhuman://auth?token=testtoken123".to_string()];- let result = try_forward_urls(&urls, &sock_path);- assert!(matches!(result, ForwardResult::Forwarded));-- std::thread::sleep(Duration::from_millis(100));- let got = received.lock().unwrap();- assert_eq!(got.len(), 1);- assert_eq!(got[0], "openhuman://auth?token=testtoken123");- }-}+#[path = "deep_link_ipc_tests.rs"]+mod tests;diff --git a/crates/openhuman-app/src/deep_link_ipc_tests.rs b/crates/openhuman-app/src/deep_link_ipc_tests.rsnew file mode 100644index 0000000000..6cf2a707a6--- /dev/null+++ b/crates/openhuman-app/src/deep_link_ipc_tests.rs@@ -0,0 +1,150 @@+use super::*;+use std::io::{self, Write};++struct FailingWriter {+ remaining: usize,+}++impl Write for FailingWriter {+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {+ if self.remaining == 0 {+ return Err(io::Error::new(+ io::ErrorKind::BrokenPipe,+ "test broken pipe",+ ));+ }++ let written = buf.len().min(self.remaining);+ self.remaining -= written;+ Ok(written)+ }++ fn flush(&mut self) -> io::Result<()> {+ Ok(())+ }+}++#[test]+fn socket_path_uses_xdg_runtime_dir() {+ std::env::set_var("XDG_RUNTIME_DIR", "/run/user/1234");+ let path = socket_path();+ assert_eq!(+ path,+ PathBuf::from("/run/user/1234/com.openhuman.app-deeplink.sock")+ );+}++#[test]+fn socket_path_fallback_has_uid() {+ std::env::remove_var("XDG_RUNTIME_DIR");+ let path = socket_path();+ let name = path.file_name().unwrap().to_string_lossy();+ assert!(+ name.contains("com_openhuman_app_deeplink"),+ "path {path:?} should contain identifier"+ );+ // Should NOT be inside /run/user since XDG_RUNTIME_DIR is unset.+ assert!(+ !path.starts_with("/run/user"),+ "path should use temp_dir fallback"+ );+}++#[test]+fn extract_deep_link_urls_filters_correctly() {+ // Exercise the REAL production filter through the args-slice seam+ // (mirrors the Windows sibling test) instead of re-implementing the+ // predicate inline — so a regression in the filter actually fails here.+ let urls = collect_deep_link_urls_from_args([+ "OpenHuman",+ "openhuman://auth?token=abc",+ "--some-flag",+ "openhuman://other",+ "https://example.com",+ ]);+ assert_eq!(+ urls,+ vec!["openhuman://auth?token=abc", "openhuman://other"]+ );+}++#[test]+fn write_urls_reports_broken_pipe_after_partial_write() {+ let urls = vec!["openhuman://auth?token=test".to_string()];+ let mut writer = FailingWriter { remaining: 5 };++ let result = write_urls(&mut writer, &urls);++ assert_eq!(result.unwrap_err().kind(), io::ErrorKind::BrokenPipe);+}++#[test]+fn write_urls_writes_all_urls_with_newlines() {+ let urls = vec![+ "openhuman://auth?token=first".to_string(),+ "openhuman://auth?token=second".to_string(),+ ];+ let mut writer = Vec::new();++ write_urls(&mut writer, &urls).unwrap();++ assert_eq!(+ writer,+ b"openhuman://auth?token=first\nopenhuman://auth?token=second\n"+ );+}++#[test]+fn failed_forward_is_not_reported_as_forwarded() {+ let urls = vec!["openhuman://auth?token=test".to_string()];+ let mut writer = FailingWriter { remaining: 5 };++ let result = forward_connected_stream(&mut writer, &urls);++ assert!(matches!(result, ForwardResult::ForwardFailed));+}++#[test]+fn no_primary_returns_no_primary() {+ let tmp = tempfile::TempDir::new().unwrap();+ let sock_path = tmp.path().join("missing-deeplink.sock");+ let urls = vec!["openhuman://auth?token=test".to_string()];++ let result = try_forward_urls(&urls, &sock_path);++ assert!(matches!(result, ForwardResult::NoPrimary));+}++#[test]+fn round_trip_bind_connect_forward() {+ use std::io::BufRead;++ // Use a temp path for this test to avoid collisions.+ let tmp = tempfile::TempDir::new().unwrap();+ let sock_path = tmp.path().join("test-deeplink.sock");++ let listener = UnixListener::bind(&sock_path).unwrap();+ let received = Arc::new(Mutex::new(Vec::<String>::new()));+ let received_clone = Arc::clone(&received);++ std::thread::spawn(move || {+ if let Ok(stream) = listener.accept().map(|(s, _)| s) {+ stream.set_read_timeout(Some(Duration::from_secs(2))).ok();+ let reader = BufReader::new(stream);+ for line in reader.lines().flatten() {+ if line.starts_with("openhuman://") {+ received_clone.lock().unwrap().push(line);+ }+ }+ }+ });++ let urls = vec!["openhuman://auth?token=testtoken123".to_string()];+ let result = try_forward_urls(&urls, &sock_path);+ assert!(matches!(result, ForwardResult::Forwarded));++ std::thread::sleep(Duration::from_millis(100));+ let got = received.lock().unwrap();+ assert_eq!(got.len(), 1);+ assert_eq!(got[0], "openhuman://auth?token=testtoken123");+}diff --git a/crates/openhuman-app/src/deep_link_ipc_windows.rs b/crates/openhuman-app/src/deep_link_ipc_windows.rsindex 8880d82b0b..8272c88a54 100644--- a/crates/openhuman-app/src/deep_link_ipc_windows.rs+++ b/crates/openhuman-app/src/deep_link_ipc_windows.rs@@ -339,38 +339,5 @@ pub(crate) fn drain_pending_urls<R: tauri::Runtime>(app: &tauri::AppHandle<R>) {}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn collect_deep_link_urls_filters_args() {- let urls = collect_deep_link_urls_from_args([- "OpenHuman.exe",- "openhuman://auth?token=secret&key=auth",- "--flag",- "https://example.test",- "openhuman://oauth/success?integrationId=abc",- ]);-- assert_eq!(- urls,- vec![- "openhuman://auth?token=secret&key=auth",- "openhuman://oauth/success?integrationId=abc"- ]- );- }-- #[test]- fn redact_url_removes_query_and_fragment() {- assert_eq!(- redact_url_for_log("openhuman://auth?token=secret&key=auth#frag"),- "openhuman://auth"- );- }-- #[test]- fn pipe_name_is_stable_and_app_scoped() {- assert_eq!(PIPE_NAME, r"\\.\pipe\com.openhuman.app-deeplink");- }-}+#[path = "deep_link_ipc_windows_tests.rs"]+mod tests;diff --git a/crates/openhuman-app/src/deep_link_ipc_windows_tests.rs b/crates/openhuman-app/src/deep_link_ipc_windows_tests.rsnew file mode 100644index 0000000000..9674f3aa2c--- /dev/null+++ b/crates/openhuman-app/src/deep_link_ipc_windows_tests.rs@@ -0,0 +1,33 @@+use super::*;++#[test]+fn collect_deep_link_urls_filters_args() {+ let urls = collect_deep_link_urls_from_args([+ "OpenHuman.exe",+ "openhuman://auth?token=secret&key=auth",+ "--flag",+ "https://example.test",+ "openhuman://oauth/success?integrationId=abc",+ ]);++ assert_eq!(+ urls,+ vec![+ "openhuman://auth?token=secret&key=auth",+ "openhuman://oauth/success?integrationId=abc"+ ]+ );+}++#[test]+fn redact_url_removes_query_and_fragment() {+ assert_eq!(+ redact_url_for_log("openhuman://auth?token=secret&key=auth#frag"),+ "openhuman://auth"+ );+}++#[test]+fn pipe_name_is_stable_and_app_scoped() {+ assert_eq!(PIPE_NAME, r"\\.\pipe\com.openhuman.app-deeplink");+}diff --git a/crates/openhuman-app/src/deep_link_registration_check.rs b/crates/openhuman-app/src/deep_link_registration_check.rsindex 51cab0ab2f..bb5f2f0e46 100644--- a/crates/openhuman-app/src/deep_link_registration_check.rs+++ b/crates/openhuman-app/src/deep_link_registration_check.rs@@ -283,177 +283,5 @@ pub(crate) fn verify_protocol_registration() -> RegistrationStatus {}#[cfg(test)]-mod tests {- use super::*;- use std::path::PathBuf;-- #[test]- fn extract_first_token_quoted_exe_with_args() {- assert_eq!(- extract_first_token("\"C:\\Program Files\\OpenHuman\\OpenHuman.exe\" \"%1\""),- "C:\\Program Files\\OpenHuman\\OpenHuman.exe"- );- }-- #[test]- fn extract_first_token_unquoted_exe_with_args() {- assert_eq!(- extract_first_token("C:\\OpenHuman\\OpenHuman.exe %1"),- "C:\\OpenHuman\\OpenHuman.exe"- );- }-- #[test]- fn extract_first_token_handles_leading_whitespace() {- assert_eq!(- extract_first_token(" C:\\OpenHuman\\OpenHuman.exe %1"),- "C:\\OpenHuman\\OpenHuman.exe"- );- }-- #[test]- fn extract_first_token_single_value_no_args() {- assert_eq!(extract_first_token("OpenHuman.exe"), "OpenHuman.exe");- }-- #[test]- fn extract_first_token_empty_string() {- // Defensive guard: an empty REG_SZ value must not panic. The caller- // (`verify_protocol_registration`) classifies this as `MissingCommand`- // before reaching the parser, but the parser itself stays total.- assert_eq!(extract_first_token(""), "");- }-- #[test]- fn extract_first_token_quoted_exe_with_no_trailing_args() {- // Some installers register the command without the `"%1"` argv- // placeholder. The first token is still the quoted exe path.- assert_eq!(- extract_first_token("\"C:\\OpenHuman\\OpenHuman.exe\""),- "C:\\OpenHuman\\OpenHuman.exe"- );- }-- #[test]- fn extract_first_token_unterminated_quote_falls_through() {- // Defensive: malformed REG_SZ should not panic. We return the rest of- // the string instead of slicing past a missing terminator.- assert_eq!(- extract_first_token("\"C:\\OpenHuman\\OpenHuman.exe %1"),- "C:\\OpenHuman\\OpenHuman.exe %1"- );- }-- #[test]- fn paths_equal_loose_is_case_insensitive_and_slash_agnostic() {- assert!(paths_equal_loose(- "C:\\Program Files\\OpenHuman\\OpenHuman.exe",- "c:/program files/openhuman/openhuman.exe"- ));- }-- #[test]- fn paths_equal_loose_distinguishes_different_paths() {- assert!(!paths_equal_loose(- "C:\\OldPath\\OpenHuman.exe",- "C:\\NewPath\\OpenHuman.exe"- ));- }-- #[test]- fn command_references_exe_matches_quoted_command_with_percent_one() {- let exe = PathBuf::from("C:\\Program Files\\OpenHuman\\OpenHuman.exe");- assert!(command_references_exe(- "\"C:\\Program Files\\OpenHuman\\OpenHuman.exe\" \"%1\"",- &exe- ));- }-- #[test]- fn command_references_exe_matches_unquoted_command() {- // Some HKCU writers omit the quotes when the path has no spaces. The- // matcher must still resolve to the exe via the unquoted code path in- // `extract_first_token` rather than relying only on the quoted path.- let exe = PathBuf::from("C:\\OpenHuman\\OpenHuman.exe");- assert!(command_references_exe(- "C:\\OpenHuman\\OpenHuman.exe %1",- &exe- ));- }-- #[test]- fn command_references_exe_detects_stale_install_path() {- // Repro of the "user moved the install" failure mode: registry still- // points at the old location.- let exe = PathBuf::from("C:\\NewLocation\\OpenHuman.exe");- assert!(!command_references_exe(- "\"C:\\OldLocation\\OpenHuman.exe\" \"%1\"",- &exe- ));- }-- #[test]- fn redacted_drops_directory_components_for_stale_paths() {- // Reproduce the Sentry-leak case: a Stale status carrying the running- // user's home directory must produce a log line that contains the- // exe basenames but neither the username nor the parent dirs.- let status = RegistrationStatus::Stale {- registered_command:- "\"C:\\Users\\joe\\AppData\\Local\\OpenHuman\\OpenHuman.exe\" \"%1\"".into(),- expected_exe: "C:\\Users\\joe\\AppData\\Local\\OpenHuman_new\\OpenHuman.exe".into(),- };- let rendered = status.redacted();- assert!(- rendered.contains("OpenHuman.exe"),- "basename should survive redaction: {rendered}"- );- assert!(- !rendered.contains("joe"),- "username must not leak: {rendered}"- );- assert!(- !rendered.contains("AppData"),- "directory path must not leak: {rendered}"- );- }-- #[test]- fn redacted_preserves_valid_variant_label_and_basename() {- let status = RegistrationStatus::Valid {- command: "\"C:\\Program Files\\OpenHuman\\OpenHuman.exe\" \"%1\"".into(),- };- assert_eq!(status.redacted(), "Valid { exe: OpenHuman.exe }");- }-- #[test]- fn redacted_passes_through_pathless_variants() {- assert_eq!(- RegistrationStatus::MissingCommand.redacted(),- "MissingCommand"- );- assert_eq!(- RegistrationStatus::NotRegistered.redacted(),- "NotRegistered"- );- assert_eq!(- RegistrationStatus::ReadError("win32 error 5".into()).redacted(),- "ReadError(win32 error 5)"- );- }-- #[test]- fn is_healthy_only_for_valid_variant() {- assert!(RegistrationStatus::Valid {- command: "x".into()- }- .is_healthy());- assert!(!RegistrationStatus::MissingCommand.is_healthy());- assert!(!RegistrationStatus::NotRegistered.is_healthy());- assert!(!RegistrationStatus::Stale {- registered_command: "x".into(),- expected_exe: "y".into()- }- .is_healthy());- assert!(!RegistrationStatus::ReadError("foo".into()).is_healthy());- }-}+#[path = "deep_link_registration_check_tests.rs"]+mod tests;diff --git a/crates/openhuman-app/src/deep_link_registration_check_tests.rs b/crates/openhuman-app/src/deep_link_registration_check_tests.rsnew file mode 100644index 0000000000..0acabfcdce--- /dev/null+++ b/crates/openhuman-app/src/deep_link_registration_check_tests.rs@@ -0,0 +1,172 @@+use super::*;+use std::path::PathBuf;++#[test]+fn extract_first_token_quoted_exe_with_args() {+ assert_eq!(+ extract_first_token("\"C:\\Program Files\\OpenHuman\\OpenHuman.exe\" \"%1\""),+ "C:\\Program Files\\OpenHuman\\OpenHuman.exe"+ );+}++#[test]+fn extract_first_token_unquoted_exe_with_args() {+ assert_eq!(+ extract_first_token("C:\\OpenHuman\\OpenHuman.exe %1"),+ "C:\\OpenHuman\\OpenHuman.exe"+ );+}++#[test]+fn extract_first_token_handles_leading_whitespace() {+ assert_eq!(+ extract_first_token(" C:\\OpenHuman\\OpenHuman.exe %1"),+ "C:\\OpenHuman\\OpenHuman.exe"+ );+}++#[test]+fn extract_first_token_single_value_no_args() {+ assert_eq!(extract_first_token("OpenHuman.exe"), "OpenHuman.exe");+}++#[test]+fn extract_first_token_empty_string() {+ // Defensive guard: an empty REG_SZ value must not panic. The caller+ // (`verify_protocol_registration`) classifies this as `MissingCommand`+ // before reaching the parser, but the parser itself stays total.+ assert_eq!(extract_first_token(""), "");+}++#[test]+fn extract_first_token_quoted_exe_with_no_trailing_args() {+ // Some installers register the command without the `"%1"` argv+ // placeholder. The first token is still the quoted exe path.+ assert_eq!(+ extract_first_token("\"C:\\OpenHuman\\OpenHuman.exe\""),+ "C:\\OpenHuman\\OpenHuman.exe"+ );+}++#[test]+fn extract_first_token_unterminated_quote_falls_through() {+ // Defensive: malformed REG_SZ should not panic. We return the rest of+ // the string instead of slicing past a missing terminator.+ assert_eq!(+ extract_first_token("\"C:\\OpenHuman\\OpenHuman.exe %1"),+ "C:\\OpenHuman\\OpenHuman.exe %1"+ );+}++#[test]+fn paths_equal_loose_is_case_insensitive_and_slash_agnostic() {+ assert!(paths_equal_loose(+ "C:\\Program Files\\OpenHuman\\OpenHuman.exe",+ "c:/program files/openhuman/openhuman.exe"+ ));+}++#[test]+fn paths_equal_loose_distinguishes_different_paths() {+ assert!(!paths_equal_loose(+ "C:\\OldPath\\OpenHuman.exe",+ "C:\\NewPath\\OpenHuman.exe"+ ));+}++#[test]+fn command_references_exe_matches_quoted_command_with_percent_one() {+ let exe = PathBuf::from("C:\\Program Files\\OpenHuman\\OpenHuman.exe");+ assert!(command_references_exe(+ "\"C:\\Program Files\\OpenHuman\\OpenHuman.exe\" \"%1\"",+ &exe+ ));+}++#[test]+fn command_references_exe_matches_unquoted_command() {+ // Some HKCU writers omit the quotes when the path has no spaces. The+ // matcher must still resolve to the exe via the unquoted code path in+ // `extract_first_token` rather than relying only on the quoted path.+ let exe = PathBuf::from("C:\\OpenHuman\\OpenHuman.exe");+ assert!(command_references_exe(+ "C:\\OpenHuman\\OpenHuman.exe %1",+ &exe+ ));+}++#[test]+fn command_references_exe_detects_stale_install_path() {+ // Repro of the "user moved the install" failure mode: registry still+ // points at the old location.+ let exe = PathBuf::from("C:\\NewLocation\\OpenHuman.exe");+ assert!(!command_references_exe(+ "\"C:\\OldLocation\\OpenHuman.exe\" \"%1\"",+ &exe+ ));+}++#[test]+fn redacted_drops_directory_components_for_stale_paths() {+ // Reproduce the Sentry-leak case: a Stale status carrying the running+ // user's home directory must produce a log line that contains the+ // exe basenames but neither the username nor the parent dirs.+ let status = RegistrationStatus::Stale {+ registered_command:+ "\"C:\\Users\\joe\\AppData\\Local\\OpenHuman\\OpenHuman.exe\" \"%1\"".into(),+ expected_exe: "C:\\Users\\joe\\AppData\\Local\\OpenHuman_new\\OpenHuman.exe".into(),+ };+ let rendered = status.redacted();+ assert!(+ rendered.contains("OpenHuman.exe"),+ "basename should survive redaction: {rendered}"+ );+ assert!(+ !rendered.contains("joe"),+ "username must not leak: {rendered}"+ );+ assert!(+ !rendered.contains("AppData"),+ "directory path must not leak: {rendered}"+ );+}++#[test]+fn redacted_preserves_valid_variant_label_and_basename() {+ let status = RegistrationStatus::Valid {+ command: "\"C:\\Program Files\\OpenHuman\\OpenHuman.exe\" \"%1\"".into(),+ };+ assert_eq!(status.redacted(), "Valid { exe: OpenHuman.exe }");+}++#[test]+fn redacted_passes_through_pathless_variants() {+ assert_eq!(+ RegistrationStatus::MissingCommand.redacted(),+ "MissingCommand"+ );+ assert_eq!(+ RegistrationStatus::NotRegistered.redacted(),+ "NotRegistered"+ );+ assert_eq!(+ RegistrationStatus::ReadError("win32 error 5".into()).redacted(),+ "ReadError(win32 error 5)"+ );+}++#[test]+fn is_healthy_only_for_valid_variant() {+ assert!(RegistrationStatus::Valid {+ command: "x".into()+ }+ .is_healthy());+ assert!(!RegistrationStatus::MissingCommand.is_healthy());+ assert!(!RegistrationStatus::NotRegistered.is_healthy());+ assert!(!RegistrationStatus::Stale {+ registered_command: "x".into(),+ expected_exe: "y".into()+ }+ .is_healthy());+ assert!(!RegistrationStatus::ReadError("foo".into()).is_healthy());+}diff --git a/crates/openhuman-app/src/dictation_hotkeys.rs b/crates/openhuman-app/src/dictation_hotkeys.rsindex e4c6fb3bfa..4686cd1a15 100644--- a/crates/openhuman-app/src/dictation_hotkeys.rs+++ b/crates/openhuman-app/src/dictation_hotkeys.rs@@ -32,55 +32,5 @@ pub(crate) fn expand_dictation_shortcuts(shortcut: &str) -> Vec<String> {}#[cfg(test)]-mod tests {- use super::expand_dictation_shortcuts;-- #[test]- fn expand_dictation_shortcuts_cmd_or_ctrl_expansion() {- #[cfg(target_os = "macos")]- {- let result = expand_dictation_shortcuts("CmdOrCtrl+Shift+D");- assert_eq!(result.len(), 2);- assert!(result.contains(&"Cmd+Shift+D".to_string()));- assert!(result.contains(&"Ctrl+Shift+D".to_string()));- }-- #[cfg(not(target_os = "macos"))]- {- let result = expand_dictation_shortcuts("CmdOrCtrl+Shift+D");- assert_eq!(result.len(), 1);- assert_eq!(result[0], "Ctrl+Shift+D");- }- }-- #[test]- fn expand_dictation_shortcuts_plain_shortcut() {- let result = expand_dictation_shortcuts("Ctrl+Alt+T");- assert_eq!(result.len(), 1);- assert_eq!(result[0], "Ctrl+Alt+T");- }-- #[test]- fn expand_dictation_shortcuts_empty_input() {- let result = expand_dictation_shortcuts("");- assert!(result.is_empty());-- let result = expand_dictation_shortcuts(" ");- assert!(result.is_empty());- }-- #[test]- #[cfg(target_os = "macos")]- fn expand_dictation_shortcuts_macos_cmd_only() {- let result = expand_dictation_shortcuts("CmdOrCtrl+Space");- assert!(result.contains(&"Cmd+Space".to_string()));- }-- #[test]- #[cfg(not(target_os = "macos"))]- fn expand_dictation_shortcuts_non_macos_ctrl_only() {- let result = expand_dictation_shortcuts("CmdOrCtrl+Space");- assert_eq!(result.len(), 1);- assert_eq!(result[0], "Ctrl+Space");- }-}+#[path = "dictation_hotkeys_tests.rs"]+mod tests;diff --git a/crates/openhuman-app/src/dictation_hotkeys_tests.rs b/crates/openhuman-app/src/dictation_hotkeys_tests.rsnew file mode 100644index 0000000000..14151a413d--- /dev/null+++ b/crates/openhuman-app/src/dictation_hotkeys_tests.rs@@ -0,0 +1,50 @@+use super::expand_dictation_shortcuts;++#[test]+fn expand_dictation_shortcuts_cmd_or_ctrl_expansion() {+ #[cfg(target_os = "macos")]+ {+ let result = expand_dictation_shortcuts("CmdOrCtrl+Shift+D");+ assert_eq!(result.len(), 2);+ assert!(result.contains(&"Cmd+Shift+D".to_string()));+ assert!(result.contains(&"Ctrl+Shift+D".to_string()));+ }++ #[cfg(not(target_os = "macos"))]+ {+ let result = expand_dictation_shortcuts("CmdOrCtrl+Shift+D");+ assert_eq!(result.len(), 1);+ assert_eq!(result[0], "Ctrl+Shift+D");+ }+}++#[test]+fn expand_dictation_shortcuts_plain_shortcut() {+ let result = expand_dictation_shortcuts("Ctrl+Alt+T");+ assert_eq!(result.len(), 1);+ assert_eq!(result[0], "Ctrl+Alt+T");+}++#[test]+fn expand_dictation_shortcuts_empty_input() {+ let result = expand_dictation_shortcuts("");+ assert!(result.is_empty());++ let result = expand_dictation_shortcuts(" ");+ assert!(result.is_empty());+}++#[test]+#[cfg(target_os = "macos")]+fn expand_dictation_shortcuts_macos_cmd_only() {+ let result = expand_dictation_shortcuts("CmdOrCtrl+Space");+ assert!(result.contains(&"Cmd+Space".to_string()));+}++#[test]+#[cfg(not(target_os = "macos"))]+fn expand_dictation_shortcuts_non_macos_ctrl_only() {+ let result = expand_dictation_shortcuts("CmdOrCtrl+Space");+ assert_eq!(result.len(), 1);+ assert_eq!(result[0], "Ctrl+Space");+}diff --git a/crates/openhuman-app/src/directory_picker.rs b/crates/openhuman-app/src/directory_picker.rsindex baed8f1316..fa07985078 100644--- a/crates/openhuman-app/src/directory_picker.rs+++ b/crates/openhuman-app/src/directory_picker.rs@@ -97,57 +97,5 @@ pub async fn pick_directory_via_dialog() -> Result<Option<String>, String> {}#[cfg(test)]-mod tests {- use super::absolute_path_string;- use std::path::Path;-- #[cfg(not(target_os = "windows"))]- const ABSOLUTE: &str = "/Users/you/notes";- #[cfg(target_os = "windows")]- const ABSOLUTE: &str = r"C:\Users\you\notes";-- #[test]- fn passes_an_absolute_path_through_unchanged() {- assert_eq!(- absolute_path_string(Path::new(ABSOLUTE)),- Ok(ABSOLUTE.to_string())- );- }-- #[test]- fn refuses_a_bare_directory_name() {- // `docs` is exactly what the old `webkitRelativePath.split('/')[0]`- // fallback stored, and what made the source unsyncable (#5831).- let err = absolute_path_string(Path::new("docs")).unwrap_err();- assert!(err.contains("non-absolute"), "unexpected message: {err}");- assert!(err.contains("docs"), "message should name the value: {err}");- }-- #[test]- fn refuses_a_relative_path_with_separators() {- assert!(absolute_path_string(Path::new("notes/inner")).is_err());- }-- /// A Unix directory name is bytes, not text. `Path::display()` would have- /// substituted U+FFFD here and returned the corrupted string as a- /// success, which is the #5831 failure mode reached by another route.- #[cfg(unix)]- #[test]- fn refuses_an_absolute_path_that_is_not_utf8() {- use std::ffi::OsStr;- use std::os::unix::ffi::OsStrExt;-- let raw = OsStr::from_bytes(b"/Users/you/\xff\xfenotes");- let path = Path::new(raw);- assert!(path.is_absolute(), "fixture must clear the absolute check");-- let err = absolute_path_string(path).unwrap_err();- assert!(err.contains("not valid UTF-8"), "unexpected message: {err}");- // The mangled rendering must not be echoed back — it is both useless- // and carries the user's login name.- assert!(- !err.contains('\u{FFFD}'),- "lossy path leaked into the error"- );- }-}+#[path = "directory_picker_tests.rs"]+mod tests;diff --git a/crates/openhuman-app/src/directory_picker_tests.rs b/crates/openhuman-app/src/directory_picker_tests.rsnew file mode 100644index 0000000000..a2c79932d6--- /dev/null+++ b/crates/openhuman-app/src/directory_picker_tests.rs@@ -0,0 +1,52 @@+use super::absolute_path_string;+use std::path::Path;++#[cfg(not(target_os = "windows"))]+const ABSOLUTE: &str = "/Users/you/notes";+#[cfg(target_os = "windows")]+const ABSOLUTE: &str = r"C:\Users\you\notes";++#[test]+fn passes_an_absolute_path_through_unchanged() {+ assert_eq!(+ absolute_path_string(Path::new(ABSOLUTE)),+ Ok(ABSOLUTE.to_string())+ );+}++#[test]+fn refuses_a_bare_directory_name() {+ // `docs` is exactly what the old `webkitRelativePath.split('/')[0]`+ // fallback stored, and what made the source unsyncable (#5831).+ let err = absolute_path_string(Path::new("docs")).unwrap_err();+ assert!(err.contains("non-absolute"), "unexpected message: {err}");+ assert!(err.contains("docs"), "message should name the value: {err}");+}++#[test]+fn refuses_a_relative_path_with_separators() {+ assert!(absolute_path_string(Path::new("notes/inner")).is_err());+}++/// A Unix directory name is bytes, not text. `Path::display()` would have+/// substituted U+FFFD here and returned the corrupted string as a+/// success, which is the #5831 failure mode reached by another route.+#[cfg(unix)]+#[test]+fn refuses_an_absolute_path_that_is_not_utf8() {+ use std::ffi::OsStr;+ use std::os::unix::ffi::OsStrExt;++ let raw = OsStr::from_bytes(b"/Users/you/\xff\xfenotes");+ let path = Path::new(raw);+ assert!(path.is_absolute(), "fixture must clear the absolute check");++ let err = absolute_path_string(path).unwrap_err();+ assert!(err.contains("not valid UTF-8"), "unexpected message: {err}");+ // The mangled rendering must not be echoed back — it is both useless+ // and carries the user's login name.+ assert!(+ !err.contains('\u{FFFD}'),+ "lossy path leaked into the error"+ );+}diff --git a/crates/openhuman-app/src/file_logging.rs b/crates/openhuman-app/src/file_logging.rsindex 760d72e486..1e1c77d6ad 100644--- a/crates/openhuman-app/src/file_logging.rs+++ b/crates/openhuman-app/src/file_logging.rs@@ -50,65 +50,8 @@ pub(crate) fn resolve_data_dir() -> PathBuf {}#[cfg(test)]-mod tests {- use super::*;-- /// Lock around env-var mutation. Cargo runs unit tests in parallel- /// threads in the same process, so concurrent `set_var` / `remove_var`- /// can race; the lock keeps the env stable for each test's duration.- static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());-- #[test]- fn resolve_data_dir_honors_workspace_override() {- let _guard = ENV_LOCK.lock().unwrap();- let prior = std::env::var("OPENHUMAN_WORKSPACE").ok();- std::env::set_var("OPENHUMAN_WORKSPACE", "/tmp/openhuman-test-override");- let dir = resolve_data_dir();- assert_eq!(dir, PathBuf::from("/tmp/openhuman-test-override"));- match prior {- Some(v) => std::env::set_var("OPENHUMAN_WORKSPACE", v),- None => std::env::remove_var("OPENHUMAN_WORKSPACE"),- }- }-- #[test]- fn resolve_data_dir_ignores_empty_workspace() {- let _guard = ENV_LOCK.lock().unwrap();- let prior = std::env::var("OPENHUMAN_WORKSPACE").ok();- std::env::set_var("OPENHUMAN_WORKSPACE", "");- // Empty string must NOT short-circuit — fall through to the- // default resolver so the user's real `~/.openhuman` is used.- let dir = resolve_data_dir();- assert_ne!(dir, PathBuf::from(""));- assert!(dir.is_absolute(), "expected absolute fallback, got {dir:?}");- match prior {- Some(v) => std::env::set_var("OPENHUMAN_WORKSPACE", v),- None => std::env::remove_var("OPENHUMAN_WORKSPACE"),- }- }-- #[test]- fn logs_folder_path_returns_none_pre_init() {- // `init()` is `Once`-guarded across the whole process, so in unit- // tests where the embedded subscriber hasn't been installed,- // `logs_folder_path` should return `None` rather than a stale path.- // (When run alongside a test that *did* call `init`, the function- // is allowed to return Some — assert the type signature only.)- let result = logs_folder_path();- let _: Option<String> = result;- }-- #[test]- fn reveal_logs_folder_errors_when_uninitialized() {- // If logging hasn't been initialized, the command must surface a- // typed error so the UI can show it instead of silently launching- // an `open` against an empty path.- if openhuman_core::core::logging::log_directory().is_none() {- let err = reveal_logs_folder().expect_err("must error pre-init");- assert!(err.contains("not initialized"), "unexpected error: {err}");- }- }-}+#[path = "file_logging_tests.rs"]+mod tests;/// Tauri command — return the absolute path to the active log directory, or/// `None` if logging hasn't been initialized in embedded mode (shouldn'tdiff --git a/crates/openhuman-app/src/file_logging_tests.rs b/crates/openhuman-app/src/file_logging_tests.rsnew file mode 100644index 0000000000..9b832e9a4d--- /dev/null+++ b/crates/openhuman-app/src/file_logging_tests.rs@@ -0,0 +1,57 @@+use super::*;++/// Lock around env-var mutation. Cargo runs unit tests in parallel+/// threads in the same process, so concurrent `set_var` / `remove_var`+/// can race; the lock keeps the env stable for each test's duration.+static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());++#[test]+fn resolve_data_dir_honors_workspace_override() {+ let _guard = ENV_LOCK.lock().unwrap();+ let prior = std::env::var("OPENHUMAN_WORKSPACE").ok();+ std::env::set_var("OPENHUMAN_WORKSPACE", "/tmp/openhuman-test-override");+ let dir = resolve_data_dir();+ assert_eq!(dir, PathBuf::from("/tmp/openhuman-test-override"));+ match prior {+ Some(v) => std::env::set_var("OPENHUMAN_WORKSPACE", v),+ None => std::env::remove_var("OPENHUMAN_WORKSPACE"),+ }+}++#[test]+fn resolve_data_dir_ignores_empty_workspace() {+ let _guard = ENV_LOCK.lock().unwrap();+ let prior = std::env::var("OPENHUMAN_WORKSPACE").ok();+ std::env::set_var("OPENHUMAN_WORKSPACE", "");+ // Empty string must NOT short-circuit — fall through to the+ // default resolver so the user's real `~/.openhuman` is used.+ let dir = resolve_data_dir();+ assert_ne!(dir, PathBuf::from(""));+ assert!(dir.is_absolute(), "expected absolute fallback, got {dir:?}");+ match prior {+ Some(v) => std::env::set_var("OPENHUMAN_WORKSPACE", v),+ None => std::env::remove_var("OPENHUMAN_WORKSPACE"),+ }+}++#[test]+fn logs_folder_path_returns_none_pre_init() {+ // `init()` is `Once`-guarded across the whole process, so in unit+ // tests where the embedded subscriber hasn't been installed,+ // `logs_folder_path` should return `None` rather than a stale path.+ // (When run alongside a test that *did* call `init`, the function+ // is allowed to return Some — assert the type signature only.)+ let result = logs_folder_path();+ let _: Option<String> = result;+}++#[test]+fn reveal_logs_folder_errors_when_uninitialized() {+ // If logging hasn't been initialized, the command must surface a+ // typed error so the UI can show it instead of silently launching+ // an `open` against an empty path.+ if openhuman_core::core::logging::log_directory().is_none() {+ let err = reveal_logs_folder().expect_err("must error pre-init");+ assert!(err.contains("not initialized"), "unexpected error: {err}");+ }+}diff --git a/crates/openhuman-app/src/imessage_scanner/imessage_scanner_tests.rs b/crates/openhuman-app/src/imessage_scanner/imessage_scanner_tests.rsnew file mode 100644index 0000000000..62aa00b17d--- /dev/null+++ b/crates/openhuman-app/src/imessage_scanner/imessage_scanner_tests.rs@@ -0,0 +1,209 @@+use super::*;++struct DropNotify(Option<tokio::sync::oneshot::Sender<()>>);++impl Drop for DropNotify {+ fn drop(&mut self) {+ if let Some(tx) = self.0.take() {+ let _ = tx.send(());+ }+ }+}++#[tokio::test]+async fn registry_shutdown_aborts_stored_scanner_and_is_repeatable() {+ let registry = ScannerRegistry::new();+ let (drop_tx, drop_rx) = tokio::sync::oneshot::channel();+ let (started_tx, started_rx) = tokio::sync::oneshot::channel();+ let task = tauri::async_runtime::spawn(async move {+ let _notify = DropNotify(Some(drop_tx));+ let _ = started_tx.send(());+ std::future::pending::<()>().await;+ });+ started_rx.await.expect("scanner task should start");+ *registry.inner.lock() = Some(task);++ registry.shutdown();++ assert!(registry.inner.lock().is_none());+ tokio::time::timeout(std::time::Duration::from_secs(1), drop_rx)+ .await+ .expect("iMessage scanner task should be cancelled promptly")+ .expect("drop notifier should send on cancellation");++ registry.shutdown();+ assert!(registry.inner.lock().is_none());+}++#[test]+fn apple_ns_to_unix_converts_apple_epoch_zero() {+ assert_eq!(apple_ns_to_unix(0), 978_307_200);+}++#[test]+fn apple_ns_to_unix_converts_one_second_past_apple_epoch() {+ assert_eq!(apple_ns_to_unix(1_000_000_000), 978_307_201);+}++#[test]+fn seconds_to_ymd_formats_known_date_in_local_tz() {+ // 2001-01-01 00:00:00 UTC. In US timezones this falls on 2000-12-31+ // in local time, so assert only the shape (YYYY-MM-DD) and that the+ // year is 2000 or 2001 — keeps the test robust across CI timezones.+ let out = seconds_to_ymd(978_307_200);+ assert_eq!(out.len(), 10);+ assert!(+ out.starts_with("2000-") || out.starts_with("2001-"),+ "got {}",+ out+ );+}++#[test]+fn extract_text_from_attributed_body_finds_message() {+ // Fake typedstream-style blob with 'hello world' as the longest+ // printable run embedded between type markers.+ let mut blob = b"streamtyped\x81\xe8\x03\x84\x01@\x84\x84\x84\x08NSString\x00\x84\x84\x08NSObject\x00\x85\x84\x01+\x0bhello world\x86".to_vec();+ blob.extend_from_slice(b"\x00\x00\x00");+ let out = extract_text_from_attributed_body(&blob).unwrap_or_default();+ assert!(out.contains("hello world"), "got {:?}", out);+}++#[test]+fn message_body_prefers_text_then_attributed_body() {+ let m = chatdb::Message {+ rowid: 1,+ guid: None,+ text: Some("direct".into()),+ attributed_body: Some(b"ignored".to_vec()),+ date_ns: 0,+ is_from_me: false,+ handle_id: None,+ chat_identifier: None,+ chat_name: None,+ service: None,+ };+ assert_eq!(message_body(&m), "direct");++ let m2 = chatdb::Message {+ rowid: 2,+ guid: None,+ text: None,+ attributed_body: Some(b"\x00\x00fallback body\x00".to_vec()),+ date_ns: 0,+ is_from_me: false,+ handle_id: None,+ chat_identifier: None,+ chat_name: None,+ service: None,+ };+ let body = message_body(&m2);+ assert!(body.contains("fallback body"), "got {:?}", body);+}++#[test]+fn chat_allowed_empty_list_allows_all() {+ assert!(chat_allowed("+15551234567", &[]));+}++#[test]+fn chat_allowed_wildcard_allows_all() {+ assert!(chat_allowed("+15551234567", &["*".to_string()]));+}++#[test]+fn chat_allowed_matches_exact_entry_case_insensitive() {+ let allowed = vec!["+15551234567".to_string(), "[email protected]".to_string()];+ assert!(chat_allowed("+15551234567", &allowed));+ assert!(chat_allowed("[email protected]", &allowed));+ assert!(!chat_allowed("+15550000000", &allowed));+}++#[test]+fn format_transcript_renders_known_messages() {+ let msgs = vec![+ chatdb::Message {+ rowid: 1,+ guid: None,+ text: Some("hi".into()),+ attributed_body: None,+ date_ns: 0,+ is_from_me: false,+ handle_id: Some("+15551234567".into()),+ chat_identifier: Some("+15551234567".into()),+ chat_name: None,+ service: None,+ },+ chatdb::Message {+ rowid: 2,+ guid: None,+ text: Some("yo".into()),+ attributed_body: None,+ date_ns: 0,+ is_from_me: true,+ handle_id: None,+ chat_identifier: Some("+15551234567".into()),+ chat_name: None,+ service: None,+ },+ ];+ let transcript = format_transcript(&msgs);+ let groups =+ std::collections::HashMap::from([("+15551234567:day".to_string(), transcript.clone())]);+ let _ = groups;+ assert_eq!(groups.len(), 1);+ let transcript = groups.values().next().expect("one group").clone();+ assert!(transcript.contains("hi"));+ assert!(transcript.contains("yo"));+ assert!(transcript.contains("me:"));+}++/// Real chat.db integration test. Gated with `#[ignore]` — run with+/// `cargo test --manifest-path crates/openhuman-app/Cargo.toml \+/// imessage_scanner -- --ignored`. Requires Full Disk Access granted+/// to the test-runner binary. Asserts we can open chat.db read-only,+/// run our JOIN query, and deserialize at least one row.+#[test]+#[ignore]+fn real_chat_db_opens_and_returns_messages() {+ let path = match chat_db_path() {+ Some(p) => p,+ None => {+ eprintln!("HOME not set — skipping");+ return;+ }+ };+ if !path.exists() {+ eprintln!("chat.db not found at {} — skipping", path.display());+ return;+ }+ let msgs = match chatdb::read_since(&path, 0, 5) {+ Ok(m) => m,+ Err(e) => panic!("read_since failed: {}", e),+ };+ assert!(+ !msgs.is_empty(),+ "expected at least one message from a real chat.db — is it empty?"+ );+ // Each message should have a rowid and a date_ns in Apple-epoch range.+ for m in &msgs {+ assert!(m.rowid > 0);+ assert!(m.date_ns >= 0);+ }+}++/// Sanity: `read_since` with cursor past max rowid returns empty.+#[test]+#[ignore]+fn real_chat_db_empty_past_cursor() {+ let path = match chat_db_path() {+ Some(p) => p,+ None => return,+ };+ if !path.exists() {+ return;+ }+ // rowid way past any real value+ let msgs = chatdb::read_since(&path, i64::MAX - 1, 10).unwrap();+ assert!(msgs.is_empty());+}diff --git a/crates/openhuman-app/src/imessage_scanner/mod.rs b/crates/openhuman-app/src/imessage_scanner/mod.rsindex 5184f7343d..a44bcb5915 100644--- a/crates/openhuman-app/src/imessage_scanner/mod.rs+++ b/crates/openhuman-app/src/imessage_scanner/mod.rs@@ -469,214 +469,5 @@ impl ScannerRegistry {}#[cfg(all(test, target_os = "macos"))]-mod tests {- use super::*;-- struct DropNotify(Option<tokio::sync::oneshot::Sender<()>>);-- impl Drop for DropNotify {- fn drop(&mut self) {- if let Some(tx) = self.0.take() {- let _ = tx.send(());- }- }- }-- #[tokio::test]- async fn registry_shutdown_aborts_stored_scanner_and_is_repeatable() {- let registry = ScannerRegistry::new();- let (drop_tx, drop_rx) = tokio::sync::oneshot::channel();- let (started_tx, started_rx) = tokio::sync::oneshot::channel();- let task = tauri::async_runtime::spawn(async move {- let _notify = DropNotify(Some(drop_tx));- let _ = started_tx.send(());- std::future::pending::<()>().await;- });- started_rx.await.expect("scanner task should start");- *registry.inner.lock() = Some(task);-- registry.shutdown();-- assert!(registry.inner.lock().is_none());- tokio::time::timeout(std::time::Duration::from_secs(1), drop_rx)- .await- .expect("iMessage scanner task should be cancelled promptly")- .expect("drop notifier should send on cancellation");-- registry.shutdown();- assert!(registry.inner.lock().is_none());- }-- #[test]- fn apple_ns_to_unix_converts_apple_epoch_zero() {- assert_eq!(apple_ns_to_unix(0), 978_307_200);- }-- #[test]- fn apple_ns_to_unix_converts_one_second_past_apple_epoch() {- assert_eq!(apple_ns_to_unix(1_000_000_000), 978_307_201);- }-- #[test]- fn seconds_to_ymd_formats_known_date_in_local_tz() {- // 2001-01-01 00:00:00 UTC. In US timezones this falls on 2000-12-31- // in local time, so assert only the shape (YYYY-MM-DD) and that the- // year is 2000 or 2001 — keeps the test robust across CI timezones.- let out = seconds_to_ymd(978_307_200);- assert_eq!(out.len(), 10);- assert!(- out.starts_with("2000-") || out.starts_with("2001-"),- "got {}",- out- );- }-- #[test]- fn extract_text_from_attributed_body_finds_message() {- // Fake typedstream-style blob with 'hello world' as the longest- // printable run embedded between type markers.- let mut blob = b"streamtyped\x81\xe8\x03\x84\x01@\x84\x84\x84\x08NSString\x00\x84\x84\x08NSObject\x00\x85\x84\x01+\x0bhello world\x86".to_vec();- blob.extend_from_slice(b"\x00\x00\x00");- let out = extract_text_from_attributed_body(&blob).unwrap_or_default();- assert!(out.contains("hello world"), "got {:?}", out);- }-- #[test]- fn message_body_prefers_text_then_attributed_body() {- let m = chatdb::Message {- rowid: 1,- guid: None,- text: Some("direct".into()),- attributed_body: Some(b"ignored".to_vec()),- date_ns: 0,- is_from_me: false,- handle_id: None,- chat_identifier: None,- chat_name: None,- service: None,- };- assert_eq!(message_body(&m), "direct");-- let m2 = chatdb::Message {- rowid: 2,- guid: None,- text: None,- attributed_body: Some(b"\x00\x00fallback body\x00".to_vec()),- date_ns: 0,- is_from_me: false,- handle_id: None,- chat_identifier: None,- chat_name: None,- service: None,- };- let body = message_body(&m2);- assert!(body.contains("fallback body"), "got {:?}", body);- }-- #[test]- fn chat_allowed_empty_list_allows_all() {- assert!(chat_allowed("+15551234567", &[]));- }-- #[test]- fn chat_allowed_wildcard_allows_all() {- assert!(chat_allowed("+15551234567", &["*".to_string()]));- }-- #[test]- fn chat_allowed_matches_exact_entry_case_insensitive() {- let allowed = vec!["+15551234567".to_string(), "[email protected]".to_string()];- assert!(chat_allowed("+15551234567", &allowed));- assert!(chat_allowed("[email protected]", &allowed));- assert!(!chat_allowed("+15550000000", &allowed));- }-- #[test]- fn format_transcript_renders_known_messages() {- let msgs = vec![- chatdb::Message {- rowid: 1,- guid: None,- text: Some("hi".into()),- attributed_body: None,- date_ns: 0,- is_from_me: false,- handle_id: Some("+15551234567".into()),- chat_identifier: Some("+15551234567".into()),- chat_name: None,- service: None,- },- chatdb::Message {- rowid: 2,- guid: None,- text: Some("yo".into()),- attributed_body: None,- date_ns: 0,- is_from_me: true,- handle_id: None,- chat_identifier: Some("+15551234567".into()),- chat_name: None,- service: None,- },- ];- let transcript = format_transcript(&msgs);- let groups =- std::collections::HashMap::from([("+15551234567:day".to_string(), transcript.clone())]);- let _ = groups;- assert_eq!(groups.len(), 1);- let transcript = groups.values().next().expect("one group").clone();- assert!(transcript.contains("hi"));- assert!(transcript.contains("yo"));- assert!(transcript.contains("me:"));- }-- /// Real chat.db integration test. Gated with `#[ignore]` — run with- /// `cargo test --manifest-path crates/openhuman-app/Cargo.toml \- /// imessage_scanner -- --ignored`. Requires Full Disk Access granted- /// to the test-runner binary. Asserts we can open chat.db read-only,- /// run our JOIN query, and deserialize at least one row.- #[test]- #[ignore]- fn real_chat_db_opens_and_returns_messages() {- let path = match chat_db_path() {- Some(p) => p,- None => {- eprintln!("HOME not set — skipping");- return;- }- };- if !path.exists() {- eprintln!("chat.db not found at {} — skipping", path.display());- return;- }- let msgs = match chatdb::read_since(&path, 0, 5) {- Ok(m) => m,- Err(e) => panic!("read_since failed: {}", e),- };- assert!(- !msgs.is_empty(),- "expected at least one message from a real chat.db — is it empty?"- );- // Each message should have a rowid and a date_ns in Apple-epoch range.- for m in &msgs {- assert!(m.rowid > 0);- assert!(m.date_ns >= 0);- }- }-- /// Sanity: `read_since` with cursor past max rowid returns empty.- #[test]- #[ignore]- fn real_chat_db_empty_past_cursor() {- let path = match chat_db_path() {- Some(p) => p,- None => return,- };- if !path.exists() {- return;- }- // rowid way past any real value- let msgs = chatdb::read_since(&path, i64::MAX - 1, 10).unwrap();- assert!(msgs.is_empty());- }-}+#[path = "imessage_scanner_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rsindex 4def664ccc..de2dbaca5b 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs@@ -35,7 +35,7 @@ const SCOUT_AGENT_ID: &str = "context_scout";/// model's free-form prose. We still reject genuinely unusable output —/// absent, unterminated/reversed, or duplicated (where we can't tell which/// envelope is authoritative) — by returning `None`.-fn extract_context_bundle(output: &str) -> Option<String> {+pub(super) fn extract_context_bundle(output: &str) -> Option<String> {const OPEN: &str = "[context_bundle]";const CLOSE: &str = "[/context_bundle]";// Exactly one open + one close tag. Duplicates are a contract violation we@@ -142,7 +142,7 @@ pub async fn run_context_scout_with_catalog(/// Walk `anyhow`'s chain for that variant; every other variant is a flat/// `thiserror` message already. Used for classification only — the/// user-visible `message` stays `err.to_string()`, unchanged.-fn scout_failure_signal(err: &SubagentRunError) -> String {+pub(super) fn scout_failure_signal(err: &SubagentRunError) -> String {let SubagentRunError::Provider(inner) = err else {return err.to_string();};@@ -165,7 +165,7 @@ fn scout_failure_signal(err: &SubagentRunError) -> String {////// Both delegate to the crate's single-source classifiers so the phrase sets/// can't drift from the cron halt / `before_send` nets that share them.-fn is_expected_billing_failure(message: &str) -> bool {+pub(super) fn is_expected_billing_failure(message: &str) -> bool {crate::inference::provider::is_budget_exhausted_message(message)|| crate::core::observability::is_insufficient_credits_message(message)}@@ -187,7 +187,7 @@ fn is_expected_billing_failure(message: &str) -> bool {/// keeps the local log line (and the Sentry breadcrumb trail for any *real*/// error that follows) without raising an issue. Every other cause still/// `error!`s and keeps paging.-fn log_scout_failure(error_kind: &str, message: &str) {+pub(super) fn log_scout_failure(error_kind: &str, message: &str) {if is_expected_billing_failure(message) {// Metadata-only — never log the raw provider body (see CLAUDE.md).tracing::warn!(diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rsindex 029d1032eb..9915fff456 100644--- a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs@@ -117,17 +117,6 @@ pub async fn fetch_connected_integrations_status(}}-/// The actual backend fetch, called on cache miss.-///-/// Returns `Some(vec)` when the backend was reachable. The returned-/// vector is the merged **integration overview** — every toolkit in-/// the backend allowlist appears as one entry, with a `connected`-/// flag indicating whether the user has an active OAuth connection.-/// Connected entries also carry the per-action tool catalogue-/// (fetched in a single batched call).-///-/// Returns `None` when we couldn't even build a client (no auth),-/// signalling the caller should NOT cache this result./// The connectable toolkit slugs to surface in the agent prompt, aligned/// with the backend's execution gate.///diff --git a/crates/openhuman-core/src/threads/ops/crud.rs b/crates/openhuman-core/src/threads/ops/crud.rsnew file mode 100644index 0000000000..e516563f98--- /dev/null+++ b/crates/openhuman-core/src/threads/ops/crud.rs@@ -0,0 +1,311 @@+//! Create, read, update, and delete operations for conversation threads and+//! their messages.++use super::support::{+ counts, envelope, message_to_record, record_to_message, run_to_completion, thread_to_summary,+ workspace_dir,+};+use crate::memory::conversations;+use crate::memory::conversations::{ConversationMessagePatch, CrossThreadHit};+use crate::memory::{+ ApiEnvelope, AppendConversationMessageRequest, ConversationMessageRecord,+ ConversationMessagesRequest, ConversationMessagesResponse, ConversationThreadSummary,+ ConversationThreadsListResponse, CreateConversationThreadRequest,+ DeleteConversationThreadRequest, DeleteConversationThreadResponse, EmptyRequest,+ UpdateConversationMessageRequest, UpdateConversationThreadLabelsRequest,+ UpdateConversationThreadTitleRequest, UpsertConversationThreadRequest,+};+use crate::rpc::RpcOutcome;+use crate::threads::turn_state;+use crate::threads::ThreadsError;+use crate::web_chat as web_channel;+use std::path::PathBuf;++/// Lists all conversation threads.+pub async fn threads_list(+ _request: EmptyRequest,+) -> Result<RpcOutcome<ApiEnvelope<ConversationThreadsListResponse>>, String> {+ let dir = workspace_dir().await?;+ let threads = conversations::blocking::list_threads(dir)+ .await?+ .into_iter()+ .map(thread_to_summary)+ .collect::<Vec<_>>();+ let count = threads.len();+ Ok(envelope(+ ConversationThreadsListResponse { threads, count },+ Some(counts([("num_threads", count)])),+ None,+ ))+}++/// Creates or refreshes a conversation thread.+pub async fn thread_upsert(+ request: UpsertConversationThreadRequest,+) -> Result<RpcOutcome<ApiEnvelope<ConversationThreadSummary>>, String> {+ let dir = workspace_dir().await?;+ let thread = conversations::blocking::ensure_thread(+ dir,+ conversations::CreateConversationThread {+ id: request.id,+ title: request.title,+ created_at: request.created_at,+ parent_thread_id: request.parent_thread_id,+ labels: request.labels,+ personality_id: request.personality_id,+ },+ )+ .await?;+ Ok(envelope(+ thread_to_summary(thread),+ Some(counts([("num_threads", 1)])),+ None,+ ))+}++/// Creates a new conversation thread with auto-generated ID and title.+pub async fn thread_create_new(+ request: CreateConversationThreadRequest,+) -> Result<RpcOutcome<ApiEnvelope<ConversationThreadSummary>>, String> {+ let dir = workspace_dir().await?;+ let id = format!("thread-{}", uuid::Uuid::new_v4());+ let now = chrono::Local::now();+ let title = format!("Chat {} {}", now.format("%b %-d"), now.format("%-I:%M %p"));+ let created_at = chrono::Utc::now().to_rfc3339();+ let thread = conversations::blocking::ensure_thread(+ dir,+ conversations::CreateConversationThread {+ id,+ title,+ created_at,+ parent_thread_id: None,+ // Pass labels through as-is; the store's infer_labels() applies+ // the same default on index rebuild, so this is the single source+ // of truth for default labels.+ labels: request.labels,+ personality_id: request.personality_id,+ },+ )+ .await?;+ tracing::debug!(+ thread_id = %thread.id,+ labels = ?thread.labels,+ "[threads] created new thread"+ );+ Ok(envelope(+ thread_to_summary(thread),+ Some(counts([("num_threads", 1)])),+ None,+ ))+}++/// Lists messages for a conversation thread.+pub async fn messages_list(+ request: ConversationMessagesRequest,+) -> Result<RpcOutcome<ApiEnvelope<ConversationMessagesResponse>>, String> {+ let dir = workspace_dir().await?;+ let messages = conversations::blocking::get_messages(dir, request.thread_id.clone())+ .await?+ .into_iter()+ .map(message_to_record)+ .collect::<Vec<_>>();+ let count = messages.len();+ Ok(envelope(+ ConversationMessagesResponse { messages, count },+ Some(counts([("num_messages", count)])),+ None,+ ))+}++/// Search messages across **every** thread in the workspace for a query,+/// returning up to `limit` of the most-recent matches (newest first). Backed+/// by the trigram/CJK-bigram inverted index in `memory_conversations` — the+/// same cross-chat reader the durable-context pipeline uses (issue #1505).+///+/// Read-only and workspace-scoped. `exclude_thread_id` lets a caller drop the+/// active chat from the results when it already has that context in hand.+pub async fn transcript_search(+ query: &str,+ limit: usize,+ exclude_thread_id: Option<&str>,+) -> Result<Vec<CrossThreadHit>, String> {+ let dir = workspace_dir().await?;+ log::debug!(+ "[threads][transcript_search] query_chars={} limit={} exclude={:?}",+ query.chars().count(),+ limit,+ exclude_thread_id+ );+ let hits = conversations::blocking::search_cross_thread_messages(+ dir,+ query.to_string(),+ limit,+ exclude_thread_id.map(str::to_string),+ )+ .await?;+ log::debug!("[threads][transcript_search] hits={}", hits.len());+ Ok(hits)+}++/// Appends a message to a conversation thread.+pub async fn message_append(+ request: AppendConversationMessageRequest,+) -> Result<RpcOutcome<ApiEnvelope<ConversationMessageRecord>>, ThreadsError> {+ let dir = workspace_dir().await?;+ let message = conversations::blocking::append_message(+ dir,+ request.thread_id.clone(),+ record_to_message(request.message),+ )+ .await+ .map_err(|err| ThreadsError::from_thread_scoped_store_error(&request.thread_id, err))?;+ Ok(envelope(+ message_to_record(message),+ Some(counts([("num_messages", 1)])),+ None,+ ))+}++/// Updates labels for a conversation thread.+///+/// An empty `labels` vec is valid and clears all labels from the thread,+/// making it invisible in every non-"All" filter view. Callers should+/// ensure this is intentional.+pub async fn thread_update_labels(+ request: UpdateConversationThreadLabelsRequest,+) -> Result<RpcOutcome<ApiEnvelope<ConversationThreadSummary>>, String> {+ let dir = workspace_dir().await?;+ let thread = conversations::blocking::update_thread_labels(+ dir,+ request.thread_id.clone(),+ request.labels.clone(),+ chrono::Utc::now().to_rfc3339(),+ )+ .await?;+ tracing::debug!(+ thread_id = %request.thread_id,+ labels = ?request.labels,+ "[threads] updated thread labels"+ );+ Ok(envelope(+ thread_to_summary(thread),+ Some(counts([("num_threads", 1)])),+ None,+ ))+}++/// Sets a user-specified title on a conversation thread, bypassing AI generation.+pub async fn thread_update_title(+ request: UpdateConversationThreadTitleRequest,+) -> Result<RpcOutcome<ApiEnvelope<ConversationThreadSummary>>, String> {+ let dir = workspace_dir().await?;+ let title = request.title.trim().to_string();+ if title.is_empty() {+ return Err("title must not be empty".to_string());+ }+ let updated = conversations::blocking::update_thread_title(+ dir,+ request.thread_id.clone(),+ title,+ chrono::Utc::now().to_rfc3339(),+ )+ .await+ .map_err(|err| format!("update title: {err}"))?;+ tracing::debug!(+ thread_id = %request.thread_id,+ title_len = updated.title.chars().count(),+ "[threads] user updated thread title"+ );+ Ok(envelope(+ thread_to_summary(updated),+ Some(counts([("num_threads", 1)])),+ None,+ ))+}++/// Updates metadata on an existing conversation message.+pub async fn message_update(+ request: UpdateConversationMessageRequest,+) -> Result<RpcOutcome<ApiEnvelope<ConversationMessageRecord>>, String> {+ let dir = workspace_dir().await?;+ let message = conversations::blocking::update_message(+ dir,+ request.thread_id.clone(),+ request.message_id.clone(),+ ConversationMessagePatch {+ extra_metadata: request.extra_metadata,+ },+ )+ .await?;+ Ok(envelope(+ message_to_record(message),+ Some(counts([("num_messages", 1)])),+ None,+ ))+}++/// Deletes a conversation thread and its message log.+///+/// The store mutation and every cleanup step it implies run inside one+/// [`run_to_completion`] task, so a caller that disconnects mid-delete cannot+/// leave the thread gone from the store with its sessions, sub-agents and turn+/// snapshot still live.+pub async fn thread_delete(+ request: DeleteConversationThreadRequest,+) -> Result<RpcOutcome<ApiEnvelope<DeleteConversationThreadResponse>>, String> {+ let dir = workspace_dir().await?;+ run_to_completion("thread_delete", thread_delete_inner(dir, request)).await+}++async fn thread_delete_inner(+ dir: PathBuf,+ request: DeleteConversationThreadRequest,+) -> Result<RpcOutcome<ApiEnvelope<DeleteConversationThreadResponse>>, String> {+ let deleted = conversations::blocking::delete_thread(+ dir.clone(),+ request.thread_id.clone(),+ request.deleted_at.clone(),+ )+ .await?;+ // Invalidate the in-process web-channel session BEFORE the+ // turn-state cleanup. The snapshot deletion is fallible and+ // returns early on error; if invalidation ran after, an active+ // session for the now-deleted thread could linger and try to+ // append to a thread index row that no longer exists.+ web_channel::invalidate_thread_sessions(&request.thread_id).await;+ // Cancel any detached sub-agents this thread spawned BEFORE clearing their+ // queued results: abort the in-flight ones first so a child can't record a+ // completion in the gap between the two calls, then discard anything already+ // queued for delivery. Both target a thread that's being deleted, so there's+ // nowhere left to deliver to — abort + cleanup is the whole behavior.+ let cancelled =+ crate::agent::orchestration::running_subagents::cancel_for_thread(&request.thread_id);+ let discarded = crate::agent::orchestration::background_completions::discard_for_thread(+ &request.thread_id,+ );+ log::debug!(+ "[threads] thread_delete thread_id={} cancelled_subagents={} discarded_completions={}",+ request.thread_id,+ cancelled,+ discarded+ );+ // Drop any persisted in-flight turn snapshot for this thread —+ // otherwise `threads_turn_state_list` keeps surfacing it (as+ // `Interrupted` on next restart) for a thread that no longer+ // exists. Failure here is surfaced as an RPC error so callers+ // can't observe a thread "deleted" while its snapshot (which+ // mirrors conversation-derived state) remains on disk; the+ // thread row itself is already gone at this point so the caller+ // sees a partial failure they can act on instead of silent drift.+ turn_state::store::delete(dir, &request.thread_id).map_err(|err| {+ format!(+ "thread {} deleted but turn-snapshot cleanup failed: {err}",+ request.thread_id+ )+ })?;+ Ok(envelope(+ DeleteConversationThreadResponse { deleted },+ None,+ None,+ ))+}