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
fix(voice): handle composio tool visibility errors in voice pipeline
Steven Enamakelf1e7bc25c41b
diff --git a/crates/openhuman-core/src/integrations/composio/tools/visibility.rs b/crates/openhuman-core/src/integrations/composio/tools/visibility.rsindex 978a626c36..509a2cb5a2 100644--- a/crates/openhuman-core/src/integrations/composio/tools/visibility.rs+++ b/crates/openhuman-core/src/integrations/composio/tools/visibility.rs@@ -104,7 +104,7 @@ async fn evaluate_tool_visibility(config: &Config, slug: &str) -> ToolDecision {/// `toolkit_from_slug` already lowercases its result, so the comparison/// is direct against entries the caller has already lowercased.fn retain_connected_tools(- resp: &mut super::types::ComposioToolsResponse,+ resp: &mut super::super::types::ComposioToolsResponse,connected: &HashSet<String>,) -> usize {let before = resp.tools.len();@@ -160,12 +160,12 @@ fn empty_uncurated_toolkits_message(toolkits: &[String]) -> Option<String> {))}-/// Filter a freshly-fetched [`super::types::ComposioToolsResponse`] in+/// Filter a freshly-fetched [`super::super::types::ComposioToolsResponse`] in/// place: drop tools that aren't curated for their toolkit and tools/// whose scope is disabled in the user's pref.async fn filter_list_tools_response(config: &Config,- resp: &mut super::types::ComposioToolsResponse,+ resp: &mut super::super::types::ComposioToolsResponse,) {let before = resp.tools.len();// Compute keep/drop decisions sequentially (the await means we@@ -239,7 +239,7 @@ fn split_arg_names(parameters: Option<&Value>) -> (Vec<String>, Vec<String>) {/// only what the agent needs to pick a slug and call `composio_execute`:/// the slug, a one-line description, and the names of required +/// optional top-level arguments. Tools are grouped by toolkit prefix.-fn render_tools_markdown(resp: &super::types::ComposioToolsResponse) -> String {+fn render_tools_markdown(resp: &super::super::types::ComposioToolsResponse) -> String {use std::collections::BTreeMap;use std::fmt::Write as _;@@ -249,7 +249,7 @@ fn render_tools_markdown(resp: &super::types::ComposioToolsResponse) -> String {// Group by toolkit slug (lowercase prefix). Use BTreeMap for stable// ordering so the agent sees the same shape across calls.- let mut by_toolkit: BTreeMap<String, Vec<&super::types::ComposioToolSchema>> = BTreeMap::new();+ let mut by_toolkit: BTreeMap<String, Vec<&super::super::types::ComposioToolSchema>> = BTreeMap::new();for t in &resp.tools {let toolkit = toolkit_from_slug(&t.function.name).unwrap_or_else(|| "other".to_string());by_toolkit.entry(toolkit).or_default().push(t);@@ -291,7 +291,7 @@ fn render_tools_markdown(resp: &super::types::ComposioToolsResponse) -> String {}// `execute_direct` was previously defined locally here; it now lives-// in `super::client::direct_execute` so the ops.rs RPC handler and the+// in `super::super::client::direct_execute` so the ops.rs RPC handler and the// agent-tool path share a single direct-mode envelope reshaper.// See `direct_execute`'s rustdoc for the v3 → ComposioExecuteResponse// translation contract.diff --git a/crates/openhuman-core/src/voice/server/pipeline.rs b/crates/openhuman-core/src/voice/server/pipeline.rsnew file mode 100644index 0000000000..7a07507a9d--- /dev/null+++ b/crates/openhuman-core/src/voice/server/pipeline.rs@@ -0,0 +1,354 @@+//! Background recording → transcription pipeline: runs off the hotkey event+//! loop so rapid consecutive presses are never missed. Owns the gates+//! (min duration, silence, hallucination) and the initial-prompt / recent+//! transcript bookkeeping that improves STT continuity.++use std::sync::atomic::Ordering;+use std::sync::Arc;+use std::time::Instant;++use log::{debug, info, warn};+use tokio::sync::Mutex;++#[cfg(target_os = "macos")]+use crate::desktop::accessibility;+use crate::config::Config;+use crate::modules::voice::{is_hallucinated, HallucinationMode};+use crate::voice::audio_capture::RecordingHandle;+use crate::voice::text_input;++use super::types::{ServerState, VoiceServerConfig, MAX_INITIAL_PROMPT_CHARS, MAX_RECENT_TRANSCRIPTS};+use super::LOG_PREFIX;++/// Capture the frontmost app name at hotkey press so insertion can be validated later.+#[cfg(target_os = "macos")]+pub(super) fn capture_expected_app_name() -> Option<String> {+ match accessibility::focused_text_context_verbose() {+ Ok(ctx) => {+ let app = ctx+ .app_name+ .as_deref()+ .map(str::trim)+ .filter(|s| !s.is_empty());+ if let Some(app_name) = app {+ debug!("{LOG_PREFIX} captured focused app on press: '{app_name}'");+ Some(app_name.to_string())+ } else {+ debug!("{LOG_PREFIX} focus query returned no app name on press");+ None+ }+ }+ Err(e) => {+ warn!("{LOG_PREFIX} failed to capture focused app on press: {e}");+ None+ }+ }+}++#[cfg(not(target_os = "macos"))]+pub(super) fn capture_expected_app_name() -> Option<String> {+ None+}++/// Build the STT initial_prompt from custom dictionary + recent transcripts.+pub(super) async fn build_initial_prompt(+ config: &VoiceServerConfig,+ recent_transcripts: &Mutex<Vec<String>>,+) -> Option<String> {+ let mut parts: Vec<String> = Vec::new();++ if !config.custom_dictionary.is_empty() {+ parts.push(config.custom_dictionary.join(", "));+ }++ let recent = recent_transcripts.lock().await;+ if !recent.is_empty() {+ parts.push(recent.join(" "));+ }++ if parts.is_empty() {+ return None;+ }++ let mut prompt = parts.join(". ");+ if prompt.chars().count() > MAX_INITIAL_PROMPT_CHARS {+ prompt = prompt.chars().take(MAX_INITIAL_PROMPT_CHARS).collect();+ if let Some(last_space) = prompt.rfind(' ') {+ prompt.truncate(last_space);+ }+ }+ debug!(+ "{LOG_PREFIX} built initial_prompt ({} chars): '{}'",+ prompt.len(),+ truncate_for_log(&prompt, 100)+ );+ Some(prompt)+}++/// Add a transcript to the rolling recent buffer.+pub(super) async fn push_recent_transcript(recent_transcripts: &Mutex<Vec<String>>, text: &str) {+ let trimmed = text.trim();+ if trimmed.is_empty() {+ return;+ }+ let mut recent = recent_transcripts.lock().await;+ recent.push(trimmed.to_string());+ while recent.len() > MAX_RECENT_TRANSCRIPTS {+ recent.remove(0);+ }+}++/// Process a completed recording in the background.+///+/// This is a free function (not `&self`) so it can be spawned via+/// `tokio::spawn` without blocking the hotkey event loop. All shared+/// state is passed as `Arc` handles.+#[allow(clippy::too_many_arguments)]+pub(super) async fn process_recording_bg(+ pipeline_id: &str,+ handle: RecordingHandle,+ config: &Config,+ server_config: &VoiceServerConfig,+ state: Arc<Mutex<ServerState>>,+ transcription_count: Arc<std::sync::atomic::AtomicU64>,+ session_generation: Arc<std::sync::atomic::AtomicU64>,+ generation: u64,+ last_error: Arc<Mutex<Option<String>>>,+ recent_transcripts: Arc<Mutex<Vec<String>>>,+ expected_app: Option<String>,+) {+ let pipeline_started = Instant::now();+ info!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=start generation={generation}");+ update_state_if_current(+ &state,+ &session_generation,+ generation,+ ServerState::Transcribing,+ "transcribing",+ )+ .await;++ let stop_started = Instant::now();+ match handle.stop(config).await {+ Ok(result) => {+ let stop_elapsed = stop_started.elapsed();+ info!(+ "{LOG_PREFIX} [pipeline={pipeline_id}] stage=stop_recording duration={:.1}s bytes={} peak_rms={:.6} stop_elapsed_ms={}",+ result.duration_secs,+ result.wav_bytes.len(),+ result.peak_rms,+ stop_elapsed.as_millis()+ );++ // Gate 1: minimum duration.+ if result.duration_secs < server_config.min_duration_secs {+ warn!(+ "{LOG_PREFIX} [pipeline={pipeline_id}] stage=gate_duration DROPPED ({:.1}s < {:.1}s min)",+ result.duration_secs,+ server_config.min_duration_secs+ );+ update_state_if_current(+ &state,+ &session_generation,+ generation,+ ServerState::Idle,+ "idle_after_short_recording",+ )+ .await;+ return;+ }++ // Gate 2: silence detection.+ if result.peak_rms < server_config.silence_threshold {+ warn!(+ "{LOG_PREFIX} [pipeline={pipeline_id}] stage=gate_silence DROPPED (peak_rms={:.6} < threshold={:.6})",+ result.peak_rms,+ server_config.silence_threshold+ );+ update_state_if_current(+ &state,+ &session_generation,+ generation,+ ServerState::Idle,+ "idle_after_silence",+ )+ .await;+ return;+ }++ // Build initial_prompt from dictionary + recent transcripts.+ let initial_prompt = build_initial_prompt(server_config, &recent_transcripts).await;+ let context = initial_prompt+ .as_deref()+ .or(server_config.context.as_deref());+ if let Some(app) = expected_app.as_deref() {+ debug!("{LOG_PREFIX} [pipeline={pipeline_id}] insertion target: app='{app}'");+ } else {+ debug!("{LOG_PREFIX} [pipeline={pipeline_id}] insertion target unknown");+ }++ info!(+ "{LOG_PREFIX} [pipeline={pipeline_id}] stage=transcribe skip_cleanup={} context={}",+ server_config.skip_cleanup,+ context.map_or("none".to_string(), |c| format!("{}chars", c.len()))+ );++ let transcribe_started = Instant::now();+ match crate::voice::voice_transcribe_bytes(+ config,+ &result.wav_bytes,+ Some("wav".to_string()),+ context,+ server_config.skip_cleanup,+ )+ .await+ {+ Ok(outcome) => {+ let transcribe_elapsed = transcribe_started.elapsed();+ let text = &outcome.value.text;+ info!(+ "{LOG_PREFIX} [pipeline={pipeline_id}] stage=transcription_result text='{}' chars={} elapsed_ms={}",+ truncate_for_log(text, 80),+ text.len(),+ transcribe_elapsed.as_millis()+ );++ // Gate 3: filter hallucinated/blank output.+ //+ // Falls OPEN when the module cannot be reached. Dictation+ // inserts into the user's active text field, so a stray+ // "Thank you." is visible and undoable, while a filter that+ // failed closed would swallow real dictation with no trace.+ let hallucinated =+ match is_hallucinated(config, text, HallucinationMode::Dictation).await {+ Ok(verdict) => verdict,+ Err(error) => {+ warn!(+ "{LOG_PREFIX} [pipeline={pipeline_id}] stage=gate_hallucination \+ UNAVAILABLE ({error}); passing text through"+ );+ false+ }+ };+ if hallucinated {+ warn!(+ "{LOG_PREFIX} [pipeline={pipeline_id}] stage=gate_hallucination DROPPED text='{}'",+ truncate_for_log(text, 60)+ );+ update_state_if_current(+ &state,+ &session_generation,+ generation,+ ServerState::Idle,+ "idle_after_hallucination",+ )+ .await;+ return;+ }++ if !text.trim().is_empty() {+ push_recent_transcript(&recent_transcripts, text).await;++ // When the Tauri app itself is focused, deliver via+ // Socket.IO so the frontend inserts into the chat.+ // Otherwise paste via OS-level Cmd+V into the+ // external app.+ let is_self = expected_app+ .as_deref()+ .map(|app| app.to_lowercase().contains("openhuman"))+ .unwrap_or(false);++ if is_self {+ let receivers = crate::voice::dictation_listener::publish_transcription(+ text.to_string(),+ );+ transcription_count.fetch_add(1, Ordering::Relaxed);+ info!(+ "{LOG_PREFIX} [pipeline={pipeline_id}] stage=deliver_socketio receivers={receivers} total_pipeline_ms={}",+ pipeline_started.elapsed().as_millis()+ );+ } else {+ let insert_started = Instant::now();+ if let Err(e) = text_input::insert_text(text, expected_app.as_deref()) {+ warn!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=deliver_paste FAILED: {e}");+ *last_error.lock().await = Some(e);+ } else {+ let insert_elapsed = insert_started.elapsed();+ transcription_count.fetch_add(1, Ordering::Relaxed);+ info!(+ "{LOG_PREFIX} [pipeline={pipeline_id}] stage=deliver_paste insert_ms={} total_pipeline_ms={}",+ insert_elapsed.as_millis(),+ pipeline_started.elapsed().as_millis()+ );+ }+ }+ } else {+ warn!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=gate_empty DROPPED (transcription was blank)");+ }+ }+ Err(e) => {+ // Windows DLL-not-found errors are classified at the+ // subprocess layer and logged with a 5-minute backoff.+ // Demote to warn! so they don't flood Sentry (issue #5168).+ if e.contains("STATUS_DLL_NOT_FOUND") {+ warn!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=transcribe DLL_UNAVAILABLE: {e}");+ } else {+ warn!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=transcribe FAILED: {e}");+ }+ *last_error.lock().await = Some(e);+ }+ }+ }+ Err(e) => {+ warn!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=stop_recording FAILED: {e}");+ *last_error.lock().await = Some(e);+ }+ }++ info!(+ "{LOG_PREFIX} [pipeline={pipeline_id}] stage=done total_pipeline_ms={}",+ pipeline_started.elapsed().as_millis()+ );+ update_state_if_current(+ &state,+ &session_generation,+ generation,+ ServerState::Idle,+ "idle_after_processing",+ )+ .await;+}++pub(super) async fn update_state_if_current(+ state: &Arc<Mutex<ServerState>>,+ session_generation: &Arc<std::sync::atomic::AtomicU64>,+ generation: u64,+ next_state: ServerState,+ reason: &str,+) {+ let latest_generation = session_generation.load(Ordering::Relaxed);+ if latest_generation != generation {+ debug!(+ "{LOG_PREFIX} skipped stale state update reason={} generation={} latest_generation={} next_state={next_state:?}",+ reason,+ generation,+ latest_generation+ );+ return;+ }++ debug!(+ "{LOG_PREFIX} state update reason={} generation={} next_state={next_state:?}",+ reason, generation+ );+ *state.lock().await = next_state;+}++pub(super) fn truncate_for_log(s: &str, max: usize) -> String {+ let truncated: String = s.chars().take(max).collect();+ if truncated.len() < s.len() {+ format!("{truncated}...")+ } else {+ truncated+ }+}diff --git a/crates/openhuman-core/src/web_chat/web_errors/timeout.rs b/crates/openhuman-core/src/web_chat/web_errors/timeout.rsnew file mode 100644index 0000000000..52e3e9d13e--- /dev/null+++ b/crates/openhuman-core/src/web_chat/web_errors/timeout.rs@@ -0,0 +1,64 @@+//! The synthetic marker a wedged web turn raises when the wall-clock backstop+//! fires, and the predicates that recognise it (and the harness's own+//! `Timeout`) in a flattened error string.++/// Stable marker embedded in the synthetic error a web turn raises when it+/// exceeds its wall-clock backstop (`OPENHUMAN_WEB_TURN_TIMEOUT_SECS`). Kept as+/// a grep-friendly anchor so [`classify_inference_error`](super::classify::classify_inference_error)+/// routes it to the dedicated `turn_timeout` branch instead of the generic+/// catch-all.+pub(crate) const TURN_TIMEOUT_MARKER: &str = "openhuman_turn_wall_clock_timeout";++/// Build the synthetic error string a wedged web turn raises when its+/// wall-clock backstop fires. Carries [`TURN_TIMEOUT_MARKER`] so the error+/// classifier surfaces a graceful, retryable `turn_timeout` chat_error rather+/// than letting the turn hang forever with no terminal event (issue #4746).+pub(crate) fn turn_timeout_error_message(secs: u64) -> String {+ format!(+ "{TURN_TIMEOUT_MARKER}: agent turn exceeded its {secs}s wall-clock budget \+ without producing a terminal event (a tool or delegated sub-agent likely stalled)"+ )+}++/// True when `err` is a turn wall-clock timeout — either the synthetic marker+/// raised by the web turn driver's outer backstop ([`TURN_TIMEOUT_MARKER`]), or+/// the tinyagents harness's own `TinyAgentsError::Timeout` (issue #4746). The+/// harness renders that as `run timed out: <model|tool> call for run `..`+/// exceeded its remaining wall-clock budget (.. ms)` / `.. exceeded its+/// wall-clock deadline`, so both wall-clock phrasings are anchored here. This+/// routes the loop's graceful budget-exhaustion terminal event to the dedicated+/// `turn_timeout` copy instead of the generic catch-all.+pub(crate) fn is_turn_timeout_error(err: &str) -> bool {+ err.contains(TURN_TIMEOUT_MARKER)+ || err.contains("run timed out:")+ || err.contains("exceeded its remaining wall-clock budget")+ || err.contains("exceeded its wall-clock deadline")+}++/// True when `err` is the **outer** web-turn backstop firing —+/// [`TURN_TIMEOUT_MARKER`], raised by `drive_turn_with_deadline` — as opposed+/// to the harness's own `Timeout`.+///+/// The two are structurally different events and only look alike once+/// stringified, which is why they were treated alike and why one of them went+/// unnoticed for as long as it did (#5804):+///+/// * The marker is raised when the turn future produced **no terminal event at+/// all** inside the channel's ceiling. By construction nothing was completing+/// — the turn wedged outside the harness run (session assembly, persistence+/// plumbing). There is no in-flight work to report and the user already has a+/// graceful `turn_timeout`, so a Sentry event would be noise.+///+/// * The harness `Timeout` is raised while bounding a **real, in-flight model+/// or tool call** against the run's remaining wall-clock budget. Reaching it+/// means the run consumed its budget doing work, and everything that work+/// produced is discarded with the turn. That is a defect signal, and+/// suppressing it is what made the discarded-turn failure invisible.+///+/// Used only for the Sentry suppression decision. [`is_turn_timeout_error`]+/// still covers both for the *user-facing* classification, which is unchanged:+/// either way the turn ran out of time and the graceful `turn_timeout` copy is+/// the right thing to show.+pub(crate) fn is_outer_backstop_timeout(err: &str) -> bool {+ err.contains(TURN_TIMEOUT_MARKER)+}