Skip to content

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

chore: files changed crates/openhuman-core/src/voice/always_on.rs,crates/openhuman-core/src/voice/al

Steven Enamakel751e3e6bd96c
diff --git a/crates/openhuman-core/src/voice/always_on.rs b/crates/openhuman-core/src/voice/always_on.rs
deleted file mode 100644
index 0d8e22a49e..0000000000
--- a/crates/openhuman-core/src/voice/always_on.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-//! Phase 2 — always-on listening.
-//!
-//! Instead of a hotkey gating each recording, always-on mode keeps the mic
-//! open continuously and uses **voice-activity detection** to carve the audio
-//! stream into utterances: an utterance opens when energy rises above an onset
-//! threshold and closes after a configurable run of silence (the "hangover").
-//! Each completed utterance is transcribed and pushed onto the dictation bus,
-//! so it reaches the agent and the notch exactly like a hotkey dictation.
-//!
-//! ## Where the work happens
-//!
-//! Device I/O, callback queues and audio processing run in the loaded TinyVoice
-//! module. The host polls bounded batches and owns configuration, permission,
-//! transcription routing, privacy gates and lifecycle cleanup.
-//!
-//! Privacy: always-on is **opt-in** (`config.voice_server.always_on_enabled`,
-//! default false) and pauses when the screen is locked.
-//!
-//! ## Module layout
-//!
-//! - [`capture`] — bounded bus forwarding and cancellation of the module stream.
-//! - [`lock_watcher`] — the macOS screen-lock privacy hook.
-//! - [`processor`] — the async pipeline: VAD session, segmentation, gating.
-//! - [`transcribe`] — STT, wake-word gating, and local fast-path commands.
-
-mod capture;
-mod lock_watcher;
-mod processor;
-mod transcribe;
-
-pub use processor::{shutdown, start_if_enabled, stop};
-
-use processor::notch_status;
-#[cfg(target_os = "macos")]
-use processor::PAUSED;
-
-#[cfg(test)]
-use crate::modules::voice as tinyvoice;
-#[cfg(test)]
-use processor::ENABLED;
-
-#[cfg(test)]
-#[path = "always_on_tests.rs"]
-mod tests;
-
-const LOG_PREFIX: &str = "[voice::always_on]";
diff --git a/crates/openhuman-core/src/voice/always_on/README.md b/crates/openhuman-core/src/voice/always_on/README.md
deleted file mode 100644
index 508bd3003c..0000000000
--- a/crates/openhuman-core/src/voice/always_on/README.md
+++ /dev/null
@@ -1,49 +0,0 @@
-# always_on
-
-Phase 2 of dictation: instead of a hotkey gating each recording, always-on mode keeps the microphone open continuously and uses voice-activity detection (VAD) to carve the audio stream into utterances. An utterance opens when energy rises above an onset threshold and closes after a configurable run of silence (the "hangover"). Each finished utterance is transcribed and pushed onto the dictation bus, so it reaches the agent and the notch pill exactly like a hotkey dictation.
-
-Always-on is opt-in (`config.voice_server.always_on_enabled`, default `false`) and pauses while the screen is locked, so nothing spoken at the lock screen is ever transcribed.
-
-## Where the work happens
-
-Device I/O, callback queues, segmentation and audio processing run in the compiled TinyVoice module. This directory owns microphone permission requests through TinyComputer, bounded batch forwarding, transcription routing, privacy gates and lease cleanup.
-
-The split follows the audio callback, not the cost of a call. A module call is about 15 microseconds against a 20 ms frame, so the bus is not the constraint. The constraint is that `cpal` delivers audio on a realtime thread where blocking is a dropout, so the callback does the least it can (convert the sample format and forward raw interleaved samples) and every transform happens in the async processor.
-
-## Key files
-
-| File | Role |
-| --- | --- |
-| [`capture.rs`](./capture.rs) | Reserves and starts a module-owned stream, polls at most two chunks per call, and forwards ordered batches through a bounded host queue. Cancellation releases the opaque lease; failed cleanup remains tracked for retry. |
-| [`lock_watcher.rs`](./lock_watcher.rs) | The macOS screen-lock privacy hook. `spawn_lock_watcher` polls `CGSessionCopyCurrentDictionary` every two seconds and flips `PAUSED` on lock/unlock transitions. Other platforms log that the watcher is unavailable and never pause (no lock signal yet). |
-| [`processor.rs`](./processor.rs) | Owns the enabled/paused gates, VAD session and transcription tasks. Toggle-off and sign-out stop capture, cancel pending transcriptions and drain the processor before restart. |
-| [`transcribe.rs`](./transcribe.rs) | Transcribes a finished utterance through the configured STT provider (the same factory dispatch `voice.stt_dispatch` uses), applies the wake-word gate (`tinyvoice::sequence_utterance`), and routes recognized commands either to a local fast path (`execute_intent`, media transport and volume via `osascript` on macOS) or, for `VoiceIntent::Unknown` or a failed local execution, to the agent via `crate::voice::dictation_listener::publish_transcription`. |
-
-`always_on.rs` (one level up, in `voice/`) is the module entry point: it declares these four submodules, re-exports `start_if_enabled`/`stop`, and holds the shared `LOG_PREFIX` constant.
-
-## Key types and constants
-
-- `capture::RawChunk` / `capture::CaptureFormat`: one chunk of raw, interleaved capture at the device's own sample rate and channel count, plus the format learned once when the stream is built.
-- `processor::ENABLED`, `processor::PAUSED`, `processor::RUNNING`: process-wide atomics gating capture, privacy, and single-instance start.
-- `processor::SESSION_RETRY_INTERVAL` (30s), `processor::CAPTURE_QUEUE_CHUNKS` (256), `processor::FRAME_MS` (20), `processor::MAX_UTTERANCE_SAMPLES` (60s worth of samples): tuning constants for VAD session retry, the capture channel's bounded queue, VAD frame size, and a defensive cap on a buffered utterance.
-- `transcribe::deliver_command` / `execute_intent`: fast-path routing for `VoiceIntent` (pause/resume/next/previous/volume/mute via AppleScript); anything unroutable defers to the agent.
-
-## Wake word and privacy
-
-Transcription is forced to English (`Some("en")`) because auto-detect rendered the wake word in non-Latin scripts that could never match. The wake-word gate fails closed: if `tinyvoice::sequence_utterance` errors, the utterance is dropped rather than delivered unaddressed to the agent. Logs never include the raw transcript or spoken command, only lengths and intent kinds, per the PII-safe logging rule.
-
-## Configuration
-
-- `config.voice_server.always_on_enabled` (bool, default `false`): the on/off switch, applied live by `start_if_enabled` without a restart.
-- `config.voice_server.wake_word` (string): the phrase that must prefix a command for it to reach the agent.
-- `config.voice_server.vad_*` fields (onset threshold, hangover, min speech, max utterance): mapped into `tinyvoice::VadTuning` by `tinyvoice::vad_config_from_server_config`.
-
-## Notes and gotchas
-
-- The microphone stream is spawned once per process and stays open for the process lifetime once started; toggling `always_on_enabled` off only stops processing, it does not close the stream. Toggling back on reuses it.
-- A VAD session that fails to open (for example, the module has not finished downloading) does not stop the capture thread. Audio is dropped and the open is retried on `SESSION_RETRY_INTERVAL` so the feature self-heals without a restart.
-- Native callbacks stay inside the module and never wait for bus calls. Its bounded queue drops newest chunks when full; the host polls bounded batches and preserves their order.
-
-## See also
-
-- [../README.md](../README.md): the voice domain overview, including the RPC surface and the dictation server that hotkey-based dictation uses.
diff --git a/crates/openhuman-core/src/voice/always_on/capture.rs b/crates/openhuman-core/src/voice/always_on/capture.rs
deleted file mode 100644
index d56f9bed56..0000000000
--- a/crates/openhuman-core/src/voice/always_on/capture.rs
+++ /dev/null
@@ -1,63 +0,0 @@
-//! Bounded batch forwarding from module-owned continuous microphone capture.
-use crate::config::Config;
-use crate::voice::capture_lease::{CaptureLease, Kind};
-pub(super) use tinyvoice_bus::capture::{CaptureFormat, RawChunk};
-static STOP: std::sync::LazyLock<tokio::sync::watch::Sender<u64>> =
- std::sync::LazyLock::new(|| tokio::sync::watch::channel(0).0);
-pub(super) fn stop_subscription() -> tokio::sync::watch::Receiver<u64> {
- STOP.subscribe()
-}
-pub(super) fn request_stop() {
- STOP.send_modify(|generation| *generation = generation.wrapping_add(1));
-}
-/// Owns the forwarding task; cancellation closes its opaque capture lease.
-pub(super) struct CapturePump(tokio::task::JoinHandle<()>);
-impl Drop for CapturePump {
- fn drop(&mut self) {
- self.0.abort();
- }
-}
-/// Start a module stream and forward ordered batches to the bounded processor queue.
-pub(super) async fn spawn_capture_thread(
- ctx: &crate::core::runtime::DispatchCtx,
- config: &Config,
- tx: tokio::sync::mpsc::Sender<RawChunk>,
-) -> Result<(CaptureFormat, CapturePump), String> {
- let lease = CaptureLease::reserve(config, Kind::Stream).await?;
- let stream = lease.start_stream().await?;
- let mut stopped = STOP.subscribe();
- let task = ctx.spawn(async move {
- loop {
- if tx.is_closed() {
- break;
- }
- let reply = tokio::select! {
- biased;
- _ = stopped.changed() => break,
- reply = lease.poll() => reply,
- };
- let batch = match reply {
- Ok(batch) => batch,
- Err(error) => {
- log::warn!("[voice::always_on] capture batch unavailable: {error}");
- break;
- }
- };
- for chunk in batch.chunks {
- tokio::select! {
- biased;
- _ = stopped.changed() => return,
- result = tx.send(chunk) => if result.is_err() { return; },
- }
- }
- if batch.closed {
- break;
- }
- tokio::time::sleep(std::time::Duration::from_millis(10)).await;
- }
- if let Err(error) = lease.close().await {
- log::warn!("[voice::always_on] capture cleanup pending: {error}");
- }
- });
- Ok((stream.format, CapturePump(task)))
-}
diff --git a/crates/openhuman-core/src/voice/always_on/lock_watcher.rs b/crates/openhuman-core/src/voice/always_on/lock_watcher.rs
deleted file mode 100644
index 7b4fd9311f..0000000000
--- a/crates/openhuman-core/src/voice/always_on/lock_watcher.rs
+++ /dev/null
@@ -1,109 +0,0 @@
-//! Screen-lock privacy hook: pauses always-on capture while the screen is
-//! locked so nothing spoken at the lock screen is ever transcribed.
-
-use super::LOG_PREFIX;
-#[cfg(target_os = "macos")]
-use super::PAUSED;
-#[cfg(target_os = "macos")]
-use std::sync::atomic::Ordering;
-
-/// Poll the screen-lock state and drive [`PAUSED`] so always-on never captures
-/// what is spoken at the lock screen. macOS-only for now (uses the Quartz
-/// session dictionary); other platforms never pause (no lock signal yet).
-pub(super) fn spawn_lock_watcher() {
- #[cfg(target_os = "macos")]
- tokio::spawn(async move {
- let mut last = false;
- loop {
- let locked = macos_lock::is_screen_locked();
- if locked != last {
- log::info!(
- "{LOG_PREFIX} screen {} → {}",
- if locked { "locked" } else { "unlocked" },
- if locked { "pausing" } else { "resuming" }
- );
- PAUSED.store(locked, Ordering::Relaxed);
- last = locked;
- }
- tokio::time::sleep(std::time::Duration::from_secs(2)).await;
- }
- });
- #[cfg(not(target_os = "macos"))]
- {
- log::info!("{LOG_PREFIX} screen-lock watcher unavailable on this platform");
- }
-}
-
-/// macOS screen-lock detection via the Quartz session dictionary.
-///
-/// `CGSessionCopyCurrentDictionary` exposes `CGSSessionScreenIsLocked`; we read
-/// it defensively (null dict ⇒ no session, treated as locked; missing/odd value
-/// ⇒ unlocked) and never assume the CF value's concrete type without checking.
-#[cfg(target_os = "macos")]
-mod macos_lock {
- use std::ffi::{c_void, CString};
-
- type CFTypeRef = *const c_void;
-
- #[link(name = "CoreGraphics", kind = "framework")]
- extern "C" {
- fn CGSessionCopyCurrentDictionary() -> CFTypeRef;
- }
- #[link(name = "CoreFoundation", kind = "framework")]
- extern "C" {
- fn CFDictionaryGetValue(dict: CFTypeRef, key: CFTypeRef) -> CFTypeRef;
- fn CFStringCreateWithCString(alloc: CFTypeRef, c: *const i8, enc: u32) -> CFTypeRef;
- fn CFGetTypeID(v: CFTypeRef) -> usize;
- fn CFBooleanGetTypeID() -> usize;
- fn CFBooleanGetValue(b: CFTypeRef) -> u8;
- fn CFNumberGetTypeID() -> usize;
- fn CFNumberGetValue(n: CFTypeRef, the_type: i64, out: *mut c_void) -> u8;
- fn CFRelease(v: CFTypeRef);
- }
- const KCF_STRING_ENCODING_UTF8: u32 = 0x0800_0100;
- const KCF_NUMBER_SINT32: i64 = 3;
-
- /// True when the screen is locked (or there is no active GUI session).
- pub fn is_screen_locked() -> bool {
- // SAFETY: standard Quartz/CoreFoundation calls. Ownership: the session
- // dict and the key string are +1 (Create/Copy) and released here; the
- // dictionary value is borrowed and must not be released.
- unsafe {
- let dict = CGSessionCopyCurrentDictionary();
- if dict.is_null() {
- return true; // no session (loginwindow) — treat as locked
- }
- let Ok(key_c) = CString::new("CGSSessionScreenIsLocked") else {
- CFRelease(dict);
- return false;
- };
- let key = CFStringCreateWithCString(
- std::ptr::null(),
- key_c.as_ptr(),
- KCF_STRING_ENCODING_UTF8,
- );
- if key.is_null() {
- CFRelease(dict);
- return false;
- }
- let value = CFDictionaryGetValue(dict, key); // borrowed
- let locked = if value.is_null() {
- false
- } else {
- let tid = CFGetTypeID(value);
- if tid == CFBooleanGetTypeID() {
- CFBooleanGetValue(value) != 0
- } else if tid == CFNumberGetTypeID() {
- let mut n: i32 = 0;
- CFNumberGetValue(value, KCF_NUMBER_SINT32, &mut n as *mut i32 as *mut c_void);
- n != 0
- } else {
- false
- }
- };
- CFRelease(key);
- CFRelease(dict);
- locked
- }
- }
-}
diff --git a/crates/openhuman-core/src/voice/always_on/processor.rs b/crates/openhuman-core/src/voice/always_on/processor.rs
deleted file mode 100644
index 34e9b26163..0000000000
--- a/crates/openhuman-core/src/voice/always_on/processor.rs
+++ /dev/null
@@ -1,415 +0,0 @@
-//! The async processor: owns the on/off gates, opens the VAD session, turns
-//! raw capture chunks into segmented utterances, and hands finished
-//! utterances to transcription.
-
-use super::capture::{spawn_capture_thread, RawChunk};
-use super::lock_watcher::spawn_lock_watcher;
-use super::transcribe::transcribe_and_deliver;
-use super::LOG_PREFIX;
-use crate::config::Config;
-use crate::modules::voice as tinyvoice;
-use crate::voice::audio_capture::TARGET_SAMPLE_RATE;
-use std::sync::atomic::{AtomicBool, Ordering};
-
-/// How long to wait before retrying a VAD session that would not open.
-///
-/// Long enough that a persistently unavailable module does not produce a call
-/// per audio chunk, short enough that a module which finishes downloading
-/// mid-session starts segmenting without the user restarting anything.
-const SESSION_RETRY_INTERVAL: std::time::Duration = std::time::Duration::from_secs(30);
-
-/// How many raw capture chunks may queue for the processor.
-///
-/// The channel was unbounded, which was survivable when the callback did the
-/// downmix and resample itself: the processor's work was pure arithmetic and it
-/// always outran the microphone. It no longer does — each chunk now costs three
-/// module round trips — so a stalled or slow processor could let the queue grow
-/// without limit behind a producer that never blocks.
-///
-/// A few seconds of chunks at typical `cpal` buffer sizes. Deliberately a
-/// *count* rather than a byte budget: the callback must not do arithmetic to
-/// decide whether to send.
-const CAPTURE_QUEUE_CHUNKS: usize = 256;
-
-/// A module capture lease and processor are active.
-static RUNNING: AtomicBool = AtomicBool::new(false);
-static LIFECYCLE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
-static PROCESSOR: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>> =
- std::sync::Mutex::new(None);
-struct RunningGuard;
-impl Drop for RunningGuard {
- fn drop(&mut self) {
- RUNNING.store(false, Ordering::SeqCst);
- }
-}
-
-/// Runtime on/off, mirrors `config.voice_server.always_on_enabled`. Toggling it
-/// at runtime takes effect immediately: when false the processor drops all audio
-/// (nothing is transcribed or sent). Lets the Settings toggle work without a
-/// restart. Disabling capture releases the module stream.
-pub(super) static ENABLED: AtomicBool = AtomicBool::new(false);
-
-/// When true, the processor drops audio and resets the segmenter (privacy hook:
-/// screen locked). Driven by [`spawn_lock_watcher`] on macOS.
-pub(super) static PAUSED: AtomicBool = AtomicBool::new(false);
-
-/// VAD frame size. 20 ms at 16 kHz = 320 samples — small enough for responsive
-/// onset/hangover detection, large enough for a stable RMS estimate.
-const FRAME_MS: u32 = 20;
-const FRAME_SAMPLES: usize = (TARGET_SAMPLE_RATE as usize / 1000) * FRAME_MS as usize;
-
-/// Hard cap on a buffered utterance (defensive — the segmenter's
-/// `max_utterance_ms` should flush first; this bounds memory if it doesn't).
-const MAX_UTTERANCE_SAMPLES: usize = TARGET_SAMPLE_RATE as usize * 60;
-
-/// Apply the always-on config: set the runtime ENABLED gate and, when enabled,
-/// open the continuous microphone stream (once per process). Safe to call at
-/// boot **and** at runtime (the Settings toggle calls it via the config RPC):
-/// toggling off flips `ENABLED` so the processor immediately stops transcribing/
-/// delivering; toggling on starts capture live without a restart.
-///
-/// Opens a continuous mic stream, segments it through the `tinyvoice` module, and
-/// routes each finished utterance through STT and the dictation delivery bus (so
-/// it reaches the agent exactly like a hotkey dictation, and lights up the notch).
-pub async fn start_if_enabled(ctx: &crate::core::runtime::DispatchCtx, app_config: &Config) {
- if !app_config.components.voice {
- log::info!("{LOG_PREFIX} [components].voice is off — always-on stays down");
- shutdown().await;
- return;
- }
- if !app_config.voice_server.always_on_enabled {
- shutdown().await;
- return;
- }
- let _lifecycle = LIFECYCLE.lock().await;
- let on = app_config.voice_server.always_on_enabled;
- ENABLED.store(on, Ordering::SeqCst);
- if !on {
- log::info!("{LOG_PREFIX} disabled — capture idle (toggle off)");
- return;
- }
- if RUNNING.swap(true, Ordering::SeqCst) {
- log::info!("{LOG_PREFIX} re-enabled; capture already running");
- return;
- }
-
- let running = RunningGuard;
- if let Err(error) = crate::modules::accessibility::AccessibilityClient::new(app_config)
- .microphone_permission(false)
- .await
- {
- log::warn!("{LOG_PREFIX} could not authorize microphone capture: {error}");
- RUNNING.store(false, Ordering::SeqCst);
- return;
- }
- let vad = tinyvoice::vad_config_from_server_config(&app_config.voice_server);
- let config = app_config.clone();
- log::info!(
- "{LOG_PREFIX} enabled — onset={:.4} hangover={}ms min_speech={}ms max_utt={}ms",
- vad.onset_threshold,
- vad.hangover_ms,
- vad.min_speech_ms,
- vad.max_utterance_ms
- );
-
- let (tx, mut rx) = tokio::sync::mpsc::channel::<RawChunk>(CAPTURE_QUEUE_CHUNKS);
- let (format, pump) = match spawn_capture_thread(ctx, app_config, tx).await {
- Ok(stream) => stream,
- Err(error) => {
- log::warn!("{LOG_PREFIX} could not start microphone capture: {error}");
- return;
- }
- };
-
- // Privacy hook: pause capture while the screen is locked.
- spawn_lock_watcher();
-
- let onset_threshold = vad.onset_threshold;
- let mut stopped = super::capture::stop_subscription();
- let processor = ctx.spawn(async move {
- let _running = running;
- let _pump = pump;
- // The segmenter lives in the module now, so opening it can fail for
- // reasons unrelated to audio — a download that has not happened yet, a
- // host with no published artifact.
- //
- // Retain the known capture lease while retrying VAD setup. Cancellation
- // closes both the processor and its module-owned stream.
- let mut session: Option<tinyvoice::VadSession> = None;
- let mut last_open_attempt: Option<std::time::Instant> = None;
-
- let mut transcriptions = tokio::task::JoinSet::new();
- let mut pending: Vec<f32> = Vec::new();
- let mut utterance: Vec<f32> = Vec::new();
- // Test-build diagnostics: confirm audio actually flows from the mic and
- // surface live input levels vs the onset threshold (every ~5s) so the VAD
- // can be tuned per mic/room without guessing. Levels are loudness, not PII.
- let mut first_chunk_logged = false;
- let mut level_peak: f32 = 0.0;
- let mut level_frames: u32 = 0;
- let mut last_level_log = std::time::Instant::now();
-
- 'capture: while let Some(chunk) = tokio::select! {
- biased;
- _ = stopped.changed() => None,
- _ = transcriptions.join_next(), if !transcriptions.is_empty() => continue 'capture,
- chunk = rx.recv() => chunk,
- } {
- if !first_chunk_logged {
- first_chunk_logged = true;
- log::info!(
- "{LOG_PREFIX} first audio chunk received from mic (samples={}) — capture pipeline live",
- chunk.samples.len()
- );
- }
- // Drop audio and abandon any in-flight utterance while paused
- // (screen locked) or toggled off — nothing is captured or sent.
- if PAUSED.load(Ordering::Relaxed) || !ENABLED.load(Ordering::Relaxed) {
- // Reset unconditionally rather than checking `is_speaking`
- // first: that check would be a second bus call to save a cheap
- // idempotent one, and the privacy path should be the shortest
- // path, not the cleverest.
- if let Some(open) = session.as_ref() {
- if let Err(error) = open.reset(&config).await {
- // Same reasoning as a failed push: a reset that did not
- // land leaves a segmenter we cannot vouch for, and this
- // is the privacy path, so discard it rather than trust
- // it to have dropped the partial utterance.
- log::warn!(
- "{LOG_PREFIX} could not reset the VAD session ({error}); reopening"
- );
- session = None;
- last_open_attempt = Some(std::time::Instant::now());
- }
- }
- pending.clear();
- utterance.clear();
- continue;
- }
-
- // Open the segmenter on first use, retrying on a cooldown so a
- // module that becomes available later heals this without a restart.
- if session.is_none() {
- let due = last_open_attempt.is_none_or(|at| at.elapsed() >= SESSION_RETRY_INTERVAL);
- if !due {
- continue;
- }
- last_open_attempt = Some(std::time::Instant::now());
- match tinyvoice::VadSession::open(&config, vad).await {
- Ok(opened) => {
- log::info!("{LOG_PREFIX} VAD session open; segmenting live audio");
- session = Some(opened);
- }
- Err(error) => {
- log::warn!(
- "{LOG_PREFIX} could not open a VAD session ({error}); \
- dropping audio and retrying in {}s",
- SESSION_RETRY_INTERVAL.as_secs()
- );
- continue;
- }
- }
- }
-
- // Downmix + resample in the module. This is the work that used to
- // happen inside the cpal callback.
- let mono16k = match tinyvoice::prepare_frames(
- &config,
- &chunk.samples,
- format.source_rate,
- format.channels,
- )
- .await
- {
- Ok(samples) => samples,
- Err(error) => {
- log::warn!("{LOG_PREFIX} could not prepare capture frames: {error}");
- continue;
- }
- };
- pending.extend_from_slice(&mono16k);
-
- // Whole frames only; the remainder stays in `pending` for the next
- // chunk so no audio is dropped at a chunk boundary.
- let whole = pending.len() / FRAME_SAMPLES * FRAME_SAMPLES;
- if whole == 0 {
- continue;
- }
- // Measure BEFORE draining. Draining first and then failing would
- // discard the frames outright — a module hiccup would eat the
- // user's audio rather than delay it.
- let energies =
- match tinyvoice::frame_energies(&config, &pending[..whole], FRAME_SAMPLES as u32)
- .await
- {
- Ok(energies) => energies,
- Err(error) => {
- log::warn!(
- "{LOG_PREFIX} could not measure frame energies ({error}); \
- retrying these frames on the next chunk"
- );
- continue;
- }
- };
- let frames: Vec<f32> = pending.drain(..whole).collect();
-
- for rms in &energies {
- level_peak = level_peak.max(*rms);
- }
- level_frames += energies.len() as u32;
- if last_level_log.elapsed() >= std::time::Duration::from_secs(5) {
- log::info!(
- "{LOG_PREFIX} mic level peak_rms={level_peak:.4} onset={onset_threshold:.4} frames={level_frames} ({})",
- if level_peak >= onset_threshold {
- "speech would trigger"
- } else {
- "below onset — lower vad_onset_threshold or check mic gain"
- }
- );
- level_peak = 0.0;
- level_frames = 0;
- last_level_log = std::time::Instant::now();
- }
-
- // One push per chunk rather than per frame: same events, same
- // order, one round trip instead of N.
- let push = match session.as_ref() {
- Some(open) => open.push(&config, FRAME_MS, &energies).await,
- None => continue,
- };
- let events = match push {
- Ok(events) => events,
- Err(error) => {
- // Drop the handle, do not just skip the chunk. A push fails
- // when the module went away or the session is no longer
- // open, and neither heals by itself — keeping the handle
- // would reuse a dead session forever, because the lazy-open
- // retry above only runs while `session` is `None`.
- log::warn!("{LOG_PREFIX} VAD push failed ({error}); reopening the session");
- session = None;
- last_open_attempt = Some(std::time::Instant::now());
- // The partial utterance belonged to the dead segmenter, so
- // its boundaries mean nothing to the next one.
- pending.clear();
- utterance.clear();
- continue;
- }
- };
-
- // `frame` indexes `frames`; slice the audio at the same boundaries
- // the segmenter reported so an utterance carries exactly the
- // samples it was measured from.
- let mut cursor = 0usize;
- for indexed in events {
- let frame = indexed.frame;
- match indexed.event {
- tinyvoice::VadEvent::SpeechStart => {
- let at = frame * FRAME_SAMPLES;
- log::info!(
- "{LOG_PREFIX} speech onset rms={:.4} (onset={onset_threshold:.4})",
- energies.get(frame).copied().unwrap_or_default()
- );
- utterance.clear();
- cursor = at;
- notch_status("Listening", 2500); // pill: capturing speech
- }
- tinyvoice::VadEvent::SpeechEnd {
- emit, voiced_ms, ..
- } => {
- let upto = ((frame + 1) * FRAME_SAMPLES).min(frames.len());
- if upto > cursor && utterance.len() < MAX_UTTERANCE_SAMPLES {
- utterance.extend_from_slice(&frames[cursor..upto]);
- }
- cursor = upto;
- let captured = std::mem::take(&mut utterance);
- log::info!(
- "{LOG_PREFIX} utterance end voiced_ms={voiced_ms} emit={emit} samples={}",
- captured.len()
- );
- if emit {
- let cfg = config.clone();
- spawn_transcription(&mut transcriptions, &stopped, async move {
- transcribe_and_deliver(&cfg, captured).await;
- });
- }
- }
- }
- }
-
- // Whatever is still open after the reported events belongs to the
- // utterance in progress.
- if cursor < frames.len()
- && !frames.is_empty()
- && utterance.len() < MAX_UTTERANCE_SAMPLES
- && match session.as_ref() {
- Some(open) => open.is_speaking(&config).await.unwrap_or(false),
- None => false,
- }
- {
- utterance.extend_from_slice(&frames[cursor..]);
- }
- }
-
- transcriptions.abort_all();
- while transcriptions.join_next().await.is_some() {}
- if let Some(open) = session.as_ref() {
- if let Err(error) = open.close(&config).await {
- log::warn!("{LOG_PREFIX} could not close the VAD session: {error}");
- }
- }
- log::info!("{LOG_PREFIX} capture channel closed; processor exiting");
- });
- *PROCESSOR.lock().expect("voice processor state poisoned") = Some(processor);
-}
-
-/// Immediately disable processing; async shutdown also releases the microphone.
-pub fn stop() {
- ENABLED.store(false, Ordering::SeqCst);
- super::capture::request_stop();
-}
-/// Release continuous capture and wait for its processor on sign-out or toggle off.
-pub async fn shutdown() {
- let _lifecycle = LIFECYCLE.lock().await;
- stop();
- if let Err(error) = crate::voice::capture_lease::close_streams().await {
- log::warn!("{LOG_PREFIX} capture cleanup pending: {error}");
- }
- let processor = PROCESSOR
- .lock()
- .expect("voice processor state poisoned")
- .take();
- if let Some(processor) = processor {
- let _ = processor.await;
- }
-}
-
-/// Push a listener status to the always-visible notch pill via the
-/// `overlay:attention` channel. The notch maps "Listening" / "Processing" to the
-/// right icon; when the message expires it falls back to "Ready". Fire-and-forget.
-pub(super) fn notch_status(status: &str, ttl_ms: u32) {
- let _ = crate::desktop::overlay::publish_attention(
- crate::desktop::overlay::OverlayAttentionEvent::new(status)
- .with_source("voice")
- .with_ttl_ms(ttl_ms),
- );
-}
-
-/// Retain the stream's observed stop generation, including a stop during VAD work.
-pub(super) fn spawn_transcription(
- tasks: &mut tokio::task::JoinSet<()>,
- cancelled: &tokio::sync::watch::Receiver<u64>,
- task: impl std::future::Future<Output = ()> + Send + 'static,
-) {
- let mut cancelled = cancelled.clone();
- tasks.spawn(async move {
- tokio::select! {
- biased;
- _ = cancelled.changed() => {},
- () = task => {},
- }
- });
-}
-
-#[cfg(test)]
-#[path = "processor_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/voice/always_on/processor_tests.rs b/crates/openhuman-core/src/voice/always_on/processor_tests.rs
deleted file mode 100644
index fcccb9b3f3..0000000000
--- a/crates/openhuman-core/src/voice/always_on/processor_tests.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-use super::*;
-
-#[test]
-fn core_shutdown_stops_and_joins_always_on_processing() {
- const CHILD_ENV: &str = "OPENHUMAN_ALWAYS_ON_SHUTDOWN_FIXTURE";
- if std::env::var(CHILD_ENV).as_deref() == Ok("1") {
- tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .unwrap()
- .block_on(shutdown_fixture());
- return;
- }
- let output = std::process::Command::new(std::env::current_exe().unwrap())
- .args([
- "--exact",
- "voice::always_on::processor::tests::core_shutdown_stops_and_joins_always_on_processing",
- "--nocapture",
- ])
- .env(CHILD_ENV, "1")
- .output()
- .unwrap();
- assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
- assert!(
- output.status.success(),
- "shutdown fixture failed: {}{}",
- String::from_utf8_lossy(&output.stdout),
- String::from_utf8_lossy(&output.stderr)
- );
-}
-
-// A child process isolates the process-wide capture and processor state.
-async fn shutdown_fixture() {
- ENABLED.store(true, Ordering::SeqCst);
- let mut stopped = super::super::capture::stop_subscription();
- let joined = std::sync::Arc::new(AtomicBool::new(false));
- let completed = joined.clone();
- *PROCESSOR.lock().unwrap() = Some(tokio::spawn(async move {
- stopped.changed().await.unwrap();
- completed.store(true, Ordering::SeqCst);
- }));
-
- crate::voice::capture_lease::shutdown_capture().await;
-
- assert!(
- !ENABLED.load(Ordering::SeqCst),
- "shutdown must disable processing"
- );
- assert!(
- joined.load(Ordering::SeqCst),
- "shutdown must join the processor"
- );
- assert!(PROCESSOR.lock().unwrap().is_none());
-}
diff --git a/crates/openhuman-core/src/voice/always_on/transcribe.rs b/crates/openhuman-core/src/voice/always_on/transcribe.rs
deleted file mode 100644
index b452fcb807..0000000000
--- a/crates/openhuman-core/src/voice/always_on/transcribe.rs
+++ /dev/null
@@ -1,230 +0,0 @@
-//! Transcription, wake-word gating, and local fast-path command execution for
-//! a finished always-on utterance.
-
-use super::{notch_status, LOG_PREFIX};
-use crate::config::Config;
-use crate::modules::voice as tinyvoice;
-use crate::voice::audio_capture::TARGET_SAMPLE_RATE;
-
-/// Transcribe a finished utterance and hand the text to the dictation bus,
-/// which delivers it to the agent (auto-send) and the notch — the same path the
-/// hotkey dictation uses.
-pub(super) async fn transcribe_and_deliver(config: &Config, samples_16k: Vec<f32>) {
- use base64::Engine as _;
- let sample_count = samples_16k.len();
- let wav = match tinyvoice::encode_wav(config, &samples_16k, TARGET_SAMPLE_RATE).await {
- Ok(wav) => wav,
- Err(error) => {
- log::warn!("{LOG_PREFIX} wav encode failed: {error}");
- return;
- }
- };
- // Route through the *configured* STT provider (cloud / slug) — the
- // same factory dispatch the `voice.stt_dispatch` RPC uses — so always-on
- // honors the user's choice of engine.
- let provider_name = crate::voice::effective_stt_provider(config);
- // Which STT backend is doing the work matters when diagnosing slow/failed
- // transcription across machines.
- log::info!(
- "{LOG_PREFIX} transcribing utterance: provider={provider_name} model=<provider default> samples={sample_count} wav_bytes={}",
- wav.len()
- );
- let provider = match crate::voice::create_stt_provider(&provider_name, "", config) {
- Ok(p) => p,
- Err(e) => {
- log::warn!("{LOG_PREFIX} STT provider '{provider_name}' unavailable: {e}");
- return;
- }
- };
- let audio_b64 = base64::engine::general_purpose::STANDARD.encode(&wav);
- let stt_started = std::time::Instant::now();
- // Force English transcription. Auto-detect was rendering the English wake
- // word "Hey Tiny" in Hindi/Bengali/etc. script ("हे टाइनी"), which could never
- // match the Latin wake word. The wake word + commands here are English.
- match provider
- .transcribe(
- config,
- &audio_b64,
- Some("audio/wav"),
- Some("utterance.wav"),
- Some("en"),
- )
- .await
- {
- Ok(outcome) => {
- let text = outcome.value.text.trim().to_string();
- log::info!(
- "{LOG_PREFIX} transcription ok in {}ms (provider={provider_name}, chars={})",
- stt_started.elapsed().as_millis(),
- text.len()
- );
- if text.is_empty() {
- log::info!("{LOG_PREFIX} empty transcript dropped");
- return;
- }
- // Wake-word sequencing is owned by the tinyvoice module. A module
- // failure must not deliver an unaddressed utterance to the agent:
- // this gate fails CLOSED.
- use crate::modules::voice::UtteranceDisposition as UD;
- let disposition =
- match tinyvoice::sequence_utterance(config, &text, &config.voice_server.wake_word)
- .await
- {
- Ok(d) => d,
- Err(error) => {
- log::warn!(
- "{LOG_PREFIX} wake-word gate unavailable ({error}); dropping the utterance"
- );
- return;
- }
- };
- match disposition {
- UD::Command { command } => {
- // Redacted: never log the raw spoken command (always-on mic PII).
- log::info!("{LOG_PREFIX} wake word matched → cmd_len={}", command.len());
- notch_status("Processing", 12000); // pill: running the command
- deliver_command(config, command).await;
- }
- UD::BareWake => {
- // Wake word spoken with no trailing command ("Hey Tiny").
- // Acknowledge with an agent turn so the user gets a reply.
- log::info!("{LOG_PREFIX} bare wake word → acknowledging");
- notch_status("Listening…", 8000);
- deliver_command(config, "hello".to_string()).await;
- }
- UD::Ignored => {
- log::info!(
- "{LOG_PREFIX} no wake word ({:?}) in transcript_len={}; ignored",
- config.voice_server.wake_word,
- text.len()
- );
- }
- }
- }
- Err(e) => log::warn!(
- "{LOG_PREFIX} transcription failed ({provider_name}) after {}ms: {e}",
- stt_started.elapsed().as_millis()
- ),
- }
-}
-
-/// Route a recognized command: run high-confidence intents locally (the fast
-/// path, no LLM turn), and fall back to the agent for `Unknown` — or when a
-/// local execution fails, so routing can only shortcut, never drop a command.
-async fn deliver_command(config: &Config, cmd: String) {
- use crate::modules::voice::{route, VoiceIntent};
- // A module that will not load costs the fast path, not the command: an
- // unroutable transcript goes to the agent, which is exactly what
- // `VoiceIntent::Unknown` already means.
- let intent = match route(config, &cmd).await {
- Ok(intent) => intent,
- Err(error) => {
- log::warn!("{LOG_PREFIX} intent routing unavailable ({error}); deferring to agent");
- VoiceIntent::Unknown
- }
- };
- // Log only the intent *kind* + lengths — never the transcript-derived query /
- // app / result text (always-on mic PII).
- if matches!(intent, VoiceIntent::Unknown) {
- log::info!(
- "{LOG_PREFIX} no fast intent → agent (cmd_len={})",
- cmd.len()
- );
- crate::voice::dictation_listener::publish_transcription(cmd);
- return;
- }
- log::info!(
- "{LOG_PREFIX} fast intent={} (local execution)",
- intent.kind()
- );
- match execute_intent(config, intent).await {
- Ok(msg) => {
- log::info!("{LOG_PREFIX} fast route done (summary_len={})", msg.len());
- notch_status(&msg, 2500);
- }
- Err(_e) => {
- log::warn!("{LOG_PREFIX} fast route failed; falling back to agent");
- crate::voice::dictation_listener::publish_transcription(cmd);
- }
- }
-}
-
-/// Execute a fast-path [`VoiceIntent`] directly (no LLM). Media transport and
-/// volume go through `osascript`. App launch and "play X" have no local
-/// fast-path (the desktop-control automation backend was removed); those
-/// intents return `Err` so the caller defers to the agent (the LLM fallback) —
-/// routing can only *shortcut*, never *block*.
-async fn execute_intent(
- _config: &Config,
- intent: crate::modules::voice::VoiceIntent,
-) -> Result<String, String> {
- use crate::modules::voice::VoiceIntent as VI;
- match intent {
- VI::Play { .. } => Err("play has no local fast-path; defer to agent".to_string()),
- VI::OpenApp { .. } => Err("app launch has no local fast-path; defer to agent".to_string()),
- VI::Pause => osa("tell application \"Music\" to pause")
- .await
- .map(|_| "Paused".to_string()),
- VI::Resume => osa("tell application \"Music\" to play")
- .await
- .map(|_| "Resumed".to_string()),
- VI::Next => osa("tell application \"Music\" to next track")
- .await
- .map(|_| "Next track".to_string()),
- VI::Previous => osa("tell application \"Music\" to previous track")
- .await
- .map(|_| "Previous track".to_string()),
- VI::SetVolume { percent } => osa(&format!("set volume output volume {percent}"))
- .await
- .map(|_| format!("Volume {percent}%")),
- VI::VolumeUp => {
- osa("set volume output volume (output volume of (get volume settings) + 12)")
- .await
- .map(|_| "Louder".to_string())
- }
- VI::VolumeDown => {
- osa("set volume output volume (output volume of (get volume settings) - 12)")
- .await
- .map(|_| "Quieter".to_string())
- }
- VI::Mute => osa("set volume with output muted")
- .await
- .map(|_| "Muted".to_string()),
- VI::Unmute => osa("set volume without output muted")
- .await
- .map(|_| "Unmuted".to_string()),
- VI::Unknown => Err("unknown intent".to_string()),
- }
-}
-
-/// Run a one-line AppleScript (macOS). Used for media transport + volume.
-async fn osa(script: &str) -> Result<(), String> {
- #[cfg(target_os = "macos")]
- {
- // Bound the subprocess so a hung osascript can't stall deliver_command
- // (which would block the agent fallback). 5s is ample for a one-liner.
- let out = tokio::time::timeout(
- std::time::Duration::from_secs(5),
- tokio::process::Command::new("osascript")
- .arg("-e")
- .arg(script)
- .output(),
- )
- .await
- .map_err(|_| "osascript timed out".to_string())?
- .map_err(|e| format!("osascript spawn failed: {e}"))?;
- if out.status.success() {
- Ok(())
- } else {
- Err(format!(
- "osascript error: {}",
- String::from_utf8_lossy(&out.stderr).trim()
- ))
- }
- }
- #[cfg(not(target_os = "macos"))]
- {
- let _ = script;
- Err("media/volume control is macOS-only".to_string())
- }
-}
diff --git a/crates/openhuman-core/src/voice/always_on_tests.rs b/crates/openhuman-core/src/voice/always_on_tests.rs
deleted file mode 100644
index 480b1436b2..0000000000
--- a/crates/openhuman-core/src/voice/always_on_tests.rs
+++ /dev/null
@@ -1,70 +0,0 @@
-use super::*;
-use std::sync::atomic::Ordering;
-
-#[test]
-fn stop_clears_enabled_gate() {
- // stop() flips the runtime gate off so the processor drops all audio.
- ENABLED.store(true, Ordering::SeqCst);
- stop();
- assert!(
- !ENABLED.load(Ordering::SeqCst),
- "stop() must clear the runtime gate"
- );
-}
-
-// The VAD state machine and the wake-word gate moved to `tinyvoice`, which
-// carries their unit tests. What stays testable here is the piece that is
-// genuinely OpenHuman's: turning persisted config into the module's tuning.
-#[test]
-fn vad_config_maps_persisted_seconds_to_milliseconds() {
- let mut c = crate::config::VoiceServerConfig::default();
- c.vad_max_utterance_secs = 2.5;
- c.vad_hangover_ms = 750;
-
- let v = tinyvoice::vad_config_from_server_config(&c);
-
- assert_eq!(v.max_utterance_ms, 2500, "seconds become milliseconds");
- assert_eq!(v.hangover_ms, 750, "milliseconds pass through");
- assert_eq!(v.onset_threshold, c.vad_onset_threshold);
-}
-
-#[test]
-fn a_nonpositive_utterance_ceiling_cannot_collapse_to_zero() {
- // A zero ceiling would close every utterance on its first frame, which
- // reads to a user as the microphone hearing nothing at all.
- let mut c = crate::config::VoiceServerConfig::default();
- c.vad_max_utterance_secs = 0.0;
- assert_eq!(
- tinyvoice::vad_config_from_server_config(&c).max_utterance_ms,
- 1
- );
-
- c.vad_max_utterance_secs = -5.0;
- assert_eq!(
- tinyvoice::vad_config_from_server_config(&c).max_utterance_ms,
- 1
- );
-}
-
-#[tokio::test]
-async fn an_utterance_started_after_stop_never_polls_its_transcription() {
- let (stop, observed) = tokio::sync::watch::channel(0_u64);
- let delivered = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
- let task_delivered = delivered.clone();
- stop.send_replace(1);
- let mut tasks = tokio::task::JoinSet::new();
- processor::spawn_transcription(&mut tasks, &observed, async move {
- task_delivered.store(true, Ordering::SeqCst);
- });
- tasks.join_next().await.unwrap().unwrap();
- assert!(!delivered.load(Ordering::SeqCst));
-}
-
-#[tokio::test]
-async fn voice_component_off_keeps_always_on_down_even_when_enabled() {
- let mut config = crate::config::Config::default();
- config.voice_server.always_on_enabled = true;
- config.components.voice = false;
- start_if_enabled(&crate::core::runtime::DispatchCtx::default(), &config).await;
- assert!(!ENABLED.load(Ordering::SeqCst));
-}