Skip to content

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

refactor: extract inline test modules to separate files

Steven Enamakele7c50fc51a28
diff --git a/crates/openhuman-app/src/imessage_scanner/tick.rs b/crates/openhuman-app/src/imessage_scanner/tick.rs
index 3226608375..17b87ffeeb 100644
--- a/crates/openhuman-app/src/imessage_scanner/tick.rs
+++ b/crates/openhuman-app/src/imessage_scanner/tick.rs
@@ -160,144 +160,5 @@ pub(crate) fn chat_db_exists(path: &Path) -> bool {
}
#[cfg(test)]
-mod tests {
- 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");
- }
-}
+#[path = "tick_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-app/src/loopback_oauth.rs b/crates/openhuman-app/src/loopback_oauth.rs
index e7e68ae57b..e318fd2ab2 100644
--- a/crates/openhuman-app/src/loopback_oauth.rs
+++ b/crates/openhuman-app/src/loopback_oauth.rs
@@ -366,153 +366,5 @@ async fn run_accept_loop(
}
#[cfg(test)]
-mod tests {
- 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");
- }
-}
+#[path = "loopback_oauth_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-app/src/mcp_commands.rs b/crates/openhuman-app/src/mcp_commands.rs
index bd702eb86e..34491f1313 100644
--- a/crates/openhuman-app/src/mcp_commands.rs
+++ b/crates/openhuman-app/src/mcp_commands.rs
@@ -269,136 +269,5 @@ pub fn mcp_open_client_config(client: String) -> Result<(), String> {
}
#[cfg(test)]
-mod tests {
- 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:?}"
- );
- }
-}
+#[path = "mcp_commands_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-app/src/native_notifications/mod.rs b/crates/openhuman-app/src/native_notifications/mod.rs
index 01a960f800..efcbb29953 100644
--- a/crates/openhuman-app/src/native_notifications/mod.rs
+++ b/crates/openhuman-app/src/native_notifications/mod.rs
@@ -274,51 +274,6 @@ mod macos {
}
#[cfg(test)]
- mod tests {
- 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"
- )));
- }
- }
+ #[path = "native_notifications_tests.rs"]
+ mod tests;
}
diff --git a/crates/openhuman-app/src/reset_reboot_schedule.rs b/crates/openhuman-app/src/reset_reboot_schedule.rs
index 5f2110aa21..7bd863b193 100644
--- a/crates/openhuman-app/src/reset_reboot_schedule.rs
+++ b/crates/openhuman-app/src/reset_reboot_schedule.rs
@@ -196,163 +196,5 @@ fn schedule_one(path: &Path) -> io::Result<()> {
}
#[cfg(test)]
-mod tests {
- 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);
- }
-}
+#[path = "reset_reboot_schedule_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-app/src/stderr_panic_hook.rs b/crates/openhuman-app/src/stderr_panic_hook.rs
index 88763ef5d4..5e035f0464 100644
--- a/crates/openhuman-app/src/stderr_panic_hook.rs
+++ b/crates/openhuman-app/src/stderr_panic_hook.rs
@@ -177,105 +177,5 @@ pub(crate) fn neutralize_broken_parent_stderr() {
pub(crate) fn neutralize_broken_parent_stderr() {}
#[cfg(test)]
-mod tests {
- 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"
- );
- }
-}
+#[path = "stderr_panic_hook_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-app/src/window_state.rs b/crates/openhuman-app/src/window_state.rs
index d2bd540f3b..6854bb5c53 100644
--- a/crates/openhuman-app/src/window_state.rs
+++ b/crates/openhuman-app/src/window_state.rs
@@ -766,436 +766,5 @@ fn clamp_to_work_area(
}
#[cfg(test)]
-mod tests {
- 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));
- }
-}
+#[path = "window_state_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-app/src/workspace_paths.rs b/crates/openhuman-app/src/workspace_paths.rs
index d0409f9a8f..664d71e183 100644
--- a/crates/openhuman-app/src/workspace_paths.rs
+++ b/crates/openhuman-app/src/workspace_paths.rs
@@ -312,157 +312,5 @@ fn utf8_preview(bytes: &[u8], truncated: bool) -> Result<String, String> {
}
#[cfg(test)]
-mod tests {
- 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}");
- }
-}
+#[path = "workspace_paths_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel.rs
new file mode 100644
index 0000000000..3472cff55f
--- /dev/null
+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel.rs
@@ -0,0 +1,66 @@
+//! Process-wide cancellation registry for running workflow engine loops.
+//!
+//! `stop_workflow_run` flips the flag; the engine loop checks it between
+//! phases and aborts in-flight child tasks via the orchestration session
+//! before marking the run `Interrupted`.
+
+use std::collections::HashMap;
+use std::sync::atomic::AtomicBool;
+use std::sync::{Arc, Mutex, OnceLock};
+
+use tinyagents_harness::CancellationToken;
+
+/// Per-run pair of legacy poll flag and crate-native cancellation token.
+#[derive(Clone)]
+pub(super) struct WorkflowCancelSignal {
+ pub(super) flag: Arc<AtomicBool>,
+ pub(super) token: CancellationToken,
+}
+
+fn cancel_registry() -> &'static Mutex<HashMap<String, WorkflowCancelSignal>> {
+ static REGISTRY: OnceLock<Mutex<HashMap<String, WorkflowCancelSignal>>> = OnceLock::new();
+ REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+/// Register (or reuse) a cancellation flag for `run_id`.
+pub(super) fn register_cancel_signal(run_id: &str) -> WorkflowCancelSignal {
+ let mut map = cancel_registry().lock().expect("cancel registry poisoned");
+ map.entry(run_id.to_string())
+ .or_insert_with(|| WorkflowCancelSignal {
+ flag: Arc::new(AtomicBool::new(false)),
+ token: CancellationToken::new(),
+ })
+ .clone()
+}
+
+/// Register (or reuse) a cancellation flag for `run_id`.
+pub(super) fn register_cancel_flag(run_id: &str) -> Arc<AtomicBool> {
+ register_cancel_signal(run_id).flag
+}
+
+/// Look up an existing cancellation signal for `run_id`, if one is registered.
+pub(super) fn lookup_cancel_signal(run_id: &str) -> Option<WorkflowCancelSignal> {
+ cancel_registry()
+ .lock()
+ .expect("cancel registry poisoned")
+ .get(run_id)
+ .cloned()
+}
+
+/// Look up an existing cancellation flag for `run_id`, if one is registered.
+pub(super) fn lookup_cancel_flag(run_id: &str) -> Option<Arc<AtomicBool>> {
+ lookup_cancel_signal(run_id).map(|signal| signal.flag)
+}
+
+/// Look up an SDK cancellation token for `run_id`, if one is registered.
+pub(super) fn lookup_cancel_token(run_id: &str) -> Option<CancellationToken> {
+ lookup_cancel_signal(run_id).map(|signal| signal.token)
+}
+
+/// Drop a run's cancellation flag once the engine loop is done with it.
+pub(super) fn clear_cancel_flag(run_id: &str) {
+ cancel_registry()
+ .lock()
+ .expect("cancel registry poisoned")
+ .remove(run_id);
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability.rs b/crates/openhuman-core/src/agent/tinyagents/observability.rs
index 36d797ed65..4d8de5005e 100644
--- a/crates/openhuman-core/src/agent/tinyagents/observability.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/observability.rs
@@ -10,6 +10,7 @@
mod cap_pauser;
mod event_bridge;
+mod event_projection;
mod graph_tracing;
#[cfg(test)]
@@ -20,7 +21,8 @@ use tinyinference::usage::Usage;
pub(crate) use cap_pauser::{
CapPauser, IterationCursor, ProviderUsageCarry, SubagentScope, ToolFailureMap, ToolNameMap,
};
-pub(crate) use event_bridge::{surface_cache_layout_events, OpenhumanEventBridge};
+pub(crate) use event_bridge::OpenhumanEventBridge;
+pub(crate) use event_projection::surface_cache_layout_events;
pub(crate) use graph_tracing::GraphTracingSink;
#[cfg(test)]
diff --git a/crates/openhuman-core/src/integrations/composio/schemas/handlers_connections.rs b/crates/openhuman-core/src/integrations/composio/schemas/handlers_connections.rs
new file mode 100644
index 0000000000..5bffd58b0f
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/composio/schemas/handlers_connections.rs
@@ -0,0 +1,81 @@
+//! Toolkit-allowlist, connection, and direct-mode-API-key handlers:
+//! `list_toolkits`, `list_capabilities`, `list_agent_ready_toolkits`,
+//! `list_connections`, `authorize`, `delete_connection`, `get_mode`,
+//! `set_api_key`, `clear_api_key`.
+
+use serde_json::{Map, Value};
+
+use crate::config::rpc as config_rpc;
+use crate::core::all::ControllerFuture;
+use crate::integrations::composio::ops;
+
+use super::util::{read_optional, read_required_non_empty, to_json};
+
+pub(super) fn handle_list_toolkits(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async {
+ let config = config_rpc::load_config_with_timeout().await?;
+ to_json(ops::composio_list_toolkits(&config).await?)
+ })
+}
+
+pub(super) fn handle_list_capabilities(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async {
+ let config = config_rpc::load_config_with_timeout().await?;
+ to_json(ops::composio_list_capabilities(&config).await?)
+ })
+}
+
+pub(super) fn handle_list_agent_ready_toolkits(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async { to_json(ops::composio_list_agent_ready_toolkits().await?) })
+}
+
+pub(super) fn handle_list_connections(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async {
+ let config = config_rpc::load_config_with_timeout().await?;
+ to_json(ops::composio_list_connections(&config).await?)
+ })
+}
+
+pub(super) fn handle_authorize(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let toolkit = read_required_non_empty(&params, "toolkit")?;
+ let extra_params = params.get("extra_params").cloned();
+ to_json(ops::composio_authorize(&config, &toolkit, extra_params).await?)
+ })
+}
+
+pub(super) fn handle_delete_connection(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let connection_id = read_required_non_empty(&params, "connection_id")?;
+ let clear_memory = read_optional::<bool>(&params, "clear_memory")?.unwrap_or(false);
+ to_json(ops::composio_delete_connection(&config, &connection_id, clear_memory).await?)
+ })
+}
+
+pub(super) fn handle_get_mode(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ tracing::debug!("[composio-direct] rpc get_mode entry");
+ let config = config_rpc::load_config_with_timeout().await?;
+ to_json(ops::composio_get_mode(&config).await?)
+ })
+}
+
+pub(super) fn handle_set_api_key(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ tracing::debug!("[composio-direct] rpc set_api_key entry");
+ let config = config_rpc::load_config_with_timeout().await?;
+ let api_key = read_required_non_empty(&params, "api_key")?;
+ let activate_direct = read_optional::<bool>(&params, "activate_direct")?.unwrap_or(false);
+ to_json(ops::composio_set_api_key(&config, &api_key, activate_direct).await?)
+ })
+}
+
+pub(super) fn handle_clear_api_key(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ tracing::debug!("[composio-direct] rpc clear_api_key entry");
+ let config = config_rpc::load_config_with_timeout().await?;
+ to_json(ops::composio_clear_api_key(&config).await?)
+ })
+}
diff --git a/crates/openhuman-core/src/voice/realtime_harness/turn_handler.rs b/crates/openhuman-core/src/voice/realtime_harness/turn_handler.rs
index 6872bfcdb5..bca163603f 100644
--- a/crates/openhuman-core/src/voice/realtime_harness/turn_handler.rs
+++ b/crates/openhuman-core/src/voice/realtime_harness/turn_handler.rs
@@ -54,7 +54,7 @@ const VOICE_ACK_DEADLINE_SECS: u64 = 8;
///
/// 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] = [
+pub(super) const VOICE_HANDOFF_LINES: [&str; 4] = [
"Still on it. ",
"Still going. ",
"Still working on it. ",
@@ -63,7 +63,7 @@ const VOICE_HANDOFF_LINES: [&str; 4] = [
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 {
+pub(super) fn next_handoff_line() -> &'static str {
VOICE_HANDOFF_LINES
[VOICE_HANDOFF_CURSOR.fetch_add(1, Ordering::Relaxed) % VOICE_HANDOFF_LINES.len()]
}
diff --git a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
new file mode 100644
index 0000000000..f3af806ffb
--- /dev/null
+++ b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
@@ -0,0 +1,247 @@
+//! Forked (`QueueMode::Parallel`) turns: spawning one alongside whatever is
+//! already in flight on a thread, and the request- or thread-scoped
+//! cancellation paths that tear them down.
+
+use std::time::Duration;
+
+use tokio_util::sync::CancellationToken;
+
+use crate::core::socketio::WebChannelEvent;
+
+use super::super::event_bus::publish_web_channel_event;
+use super::super::run_task::run_chat_task;
+use super::super::types::{ChatRequestMetadata, ParallelEntry};
+use super::super::web_errors::classify_inference_error;
+use super::state::PARALLEL_IN_FLIGHT;
+use super::turn_guards::{run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag};
+
+/// Spawn an independent, forked (`QueueMode::Parallel`) turn. It snapshots the
+/// thread's history-at-start (inside `run_chat_task` with `fork = true`), runs
+/// concurrently with any other turn on the thread, and on completion delivers
+/// its response (append-only) and removes itself from `PARALLEL_IN_FLIGHT`.
+/// Emits the same per-`request_id` stream events as a primary turn, so the UI
+/// can render it as an interleaved branch.
+#[allow(clippy::too_many_arguments)]
+pub(crate) async fn spawn_parallel_turn(
+ client_id: &str,
+ thread_id: &str,
+ request_id: String,
+ message: &str,
+ model_override: Option<String>,
+ temperature: Option<f64>,
+ profile_id: Option<String>,
+ locale: Option<String>,
+ metadata: ChatRequestMetadata,
+) {
+ let cancel_token = CancellationToken::new();
+ let task_cancel_token = cancel_token.clone();
+
+ let client_id_task = client_id.to_string();
+ let thread_id_task = thread_id.to_string();
+ let request_id_task = request_id.clone();
+ let user_message = message.to_string();
+ // Forked turns don't participate in the steer/followup/collect queue, but
+ // `run_chat_task` requires a queue handle — give each its own.
+ let run_queue = crate::agent::harness::run_queue::RunQueue::new();
+
+ let handle = tokio::spawn(crate::core::runtime::context::CoreContext::propagate(
+ async move {
+ let approval_ctx = crate::security::approval::ApprovalChatContext {
+ thread_id: thread_id_task.clone(),
+ client_id: client_id_task.clone(),
+ };
+ let origin = crate::agent::turn_origin::AgentTurnOrigin::WebChat {
+ thread_id: thread_id_task.clone(),
+ client_id: client_id_task.clone(),
+ request_id: Some(request_id_task.clone()),
+ };
+ let result = run_turn_under_cancel_and_deadline(
+ task_cancel_token,
+ origin,
+ approval_ctx,
+ run_chat_task(
+ &client_id_task,
+ &thread_id_task,
+ &request_id_task,
+ &user_message,
+ model_override,
+ temperature,
+ profile_id,
+ locale,
+ run_queue,
+ metadata,
+ /* fork */ true,
+ ),
+ )
+ .await;
+
+ match result {
+ Some(Ok(chat_result)) => {
+ crate::web_chat::presentation::deliver_response(
+ &client_id_task,
+ &thread_id_task,
+ &request_id_task,
+ &chat_result.full_response,
+ &user_message,
+ &chat_result.citations,
+ chat_result.usage.as_ref(),
+ // The workspace the turn ran in, so the reply is stored
+ // there before it is announced (#6034).
+ Some(chat_result.workspace_dir.as_path()),
+ )
+ .await;
+ }
+ Some(Err(err)) => {
+ log::warn!(
+ "[web-channel] parallel run_chat_task failed client_id={} thread_id={} request_id={} error={}",
+ client_id_task,
+ thread_id_task,
+ request_id_task,
+ err
+ );
+ let detailed = format!(
+ "parallel run_chat_task failed client_id={} thread_id={} request_id={} error={}",
+ client_id_task, thread_id_task, request_id_task, err
+ );
+ let classified = classify_inference_error(&err);
+ let classified_type = classified.error_type;
+
+ // A parallel turn runs under the same deadline wrapper as the
+ // serial one and dies the same way, but this branch reported
+ // NOTHING to Sentry — not merely the timeouts this PR
+ // un-suppresses, but every error type, since the parallel path
+ // was added. So a discarded turn was invisible here even
+ // before the suppression arm existed, and fixing only
+ // `start_chat` would have left `QueueMode::Parallel` exactly
+ // as blind as it was (#5804 review).
+ //
+ // Same policy as the serial site, deliberately sharing
+ // `sentry_suppression_reason` rather than restating it: the
+ // outer backstop stays suppressed, a harness `Timeout` reports
+ // with the ceiling that fired.
+ if let Some(reason) = sentry_suppression_reason(&detailed) {
+ log::info!(
+ target: "web_channel",
+ "[web_channel.spawn_parallel_turn] suppressed Sentry emission for {} \
+ client_id={} thread_id={} request_id={} error_type={} message={}",
+ reason,
+ client_id_task,
+ thread_id_task,
+ request_id_task,
+ classified_type,
+ detailed
+ );
+ } else {
+ crate::core::observability::report_error_or_expected(
+ detailed.as_str(),
+ "web_channel",
+ "spawn_parallel_turn",
+ &[
+ ("channel", "web"),
+ ("error_type", classified_type),
+ ("thread_id", thread_id_task.as_str()),
+ ("request_id", request_id_task.as_str()),
+ ("queue_mode", "parallel"),
+ ("timeout_bound", timeout_bound_tag(&detailed)),
+ ],
+ );
+ }
+
+ publish_web_channel_event(WebChannelEvent {
+ event: "chat_error".to_string(),
+ client_id: client_id_task.clone(),
+ thread_id: thread_id_task.clone(),
+ request_id: request_id_task.clone(),
+ message: Some(classified.message),
+ error_type: Some(classified.error_type.to_string()),
+ error_source: Some(classified.source.to_string()),
+ error_retryable: Some(classified.retryable),
+ error_retry_after_ms: classified.retry_after_ms,
+ error_provider: classified.provider,
+ error_fallback_available: classified.fallback_available,
+ ..Default::default()
+ });
+ }
+ None => {
+ log::info!(
+ "[web-channel] parallel turn cancelled cooperatively thread_id={} request_id={}",
+ thread_id_task,
+ request_id_task
+ );
+ }
+ }
+
+ PARALLEL_IN_FLIGHT.lock().await.remove(&request_id_task);
+ },
+ ));
+
+ PARALLEL_IN_FLIGHT.lock().await.insert(
+ request_id,
+ ParallelEntry {
+ thread_id: thread_id.to_string(),
+ handle,
+ cancel_token,
+ },
+ );
+}
+
+/// Cooperatively cancel every parallel turn on a thread. Returns the cancelled
+/// request ids. Used by the thread-level cancel paths so a cancel/stop also
+/// tears down any concurrent forked turns, not just the primary turn.
+pub(crate) async fn cancel_parallel_turns_for_thread(thread_id: &str) -> Vec<String> {
+ let mut cancelled = Vec::new();
+ let mut parallel = PARALLEL_IN_FLIGHT.lock().await;
+ let request_ids: Vec<String> = parallel
+ .iter()
+ .filter(|(_, entry)| entry.thread_id == thread_id)
+ .map(|(request_id, _)| request_id.clone())
+ .collect();
+ for request_id in request_ids {
+ if let Some(entry) = parallel.remove(&request_id) {
+ entry.cancel_token.cancel();
+ let mut handle = entry.handle;
+ tokio::spawn(async move {
+ tokio::select! {
+ _ = &mut handle => {}
+ _ = tokio::time::sleep(Duration::from_secs(5)) => {
+ handle.abort();
+ }
+ }
+ });
+ cancelled.push(request_id);
+ }
+ }
+ cancelled
+}
+
+/// Cancel a single parallel (forked) turn identified by `request_id`, but only
+/// when it belongs to `thread_id`. Returns the cancelled id (as a one-element
+/// vec, mirroring [`cancel_parallel_turns_for_thread`]) or empty when no such
+/// parallel turn exists. Request-scoped cancel path (#4760).
+pub(crate) async fn cancel_parallel_turn_by_request_id(
+ thread_id: &str,
+ request_id: &str,
+) -> Vec<String> {
+ let mut parallel = PARALLEL_IN_FLIGHT.lock().await;
+ let matches = parallel
+ .get(request_id)
+ .map(|entry| entry.thread_id == thread_id)
+ .unwrap_or(false);
+ if !matches {
+ return Vec::new();
+ }
+ if let Some(entry) = parallel.remove(request_id) {
+ entry.cancel_token.cancel();
+ let mut handle = entry.handle;
+ tokio::spawn(async move {
+ tokio::select! {
+ _ = &mut handle => {}
+ _ = tokio::time::sleep(Duration::from_secs(5)) => {
+ handle.abort();
+ }
+ }
+ });
+ return vec![request_id.to_string()];
+ }
+ Vec::new()
+}