The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: remove unused accessibility module and re-export schedule functions
Steven Enamakelbbf6fc81893b
diff --git a/crates/openhuman-core/src/cron/mod.rs b/crates/openhuman-core/src/cron/mod.rsindex aed59ca48b..c21bfc8e80 100644--- a/crates/openhuman-core/src/cron/mod.rs+++ b/crates/openhuman-core/src/cron/mod.rs@@ -20,16 +20,9 @@ pub mod scheduler;pub use ops as rpc;pub use ops::{add_once, add_once_at, parse_human_delay, pause_job, resume_job, update_cron_job};-// Pure scheduling logic lives in `tinyflows-schedule`; the host keeps the-// scheduler runtime, store, config and RPC. `schedule`/`types` stay addressable-// as `crate::cron::{schedule,types}` for the modules beneath `cron`.-use tinyflows_schedule::{schedule, types};--#[allow(unused_imports)]-pub use tinyflows_schedule::schedule::{- next_run_for_schedule, normalize_expression, runs_closer_than, schedule_cron_expression,- validate_agent_schedule, validate_schedule, TooFrequent, MIN_AGENT_JOB_INTERVAL,-};+// Pure scheduling logic (schedule model, next-run computation) lives in+// `tinyflows-schedule`; the host keeps the scheduler runtime, store, config+// and RPC, and re-exports the upstream names so `cron::Schedule` etc. hold.pub use schemas::{all_controller_schemas as all_cron_controller_schemas,all_registered_controllers as all_cron_registered_controllers, schemas as cron_schemas,@@ -41,6 +34,11 @@ pub use store::{get_job, list_jobs, list_runs, record_last_run, record_run, remove_job, reschedule_after_run,update_job,};+#[allow(unused_imports)]+pub use tinyflows_schedule::schedule::{+ next_run_for_schedule, normalize_expression, runs_closer_than, schedule_cron_expression,+ validate_agent_schedule, validate_schedule, TooFrequent, MIN_AGENT_JOB_INTERVAL,+};pub use tinyflows_schedule::types::{ActiveHours, CronJob, CronJobPatch, CronRun, DeliveryConfig, JobType, Schedule, SessionTarget,};diff --git a/crates/openhuman-core/src/desktop/accessibility/README.md b/crates/openhuman-core/src/desktop/accessibility/README.mddeleted file mode 100644index 2e726be873..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/README.md+++ /dev/null@@ -1,35 +0,0 @@-# Accessibility--Cross-platform accessibility middleware. Owns the macOS AX / IOKit FFI, the unified Swift helper-process bridge (focus queries, paste, and overlay in one persistent process), focused-text inspection, system-permission detection (Accessibility, Input Monitoring, Microphone), the Globe-key listener, "System Events" automation-denial tracking, terminal heuristics, and AX-string normalization. Centralises platform-specific code so that `voice` never touches FFI directly.--## Public surface--Re-exported from `mod.rs`:--- `pub fn clear_automation_denial` / `mark_system_events_denied` / `system_events_denied` (`automation_state.rs`): tracks whether macOS has denied AppleScript "System Events" automation, so callers can stop retrying until the user re-grants it.-- `pub fn focused_text_context` / `focused_text_context_verbose` / `validate_focused_target` (`focus.rs`): query the OS for the currently focused text field.-- `pub fn globe_listener_start` / `globe_listener_stop` / `globe_listener_poll` / `pub struct GlobeHotkeyPollResult` / `pub enum GlobeHotkeyStatus` (`globe.rs`): macOS Globe-key (Fn) hotkey monitor.-- `pub fn precompile_helper_background`: `helper.rs`, split into submodules `helper/process.rs` (process management, `pub(crate) helper_send_receive`), `helper/swift_focus.rs` / `helper/swift_paste.rs` / `helper/swift_overlay.rs` / `helper/swift_ax_actions.rs` (embedded Swift source pieces), and `helper/swift_source.rs` (assembles the full source), compile the Swift helper with `swiftc` on a background thread so the first request avoids compile latency. No caller outside this module today.-- Permission detection: `detect_permissions`, `detect_microphone_permission`, `microphone_denied_message`, `permission_to_str`, `request_microphone_access` (cross-platform); macOS-only `detect_accessibility_permission`, `detect_input_monitoring_permission`, `open_macos_privacy_pane`, `request_accessibility_access`: `permissions.rs`. Microphone detection probes `cpal` for a default input device and needs the `inference` feature; without it the result is `PermissionState::Unknown`.-- `pub fn extract_terminal_input_context` / `is_terminal_app` / `is_text_role` / `looks_like_terminal_buffer` (`terminal.rs`): terminal-window heuristics.-- `pub fn normalize_ax_value` / `parse_ax_number` / `truncate_tail` (`text_util.rs`): AX value normalization.-- `pub struct ElementBounds` / `FocusedTextContext` / `PermissionKind` / `PermissionState` / `PermissionStatus`: `types.rs`.--## Calls into--- macOS frameworks `ApplicationServices`, `CoreFoundation`, and `IOKit` via `#[link]` FFI in `permissions.rs`; `CGEvent` key synthesis happens inside the Swift helper, not in Rust.-- The Swift helper process, compiled on first use with `swiftc` from the source assembled in `helper/swift_source.rs` and driven over stdin/stdout JSON by `helper_send_receive`.-- `cpal` (behind the `inference` feature) for the microphone probe.-- No `crate::*` imports: this module does not read `Config`.--## Called by--- `crates/openhuman-core/src/voice/server/hotkey_listener.rs`: `globe_listener_start` / `globe_listener_poll` for the Fn hotkey; `voice/server/pipeline.rs`: `focused_text_context_verbose` to capture the frontmost app at hotkey press.-- `crates/openhuman-core/src/voice/text_input.rs`: `validate_focused_target` before inserting dictated text.-- `crates/openhuman-core/src/voice/always_on/capture.rs`: `detect_microphone_permission`; `audio_capture.rs`: the same plus `microphone_denied_message` / `request_microphone_access` before opening the input device.-- `crates/openhuman-core/src/core/all_tests.rs`: asserts `detect_microphone_permission()` is `Unknown` when `inference` is compiled out.--## Tests--- Sibling `*_tests.rs` files for `automation_state`, `focus`, `globe`, `permissions`, `terminal`, and `text_util`, attached via `#[cfg(test)] #[path = ...] mod tests;`.-- AX FFI and the Swift helper are only exercised on a real macOS host, Linux CI skips the platform-gated paths.diff --git a/crates/openhuman-core/src/desktop/accessibility/automation_state.rs b/crates/openhuman-core/src/desktop/accessibility/automation_state.rsdeleted file mode 100644index 4d02a7d72f..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/automation_state.rs+++ /dev/null@@ -1,57 +0,0 @@-//! Session-local denial flag for macOS Apple Events automation.-//!-//! Captures the reactive signal that osascript returns-//! `errAEEventNotPermitted (-1743)` when the calling app lacks an-//! Automation grant for the target. After observation, gated osascript-//! call sites short-circuit until the flag is cleared.-//!-//! Why a reactive flag instead of an in-process probe:-//! `AEDeterminePermissionToAutomateTarget(askUserIfNeeded=false)` would-//! be the principled silent-probe API but it SIGBUSes inside-//! AE.framework's TCC client whenever called from any binary that links-//! `openhuman_core` (PAC mismatch between arm64 Rust binaries and-//! arm64e Apple frameworks, mediated by `objc2-app-kit` transitive-//! deps). Verified across seven workarounds during #985 plan validation.-//! The osascript stderr `(-1743)` substring is a stable Apple-defined-//! error code that's already produced by the existing fallback path —-//! capturing it costs nothing extra and avoids the FFI entirely.-//!-//! The flag is cleared at the top of `autocomplete::start_if_enabled`-//! so a user-initiated re-engagement (toggle autocomplete off+on after-//! granting via System Settings) re-probes naturally on the next tick.--use std::sync::atomic::{AtomicBool, Ordering};--static SYSTEM_EVENTS_DENIED: AtomicBool = AtomicBool::new(false);--/// Mark that osascript has returned -1743 for `tell application "System-/// Events"` in this process. Called from the autocomplete refresh-loop-/// error branch when the sentinel substring is observed.-pub fn mark_system_events_denied() {- SYSTEM_EVENTS_DENIED.store(true, Ordering::Relaxed);-}--/// True iff a -1743 has been observed in this process since the last-/// `clear()`. Gated osascript call sites in `focus.rs` / `paste.rs`-/// check this and short-circuit before spawning osascript.-pub fn system_events_denied() -> bool {- SYSTEM_EVENTS_DENIED.load(Ordering::Relaxed)-}--/// Reset the denial flag. Called from `autocomplete::start_if_enabled`-/// so an explicit re-engagement (user toggled autocomplete off+on, or-/// the engine was started fresh) re-probes via the next osascript tick-/// instead of inheriting a stale denial from a previous session.-pub fn clear() {- SYSTEM_EVENTS_DENIED.store(false, Ordering::Relaxed);-}--#[cfg(test)]-pub(crate) fn test_lock() -> std::sync::MutexGuard<'static, ()> {- static M: std::sync::Mutex<()> = std::sync::Mutex::new(());- M.lock().unwrap_or_else(|e| e.into_inner())-}--#[cfg(test)]-#[path = "automation_state_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/desktop/accessibility/automation_state_tests.rs b/crates/openhuman-core/src/desktop/accessibility/automation_state_tests.rsdeleted file mode 100644index 1912699282..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/automation_state_tests.rs+++ /dev/null@@ -1,53 +0,0 @@-use super::*;--#[test]-fn defaults_to_not_denied() {- let _g = test_lock();- clear();- assert!(!system_events_denied());-}--#[test]-fn mark_then_observe() {- let _g = test_lock();- clear();- assert!(!system_events_denied());- mark_system_events_denied();- assert!(system_events_denied());- clear();- assert!(!system_events_denied());-}--#[test]-fn idempotent_mark_and_clear() {- let _g = test_lock();- clear();- mark_system_events_denied();- mark_system_events_denied();- assert!(system_events_denied());- clear();- clear();- assert!(!system_events_denied());-}--#[test]-fn concurrent_mark_and_read() {- let _g = test_lock();- clear();- let producers: Vec<_> = (0..8)- .map(|_| std::thread::spawn(mark_system_events_denied))- .collect();- let readers: Vec<_> = (0..8)- .map(|_| std::thread::spawn(|| system_events_denied()))- .collect();- for h in producers {- h.join().unwrap();- }- for h in readers {- // Read may race the marks — only the post-join state is- // load-bearing for correctness.- let _ = h.join().unwrap();- }- assert!(system_events_denied());- clear();-}diff --git a/crates/openhuman-core/src/desktop/accessibility/focus.rs b/crates/openhuman-core/src/desktop/accessibility/focus.rsdeleted file mode 100644index aadc3d1fd3..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/focus.rs+++ /dev/null@@ -1,458 +0,0 @@-//! Accessibility focus queries.-//!-//! Primary path: unified Swift helper (native AX API, fast, persistent process).-//! Fallback: osascript subprocess (slower, but works without compiled helper).--#[cfg(target_os = "macos")]-use super::terminal::{is_terminal_app, is_text_role};-#[cfg(target_os = "macos")]-use super::text_util::{normalize_ax_value, parse_ax_number};-#[cfg(target_os = "macos")]-use super::types::ElementBounds;-use super::types::FocusedTextContext;-#[cfg(any(target_os = "macos", test))]-use std::{- process::{Command, Output, Stdio},- time::{Duration, Instant},-};--#[cfg(target_os = "macos")]-const FOCUS_COMMAND_TIMEOUT: Duration = Duration::from_millis(1_500);-#[cfg(any(target_os = "macos", test))]-const COMMAND_TIMEOUT_POLL_INTERVAL: Duration = Duration::from_millis(10);--#[cfg(any(target_os = "macos", test))]-fn command_output_with_timeout(- command_name: &str,- command: &mut Command,- timeout: Duration,-) -> Result<Output, String> {- command.stdout(Stdio::piped()).stderr(Stdio::piped());- let mut child = command- .spawn()- .map_err(|e| format!("failed to run {command_name}: {e}"))?;- let started_at = Instant::now();-- loop {- match child.try_wait() {- Ok(Some(_)) => {- return child- .wait_with_output()- .map_err(|e| format!("failed to collect {command_name} output: {e}"));- }- Ok(None) if started_at.elapsed() >= timeout => {- let _ = child.kill();- let _ = child.wait();- return Err(format!(- "{command_name} timed out after {}ms",- timeout.as_millis()- ));- }- Ok(None) => std::thread::sleep(COMMAND_TIMEOUT_POLL_INTERVAL),- Err(error) => {- let _ = child.kill();- let _ = child.wait();- return Err(format!("failed to wait for {command_name}: {error}"));- }- }- }-}--// ----------------------------------------------------------------------------// Focus query: unified helper → osascript fallback-// -----------------------------------------------------------------------------#[cfg(target_os = "macos")]-pub fn focused_text_context() -> Result<FocusedTextContext, String> {- let ctx = focused_text_context_verbose()?;- if let Some(err) = ctx.raw_error.as_ref() {- return Err(format!(- "focused text unavailable via accessibility api: {err}"- ));- }- Ok(ctx)-}--/// Query the focused text element. Tries the unified Swift helper first (native AX, ~5-15ms),-/// falls back to osascript (~50-100ms) if the helper is unavailable.-#[cfg(target_os = "macos")]-pub fn focused_text_context_verbose() -> Result<FocusedTextContext, String> {- match focused_text_via_helper() {- Ok(ctx) if ctx.raw_error.is_some() => {- log::debug!(- "[accessibility] helper returned raw_error={:?}, falling back to osascript",- ctx.raw_error- );- focused_text_via_osascript()- }- Ok(ctx) => Ok(ctx),- Err(helper_err) => {- log::debug!(- "[accessibility] helper focus query failed ({}), falling back to osascript",- helper_err- );- focused_text_via_osascript()- }- }-}--/// Focus query via the unified Swift helper.-#[cfg(target_os = "macos")]-fn focused_text_via_helper() -> Result<FocusedTextContext, String> {- let request = serde_json::json!({"type": "focus"});- let resp = super::helper::helper_send_receive(&request)?;-- let app_name = resp- .get("app_name")- .and_then(|v| v.as_str())- .map(|s| s.to_string());- let role = resp- .get("role")- .and_then(|v| v.as_str())- .map(|s| s.to_string());- let text = resp- .get("text")- .and_then(|v| v.as_str())- .unwrap_or_default()- .to_string();- let selected_text = resp- .get("selected_text")- .and_then(|v| v.as_str())- .map(|s| s.to_string());- let raw_error = resp- .get("error")- .and_then(|v| v.as_str())- .map(|s| s.to_string());-- let x = resp.get("x").and_then(|v| v.as_i64()).map(|v| v as i32);- let y = resp.get("y").and_then(|v| v.as_i64()).map(|v| v as i32);- let w = resp.get("w").and_then(|v| v.as_i64()).map(|v| v as i32);- let h = resp.get("h").and_then(|v| v.as_i64()).map(|v| v as i32);-- Ok(FocusedTextContext {- app_name,- role,- text,- selected_text,- raw_error,- bounds: match (x, y, w, h) {- (Some(x), Some(y), Some(width), Some(height)) if width > 0 && height > 0 => {- Some(ElementBounds {- x,- y,- width,- height,- })- }- _ => None,- },- })-}--/// Focus query via osascript (fallback when helper is unavailable).-///-/// Short-circuits when `automation_state::system_events_denied()` is set-/// (the autocomplete refresh loop captured `(-1743)` from a prior-/// osascript invocation). This stops re-firing osascript — and the-/// macOS Apple Events consent popup — once we've observed the denial-/// within the current session. The flag clears on-/// `autocomplete::start_if_enabled` so a user-initiated re-engagement-/// after granting via System Settings re-probes naturally.-#[cfg(target_os = "macos")]-fn focused_text_via_osascript() -> Result<FocusedTextContext, String> {- if super::automation_state::system_events_denied() {- return Err(- "focused_text_via_osascript skipped: System Events automation previously denied (-1743)"- .to_string(),- );- }-- let script = r##"- tell application "System Events"- set sep to character id 31- set frontApp to first application process whose frontmost is true- set appName to name of frontApp- set roleValue to "unknown"- set textValue to ""- set selectedValue to ""- set errValue to ""- set posX to ""- set posY to ""- set sizeW to ""- set sizeH to ""- set targetRoles to {"AXTextArea", "AXTextField", "AXSearchField", "AXComboBox", "AXEditableText"}-- try- set value of attribute "AXEnhancedUserInterface" of frontApp to true- end try-- try- set focusedElement to value of attribute "AXFocusedUIElement" of frontApp- try- set roleValue to value of attribute "AXRole" of focusedElement as text- end try- try- set textValue to value of attribute "AXValue" of focusedElement as text- end try- try- set p to value of attribute "AXPosition" of focusedElement- set posX to item 1 of p as text- set posY to item 2 of p as text- end try- try- set s to value of attribute "AXSize" of focusedElement- set sizeW to item 1 of s as text- set sizeH to item 2 of s as text- end try- if textValue is "missing value" then set textValue to ""- if textValue is "" then- try- set selectedValue to value of attribute "AXSelectedText" of focusedElement as text- end try- if selectedValue is "missing value" then set selectedValue to ""- if selectedValue is not "" then set textValue to selectedValue- end if- if textValue is "" then- try- set textValue to value of attribute "AXTitle" of focusedElement as text- end try- if textValue is "missing value" then set textValue to ""- end if- on error errMsg number errNum- set errValue to "ERROR:" & errNum & ":" & errMsg- end try-- if textValue is "" then- try- set focusedWindow to value of attribute "AXFocusedWindow" of frontApp- set childElems to entire contents of focusedWindow- set staticPromptValue to ""- set staticFallbackValue to ""- repeat with childElem in childElems- set childRole to ""- set childValue to ""- set childSelectedValue to ""- try- set childRole to value of attribute "AXRole" of childElem as text- end try- if childRole is in targetRoles then- try- set childValue to value of attribute "AXValue" of childElem as text- end try- set childPosX to ""- set childPosY to ""- set childSizeW to ""- set childSizeH to ""- try- set cp to value of attribute "AXPosition" of childElem- set childPosX to item 1 of cp as text- set childPosY to item 2 of cp as text- end try- try- set cs to value of attribute "AXSize" of childElem- set childSizeW to item 1 of cs as text- set childSizeH to item 2 of cs as text- end try- if childValue is "missing value" then set childValue to ""- if childValue is "" then- try- set childSelectedValue to value of attribute "AXSelectedText" of childElem as text- end try- if childSelectedValue is "missing value" then set childSelectedValue to ""- if childSelectedValue is not "" then set childValue to childSelectedValue- end if- if childValue is not "" then- set roleValue to childRole- set textValue to childValue- if childPosX is not "" then set posX to childPosX- if childPosY is not "" then set posY to childPosY- if childSizeW is not "" then set sizeW to childSizeW- if childSizeH is not "" then set sizeH to childSizeH- exit repeat- end if- end if- end repeat- if textValue is "" then- repeat with childElem in childElems- set childRole to ""- set childValue to ""- try- set childRole to value of attribute "AXRole" of childElem as text- end try- if childRole is "AXStaticText" then- try- set childValue to value of attribute "AXValue" of childElem as text- end try- if childValue is "missing value" then set childValue to ""- if childValue is not "" then- set staticFallbackValue to childValue- if childValue contains "$ " or childValue contains "# " or childValue contains "> " then- set staticPromptValue to childValue- end if- end if- end if- end repeat- if staticPromptValue is not "" then- set roleValue to "AXStaticText"- set textValue to staticPromptValue- else if staticFallbackValue is not "" then- set roleValue to "AXStaticText"- set textValue to staticFallbackValue- end if- end if- on error errMsg2 number errNum2- if errValue is "" then set errValue to "ERROR:" & errNum2 & ":" & errMsg2- end try- end if-- if textValue is "" and errValue is "" then- set errValue to "ERROR:no_text_candidate_found"- end if-- return appName & sep & roleValue & sep & textValue & sep & selectedValue & sep & errValue & sep & posX & sep & posY & sep & sizeW & sep & sizeH- end tell- "##;-- let mut command = Command::new("osascript");- command.arg("-e").arg(script);- let output = command_output_with_timeout(- "osascript focused_text_via_osascript",- &mut command,- FOCUS_COMMAND_TIMEOUT,- )?;- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();- if stderr.is_empty() {- return Err("unable to query focused text context".to_string());- }- return Err(format!("unable to query focused text context: {stderr}"));- }-- let text = String::from_utf8_lossy(&output.stdout);- let trimmed = text.trim_end_matches(['\r', '\n']);- let mut segments = trimmed.splitn(9, '\u{1f}');- let app_name = segments- .next()- .map(|s| normalize_ax_value(s.trim()))- .filter(|s| !s.is_empty());- let role = segments- .next()- .map(|s| normalize_ax_value(s.trim()))- .filter(|s| !s.is_empty());- let mut value = segments.next().map(normalize_ax_value).unwrap_or_default();- let mut selected_text = segments- .next()- .map(normalize_ax_value)- .filter(|s| !s.is_empty());- let mut raw_error = segments- .next()- .map(|s| normalize_ax_value(s.trim()))- .filter(|s| !s.is_empty());- let pos_x = segments.next().and_then(parse_ax_number);- let pos_y = segments.next().and_then(parse_ax_number);- let size_w = segments.next().and_then(parse_ax_number);- let size_h = segments.next().and_then(parse_ax_number);-- let allow_terminal_text_value =- is_terminal_app(app_name.as_deref()) && !value.trim().is_empty();- if !is_text_role(role.as_deref()) && !allow_terminal_text_value {- value.clear();- selected_text = None;- if raw_error.is_none() {- raw_error = Some("ERROR:no_text_candidate_found".to_string());- }- }-- Ok(FocusedTextContext {- app_name,- role,- text: value,- selected_text,- raw_error,- bounds: match (pos_x, pos_y, size_w, size_h) {- (Some(x), Some(y), Some(width), Some(height)) if width > 0 && height > 0 => {- Some(ElementBounds {- x,- y,- width,- height,- })- }- _ => None,- },- })-}--#[cfg(not(target_os = "macos"))]-pub fn focused_text_context() -> Result<FocusedTextContext, String> {- Err("accessibility focus queries are only supported on macOS".to_string())-}--#[cfg(not(target_os = "macos"))]-pub fn focused_text_context_verbose() -> Result<FocusedTextContext, String> {- Err("accessibility focus queries are only supported on macOS".to_string())-}--// ----------------------------------------------------------------------------// Focus target validation-// -----------------------------------------------------------------------------/// Validate that the currently focused element still matches the target we generated the-/// suggestion for. Returns Ok if it matches or if validation is inconclusive.-#[cfg(target_os = "macos")]-fn is_text_editable_role(role: &str) -> bool {- matches!(role, "AXTextArea" | "AXTextField")-}--#[cfg(target_os = "macos")]-pub fn validate_focused_target(- expected_app: Option<&str>,- expected_role: Option<&str>,-) -> Result<(), String> {- if expected_app.is_none() {- return Ok(());- }- let current = focused_text_context_verbose();- match current {- Ok(ctx) => {- if let (Some(expected), Some(actual)) = (expected_app, ctx.app_name.as_deref()) {- if expected.to_lowercase() != actual.to_lowercase() {- return Err(format!(- "focus shifted from '{}' to '{}', aborting insertion",- expected, actual- ));- }- }- if let (Some(expected), Some(actual)) = (expected_role, ctx.role.as_deref()) {- if expected != actual {- if is_text_editable_role(expected) && is_text_editable_role(actual) {- log::debug!(- "[accessibility] validate_focused_target: role changed '{}' -> '{}'; proceeding",- expected,- actual- );- } else {- return Err(format!(- "focus role changed from '{}' to '{}', aborting insertion",- expected, actual- ));- }- }- }- Ok(())- }- Err(_) => Ok(()),- }-}--#[cfg(not(target_os = "macos"))]-pub fn validate_focused_target(- _expected_app: Option<&str>,- _expected_role: Option<&str>,-) -> Result<(), String> {- Ok(())-}--#[cfg(test)]-#[path = "focus_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/desktop/accessibility/focus_tests.rs b/crates/openhuman-core/src/desktop/accessibility/focus_tests.rsdeleted file mode 100644index 6ad775646a..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/focus_tests.rs+++ /dev/null@@ -1,28 +0,0 @@-use super::*;--#[cfg(unix)]-#[test]-fn command_output_with_timeout_returns_output_for_fast_command() {- let mut command = Command::new("sh");- command.arg("-c").arg("printf ready");-- let output =- command_output_with_timeout("test fast command", &mut command, Duration::from_secs(1))- .expect("fast command should complete");-- assert!(output.status.success());- assert_eq!(String::from_utf8_lossy(&output.stdout), "ready");-}--#[cfg(unix)]-#[test]-fn command_output_with_timeout_kills_slow_command() {- let mut command = Command::new("sh");- command.arg("-c").arg("sleep 2; printf late");-- let error =- command_output_with_timeout("test slow command", &mut command, Duration::from_millis(50))- .expect_err("slow command should time out");-- assert!(error.contains("timed out after"));-}diff --git a/crates/openhuman-core/src/desktop/accessibility/globe.rs b/crates/openhuman-core/src/desktop/accessibility/globe.rsdeleted file mode 100644index 9a414b4ccd..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/globe.rs+++ /dev/null@@ -1,463 +0,0 @@-//! macOS Globe/Fn key listener helper management.-//!-//! The listener runs as a tiny Swift process that monitors `flagsChanged`-//! events globally and reports `FN_DOWN` / `FN_UP` lines over stdout.--use super::{detect_permissions, PermissionState};-#[cfg(target_os = "macos")]-use std::collections::VecDeque;--#[cfg(target_os = "macos")]-use once_cell::sync::Lazy;-#[cfg(target_os = "macos")]-use std::fs;-#[cfg(target_os = "macos")]-use std::io::{BufRead, BufReader};-#[cfg(target_os = "macos")]-use std::path::PathBuf;-#[cfg(target_os = "macos")]-use std::process::{Child, Command, Stdio};-#[cfg(target_os = "macos")]-use std::sync::{Arc, Mutex as StdMutex};--const LOG_PREFIX: &str = "[globe_hotkey]";-const MAX_PENDING_EVENTS: usize = 64;--#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]-pub struct GlobeHotkeyStatus {- pub supported: bool,- pub running: bool,- pub input_monitoring_permission: PermissionState,- pub last_error: Option<String>,- pub events_pending: usize,-}--#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]-pub struct GlobeHotkeyPollResult {- pub status: GlobeHotkeyStatus,- pub events: Vec<String>,-}--#[cfg(target_os = "macos")]-struct GlobeListenerProcess {- child: Child,- event_queue: Arc<StdMutex<VecDeque<String>>>,- last_error: Arc<StdMutex<Option<String>>>,-}--#[cfg(target_os = "macos")]-static GLOBE_LISTENER: Lazy<StdMutex<Option<GlobeListenerProcess>>> =- Lazy::new(|| StdMutex::new(None));--#[cfg(target_os = "macos")]-fn push_event(queue: &Arc<StdMutex<VecDeque<String>>>, event: String) {- let Ok(mut guard) = queue.lock() else {- log::warn!("{LOG_PREFIX} failed to lock queue for event");- return;- };- guard.push_back(event);- while guard.len() > MAX_PENDING_EVENTS {- let _ = guard.pop_front();- }-}--#[cfg(target_os = "macos")]-fn set_last_error(error_store: &Arc<StdMutex<Option<String>>>, message: Option<String>) {- let Ok(mut guard) = error_store.lock() else {- log::warn!("{LOG_PREFIX} failed to lock last_error store");- return;- };- *guard = message;-}--#[cfg(target_os = "macos")]-fn drain_events(queue: &Arc<StdMutex<VecDeque<String>>>) -> Vec<String> {- let Ok(mut guard) = queue.lock() else {- log::warn!("{LOG_PREFIX} failed to lock queue for drain");- return Vec::new();- };- guard.drain(..).collect()-}--#[cfg(target_os = "macos")]-fn queue_len(queue: &Arc<StdMutex<VecDeque<String>>>) -> usize {- let Ok(guard) = queue.lock() else {- return 0;- };- guard.len()-}--#[cfg(target_os = "macos")]-fn current_error(error_store: &Arc<StdMutex<Option<String>>>) -> Option<String> {- let Ok(guard) = error_store.lock() else {- return Some("failed to read globe listener error state".to_string());- };- guard.clone()-}--#[cfg(target_os = "macos")]-fn ensure_running_locked(- state: &mut Option<GlobeListenerProcess>,-) -> Result<GlobeHotkeyStatus, String> {- let input_monitoring_permission = detect_permissions().input_monitoring;- if input_monitoring_permission != PermissionState::Granted {- let message =- "input monitoring permission is required for the macOS Globe/Fn listener".to_string();- log::warn!(- "{LOG_PREFIX} start skipped: input_monitoring_permission={:?}",- input_monitoring_permission- );- if let Some(process) = state.as_ref() {- set_last_error(&process.last_error, Some(message.clone()));- }- return Ok(GlobeHotkeyStatus {- supported: true,- running: false,- input_monitoring_permission,- last_error: Some(message),- events_pending: 0,- });- }-- if let Some(process) = state.as_mut() {- match process.child.try_wait() {- Ok(None) => {- return Ok(GlobeHotkeyStatus {- supported: true,- running: true,- input_monitoring_permission,- last_error: current_error(&process.last_error),- events_pending: queue_len(&process.event_queue),- });- }- Ok(Some(status)) => {- let message = format!("globe listener exited unexpectedly: {status}");- log::warn!("{LOG_PREFIX} {message}");- set_last_error(&process.last_error, Some(message));- *state = None;- }- Err(err) => {- let message = format!("failed to inspect globe listener state: {err}");- log::warn!("{LOG_PREFIX} {message}");- set_last_error(&process.last_error, Some(message));- *state = None;- }- }- }-- let binary_path = ensure_globe_helper_binary()?;- log::info!("{LOG_PREFIX} starting helper {}", binary_path.display());- let mut child = Command::new(&binary_path)- .stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .spawn()- .map_err(|e| format!("failed to spawn globe listener helper: {e}"))?;-- let stdout = child- .stdout- .take()- .ok_or_else(|| "failed to capture globe listener stdout".to_string())?;- let stderr = child- .stderr- .take()- .ok_or_else(|| "failed to capture globe listener stderr".to_string())?;-- let event_queue = Arc::new(StdMutex::new(VecDeque::with_capacity(MAX_PENDING_EVENTS)));- let last_error = Arc::new(StdMutex::new(None));-- {- let queue = event_queue.clone();- let error_store = last_error.clone();- std::thread::spawn(move || {- let reader = BufReader::new(stdout);- for line in reader.lines() {- match line {- Ok(line) => {- let trimmed = line.trim();- if trimmed.is_empty() {- continue;- }- log::debug!("{LOG_PREFIX} helper event={trimmed}");- push_event(&queue, trimmed.to_string());- set_last_error(&error_store, None);- }- Err(err) => {- let message = format!("failed reading globe listener stdout: {err}");- log::warn!("{LOG_PREFIX} {message}");- set_last_error(&error_store, Some(message));- break;- }- }- }- log::debug!("{LOG_PREFIX} stdout reader exited");- });- }-- {- let error_store = last_error.clone();- std::thread::spawn(move || {- let reader = BufReader::new(stderr);- for line in reader.lines() {- match line {- Ok(line) => {- let trimmed = line.trim();- if trimmed.is_empty() {- continue;- }- log::warn!("{LOG_PREFIX} helper stderr={trimmed}");- set_last_error(&error_store, Some(trimmed.to_string()));- }- Err(err) => {- let message = format!("failed reading globe listener stderr: {err}");- log::warn!("{LOG_PREFIX} {message}");- set_last_error(&error_store, Some(message));- break;- }- }- }- log::debug!("{LOG_PREFIX} stderr reader exited");- });- }-- *state = Some(GlobeListenerProcess {- child,- event_queue,- last_error,- });-- let process = state- .as_ref()- .ok_or_else(|| "globe listener process missing after spawn".to_string())?;- Ok(GlobeHotkeyStatus {- supported: true,- running: true,- input_monitoring_permission,- last_error: current_error(&process.last_error),- events_pending: queue_len(&process.event_queue),- })-}--#[cfg(target_os = "macos")]-fn ensure_globe_helper_binary() -> Result<PathBuf, String> {- let cache_dir = std::env::temp_dir().join("openhuman-globe-listener");- fs::create_dir_all(&cache_dir).map_err(|e| format!("failed to create globe cache dir: {e}"))?;-- let source_path = cache_dir.join("globe_listener.swift");- let binary_path = cache_dir.join("globe_listener_bin");- let source = globe_swift_source();-- let needs_write = match fs::read_to_string(&source_path) {- Ok(existing) => existing != source,- Err(_) => true,- };- if needs_write {- fs::write(&source_path, &source)- .map_err(|e| format!("failed to write globe helper source: {e}"))?;- }-- let needs_compile = needs_write || !binary_path.exists();- if needs_compile {- log::debug!("{LOG_PREFIX} compiling Swift helper");- let output = Command::new("xcrun")- .args(["swiftc", "-O", "-framework", "Cocoa"])- .arg(&source_path)- .arg("-o")- .arg(&binary_path)- .output()- .or_else(|_| {- Command::new("swiftc")- .args(["-O", "-framework", "Cocoa"])- .arg(&source_path)- .arg("-o")- .arg(&binary_path)- .output()- })- .map_err(|e| format!("failed to invoke swiftc for globe listener: {e}"))?;- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();- return Err(format!(- "failed to compile globe listener helper: {}",- if stderr.is_empty() {- "swiftc returned non-zero exit status".to_string()- } else {- stderr- }- ));- }- log::debug!("{LOG_PREFIX} Swift helper compiled successfully");- }-- Ok(binary_path)-}--#[cfg(target_os = "macos")]-fn globe_swift_source() -> String {- r##"import Cocoa-import Darwin--var fnIsDown = false-var lastModifierFlags: NSEvent.ModifierFlags = []--let rightModifiers: [(UInt16, NSEvent.ModifierFlags, String)] = [- (61, .option, "RightOption"),- (54, .command, "RightCommand"),- (62, .control, "RightControl"),- (60, .shift, "RightShift"),-]--let modifierMask: NSEvent.ModifierFlags = [.control, .command, .option, .shift]--let releases: [(NSEvent.ModifierFlags, String)] = [- (.control, "control"),- (.command, "command"),- (.option, "option"),- (.shift, "shift"),-]--func emit(_ message: String) {- FileHandle.standardOutput.write((message + "\n").data(using: .utf8)!)- fflush(stdout)-}--guard let monitor = NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged, handler: { event in- let flags = event.modifierFlags- let containsFn = flags.contains(.function)-- if containsFn && !fnIsDown {- fnIsDown = true- emit("FN_DOWN")- } else if !containsFn && fnIsDown {- fnIsDown = false- emit("FN_UP")- }-- let keyCode = event.keyCode- for (code, flag, name) in rightModifiers {- if keyCode == code {- emit(flags.contains(flag) ? "RIGHT_MOD_DOWN:\(name)" : "RIGHT_MOD_UP:\(name)")- break- }- }-- let currentModifiers = flags.intersection(modifierMask)- if currentModifiers != lastModifierFlags {- let released = lastModifierFlags.subtracting(currentModifiers)- for (flag, name) in releases {- if released.contains(flag) {- emit("MODIFIER_UP:\(name)")- }- }- lastModifierFlags = currentModifiers- }-}) else {- FileHandle.standardError.write("Failed to create event monitor\n".data(using: .utf8)!)- exit(1)-}--let signalSource = DispatchSource.makeSignalSource(signal: SIGTERM, queue: .main)-signal(SIGTERM, SIG_IGN)-signalSource.setEventHandler {- NSEvent.removeMonitor(monitor)- exit(0)-}-signalSource.resume()--let app = NSApplication.shared-app.setActivationPolicy(.accessory)-app.run()-"##- .to_string()-}--#[cfg(target_os = "macos")]-pub fn globe_listener_start() -> Result<GlobeHotkeyStatus, String> {- let mut guard = GLOBE_LISTENER- .lock()- .map_err(|_| "globe listener lock poisoned".to_string())?;- ensure_running_locked(&mut guard)-}--#[cfg(target_os = "macos")]-pub fn globe_listener_poll() -> Result<GlobeHotkeyPollResult, String> {- let mut guard = GLOBE_LISTENER- .lock()- .map_err(|_| "globe listener lock poisoned".to_string())?;- let status = ensure_running_locked(&mut guard)?;- let events = guard- .as_ref()- .map(|process| drain_events(&process.event_queue))- .unwrap_or_default();- Ok(GlobeHotkeyPollResult {- status: GlobeHotkeyStatus {- events_pending: 0,- ..status- },- events,- })-}--#[cfg(target_os = "macos")]-pub fn globe_listener_stop() -> Result<GlobeHotkeyStatus, String> {- let mut guard = GLOBE_LISTENER- .lock()- .map_err(|_| "globe listener lock poisoned".to_string())?;- if let Some(mut process) = guard.take() {- log::info!("{LOG_PREFIX} stopping helper pid={}", process.child.id());- let _ = process.child.kill();- let _ = process.child.wait();- let events = drain_events(&process.event_queue);- log::debug!(- "{LOG_PREFIX} drained {} queued events on stop",- events.len()- );- }-- Ok(GlobeHotkeyStatus {- supported: true,- running: false,- input_monitoring_permission: detect_permissions().input_monitoring,- last_error: None,- events_pending: 0,- })-}--#[cfg(not(target_os = "macos"))]-pub fn globe_listener_start() -> Result<GlobeHotkeyStatus, String> {- Ok(GlobeHotkeyStatus {- supported: false,- running: false,- input_monitoring_permission: detect_permissions().input_monitoring,- last_error: Some("Globe/Fn hotkey listener is only supported on macOS".to_string()),- events_pending: 0,- })-}--#[cfg(not(target_os = "macos"))]-pub fn globe_listener_poll() -> Result<GlobeHotkeyPollResult, String> {- Ok(GlobeHotkeyPollResult {- status: GlobeHotkeyStatus {- supported: false,- running: false,- input_monitoring_permission: detect_permissions().input_monitoring,- last_error: Some("Globe/Fn hotkey listener is only supported on macOS".to_string()),- events_pending: 0,- },- events: Vec::new(),- })-}--#[cfg(not(target_os = "macos"))]-pub fn globe_listener_stop() -> Result<GlobeHotkeyStatus, String> {- Ok(GlobeHotkeyStatus {- supported: false,- running: false,- input_monitoring_permission: detect_permissions().input_monitoring,- last_error: Some("Globe/Fn hotkey listener is only supported on macOS".to_string()),- events_pending: 0,- })-}--#[cfg(test)]-#[path = "globe_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/desktop/accessibility/globe_tests.rs b/crates/openhuman-core/src/desktop/accessibility/globe_tests.rsdeleted file mode 100644index 5f14910dfe..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/globe_tests.rs+++ /dev/null@@ -1,25 +0,0 @@-use super::MAX_PENDING_EVENTS;-use std::collections::VecDeque;--fn push_event_local(queue: &mut VecDeque<String>, event: String) {- queue.push_back(event);- while queue.len() > MAX_PENDING_EVENTS {- let _ = queue.pop_front();- }-}--#[test]-fn event_queue_keeps_latest_events() {- let mut queue = VecDeque::new();- for index in 0..(MAX_PENDING_EVENTS + 5) {- push_event_local(&mut queue, format!("event-{index}"));- }-- assert_eq!(queue.len(), MAX_PENDING_EVENTS);- assert_eq!(queue.front().map(String::as_str), Some("event-5"));- let expected_last = format!("event-{}", MAX_PENDING_EVENTS + 4);- assert_eq!(- queue.back().map(String::as_str),- Some(expected_last.as_str())- );-}diff --git a/crates/openhuman-core/src/desktop/accessibility/helper.rs b/crates/openhuman-core/src/desktop/accessibility/helper.rsdeleted file mode 100644index ecbf7339a8..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/helper.rs+++ /dev/null@@ -1,39 +0,0 @@-//! Unified Swift helper process: focus queries, paste, and overlay in one native binary.-//!-//! Replaces the separate osascript subprocess spawns and standalone overlay binary-//! with a single persistent Swift process communicating via stdin/stdout JSON.-//!-//! ## Mutex architecture-//!-//! Three globals prevent deadlock between fire-and-forget (show/hide) and-//! request-response (focus/paste) callers:-//!-//! - `UNIFIED_HELPER`: guards the process handle + stdin writer.-//! Held only for the brief duration of a stdin write (~μs).-//! - `RESPONSE_RX`: guards the mpsc receiver that the background reader-//! thread populates. Held only for the duration of `recv_timeout`.-//! - `RECV_SERIALISER`: held for the entire send+receive round-trip so that-//! two callers cannot interleave their reads.-//!-//! Fire-and-forget callers never touch `RESPONSE_RX` or `RECV_SERIALISER`,-//! so `show`/`hide` can proceed while a `focus` query is in-flight.-//!-//! Split by responsibility: [`process`] owns the process lifecycle and the-//! send/receive paths, and the `swift_*` modules hold the embedded Swift-//! source (assembled by [`swift_source`]) that the helper binary compiles-//! from.--mod process;-mod swift_ax_actions;-mod swift_focus;-mod swift_overlay;-mod swift_paste;-mod swift_source;--#[cfg(target_os = "macos")]-#[allow(unused_imports)]-pub(crate) use process::helper_send_receive;-pub use process::precompile_helper_background;-#[cfg(target_os = "macos")]-#[allow(unused_imports)]-pub(in crate::desktop::accessibility) use process::{helper_quit, helper_send_fire_and_forget};diff --git a/crates/openhuman-core/src/desktop/accessibility/helper/process.rs b/crates/openhuman-core/src/desktop/accessibility/helper/process.rsdeleted file mode 100644index 0c9cc087e0..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/helper/process.rs+++ /dev/null@@ -1,373 +0,0 @@-//! Unified helper process lifecycle: spawning and supervising the persistent-//! Swift binary, the request/response and fire-and-forget send paths, and-//! compiling/caching the helper binary from its embedded Swift source.--#[cfg(target_os = "macos")]-use once_cell::sync::Lazy;-#[cfg(target_os = "macos")]-use std::io::{BufRead, BufReader, Write};-#[cfg(target_os = "macos")]-use std::sync::atomic::{AtomicU64, Ordering};-#[cfg(target_os = "macos")]-use std::sync::{mpsc, Mutex as StdMutex};-#[cfg(target_os = "macos")]-use std::time::{Duration, Instant};-#[cfg(target_os = "macos")]-use std::{- fs,- path::PathBuf,- process::{Child, ChildStdin, Command, Stdio},-};--#[cfg(target_os = "macos")]-use super::swift_source::unified_swift_source;-#[cfg(target_os = "macos")]-use serde_json::Value;--/// Process handle + stdin writer. Held only briefly for writes.-#[cfg(target_os = "macos")]-struct UnifiedHelperProcess {- child: Child,- stdin: ChildStdin,-}--/// Guards the process handle and stdin.-#[cfg(target_os = "macos")]-static UNIFIED_HELPER: Lazy<StdMutex<Option<UnifiedHelperProcess>>> =- Lazy::new(|| StdMutex::new(None));--/// Channel receiver fed by the background stdout-reader thread.-/// Separate from UNIFIED_HELPER so fire-and-forget callers never contend here.-#[cfg(target_os = "macos")]-static RESPONSE_RX: Lazy<StdMutex<Option<mpsc::Receiver<String>>>> =- Lazy::new(|| StdMutex::new(None));--/// Serialises request/response pairs so two callers cannot interleave reads.-/// Fire-and-forget callers never acquire this lock.-#[cfg(target_os = "macos")]-static RECV_SERIALISER: Lazy<StdMutex<()>> = Lazy::new(|| StdMutex::new(()));--/// Prevents concurrent Swift compiles from `ensure_helper_binary` vs background precompile.-#[cfg(target_os = "macos")]-static HELPER_COMPILE_LOCK: Lazy<StdMutex<()>> = Lazy::new(|| StdMutex::new(()));--/// Monotonic ids for `helper_send_receive` so a late line cannot be consumed as the wrong reply.-#[cfg(target_os = "macos")]-static HELPER_REQ_ID: AtomicU64 = AtomicU64::new(1);--/// Timeout for a single request/response round-trip with the Swift helper.-#[cfg(target_os = "macos")]-const HELPER_RECV_TIMEOUT: Duration = Duration::from_secs(8);--/// Send a JSON request and read a JSON response (one line each).-/// Used for `focus` and `paste` commands that produce a response.-///-/// Holds `RECV_SERIALISER` for the full round-trip, but releases-/// `UNIFIED_HELPER` before blocking on the channel recv, so fire-and-forget-/// callers (`show`/`hide`) are never blocked by an in-flight focus query.-#[cfg(target_os = "macos")]-pub(crate) fn helper_send_receive(- request: &serde_json::Value,-) -> Result<serde_json::Value, String> {- // Serialise request/response pairs — prevents interleaved reads.- let _rr_guard = RECV_SERIALISER- .lock()- .map_err(|_| "recv serialiser lock poisoned".to_string())?;-- ensure_helper_running()?;-- let id_num = HELPER_REQ_ID.fetch_add(1, Ordering::Relaxed);- let id_str = id_num.to_string();-- let mut req = request.clone();- let req_obj = req- .as_object_mut()- .ok_or_else(|| "helper request must be a JSON object".to_string())?;- req_obj.insert("id".to_string(), Value::String(id_str.clone()));-- // Write the request, holding UNIFIED_HELPER only for this brief write.- {- let mut guard = UNIFIED_HELPER- .lock()- .map_err(|_| "unified helper lock poisoned".to_string())?;- let helper = guard- .as_mut()- .ok_or_else(|| "unified helper unavailable".to_string())?;- let line = req.to_string();- helper- .stdin- .write_all(line.as_bytes())- .and_then(|_| helper.stdin.write_all(b"\n"))- .and_then(|_| helper.stdin.flush())- .map_err(|e| format!("failed to write to helper stdin: {e}"))?;- } // UNIFIED_HELPER released here — fire-and-forget callers can proceed-- // Read until the line matches `id` (discards stale lines after a timeout or reordering).- let deadline = Instant::now() + HELPER_RECV_TIMEOUT;- loop {- let remaining = deadline.saturating_duration_since(Instant::now());- if remaining.is_zero() {- return Err(format!(- "helper response timed out waiting for id {id_str} (stale lines may follow)"- ));- }- let chunk = remaining.min(Duration::from_millis(500));- let response_line = {- let rx_guard = RESPONSE_RX- .lock()- .map_err(|_| "response rx lock poisoned".to_string())?;- let rx = rx_guard- .as_ref()- .ok_or_else(|| "response channel unavailable".to_string())?;- match rx.recv_timeout(chunk) {- Ok(line) => line,- Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {- // Non-fatal: the outer loop will check `remaining` and- // either retry or surface the top-level timeout.- continue;- }- Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {- return Err("helper response channel disconnected".to_string());- }- }- };-- if response_line.trim().is_empty() {- log::debug!(- "[accessibility] helper skipped empty stdout line while waiting for id {id_str}"- );- continue;- }-- let value: Value = serde_json::from_str(response_line.trim())- .map_err(|e| format!("failed to parse helper response: {e}"))?;-- let matches = value- .get("id")- .and_then(|v| v.as_str())- .is_some_and(|rid| rid == id_str.as_str());- if matches {- return Ok(value);- }- log::debug!(- "[accessibility] discarding helper response with mismatched or missing id (want id={})",- id_str- );- }-}--/// Send a JSON request without waiting for a response.-/// Used for `show`, `hide`, and `quit` commands.-/// Only acquires UNIFIED_HELPER (for the stdin write) — never blocks on I/O.-#[cfg(target_os = "macos")]-pub(in crate::desktop::accessibility) fn helper_send_fire_and_forget(- request: &serde_json::Value,-) -> Result<(), String> {- ensure_helper_running()?;- let mut guard = UNIFIED_HELPER- .lock()- .map_err(|_| "unified helper lock poisoned".to_string())?;- let helper = guard- .as_mut()- .ok_or_else(|| "unified helper unavailable".to_string())?;-- let line = request.to_string();- helper- .stdin- .write_all(line.as_bytes())- .and_then(|_| helper.stdin.write_all(b"\n"))- .and_then(|_| helper.stdin.flush())- .map_err(|e| format!("failed to write to helper stdin: {e}"))?;- Ok(())-}--/// Quit and clean up the helper process.-#[cfg(target_os = "macos")]-pub(in crate::desktop::accessibility) fn helper_quit() -> Result<(), String> {- // Drop the response channel first so the reader thread exits cleanly.- {- let mut rx_guard = RESPONSE_RX- .lock()- .map_err(|_| "response rx lock poisoned".to_string())?;- rx_guard.take();- }- let mut guard = UNIFIED_HELPER- .lock()- .map_err(|_| "unified helper lock poisoned".to_string())?;- if let Some(mut helper) = guard.take() {- let _ = helper.stdin.write_all(br#"{"type":"quit"}"#);- let _ = helper.stdin.write_all(b"\n");- let _ = helper.stdin.flush();- let _ = helper.child.kill();- let _ = helper.child.wait();- }- Ok(())-}--/// Ensure the helper process is running. Spawns it (and the stdout reader-/// thread) if not yet started or if it has exited unexpectedly.-#[cfg(target_os = "macos")]-fn ensure_helper_running() -> Result<(), String> {- let mut guard = UNIFIED_HELPER- .lock()- .map_err(|_| "unified helper lock poisoned".to_string())?;-- if let Some(helper) = guard.as_mut() {- if helper- .child- .try_wait()- .map_err(|e| format!("failed to query helper state: {e}"))?- .is_none()- {- return Ok(()); // Still running- }- log::debug!("[accessibility] unified helper exited, restarting");- *guard = None;- // Also drop the stale receiver so a new one will be created below.- if let Ok(mut rx_guard) = RESPONSE_RX.lock() {- rx_guard.take();- }- }-- let binary_path = ensure_helper_binary()?;- let mut child = Command::new(&binary_path)- .stdin(Stdio::piped())- .stdout(Stdio::piped())- .stderr(Stdio::null())- .spawn()- .map_err(|e| format!("failed to spawn unified helper: {e}"))?;-- let stdin = child- .stdin- .take()- .ok_or_else(|| "failed to capture helper stdin".to_string())?;- let stdout = child- .stdout- .take()- .ok_or_else(|| "failed to capture helper stdout".to_string())?;-- // Spawn a background thread that continuously reads lines from the helper's- // stdout and forwards them into the channel. The thread exits when the- // sender is dropped (i.e. when helper_quit drops RESPONSE_RX) or when the- // process closes its stdout.- let (tx, rx) = mpsc::channel::<String>();- std::thread::spawn(move || {- let mut reader = BufReader::new(stdout);- let mut line = String::new();- loop {- line.clear();- match reader.read_line(&mut line) {- Ok(0) => break, // EOF — helper exited- Ok(_) => {- let trimmed = line.trim().to_string();- if !trimmed.is_empty() && tx.send(trimmed).is_err() {- break; // Receiver dropped — time to exit- }- }- Err(e) => {- log::debug!("[accessibility] helper stdout reader error: {e}");- break;- }- }- }- log::debug!("[accessibility] helper stdout reader thread exiting");- });-- // Store the new receiver.- if let Ok(mut rx_guard) = RESPONSE_RX.lock() {- *rx_guard = Some(rx);- }-- *guard = Some(UnifiedHelperProcess { child, stdin });- log::debug!("[accessibility] unified helper started");- Ok(())-}--/// Compile the Swift helper binary in the background so the first overlay-/// request does not incur the compile latency. Safe to call multiple times;-/// subsequent calls are no-ops (the binary is cached by `ensure_helper_binary`).-#[cfg(target_os = "macos")]-pub fn precompile_helper_background() {- std::thread::spawn(|| {- log::debug!("[accessibility] precompile_helper_background: starting");- match ensure_helper_binary() {- Ok(path) => log::debug!("[accessibility] helper binary ready: {}", path.display()),- Err(e) => log::warn!(- "[accessibility] helper precompile failed (will retry on first use): {e}"- ),- }- });-}--/// No-op on non-macOS platforms.-#[cfg(not(target_os = "macos"))]-pub fn precompile_helper_background() {}--#[cfg(target_os = "macos")]-fn ensure_helper_binary() -> Result<PathBuf, String> {- let _compile_guard = HELPER_COMPILE_LOCK- .lock()- .map_err(|_| "helper compile lock poisoned".to_string())?;-- let cache_dir = std::env::temp_dir().join("openhuman-accessibility-helper");- fs::create_dir_all(&cache_dir).map_err(|e| format!("failed to create cache dir: {e}"))?;- let source_path = cache_dir.join("unified_helper.swift");- let binary_path = cache_dir.join("unified_helper_bin");- let source = unified_swift_source();-- let needs_write = match fs::read_to_string(&source_path) {- Ok(existing) => existing != source,- Err(_) => true,- };- if needs_write {- fs::write(&source_path, &source)- .map_err(|e| format!("failed to write helper source: {e}"))?;- }-- let needs_compile = needs_write || !binary_path.exists();- if needs_compile {- log::debug!("[accessibility] compiling unified Swift helper");- let output = Command::new("xcrun")- .args([- "swiftc",- "-O",- "-framework",- "Cocoa",- "-framework",- "ApplicationServices",- ])- .arg(&source_path)- .arg("-o")- .arg(&binary_path)- .output()- .or_else(|_| {- Command::new("swiftc")- .args([- "-O",- "-framework",- "Cocoa",- "-framework",- "ApplicationServices",- ])- .arg(&source_path)- .arg("-o")- .arg(&binary_path)- .output()- })- .map_err(|e| format!("failed to invoke swiftc: {e}"))?;- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();- return Err(format!(- "failed to compile unified helper: {}",- if stderr.is_empty() {- "swiftc returned non-zero exit status".to_string()- } else {- stderr- }- ));- }- log::debug!("[accessibility] unified helper compiled successfully");- }-- Ok(binary_path)-}diff --git a/crates/openhuman-core/src/desktop/accessibility/helper/swift_ax_actions.rs b/crates/openhuman-core/src/desktop/accessibility/helper/swift_ax_actions.rsdeleted file mode 100644index eae5e035b4..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/helper/swift_ax_actions.rs+++ /dev/null@@ -1,148 +0,0 @@-//! Embedded Swift source fragment: AXUIElement app interaction — finding a-//! running app, walking its AX tree, listing elements, pressing controls, and-//! setting text-field values.-#[cfg(target_os = "macos")]-pub(super) const SWIFT_AX_ACTIONS: &str = r##"// MARK: - AXUIElement App Interaction--/// Find a running application by display name (exact, prefix, or contains match).-func findRunningApp(named appName: String) -> NSRunningApplication? {- let apps = NSWorkspace.shared.runningApplications- let lower = appName.lowercased()- if let app = apps.first(where: { $0.localizedName?.lowercased() == lower }) { return app }- if let app = apps.first(where: { $0.localizedName?.lowercased().hasPrefix(lower) ?? false }) { return app }- return apps.first(where: { $0.localizedName?.lowercased().contains(lower) ?? false })-}--/// Walk the AX element tree depth-first. Visitor returns true to stop early.-func axWalk(_ element: AXUIElement, depth: Int = 0, maxDepth: Int = 12,- visitor: (AXUIElement, String, String) -> Bool) -> Bool {- if depth > maxDepth { return false }- var roleRef: AnyObject?- AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &roleRef)- let role = (roleRef as? String) ?? ""- var labelRef: AnyObject?- AXUIElementCopyAttributeValue(element, kAXTitleAttribute as CFString, &labelRef)- var label = (labelRef as? String) ?? ""- if label.isEmpty {- var descRef: AnyObject?- AXUIElementCopyAttributeValue(element, kAXDescriptionAttribute as CFString, &descRef)- label = (descRef as? String) ?? ""- }- if visitor(element, role, label) { return true }- var childrenRef: AnyObject?- guard AXUIElementCopyAttributeValue(element, kAXChildrenAttribute as CFString, &childrenRef) == .success,- let children = childrenRef as? [AXUIElement] else { return false }- for child in children {- if axWalk(child, depth: depth + 1, maxDepth: maxDepth, visitor: visitor) { return true }- }- return false-}--/// List interactive UI elements in the named app.-func axListElements(appName: String, id: String?) -> [String: Any] {- guard let app = findRunningApp(named: appName) else {- return ["type": "ax_list", "id": id ?? "", "ok": false,- "error": "App '\(appName)' not found or not running", "elements": [] as [Any]]- }- let axApp = AXUIElementCreateApplication(app.processIdentifier)- let interactiveRoles: Set<String> = [- "AXButton", "AXMenuItem", "AXMenuBarItem", "AXTextField", "AXTextArea",- "AXCheckBox", "AXRadioButton", "AXSlider", "AXPopUpButton",- "AXComboBox", "AXLink", "AXTab"- ]- var elements: [[String: Any]] = []- axWalk(axApp, maxDepth: 10) { el, role, label in- if interactiveRoles.contains(role) && !label.isEmpty {- elements.append(["role": role, "label": label, "enabled": axEnabled(el)])- }- return false- }- return ["type": "ax_list", "id": id ?? "", "ok": true, "error": NSNull(), "elements": elements]-}--/// Read the AXEnabled attribute; default to `true` when the attribute is absent-/// (most static/text elements don't expose it, and we don't want to hide them).-func axEnabled(_ element: AXUIElement) -> Bool {- var ref: AnyObject?- if AXUIElementCopyAttributeValue(element, kAXEnabledAttribute as CFString, &ref) == .success,- let b = ref as? Bool {- return b- }- return true-}--/// Collect all AX elements whose label contains `label` (case-insensitive).-/// Returns matches sorted exact-first so "Play" beats "Playlist".-struct AXCandidate {- var element: AXUIElement- var label: String- var exact: Bool-}--func axCollectMatches(_ root: AXUIElement, label: String, depth: Int = 0, maxDepth: Int = 12) -> [AXCandidate] {- if depth > maxDepth { return [] }- var roleRef: AnyObject?; AXUIElementCopyAttributeValue(root, kAXRoleAttribute as CFString, &roleRef)- var titleRef: AnyObject?; AXUIElementCopyAttributeValue(root, kAXTitleAttribute as CFString, &titleRef)- var elemLabel = (titleRef as? String) ?? ""- if elemLabel.isEmpty { var d: AnyObject?; AXUIElementCopyAttributeValue(root, kAXDescriptionAttribute as CFString, &d); elemLabel = (d as? String) ?? "" }- let lower = label.lowercased(); let elLower = elemLabel.lowercased()- var results: [AXCandidate] = []- if !elemLabel.isEmpty, elLower.contains(lower) {- results.append(AXCandidate(element: root, label: elemLabel, exact: elLower == lower))- }- var childrenRef: AnyObject?- guard AXUIElementCopyAttributeValue(root, kAXChildrenAttribute as CFString, &childrenRef) == .success,- let children = childrenRef as? [AXUIElement] else { return results }- for child in children { results += axCollectMatches(child, label: label, depth: depth+1, maxDepth: maxDepth) }- return results-}--/// Press a UI element by label — exact match preferred over contains match.-func axPress(appName: String, label: String, id: String?) -> [String: Any] {- guard let app = findRunningApp(named: appName) else {- return ["type": "ax_press", "id": id ?? "", "ok": false,- "error": "App '\(appName)' not found or not running"]- }- let axApp = AXUIElementCreateApplication(app.processIdentifier)- var matches = axCollectMatches(axApp, label: label)- // Exact matches first so "Play" beats "Playlist"- matches.sort { $0.exact && !$1.exact }- for match in matches {- if AXUIElementPerformAction(match.element, kAXPressAction as CFString) == .success {- return ["type": "ax_press", "id": id ?? "", "ok": true, "error": NSNull(),- "pressed": match.label]- }- }- return ["type": "ax_press", "id": id ?? "", "ok": false,- "error": "No pressable element matching '\(label)' found in '\(appName)' (\(matches.count) label match(es) not actionable)"]-}--/// Set the value of a text field by partial label match (or first text field if label is empty).-func axSetValue(appName: String, label: String, value: String, id: String?) -> [String: Any] {- guard let app = findRunningApp(named: appName) else {- return ["type": "ax_set_value", "id": id ?? "", "ok": false,- "error": "App '\(appName)' not found or not running"]- }- let axApp = AXUIElementCreateApplication(app.processIdentifier)- let textRoles: Set<String> = ["AXTextField", "AXTextArea", "AXSearchField", "AXComboBox"]- let lower = label.lowercased()- var setLabel = ""- let found = axWalk(axApp) { element, role, elemLabel in- guard textRoles.contains(role) else { return false }- let matchLabel = lower.isEmpty || elemLabel.lowercased().contains(lower)- guard matchLabel else { return false }- if AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, value as CFTypeRef) == .success {- setLabel = elemLabel- return true- }- return false- }- if found {- return ["type": "ax_set_value", "id": id ?? "", "ok": true, "error": NSNull(),- "field": setLabel]- }- return ["type": "ax_set_value", "id": id ?? "", "ok": false,- "error": "No text field matching '\(label)' found in '\(appName)'"]-}--"##;diff --git a/crates/openhuman-core/src/desktop/accessibility/helper/swift_focus.rs b/crates/openhuman-core/src/desktop/accessibility/helper/swift_focus.rsdeleted file mode 100644index 1c4506b92f..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/helper/swift_focus.rs+++ /dev/null@@ -1,222 +0,0 @@-//! Embedded Swift source fragment: imports, the thread-safe stdout writer, and-//! the accessibility focus-query logic (`queryFocusedElement` and its helpers).-#[cfg(target_os = "macos")]-pub(super) const SWIFT_HEADER_AND_FOCUS: &str = r##"import Cocoa-import Foundation-import ApplicationServices--// MARK: - Thread-safe stdout writer--let stdoutLock = NSLock()--func writeResponse(_ dict: [String: Any]) {- guard let data = try? JSONSerialization.data(withJSONObject: dict),- let line = String(data: data, encoding: .utf8) else { return }- stdoutLock.lock()- print(line)- fflush(stdout)- stdoutLock.unlock()-}--// MARK: - Accessibility Focus Query--let textRoles: Set<String> = ["AXTextArea", "AXTextField", "AXSearchField", "AXComboBox", "AXEditableText"]--// Apps that need AXEnhancedUserInterface to expose focused text elements properly.-let chromiumAppPatterns = ["chrom", "electron", "code", "slack", "discord", "brave", "edge", "opera", "vivaldi", "arc"]--func isChromiumApp(_ name: String) -> Bool {- let lower = name.lowercased()- return chromiumAppPatterns.contains(where: { lower.contains($0) })-}--func getAXStringAttr(_ element: AXUIElement, _ attr: String) -> String? {- var value: AnyObject?- let err = AXUIElementCopyAttributeValue(element, attr as CFString, &value)- guard err == .success, let str = value as? String, str != "missing value" else { return nil }- return str-}--func getAXPosition(_ element: AXUIElement) -> (x: Int, y: Int)? {- var value: AnyObject?- let err = AXUIElementCopyAttributeValue(element, kAXPositionAttribute as String as CFString, &value)- guard err == .success else { return nil }- var point = CGPoint.zero- AXValueGetValue(value as! AXValue, .cgPoint, &point)- return (Int(point.x), Int(point.y))-}--func getAXSize(_ element: AXUIElement) -> (w: Int, h: Int)? {- var value: AnyObject?- let err = AXUIElementCopyAttributeValue(element, kAXSizeAttribute as String as CFString, &value)- guard err == .success else { return nil }- var size = CGSize.zero- AXValueGetValue(value as! AXValue, .cgSize, &size)- return (Int(size.width), Int(size.height))-}--func scanChildrenForText(_ parent: AXUIElement, depth: Int = 0) -> (role: String, text: String, pos: (Int, Int)?, size: (Int, Int)?)? {- if depth > 5 { return nil }- var childrenRef: AnyObject?- let err = AXUIElementCopyAttributeValue(parent, kAXChildrenAttribute as String as CFString, &childrenRef)- guard err == .success, let children = childrenRef as? [AXUIElement] else { return nil }-- // First pass: look for text-role elements with content- for child in children.prefix(200) {- let role = getAXStringAttr(child, kAXRoleAttribute as String) ?? ""- if textRoles.contains(role) {- var text = getAXStringAttr(child, kAXValueAttribute as String) ?? ""- if text.isEmpty {- text = getAXStringAttr(child, kAXSelectedTextAttribute as String) ?? ""- }- if !text.isEmpty {- return (role, text, getAXPosition(child), getAXSize(child))- }- }- }-- // Second pass: look for AXStaticText with prompt patterns (terminal support)- var staticFallback: (role: String, text: String, pos: (Int, Int)?, size: (Int, Int)?)?- for child in children.prefix(200) {- let role = getAXStringAttr(child, kAXRoleAttribute as String) ?? ""- if role == "AXStaticText" {- let text = getAXStringAttr(child, kAXValueAttribute as String) ?? ""- if !text.isEmpty {- if text.contains("$ ") || text.contains("# ") || text.contains("> ") {- return (role, text, getAXPosition(child), getAXSize(child))- }- if staticFallback == nil {- staticFallback = (role, text, getAXPosition(child), getAXSize(child))- }- }- }- }- if let fb = staticFallback { return fb }-- // Recurse into children- for child in children.prefix(50) {- if let result = scanChildrenForText(child, depth: depth + 1) {- return result- }- }- return nil-}--func queryFocusedElement(id: String?) -> [String: Any] {- var result: [String: Any] = [- "type": "focus",- "app_name": NSNull(),- "role": NSNull(),- "text": "",- "selected_text": NSNull(),- "x": NSNull(), "y": NSNull(), "w": NSNull(), "h": NSNull(),- "error": NSNull(),- "ax_trusted": AXIsProcessTrusted(),- ]- if let id = id { result["id"] = id }-- let systemWide = AXUIElementCreateSystemWide()-- // Get focused application- var appRef: AnyObject?- var appErr = AXUIElementCopyAttributeValue(systemWide, kAXFocusedApplicationAttribute as String as CFString, &appRef)- guard appErr == .success, let appElement = appRef else {- result["error"] = "ERROR:no_focused_application"- return result- }-- let appName = getAXStringAttr(appElement as! AXUIElement, kAXTitleAttribute as String) ?? "unknown"- result["app_name"] = appName-- // Enable AXEnhancedUserInterface for Chromium apps- if isChromiumApp(appName) {- AXUIElementSetAttributeValue(appElement as! AXUIElement, "AXEnhancedUserInterface" as CFString, true as CFBoolean)- }-- // Get focused element- var focusedRef: AnyObject?- let focusErr = AXUIElementCopyAttributeValue(appElement as! AXUIElement, kAXFocusedUIElementAttribute as String as CFString, &focusedRef)-- if focusErr == .success, let focused = focusedRef {- let focusedElement = focused as! AXUIElement- let role = getAXStringAttr(focusedElement, kAXRoleAttribute as String) ?? "unknown"- result["role"] = role-- var text = getAXStringAttr(focusedElement, kAXValueAttribute as String) ?? ""- let selectedText = getAXStringAttr(focusedElement, kAXSelectedTextAttribute as String)- result["selected_text"] = selectedText ?? NSNull()-- if text.isEmpty, let sel = selectedText, !sel.isEmpty {- text = sel- }- if text.isEmpty {- text = getAXStringAttr(focusedElement, kAXTitleAttribute as String) ?? ""- }-- if let pos = getAXPosition(focusedElement) {- result["x"] = pos.x- result["y"] = pos.y- }- if let size = getAXSize(focusedElement) {- result["w"] = size.w- result["h"] = size.h- }-- // If we got text from a text-role element, we're done- if !text.isEmpty && textRoles.contains(role) {- result["text"] = text- return result- }-- // If role is not a text role, still return text if it looks terminal-like- let terminalApps = ["terminal", "iterm", "wezterm", "warp", "alacritty", "kitty", "ghostty", "hyper", "rio"]- let isTerminal = terminalApps.contains(where: { appName.lowercased().contains($0) })- if isTerminal && !text.isEmpty {- result["text"] = text- return result- }-- // Text is empty or not from a text role — scan window children- if text.isEmpty || !textRoles.contains(role) {- // Try scanning focused window's children- var windowRef: AnyObject?- let winErr = AXUIElementCopyAttributeValue(appElement as! AXUIElement, kAXFocusedWindowAttribute as String as CFString, &windowRef)- if winErr == .success, let window = windowRef {- if let found = scanChildrenForText(window as! AXUIElement) {- result["role"] = found.role- result["text"] = found.text- if let pos = found.pos { result["x"] = pos.0; result["y"] = pos.1 }- if let size = found.size { result["w"] = size.0; result["h"] = size.1 }- return result- }- }-- if text.isEmpty {- result["error"] = "ERROR:no_text_candidate_found"- } else {- // Got text but from non-text role and not terminal — still return it- result["text"] = text- }- } else {- result["text"] = text- }- } else {- // No focused element found — try window scanning- var windowRef: AnyObject?- let winErr = AXUIElementCopyAttributeValue(appElement as! AXUIElement, kAXFocusedWindowAttribute as String as CFString, &windowRef)- if winErr == .success, let window = windowRef {- if let found = scanChildrenForText(window as! AXUIElement) {- result["role"] = found.role- result["text"] = found.text- if let pos = found.pos { result["x"] = pos.0; result["y"] = pos.1 }- if let size = found.size { result["w"] = size.0; result["h"] = size.1 }- return result- }- }- result["error"] = "ERROR:-1728:no_focused_element"- }-- return result-}--"##;diff --git a/crates/openhuman-core/src/desktop/accessibility/helper/swift_overlay.rs b/crates/openhuman-core/src/desktop/accessibility/helper/swift_overlay.rsdeleted file mode 100644index 6ae31b450f..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/helper/swift_overlay.rs+++ /dev/null@@ -1,215 +0,0 @@-//! Embedded Swift source fragment: the on-screen overlay controller and the-//! process's stdin-driven main dispatch loop.-#[cfg(target_os = "macos")]-pub(super) const SWIFT_OVERLAY_AND_MAIN: &str = r##"// MARK: - Overlay Controller--final class OverlayController {- private var panel: NSPanel?- private var textField: NSTextField?- private var hintField: NSTextField?- private var hideWorkItem: DispatchWorkItem?-- func show(x: CGFloat, yTop: CGFloat, width: CGFloat, height: CGFloat, text: String, ttlMs: Int, tabHint: String) {- let showTabHint = !tabHint.isEmpty- // Detect current system appearance for contrast-appropriate colors.- let isDark: Bool = {- if #available(macOS 10.14, *) {- return NSApp.effectiveAppearance- .bestMatch(from: [.darkAqua, .aqua]) == .darkAqua- }- return false- }()- let bgColor = isDark- ? NSColor(white: 0.92, alpha: 0.82) // light badge on dark background- : NSColor(white: 0.10, alpha: 0.82) // dark badge on light background- let textColor = isDark- ? NSColor(white: 0.08, alpha: 0.95)- : NSColor(white: 1.0, alpha: 0.95)-- // Measure badge width from actual text metrics instead of char-count estimate.- let font = NSFont.systemFont(ofSize: 13)- let attrs: [NSAttributedString.Key: Any] = [.font: font]- let measured = (text as NSString).size(withAttributes: attrs)- let hintPad: CGFloat = showTabHint ? 80 : 16- let panelWidth = min(480, max(140, ceil(measured.width) + hintPad))- let panelHeight: CGFloat = 28-- // Multi-monitor: find the screen containing the target or mouse cursor.- let screen: NSScreen? = {- let mainHeight = NSScreen.screens.first?.frame.height ?? 900- if width > 0 && height > 0 {- let cocoaPoint = NSPoint(x: x + width / 2, y: mainHeight - (yTop + height / 2))- if let s = NSScreen.screens.first(where: { $0.frame.contains(cocoaPoint) }) {- return s- }- }- let mouseLocation = NSEvent.mouseLocation- if let s = NSScreen.screens.first(where: { $0.frame.contains(mouseLocation) }) {- return s- }- return NSScreen.main ?? NSScreen.screens.first- }()- let screenFrame = screen?.frame ?? NSRect(x: 0, y: 0, width: 1440, height: 900)- let screenHeight = screenFrame.height + screenFrame.origin.y-- var originX: CGFloat- var originYCocoa: CGFloat-- if width > 0 && height > 0 {- originX = x + max(8, min(width - panelWidth - 8, 28))- let originYTop = yTop + max(5, min(height - panelHeight - 4, 10))- originYCocoa = max(6, screenHeight - originYTop - panelHeight)- } else {- let mouseLocation = NSEvent.mouseLocation- originX = mouseLocation.x + 8- originYCocoa = mouseLocation.y - panelHeight - 8- }-- // Clamp to screen bounds- originX = max(screenFrame.origin.x + 4, min(originX, screenFrame.origin.x + screenFrame.width - panelWidth - 4))- originYCocoa = max(screenFrame.origin.y + 4, min(originYCocoa, screenFrame.origin.y + screenFrame.height - panelHeight - 4))-- if panel == nil {- let p = NSPanel(- contentRect: NSRect(x: originX, y: originYCocoa, width: panelWidth, height: panelHeight),- styleMask: [.borderless, .nonactivatingPanel],- backing: .buffered,- defer: false- )- p.level = .statusBar- p.hasShadow = false- p.isOpaque = false- p.backgroundColor = .clear- p.ignoresMouseEvents = true- p.collectionBehavior = [.canJoinAllSpaces, .transient]-- let content = NSView(frame: NSRect(x: 0, y: 0, width: panelWidth, height: panelHeight))- content.wantsLayer = true- content.layer?.cornerRadius = 6- content.layer?.backgroundColor = bgColor.cgColor- p.contentView = content-- let label = NSTextField(labelWithString: text)- label.frame = NSRect(x: 8, y: 5, width: panelWidth - (showTabHint ? 62 : 16), height: 18)- label.textColor = textColor- label.font = font- label.lineBreakMode = .byTruncatingTail- content.addSubview(label)-- let hint = NSTextField(labelWithString: tabHint.isEmpty ? "Tab ↵" : tabHint)- hint.frame = NSRect(x: panelWidth - 54, y: 5, width: 48, height: 18)- hint.textColor = NSColor(white: isDark ? 0.35 : 0.65, alpha: 1.0)- hint.font = NSFont.monospacedSystemFont(ofSize: 10, weight: .regular)- hint.alignment = .right- hint.isHidden = !showTabHint- content.addSubview(hint)-- panel = p- textField = label- hintField = hint- }-- // Re-apply colors on every show so runtime appearance changes are reflected.- panel?.contentView?.layer?.backgroundColor = bgColor.cgColor- textField?.textColor = textColor- hintField?.textColor = NSColor(white: isDark ? 0.35 : 0.65, alpha: 1.0)- hintField?.isHidden = !showTabHint- if showTabHint {- hintField?.stringValue = tabHint- }-- panel?.setFrame(NSRect(x: originX, y: originYCocoa, width: panelWidth, height: panelHeight), display: true)- panel?.contentView?.frame = NSRect(x: 0, y: 0, width: panelWidth, height: panelHeight)- textField?.frame = NSRect(x: 8, y: 5, width: panelWidth - (showTabHint ? 62 : 16), height: 18)- hintField?.frame = NSRect(x: panelWidth - 54, y: 5, width: 48, height: 18)- textField?.stringValue = text- panel?.orderFrontRegardless()-- hideWorkItem?.cancel()- let work = DispatchWorkItem { [weak self] in- self?.hide()- }- hideWorkItem = work- DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(max(120, ttlMs)), execute: work)- }-- func hide() {- panel?.orderOut(nil)- }-}--// MARK: - Main Entry Point--let app = NSApplication.shared-app.setActivationPolicy(.accessory)-let controller = OverlayController()--DispatchQueue.global(qos: .userInitiated).async {- while let line = readLine() {- guard let data = line.data(using: .utf8),- let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let kind = payload["type"] as? String else {- continue- }- let id = payload["id"] as? String-- switch kind {- case "focus":- let response = queryFocusedElement(id: id)- writeResponse(response)-- case "paste":- let text = (payload["text"] as? String) ?? ""- let response = pasteText(id: id, text: text)- writeResponse(response)-- case "ax_list":- let appName = (payload["app_name"] as? String) ?? ""- writeResponse(axListElements(appName: appName, id: id))-- case "ax_press":- let appName = (payload["app_name"] as? String) ?? ""- let label = (payload["label"] as? String) ?? ""- writeResponse(axPress(appName: appName, label: label, id: id))-- case "ax_set_value":- let appName = (payload["app_name"] as? String) ?? ""- let label = (payload["label"] as? String) ?? ""- let value = (payload["value"] as? String) ?? ""- writeResponse(axSetValue(appName: appName, label: label, value: value, id: id))-- case "show":- let x = CGFloat((payload["x"] as? NSNumber)?.doubleValue ?? 0)- let y = CGFloat((payload["y"] as? NSNumber)?.doubleValue ?? 0)- let w = CGFloat((payload["w"] as? NSNumber)?.doubleValue ?? 0)- let h = CGFloat((payload["h"] as? NSNumber)?.doubleValue ?? 0)- let text = (payload["text"] as? String) ?? ""- let ttl = (payload["ttl_ms"] as? NSNumber)?.intValue ?? 900- let tabHint: String = {- if let s = payload["tab_hint"] as? String { return s }- return "Tab ↵"- }()- DispatchQueue.main.async {- controller.show(x: x, yTop: y, width: w, height: h, text: text, ttlMs: ttl, tabHint: tabHint)- }-- case "hide":- DispatchQueue.main.async {- controller.hide()- }-- case "quit":- DispatchQueue.main.async {- controller.hide()- NSApplication.shared.terminate(nil)- }- return-- default:- break- }- }-}--app.run()-"##;diff --git a/crates/openhuman-core/src/desktop/accessibility/helper/swift_paste.rs b/crates/openhuman-core/src/desktop/accessibility/helper/swift_paste.rsdeleted file mode 100644index 8e3b3a4284..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/helper/swift_paste.rs+++ /dev/null@@ -1,44 +0,0 @@-//! Embedded Swift source fragment: the clipboard-based paste helper (`pasteText`).-#[cfg(target_os = "macos")]-pub(super) const SWIFT_PASTE: &str = r##"// MARK: - Paste Helper--func pasteText(id: String?, text: String) -> [String: Any] {- var result: [String: Any] = ["type": "paste", "ok": true, "error": NSNull()]- if let id = id { result["id"] = id }-- let pb = NSPasteboard.general- let originalContents = pb.string(forType: .string)-- // Set clipboard to new text- pb.clearContents()- pb.setString(text, forType: .string)-- // Brief delay for clipboard to settle- usleep(10_000) // 10ms-- // Simulate Cmd+V via CGEvent- guard let keyDown = CGEvent(keyboardEventSource: nil, virtualKey: 0x09, keyDown: true),- let keyUp = CGEvent(keyboardEventSource: nil, virtualKey: 0x09, keyDown: false) else {- result["ok"] = false- result["error"] = "failed to create CGEvent"- return result- }- keyDown.flags = .maskCommand- keyUp.flags = .maskCommand- keyDown.post(tap: .cgSessionEventTap)- usleep(8_000) // 8ms between key down/up- keyUp.post(tap: .cgSessionEventTap)-- // Restore clipboard after delay- if let original = originalContents {- DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + .milliseconds(250)) {- let pb = NSPasteboard.general- pb.clearContents()- pb.setString(original, forType: .string)- }- }-- return result-}--"##;diff --git a/crates/openhuman-core/src/desktop/accessibility/helper/swift_source.rs b/crates/openhuman-core/src/desktop/accessibility/helper/swift_source.rsdeleted file mode 100644index a21fdb576d..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/helper/swift_source.rs+++ /dev/null@@ -1,19 +0,0 @@-//! Assembles the embedded Swift source for the unified helper process from-//! its per-responsibility fragments (focus query, paste, AX actions, overlay-//! and main loop). Splitting the fragments keeps each one reviewable; the-//! compiled Swift program is unaffected — this just concatenates them back-//! into one source string for `swiftc`.--#[cfg(target_os = "macos")]-use super::swift_ax_actions::SWIFT_AX_ACTIONS;-#[cfg(target_os = "macos")]-use super::swift_focus::SWIFT_HEADER_AND_FOCUS;-#[cfg(target_os = "macos")]-use super::swift_overlay::SWIFT_OVERLAY_AND_MAIN;-#[cfg(target_os = "macos")]-use super::swift_paste::SWIFT_PASTE;--#[cfg(target_os = "macos")]-pub(super) fn unified_swift_source() -> String {- format!("{SWIFT_HEADER_AND_FOCUS}{SWIFT_PASTE}{SWIFT_AX_ACTIONS}{SWIFT_OVERLAY_AND_MAIN}")-}diff --git a/crates/openhuman-core/src/desktop/accessibility/mod.rs b/crates/openhuman-core/src/desktop/accessibility/mod.rsdeleted file mode 100644index 09ea5c89c1..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/mod.rs+++ /dev/null@@ -1,40 +0,0 @@-//! Platform accessibility middleware: focus queries and permission management.-//!-//! Centralises macOS AX/IOKit FFI and the unified Swift helper process.-//! Voice services call into this module instead of owning platform-specific-//! code directly.--mod automation_state;-mod focus;-mod globe;-mod helper;-mod permissions;-mod terminal;-mod text_util;-mod types;--pub use automation_state::{- clear as clear_automation_denial, mark_system_events_denied, system_events_denied,-};-pub use focus::{focused_text_context, focused_text_context_verbose, validate_focused_target};-pub use globe::{- globe_listener_poll, globe_listener_start, globe_listener_stop, GlobeHotkeyPollResult,- GlobeHotkeyStatus,-};-pub use helper::precompile_helper_background;-#[cfg(target_os = "macos")]-pub use permissions::{- detect_accessibility_permission, detect_input_monitoring_permission, open_macos_privacy_pane,- request_accessibility_access,-};-pub use permissions::{- detect_microphone_permission, detect_permissions, microphone_denied_message, permission_to_str,- request_microphone_access,-};-pub use terminal::{- extract_terminal_input_context, is_terminal_app, is_text_role, looks_like_terminal_buffer,-};-pub use text_util::{normalize_ax_value, parse_ax_number, truncate_tail};-pub use types::{- ElementBounds, FocusedTextContext, PermissionKind, PermissionState, PermissionStatus,-};diff --git a/crates/openhuman-core/src/desktop/accessibility/permissions.rs b/crates/openhuman-core/src/desktop/accessibility/permissions.rsdeleted file mode 100644index 156629c63a..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/permissions.rs+++ /dev/null@@ -1,266 +0,0 @@-//! Platform permission detection and requests for accessibility, input monitoring, and microphone access.--use super::types::{PermissionKind, PermissionState, PermissionStatus};--#[cfg(target_os = "macos")]-use std::ffi::c_void;--#[cfg(target_os = "macos")]-type CFAllocatorRef = *const c_void;-#[cfg(target_os = "macos")]-type CFDictionaryRef = *const c_void;-#[cfg(target_os = "macos")]-type CFBooleanRef = *const c_void;-#[cfg(target_os = "macos")]-type CFStringRef = *const c_void;--#[cfg(target_os = "macos")]-#[link(name = "ApplicationServices", kind = "framework")]-extern "C" {- fn AXIsProcessTrusted() -> bool;- fn AXIsProcessTrustedWithOptions(options: CFDictionaryRef) -> bool;- static kAXTrustedCheckOptionPrompt: CFStringRef;-}--#[cfg(target_os = "macos")]-#[link(name = "CoreFoundation", kind = "framework")]-extern "C" {- static kCFAllocatorDefault: CFAllocatorRef;- static kCFBooleanTrue: CFBooleanRef;- fn CFDictionaryCreate(- allocator: CFAllocatorRef,- keys: *const *const c_void,- values: *const *const c_void,- num_values: isize,- key_callbacks: *const c_void,- value_callbacks: *const c_void,- ) -> CFDictionaryRef;- fn CFRelease(cf: *const c_void);-}--#[cfg(target_os = "macos")]-#[link(name = "IOKit", kind = "framework")]-extern "C" {- fn IOHIDCheckAccess(request_type: i32) -> isize;-}--#[cfg(target_os = "macos")]-const IOHID_REQUEST_TYPE_LISTEN_EVENT: i32 = 1;-#[cfg(target_os = "macos")]-const IOHID_ACCESS_GRANTED: isize = 0;-#[cfg(target_os = "macos")]-const IOHID_ACCESS_DENIED: isize = 1;-#[cfg(target_os = "macos")]-const IOHID_ACCESS_UNKNOWN: isize = 2;--pub fn permission_to_str(permission: PermissionKind) -> &'static str {- match permission {- PermissionKind::Accessibility => "accessibility",- PermissionKind::InputMonitoring => "input_monitoring",- PermissionKind::Microphone => "microphone",- }-}--#[cfg(target_os = "macos")]-pub fn open_macos_privacy_pane(pane: &str) {- let url = format!("x-apple.systempreferences:com.apple.preference.security?{pane}");- let _ = std::process::Command::new("open").arg(url).status();-}--#[cfg(target_os = "macos")]-pub fn request_accessibility_access() {- unsafe {- let keys = [kAXTrustedCheckOptionPrompt];- let values = [kCFBooleanTrue];- let options = CFDictionaryCreate(- kCFAllocatorDefault,- keys.as_ptr(),- values.as_ptr(),- 1,- std::ptr::null(),- std::ptr::null(),- );- let _ = AXIsProcessTrustedWithOptions(options);- if !options.is_null() {- CFRelease(options);- }- }-}--#[cfg(target_os = "macos")]-pub fn detect_accessibility_permission() -> PermissionState {- unsafe {- if AXIsProcessTrusted() {- PermissionState::Granted- } else {- PermissionState::Denied- }- }-}--#[cfg(target_os = "macos")]-pub fn detect_input_monitoring_permission() -> PermissionState {- let access = unsafe { IOHIDCheckAccess(IOHID_REQUEST_TYPE_LISTEN_EVENT) };- match access {- IOHID_ACCESS_GRANTED => PermissionState::Granted,- IOHID_ACCESS_DENIED => PermissionState::Denied,- IOHID_ACCESS_UNKNOWN => PermissionState::Unknown,- _ => PermissionState::Unknown,- }-}--// ----------------------------------------------------------------------------// Microphone permission — cross-platform-// -----------------------------------------------------------------------------/// Detect whether the app has microphone permission.-///-/// Uses CPAL device probing as a cross-platform permission proxy:-/// - If `default_input_device()` returns a device, access is available.-/// - If it returns `None`, either permission is denied or no mic is connected.-///-/// On **macOS** under hardened runtime, CPAL will fail to enumerate input-/// devices when the `com.apple.security.device.audio-input` entitlement is-/// missing or microphone permission is denied in System Settings.-///-/// On **Windows**, `None` may indicate a privacy toggle denial or no hardware.-///-/// **Linux** standard desktops don't enforce per-app permissions; Flatpak/Snap-/// sandboxes are detected separately.-#[cfg(all(feature = "inference", any(target_os = "macos", target_os = "windows")))]-pub fn detect_microphone_permission() -> PermissionState {- use cpal::traits::HostTrait;- let host = cpal::default_host();- match host.default_input_device() {- Some(device) => {- let name =- cpal::traits::DeviceTrait::name(&device).unwrap_or_else(|_| "<unknown>".into());- log::debug!("[permissions] microphone access available — device: {name}");- PermissionState::Granted- }- None => {- log::debug!(- "[permissions] no default input device — possible permission denial or no mic connected"- );- PermissionState::Unknown- }- }-}--#[cfg(all(feature = "inference", target_os = "linux"))]-pub fn detect_microphone_permission() -> PermissionState {- // Standard Linux desktops (PulseAudio/PipeWire) don't enforce app-level mic permissions.- // Detect Flatpak sandbox — if sandboxed, probe CPAL as a permission proxy.- if std::env::var("FLATPAK_ID").is_ok() || std::path::Path::new("/run/flatpak").exists() {- use cpal::traits::HostTrait;- let host = cpal::default_host();- match host.default_input_device() {- Some(_) => PermissionState::Granted,- None => {- log::debug!(- "[permissions] Linux (Flatpak): no default input device — possible sandbox restriction"- );- PermissionState::Denied- }- }- } else {- PermissionState::Granted- }-}--/// With the `inference` feature off, `cpal` is not compiled in, so there is no-/// audio-device API to probe and the microphone cannot be inspected. Report-/// `Unknown` on otherwise-supported desktop platforms rather than a misleading-/// `Granted`/`Denied`.-#[cfg(all(- not(feature = "inference"),- any(target_os = "macos", target_os = "windows", target_os = "linux")-))]-pub fn detect_microphone_permission() -> PermissionState {- log::debug!(- "[permissions] microphone probe unavailable (built without the `inference` feature)"- );- PermissionState::Unknown-}--#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]-pub fn detect_microphone_permission() -> PermissionState {- PermissionState::Unsupported-}--/// Request microphone access from the operating system.-///-/// - **macOS**: Triggers the system permission prompt if status is `NotDetermined`.-/// Note: `AVCaptureDevice.requestAccess(for:)` is async in ObjC but we call the-/// synchronous authorization check — the system prompt is triggered by the check itself-/// when entitlements + usage description are present. Alternatively, opening the-/// Privacy pane guides the user.-/// - **Windows**: Opens the Privacy > Microphone settings page.-/// - **Linux**: No-op for standard installs; guidance for Flatpak in error messages.-#[cfg(target_os = "macos")]-pub fn request_microphone_access() {- log::debug!("[permissions] requesting macOS microphone access via Privacy pane");- open_macos_privacy_pane("Privacy_Microphone");-}--#[cfg(target_os = "windows")]-pub fn request_microphone_access() {- log::debug!("[permissions] opening Windows Privacy > Microphone settings");- let _ = std::process::Command::new("cmd")- .args(["/C", "start", "ms-settings:privacy-microphone"])- .status();-}--#[cfg(target_os = "linux")]-pub fn request_microphone_access() {- log::debug!("[permissions] Linux: no programmatic mic permission request available");- // No-op — standard Linux desktops don't have an app-level permission gate.- // For Flatpak, the XDG Portal API (ashpd crate) could be used in the future.-}--#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]-pub fn request_microphone_access() {- // Unsupported platform — no-op.-}--#[cfg(test)]-#[path = "permissions_tests.rs"]-mod tests;--/// Returns a platform-specific user-facing message when microphone permission is denied.-pub fn microphone_denied_message() -> String {- #[cfg(target_os = "macos")]- {- "Microphone permission denied. Grant access in System Settings > Privacy & Security > Microphone, then restart the app.".to_string()- }- #[cfg(target_os = "windows")]- {- "Microphone access unavailable. Check Settings > Privacy & Security > Microphone and ensure the app is allowed. If no microphone is connected, plug one in.".to_string()- }- #[cfg(target_os = "linux")]- {- "No microphone device available. Check your audio settings and ensure a microphone is connected. If running in a Flatpak sandbox, grant microphone access via Flatseal or system settings.".to_string()- }- #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]- {- "Microphone access is not supported on this platform.".to_string()- }-}--#[cfg(target_os = "macos")]-pub fn detect_permissions() -> PermissionStatus {- PermissionStatus {- accessibility: detect_accessibility_permission(),- input_monitoring: detect_input_monitoring_permission(),- microphone: detect_microphone_permission(),- }-}--#[cfg(not(target_os = "macos"))]-pub fn detect_permissions() -> PermissionStatus {- PermissionStatus {- accessibility: PermissionState::Unsupported,- input_monitoring: PermissionState::Unsupported,- microphone: detect_microphone_permission(),- }-}diff --git a/crates/openhuman-core/src/desktop/accessibility/permissions_tests.rs b/crates/openhuman-core/src/desktop/accessibility/permissions_tests.rsdeleted file mode 100644index 753a3206ae..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/permissions_tests.rs+++ /dev/null@@ -1,284 +0,0 @@-//! Unit tests for `accessibility::permissions`.-//!-//! macOS-only FFI functions (`detect_accessibility_permission`,-//! `detect_input_monitoring_permission`,-//! `request_*`) call into Apple frameworks and cannot be exercised in a-//! cross-platform test binary without hardware. Tests here cover:-//!-//! - `permission_to_str` — pure logic, always available.-//! - `microphone_denied_message` — pure logic, always available.-//! - `detect_permissions` — non-macOS fallback (unsupported states).-//! - `detect_microphone_permission` — cross-platform probe guard.--use super::*;--// ── permission_to_str ─────────────────────────────────────────────────────--#[test]-fn permission_to_str_accessibility() {- assert_eq!(- permission_to_str(PermissionKind::Accessibility),- "accessibility"- );-}--#[test]-fn permission_to_str_input_monitoring() {- assert_eq!(- permission_to_str(PermissionKind::InputMonitoring),- "input_monitoring"- );-}--#[test]-fn permission_to_str_microphone() {- assert_eq!(permission_to_str(PermissionKind::Microphone), "microphone");-}--#[test]-fn permission_to_str_is_snake_case_and_nonempty() {- for kind in [- PermissionKind::Accessibility,- PermissionKind::InputMonitoring,- PermissionKind::Microphone,- ] {- let s = permission_to_str(kind);- assert!(- !s.is_empty(),- "permission_to_str should never return empty string"- );- // Convention: snake_case, no spaces- assert!(- !s.contains(' '),- "permission string should not contain spaces: {s}"- );- assert_eq!(- s,- s.to_ascii_lowercase(),- "permission string should be lowercase: {s}"- );- }-}--// ── microphone_denied_message ─────────────────────────────────────────────--#[test]-fn microphone_denied_message_is_nonempty() {- let msg = microphone_denied_message();- assert!(!msg.is_empty(), "denied message should not be empty");-}--#[test]-fn microphone_denied_message_is_human_readable() {- let msg = microphone_denied_message().to_ascii_lowercase();- // All platform messages mention "microphone" as a cue to the user.- assert!(- msg.contains("microphone"),- "denied message should mention 'microphone': {msg}"- );-}--// ── detect_permissions (non-macOS path) ──────────────────────────────────--/// On non-macOS platforms `detect_permissions` reports accessibility and-/// input_monitoring as `Unsupported`. Microphone gets a-/// real check via CPAL.-#[cfg(not(target_os = "macos"))]-#[test]-fn detect_permissions_non_macos_reports_unsupported_for_desktop_perms() {- let status = detect_permissions();- assert_eq!(- status.accessibility,- PermissionState::Unsupported,- "accessibility should be Unsupported on non-macOS"- );- assert_eq!(- status.input_monitoring,- PermissionState::Unsupported,- "input_monitoring should be Unsupported on non-macOS"- );-}--/// Microphone permission on non-macOS/non-Windows platforms should be-/// `Granted` (standard Linux desktop) or `Unknown`/`Denied` (Flatpak). It-/// should never be `Unsupported` unless the platform has a dedicated stub.-#[cfg(target_os = "linux")]-#[test]-fn detect_microphone_permission_linux_returns_valid_state() {- let state = detect_microphone_permission();- assert!(- !matches!(state, PermissionState::Unsupported),- "Linux microphone state should not be Unsupported"- );-}--// ── PermissionState serde round-trip ─────────────────────────────────────--#[test]-fn permission_state_serde_round_trip() {- use crate::desktop::accessibility::types::{PermissionState, PermissionStatus};-- let status = PermissionStatus {- accessibility: PermissionState::Denied,- input_monitoring: PermissionState::Unknown,- microphone: PermissionState::Unsupported,- };- let json = serde_json::to_string(&status).expect("serialize PermissionStatus");- let back: PermissionStatus = serde_json::from_str(&json).expect("deserialize PermissionStatus");- assert_eq!(back.accessibility, PermissionState::Denied);- assert_eq!(back.input_monitoring, PermissionState::Unknown);- assert_eq!(back.microphone, PermissionState::Unsupported);-}--/// Partial permission state must survive as three independent fields on the-/// wire, spelled exactly as the renderer reads them (matrix 2.2.4).-///-/// `permission_state_serde_round_trip` above proves Rust -> JSON -> Rust, which-/// passes even if the keys were `a`/`b`/`c` and the variants `V1`/`V2`: both-/// sides of that round trip use the same `derive`. Nothing pinned the *wire-/// spelling*, and the renderer does not go through `serde` — it indexes the-/// JSON by name. A `rename_all` change or a renamed field would leave every-/// lookup `undefined`, which renders as "not granted" indefinitely and looks-/// exactly like a permission the user never gave.-///-/// The three states here are deliberately all different: a status that-/// collapsed to one verdict, or grew a fourth field, fails the shape check-/// rather than silently reporting the first field for all three.-#[test]-fn partial_permission_status_serializes_three_distinct_snake_case_fields() {- use crate::desktop::accessibility::types::{PermissionState, PermissionStatus};-- let status = PermissionStatus {- accessibility: PermissionState::Granted,- input_monitoring: PermissionState::Denied,- microphone: PermissionState::Unsupported,- };-- let json = serde_json::to_value(&status).expect("serialize PermissionStatus");- let object = json- .as_object()- .expect("PermissionStatus must serialize to a JSON object");-- assert_eq!(- object.len(),- 3,- "PermissionStatus gained or lost a field; the renderer reads exactly \- accessibility/input_monitoring/microphone: {json}"- );- assert_eq!(- object.get("accessibility").and_then(|v| v.as_str()),- Some("granted"),- "accessibility must serialize as snake_case `granted`: {json}"- );- assert_eq!(- object.get("input_monitoring").and_then(|v| v.as_str()),- Some("denied"),- "input_monitoring must keep its own value, not the accessibility one: {json}"- );- assert_eq!(- object.get("microphone").and_then(|v| v.as_str()),- Some("unsupported"),- "microphone must keep its own value: {json}"- );-}--/// `Unsupported` is not `Granted`, and a caller cannot get away with treating-/// "not denied" as "granted" (matrix 2.2.4).-///-/// On a non-macOS build `detect_permissions` reports accessibility and-/// input_monitoring as `Unsupported` while microphone is a real CPAL probe, so-/// the struct is genuinely mixed-provenance in production. Any consumer that-/// reduces it to one boolean is wrong on at least one field; this pins the-/// three-way distinction the reduction would erase.-#[test]-fn unsupported_is_distinguishable_from_granted_and_denied() {- use crate::desktop::accessibility::types::PermissionState;-- let states = [- PermissionState::Granted,- PermissionState::Denied,- PermissionState::Unknown,- PermissionState::Unsupported,- ];-- let wire: Vec<String> = states- .iter()- .map(|state| {- serde_json::to_value(state)- .expect("serialize PermissionState")- .as_str()- .expect("PermissionState serializes to a string")- .to_string()- })- .collect();-- assert_eq!(- wire,- vec!["granted", "denied", "unknown", "unsupported"],- "PermissionState wire spelling changed; the renderer compares these \- strings literally"- );-- let mut unique = wire.clone();- unique.sort();- unique.dedup();- assert_eq!(- unique.len(),- states.len(),- "two PermissionState variants collapsed to the same wire value, so a \- partial permission state cannot be told apart: {wire:?}"- );-}--// ── No stale denied cache across restart (automation_state) ───────────────-//-// The `automation_state` module exposes a process-local atomic flag. The-// "no stale denied cache across restart" guarantee is enforced by the fact-// that the flag is `AtomicBool` initialized to `false` — each new process-// starts clean. The tests below verify the clean-start invariant at the-// module level and that `clear()` restores the initial state, which is the-// mechanism used by `autocomplete::start_if_enabled` on re-engagement.--mod automation_state_stale_cache {- use crate::desktop::accessibility::automation_state;- use crate::desktop::accessibility::{- clear_automation_denial, mark_system_events_denied, system_events_denied,- };-- #[test]- fn fresh_state_is_not_denied() {- let _g = automation_state::test_lock();- clear_automation_denial();- assert!(- !system_events_denied(),- "after clear(), system_events_denied should be false (simulates process restart)"- );- }-- #[test]- fn clear_resets_denial_flag() {- let _g = automation_state::test_lock();- clear_automation_denial();- mark_system_events_denied();- assert!(system_events_denied(), "should be denied after mark");- clear_automation_denial();- assert!(- !system_events_denied(),- "clear() should erase the stale denied state"- );- }-- #[test]- fn denied_flag_does_not_persist_through_clear() {- let _g = automation_state::test_lock();- // Simulate: previous session left the flag set.- // clear() is called on re-engagement → no stale state carried over.- mark_system_events_denied();- clear_automation_denial();- // Re-query after clear — must be false, simulating a "fresh sidecar" read.- assert!(- !system_events_denied(),- "denial flag must not persist after clear() — no stale cache"- );- }-}diff --git a/crates/openhuman-core/src/desktop/accessibility/terminal.rs b/crates/openhuman-core/src/desktop/accessibility/terminal.rsdeleted file mode 100644index 1a05e4361e..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/terminal.rs+++ /dev/null@@ -1,86 +0,0 @@-//! Terminal app detection and context extraction.--/// Known terminal application name substrings (lowercase).-/// Extend this list to support additional terminal emulators.-pub const TERMINAL_NAMES: &[&str] = &[- "terminal",- "iterm",- "wezterm",- "warp",- "alacritty",- "kitty",- "ghostty",- "hyper",- "rio",- "tabby",- "wave",- "contour",- "foot",-];--pub fn is_text_role(role: Option<&str>) -> bool {- matches!(- role.unwrap_or_default(),- "AXTextArea" | "AXTextField" | "AXSearchField" | "AXComboBox" | "AXEditableText"- )-}--pub fn is_terminal_app(app_name: Option<&str>) -> bool {- let app = app_name.unwrap_or_default().to_ascii_lowercase();- TERMINAL_NAMES.iter().any(|needle| app.contains(needle))-}--pub fn looks_like_terminal_buffer(text: &str) -> bool {- let lower = text.to_ascii_lowercase();- let line_count = text.lines().count();- line_count >= 5- && (lower.contains("$ ")- || lower.contains("# ")- || lower.contains("❯")- || lower.contains("[1] 0:")- || lower.contains("tmux")- || lower.contains("cargo run")- || lower.contains("git status"))-}--fn is_terminal_noise_line(line: &str) -> bool {- let trimmed = line.trim();- if trimmed.is_empty() {- return true;- }- trimmed.starts_with('•')- || trimmed.starts_with('└')- || trimmed.starts_with('─')- || trimmed.starts_with('│')- || (trimmed.starts_with('[')- && (trimmed.contains(" 0:") || trimmed.contains("[tmux]") || trimmed.contains("\"⠙")))-}--pub fn extract_terminal_input_context(text: &str) -> String {- let mut fallback = String::new();- for raw_line in text.lines().rev().take(40) {- let line = raw_line.trim();- if line.is_empty() {- continue;- }- if fallback.is_empty() && !is_terminal_noise_line(line) {- fallback = line.to_string();- }- if is_terminal_noise_line(line) {- continue;- }- if line.contains("$ ")- || line.contains("# ")- || line.contains("❯")- || line.contains("➜")- || line.contains("λ")- {- return line.to_string();- }- }- fallback-}--#[cfg(test)]-#[path = "terminal_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/desktop/accessibility/terminal_tests.rs b/crates/openhuman-core/src/desktop/accessibility/terminal_tests.rsdeleted file mode 100644index a4ec4e762e..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/terminal_tests.rs+++ /dev/null@@ -1,101 +0,0 @@-use super::*;--#[test]-fn is_text_role_accepts_known_roles() {- assert!(is_text_role(Some("AXTextArea")));- assert!(is_text_role(Some("AXTextField")));- assert!(is_text_role(Some("AXSearchField")));- assert!(is_text_role(Some("AXComboBox")));- assert!(is_text_role(Some("AXEditableText")));-}--#[test]-fn is_text_role_rejects_other_roles() {- assert!(!is_text_role(Some("AXButton")));- assert!(!is_text_role(Some("AXImage")));- assert!(!is_text_role(None));- assert!(!is_text_role(Some("")));-}--#[test]-fn is_terminal_app_detects_known_terminals() {- assert!(is_terminal_app(Some("iTerm2")));- assert!(is_terminal_app(Some("Terminal")));- assert!(is_terminal_app(Some("WezTerm")));- assert!(is_terminal_app(Some("Alacritty")));- assert!(is_terminal_app(Some("kitty")));- assert!(is_terminal_app(Some("Warp")));- assert!(is_terminal_app(Some("Ghostty")));-}--#[test]-fn is_terminal_app_rejects_non_terminals() {- assert!(!is_terminal_app(Some("Safari")));- assert!(!is_terminal_app(Some("Slack")));- assert!(!is_terminal_app(None));- assert!(!is_terminal_app(Some("")));-}--#[test]-fn looks_like_terminal_buffer_detects_shell_prompts() {- let buffer = "line1\nline2\nline3\nline4\n$ cargo build\nCompiling...\n";- assert!(looks_like_terminal_buffer(buffer));-}--#[test]-fn looks_like_terminal_buffer_rejects_short_text() {- assert!(!looks_like_terminal_buffer("hello"));- assert!(!looks_like_terminal_buffer("$ cmd"));-}--#[test]-fn looks_like_terminal_buffer_detects_git_status() {- let buffer = "line1\nline2\nline3\nline4\ngit status\nOn branch main\n";- assert!(looks_like_terminal_buffer(buffer));-}--#[test]-fn extract_terminal_input_context_finds_prompt_line() {- let text = "old output\n$ ls -la\ntotal 42\nfile1.txt\nfile2.txt\n";- let ctx = extract_terminal_input_context(text);- assert!(ctx.contains("$ ls"), "expected prompt line, got: {ctx}");-}--#[test]-fn extract_terminal_input_context_skips_noise() {- let text = "actual content\n• bullet point\n└── tree branch\n│ pipe\n";- let ctx = extract_terminal_input_context(text);- assert_eq!(ctx, "actual content");-}--#[test]-fn extract_terminal_input_context_empty_returns_empty() {- assert!(extract_terminal_input_context("").is_empty());-}--#[test]-fn extract_terminal_input_context_all_noise_returns_empty() {- let text = "\n\n\n";- assert!(extract_terminal_input_context(text).is_empty());-}--#[test]-fn terminal_names_is_nonempty() {- assert!(!TERMINAL_NAMES.is_empty());-}--#[test]-fn is_terminal_noise_line_detects_noise() {- assert!(is_terminal_noise_line(""));- assert!(is_terminal_noise_line(" "));- assert!(is_terminal_noise_line("• item"));- assert!(is_terminal_noise_line("└── branch"));- assert!(is_terminal_noise_line("─────"));- assert!(is_terminal_noise_line("│ pipe"));-}--#[test]-fn is_terminal_noise_line_passes_normal_text() {- assert!(!is_terminal_noise_line("hello world"));- assert!(!is_terminal_noise_line("$ command"));-}diff --git a/crates/openhuman-core/src/desktop/accessibility/text_util.rs b/crates/openhuman-core/src/desktop/accessibility/text_util.rsdeleted file mode 100644index ce318168dd..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/text_util.rs+++ /dev/null@@ -1,40 +0,0 @@-//! Shared text utilities for accessibility value parsing.--pub fn truncate_tail(text: &str, max_chars: usize) -> String {- let chars: Vec<char> = text.chars().collect();- if chars.len() <= max_chars {- return text.to_string();- }- chars[chars.len() - max_chars..].iter().collect()-}--pub fn normalize_ax_value(raw: &str) -> String {- let v = raw.trim();- if v.eq_ignore_ascii_case("missing value") {- String::new()- } else {- v.to_string()- }-}--pub fn parse_ax_number(raw: &str) -> Option<i32> {- let trimmed = normalize_ax_value(raw);- if trimmed.is_empty() {- return None;- }- let cleaned = trimmed.replace(',', ".");- cleaned.parse::<f64>().ok().and_then(|v| {- if !v.is_finite() {- return None;- }- let rounded = v.round();- if rounded < i32::MIN as f64 || rounded > i32::MAX as f64 {- return None;- }- Some(rounded as i32)- })-}--#[cfg(test)]-#[path = "text_util_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/desktop/accessibility/text_util_tests.rs b/crates/openhuman-core/src/desktop/accessibility/text_util_tests.rsdeleted file mode 100644index 326f382313..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/text_util_tests.rs+++ /dev/null@@ -1,142 +0,0 @@-use super::*;--// --- truncate_tail -----#[test]-fn truncate_tail_shorter_than_max_returns_original() {- assert_eq!(truncate_tail("hello", 10), "hello");-}--#[test]-fn truncate_tail_exactly_max_returns_original() {- assert_eq!(truncate_tail("hello", 5), "hello");-}--#[test]-fn truncate_tail_longer_than_max_returns_tail() {- assert_eq!(truncate_tail("hello", 3), "llo");-}--#[test]-fn truncate_tail_empty_string() {- assert_eq!(truncate_tail("", 5), "");-}--#[test]-fn truncate_tail_zero_max_returns_empty() {- assert_eq!(truncate_tail("hello", 0), "");-}--#[test]-fn truncate_tail_multibyte_chars_counts_chars_not_bytes() {- // "héllo" is 5 chars; last 3 = "llo"- assert_eq!(truncate_tail("héllo", 3), "llo");-}--#[test]-fn truncate_tail_unicode_emoji_counts_codepoints() {- // "ab🎉cd" — 5 codepoints; last 3 = "🎉cd"- assert_eq!(truncate_tail("ab🎉cd", 3), "🎉cd");-}--// --- normalize_ax_value -----#[test]-fn normalize_ax_value_trims_whitespace() {- assert_eq!(normalize_ax_value(" hello "), "hello");-}--#[test]-fn normalize_ax_value_missing_value_lowercase_returns_empty() {- assert_eq!(normalize_ax_value("missing value"), "");-}--#[test]-fn normalize_ax_value_missing_value_uppercase_returns_empty() {- assert_eq!(normalize_ax_value("MISSING VALUE"), "");-}--#[test]-fn normalize_ax_value_mixed_case_missing_value_returns_empty() {- assert_eq!(normalize_ax_value("Missing Value"), "");-}--#[test]-fn normalize_ax_value_empty_string_returns_empty() {- assert_eq!(normalize_ax_value(""), "");-}--#[test]-fn normalize_ax_value_only_whitespace_returns_empty() {- assert_eq!(normalize_ax_value(" "), "");-}--#[test]-fn normalize_ax_value_regular_text_unchanged() {- assert_eq!(normalize_ax_value("some value"), "some value");-}--// --- parse_ax_number -----#[test]-fn parse_ax_number_integer_string() {- assert_eq!(parse_ax_number("42"), Some(42));-}--#[test]-fn parse_ax_number_negative_integer() {- assert_eq!(parse_ax_number("-7"), Some(-7));-}--#[test]-fn parse_ax_number_float_rounds_to_nearest() {- assert_eq!(parse_ax_number("42.4"), Some(42));- assert_eq!(parse_ax_number("42.6"), Some(43));-}--#[test]-fn parse_ax_number_comma_treated_as_decimal_separator() {- // Locale-style: "1,5" → 1.5 → rounds to 2- assert_eq!(parse_ax_number("1,5"), Some(2));-}--#[test]-fn parse_ax_number_missing_value_returns_none() {- assert_eq!(parse_ax_number("missing value"), None);-}--#[test]-fn parse_ax_number_empty_returns_none() {- assert_eq!(parse_ax_number(""), None);-}--#[test]-fn parse_ax_number_whitespace_only_returns_none() {- assert_eq!(parse_ax_number(" "), None);-}--#[test]-fn parse_ax_number_non_numeric_returns_none() {- assert_eq!(parse_ax_number("abc"), None);-}--#[test]-fn parse_ax_number_nan_returns_none() {- assert_eq!(parse_ax_number("NaN"), None);-}--#[test]-fn parse_ax_number_infinity_returns_none() {- assert_eq!(parse_ax_number("inf"), None);- assert_eq!(parse_ax_number("infinity"), None);-}--#[test]-fn parse_ax_number_zero() {- assert_eq!(parse_ax_number("0"), Some(0));-}--#[test]-fn parse_ax_number_trims_surrounding_whitespace() {- assert_eq!(parse_ax_number(" 10 "), Some(10));-}diff --git a/crates/openhuman-core/src/desktop/accessibility/types.rs b/crates/openhuman-core/src/desktop/accessibility/types.rsdeleted file mode 100644index e41b5fae5e..0000000000--- a/crates/openhuman-core/src/desktop/accessibility/types.rs+++ /dev/null@@ -1,47 +0,0 @@-//! Shared platform types for accessibility, focus, and permissions.--use serde::{Deserialize, Serialize};--/// Unified element bounds — used by autocomplete.-#[derive(Debug, Clone, Copy)]-pub struct ElementBounds {- pub x: i32,- pub y: i32,- pub width: i32,- pub height: i32,-}--/// Context returned by an accessibility focus query.-#[derive(Debug, Clone)]-pub struct FocusedTextContext {- pub app_name: Option<String>,- pub role: Option<String>,- pub text: String,- pub selected_text: Option<String>,- pub raw_error: Option<String>,- pub bounds: Option<ElementBounds>,-}--#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]-#[serde(rename_all = "snake_case")]-pub enum PermissionState {- Granted,- Denied,- Unknown,- Unsupported,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct PermissionStatus {- pub accessibility: PermissionState,- pub input_monitoring: PermissionState,- pub microphone: PermissionState,-}--#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]-#[serde(rename_all = "snake_case")]-pub enum PermissionKind {- Accessibility,- InputMonitoring,- Microphone,-}