Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(test): remove unused imports in test files

Steven Enamakel06d8623ebc52
diff --git a/crates/openhuman-app/src/imessage_scanner/tick_tests.rs b/crates/openhuman-app/src/imessage_scanner/tick_tests.rs
new file mode 100644
index 0000000000..353b828092
--- /dev/null
+++ b/crates/openhuman-app/src/imessage_scanner/tick_tests.rs
@@ -0,0 +1,139 @@
+use super::*;
+use parking_lot::Mutex;
+use std::sync::Arc;
+
+struct FakeDeps {
+ gate: anyhow::Result<Option<Vec<String>>>,
+ calls: Arc<Mutex<Vec<(String, String, String)>>>,
+ fail_keys: Vec<String>,
+}
+
+impl FakeDeps {
+ fn new(gate: Option<Vec<String>>) -> Self {
+ Self {
+ gate: Ok(gate),
+ calls: Arc::new(Mutex::new(Vec::new())),
+ fail_keys: Vec::new(),
+ }
+ }
+}
+
+#[async_trait]
+impl TickDeps for FakeDeps {
+ async fn fetch_gate(&self) -> anyhow::Result<Option<Vec<String>>> {
+ match &self.gate {
+ Ok(g) => Ok(g.clone()),
+ Err(e) => Err(anyhow::anyhow!("{}", e)),
+ }
+ }
+ async fn ingest_group(
+ &self,
+ account_id: &str,
+ key: &str,
+ transcript: String,
+ ) -> anyhow::Result<()> {
+ if self.fail_keys.iter().any(|k| k == key) {
+ anyhow::bail!("forced failure for key={}", key);
+ }
+ self.calls
+ .lock()
+ .push((account_id.to_string(), key.to_string(), transcript));
+ Ok(())
+ }
+}
+
+fn chat_db() -> Option<PathBuf> {
+ super::super::chat_db_path().filter(|p| p.exists())
+}
+
+#[tokio::test]
+async fn skips_when_gate_disconnected() {
+ let deps = FakeDeps::new(None);
+ let out = run_single_tick(
+ TickInput {
+ db_path: PathBuf::from("/nonexistent/chat.db"),
+ last_rowid: 0,
+ account_id: "test".into(),
+ },
+ &deps,
+ )
+ .await
+ .unwrap();
+ assert!(out.skipped_unconnected);
+ assert_eq!(out.groups_attempted, 0);
+ assert_eq!(out.new_rowid, 0);
+ assert!(deps.calls.lock().is_empty());
+}
+
+#[tokio::test]
+#[ignore]
+async fn run_single_tick_ingests_groups_from_real_chatdb() {
+ let Some(db) = chat_db() else {
+ eprintln!("chat.db not available — skipping");
+ return;
+ };
+ let deps = FakeDeps::new(Some(vec!["*".into()]));
+ let out = run_single_tick(
+ TickInput {
+ db_path: db,
+ last_rowid: 0,
+ account_id: "local".into(),
+ },
+ &deps,
+ )
+ .await
+ .unwrap();
+ assert!(!out.skipped_unconnected);
+ assert!(
+ out.groups_ingested >= 1,
+ "expected at least one group ingested from real chat.db, got {:?}",
+ out
+ );
+ assert!(out.new_rowid > 0);
+ let calls = deps.calls.lock();
+ assert_eq!(calls.len(), out.groups_ingested);
+ for (acct, key, transcript) in calls.iter() {
+ assert_eq!(acct, "local");
+ assert!(key.contains(':'), "key missing YMD: {}", key);
+ assert!(!transcript.is_empty());
+ }
+}
+
+#[tokio::test]
+#[ignore]
+async fn run_single_tick_keeps_cursor_on_group_failure() {
+ let Some(db) = chat_db() else {
+ return;
+ };
+ // First, sniff one key so we know what to fail.
+ let probe = FakeDeps::new(Some(vec!["*".into()]));
+ let _ = run_single_tick(
+ TickInput {
+ db_path: db.clone(),
+ last_rowid: 0,
+ account_id: "probe".into(),
+ },
+ &probe,
+ )
+ .await
+ .unwrap();
+ let Some(first_key) = probe.calls.lock().first().map(|(_, k, _)| k.clone()) else {
+ eprintln!("no groups in chat.db — skipping");
+ return;
+ };
+
+ let mut deps = FakeDeps::new(Some(vec!["*".into()]));
+ deps.fail_keys = vec![first_key];
+ let out = run_single_tick(
+ TickInput {
+ db_path: db,
+ last_rowid: 0,
+ account_id: "fail".into(),
+ },
+ &deps,
+ )
+ .await
+ .unwrap();
+ assert!(out.had_group_failure);
+ assert_eq!(out.new_rowid, 0, "cursor must stay on failure");
+}
diff --git a/crates/openhuman-app/src/loopback_oauth_tests.rs b/crates/openhuman-app/src/loopback_oauth_tests.rs
new file mode 100644
index 0000000000..f5518d2160
--- /dev/null
+++ b/crates/openhuman-app/src/loopback_oauth_tests.rs
@@ -0,0 +1,148 @@
+use super::*;
+
+#[test]
+fn parses_get_request_target() {
+ let head = "GET /auth?token=abc&state=xyz HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
+ assert_eq!(
+ parse_request_target(head),
+ Some("/auth?token=abc&state=xyz")
+ );
+}
+
+#[test]
+fn rejects_non_get_methods() {
+ let head = "POST /auth HTTP/1.1\r\n\r\n";
+ assert_eq!(parse_request_target(head), None);
+}
+
+#[test]
+fn extracts_state_value() {
+ assert_eq!(extract_state("token=abc&state=xyz"), Some("xyz"));
+ assert_eq!(extract_state("state=only"), Some("only"));
+ assert_eq!(extract_state("token=abc"), None);
+ assert_eq!(extract_state(""), None);
+}
+
+#[tokio::test]
+async fn random_state_is_32_hex_chars() {
+ let s = random_state_nonce();
+ assert_eq!(s.len(), 32);
+ assert!(s.chars().all(|c| c.is_ascii_hexdigit()));
+}
+
+// ── classify_request ────────────────────────────────────────────────────
+
+fn auth_head(query: &str) -> String {
+ format!("GET /auth{query} HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n")
+}
+
+#[test]
+fn classify_valid_auth_request_returns_callback_url() {
+ let head = auth_head("?token=jwt&state=deadbeef");
+ let outcome = classify_request(&head, "deadbeef", 53824);
+ assert_eq!(
+ outcome,
+ RequestOutcome::AuthCallback {
+ callback_url: "http://127.0.0.1:53824/auth?token=jwt&state=deadbeef".to_string()
+ }
+ );
+}
+
+#[test]
+fn classify_wrong_state_returns_state_mismatch() {
+ let head = auth_head("?token=jwt&state=wrong");
+ assert_eq!(
+ classify_request(&head, "correct", 53824),
+ RequestOutcome::StateMismatch
+ );
+}
+
+#[test]
+fn classify_missing_state_returns_state_mismatch() {
+ let head = auth_head("?token=jwt");
+ assert_eq!(
+ classify_request(&head, "expected", 53824),
+ RequestOutcome::StateMismatch
+ );
+}
+
+#[test]
+fn classify_no_query_string_on_auth_path_returns_state_mismatch() {
+ let head = "GET /auth HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
+ assert_eq!(
+ classify_request(head, "nonce", 53824),
+ RequestOutcome::StateMismatch
+ );
+}
+
+#[test]
+fn classify_favicon_returns_not_found() {
+ let head = "GET /favicon.ico HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
+ assert_eq!(
+ classify_request(head, "state", 53824),
+ RequestOutcome::NotFound
+ );
+}
+
+#[test]
+fn classify_root_path_returns_not_found() {
+ let head = "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
+ assert_eq!(
+ classify_request(head, "state", 53824),
+ RequestOutcome::NotFound
+ );
+}
+
+#[test]
+fn classify_post_method_returns_method_not_allowed() {
+ let head = "POST /auth?state=abc HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";
+ assert_eq!(
+ classify_request(head, "abc", 53824),
+ RequestOutcome::MethodNotAllowed
+ );
+}
+
+#[test]
+fn classify_callback_url_uses_bound_port() {
+ let head = auth_head("?state=s&token=t");
+ let outcome = classify_request(&head, "s", 12345);
+ assert_eq!(
+ outcome,
+ RequestOutcome::AuthCallback {
+ callback_url: "http://127.0.0.1:12345/auth?state=s&token=t".to_string()
+ }
+ );
+}
+
+#[test]
+fn classify_state_only_query_returns_callback() {
+ // Minimal valid request: only state param, no other query params.
+ let head = auth_head("?state=abc123");
+ assert_eq!(
+ classify_request(&head, "abc123", 53824),
+ RequestOutcome::AuthCallback {
+ callback_url: "http://127.0.0.1:53824/auth?state=abc123".to_string()
+ }
+ );
+}
+
+// ── bind_loopback (integration: real OS socket) ─────────────────────────
+
+#[tokio::test]
+async fn bind_loopback_succeeds_on_ephemeral_port() {
+ let listener = bind_loopback(0).expect("bind on port 0 must succeed");
+ let addr = listener.local_addr().expect("must have local addr");
+ assert!(addr.ip().is_loopback());
+ assert_ne!(addr.port(), 0, "OS should assign a non-zero ephemeral port");
+}
+
+#[tokio::test]
+async fn bind_loopback_allows_rebind_via_so_reuseaddr() {
+ // Bind once, drop the listener, then bind again on the same port. The
+ // short TIME_WAIT window should not block the rebind because we set
+ // SO_REUSEADDR.
+ let listener = bind_loopback(0).expect("first bind");
+ let port = listener.local_addr().unwrap().port();
+ drop(listener);
+ let _ = bind_loopback(port).expect("rebind on same port must succeed with SO_REUSEADDR");
+}
diff --git a/crates/openhuman-app/src/mcp_commands_tests.rs b/crates/openhuman-app/src/mcp_commands_tests.rs
new file mode 100644
index 0000000000..d6407a0424
--- /dev/null
+++ b/crates/openhuman-app/src/mcp_commands_tests.rs
@@ -0,0 +1,131 @@
+use super::*;
+
+// -------------------------------------------------------------------------
+// config_path_for_client — pure path resolution tests
+// -------------------------------------------------------------------------
+
+#[test]
+fn config_path_claude_desktop_macos() {
+ let path =
+ config_path_for_client("claude-desktop", "macos").expect("should resolve on macos");
+ let s = path.display().to_string();
+ assert!(
+ s.contains("Library/Application Support/Claude/claude_desktop_config.json"),
+ "unexpected path: {s}"
+ );
+}
+
+#[test]
+fn config_path_claude_desktop_linux() {
+ let path =
+ config_path_for_client("claude-desktop", "linux").expect("should resolve on linux");
+ let s = path.display().to_string();
+ assert!(
+ s.contains(".config/Claude/claude_desktop_config.json"),
+ "unexpected path: {s}"
+ );
+}
+
+#[test]
+fn config_path_cursor_macos() {
+ let path = config_path_for_client("cursor", "macos").expect("should resolve");
+ let s = path.display().to_string();
+ assert!(s.ends_with(".cursor/mcp.json"), "unexpected path: {s}");
+}
+
+#[test]
+fn config_path_cursor_linux() {
+ let path = config_path_for_client("cursor", "linux").expect("should resolve");
+ let s = path.display().to_string();
+ assert!(s.ends_with(".cursor/mcp.json"), "unexpected path: {s}");
+}
+
+#[test]
+fn config_path_codex_all_platforms() {
+ for os in &["macos", "windows", "linux"] {
+ let path = config_path_for_client("codex", os)
+ .unwrap_or_else(|_| panic!("should resolve for os={os}"));
+ let s = path.display().to_string();
+ assert!(
+ s.ends_with(".codex/config.json"),
+ "unexpected path for os={os}: {s}"
+ );
+ }
+}
+
+#[test]
+fn config_path_zed_macos() {
+ let path = config_path_for_client("zed", "macos").expect("should resolve");
+ let s = path.display().to_string();
+ assert!(
+ s.contains("Library/Application Support/Zed/settings.json"),
+ "unexpected path: {s}"
+ );
+}
+
+#[test]
+fn config_path_zed_linux() {
+ let path = config_path_for_client("zed", "linux").expect("should resolve");
+ let s = path.display().to_string();
+ assert!(
+ s.contains(".config/zed/settings.json"),
+ "unexpected path: {s}"
+ );
+}
+
+#[test]
+fn config_path_unknown_client_returns_err() {
+ let result = config_path_for_client("unknown-client", "macos");
+ assert!(result.is_err(), "unknown client should return Err");
+ let err = result.unwrap_err();
+ assert!(
+ err.contains("Unknown MCP client: unknown-client"),
+ "unexpected error message: {err}"
+ );
+}
+
+// -------------------------------------------------------------------------
+// mcp_resolve_binary_path — integration-style test (path must exist in dev)
+// -------------------------------------------------------------------------
+
+/// In debug builds (the only mode in which `cargo test` runs), the binary
+/// path resolver should either find `OPENHUMAN_CORE_BINARY_PATH` or locate
+/// `target/debug/openhuman-core` by walking up from the test executable.
+///
+/// We only assert the path *contains* `openhuman-core` — the binary may or
+/// may not exist on disk in a fresh checkout, so we don't assert `Ok` here;
+/// instead we verify the error message is sensible when the file is absent.
+#[test]
+fn binary_path_result_contains_openhuman_core() {
+ match resolve_binary_path() {
+ Ok(p) => {
+ let s = p.display().to_string();
+ assert!(
+ s.contains("openhuman-core"),
+ "resolved path should contain 'openhuman-core', got: {s}"
+ );
+ }
+ Err(e) => {
+ // Acceptable in a clean CI checkout where the binary hasn't
+ // been built yet. The error must be descriptive.
+ assert!(
+ e.contains("openhuman-core")
+ || e.contains("current_exe")
+ || e.contains("target"),
+ "error message should reference the binary or path: {e}"
+ );
+ }
+ }
+}
+
+#[test]
+fn find_debug_binary_returns_none_for_empty_dir() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ // Walk up from a fresh tempdir in the system temp folder — no ancestor
+ // of /tmp (or equivalent) will contain target/debug/openhuman-core.
+ let result = find_debug_binary_walking_up(dir.path());
+ assert!(
+ result.is_none(),
+ "expected None walking up from an empty tempdir, got: {result:?}"
+ );
+}
diff --git a/crates/openhuman-app/src/native_notifications/native_notifications_tests.rs b/crates/openhuman-app/src/native_notifications/native_notifications_tests.rs
new file mode 100644
index 0000000000..f36ded40d6
--- /dev/null
+++ b/crates/openhuman-app/src/native_notifications/native_notifications_tests.rs
@@ -0,0 +1,46 @@
+ use super::*;
+
+ #[test]
+ fn is_granted_treats_authorized_variants_as_granted() {
+ assert!(is_granted("granted"));
+ assert!(is_granted("provisional"));
+ assert!(is_granted("ephemeral"));
+ }
+
+ #[test]
+ fn is_granted_rejects_unauthorized_states() {
+ assert!(!is_granted("denied"));
+ assert!(!is_granted("not_determined"));
+ assert!(!is_granted("unknown"));
+ assert!(!is_granted(""));
+ }
+
+ #[test]
+ fn status_to_str_maps_known_statuses() {
+ assert_eq!(status_to_str(UNAuthorizationStatus::Authorized), "granted");
+ assert_eq!(status_to_str(UNAuthorizationStatus::Denied), "denied");
+ assert_eq!(
+ status_to_str(UNAuthorizationStatus::NotDetermined),
+ "not_determined"
+ );
+ assert_eq!(
+ status_to_str(UNAuthorizationStatus::Provisional),
+ "provisional"
+ );
+ assert_eq!(status_to_str(UNAuthorizationStatus::Ephemeral), "ephemeral");
+ }
+
+ #[test]
+ fn bundled_app_layout_is_accepted() {
+ assert!(is_bundled_app_executable(Path::new(
+ "/Applications/OpenHuman.app/Contents/MacOS/OpenHuman"
+ )));
+ }
+
+ #[test]
+ fn unbundled_executable_is_rejected() {
+ assert!(!is_bundled_app_executable(Path::new(
+ "/tmp/openhuman/target/debug/OpenHuman"
+ )));
+ }
+}
diff --git a/crates/openhuman-app/src/reset_reboot_schedule_tests.rs b/crates/openhuman-app/src/reset_reboot_schedule_tests.rs
new file mode 100644
index 0000000000..1c70e8258e
--- /dev/null
+++ b/crates/openhuman-app/src/reset_reboot_schedule_tests.rs
@@ -0,0 +1,158 @@
+use super::*;
+
+/// Test-only no-op scheduler. Lets the traversal/counting tests run
+/// in any user context (incl. non-administrator) by sidestepping the
+/// `MoveFileExW + MOVEFILE_DELAY_UNTIL_REBOOT` call that would
+/// otherwise need HKLM write access. We capture the call order so a
+/// regression in depth-first ordering would surface as a wrong path
+/// sequence here, even though the real OS-side scheduling stays
+/// out of the test process.
+fn noop_scheduler(
+ captured: &mut Vec<std::path::PathBuf>,
+) -> impl FnMut(&Path) -> io::Result<()> + '_ {
+ move |path: &Path| {
+ captured.push(path.to_path_buf());
+ Ok(())
+ }
+}
+
+#[test]
+fn schedule_walks_files_then_dirs() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let root = dir.path().join("reset-target");
+ std::fs::create_dir_all(root.join("nested")).expect("mkdir nested");
+ std::fs::write(root.join("a.txt"), b"a").expect("write a.txt");
+ std::fs::write(root.join("nested").join("b.txt"), b"b").expect("write b.txt");
+
+ let mut captured = Vec::new();
+ let summary =
+ schedule_path_with_scheduler(&root, &mut noop_scheduler(&mut captured)).expect("walk");
+
+ // root + nested == 2 dirs; a.txt + nested/b.txt == 2 files
+ assert_eq!(summary.files, 2, "expected 2 files queued, got {summary:?}");
+ assert_eq!(summary.dirs, 2, "expected 2 dirs queued, got {summary:?}");
+ assert_eq!(summary.total(), 4);
+ assert!(!summary.partial, "Ok must not flag partial");
+
+ // Depth-first: a parent must only appear after all of its children.
+ // Track per-path positions in the call order, then assert each
+ // directory sits after every entry whose path is rooted inside it.
+ let position = |needle: &Path| -> usize {
+ captured
+ .iter()
+ .position(|p| p == needle)
+ .unwrap_or_else(|| panic!("missing {} in {captured:?}", needle.display()))
+ };
+ let root_pos = position(&root);
+ let nested_pos = position(&root.join("nested"));
+ let a_pos = position(&root.join("a.txt"));
+ let b_pos = position(&root.join("nested").join("b.txt"));
+ assert!(
+ b_pos < nested_pos,
+ "b.txt must be scheduled before its parent (nested)"
+ );
+ assert!(
+ nested_pos < root_pos && a_pos < root_pos,
+ "nested + a.txt must be scheduled before root"
+ );
+}
+
+#[test]
+fn schedule_single_file_reports_one_file() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let file = dir.path().join("solo.txt");
+ std::fs::write(&file, b"x").expect("write solo.txt");
+
+ let mut captured = Vec::new();
+ let summary =
+ schedule_path_with_scheduler(&file, &mut noop_scheduler(&mut captured)).expect("walk");
+
+ assert_eq!(
+ summary,
+ RebootDeletionSchedule {
+ files: 1,
+ dirs: 0,
+ partial: false,
+ }
+ );
+ assert_eq!(captured, vec![file]);
+}
+
+#[test]
+fn schedule_missing_path_yields_not_found() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let missing = dir.path().join("does-not-exist");
+
+ let mut captured = Vec::new();
+ let failure = schedule_path_with_scheduler(&missing, &mut noop_scheduler(&mut captured))
+ .expect_err("missing");
+ assert_eq!(failure.error.kind(), io::ErrorKind::NotFound);
+ // Nothing scheduled, but partial flag still reports "did not
+ // complete" so callers can distinguish from a clean success.
+ assert!(failure.partial.partial);
+ assert_eq!(failure.partial.files, 0);
+ assert_eq!(failure.partial.dirs, 0);
+ assert!(
+ captured.is_empty(),
+ "no scheduling should have been attempted: {captured:?}"
+ );
+}
+
+#[test]
+fn schedule_empty_dir_counts_one_dir() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let empty = dir.path().join("empty-target");
+ std::fs::create_dir(&empty).expect("mkdir empty-target");
+
+ let mut captured = Vec::new();
+ let summary =
+ schedule_path_with_scheduler(&empty, &mut noop_scheduler(&mut captured)).expect("walk");
+
+ assert_eq!(
+ summary,
+ RebootDeletionSchedule {
+ files: 0,
+ dirs: 1,
+ partial: false,
+ }
+ );
+ assert_eq!(captured, vec![empty]);
+}
+
+#[test]
+fn schedule_propagates_scheduler_failure_with_partial_counts() {
+ // Simulate the non-administrator MoveFileExW failure path: the
+ // walk visits children successfully, then the third call (the
+ // parent dir) errors out. The Err must carry the leaf counts
+ // queued before the failure so the caller can surface "we did
+ // get X files scheduled before this hit the registry wall."
+ let dir = tempfile::tempdir().expect("tempdir");
+ let root = dir.path().join("partial-fail");
+ std::fs::create_dir_all(&root).expect("mkdir");
+ std::fs::write(root.join("a.txt"), b"a").expect("write a.txt");
+ std::fs::write(root.join("b.txt"), b"b").expect("write b.txt");
+
+ let root_path = root.clone();
+ let mut count = 0usize;
+ let mut scheduler = |path: &Path| -> io::Result<()> {
+ count += 1;
+ if path == root_path {
+ Err(io::Error::new(
+ io::ErrorKind::PermissionDenied,
+ "simulated non-admin MoveFileExW failure",
+ ))
+ } else {
+ Ok(())
+ }
+ };
+
+ let failure =
+ schedule_path_with_scheduler(&root, &mut scheduler).expect_err("scheduler failed");
+ assert_eq!(failure.error.kind(), io::ErrorKind::PermissionDenied);
+ assert!(failure.partial.partial);
+ // Both leaf files were scheduled before the parent-dir call failed.
+ assert_eq!(failure.partial.files, 2, "got {:?}", failure.partial);
+ assert_eq!(failure.partial.dirs, 0, "got {:?}", failure.partial);
+ // Sanity: scheduler was called for both leaves + the parent.
+ assert_eq!(count, 3);
+}
diff --git a/crates/openhuman-app/src/stderr_panic_hook_tests.rs b/crates/openhuman-app/src/stderr_panic_hook_tests.rs
new file mode 100644
index 0000000000..4c27a99feb
--- /dev/null
+++ b/crates/openhuman-app/src/stderr_panic_hook_tests.rs
@@ -0,0 +1,100 @@
+use super::*;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+
+#[test]
+fn classifies_windows_pipe_closing_232_as_broken_pipe() {
+ assert!(is_broken_pipe_stderr_panic(
+ "failed printing to stderr: The pipe is being closed. (os error 232)"
+ ));
+}
+
+#[test]
+fn classifies_chinese_locale_variant_via_os_error_code() {
+ // Localized strerror, but the `(os error 232)` suffix is locale-stable.
+ assert!(is_broken_pipe_stderr_panic(
+ "failed printing to stderr: 管道正在被关闭。 (os error 232)"
+ ));
+}
+
+#[test]
+fn classifies_windows_broken_pipe_109() {
+ assert!(is_broken_pipe_stderr_panic(
+ "failed printing to stderr: The pipe has been ended. (os error 109)"
+ ));
+}
+
+#[test]
+fn classifies_posix_epipe_32() {
+ assert!(is_broken_pipe_stderr_panic(
+ "failed printing to stderr: Broken pipe (os error 32)"
+ ));
+}
+
+#[test]
+fn does_not_classify_assertion_panic() {
+ assert!(!is_broken_pipe_stderr_panic(
+ "assertion `left == right` failed\n left: 1\n right: 2"
+ ));
+}
+
+#[test]
+fn does_not_classify_arbitrary_panic() {
+ assert!(!is_broken_pipe_stderr_panic(
+ "index out of bounds: the len is 0 but the index is 3"
+ ));
+}
+
+#[test]
+fn does_not_classify_stdout_broken_pipe() {
+ assert!(!is_broken_pipe_stderr_panic(
+ "failed printing to stdout: The pipe is being closed. (os error 232)"
+ ));
+}
+
+#[test]
+fn does_not_classify_stderr_panic_with_unrelated_error() {
+ assert!(!is_broken_pipe_stderr_panic(
+ "failed printing to stderr: Permission denied (os error 13)"
+ ));
+}
+
+#[test]
+fn empty_message_is_not_broken_pipe() {
+ assert!(!is_broken_pipe_stderr_panic(""));
+}
+
+// The contract the Codex review demanded: the hook must NEVER hide a crash
+// from Sentry. `handle_panic` must call `chain` for EVERY panic — including
+// the broken-pipe family it used to swallow.
+fn run_handle_panic_and_record_chain(panic_msg: &'static str) -> bool {
+ let chained = Arc::new(AtomicBool::new(false));
+ let chained_for_hook = Arc::clone(&chained);
+ // Trigger a panic to obtain a real PanicHookInfo, observe it in our hook.
+ let prev = std::panic::take_hook();
+ std::panic::set_hook(Box::new(move |info| {
+ let flag = Arc::clone(&chained_for_hook);
+ handle_panic(info, &move |_| flag.store(true, Ordering::SeqCst));
+ }));
+ let _ = std::panic::catch_unwind(|| panic!("{panic_msg}"));
+ std::panic::set_hook(prev);
+ chained.load(Ordering::SeqCst)
+}
+
+// Combined into one test: each case installs the GLOBAL panic hook, so they
+// must run serially (cargo parallelises separate #[test] fns).
+#[test]
+fn every_panic_class_chains_to_previous_hook() {
+ // The exact broken-pipe case that used to be swallowed must now reach
+ // Sentry (Codex review, PR #3772) — and so must an ordinary panic.
+ assert!(
+ run_handle_panic_and_record_chain(
+ "failed printing to stderr: The pipe is being closed. (os error 232)"
+ ),
+ "broken-pipe stderr panic must still chain to the previous (Sentry) hook"
+ );
+ assert!(
+ run_handle_panic_and_record_chain("assertion `left == right` failed"),
+ "ordinary panic must chain to the previous (Sentry) hook"
+ );
+}
diff --git a/crates/openhuman-app/src/window_state_tests.rs b/crates/openhuman-app/src/window_state_tests.rs
new file mode 100644
index 0000000000..554dcb19ee
--- /dev/null
+++ b/crates/openhuman-app/src/window_state_tests.rs
@@ -0,0 +1,431 @@
+use super::*;
+
+#[test]
+fn window_state_toml_roundtrips() {
+ // `save_main` serializes this record to `window_state.toml` and
+ // `restore_main` parses it back on the next launch. The whole
+ // save-on-quit → restore-on-launch feature (#4810) hinges on this
+ // record surviving the round trip byte-for-byte, including a
+ // negative x from a monitor left of the primary. Guards the
+ // on-disk contract against an accidental serde/rename change.
+ let state = WindowState {
+ x: -1920,
+ y: 100,
+ width: 1280,
+ height: 800,
+ };
+ let raw = toml::to_string_pretty(&state).expect("serialize");
+ let parsed: WindowState = toml::from_str(&raw).expect("parse");
+ assert_eq!(
+ (parsed.x, parsed.y, parsed.width, parsed.height),
+ (state.x, state.y, state.width, state.height)
+ );
+}
+
+fn wa(x: i32, y: i32, width: u32, height: u32) -> WorkArea {
+ wa_dpi(x, y, width, height, 1.0)
+}
+
+/// Same as [`wa`] but with an explicit DPI scale factor, for the
+/// mixed-DPI cases in #5041.
+fn wa_dpi(x: i32, y: i32, width: u32, height: u32, scale: f64) -> WorkArea {
+ WorkArea {
+ x,
+ y,
+ width,
+ height,
+ scale,
+ }
+}
+
+/// The reporter's layout from #5041: a 2560x1600 @ 150 % primary at
+/// the virtual-desktop origin, and a 1920x1080 @ 100 % secondary
+/// placed to its **left** (so the secondary's origin is negative).
+/// Work areas subtract a plausible taskbar.
+fn reporter_layout() -> (WorkArea, WorkArea) {
+ let primary = wa_dpi(0, 0, 2560, 1520, 1.5);
+ let secondary = wa_dpi(-1920, 0, 1920, 1032, 1.0);
+ (primary, secondary)
+}
+
+#[test]
+fn clamp_leaves_in_bounds_geometry_alone() {
+ // 1280×800 work area, 1000×800 window centered-ish: width fits,
+ // height fits exactly — nothing should change.
+ let work_area = wa(0, 0, 1280, 800);
+ let (x, y, w, h) = clamp_to_work_area(100, 0, 1000, 800, work_area);
+ assert_eq!((x, y, w, h), (100, 0, 1000, 800));
+}
+
+#[test]
+fn clamp_shrinks_window_taller_than_work_area() {
+ // Repro for #2282: default 1000×800 on a 1280×720 work area
+ // (e.g. macOS 13" Air with menu bar+dock visible). Height
+ // shrinks to the work area height so bottom nav stays visible.
+ let work_area = wa(0, 0, 1280, 720);
+ let (x, y, w, h) = clamp_to_work_area(0, 0, 1000, 800, work_area);
+ assert_eq!(w, 1000);
+ assert_eq!(h, 720);
+ assert_eq!((x, y), (0, 0));
+}
+
+#[test]
+fn clamp_shrinks_window_wider_than_work_area() {
+ let work_area = wa(0, 0, 800, 600);
+ let (_, _, w, h) = clamp_to_work_area(0, 0, 1600, 1200, work_area);
+ assert_eq!(w, 800);
+ assert_eq!(h, 600);
+}
+
+#[test]
+fn clamp_respects_minimum_size_on_tiny_work_area() {
+ // Pathological tiny work area: don't shrink below the usability
+ // floor. (User can still scroll/resize; better than a 0×0 sliver.)
+ let work_area = wa(0, 0, 200, 150);
+ let (_, _, w, h) = clamp_to_work_area(0, 0, 1000, 800, work_area);
+ assert_eq!(w, MIN_WINDOW_WIDTH);
+ assert_eq!(h, MIN_WINDOW_HEIGHT);
+}
+
+#[test]
+fn clamp_pushes_window_back_inside_when_off_right_or_bottom() {
+ // Saved at (1200, 700) sized 1000×800 — bottom-right is far
+ // outside the 1280×800 work area. Position should shift left
+ // and up so the *whole frame* fits inside the work area.
+ let work_area = wa(0, 0, 1280, 800);
+ let (x, y, w, h) = clamp_to_work_area(1200, 700, 1000, 800, work_area);
+ assert_eq!(w, 1000);
+ assert_eq!(h, 800);
+ assert_eq!(x, 1280 - 1000);
+ assert_eq!(y, 0);
+}
+
+#[test]
+fn clamp_handles_negative_position_on_offset_monitor() {
+ // Secondary monitor positioned to the left of the primary —
+ // origin is at (-1920, 0). A saved window slightly left of that
+ // monitor's left edge should be pulled inward.
+ let work_area = wa(-1920, 0, 1920, 1080);
+ let (x, y, _, _) = clamp_to_work_area(-2000, 100, 1000, 800, work_area);
+ assert_eq!(x, -1920);
+ assert_eq!(y, 100);
+}
+
+#[test]
+fn work_area_fill_uses_the_whole_work_area_on_a_normal_monitor() {
+ let (x, y, w, h) = work_area_fill_geometry(wa(0, 60, 3600, 2190));
+ assert_eq!((x, y), (0, 60));
+ assert_eq!((w, h), (3600, 2190));
+}
+
+#[test]
+fn work_area_fill_keeps_the_offset_of_a_secondary_monitor() {
+ // A monitor to the left of the primary has a negative origin; filling
+ // its work area must land there, not at (0, 0).
+ let (x, y, w, h) = work_area_fill_geometry(wa(-1920, 0, 1920, 1080));
+ assert_eq!((x, y), (-1920, 0));
+ assert_eq!((w, h), (1920, 1080));
+}
+
+#[test]
+fn work_area_fill_never_goes_below_the_minimum_window_size() {
+ // The invariant this helper exists for: a work area smaller than
+ // MIN_WINDOW_* must still produce at least the minimum, matching what
+ // `restore_main` and `center_main` guarantee.
+ let (_, _, w, h) = work_area_fill_geometry(wa(0, 0, 320, 200));
+ assert_eq!((w, h), (MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT));
+}
+
+#[test]
+fn clamp_size_only_caps_to_work_area() {
+ let work_area = wa(0, 0, 1024, 600);
+ let (w, h) = clamp_size(1600, 1200, &work_area);
+ assert_eq!((w, h), (1024, 600));
+}
+
+#[test]
+fn clamp_size_below_minimum_floor_returns_minimum() {
+ let work_area = wa(0, 0, 200, 150);
+ let (w, h) = clamp_size(100, 50, &work_area);
+ assert_eq!((w, h), (MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT));
+}
+
+#[test]
+fn pick_monitor_finds_overlapping_monitor() {
+ let monitors = vec![wa(0, 0, 1920, 1080), wa(1920, 0, 1280, 800)];
+ // Window sits on the secondary monitor (right of primary).
+ let m = pick_monitor_for_window(2000, 100, 1000, 700, &monitors).unwrap();
+ assert_eq!((m.x, m.width), (1920, 1280));
+}
+
+#[test]
+fn pick_monitor_returns_none_when_window_off_every_screen() {
+ // Saved on a now-disconnected display (large positive offset).
+ let monitors = vec![wa(0, 0, 1920, 1080)];
+ let m = pick_monitor_for_window(5000, 5000, 1000, 800, &monitors);
+ assert!(
+ m.is_none(),
+ "off-screen window should not match any monitor"
+ );
+}
+
+#[test]
+fn pick_monitor_requires_minimum_overlap() {
+ // Window only intersects the monitor by a 50px sliver — below
+ // the 100px threshold, so we treat it as off-screen.
+ let monitors = vec![wa(0, 0, 1920, 1080)];
+ let m = pick_monitor_for_window(-950, 100, 1000, 700, &monitors);
+ assert!(m.is_none(), "sub-threshold overlap should not match");
+}
+
+#[test]
+fn pick_monitor_handles_empty_list() {
+ let m = pick_monitor_for_window(0, 0, 1000, 800, &[]);
+ assert!(m.is_none());
+}
+
+#[test]
+fn pick_monitor_prefers_largest_overlap_for_straddling_window() {
+ // Window at (1820, 0) with 1000×700 straddles two horizontally
+ // adjacent monitors: 100×700 = 70 000 px² on the primary,
+ // 900×700 = 630 000 px² on the secondary. Must pick the
+ // secondary regardless of `available_monitors()` ordering.
+ let primary = wa(0, 0, 1920, 1080);
+ let secondary = wa(1920, 0, 1280, 800);
+ // Primary first.
+ let m = pick_monitor_for_window(1820, 0, 1000, 700, &[primary, secondary]).unwrap();
+ assert_eq!((m.x, m.width), (1920, 1280));
+ // Secondary first — same answer.
+ let m = pick_monitor_for_window(1820, 0, 1000, 700, &[secondary, primary]).unwrap();
+ assert_eq!((m.x, m.width), (1920, 1280));
+}
+
+// ── Mixed-DPI multi-monitor (#5041) ──────────────────────────────
+
+#[test]
+fn dpi_adjusted_size_grows_when_moving_to_a_higher_dpi_monitor() {
+ // The #5041 arithmetic: a window fitted to the 150 % primary's
+ // 2560 px work-area width while still sitting on the 100 %
+ // secondary arrives at 3840 px — wider than the very monitor it
+ // was just fitted to. This is the reported ~3875 px window.
+ let (grown_w, grown_h) = dpi_adjusted_size(2560, 1520, 1.0, 1.5);
+ assert_eq!(grown_w, 3840);
+ assert_eq!(grown_h, 2280);
+}
+
+#[test]
+fn dpi_adjusted_size_shrinks_when_moving_to_a_lower_dpi_monitor() {
+ let (w, h) = dpi_adjusted_size(3840, 2280, 1.5, 1.0);
+ assert_eq!((w, h), (2560, 1520));
+}
+
+#[test]
+fn dpi_adjusted_size_is_identity_at_equal_scale() {
+ assert_eq!(dpi_adjusted_size(1280, 900, 1.5, 1.5), (1280, 900));
+ assert_eq!(dpi_adjusted_size(1280, 900, 1.0, 1.0), (1280, 900));
+}
+
+#[test]
+fn dpi_adjusted_size_round_trips_without_drift() {
+ // A→B→A must land back on the original size; truncating instead
+ // of rounding would lose a pixel on every move.
+ //
+ // Covers the whole standard DPI ladder rather than just 1.0↔1.5:
+ // a single pair does not establish the property (review, #5041).
+ // Odd dimensions are deliberate — even ones round-trip trivially.
+ const SIZES: [(u32, u32); 3] = [(1281, 901), (1920, 1080), (2560, 1600)];
+
+ // Upscale first: exact. This is the common case — a window sized
+ // on a low-DPI monitor moves to a high-DPI one and back.
+ for (from, to) in [
+ (1.0, 1.25),
+ (1.0, 1.5),
+ (1.0, 1.75),
+ (1.0, 2.0),
+ (1.25, 1.5),
+ (1.5, 2.0),
+ ] {
+ for (w, h) in SIZES {
+ let (up_w, up_h) = dpi_adjusted_size(w, h, from, to);
+ let (back_w, back_h) = dpi_adjusted_size(up_w, up_h, to, from);
+ assert_eq!(
+ (back_w, back_h),
+ (w, h),
+ "upscale-first round trip {w}x{h} at {from}->{to}->{from} drifted to {back_w}x{back_h}"
+ );
+ }
+ }
+
+ // Downscale first: bounded, not exact. The intermediate size has
+ // genuinely lost information (1281 at 2.0->1.25 is 801, and 801
+ // back up is 1282), so the contract is that the error stays
+ // within 1 px and never accumulates — which is precisely what
+ // truncation fails to do.
+ for (from, to) in [(2.0, 1.25), (1.75, 1.0), (2.0, 1.0), (1.5, 1.25)] {
+ for (w, h) in SIZES {
+ let (down_w, down_h) = dpi_adjusted_size(w, h, from, to);
+ let (back_w, back_h) = dpi_adjusted_size(down_w, down_h, to, from);
+ assert!(
+ back_w.abs_diff(w) <= 1 && back_h.abs_diff(h) <= 1,
+ "downscale-first round trip {w}x{h} at {from}->{to}->{from} drifted to {back_w}x{back_h}, beyond the 1px bound"
+ );
+ }
+ }
+}
+
+#[test]
+fn dpi_adjusted_size_rejects_unusable_scale_factors() {
+ // A runtime reporting 0.0 / NaN / infinity must not zero out or
+ // panic the window size — return the input untouched instead.
+ for (from, to) in [
+ (0.0, 1.5),
+ (1.5, 0.0),
+ (f64::NAN, 1.5),
+ (1.5, f64::NAN),
+ (f64::INFINITY, 1.5),
+ (1.5, f64::INFINITY),
+ (-1.0, 1.5),
+ ] {
+ assert_eq!(
+ dpi_adjusted_size(1280, 900, from, to),
+ (1280, 900),
+ "scale pair ({from}, {to}) must be treated as unusable"
+ );
+ }
+}
+
+#[test]
+fn target_prefers_the_monitor_the_window_is_already_on() {
+ // Window created on the 100 % secondary (negative origin).
+ // Selecting the primary here is what forces the cross-DPI move
+ // that #5041 is about — we must stay put instead.
+ let (primary, secondary) = reporter_layout();
+ let target = target_work_area_for_new_window(
+ -1800,
+ 100,
+ 1280,
+ 900,
+ &[primary, secondary],
+ Some(primary),
+ )
+ .expect("a monitor should be selected");
+ assert_eq!(
+ (target.x, target.width),
+ (secondary.x, secondary.width),
+ "window on the secondary must be sized against the secondary"
+ );
+ assert!(
+ (target.scale - secondary.scale).abs() < f64::EPSILON,
+ "and must carry the secondary's scale factor"
+ );
+}
+
+#[test]
+fn target_falls_back_to_primary_when_window_overlaps_nothing() {
+ // Windows can place a not-yet-shown window at CW_USEDEFAULT,
+ // off every work area.
+ let (primary, secondary) = reporter_layout();
+ let target = target_work_area_for_new_window(
+ 50_000,
+ 50_000,
+ 1280,
+ 900,
+ &[primary, secondary],
+ Some(primary),
+ )
+ .expect("should fall back to primary");
+ assert_eq!((target.x, target.width), (primary.x, primary.width));
+}
+
+#[test]
+fn target_falls_back_to_any_monitor_without_a_primary() {
+ let (primary, secondary) = reporter_layout();
+ let target =
+ target_work_area_for_new_window(50_000, 50_000, 1280, 900, &[secondary, primary], None)
+ .expect("should fall back to the first attached monitor");
+ assert_eq!(target.x, secondary.x);
+}
+
+#[test]
+fn target_returns_none_without_monitors() {
+ assert!(target_work_area_for_new_window(0, 0, 1280, 900, &[], None).is_none());
+}
+
+#[test]
+fn clamp_then_move_overflows_but_move_then_clamp_fits() {
+ // End-to-end regression for #5041, expressed against the pure
+ // helpers so it runs without a Tauri runtime.
+ //
+ // Setup: an oversized window (larger than either work area) is
+ // created on the 100 % secondary and needs to end up on the
+ // 150 % primary.
+ let (primary, _secondary) = reporter_layout();
+ let (created_w, created_h) = (3000, 1700);
+
+ // OLD ordering — clamp to the destination, then move. The OS
+ // rescales by 1.5 on arrival and the result overflows the very
+ // monitor it was fitted to.
+ let (clamped_w, clamped_h) = clamp_size(created_w, created_h, &primary);
+ assert_eq!(
+ (clamped_w, clamped_h),
+ (2560, 1520),
+ "clamp itself is correct"
+ );
+ let (arrived_w, arrived_h) = dpi_adjusted_size(clamped_w, clamped_h, 1.0, 1.5);
+ assert!(
+ arrived_w > primary.width && arrived_h > primary.height,
+ "old ordering must reproduce the oversized window: {arrived_w}x{arrived_h} vs work area {}x{}",
+ primary.width,
+ primary.height
+ );
+
+ // NEW ordering — move first (absorbing the OS rescale), then
+ // clamp against the destination. Result fits.
+ let (moved_w, moved_h) = dpi_adjusted_size(created_w, created_h, 1.0, 1.5);
+ let (final_w, final_h) = clamp_size(moved_w, moved_h, &primary);
+ assert!(
+ final_w <= primary.width && final_h <= primary.height,
+ "new ordering must fit the work area: {final_w}x{final_h} vs {}x{}",
+ primary.width,
+ primary.height
+ );
+}
+
+#[test]
+fn reclamped_geometry_never_leaves_the_work_area_after_a_scale_change() {
+ // What `reclamp_after_scale_change` delegates to: whatever size
+ // the OS imposed on arrival, the window must end up wholly
+ // inside the destination work area.
+ let (primary, _) = reporter_layout();
+ let (os_w, os_h) = dpi_adjusted_size(2560, 1520, 1.0, 1.5);
+ let (x, y, w, h) = clamp_to_work_area(0, 0, os_w, os_h, primary);
+ assert!(w <= primary.width && h <= primary.height);
+ assert!(x >= primary.x && y >= primary.y);
+ assert!(x.saturating_add(w as i32) <= primary.x.saturating_add(primary.width as i32));
+ assert!(y.saturating_add(h as i32) <= primary.y.saturating_add(primary.height as i32));
+}
+
+#[test]
+fn center_origin_after_min_floor_stays_in_work_area() {
+ // Repro for the `center_main` edge case: a pathological work
+ // area smaller than `MIN_WINDOW_*` forces the size to stay at
+ // the minimum floor (480×360), which is larger than the work
+ // area itself (e.g. 200×150). The naive centered origin would
+ // be `(200 - 480)/2 = -140` — title bar off-screen. Running
+ // the centered origin through `clamp_to_work_area` must pin it
+ // back to the work-area top-left so the title bar is at least
+ // reachable.
+ let work_area = wa(0, 0, 200, 150);
+ let clamped_w = MIN_WINDOW_WIDTH;
+ let clamped_h = MIN_WINDOW_HEIGHT;
+ let centered_x = work_area.x + (work_area.width as i32 - clamped_w as i32) / 2;
+ let centered_y = work_area.y + (work_area.height as i32 - clamped_h as i32) / 2;
+ assert!(
+ centered_x < work_area.x,
+ "precondition: naive center should land off-screen"
+ );
+ let (x, y, w, h) =
+ clamp_to_work_area(centered_x, centered_y, clamped_w, clamped_h, work_area);
+ assert_eq!((x, y), (work_area.x, work_area.y));
+ assert_eq!((w, h), (clamped_w, clamped_h));
+}
diff --git a/crates/openhuman-app/src/workspace_paths_tests.rs b/crates/openhuman-app/src/workspace_paths_tests.rs
new file mode 100644
index 0000000000..e2d47a0858
--- /dev/null
+++ b/crates/openhuman-app/src/workspace_paths_tests.rs
@@ -0,0 +1,152 @@
+use super::*;
+use std::fs;
+use tempfile::tempdir;
+
+#[test]
+fn resolve_workspace_path_accepts_existing_relative_file_inside_workspace() {
+ let workspace = tempdir().unwrap();
+ let docs = workspace.path().join("docs");
+ fs::create_dir_all(&docs).unwrap();
+ let file = docs.join("note.md");
+ fs::write(&file, "hello").unwrap();
+
+ let resolved = resolve_workspace_path(workspace.path(), "docs/note.md").unwrap();
+
+ assert_eq!(resolved, file.canonicalize().unwrap());
+}
+
+#[test]
+fn resolve_workspace_path_rejects_parent_directory_escape() {
+ let workspace = tempdir().unwrap();
+
+ let err = resolve_workspace_path(workspace.path(), "../secret.txt").unwrap_err();
+
+ assert!(err.contains("workspace"), "unexpected error: {err}");
+}
+
+#[test]
+fn resolve_workspace_path_rejects_absolute_paths() {
+ let workspace = tempdir().unwrap();
+
+ let err = resolve_workspace_path(workspace.path(), "/etc/passwd").unwrap_err();
+
+ assert!(err.contains("relative"), "unexpected error: {err}");
+}
+
+#[test]
+fn resolve_workspace_path_rejects_uri_scheme_prefix() {
+ let workspace = tempdir().unwrap();
+
+ let err = resolve_workspace_path(workspace.path(), "file://etc/passwd").unwrap_err();
+
+ assert!(err.contains("relative"), "unexpected error: {err}");
+}
+
+#[test]
+fn resolve_workspace_path_accepts_colons_after_first_segment() {
+ let workspace = tempdir().unwrap();
+ let docs = workspace.path().join("docs");
+ fs::create_dir_all(&docs).unwrap();
+ let file = docs.join("2026:05.md");
+ fs::write(&file, "dated").unwrap();
+
+ let resolved = resolve_workspace_path(workspace.path(), "docs/2026:05.md").unwrap();
+
+ assert_eq!(resolved, file.canonicalize().unwrap());
+}
+
+#[test]
+fn resolve_workspace_path_errors_do_not_expose_workspace_root() {
+ let workspace = tempdir().unwrap();
+
+ let err = resolve_workspace_path(workspace.path(), "docs/missing.md").unwrap_err();
+
+ assert!(err.contains("docs/missing.md"), "unexpected error: {err}");
+ assert!(
+ !err.contains(&workspace.path().display().to_string()),
+ "error leaked workspace root: {err}"
+ );
+}
+
+#[test]
+fn preview_workspace_text_from_root_reads_utf8_text() {
+ let workspace = tempdir().unwrap();
+ fs::write(workspace.path().join("readme.md"), "# Hello").unwrap();
+
+ let preview =
+ preview_workspace_text_from_root(workspace.path(), "readme.md", 1024).unwrap();
+
+ assert_eq!(preview.path, "readme.md");
+ assert_eq!(preview.contents, "# Hello");
+ assert!(!preview.truncated);
+ assert_eq!(preview.size_bytes, 7);
+}
+
+#[test]
+fn preview_workspace_text_from_root_truncates_large_text() {
+ let workspace = tempdir().unwrap();
+ fs::write(workspace.path().join("large.md"), "0123456789").unwrap();
+
+ let preview = preview_workspace_text_from_root(workspace.path(), "large.md", 4).unwrap();
+
+ assert_eq!(preview.contents, "0123");
+ assert!(preview.truncated);
+ assert_eq!(preview.size_bytes, 10);
+}
+
+#[test]
+fn preview_workspace_text_from_root_errors_do_not_expose_workspace_root() {
+ let workspace = tempdir().unwrap();
+ fs::create_dir_all(workspace.path().join("docs")).unwrap();
+
+ let err = preview_workspace_text_from_root(workspace.path(), "docs", 1024).unwrap_err();
+
+ assert!(err.contains("docs"), "unexpected error: {err}");
+ assert!(
+ !err.contains(&workspace.path().display().to_string()),
+ "error leaked workspace root: {err}"
+ );
+}
+
+#[test]
+fn resolve_workspace_path_resolves_memory_tree_content_inside_workspace() {
+ let workspace = tempdir().unwrap();
+ let docs = workspace.path().join("memory_tree").join("content");
+ fs::create_dir_all(&docs).unwrap();
+
+ let resolved = resolve_workspace_path(workspace.path(), "memory_tree/content").unwrap();
+
+ let canonical_root = fs::canonicalize(workspace.path()).unwrap();
+ assert!(
+ resolved.starts_with(&canonical_root),
+ "resolved path escaped workspace root: {} not under {}",
+ resolved.display(),
+ canonical_root.display()
+ );
+ assert_eq!(resolved, docs.canonicalize().unwrap());
+}
+
+#[test]
+fn resolve_workspace_path_rejects_empty_whitespace_input() {
+ let workspace = tempdir().unwrap();
+
+ let err = resolve_workspace_path(workspace.path(), " ").unwrap_err();
+
+ assert!(err.contains("empty"), "unexpected error: {err}");
+}
+
+#[cfg(unix)]
+#[test]
+fn resolve_workspace_path_rejects_symlink_escape() {
+ use std::os::unix::fs::symlink;
+
+ let workspace = tempdir().unwrap();
+ let outside = tempdir().unwrap();
+ let outside_file = outside.path().join("secret.txt");
+ fs::write(&outside_file, "secret").unwrap();
+ symlink(&outside_file, workspace.path().join("secret-link")).unwrap();
+
+ let err = resolve_workspace_path(workspace.path(), "secret-link").unwrap_err();
+
+ assert!(err.contains("workspace"), "unexpected error: {err}");
+}
diff --git a/crates/openhuman-core/src/voice/realtime_harness/turn_handler.rs b/crates/openhuman-core/src/voice/realtime_harness/turn_handler.rs
new file mode 100644
index 0000000000..6872bfcdb5
--- /dev/null
+++ b/crates/openhuman-core/src/voice/realtime_harness/turn_handler.rs
@@ -0,0 +1,390 @@
+//! Handling one relayed voice turn end to end: dedup, stream deltas back to
+//! the relay socket, race the turn against the spoken-ack deadline, and hand
+//! a slow turn off to chat delivery in the background.
+
+use std::collections::HashSet;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::{Arc, LazyLock, Mutex};
+use std::time::Duration;
+
+use log::{info, warn};
+use serde_json::{json, Value};
+use tokio::sync::Semaphore;
+
+use crate::agent::progress::AgentProgress;
+
+use super::agent::run_voice_turn;
+use super::chat_delivery::{deliver_voice_failure_to_chat, deliver_voice_result_to_chat, emit_error, emit_event};
+use super::prompt::{extract_prompt, is_answerable_prompt, is_content_free, readback_payload, should_arm_speak_back, spoken_delta};
+
+/// How long a voice turn may run before we stop making the caller wait and hand
+/// the result off to chat. The cloud voice session cancels a turn with no spoken
+/// token in ~11-12s, and a slow tool action (email/calendar summary can be
+/// 20-30s of Composio round-trips) will never fit that window. Once this elapses
+/// we close the voice turn cleanly — the caller has heard the relay's spoken
+/// filler and is told the answer is still coming (see VOICE_HANDOFF_LINES) — and
+/// let the orchestrator finish in the background,
+/// delivering its answer into the user's in-app chat and, while the call is
+/// still up, reading it aloud. Sits under the provider's cancel deadline so
+/// `done` always beats the cut.
+const VOICE_ACK_DEADLINE_SECS: u64 = 8;
+
+/// Spoken when the ack deadline closes a turn that never produced text of its
+/// own, so the caller is told the answer is still coming instead of being left on
+/// a trail of filler.
+///
+/// The model is deliberately not asked to speak first (see VOICE_DIRECTIVE), and
+/// could not be relied on to anyway: building the per-turn orchestrator (config
+/// load, tool registry, integration catalogue) takes seconds before the first
+/// model token is even requested, and the first round is usually a tool call
+/// carrying no text. Measured against staging, the first streamable token landed
+/// ~10.6s into a turn whose whole budget is 8s.
+///
+/// Neutral rather than a promise. "I'll have that for you in a moment" states an
+/// outcome the turn cannot guarantee the shape of: the answer may follow a second
+/// later, or thirty, and on a turn the caller expected to be trivial ("no, not
+/// now") a promise of future delivery reads as the assistant having
+/// misunderstood. A short acknowledgement says the same thing about the only fact
+/// known at this point — work is still going — without committing to when.
+///
+/// Rotated per turn so a caller who hits the deadline twice in a call does not
+/// hear the same words back. Each ends in a full stop deliberately: the provider
+/// synthesises on sentence boundaries, so an unterminated line is buffered rather
+/// than spoken (see `VOICE_FILLERS` in the backend relay).
+///
+/// The answer itself still arrives on both delivery paths — posted to chat and,
+/// while the call is still up, read aloud.
+const VOICE_HANDOFF_LINES: [&str; 4] = [
+ "Still on it. ",
+ "Still going. ",
+ "Still working on it. ",
+ "Bear with me. ",
+];
+static VOICE_HANDOFF_CURSOR: AtomicUsize = AtomicUsize::new(0);
+
+/// Next handoff line, rotating. Pure apart from the cursor; unit-tested.
+fn next_handoff_line() -> &'static str {
+ VOICE_HANDOFF_LINES
+ [VOICE_HANDOFF_CURSOR.fetch_add(1, Ordering::Relaxed) % VOICE_HANDOFF_LINES.len()]
+}
+
+/// Sent for a turn we have nothing to say to.
+///
+/// A turn that ends with no spoken content at all is not a valid answer to the
+/// cloud session: it ends the whole call with `custom_llm_error: LLM Cascade
+/// Error: Brain returned no response` (confirmed live — three recognition
+/// artefacts answered with empty turns killed a working call). So even "nothing
+/// to say" has to say something, and the least intrusive something is an ellipsis
+/// pause, which the provider voices as a beat of silence rather than words.
+const VOICE_SILENT_REPLY: &str = "… ";
+
+/// Cap on concurrent local-agent turns driven by the relay. Each turn loads
+/// config, builds a full orchestrator, and runs for up to `TURN_TIMEOUT_SECS`,
+/// so an unbounded burst (or retry storm) would spawn unbounded heavy agent
+/// sessions. Excess turns queue on the permit rather than piling up.
+const MAX_CONCURRENT_VOICE_TURNS: usize = 3;
+
+static VOICE_TURN_LIMITER: LazyLock<Arc<Semaphore>> =
+ LazyLock::new(|| Arc::new(Semaphore::new(MAX_CONCURRENT_VOICE_TURNS)));
+
+/// Correlation ids currently being processed, so a relay retry that re-delivers
+/// the same `voice:harness` event is deduplicated instead of running the turn
+/// (and charging/emitting) twice.
+static IN_FLIGHT_CORRELATIONS: LazyLock<Mutex<HashSet<String>>> =
+ LazyLock::new(|| Mutex::new(HashSet::new()));
+
+/// RAII claim on a correlation id: inserts on `claim`, removes on drop. `None`
+/// from `claim` means a turn for that id is already in flight.
+struct InFlightGuard(String);
+
+impl InFlightGuard {
+ fn claim(correlation_id: &str) -> Option<Self> {
+ let mut set = IN_FLIGHT_CORRELATIONS
+ .lock()
+ .unwrap_or_else(|p| p.into_inner());
+ if set.insert(correlation_id.to_string()) {
+ Some(Self(correlation_id.to_string()))
+ } else {
+ None
+ }
+ }
+}
+
+impl Drop for InFlightGuard {
+ fn drop(&mut self) {
+ let mut set = IN_FLIGHT_CORRELATIONS
+ .lock()
+ .unwrap_or_else(|p| p.into_inner());
+ set.remove(&self.0);
+ }
+}
+
+/// Handle one relayed voice turn end to end. The reply streams token-by-token
+/// back up the socket as it is produced. A turn that finishes inside the voice
+/// window is spoken in full; a slow tool action (email/calendar summary — tens of
+/// seconds of Composio round-trips) is acknowledged aloud, then finishes in the
+/// background and delivers its answer into the user's in-app chat. Never panics —
+/// every failure path emits `voice:harness:error` (or a clean `done`) so the
+/// backend relay ends the turn cleanly.
+pub async fn handle_voice_harness_turn(correlation_id: String, messages: Vec<Value>) {
+ let prompt = extract_prompt(&messages);
+ if prompt.trim().is_empty() {
+ emit_error(&correlation_id, "no user message in the relayed turn").await;
+ return;
+ }
+
+ // A read-back turn hands us the very text it wants spoken. Running an
+ // orchestrator turn to echo it costs a full agent build, memory recall and a
+ // model round-trip — far more than the turn budget allows — so the caller
+ // hears filler instead of the answer they are waiting for. Current backends
+ // answer these at the relay and never wake us; an older one still relays them,
+ // so answer from the prompt here too.
+ if let Some(payload) = readback_payload(&prompt) {
+ info!(
+ "[voice-harness] read-back answered from the prompt correlation={correlation_id} chars={}",
+ payload.chars().count()
+ );
+ // Always speak something, even for an empty payload — see VOICE_SILENT_REPLY.
+ emit_event(
+ "voice:harness:delta",
+ json!({ "correlationId": correlation_id,
+ "text": if payload.is_empty() { VOICE_SILENT_REPLY } else { payload } }),
+ )
+ .await;
+ emit_event(
+ "voice:harness:done",
+ json!({ "correlationId": correlation_id }),
+ )
+ .await;
+ return;
+ }
+
+ // Speech recognition turns a pause during a filler-heavy turn into a "..."
+ // user message, and the provider relays it as a real turn. Building an
+ // orchestrator for it burns a concurrency slot and a model round-trip to
+ // answer nothing — and its empty reply surfaced in chat as a failure notice
+ // the user never asked for.
+ if is_content_free(&prompt) {
+ info!("[voice-harness] ignoring content-free turn correlation={correlation_id} prompt={prompt:?}");
+ emit_event(
+ "voice:harness:delta",
+ json!({ "correlationId": correlation_id, "text": VOICE_SILENT_REPLY }),
+ )
+ .await;
+ emit_event(
+ "voice:harness:done",
+ json!({ "correlationId": correlation_id }),
+ )
+ .await;
+ return;
+ }
+
+ // Deduplicate a re-delivered turn (relay retry) before doing any work. Owned
+ // so it can move into the background continuation and track the real turn.
+ let Some(in_flight) = InFlightGuard::claim(&correlation_id) else {
+ warn!("[voice-harness] duplicate turn correlation={correlation_id} already in flight — dropping");
+ return;
+ };
+
+ // Stream the reply token-by-token: the orchestrator emits `TextDelta` as it
+ // generates, and `forward_reply_deltas` relays each as a `voice:harness:delta`
+ // so the reply leaves the desktop as it is produced.
+ let streamed = Arc::new(AtomicBool::new(false));
+ let (progress_tx, progress_rx) = tokio::sync::mpsc::channel::<AgentProgress>(256);
+ let forwarder = tokio::spawn(forward_reply_deltas(
+ progress_rx,
+ correlation_id.clone(),
+ streamed.clone(),
+ ));
+
+ // Run the turn on a detached task so it can outlive the spoken ack. A slow
+ // delegation keeps working after we close the voice turn and delivers its
+ // result into the user's chat. The task owns the agent, the concurrency
+ // permit, and the in-flight guard so that bookkeeping tracks the real turn.
+ let (result_tx, result_rx) = tokio::sync::oneshot::channel::<Result<String, String>>();
+ // Captured before the prompt moves into the task, so the foreground can still
+ // tell whether the user is waiting on an answer if that task dies.
+ let answerable = is_answerable_prompt(&prompt);
+ let turn_cid = correlation_id.clone();
+ let turn_messages = messages;
+ let turn_prompt = prompt;
+ tokio::spawn(async move {
+ let _in_flight = in_flight;
+ // Bound concurrent heavy agent turns; excess turns queue HERE, inside the
+ // detached task, never in front of the ack deadline below. Acquiring in the
+ // foreground meant a turn queued behind slower ones started no clock and
+ // emitted no `done` at all, and the provider ended the whole session over
+ // it. Held for the REAL turn lifetime (including any background tail), so
+ // it still caps a retry storm.
+ let _permit = match VOICE_TURN_LIMITER.clone().acquire_owned().await {
+ Ok(permit) => permit,
+ Err(_) => {
+ warn!("[voice-harness] turn limiter unavailable correlation={turn_cid}");
+ if is_answerable_prompt(&turn_prompt) {
+ deliver_voice_failure_to_chat(&turn_cid);
+ }
+ return;
+ }
+ };
+ let outcome = run_voice_turn(&turn_cid, &turn_messages, &turn_prompt, progress_tx).await;
+ // Hand the result to the foreground. If it already deferred (dropped the
+ // receiver at the ack deadline), the send fails and we deliver the reply
+ // into the user's chat instead.
+ if let Err(unsent) = result_tx.send(outcome) {
+ match unsent {
+ Ok(reply) => {
+ // A read-back turn only re-reads an answer already delivered to
+ // chat; delivering it again would duplicate the chat message, and
+ // re-arming speak-back would loop. So deliver + arm speak-back ONLY
+ // for a genuine deferred answer, and skip the whole delivery for a
+ // read-back echo turn.
+ if should_arm_speak_back(&turn_prompt) {
+ deliver_voice_result_to_chat(&turn_cid, reply, true);
+ } else {
+ info!("[voice-harness] deferred read-back turn carries no new content; skipping chat delivery correlation={turn_cid}");
+ }
+ }
+ Err(err) => {
+ // The spoken turn already closed with `done` and the caller was
+ // told the answer was still coming, so a silent failure would leave
+ // the user waiting for a message that never arrives. Post a brief
+ // failure notice to the same thread — but only for a turn whose
+ // answer the user is actually waiting on. A read-back or a
+ // recognition artefact has nothing to deliver, and a notice for
+ // one reads as the assistant failing a request nobody made.
+ warn!("[voice-harness] deferred turn failed correlation={turn_cid}: {err}");
+ if is_answerable_prompt(&turn_prompt) {
+ deliver_voice_failure_to_chat(&turn_cid);
+ }
+ }
+ }
+ }
+ });
+
+ // Race the turn against the spoken-ack deadline.
+ match tokio::time::timeout(Duration::from_secs(VOICE_ACK_DEADLINE_SECS), result_rx).await {
+ Ok(Ok(outcome)) => {
+ // Finished inside the voice window — deltas already streamed. Join the
+ // forwarder so every delta is out before `done`, and learn whether
+ // anything streamed (fallback for a non-streaming reply).
+ let streamed_any = forwarder.await.unwrap_or(false);
+ match outcome {
+ Ok(reply) => {
+ if !streamed_any {
+ // A turn that produced no text still has to say something, or
+ // the provider ends the call (see VOICE_SILENT_REPLY).
+ let spoken = reply.trim();
+ let spoken = if spoken.is_empty() {
+ VOICE_SILENT_REPLY
+ } else {
+ spoken
+ };
+ emit_event(
+ "voice:harness:delta",
+ json!({ "correlationId": correlation_id, "text": spoken }),
+ )
+ .await;
+ }
+ emit_event(
+ "voice:harness:done",
+ json!({ "correlationId": correlation_id }),
+ )
+ .await;
+ }
+ Err(err) => {
+ warn!("[voice-harness] turn failed correlation={correlation_id}: {err}");
+ emit_error(&correlation_id, &err).await;
+ }
+ }
+ }
+ Ok(Err(_recv)) => {
+ // Sender dropped without a value (task aborted or panicked). A silent
+ // turn with no spoken text and no chat delivery is hard to trace, so
+ // log with the correlation id before ending cleanly.
+ warn!(
+ "[voice-harness] turn task ended without a result (panicked or aborted) correlation={correlation_id}"
+ );
+ // Unlike the ack-deadline path, nothing else will deliver here: the task
+ // died before reaching its own chat-delivery branch. The turn may already
+ // have promised a follow-up in chat, so post the notice from this side —
+ // for a turn the user is actually waiting on (see is_answerable_prompt).
+ if answerable {
+ deliver_voice_failure_to_chat(&correlation_id);
+ }
+ // Closing on nothing at all would end the whole call (see
+ // VOICE_SILENT_REPLY), so a lost turn still ends with a spoken beat.
+ if !streamed.load(Ordering::SeqCst) {
+ emit_event(
+ "voice:harness:delta",
+ json!({ "correlationId": correlation_id, "text": VOICE_SILENT_REPLY }),
+ )
+ .await;
+ }
+ emit_event(
+ "voice:harness:done",
+ json!({ "correlationId": correlation_id }),
+ )
+ .await;
+ }
+ Err(_deadline) => {
+ // Still running (a slow tool action). Close the voice turn cleanly; the
+ // detached task keeps going and delivers its answer into the user's
+ // chat. `timeout` consumed `result_rx`, so the task's send fails and
+ // takes the chat-delivery path. The forwarder is left running to keep
+ // draining progress — any late deltas reach a settled relay turn and
+ // are dropped harmlessly.
+ info!("[voice-harness] ack deadline reached, handing off to chat correlation={correlation_id}");
+ // If the turn never said anything of its own, the caller has heard only
+ // the relay's filler. Ending there sounds like the assistant lost the
+ // thread, so say the answer is still coming — it is, on both delivery
+ // paths (chat, and read aloud while the call is up).
+ if !streamed.load(Ordering::SeqCst) {
+ emit_event(
+ "voice:harness:delta",
+ json!({ "correlationId": correlation_id, "text": next_handoff_line() }),
+ )
+ .await;
+ }
+ emit_event(
+ "voice:harness:done",
+ json!({ "correlationId": correlation_id }),
+ )
+ .await;
+ }
+ }
+}
+
+/// Forward the orchestrator's streamed assistant text to the relay socket, one
+/// `voice:harness:delta` per top-level `AgentProgress::TextDelta`, until the
+/// turn's progress channel closes (the agent drops its sender when the turn
+/// ends). Returns whether any non-empty delta was streamed, so the caller can
+/// fall back to emitting the whole reply for a turn that produced text off the
+/// streaming path. Only top-level assistant text is voiced — sub-agent narration,
+/// thinking, tool-call args, and lifecycle events are deliberately not spoken.
+async fn forward_reply_deltas(
+ mut progress_rx: tokio::sync::mpsc::Receiver<AgentProgress>,
+ correlation_id: String,
+ streamed: Arc<AtomicBool>,
+) -> bool {
+ let mut streamed_any = false;
+ while let Some(progress) = progress_rx.recv().await {
+ let Some(text) = spoken_delta(&progress) else {
+ continue;
+ };
+ // Skip only truly empty deltas — whitespace carries word boundaries and
+ // must be forwarded so the concatenated speech isn't run together.
+ if text.is_empty() {
+ continue;
+ }
+ streamed_any = true;
+ // Published for the ack + handoff decisions, which need to know whether the
+ // orchestrator is talking *while* the turn is still open.
+ streamed.store(true, Ordering::SeqCst);
+ emit_event(
+ "voice:harness:delta",
+ json!({ "correlationId": correlation_id, "text": text }),
+ )
+ .await;
+ }
+ streamed_any
+}