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: files changed crates/openhuman-core/src/voice/audio_capture.rs,crates/openhuman-core/src/voic
Steven Enamakel80b1ac2b20c7
diff --git a/crates/openhuman-core/src/voice/audio_capture.rs b/crates/openhuman-core/src/voice/audio_capture.rsdeleted file mode 100644index 86a266ef13..0000000000--- a/crates/openhuman-core/src/voice/audio_capture.rs+++ /dev/null@@ -1,70 +0,0 @@-//! Host recording policy over module-owned native capture and audio preparation.-use super::capture_lease::CaptureLease;-use crate::config::Config;-/// Sample rate of the TinyVoice output contract (mono 16 kHz PCM).-pub(crate) const TARGET_SAMPLE_RATE: u32 = 16_000;-/// Prepared recording and module-computed metrics used by the STT gates.-#[derive(Debug, Clone)]-pub struct RecordingResult {- /// Prepared WAV audio.- pub wav_bytes: Vec<u8>,- /// Duration of the gated output.- pub duration_secs: f32,- /// Mono sample count after gating.- pub sample_count: usize,- /// Peak RMS measured before gating.- pub peak_rms: f32,-}-/// Opaque recording lease. Dropping it cancels capture and releases output.-pub struct RecordingHandle {- inner: Option<CaptureLease>,- #[cfg(test)]- finalized: Option<Result<RecordingResult, String>>,-}-impl RecordingHandle {- /// Stop capture, read prepared audio in bounded slices, and release it.- pub async fn stop(mut self, _config: &Config) -> Result<RecordingResult, String> {- #[cfg(test)]- if let Some(result) = self.finalized.take() {- return result;- }- let lease = self.inner.take().ok_or("recording already stopped")?;- let result = lease.finish().await;- if result.is_err() {- if let Err(error) = lease.close().await {- log::warn!("[voice_capture] recording cleanup pending: {error}");- }- }- result- }- #[cfg(test)]- pub(crate) fn from_test_result(result: Result<RecordingResult, String>) -> Self {- Self {- inner: None,- finalized: Some(result),- }- }-}-/// Obtain permission through TinyComputer before starting a TinyVoice recording.-pub async fn start_recording(config: &Config) -> Result<RecordingHandle, String> {- crate::modules::accessibility::AccessibilityClient::new(config)- .microphone_permission(true)- .await- .map_err(|e| e.to_string())?;- let lease = CaptureLease::reserve(config).await?;- lease.start_recording().await?;- Ok(RecordingHandle {- inner: Some(lease),- #[cfg(test)]- finalized: None,- })-}-/// Enumerate native input devices through the loaded module.-pub async fn list_input_devices(config: &Config) -> Result<Vec<String>, String> {- use tinyvoice_bus::{capture::CaptureResult, names::methods};- let result: CaptureResult<Vec<String>> = crate::modules::client(config.clone())- .call_confidential("tinyvoice", methods::LIST_INPUT_DEVICES, ())- .await- .map_err(|e| e.to_string())?;- result.map_err(|_| "input device enumeration failed".to_string())-}diff --git a/crates/openhuman-core/src/voice/capture_lease.rs b/crates/openhuman-core/src/voice/capture_lease.rsdeleted file mode 100644index 2cfad0e89f..0000000000--- a/crates/openhuman-core/src/voice/capture_lease.rs+++ /dev/null@@ -1,308 +0,0 @@-//! Host ownership and cancellation of opaque TinyVoice capture leases.-use super::audio_capture::{RecordingResult, TARGET_SAMPLE_RATE};-use crate::config::Config;-use base64::Engine as _;-use serde::{de::DeserializeOwned, Serialize};-use std::collections::HashMap;-use std::sync::{- atomic::{AtomicBool, AtomicU64, Ordering},- Arc, LazyLock, Mutex,-};-use tinybus::module::ModuleClient;-use tinyvoice_bus::{- capture::{- AudioOutput, CaptureError, CaptureHandle, CaptureResult, MicrophonePermission,- ReadAudioRequest, RecordingFinishRequest, RecordingStartRequest, RecordingSummary,- RecordingSummaryRequest,- },- names::methods,-};--const MODULE: &str = "tinyvoice";-const READ_BYTES: usize = 256 * 1024;-const MAX_OUTPUT_BYTES: usize = 32 * 1024 * 1024;-static RECORDING_GENERATION: AtomicU64 = AtomicU64::new(0);-static NEXT_ID: AtomicU64 = AtomicU64::new(1);-static LEASES: LazyLock<Mutex<HashMap<u64, Arc<State>>>> =- LazyLock::new(|| Mutex::new(HashMap::new()));-static HOOK: AtomicBool = AtomicBool::new(false);-#[async_trait::async_trait]-trait Port: Send + Sync {- async fn call(- &self,- member: &'static str,- args: serde_json::Value,- ) -> Result<serde_json::Value, String>;-}-struct BusPort(ModuleClient);-#[async_trait::async_trait]-impl Port for BusPort {- async fn call(- &self,- member: &'static str,- args: serde_json::Value,- ) -> Result<serde_json::Value, String> {- self.0- .call_confidential(MODULE, member, args)- .await- .map_err(|e| e.to_string())- }-}-struct State {- id: u64,- port: Arc<dyn Port>,- handle: CaptureHandle,- closed: AtomicBool,- serial: tokio::sync::Mutex<()>,-}-impl State {- async fn call<T: DeserializeOwned>(- &self,- member: &'static str,- args: impl Serialize,- ) -> Result<CaptureResult<T>, String> {- let args = serde_json::to_value(args).map_err(|_| malformed())?;- let value = self.port.call(member, args).await?;- serde_json::from_value(value).map_err(|_| malformed())- }- fn check_open(&self) -> Result<(), String> {- if self.closed.load(Ordering::SeqCst) {- Err("capture lease closed".into())- } else {- Ok(())- }- }- async fn close(&self) -> Result<(), String> {- let _serial = self.serial.lock().await;- if self.closed.load(Ordering::SeqCst) {- return Ok(());- }- cleanup_result(- self.call::<()>(methods::RECORDING_CANCEL, (&self.handle,))- .await?,- )?;- cleanup_result(- self.call::<()>(methods::RELEASE_AUDIO_OUTPUT, (&self.handle,))- .await?,- )?;- self.mark_closed();- Ok(())- }- fn mark_closed(&self) {- self.closed.store(true, Ordering::SeqCst);- LEASES- .lock()- .expect("capture lease registry poisoned")- .remove(&self.id);- }-}-/// Dropping a lease schedules cleanup; failed cleanup stays registered for retry.-pub(super) struct CaptureLease {- state: Arc<State>,-}-impl CaptureLease {- pub(super) async fn reserve(config: &Config) -> Result<Self, String> {- let port: Arc<dyn Port> = Arc::new(BusPort(crate::modules::client(config.clone())));- Self::reserve_with_port(port).await- }- async fn reserve_with_port(port: Arc<dyn Port>) -> Result<Self, String> {- let generation = RECORDING_GENERATION.load(Ordering::SeqCst);- let reply = port- .call(- methods::RESERVE_CAPTURE,- serde_json::to_value((RecordingStartRequest {- permission: MicrophonePermission::Granted,- handle: None,- },))- .map_err(|_| malformed())?,- )- .await?;- let handle: CaptureResult<CaptureHandle> =- serde_json::from_value(reply).map_err(|_| malformed())?;- let state = Arc::new(State {- id: NEXT_ID.fetch_add(1, Ordering::Relaxed),- port,- handle: handle.map_err(capture_error)?,- closed: AtomicBool::new(false),- serial: tokio::sync::Mutex::new(()),- });- LEASES- .lock()- .expect("capture lease registry poisoned")- .insert(state.id, state.clone());- register_shutdown();- let lease = Self { state };- if generation != RECORDING_GENERATION.load(Ordering::SeqCst) {- lease.close().await?;- return Err("capture cancelled during lifecycle change".into());- }- Ok(lease)- }- pub(super) async fn start_recording(&self) -> Result<(), String> {- let _serial = self.state.serial.lock().await;- self.state.check_open()?;- let handle: CaptureHandle = self- .state- .call(- methods::RECORDING_START,- (RecordingStartRequest {- permission: MicrophonePermission::Granted,- handle: Some(self.state.handle.clone()),- },),- )- .await?- .map_err(capture_error)?;- if handle != self.state.handle {- return Err(malformed());- }- Ok(())- }- pub(super) async fn finish(&self) -> Result<RecordingResult, String> {- let _serial = self.state.serial.lock().await;- self.state.check_open()?;- let output: AudioOutput = self- .state- .call(- methods::RECORDING_FINISH,- (RecordingFinishRequest {- handle: self.state.handle.clone(),- gate_threshold: 0.002,- },),- )- .await?- .map_err(capture_error)?;- if output.handle != self.state.handle || !(44..=MAX_OUTPUT_BYTES).contains(&output.length) {- return Err(malformed());- }- let summary: RecordingSummary = self- .state- .call(- methods::RECORDING_SUMMARY,- (RecordingSummaryRequest {- handle: self.state.handle.clone(),- },),- )- .await?- .map_err(capture_error)?;- if !summary.peak_rms.is_finite()- || summary.peak_rms < 0.0- || summary.sample_count > MAX_OUTPUT_BYTES / 2- || summary.sample_count.saturating_mul(2).saturating_add(44) != output.length- {- return Err(malformed());- }- let mut wav_bytes = Vec::with_capacity(output.length);- while wav_bytes.len() < output.length {- let length = READ_BYTES.min(output.length - wav_bytes.len());- let encoded: String = self- .state- .call(- methods::READ_AUDIO_OUTPUT,- (ReadAudioRequest {- handle: self.state.handle.clone(),- offset: wav_bytes.len(),- length,- },),- )- .await?- .map_err(capture_error)?;- if encoded.len() > READ_BYTES.div_ceil(3) * 4 {- return Err(malformed());- }- let bytes = base64::engine::general_purpose::STANDARD- .decode(encoded)- .map_err(|_| malformed())?;- if bytes.len() != length {- return Err(malformed());- }- wav_bytes.extend(bytes);- }- cleanup_result(- self.state- .call::<()>(methods::RELEASE_AUDIO_OUTPUT, (&self.state.handle,))- .await?,- )?;- self.state.mark_closed();- Ok(RecordingResult {- wav_bytes,- duration_secs: summary.sample_count as f32 / TARGET_SAMPLE_RATE as f32,- sample_count: summary.sample_count,- peak_rms: summary.peak_rms,- })- }- pub(super) async fn close(&self) -> Result<(), String> {- self.state.close().await- }-}-impl Drop for CaptureLease {- fn drop(&mut self) {- if self.state.closed.load(Ordering::SeqCst) {- return;- }- if let Ok(runtime) = tokio::runtime::Handle::try_current() {- let state = self.state.clone();- runtime.spawn(async move {- if let Err(error) = state.close().await {- log::warn!("[voice_capture] lease cleanup pending: {error}");- }- });- }- }-}-fn malformed() -> String {- crate::modules::report::malformed_reply(MODULE);- tinybus::module::ModuleCallError::ModuleFault.to_string()-}-fn capture_error(error: CaptureError) -> String {- let reason = match error {- CaptureError::PermissionDenied => "microphone permission denied",- CaptureError::Cancelled => "capture cancelled",- CaptureError::Closed => "capture module closed",- CaptureError::Busy => "microphone already in use",- CaptureError::UnknownHandle => "capture lease unavailable",- CaptureError::LimitExceeded => "capture limit exceeded",- CaptureError::InvalidParameters => "invalid capture parameters",- CaptureError::Device(_) => "microphone operation failed",- };- reason.into()-}-fn cleanup_result(result: CaptureResult<()>) -> Result<(), String> {- match result {- Ok(()) | Err(CaptureError::UnknownHandle) => Ok(()),- Err(error) => Err(capture_error(error)),- }-}-/// Release every retained capture lease on sign-out, including failed Drop cleanup.-pub(crate) async fn close_all() -> Result<(), String> {- RECORDING_GENERATION.fetch_add(1, Ordering::SeqCst);- let states: Vec<_> = LEASES- .lock()- .expect("capture lease registry poisoned")- .values()- .cloned()- .collect();- let mut failure = None;- for state in states {- if let Err(error) = state.close().await {- failure = Some(error);- }- }- failure.map_or(Ok(()), Err)-}-fn register_shutdown() {- if HOOK.swap(true, Ordering::SeqCst) {- return;- }- crate::core::shutdown::register(|| async {- shutdown_capture().await;- });-}-pub(crate) async fn shutdown_capture() {- HOOK.store(false, Ordering::SeqCst);- if let Err(error) = close_all().await {- log::warn!("[voice_capture] shutdown cleanup pending: {error}");- }-}-#[cfg(test)]-#[path = "capture_lease_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/voice/capture_lease_tests.rs b/crates/openhuman-core/src/voice/capture_lease_tests.rsdeleted file mode 100644index 3cd5a28f41..0000000000--- a/crates/openhuman-core/src/voice/capture_lease_tests.rs+++ /dev/null@@ -1,211 +0,0 @@-use super::*;--#[tokio::test]-async fn missing_module_never_starts_a_local_microphone() {- let mut config = Config::default();- config.modules.enabled = false;- let error = CaptureLease::reserve(&config).await.err().unwrap();- assert!(error.contains("MODULE_CALL_REPORTED"));-}--#[tokio::test]-async fn unavailable_cleanup_retains_the_lease_for_retry() {- let port = Arc::new(Fixture::default());- port.fail_cleanup.store(true, Ordering::SeqCst);- let lease = fixture_lease(port.clone());- assert!(lease.close().await.is_err());- assert!(!lease.state.closed.load(Ordering::SeqCst));- port.fail_cleanup.store(false, Ordering::SeqCst);- lease.close().await.unwrap();- assert!(lease.state.closed.load(Ordering::SeqCst));- assert_eq!(- *port.calls.lock().unwrap(),- vec![- methods::RECORDING_CANCEL,- methods::RECORDING_CANCEL,- methods::RELEASE_AUDIO_OUTPUT- ]- );-}--#[tokio::test]-async fn finishing_reads_bounded_output_and_uses_module_metrics() {- let port = Arc::new(Fixture::default());- let lease = fixture_lease(port.clone());- let result = lease.finish().await.unwrap();- assert_eq!(result.wav_bytes, vec![7; READ_BYTES + 2]);- assert_eq!(result.sample_count, (READ_BYTES + 2 - 44) / 2);- assert_eq!(result.peak_rms, 0.25);- assert_eq!(- port.reads.lock().unwrap().as_slice(),- &[(0, READ_BYTES), (READ_BYTES, 2)]- );- assert!(lease.state.closed.load(Ordering::SeqCst));-}--#[tokio::test]-async fn cancelled_finish_releases_the_known_recording_and_output() {- let port = Arc::new(Fixture::default());- port.block_finish.store(true, Ordering::SeqCst);- let lease = fixture_lease(port.clone());- let state = lease.state.clone();- let task = tokio::spawn(async move { lease.finish().await });- port.entered.notified().await;- task.abort();- let _ = task.await;- state.close().await.unwrap();- assert!(state.closed.load(Ordering::SeqCst));- let calls = port.calls.lock().unwrap();- assert!(calls.contains(&methods::RECORDING_CANCEL));- assert!(calls.contains(&methods::RELEASE_AUDIO_OUTPUT));-}--#[derive(Default)]-struct Fixture {- calls: std::sync::Mutex<Vec<&'static str>>,- reads: std::sync::Mutex<Vec<(usize, usize)>>,- fail_cleanup: AtomicBool,- block_finish: AtomicBool,- block_reserve: AtomicBool,- release_reserve: tokio::sync::Notify,- entered: tokio::sync::Notify,-}-#[async_trait::async_trait]-impl Port for Fixture {- async fn call(- &self,- member: &'static str,- args: serde_json::Value,- ) -> Result<serde_json::Value, String> {- self.calls.lock().unwrap().push(member);- if self.fail_cleanup.load(Ordering::SeqCst) && member == methods::RECORDING_CANCEL {- return Err("MODULE_CALL_REPORTED: transport failed".into());- }- match member {- methods::RESERVE_CAPTURE => {- if self.block_reserve.load(Ordering::SeqCst) {- self.entered.notify_one();- self.release_reserve.notified().await;- }- Ok(serde_json::to_value(CaptureResult::Ok(CaptureHandle("lease".into()))).unwrap())- }-- methods::RECORDING_FINISH => {- if self.block_finish.load(Ordering::SeqCst) {- self.entered.notify_one();- std::future::pending::<()>().await;- }- Ok(serde_json::to_value(CaptureResult::Ok(AudioOutput {- handle: CaptureHandle("lease".into()),- length: READ_BYTES + 2,- }))- .unwrap())- }- methods::RECORDING_SUMMARY => {- Ok(serde_json::to_value(CaptureResult::Ok(RecordingSummary {- sample_count: (READ_BYTES + 2 - 44) / 2,- peak_rms: 0.25,- }))- .unwrap())- }- methods::READ_AUDIO_OUTPUT => {- let request: ReadAudioRequest = serde_json::from_value(args[0].clone()).unwrap();- self.reads- .lock()- .unwrap()- .push((request.offset, request.length));- Ok(serde_json::to_value(CaptureResult::Ok(- base64::engine::general_purpose::STANDARD.encode(vec![7; request.length]),- ))- .unwrap())- }- methods::RECORDING_CANCEL => Ok(serde_json::to_value(CaptureResult::<()>::Err(- CaptureError::UnknownHandle,- ))- .unwrap()),- _ => Ok(serde_json::to_value(CaptureResult::Ok(())).unwrap()),- }- }-}-fn fixture_lease(port: Arc<Fixture>) -> CaptureLease {- CaptureLease {- state: Arc::new(State {- id: 0,- port,- handle: CaptureHandle("lease".into()),- closed: AtomicBool::new(false),- serial: tokio::sync::Mutex::new(()),- }),- }-}--#[cfg(feature = "modules")]-#[tokio::test]-async fn capture_never_retries_through_an_unattested_bus() {- use tinybus::{broker::Broker, transport::memory::MemoryBus, Connection, ObjectPath};- #[derive(Clone)]- struct Unattested(Arc<AtomicU64>);- #[tinybus::interface(name = "test.Capture")]- impl Unattested {- async fn recording_start(- &self,- _: RecordingStartRequest,- ) -> tinybus::Result<CaptureResult<CaptureHandle>> {- self.0.fetch_add(1, Ordering::SeqCst);- Ok(Ok(CaptureHandle("lease".into())))- }- }- let bus = MemoryBus::new();- Broker::new().spawn(bus.clone());- let service = Connection::connect(bus.connect().await.unwrap())- .await- .unwrap();- let caller = Connection::connect(bus.connect().await.unwrap())- .await- .unwrap();- let calls = Arc::new(AtomicU64::new(0));- service- .serve_at(- ObjectPath::new("/test/Capture").unwrap(),- Unattested(calls.clone()),- )- .await- .unwrap();- service.request_name("test.Capture").await.unwrap();- let proxy = caller- .proxy("test.Capture", "/test/Capture", "test.Capture")- .unwrap();- let lease = CaptureLease {- state: Arc::new(State {- id: 0,- port: Arc::new(BusPort(crate::modules::ops::fixture_client(proxy))),- handle: CaptureHandle("lease".into()),- closed: AtomicBool::new(false),- serial: tokio::sync::Mutex::new(()),- }),- };- let error = lease.start_recording().await.unwrap_err();- assert!(error.contains("MODULE_CALL_REPORTED"));- assert_eq!(calls.load(Ordering::SeqCst), 0);- lease.state.closed.store(true, Ordering::SeqCst);-}--#[tokio::test]-async fn a_reservation_finishing_after_sign_out_is_closed_before_start() {- let port = Arc::new(Fixture::default());- port.block_reserve.store(true, Ordering::SeqCst);- let task_port = port.clone();- let task = tokio::spawn(async move { CaptureLease::reserve_with_port(task_port).await });- port.entered.notified().await;- RECORDING_GENERATION.fetch_add(1, Ordering::SeqCst);- port.release_reserve.notify_one();- assert!(task.await.unwrap().is_err());- assert_eq!(- *port.calls.lock().unwrap(),- vec![- methods::RESERVE_CAPTURE,- methods::RECORDING_CANCEL,- methods::RELEASE_AUDIO_OUTPUT,- ]- );-}diff --git a/crates/openhuman-core/src/voice/cli.rs b/crates/openhuman-core/src/voice/cli.rsdeleted file mode 100644index 5a7a6620e3..0000000000--- a/crates/openhuman-core/src/voice/cli.rs+++ /dev/null@@ -1,126 +0,0 @@-//! Voice CLI adapter — domain-owned.-//!-//! Handles the `openhuman voice` / `openhuman dictate` subcommand which runs a-//! long-lived, blocking standalone dictation server (hotkey → record →-//! transcribe → insert). This flow doesn't fit the request/response controller-//! registry pattern because it blocks forever on the hotkey listener, so the-//! adapter lives here inside the voice domain rather than in `crates/openhuman-core/src/core/cli.rs`.--use anyhow::{anyhow, Result};--use crate::core::logging::{init_for_cli_run, CliLogDefault};-use crate::voice::server::{run_standalone, VoiceServerConfig};-use tinyvoice_bus::hotkey::ActivationMode;--/// Parse and execute the `openhuman voice` / `openhuman dictate` subcommand.-///-/// Supported flags:-/// --hotkey <combo> Key combination (default from config, usually `fn`)-/// --mode <tap|push> Activation mode (default push)-/// --skip-cleanup Skip LLM post-processing on transcriptions-/// -v / --verbose Enable debug logging-/// -h / --help Print usage-pub(crate) fn run_standalone_subcommand(args: &[String]) -> Result<()> {- let mut hotkey: Option<String> = None;- let mut mode: Option<String> = None;- let mut skip_cleanup = false;- let mut verbose = false;- let mut i = 0usize;-- while i < args.len() {- match args[i].as_str() {- "--hotkey" => {- hotkey = Some(- args.get(i + 1)- .ok_or_else(|| anyhow!("missing value for --hotkey"))?- .clone(),- );- i += 2;- }- "--mode" => {- mode = Some(- args.get(i + 1)- .ok_or_else(|| anyhow!("missing value for --mode"))?- .clone(),- );- i += 2;- }- "--skip-cleanup" => {- skip_cleanup = true;- i += 1;- }- "-v" | "--verbose" => {- verbose = true;- i += 1;- }- "-h" | "--help" => {- print_help();- return Ok(());- }- other => return Err(anyhow!("unknown voice arg: {other}")),- }- }-- log::debug!(- "[voice-cli] starting standalone server hotkey={:?} mode={:?} skip_cleanup={} verbose={}",- hotkey,- mode,- skip_cleanup,- verbose- );-- init_for_cli_run(verbose, CliLogDefault::Global);-- let rt = tokio::runtime::Builder::new_multi_thread()- .enable_all()- .build()?;-- rt.block_on(async {- let mut config = match crate::config::Config::load_or_init().await {- Ok(cfg) => cfg,- Err(e) => {- log::warn!("[voice-cli] config load failed, using defaults: {e}");- crate::config::Config::default()- }- };- config.apply_env_overrides();-- let activation_mode = match mode.as_deref() {- Some("tap") => ActivationMode::Tap,- Some("push") | None => ActivationMode::Push,- Some(other) => return Err(anyhow!("invalid --mode '{other}', expected tap|push")),- };-- let server_config = VoiceServerConfig {- hotkey: hotkey.unwrap_or_else(|| config.voice_server.hotkey.clone()),- activation_mode,- skip_cleanup,- context: None,- min_duration_secs: config.voice_server.min_duration_secs,- silence_threshold: config.voice_server.silence_threshold,- custom_dictionary: config.voice_server.custom_dictionary.clone(),- };-- run_standalone(- &crate::core::runtime::DispatchCtx::host_default(),- config,- server_config,- )- .await- .map_err(anyhow::Error::msg)- })?;-- Ok(())-}--fn print_help() {- println!("Usage: openhuman voice [--hotkey <combo>] [--mode <tap|push>] [--skip-cleanup] [-v]");- println!();- println!(" --hotkey <combo> Key combination (default: fn)");- println!(" --mode <tap|push> Activation: tap to toggle, push to hold (default: push)");- println!(" --skip-cleanup Skip LLM post-processing on transcriptions");- println!(" -v, --verbose Enable debug logging");- println!();- println!("Standalone voice dictation server. Press the hotkey to dictate,");- println!("transcribed text is inserted into the active text field.");-}diff --git a/crates/openhuman-core/src/voice/dictation_listener.rs b/crates/openhuman-core/src/voice/dictation_listener.rsdeleted file mode 100644index 3b7d03fd4d..0000000000--- a/crates/openhuman-core/src/voice/dictation_listener.rs+++ /dev/null@@ -1,269 +0,0 @@-//! Core-side dictation hotkey listener.-//!-//! Reads the `DictationConfig` from config, starts a module-owned global-//! hotkey listener on the core process, and broadcasts `dictation:toggle`-//! events over a `tokio::sync::broadcast` channel that the Socket.IO-//! bridge subscribes to — so the frontend receives hotkey presses without-//! any Tauri-side shortcut registration.--use once_cell::sync::Lazy;-use serde::Serialize;-use std::sync::Mutex;-use tokio::sync::broadcast;-use tokio::task::JoinHandle;-use tokio_util::sync::CancellationToken;--use crate::config::Config;-// macOS keeps the Tauri-owned global shortcut. Other platforms use TinyVoice's-// module-owned native listener through the same adapter as the voice server.-#[cfg(not(target_os = "macos"))]-use tinyvoice_bus::hotkey::{ActivationMode, HotkeyEvent};--const LOG_PREFIX: &str = "[dictation_listener]";--// ── Listener task handle (for stop support) ─────────────────────────--type ListenerTask = (CancellationToken, JoinHandle<()>);--static LISTENER_HANDLE: Lazy<Mutex<Option<ListenerTask>>> = Lazy::new(|| Mutex::new(None));--// ── Broadcast channel for dictation events ────────────────────────────--/// A dictation event broadcast to Socket.IO clients.-#[derive(Debug, Clone, Serialize)]-pub struct DictationEvent {- /// Event type: `"pressed"` or `"released"`.- #[serde(rename = "type")]- pub event_type: String,- /// The hotkey that triggered this event.- pub hotkey: String,- /// The activation mode in use.- pub activation_mode: String,-}--static DICTATION_BUS: Lazy<broadcast::Sender<DictationEvent>> = Lazy::new(|| {- let (tx, _rx) = broadcast::channel(64);- tx-});--/// Subscribe to dictation events (used by the Socket.IO bridge).-pub fn subscribe_dictation_events() -> broadcast::Receiver<DictationEvent> {- DICTATION_BUS.subscribe()-}--pub fn publish_dictation_event(event: DictationEvent) {- let _ = DICTATION_BUS.send(event);-}--// ── Transcription result broadcast ───────────────────────────────────--static TRANSCRIPTION_BUS: Lazy<broadcast::Sender<String>> = Lazy::new(|| {- let (tx, _rx) = broadcast::channel(64);- tx-});--/// Subscribe to transcription results (used by the Socket.IO bridge).-pub fn subscribe_transcription_results() -> broadcast::Receiver<String> {- TRANSCRIPTION_BUS.subscribe()-}--/// Broadcast a completed transcription to frontend clients.-///-/// Returns the number of receivers that received the message, or 0 if-/// there are no active subscribers.-pub fn publish_transcription(text: String) -> usize {- let receiver_count = TRANSCRIPTION_BUS.receiver_count();- log::info!(- "{LOG_PREFIX} publishing transcription: {} chars, {} active receivers",- text.len(),- receiver_count- );- match TRANSCRIPTION_BUS.send(text) {- Ok(n) => {- log::debug!("{LOG_PREFIX} transcription delivered to {n} receivers");- n- }- Err(_) => {- log::warn!("{LOG_PREFIX} transcription send failed — no active receivers");- 0- }- }-}--// ── Listener lifecycle ────────────────────────────────────────────────--/// Start the dictation hotkey listener if enabled in config.-///-/// Intended to be called once from `run_server()` as a background task.-/// Reads the `dictation` config section and registers the global hotkey.-/// When the hotkey fires, publishes a `DictationEvent` to the broadcast-/// channel that the Socket.IO bridge forwards to all connected clients.-///-/// **macOS note**: this function is a no-op on macOS. Starting with macOS 26,-/// `TSMGetInputSourceProperty` is enforced to run on the main dispatch queue;-/// rdev's CGEventTap callback fires on a background thread and crashes with-/// `EXC_BREAKPOINT` (`dispatch_assert_queue_fail`) on the first key press. The-/// Tauri host already registers the shortcut via `tauri-plugin-global-shortcut`-/// (main-thread-safe) and emits `dictation://toggle` to the frontend, making-/// the core-side rdev listener redundant on macOS. (#2677)-pub async fn start_if_enabled(ctx: &crate::core::runtime::DispatchCtx, config: &Config) {- if !config.components.voice {- log::info!("{LOG_PREFIX} [components].voice is off, skipping hotkey listener");- return;- }- if !config.dictation.enabled {- log::info!("{LOG_PREFIX} dictation disabled in config, skipping hotkey listener");- return;- }-- let hotkey_str = config.dictation.hotkey.clone();- if hotkey_str.is_empty() {- log::warn!("{LOG_PREFIX} dictation enabled but no hotkey configured");- return;- }-- // On macOS the rdev listener must not start: rdev's CGEventTap callback- // calls TSMGetInputSourceProperty off the main thread, crashing with- // EXC_BREAKPOINT on macOS 26 (dispatch_assert_queue_fail). The Tauri host- // handles this shortcut via tauri-plugin-global-shortcut instead. (#2677)- #[cfg(target_os = "macos")]- {- log::info!(- "{LOG_PREFIX} macOS: skipping rdev hotkey listener — \- handled by Tauri host via tauri-plugin-global-shortcut (issue #2677)"- );- }-- // Non-macOS: start the TinyVoice-owned native listener.- #[cfg(not(target_os = "macos"))]- start_module_listener(ctx, hotkey_str, config).await;-}--#[cfg(not(target_os = "macos"))]-async fn start_module_listener(- ctx: &crate::core::runtime::DispatchCtx,- hotkey_str: String,- config: &Config,-) {- // Map DictationActivationMode to our hotkey ActivationMode.- let mode = match config.dictation.activation_mode {- crate::config::DictationActivationMode::Push => ActivationMode::Push,- crate::config::DictationActivationMode::Toggle => ActivationMode::Tap,- };-- // Normalize the product spelling before passing it to TinyVoice.- let normalized = normalize_hotkey(&hotkey_str);-- log::info!(- "{LOG_PREFIX} starting dictation hotkey listener: hotkey={normalized} (raw={hotkey_str}) mode={mode:?}"- );-- let cancel = CancellationToken::new();- let (listener, mut hotkey_rx) =- match crate::voice::server::hotkey_listener::start_hotkey_listener(- ctx,- config,- &normalized,- mode,- &cancel,- )- .await- {- Ok(pair) => pair,- Err(e) => {- log::warn!("{LOG_PREFIX} failed to start hotkey listener: {e}");- return;- }- };-- let mode_str = match mode {- ActivationMode::Tap => "toggle",- ActivationMode::Push => "push",- };-- log::info!("{LOG_PREFIX} dictation hotkey active: {normalized}");-- // Forward hotkey events to the broadcast channel.- let task_cancel = cancel.clone();- let task = tokio::spawn(async move {- loop {- let event = tokio::select! {- _ = task_cancel.cancelled() => break,- event = hotkey_rx.recv() => match event {- Some(event) => event,- None => break,- },- };- let event_type = match event {- HotkeyEvent::Pressed => "pressed",- HotkeyEvent::Released => "released",- };-- log::debug!("{LOG_PREFIX} hotkey {event_type}");-- publish_dictation_event(DictationEvent {- event_type: event_type.to_string(),- hotkey: normalized.clone(),- activation_mode: mode_str.to_string(),- });- }-- listener.stop().await;- log::debug!("{LOG_PREFIX} hotkey listener stopped");- });-- // Store handle so `stop()` can abort it on logout.- if let Ok(mut guard) = LISTENER_HANDLE.lock() {- *guard = Some((cancel, task));- }-}--/// Stop the dictation hotkey listener if running.-///-/// Cancels the event forwarder and joins TinyVoice's native listener cleanup,-/// preventing duplicate hooks from accumulating across logout → login cycles.-pub async fn stop() {- let listener = LISTENER_HANDLE- .lock()- .ok()- .and_then(|mut guard| guard.take());- if let Some((cancel, handle)) = listener {- cancel.cancel();- if let Err(error) = handle.await {- log::warn!("{LOG_PREFIX} dictation listener task ended: {error}");- } else {- log::info!("{LOG_PREFIX} dictation listener stopped");- }- }-}--/// Normalize the host-style hotkey spelling for TinyVoice's portable parser.-///-/// Converts `CmdOrCtrl+Shift+D` → `cmd+shift+d` (macOS) or `ctrl+shift+d` (other).-fn normalize_hotkey(hotkey: &str) -> String {- let parts: Vec<&str> = hotkey.split('+').map(|s| s.trim()).collect();- let mut result = Vec::new();-- for part in parts {- let lower = part.to_lowercase();- let mapped = match lower.as_str() {- "cmdorctrl" | "commandorcontrol" => {- if cfg!(target_os = "macos") {- "cmd"- } else {- "ctrl"- }- }- "cmd" | "command" => "cmd",- "ctrl" | "control" => "ctrl",- other => other,- };- result.push(mapped.to_string());- }-- result.join("+")-}--#[cfg(test)]-#[path = "dictation_listener_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/voice/dictation_listener_tests.rs b/crates/openhuman-core/src/voice/dictation_listener_tests.rsdeleted file mode 100644index 7569f1856b..0000000000--- a/crates/openhuman-core/src/voice/dictation_listener_tests.rs+++ /dev/null@@ -1,164 +0,0 @@-use super::*;--#[test]-fn normalize_cmdorctrl_macos() {- let result = normalize_hotkey("CmdOrCtrl+Shift+D");- if cfg!(target_os = "macos") {- assert_eq!(result, "cmd+shift+d");- } else {- assert_eq!(result, "ctrl+shift+d");- }-}--#[test]-fn normalize_plain_keys() {- assert_eq!(normalize_hotkey("Ctrl+Space"), "ctrl+space");-}--#[test]-fn normalize_preserves_structure() {- assert_eq!(normalize_hotkey("Alt+Shift+F5"), "alt+shift+f5");-}--#[test]-fn subscribe_returns_receiver() {- let _rx = subscribe_dictation_events();-}--#[test]-fn publish_dictation_event_reaches_subscriber() {- let mut rx = subscribe_dictation_events();- publish_dictation_event(DictationEvent {- event_type: "pressed".to_string(),- hotkey: "chat_button".to_string(),- activation_mode: "toggle".to_string(),- });- let evt = rx.try_recv().expect("should receive dictation event");- assert_eq!(evt.event_type, "pressed");- assert_eq!(evt.hotkey, "chat_button");-}--#[test]-fn publish_transcription_reaches_subscriber() {- let mut rx = subscribe_transcription_results();- publish_transcription("hello world".to_string());- let text = rx.try_recv().expect("should receive transcription");- assert_eq!(text, "hello world");-}--#[test]-fn normalize_commandorcontrol_alias() {- let result = normalize_hotkey("CommandOrControl+Alt+K");- if cfg!(target_os = "macos") {- assert_eq!(result, "cmd+alt+k");- } else {- assert_eq!(result, "ctrl+alt+k");- }-}--#[test]-fn dictation_event_serializes_wire_type_field() {- let evt = DictationEvent {- event_type: "released".to_string(),- hotkey: "fn".to_string(),- activation_mode: "push".to_string(),- };- let json = serde_json::to_value(evt).expect("serialize dictation event");- assert_eq!(json["type"], "released");- assert_eq!(json["hotkey"], "fn");- assert_eq!(json["activation_mode"], "push");-}--#[tokio::test]-async fn start_if_enabled_returns_early_when_config_disabled() {- // Fast path — `enabled=false` → the fn returns without spawning.- let mut config = Config::default();- config.dictation.enabled = false;- start_if_enabled(&crate::core::runtime::DispatchCtx::default(), &config).await;- // No panic = pass. The absence of a spawned hotkey task is what- // we're verifying; hard to assert directly without internals.-}--#[tokio::test]-async fn start_if_enabled_returns_early_when_hotkey_empty() {- let mut config = Config::default();- config.dictation.enabled = true;- config.dictation.hotkey = String::new();- start_if_enabled(&crate::core::runtime::DispatchCtx::default(), &config).await;-}--#[tokio::test]-async fn start_if_enabled_returns_early_when_hotkey_unparseable() {- let mut config = Config::default();- config.dictation.enabled = true;- config.dictation.hotkey = "not a real hotkey".into();- start_if_enabled(&crate::core::runtime::DispatchCtx::default(), &config).await;-}--// On macOS the rdev listener must never start — TSMGetInputSourceProperty-// must run on the main dispatch queue; rdev fires its callback on a-// background thread and crashes with EXC_BREAKPOINT on macOS 26. (#2677)-#[cfg(target_os = "macos")]-#[tokio::test]-async fn start_if_enabled_is_noop_on_macos_with_valid_hotkey() {- let mut config = Config::default();- config.dictation.enabled = true;- config.dictation.hotkey = "ctrl+space".into();- // Must return without panicking or spawning the rdev listener.- start_if_enabled(&crate::core::runtime::DispatchCtx::default(), &config).await;- // No rdev thread was started: the global handle remains None.- let guard = LISTENER_HANDLE.lock().expect("lock");- assert!(- guard.is_none(),- "rdev listener must not be started on macOS"- );-}--#[cfg(target_os = "macos")]-#[tokio::test]-async fn start_if_enabled_is_noop_on_macos_with_fn_hotkey() {- let mut config = Config::default();- config.dictation.enabled = true;- config.dictation.hotkey = "fn".into();- start_if_enabled(&crate::core::runtime::DispatchCtx::default(), &config).await;- let guard = LISTENER_HANDLE.lock().expect("lock");- assert!(- guard.is_none(),- "rdev listener must not be started on macOS"- );-}--#[test]-fn normalize_maps_shift_and_alt_verbatim() {- let result = normalize_hotkey("Shift+Alt+D");- assert_eq!(result, "shift+alt+d");-}--#[test]-fn normalize_handles_lowercase_input() {- assert_eq!(normalize_hotkey("cmd+d"), "cmd+d");-}--#[test]-fn normalize_preserves_function_keys() {- assert_eq!(normalize_hotkey("F12"), "f12");-}--#[test]-fn normalize_trims_whitespace_between_segments() {- let result = normalize_hotkey(" cmd + shift + d ");- assert_eq!(result, "cmd+shift+d");-}--#[tokio::test]-async fn voice_component_off_overrides_dictation_enabled() {- let mut config = Config::default();- config.dictation.enabled = true;- config.dictation.hotkey = "ctrl+space".into();- config.components.voice = false;- start_if_enabled(&crate::core::runtime::DispatchCtx::default(), &config).await;- assert!(- LISTENER_HANDLE.lock().expect("lock").is_none(),- "no hotkey listener while [components].voice is off"- );-}diff --git a/crates/openhuman-core/src/voice/server.rs b/crates/openhuman-core/src/voice/server.rsdeleted file mode 100644index 72c3b2ab6f..0000000000--- a/crates/openhuman-core/src/voice/server.rs+++ /dev/null@@ -1,50 +0,0 @@-//! Standalone voice server — hotkey → record → transcribe → insert text.-//!-//! Can run as part of the core process or independently via the CLI.-//! The server listens for a configurable hotkey, records audio from the-//! microphone, transcribes via the configured STT engine, and inserts the result into the-//! active text field.-//!-//! ## Module layout-//!-//! - [`types`] — run state, status snapshot, and server config.-//! - [`hotkey_listener`] — TinyVoice native listeners and the macOS Globe composition.-//! - [`pipeline`] — the background recording → transcription pass.-//! - [`runtime`] — the hotkey event loop that drives a `VoiceServer`.-//! - [`singleton`] — the process-global instance, auto-start, and the-//! standalone (CLI) entry point.--pub(crate) mod hotkey_listener;-mod pipeline;-mod recorder;-mod runtime;-mod singleton;-mod types;--pub use runtime::VoiceServer;-pub use singleton::{global_server, run_standalone, start_if_enabled, try_global_server};-pub use types::{ServerState, VoiceServerConfig, VoiceServerStatus};--#[cfg(test)]-use crate::config::Config;-#[cfg(test)]-use crate::voice::audio_capture::RecordingHandle;-#[cfg(test)]-use pipeline::{- build_initial_prompt, capture_expected_app_name, process_recording_bg, push_recent_transcript,- truncate_for_log,-};-#[cfg(test)]-use std::sync::Arc;-#[cfg(test)]-use tinyvoice_bus::hotkey::ActivationMode;-#[cfg(test)]-use tokio::sync::Mutex;-#[cfg(test)]-use types::DEFAULT_SILENCE_THRESHOLD;--const LOG_PREFIX: &str = "[voice_server]";--#[cfg(test)]-#[path = "server_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/voice/server/README.md b/crates/openhuman-core/src/voice/server/README.mddeleted file mode 100644index 26845ca6bf..0000000000--- a/crates/openhuman-core/src/voice/server/README.md+++ /dev/null@@ -1,48 +0,0 @@-# voice/server--The `VoiceServer` dictation runtime: hotkey press, record, transcribe, insert-text. It is the implementation behind `voice::server` (see the parent-[README](../README.md)), and can run embedded in the core process or-standalone through the `openhuman voice`/`openhuman dictate` CLI subcommand.--## Responsibilities--- Listen for a configurable hotkey and turn press/release events into audio recordings.-- Hand each finished recording to a background pipeline that gates on minimum duration, silence, and hallucinated output, then transcribes and delivers the result.-- Mirror the running state (`Stopped`/`Idle`/`Recording`/`Transcribing`), owned by the `tinyvoice` module's recording session, plus a transcription counter, and the last error, exposed through `VoiceServerStatus`.-- Keep a rolling buffer of recent transcripts to bias the STT engine's `initial_prompt` for continuity across consecutive recordings.-- Provide a process-global singleton so RPC status/stop calls and the embedded auto-start path always act on the same running instance.--## Key files--| File | Role |-| --- | --- |-| [`types.rs`](./types.rs) | `ServerState`, `VoiceServerStatus`, `VoiceServerConfig` (hotkey, activation mode, skip_cleanup, context, min duration, silence threshold, custom dictionary), plus the `DEFAULT_SILENCE_THRESHOLD` (0.002 RMS, matching OpenWhispr's default), `MAX_RECENT_TRANSCRIPTS` (5), and `MAX_INITIAL_PROMPT_CHARS` (500) tunables. |-| [`recorder.rs`](./recorder.rs) | `Recorder`: the host handle on the module-owned state machine (`SessionAdvance`); serialises each call with the phase mirror write. |-| [`runtime.rs`](./runtime.rs) | `VoiceServer`: the hotkey event loop. Starts the platform hotkey listener, reports hotkey facts and setup results to the module session and performs the action it answers with (start, defer stop, stop), reports a buffered event found behind a finished setup, and spawns `process_recording_bg` off the event loop so rapid consecutive presses are never missed. Owns `run`/`stop`/`status`. |-| [`hotkey_listener.rs`](./hotkey_listener.rs) | Picks the platform-appropriate listener. Uses `rdev` everywhere except the macOS `Fn`/Globe key, which goes through a Swift-based globe listener inside the compiled TinyComputer module, with acknowledged batches and explicit lease cleanup instead, because `rdev`'s `CGEventTap` callback calls `TSMGetInputSourceProperty` off the main thread and macOS 26 kills the process for that (#2677). Any other hotkey is rejected on macOS with a message pointing at `hotkey = "fn"`. |-| [`pipeline.rs`](./pipeline.rs) | `process_recording_bg`: stops the recording, applies the duration/silence gates (`GateRecording`) and the hallucination gate, builds the `initial_prompt` from the custom dictionary and recent transcripts, transcribes via `crate::voice::voice_transcribe_bytes`, and delivers the text either over Socket.IO (when the focused app is OpenHuman itself) or by pasting into the external app via `text_input::insert_text`. |-| [`singleton.rs`](./singleton.rs) | `global_server`/`try_global_server` (the process-global `OnceCell<Arc<VoiceServer>>`), `start_if_enabled` (embedded auto-start, gated on `config.voice_server.auto_start`), and `run_standalone` (the blocking CLI entry point, which deliberately does not register in the global singleton so CLI-started instances stay isolated from the core RPC lifecycle). |--## How it fits--`server.rs` in the parent `voice` module re-exports this submodule's public-surface (`VoiceServer`, `global_server`, `try_global_server`,-`start_if_enabled`, `run_standalone`, `ServerState`, `VoiceServerConfig`,-`VoiceServerStatus`) and is itself gated behind the `voice` Cargo feature (see-the compile-time gate section in [../README.md](../README.md)). The RPC and-agent-tool surface for voice generally lives in `voice/schemas/` and-`voice/ops.rs`, not here; this module only owns the dictation runtime.--## Notes / gotchas--- Focus capture and microphone permission checks run through async TinyComputer calls; device setup then runs on a blocking thread (`audio_capture::start_recording`) so the event loop stays responsive to a `Released` event that some keys, including `Fn`, fire almost immediately. A release or a second press that arrives during that setup is buffered as a stop intent and applied once the recording handle is ready, with a minimum post-setup recording window (1500ms) so very quick releases still capture real speech.-- `stop()` cancels the run-loop's `CancellationToken` and polls for up to 5 seconds for the state to reach `Stopped`, since a fast logout/login cycle should not see a stale `Idle`/`Recording` state and skip a restart.-- State updates carry a `generation` counter so a stale background pipeline task from a superseded recording cannot overwrite the state of a newer one.--## Further reading--- [Parent module (`voice`)](../README.md)-- [Voice tools](../../../../../docs/gitbooks/en/features/native-tools/voice.md)-- [tinyvoice submodule](../../../../../vendor/tinyvoice/README.md)-- [Chat](../../../../../docs/gitbooks/en/features/chat.md)diff --git a/crates/openhuman-core/src/voice/server/hotkey_listener.rs b/crates/openhuman-core/src/voice/server/hotkey_listener.rsdeleted file mode 100644index 4a4f69b6ba..0000000000--- a/crates/openhuman-core/src/voice/server/hotkey_listener.rs+++ /dev/null@@ -1,534 +0,0 @@-//! Hotkey listener dispatch. TinyVoice owns native listeners; macOS Globe-//! input remains a host-fed composition over TinyComputer facts.--#[cfg(any(target_os = "macos", test))]-use std::time::Duration;--#[cfg(any(target_os = "macos", test))]-use log::warn;-use tokio_util::sync::CancellationToken;--use tinyvoice_bus::hotkey;--use super::LOG_PREFIX;--/// Opaque handle that keeps the hotkey listener alive. Drop to stop.-pub(crate) enum HotkeyListenerKind {- Module {- cancel: CancellationToken,- task: tokio::task::JoinHandle<()>,- },- #[cfg(any(target_os = "macos", test))]- Globe {- cancel: CancellationToken,- task: tokio::task::JoinHandle<()>,- },-}--impl HotkeyListenerKind {- pub(crate) async fn stop(self) {- match self {- HotkeyListenerKind::Module { cancel, task } => {- cancel.cancel();- let _ = task.await;- }- #[cfg(any(target_os = "macos", test))]- HotkeyListenerKind::Globe { cancel, task } => {- cancel.cancel();- let _ = task.await;- }- }- }-}--/// Start the appropriate hotkey listener for the current platform and key.-///-/// On macOS, the Fn/Globe key is handled by the Swift-based globe listener-/// inside the TinyComputer module which monitors `NSEvent.flagsChanged`. All other-/// keys return an error on macOS: rdev's CGEventTap callback calls-/// `TSMGetInputSourceProperty` off the main thread; macOS 26 enforces-/// `dispatch_assert_queue(main_queue)` inside that API and kills the process-/// with `EXC_BREAKPOINT` (`dispatch_assert_queue_fail`). Configure-/// `hotkey = "fn"` to avoid this. (#2677)-pub(crate) async fn start_hotkey_listener(- ctx: &crate::core::runtime::DispatchCtx,- config: &crate::config::Config,- hotkey_str: &str,- mode: hotkey::ActivationMode,- server_cancel: &CancellationToken,-) -> Result<- (- HotkeyListenerKind,- tokio::sync::mpsc::Receiver<hotkey::HotkeyEvent>,- ),- String,-> {- #[cfg(target_os = "macos")]- {- if hotkey_str.trim().eq_ignore_ascii_case("fn") {- return start_globe_hotkey_listener(ctx, config, mode, server_cancel).await;- }- // rdev calls TSMGetInputSourceProperty off the main thread; macOS 26- // enforces main-queue-only access and crashes the process. Only the- // Fn/Globe key is safe via the Swift globe listener. (#2677)- Err(format!(- "voice server hotkey '{}' is not supported on macOS — \- only 'fn' (Fn/Globe key) is safe. rdev calls \- TSMGetInputSourceProperty off the main thread on macOS 26, \- causing EXC_BREAKPOINT. Set hotkey = \"fn\" in voice config \- (issue #2677).",- hotkey_str- ))- }-- // Non-macOS: TinyVoice owns its native listener and cleanup worker.- #[cfg(not(target_os = "macos"))]- {- start_module_hotkey_listener(ctx, config, hotkey_str, mode, server_cancel).await- }-}--#[cfg(not(target_os = "macos"))]-async fn start_module_hotkey_listener(- ctx: &crate::core::runtime::DispatchCtx,- config: &crate::config::Config,- hotkey_str: &str,- mode: hotkey::ActivationMode,- server_cancel: &CancellationToken,-) -> Result<- (- HotkeyListenerKind,- tokio::sync::mpsc::Receiver<hotkey::HotkeyEvent>,- ),- String,-> {- use crate::modules::voice;- use std::time::Duration;-- let handle = voice::reserve_hotkey(- config,- hotkey::HotkeyRequest {- key: hotkey_str.to_string(),- mode,- source: hotkey::HotkeySource::Native,- },- )- .await- .map_err(|error| error.to_string())?- .map_err(|error| format!("hotkey reservation failed: {error:?}"))?;-- let task_cancel = server_cancel.child_token();- let worker_cancel = task_cancel.clone();- let task_config = config.clone();- let (events_tx, events_rx) = tokio::sync::mpsc::channel(65);- let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();- let worker_handle = handle.clone();- let task = ctx.spawn(async move {- let generation = loop {- if worker_cancel.is_cancelled() || events_tx.is_closed() {- break None;- }- match voice::start_hotkey(&task_config, worker_handle.clone()).await {- Ok(Ok(status)) if status.state == hotkey::HotkeyState::Running => {- break status.generation;- }- Ok(Ok(_)) => break None,- Ok(Err(error)) => {- let _ = ready_tx.send(Err(format!("hotkey startup failed: {error:?}")));- close_module_hotkey(&task_config, worker_handle).await;- return;- }- Err(error) => {- tokio::select! {- _ = worker_cancel.cancelled() => break None,- _ = tokio::time::sleep(Duration::from_millis(250)) => {}- }- log::debug!("{LOG_PREFIX} retrying uncertain hotkey start: {error}");- }- }- };- let Some(generation) = generation else {- let _ = ready_tx.send(Err("hotkey startup canceled".into()));- close_module_hotkey(&task_config, worker_handle).await;- return;- };- if ready_tx.send(Ok(())).is_err() {- close_module_hotkey(&task_config, worker_handle).await;- return;- }-- let mut delivery = HotkeyDelivery::new(generation);- let mut interval = tokio::time::interval(Duration::from_millis(25));- interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);- loop {- tokio::select! {- _ = worker_cancel.cancelled() => break,- _ = events_tx.closed() => break,- _ = interval.tick() => {}- }- // A batch is capped at 64 events. Reserve one slot for the- // inactive edge delivered when the module reports a reset.- if events_tx.capacity() != 65 {- continue;- }- let batch = match voice::read_hotkey(- &task_config,- hotkey::HotkeyReadRequest {- handle: worker_handle.clone(),- acknowledged_batch: delivery.acknowledged_batch,- },- )- .await- {- Ok(Ok(batch)) => batch,- Ok(Err(error)) => {- log::warn!("{LOG_PREFIX} module hotkey read failed: {error:?}");- break;- }- Err(error) => {- log::warn!("{LOG_PREFIX} module hotkey read unavailable: {error}");- continue;- }- };- let events = match delivery.accept(&batch) {- Ok(events) => events,- Err(()) => {- log::warn!("{LOG_PREFIX} invalid TinyVoice hotkey batch continuity");- break;- }- };- let mut delivered = true;- for event in events {- if events_tx.send(event).await.is_err() {- delivered = false;- break;- }- }- if !delivered {- break;- }- }- close_module_hotkey(&task_config, worker_handle).await;- });-- tokio::select! {- result = ready_rx => result.map_err(|_| "TinyVoice hotkey startup task ended".to_string())??,- _ = server_cancel.cancelled() => return Err("hotkey startup canceled".into()),- }- Ok((- HotkeyListenerKind::Module {- cancel: task_cancel,- task,- },- events_rx,- ))-}--#[cfg(not(target_os = "macos"))]-async fn close_module_hotkey(config: &crate::config::Config, handle: hotkey::HotkeyHandle) {- loop {- match crate::modules::voice::stop_hotkey(config, handle.clone()).await {- Ok(Ok(status)) if status.state == hotkey::HotkeyState::Stopped => return,- Ok(Ok(status)) => {- log::warn!(- "{LOG_PREFIX} hotkey cleanup still active: {:?}",- status.state- )- }- Ok(Err(hotkey::HotkeyError::UnknownHandle)) => return,- Ok(Err(error)) => log::warn!("{LOG_PREFIX} hotkey cleanup pending: {error:?}"),- Err(error) => log::warn!("{LOG_PREFIX} hotkey cleanup unavailable: {error}"),- }- tokio::time::sleep(std::time::Duration::from_millis(250)).await;- }-}--/// Validate and translate one replayable module batch before acknowledging it.-/// The queue stays bounded to one batch, so acknowledgment means every event-/// has been admitted to the host's receiver.-#[cfg(not(target_os = "macos"))]-struct HotkeyDelivery {- generation: u64,- acknowledged_batch: Option<u64>,- active: bool,- last_sequence: Option<u64>,-}--#[cfg(not(target_os = "macos"))]-impl HotkeyDelivery {- fn new(generation: u64) -> Self {- Self {- generation,- acknowledged_batch: None,- active: false,- last_sequence: None,- }- }-- fn accept(&mut self, batch: &hotkey::HotkeyBatch) -> Result<Vec<hotkey::HotkeyEvent>, ()> {- if batch.generation != self.generation- || batch.events.len() > 64- || batch.batch != self.acknowledged_batch.unwrap_or(0).saturating_add(1)- {- return Err(());- }-- let mut active = self.active;- let mut last_sequence = self.last_sequence;- let mut output = Vec::with_capacity(batch.events.len() + usize::from(batch.reset));- if batch.reset {- if active {- output.push(hotkey::HotkeyEvent::Released);- }- active = false;- last_sequence = None;- }- for event in &batch.events {- if event.generation != self.generation- || last_sequence.is_some_and(|last| event.sequence <= last)- {- return Err(());- }- active = event.event == hotkey::HotkeyEvent::Pressed;- last_sequence = Some(event.sequence);- output.push(event.event);- }- if active != batch.active {- return Err(());- }-- self.acknowledged_batch = Some(batch.batch);- self.active = active;- self.last_sequence = last_sequence;- Ok(output)- }-}--/// Start an owned task before awaiting the module, so cancellation during startup-/// still leaves an owner to recover a lost start reply and close the native lease.-#[cfg(target_os = "macos")]-async fn start_globe_hotkey_listener(- ctx: &crate::core::runtime::DispatchCtx,- config: &crate::config::Config,- mode: hotkey::ActivationMode,- server_cancel: &CancellationToken,-) -> Result<- (- HotkeyListenerKind,- tokio::sync::mpsc::Receiver<hotkey::HotkeyEvent>,- ),- String,-> {- start_globe_with_client(- ctx,- crate::modules::accessibility::AccessibilityClient::new(config),- mode,- server_cancel,- )- .await-}--#[cfg(any(target_os = "macos", test))]-async fn start_globe_with_client(- ctx: &crate::core::runtime::DispatchCtx,- client: crate::modules::accessibility::AccessibilityClient,- mode: hotkey::ActivationMode,- server_cancel: &CancellationToken,-) -> Result<- (- HotkeyListenerKind,- tokio::sync::mpsc::Receiver<hotkey::HotkeyEvent>,- ),- String,-> {- static ADMISSION: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());- let admission = tokio::time::timeout(Duration::from_secs(15), ADMISSION.lock())- .await- .map_err(|_| "previous Globe listener cleanup is still pending".to_string())?;- let (tx, rx) = tokio::sync::mpsc::channel(65);- let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();- let cancel = server_cancel.child_token();- let task_cancel = cancel.clone();- let task = ctx.spawn(async move {- let _admission = admission;- let started = match client.globe_start().await {- Ok(started) => started,- Err(error) => {- let recover = matches!(- error,- crate::modules::accessibility::AccessibilityError::Bus(- tinybus::module::ModuleCallError::TransportFailed- | tinybus::module::ModuleCallError::ModuleFault- )- );- let _ = ready_tx.send(Err(error.to_string()));- if !recover {- return;- }- // Start is idempotent. Recover its lease before cleanup rather- // than abandoning a native start whose reply was lost.- loop {- match client.globe_start().await {- Ok(started) => {- close_globe(&client, started.handle).await;- return;- }- Err(_) => tokio::time::sleep(Duration::from_secs(1)).await,- }- }- }- };- let handle = started.handle;- if !started.status.running {- let _ = ready_tx.send(Err(started- .status- .last_error- .unwrap_or_else(|| "Globe listener did not start".into())));- close_globe(&client, handle).await;- return;- }- if ready_tx.send(Ok(())).is_err() {- close_globe(&client, handle).await;- return;- }- let mut acknowledged_batch = None;- let mut activation = GlobeActivation::default();- let mut interval = tokio::time::interval(Duration::from_millis(50));- interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);- loop {- tokio::select! {- _ = task_cancel.cancelled() => break,- _ = tx.closed() => break,- _ = interval.tick() => {}- }- // One bounded module batch at a time. Wait for the host to consume- // its queue before accepting another batch (at most 65 events).- if tx.capacity() != 65 {- continue;- }- let batch = match client- .globe_read(crate::modules::accessibility::GlobeRead {- handle: handle.clone(),- acknowledged_batch,- })- .await- {- Ok(batch) => batch,- Err(error) => {- warn!("{LOG_PREFIX} Globe read failed: {error}");- break;- }- };- if batch.handle != handle- || batch.events.len() > 64- || batch.batch != acknowledged_batch.unwrap_or(0).saturating_add(1)- {- warn!("{LOG_PREFIX} invalid Globe batch");- break;- }- if !batch.status.running {- break;- }- if batch.overflow {- if let Some(event) = activation.reset() {- if tx.send(event).await.is_err() {- break;- }- }- }- let mut delivered = true;- for event in batch.events {- if let Some(event) = activation.event(event, mode) {- if tx.send(event).await.is_err() {- delivered = false;- break;- }- }- }- if !delivered {- break;- }- acknowledged_batch = Some(batch.batch);- }- close_globe(&client, handle).await;- });- // Dropping the startup future cancels the task's receiver; ready_tx then- // fails and the task closes its lease before releasing admission.- ready_rx- .await- .map_err(|_| "Globe startup task failed".to_string())??;- Ok((HotkeyListenerKind::Globe { cancel, task }, rx))-}--/// Keep the admission guard while close fails; a successor cannot adopt a-/// listener with uncertain native cleanup. An already-retired lease is closed.-#[cfg(any(target_os = "macos", test))]-async fn close_globe(- client: &crate::modules::accessibility::AccessibilityClient,- handle: crate::modules::accessibility::GlobeHandle,-) {- loop {- match client.globe_stop(handle.clone()).await {- Ok(_) => return,- Err(crate::modules::accessibility::AccessibilityError::Operation(error))- if error.code == "UNKNOWN_LISTENER" =>- {- return- }- Err(error) => warn!("{LOG_PREFIX} Globe cleanup pending: {error}"),- }- tokio::time::sleep(Duration::from_secs(1)).await;- }-}--/// Host activation policy; an overflow requires a physical release before rearming.-#[cfg(any(target_os = "macos", test))]-#[derive(Default)]-struct GlobeActivation {- active: bool,- wait_release: bool,-}--#[cfg(any(target_os = "macos", test))]-impl GlobeActivation {- fn reset(&mut self) -> Option<hotkey::HotkeyEvent> {- self.wait_release = true;- std::mem::take(&mut self.active).then_some(hotkey::HotkeyEvent::Released)- }- fn event(- &mut self,- event: tinycomputer_bus::accessibility::GlobeEvent,- mode: hotkey::ActivationMode,- ) -> Option<hotkey::HotkeyEvent> {- use tinycomputer_bus::accessibility::GlobeEvent::{Down, Up};- if self.wait_release {- if event == Up {- self.wait_release = false;- }- return None;- }- match (event, mode) {- (Down, hotkey::ActivationMode::Tap) => {- self.active = !self.active;- Some(if self.active {- hotkey::HotkeyEvent::Pressed- } else {- hotkey::HotkeyEvent::Released- })- }- (Down, hotkey::ActivationMode::Push) if !self.active => {- self.active = true;- Some(hotkey::HotkeyEvent::Pressed)- }- (Up, hotkey::ActivationMode::Push) if self.active => {- self.active = false;- Some(hotkey::HotkeyEvent::Released)- }- _ => None,- }- }-}--#[cfg(test)]-#[path = "hotkey_listener_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/voice/server/hotkey_listener_tests.rs b/crates/openhuman-core/src/voice/server/hotkey_listener_tests.rsdeleted file mode 100644index 873c809b4e..0000000000--- a/crates/openhuman-core/src/voice/server/hotkey_listener_tests.rs+++ /dev/null@@ -1,375 +0,0 @@-use super::*;-use hotkey::{- ActivationMode::{Push, Tap},- HotkeyEvent::{Pressed, Released},-};-use tinycomputer_bus::accessibility::GlobeEvent::{Down, Up};--#[cfg(not(target_os = "macos"))]-use tinyvoice_bus::hotkey::{HotkeyBatch, SequencedHotkeyEvent};--#[cfg(not(target_os = "macos"))]-fn batch(- generation: u64,- batch: u64,- events: &[(u64, hotkey::HotkeyEvent)],- reset: bool,- active: bool,-) -> HotkeyBatch {- HotkeyBatch {- generation,- batch,- events: events- .iter()- .map(|(sequence, event)| SequencedHotkeyEvent {- generation,- sequence: *sequence,- event: *event,- })- .collect(),- reset,- active,- }-}--#[cfg(not(target_os = "macos"))]-#[test]-fn native_hotkey_batches_ack_only_after_ordered_event_state_is_valid() {- let mut delivery = HotkeyDelivery::new(4);- assert_eq!(- delivery- .accept(&batch(4, 1, &[(1, Pressed)], false, true))- .unwrap(),- [Pressed]- );- assert_eq!(delivery.acknowledged_batch, Some(1));-- let invalid = batch(4, 2, &[(2, Released)], false, true);- assert!(delivery.accept(&invalid).is_err());- assert_eq!(delivery.acknowledged_batch, Some(1));- assert!(delivery.active);-- assert_eq!(- delivery- .accept(&batch(4, 2, &[(2, Released)], false, false))- .unwrap(),- [Released]- );- assert_eq!(delivery.acknowledged_batch, Some(2));-}--#[cfg(not(target_os = "macos"))]-#[test]-fn native_hotkey_reset_releases_active_state_and_accepts_fresh_sequence() {- let mut delivery = HotkeyDelivery::new(9);- delivery- .accept(&batch(9, 1, &[(4, Pressed)], false, true))- .unwrap();- assert_eq!(- delivery.accept(&batch(9, 2, &[], true, false)).unwrap(),- [Released]- );- assert_eq!(delivery.acknowledged_batch, Some(2));- assert_eq!(- delivery- .accept(&batch(9, 3, &[(8, Pressed)], false, true))- .unwrap(),- [Pressed]- );- assert_eq!(delivery.acknowledged_batch, Some(3));- assert!(delivery.active);-}--#[test]-fn overflow_stops_activation_and_waits_for_physical_release() {- for mode in [Push, Tap] {- let mut state = GlobeActivation::default();- assert!(matches!(state.event(Down, mode), Some(Pressed)));- assert!(matches!(state.reset(), Some(Released)));- assert!(state.event(Down, mode).is_none());- assert!(state.event(Up, mode).is_none());- assert!(matches!(state.event(Down, mode), Some(Pressed)));- }-}--#[test]-fn tap_ignores_key_release_and_toggles_on_the_next_press() {- let mut state = GlobeActivation::default();- assert!(matches!(state.event(Down, Tap), Some(Pressed)));- assert!(state.event(Up, Tap).is_none());- assert!(matches!(state.event(Down, Tap), Some(Released)));-}--#[test]-fn push_suppresses_duplicate_physical_edges() {- let mut state = GlobeActivation::default();- assert!(matches!(state.event(Down, Push), Some(Pressed)));- assert!(state.event(Down, Push).is_none());- assert!(matches!(state.event(Up, Push), Some(Released)));- assert!(state.event(Up, Push).is_none());-}--#[cfg(feature = "modules")]-#[derive(Clone, Default)]-struct ListenerFixture {- entered: std::sync::Arc<tokio::sync::Notify>,- allow_start: std::sync::Arc<tokio::sync::Notify>,- stopped: std::sync::Arc<tokio::sync::Notify>,- closes: std::sync::Arc<std::sync::atomic::AtomicUsize>,- lose_start_reply: std::sync::Arc<std::sync::atomic::AtomicBool>,- fail_close: std::sync::Arc<std::sync::atomic::AtomicBool>,-}--#[cfg(feature = "modules")]-fn status(running: bool) -> crate::modules::accessibility::GlobeHotkeyStatus {- crate::modules::accessibility::GlobeHotkeyStatus {- supported: true,- running,- input_monitoring_permission: crate::modules::accessibility::PermissionState::Granted,- last_error: None,- events_pending: 0,- }-}--#[cfg(feature = "modules")]-#[tinybus::interface(name = "test.Globe")]-impl ListenerFixture {- async fn globe_start(&self) -> tinybus::Result<tinycomputer_bus::DesktopResponse> {- self.entered.notify_one();- if self- .lose_start_reply- .swap(false, std::sync::atomic::Ordering::SeqCst)- {- return Err(tinybus::Error::MethodFailed {- name: tinybus::Error::NOT_ATTESTED.into(),- message: "fixture lost response".into(),- });- }- self.allow_start.notified().await;- Ok(tinycomputer_bus::DesktopResponse::ok(- "globe-start",- serde_json::to_value(crate::modules::accessibility::GlobeStarted {- handle: crate::modules::accessibility::GlobeHandle("lease".into()),- status: status(true),- })- .unwrap(),- ))- }- async fn globe_stop(- &self,- handle: crate::modules::accessibility::GlobeHandle,- ) -> tinybus::Result<tinycomputer_bus::DesktopResponse> {- assert_eq!(handle.0, "lease");- if self- .fail_close- .swap(false, std::sync::atomic::Ordering::SeqCst)- {- return Err(tinybus::Error::failed("fixture cleanup pending"));- }- self.closes- .fetch_add(1, std::sync::atomic::Ordering::SeqCst);- self.stopped.notify_one();- Ok(tinycomputer_bus::DesktopResponse::ok(- "globe-stop",- serde_json::to_value(status(false)).unwrap(),- ))- }- async fn globe_read(- &self,- request: crate::modules::accessibility::GlobeRead,- ) -> tinybus::Result<tinycomputer_bus::DesktopResponse> {- Ok(tinycomputer_bus::DesktopResponse::ok(- "globe-read",- serde_json::to_value(crate::modules::accessibility::GlobeBatch {- handle: request.handle,- batch: 1,- status: status(true),- events: vec![],- overflow: false,- })- .unwrap(),- ))- }-}--#[cfg(feature = "modules")]-async fn listener_fixture() -> (- crate::modules::accessibility::AccessibilityClient,- ListenerFixture,- tinybus::Connection,-) {- use tinybus::{broker::Broker, transport::memory::MemoryBus, Connection, ObjectPath};- let bus = MemoryBus::new();- Broker::new().spawn(bus.clone());- let service = Connection::connect(bus.connect().await.unwrap())- .await- .unwrap();- let caller = Connection::connect(bus.connect().await.unwrap())- .await- .unwrap();- let fixture = ListenerFixture::default();- service- .serve_at(ObjectPath::new("/test/Globe").unwrap(), fixture.clone())- .await- .unwrap();- service.request_name("test.Globe").await.unwrap();- let proxy = caller- .proxy("test.Globe", "/test/Globe", "test.Globe")- .unwrap();- (- crate::modules::accessibility::AccessibilityClient::fixture(proxy),- fixture,- service,- )-}--#[cfg(feature = "modules")]-async fn cancelling_startup_still_closes_the_module_owned_listener_fixture() {- let (client, fixture, _service) = listener_fixture().await;- let startup = tokio::spawn(async move {- start_globe_with_client(- &crate::core::runtime::DispatchCtx::default(),- client,- Push,- &CancellationToken::new(),- )- .await- });- fixture.entered.notified().await;- startup.abort();- assert!(matches!(startup.await, Err(error) if error.is_cancelled()));- fixture.allow_start.notify_one();- tokio::time::timeout(- std::time::Duration::from_secs(5),- fixture.stopped.notified(),- )- .await- .unwrap();- assert_eq!(fixture.closes.load(std::sync::atomic::Ordering::SeqCst), 1);-}--#[cfg(feature = "modules")]-async fn stopping_listener_joins_its_bus_cleanup_fixture() {- let (client, fixture, _service) = listener_fixture().await;- fixture.allow_start.notify_one();- let (handle, _rx) = start_globe_with_client(- &crate::core::runtime::DispatchCtx::default(),- client,- Push,- &CancellationToken::new(),- )- .await- .unwrap();- handle.stop().await;- assert_eq!(fixture.closes.load(std::sync::atomic::Ordering::SeqCst), 1);-}--#[cfg(feature = "modules")]-async fn lost_start_reply_recovers_the_lease_before_releasing_admission_fixture() {- let (client, fixture, _service) = listener_fixture().await;- fixture- .lose_start_reply- .store(true, std::sync::atomic::Ordering::SeqCst);- fixture.allow_start.notify_one();- assert!(start_globe_with_client(- &crate::core::runtime::DispatchCtx::default(),- client,- Push,- &CancellationToken::new()- )- .await- .is_err());- tokio::time::timeout(- std::time::Duration::from_secs(5),- fixture.stopped.notified(),- )- .await- .unwrap();- assert_eq!(fixture.closes.load(std::sync::atomic::Ordering::SeqCst), 1);-}--#[cfg(feature = "modules")]-async fn failed_close_retains_ownership_until_the_module_confirms_cleanup_fixture() {- let (client, fixture, _service) = listener_fixture().await;- fixture- .fail_close- .store(true, std::sync::atomic::Ordering::SeqCst);- fixture.allow_start.notify_one();- let (handle, _rx) = start_globe_with_client(- &crate::core::runtime::DispatchCtx::default(),- client,- Push,- &CancellationToken::new(),- )- .await- .unwrap();- handle.stop().await;- assert_eq!(fixture.closes.load(std::sync::atomic::Ordering::SeqCst), 1);-}--// Each fixture owns the process-wide Globe admission lock and its cleanup tasks.-// Separate processes prevent paused-clock fixtures from timing out on another-// fixture's in-flight cleanup, and runtime teardown cannot strand a shared lock.-#[cfg(feature = "modules")]-fn run_lifecycle_fixture(name: &str, fixture: impl std::future::Future<Output = ()>) {- const CHILD_ENV: &str = "OPENHUMAN_HOTKEY_LIFECYCLE_FIXTURE";- if std::env::var(CHILD_ENV).as_deref() == Ok(name) {- tokio::runtime::Builder::new_current_thread()- .enable_all()- .start_paused(- name == "failed_close_retains_ownership_until_the_module_confirms_cleanup",- )- .build()- .unwrap()- .block_on(fixture);- return;- }- let output = std::process::Command::new(std::env::current_exe().unwrap())- .args(["--exact", "--nocapture"])- .env(CHILD_ENV, name)- .arg(format!("voice::server::hotkey_listener::tests::{name}"))- .output()- .unwrap();- assert!(- output.status.success() && String::from_utf8_lossy(&output.stdout).contains("1 passed"),- "lifecycle fixture failed: {}{}",- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr),- );-}--#[cfg(feature = "modules")]-#[test]-fn cancelling_startup_still_closes_the_module_owned_listener() {- run_lifecycle_fixture(- "cancelling_startup_still_closes_the_module_owned_listener",- cancelling_startup_still_closes_the_module_owned_listener_fixture(),- );-}--#[cfg(feature = "modules")]-#[test]-fn stopping_listener_joins_its_bus_cleanup() {- run_lifecycle_fixture(- "stopping_listener_joins_its_bus_cleanup",- stopping_listener_joins_its_bus_cleanup_fixture(),- );-}--#[cfg(feature = "modules")]-#[test]-fn lost_start_reply_recovers_the_lease_before_releasing_admission() {- run_lifecycle_fixture(- "lost_start_reply_recovers_the_lease_before_releasing_admission",- lost_start_reply_recovers_the_lease_before_releasing_admission_fixture(),- );-}--#[cfg(feature = "modules")]-#[test]-fn failed_close_retains_ownership_until_the_module_confirms_cleanup() {- run_lifecycle_fixture(- "failed_close_retains_ownership_until_the_module_confirms_cleanup",- failed_close_retains_ownership_until_the_module_confirms_cleanup_fixture(),- );-}diff --git a/crates/openhuman-core/src/voice/server/pipeline.rs b/crates/openhuman-core/src/voice/server/pipeline.rsdeleted file mode 100644index 011b5e2505..0000000000--- a/crates/openhuman-core/src/voice/server/pipeline.rs+++ /dev/null@@ -1,315 +0,0 @@-//! 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;--use crate::config::Config;-use crate::modules::accessibility::{AccessibilityClient, FocusTarget, PasteRequest};-use crate::modules::voice::{- gate_recording, is_hallucinated, GateVerdict, HallucinationMode, RecordingGates, SessionInput,-};-use crate::voice::audio_capture::RecordingHandle;--use super::recorder::Recorder;-use super::types::{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) async fn capture_expected_app_name(config: &Config) -> Option<String> {- match AccessibilityClient::new(config)- .focus(crate::modules::accessibility::FocusQuery { verbose: true })- .await- {- 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) async fn capture_expected_app_name(_config: &Config) -> 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,- recorder: Recorder,- transcription_count: 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}");- recorder- .advance(config, SessionInput::Transcribing { generation })- .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()- );-- // Gates 1 and 2 (minimum duration, silence) run in the module.- //- // Falls OPEN when the module cannot be reached, for the same- // reason as the hallucination gate below.- let gates = RecordingGates {- min_duration_secs: server_config.min_duration_secs,- silence_threshold: server_config.silence_threshold,- };- match gate_recording(config, result.duration_secs, result.peak_rms, gates).await {- Ok(GateVerdict::Pass) => {}- Ok(verdict) => {- warn!(- "{LOG_PREFIX} [pipeline={pipeline_id}] stage=gate_recording DROPPED verdict={verdict:?} duration={:.1}s peak_rms={:.6}",- result.duration_secs, result.peak_rms- );- recorder- .advance(config, SessionInput::Finished { generation })- .await;- return;- }- Err(error) => warn!(- "{LOG_PREFIX} [pipeline={pipeline_id}] stage=gate_recording UNAVAILABLE ({error}); passing recording through"- ),- }-- // 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)- );- recorder- .advance(config, SessionInput::Finished { generation })- .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) = AccessibilityClient::new(config)- .paste(PasteRequest {- text: text.to_string(),- target: FocusTarget {- app: expected_app.clone(),- ..Default::default()- },- })- .await- {- warn!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=deliver_paste FAILED: {e}");- *last_error.lock().await = Some(e.to_string());- } 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()- );- recorder- .advance(config, SessionInput::Finished { generation })- .await;-}--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/voice/server/recorder.rs b/crates/openhuman-core/src/voice/server/recorder.rsdeleted file mode 100644index 5efdfb1e9f..0000000000--- a/crates/openhuman-core/src/voice/server/recorder.rs+++ /dev/null@@ -1,63 +0,0 @@-//! Host handle on the module-owned hotkey -> record -> finish state machine.-//!-//! The phase, generation guard and setup / stop-intent buffering live in the-//! `tinyvoice` module (`SessionOpen` / `SessionAdvance`). This wrapper only-//! reports facts to it, mirrors the phase it answers with so `status()` needs-//! no bus call, and serialises the call and the mirror write so two tasks-//! cannot leave the mirror behind the module.--use std::sync::Arc;--use log::{debug, warn};-use tokio::sync::Mutex;--use crate::config::Config;-use crate::modules::voice::{RecorderSession, SessionAdvance, SessionInput};--use super::types::ServerState;-use super::LOG_PREFIX;--/// A recording session plus the phase mirror it keeps current.-#[derive(Clone)]-pub(super) struct Recorder {- session: RecorderSession,- state: Arc<Mutex<ServerState>>,-}--impl Recorder {- pub(super) fn new(session: RecorderSession, state: Arc<Mutex<ServerState>>) -> Self {- Self { session, state }- }-- /// Report `input`; `None` when the module could not be reached or the- /// session is gone. A failure is logged, never fatal: a stale pipeline- /// finishing after the server stopped lands here by design.- pub(super) async fn advance(- &self,- config: &Config,- input: SessionInput,- ) -> Option<SessionAdvance> {- let mut state = self.state.lock().await;- match self.session.advance(config, input).await {- Ok(reply) => {- debug!(- "{LOG_PREFIX} session input={input:?} accepted={} phase={:?} generation={} action={:?}",- reply.accepted, reply.phase, reply.generation, reply.action- );- *state = reply.phase.into();- Some(reply)- }- Err(error) => {- warn!("{LOG_PREFIX} session input={input:?} failed: {error}");- None- }- }- }-- /// Release the module-side session.- pub(super) async fn close(&self, config: &Config) {- if let Err(error) = self.session.close(config).await {- warn!("{LOG_PREFIX} closing the recording session failed: {error}");- }- }-}diff --git a/crates/openhuman-core/src/voice/server/runtime.rs b/crates/openhuman-core/src/voice/server/runtime.rsdeleted file mode 100644index 3a5ae91898..0000000000--- a/crates/openhuman-core/src/voice/server/runtime.rs+++ /dev/null@@ -1,413 +0,0 @@-//! The voice server runtime: owns the hotkey event loop that turns-//! press/release events into recordings, and hands each finished recording-//! off to the background pipeline. The state machine deciding what each event-//! means lives in the `tinyvoice` module; this loop reports facts to it-//! (`SessionAdvance`) and performs the action it answers with.--use std::sync::atomic::Ordering;-use std::sync::Arc;--use log::{debug, info, warn};-use tokio::sync::Mutex;-use tokio_util::sync::CancellationToken;-use uuid::Uuid;--use crate::config::Config;-use crate::modules::voice::{RecorderSession, SessionAction, SessionInput};-use crate::voice::audio_capture::{self, RecordingHandle};-use tinyvoice_bus::hotkey::{ActivationMode, HotkeyEvent};--use super::hotkey_listener::start_hotkey_listener;-use super::pipeline::{capture_expected_app_name, process_recording_bg};-use super::recorder::Recorder;-use super::types::{ServerState, VoiceServerConfig, VoiceServerStatus};-use super::LOG_PREFIX;--type RecordingSetupReceiver =- tokio::sync::oneshot::Receiver<Result<(RecordingHandle, Option<String>), String>>;--/// The voice server runtime.-pub struct VoiceServer {- /// Mirror of the module-owned session phase; see [`Recorder`].- state: Arc<Mutex<ServerState>>,- /// The live session, present only while `run()` is active.- recorder: Mutex<Option<Recorder>>,- /// Wrapped in a Mutex so `run()` can replace it with a fresh token after- /// `stop()` — a `CancellationToken` cannot be un-cancelled.- cancel: Mutex<CancellationToken>,- config: VoiceServerConfig,- transcription_count: Arc<std::sync::atomic::AtomicU64>,- last_error: Arc<Mutex<Option<String>>>,- /// Rolling buffer of recent transcriptions used as STT context for- /// better continuity across consecutive recordings.- recent_transcripts: Arc<Mutex<Vec<String>>>,-}--impl VoiceServer {- pub fn new(config: VoiceServerConfig) -> Self {- Self {- state: Arc::new(Mutex::new(ServerState::Stopped)),- recorder: Mutex::new(None),- cancel: Mutex::new(CancellationToken::new()),- config,- transcription_count: Arc::new(std::sync::atomic::AtomicU64::new(0)),- last_error: Arc::new(Mutex::new(None)),- recent_transcripts: Arc::new(Mutex::new(Vec::new())),- }- }-- /// Get the current server status.- pub async fn status(&self) -> VoiceServerStatus {- VoiceServerStatus {- state: *self.state.lock().await,- hotkey: self.config.hotkey.clone(),- activation_mode: self.config.activation_mode,- transcription_count: self.transcription_count.load(Ordering::Relaxed),- last_error: self.last_error.lock().await.clone(),- }- }-- /// Run the voice server. Blocks until stopped.- ///- /// This is the main entry point for both embedded and standalone modes.- pub async fn run(- &self,- ctx: &crate::core::runtime::DispatchCtx,- app_config: &Config,- ) -> Result<(), String> {- // Atomically transition Stopped → Idle to prevent concurrent run() calls.- // The globe listener compilation can take several seconds; without this- // guard the RPC handler sees "Stopped" and spawns a duplicate run().- //- // Also replace the cancellation token with a fresh one — a cancelled- // token cannot be reused (stop() cancels it permanently).- let (cancel, recorder) = {- // Lock cancel FIRST, then state — same order as stop() — to- // prevent a race where stop() cancels the old token between- // setting Idle and swapping the token.- let mut cancel_guard = self.cancel.lock().await;- let mut state = self.state.lock().await;- if *state != ServerState::Stopped {- return Err(format!("voice server already running (state={:?})", *state));- }-- let session = RecorderSession::open(app_config)- .await- .map_err(|e| format!("could not open the recording session: {e}"))?;- match session.advance(app_config, SessionInput::Run).await {- Ok(reply) if reply.accepted => *state = reply.phase.into(),- other => {- let _ = session.close(app_config).await;- return Err(format!("recording session refused to start: {other:?}"));- }- }-- let fresh = CancellationToken::new();- *cancel_guard = fresh.clone();- let recorder = Recorder::new(session, self.state.clone());- *self.recorder.lock().await = Some(recorder.clone());- (fresh, recorder)- };-- info!(- "{LOG_PREFIX} starting voice server: hotkey={} mode={:?}",- self.config.hotkey, self.config.activation_mode- );-- // On macOS, the Fn/Globe key is intercepted by the system before- // rdev's CGEventTap can see it. Use the Swift-based globe listener- // instead, which monitors NSEvent.flagsChanged for the .function flag.- let (listener_handle, mut hotkey_rx) = match start_hotkey_listener(- ctx,- app_config,- &self.config.hotkey,- self.config.activation_mode,- &cancel,- )- .await- {- Ok(pair) => pair,- Err(e) => {- self.shut_session(app_config, &recorder).await;- return Err(e);- }- };-- info!("{LOG_PREFIX} voice server ready, listening for hotkey");-- let mut recording: Option<RecordingHandle> = None;- let mut recording_expected_app: Option<String> = None;-- // Pending recording setup: `start_recording()` runs on a blocking- // thread so the event loop stays responsive to Release events that- // macOS fires almost immediately for the Fn key.- let mut recording_pending_rx: Option<RecordingSetupReceiver> = None;- // Deferred stop deadline, set when the module answers `DeferStop`- // because a stop intent arrived during setup. Keeping this in a- // select! branch avoids blocking the hotkey loop.- let mut deferred_stop_deadline: Option<tokio::time::Instant> = None;-- loop {- // Build a future that resolves when the pending recording setup- // completes, or never if there is no pending setup.- let pending_ready = async {- match recording_pending_rx.as_mut() {- Some(rx) => rx.await,- None => std::future::pending().await,- }- };- let deferred_stop_ready = async {- match deferred_stop_deadline {- Some(deadline) => tokio::time::sleep_until(deadline).await,- None => std::future::pending().await,- }- };-- tokio::select! {- ev = hotkey_rx.recv() => {- let event = match ev {- Some(e) => e,- None => {- warn!("{LOG_PREFIX} hotkey channel closed");- break;- }- };-- // Forward hotkey event to the dictation bus so Socket.IO- // clients receive dictation:toggle events even when the- // dictation_listener is not running (single TinyVoice listener).- {- use crate::voice::dictation_listener;- let event_type = match event {- HotkeyEvent::Pressed => "pressed",- HotkeyEvent::Released => "released",- };- dictation_listener::publish_dictation_event(- dictation_listener::DictationEvent {- event_type: event_type.to_string(),- hotkey: self.config.hotkey.clone(),- activation_mode: match self.config.activation_mode {- ActivationMode::Tap => "toggle".to_string(),- ActivationMode::Push => "push".to_string(),- },- },- );- }-- let input = match event {- HotkeyEvent::Pressed => SessionInput::Pressed,- HotkeyEvent::Released => SessionInput::Released,- };- info!(- "{LOG_PREFIX} received hotkey event={event:?} recording={} pending={}",- recording.is_some(),- recording_pending_rx.is_some()- );- let Some(reply) = recorder.advance(app_config, input).await else {- continue;- };- match reply.action {- SessionAction::StartRecording { generation } => {- debug!("{LOG_PREFIX} hotkey pressed → starting recording generation={generation} (non-blocking)");- deferred_stop_deadline = None;-- // Start recording on a blocking thread so the- // event loop remains responsive to Release.- let (tx, rx) = tokio::sync::oneshot::channel();- let capture_config = app_config.clone();- ctx.spawn(async move {- let expected_app = capture_expected_app_name(&capture_config).await;- let result = audio_capture::start_recording(&capture_config).await- .map(|handle| (handle, expected_app));- let _ = tx.send(result);- });- recording_pending_rx = Some(rx);- }- SessionAction::StopRecording { generation } => {- deferred_stop_deadline = None;- if let Some(handle) = recording.take() {- debug!("{LOG_PREFIX} hotkey stop → stopping recording generation={generation}");- self.spawn_process_recording(- ctx,- handle,- app_config,- &recorder,- generation,- recording_expected_app.take(),- );- }- }- SessionAction::None- | SessionAction::RecordingLive { .. }- | SessionAction::DeferStop { .. } => {}- }- }-- result = pending_ready => {- // Recording setup completed (or failed).- recording_pending_rx = None;- match result {- Ok(Ok((handle, expected_app))) => {- // A hotkey event queued behind the setup result lost- // the select! race against `pending_ready` (on warm- // CPAL init both are ready at once). Either kind is- // a stop intent; the module decides what it means.- let stop_buffered = hotkey_rx.try_recv().is_ok();- if stop_buffered {- info!("{LOG_PREFIX} recording handle ready — found a buffered hotkey event (select! race recovered)");- }- match recorder- .advance(app_config, SessionInput::SetupReady { stop_buffered })- .await- {- Some(reply) if reply.accepted => {- recording = Some(handle);- recording_expected_app = expected_app;- match reply.action {- SessionAction::DeferStop { after_ms, .. } => {- info!("{LOG_PREFIX} deferred stop: recording for at least {after_ms}ms");- deferred_stop_deadline = Some(- tokio::time::Instant::now()- + std::time::Duration::from_millis(after_ms),- );- }- _ => {- deferred_stop_deadline = None;- info!("{LOG_PREFIX} recording started (live)");- }- }- }- _ => {- // The session moved on (stopped, or the module- // is unreachable): this recording has no owner.- warn!("{LOG_PREFIX} recording setup result not accepted; dropping the recording");- drop(handle);- }- }- }- Ok(Err(e)) => {- deferred_stop_deadline = None;- warn!("{LOG_PREFIX} failed to start recording: {e}");- recorder.advance(app_config, SessionInput::SetupFailed).await;- *self.last_error.lock().await = Some(e);- }- Err(_) => {- deferred_stop_deadline = None;- warn!("{LOG_PREFIX} recording setup task dropped");- recorder.advance(app_config, SessionInput::SetupFailed).await;- }- }- }-- _ = deferred_stop_ready => {- deferred_stop_deadline = None;- if let Some(reply) = recorder- .advance(app_config, SessionInput::DeferredStopElapsed)- .await- {- if let SessionAction::StopRecording { generation } = reply.action {- if let Some(handle) = recording.take() {- info!("{LOG_PREFIX} deferred stop deadline reached, stopping recording");- self.spawn_process_recording(- ctx,- handle,- app_config,- &recorder,- generation,- recording_expected_app.take(),- );- }- }- }- }-- _ = cancel.cancelled() => {- debug!("{LOG_PREFIX} cancellation received");- break;- }- }- }-- listener_handle.stop().await;- self.shut_session(app_config, &recorder).await;- info!("{LOG_PREFIX} voice server stopped");-- Ok(())- }-- /// Stop the module-side session (invalidating in-flight pipelines), close- /// it, and leave the mirrored state `Stopped`.- async fn shut_session(&self, config: &Config, recorder: &Recorder) {- recorder.advance(config, SessionInput::Stop).await;- recorder.close(config).await;- *self.recorder.lock().await = None;- // The module may have been unreachable; the server is stopped either way.- *self.state.lock().await = ServerState::Stopped;- }-- /// Stop the voice server and wait for it to reach `Stopped` state.- ///- /// Cancels the run-loop token and polls until the state transitions to- /// `Stopped` (or a 5-second timeout expires). This prevents a fast- /// logout → login cycle from seeing a stale `Idle`/`Recording` state- /// and skipping the restart.- pub async fn stop(&self) {- info!("{LOG_PREFIX} stopping voice server");- self.cancel.lock().await.cancel();-- // Wait for the run-loop to observe cancellation and set Stopped.- for _ in 0..50 {- if *self.state.lock().await == ServerState::Stopped {- return;- }- tokio::time::sleep(std::time::Duration::from_millis(100)).await;- }- warn!("{LOG_PREFIX} stop timed out after 5s — state may not be Stopped");- }-- /// Record an error message so it can be surfaced via status().- pub async fn set_last_error(&self, msg: &str) {- *self.last_error.lock().await = Some(msg.to_string());- }-- /// Spawn `process_recording` as a background task so the hotkey event- /// loop is not blocked during transcription. This ensures rapid- /// consecutive Fn presses are never missed.- fn spawn_process_recording(- &self,- ctx: &crate::core::runtime::DispatchCtx,- handle: RecordingHandle,- config: &Config,- recorder: &Recorder,- generation: u64,- expected_app: Option<String>,- ) {- let pipeline_id = Uuid::new_v4().to_string()[..8].to_string();- let server_config = self.config.clone();- let transcription_count = self.transcription_count.clone();- let recorder = recorder.clone();- let last_error = self.last_error.clone();- let recent_transcripts = self.recent_transcripts.clone();- let app_config = config.clone();-- info!(- "{LOG_PREFIX} [pipeline={pipeline_id}] spawning process_recording (generation={generation})"- );-- ctx.spawn(async move {- process_recording_bg(- &pipeline_id,- handle,- &app_config,- &server_config,- recorder,- transcription_count,- generation,- last_error,- recent_transcripts,- expected_app,- )- .await;- });- }-}diff --git a/crates/openhuman-core/src/voice/server/singleton.rs b/crates/openhuman-core/src/voice/server/singleton.rsdeleted file mode 100644index 86f3261084..0000000000--- a/crates/openhuman-core/src/voice/server/singleton.rs+++ /dev/null@@ -1,117 +0,0 @@-//! The process-global voice server singleton, plus the embedded auto-start-//! and standalone (CLI) entry points that create/drive it.--use std::sync::Arc;--use log::{info, warn};--use crate::config::Config;-use tinyvoice_bus::hotkey::ActivationMode;--use super::runtime::VoiceServer;-use super::types::{ServerState, VoiceServerConfig};-use super::LOG_PREFIX;--/// Global voice server instance, lazily initialized.-static VOICE_SERVER: once_cell::sync::OnceCell<Arc<VoiceServer>> = once_cell::sync::OnceCell::new();--/// Get or initialize the global voice server instance.-pub fn global_server(config: VoiceServerConfig) -> Arc<VoiceServer> {- VOICE_SERVER- .get_or_init(|| Arc::new(VoiceServer::new(config)))- .clone()-}--/// Get the global voice server if already initialized.-pub fn try_global_server() -> Option<Arc<VoiceServer>> {- VOICE_SERVER.get().cloned()-}--/// Start the embedded global voice server when config enables auto-start.-///-/// This is intended for core process startup. The server runs in the background-/// and reuses the process-global singleton so RPC status/stop calls continue to-/// operate on the same instance.-pub async fn start_if_enabled(ctx: &crate::core::runtime::DispatchCtx, app_config: &Config) {- if !app_config.components.voice {- info!("{LOG_PREFIX} [components].voice is off, skipping embedded voice server");- return;- }- if !app_config.voice_server.auto_start {- info!("{LOG_PREFIX} auto-start disabled in config, skipping embedded voice server");- return;- }-- let server_config = VoiceServerConfig {- hotkey: app_config.voice_server.hotkey.clone(),- activation_mode: match app_config.voice_server.activation_mode {- crate::config::VoiceActivationMode::Tap => ActivationMode::Tap,- crate::config::VoiceActivationMode::Push => ActivationMode::Push,- },- skip_cleanup: app_config.voice_server.skip_cleanup,- context: None,- min_duration_secs: app_config.voice_server.min_duration_secs,- silence_threshold: app_config.voice_server.silence_threshold,- custom_dictionary: app_config.voice_server.custom_dictionary.clone(),- };-- if let Some(existing) = try_global_server() {- let status = existing.status().await;- if status.state != ServerState::Stopped {- info!(- "{LOG_PREFIX} embedded voice server already running: hotkey={} mode={:?}",- status.hotkey, status.activation_mode- );- return;- }- }-- info!(- "{LOG_PREFIX} auto-start enabled, launching embedded voice server: hotkey={} mode={:?}",- server_config.hotkey, server_config.activation_mode- );-- let server = global_server(server_config);- let config_for_run = app_config.clone();- let server_for_err = server.clone();- let run_ctx = ctx.clone();- tokio::spawn(async move {- if let Err(e) = server.run(&run_ctx, &config_for_run).await {- warn!("{LOG_PREFIX} embedded voice server exited with error: {e}");- server_for_err.set_last_error(&e).await;- }- });-}--/// Run the voice server standalone (blocking). Intended for CLI usage.-///-/// Creates a fresh `VoiceServer` that is **not** registered in the global-/// singleton used by `voice_server_status` RPC. This keeps CLI-started-/// instances isolated from the core RPC lifecycle.-pub async fn run_standalone(- ctx: &crate::core::runtime::DispatchCtx,- app_config: Config,- server_config: VoiceServerConfig,-) -> Result<(), String> {- info!("{LOG_PREFIX} starting standalone voice server");- info!("{LOG_PREFIX} hotkey: {}", server_config.hotkey);- info!("{LOG_PREFIX} mode: {:?}", server_config.activation_mode);- info!("{LOG_PREFIX} press the hotkey to start dictating");-- let server = VoiceServer::new(server_config);-- // Handle Ctrl+C gracefully.- let server_arc = Arc::new(server);- let server_for_signal = server_arc.clone();-- tokio::spawn(async move {- if let Ok(()) = tokio::signal::ctrl_c().await {- info!("{LOG_PREFIX} Ctrl+C received, shutting down");- server_for_signal.stop().await;- }- });-- // This is safe because we hold the Arc and nothing else moves it.- // The server.run() borrows &self, and we await it to completion.- server_arc.run(ctx, &app_config).await-}diff --git a/crates/openhuman-core/src/voice/server/types.rs b/crates/openhuman-core/src/voice/server/types.rsdeleted file mode 100644index daa4e50e34..0000000000--- a/crates/openhuman-core/src/voice/server/types.rs+++ /dev/null@@ -1,84 +0,0 @@-//! Wire and config types for the voice server: run state, status snapshot,-//! and the tunables that shape a recording → transcription pass.--use tinyvoice_bus::hotkey::ActivationMode;--/// Running state of the voice server.-#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum ServerState {- /// Server is not running.- Stopped,- /// Server is running and idle, waiting for hotkey.- Idle,- /// Actively recording audio.- Recording,- /// Transcribing recorded audio.- Transcribing,-}--impl From<crate::modules::voice::SessionPhase> for ServerState {- fn from(phase: crate::modules::voice::SessionPhase) -> Self {- use crate::modules::voice::SessionPhase;- match phase {- SessionPhase::Stopped => Self::Stopped,- SessionPhase::Idle => Self::Idle,- SessionPhase::Recording => Self::Recording,- SessionPhase::Transcribing => Self::Transcribing,- }- }-}--/// Status snapshot of the voice server.-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]-pub struct VoiceServerStatus {- pub state: ServerState,- pub hotkey: String,- pub activation_mode: ActivationMode,- pub transcription_count: u64,- pub last_error: Option<String>,-}--/// Default silence threshold (RMS energy). Recordings with peak RMS below-/// this are considered silent and skipped. Matches OpenWhispr's 0.002 default.-pub(super) const DEFAULT_SILENCE_THRESHOLD: f32 = 0.002;--/// Maximum number of recent transcriptions to keep as context for the STT engine's-/// initial_prompt, improving continuity across consecutive recordings.-pub(super) const MAX_RECENT_TRANSCRIPTS: usize = 5;--/// Maximum character length of the combined initial prompt (dictionary +-/// recent transcripts). The prompt token budget is limited.-pub(super) const MAX_INITIAL_PROMPT_CHARS: usize = 500;--/// Configuration for the voice server.-#[derive(Debug, Clone)]-pub struct VoiceServerConfig {- pub hotkey: String,- pub activation_mode: ActivationMode,- /// Skip LLM post-processing on transcriptions.- pub skip_cleanup: bool,- /// Optional conversation context for better transcription accuracy.- pub context: Option<String>,- /// Minimum recording duration in seconds. Shorter recordings are discarded.- pub min_duration_secs: f32,- /// RMS energy threshold for silence detection. Recordings with peak- /// energy below this are treated as silence and skipped.- pub silence_threshold: f32,- /// Custom vocabulary words to bias the STT engine toward (passed as initial_prompt).- pub custom_dictionary: Vec<String>,-}--impl Default for VoiceServerConfig {- fn default() -> Self {- Self {- hotkey: "Fn".to_string(),- activation_mode: ActivationMode::Push,- skip_cleanup: false,- context: None,- min_duration_secs: 0.3,- silence_threshold: DEFAULT_SILENCE_THRESHOLD,- custom_dictionary: Vec::new(),- }- }-}diff --git a/crates/openhuman-core/src/voice/server_tests.rs b/crates/openhuman-core/src/voice/server_tests.rsdeleted file mode 100644index 8021be6241..0000000000--- a/crates/openhuman-core/src/voice/server_tests.rs+++ /dev/null@@ -1,190 +0,0 @@-use super::*;-use crate::voice::server::types::{MAX_INITIAL_PROMPT_CHARS, MAX_RECENT_TRANSCRIPTS};--#[test]-fn default_server_config() {- let cfg = VoiceServerConfig::default();- assert_eq!(cfg.hotkey, "Fn");- assert_eq!(cfg.activation_mode, ActivationMode::Push);- assert!(!cfg.skip_cleanup);- assert!(cfg.context.is_none());- assert!(cfg.custom_dictionary.is_empty());- assert!((cfg.silence_threshold - DEFAULT_SILENCE_THRESHOLD).abs() < 1e-6);-}--#[tokio::test]-async fn server_status_initial() {- let server = VoiceServer::new(VoiceServerConfig::default());- let status = server.status().await;- assert_eq!(status.state, ServerState::Stopped);- assert_eq!(status.transcription_count, 0);- assert!(status.last_error.is_none());-}--#[test]-fn server_state_follows_the_module_session_phase() {- use crate::modules::voice::SessionPhase;- assert_eq!(- ServerState::from(SessionPhase::Stopped),- ServerState::Stopped- );- assert_eq!(ServerState::from(SessionPhase::Idle), ServerState::Idle);- assert_eq!(- ServerState::from(SessionPhase::Recording),- ServerState::Recording- );- assert_eq!(- ServerState::from(SessionPhase::Transcribing),- ServerState::Transcribing- );-}--#[test]-fn server_state_serializes() {- let json = serde_json::to_string(&ServerState::Recording).unwrap();- assert_eq!(json, "\"recording\"");-}--#[test]-fn voice_server_status_serializes() {- let status = VoiceServerStatus {- state: ServerState::Idle,- hotkey: "Fn".into(),- activation_mode: ActivationMode::Push,- transcription_count: 5,- last_error: None,- };- let v = serde_json::to_value(&status).unwrap();- assert_eq!(v["state"], "idle");- assert_eq!(v["transcription_count"], 5);-}--#[test]-fn truncate_for_log_short() {- assert_eq!(truncate_for_log("hello", 10), "hello");-}--#[test]-fn truncate_for_log_long() {- let result = truncate_for_log("hello world this is long", 10);- assert!(result.ends_with("..."));- assert!(result.len() <= 14); // 10 + "..."-}--#[tokio::test]-async fn build_initial_prompt_combines_dictionary_and_recent_transcripts() {- let config = VoiceServerConfig {- custom_dictionary: vec!["OpenHuman".into(), "QuickJS".into()],- ..VoiceServerConfig::default()- };- let recent = Mutex::new(vec!["first note".into(), "second note".into()]);-- let prompt = build_initial_prompt(&config, &recent)- .await- .expect("prompt should be built");-- assert!(prompt.contains("OpenHuman, QuickJS"));- assert!(prompt.contains("first note second note"));-}--#[tokio::test]-async fn build_initial_prompt_truncates_on_char_boundary() {- let repeated = "é".repeat(MAX_INITIAL_PROMPT_CHARS + 25);- let config = VoiceServerConfig {- custom_dictionary: vec![repeated],- ..VoiceServerConfig::default()- };- let recent = Mutex::new(Vec::new());-- let prompt = build_initial_prompt(&config, &recent)- .await- .expect("prompt should be built");-- assert!(prompt.chars().count() <= MAX_INITIAL_PROMPT_CHARS);- assert!(std::str::from_utf8(prompt.as_bytes()).is_ok());-}--#[tokio::test]-async fn push_recent_transcript_ignores_blank_and_caps_history() {- let recent = Mutex::new(Vec::new());- push_recent_transcript(&recent, " ").await;- assert!(recent.lock().await.is_empty());-- for idx in 0..(MAX_RECENT_TRANSCRIPTS + 2) {- push_recent_transcript(&recent, &format!("line {idx}")).await;- }-- let values = recent.lock().await.clone();- assert_eq!(values.len(), MAX_RECENT_TRANSCRIPTS);- assert_eq!(values.first().unwrap(), "line 2");- assert_eq!(values.last().unwrap(), "line 6");-}--#[tokio::test]-async fn capture_expected_app_name_is_none_off_macos() {- if !cfg!(target_os = "macos") {- assert_eq!(- capture_expected_app_name(&crate::config::Config::default()).await,- None- );- }-}--#[tokio::test]-async fn process_recording_sets_last_error_when_stop_fails() {- let handle = RecordingHandle::from_test_result(Err("stop failed".to_string()));- let state = Arc::new(Mutex::new(ServerState::Recording));- let recorder = recorder::Recorder::new(- crate::modules::voice::RecorderSession::unopened_for_test(),- state,- );- let last_error = Arc::new(Mutex::new(None));-- process_recording_bg(- "test",- handle,- &Config::default(),- &VoiceServerConfig::default(),- recorder,- Arc::new(std::sync::atomic::AtomicU64::new(0)),- 1,- last_error.clone(),- Arc::new(Mutex::new(Vec::new())),- None,- )- .await;-- assert_eq!(last_error.lock().await.as_deref(), Some("stop failed"));-}--// ── truncate_for_log ───────────────────────────────────────────--#[test]-fn truncate_for_log_passes_through_short_strings() {- assert_eq!(truncate_for_log("hi", 10), "hi");- assert_eq!(truncate_for_log("", 10), "");-}--#[test]-fn truncate_for_log_appends_ellipsis_when_truncated() {- assert_eq!(truncate_for_log("abcdefghij", 5), "abcde...");-}--#[test]-fn truncate_for_log_handles_multibyte_chars() {- // Each "日" is multi-byte but one `char` — truncate by char count.- let out = truncate_for_log("日本語テスト", 3);- assert_eq!(out, "日本語...");-}--// ── try_global_server / global_server ─────────────────────────--#[tokio::test]-async fn try_global_server_returns_some_after_global_server_initialized() {- // `global_server` is OnceCell-backed; first call initialises it.- let _ = global_server(VoiceServerConfig::default());- assert!(try_global_server().is_some());-}--// ── ServerState transitions ───────────────────────────────────-// Initial-status coverage lives in `server_status_initial` above.