Skip to content

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

feat(voice): add text input module for voice pipeline

Steven Enamakel1f9b991353e4
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index c8a13a36e6..8f1713a594 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -488,8 +488,6 @@ sentry = { version = "0.47.0", default-features = false, optional = true, featur
tokio-stream = { version = "0.1.18", default-features = false, features = ["sync"] }
url = "2"
tempfile = "3"
-enigo = { version = "0.3", optional = true }
-arboard = { version = "3", optional = true }
fs2 = "0.4"
# Cross-platform battery probe for the scheduler gate. Maintained fork of
# the abandoned `battery` crate; same `use battery::*;` API surface. Used
@@ -918,8 +916,8 @@ modules = ["tinybus/modules", "dep:tinycomputer-bus"]
# feature narrows the compile-time surface, `DomainSet` gates it at runtime.
# Requires `inference` (the microphone-permission probe), so enabling `voice` turns
# `inference` on transitively.
-# `arboard`/`enigo`/`tinyvoice` (the `rdev` hotkey listener) join here rather than getting their own gate: their
-# only call sites are `voice::text_input` (clipboard + synthetic keystrokes to
+# `arboard`/`enigo` (now behind `tinycomputer-accessibility/paste`) and `tinyvoice` (the `rdev` hotkey listener) join here rather than getting their own gate: their
+# only call sites are `tinycomputer_accessibility::paste` (clipboard + synthetic keystrokes to
# insert a dictated transcript) and `voice::hotkey` (the global push-to-talk
# listener), both already `#[cfg(feature = "voice")]`, and nothing outside
# `voice/` reaches them. Worth 17 crates — the largest single shed in the wave —
@@ -937,8 +935,9 @@ voice = [
# only — `serde` and nothing else.
"dep:tinyvoice-bus",
"dep:lettre",
- "dep:arboard",
- "dep:enigo",
+ # `voice::server` inserts dictated text through `tinycomputer_accessibility::paste`
+ # (clipboard + synthetic keystrokes: `arboard`/`enigo` live behind that feature).
+ "tinycomputer-accessibility/paste",
"dep:tinyvoice",
# `audio_toolkit::ops` delivers generated podcasts through tinychannels'
# EmailChannel, so the provider — and therefore the implementation crate —
diff --git a/crates/openhuman-core/src/voice/README.md b/crates/openhuman-core/src/voice/README.md
index 07b8613a88..e7fbaf3c1e 100644
--- a/crates/openhuman-core/src/voice/README.md
+++ b/crates/openhuman-core/src/voice/README.md
@@ -47,14 +47,13 @@ Keeping the two surfaces in lockstep is enforced by the disabled-build check
| `hotkey.rs` | Re-export of `tinyvoice::hotkey` (the `tinyvoice` library's off-by-default `hotkey` feature, which owns the `rdev` dependency): `ActivationMode` (Tap/Push), `HotkeyEvent`, `HotkeyCombination`, `parse_hotkey`, `start_listener`. Its tests live in tinyvoice. |
| `audio_capture.rs` | Mic capture → 16 kHz mono WAV bytes; `RecordingHandle`, peak-RMS reporting, and the host microphone-permission policy. The `cpal` device flow is `tinyvoice::capture`. Delegates framing/resample/energy math to `crate::modules::voice` (the `tinyvoice` module). |
| `audio_toolkit/` | Podcast generation + email delivery (`audio_toolkit` RPC namespace), gated by the same `voice` feature. See its own [README](audio_toolkit/README.md). |
-| `text_input.rs` | Clipboard-paste text insertion (`insert_text`): writes clipboard then simulates Cmd/Ctrl+V via enigo, restoring prior clipboard. |
| `dictation_listener.rs` | Core-side dictation broadcast bus: `DictationEvent`, `publish_dictation_event` / `subscribe_dictation_events`, `publish_transcription` / `subscribe_transcription_results`, rdev listener lifecycle (`start_if_enabled` / `stop`), `normalize_hotkey_for_rdev`. |
| `reply_speech.rs` | Agent reply synthesis via backend `/openai/v1/audio/speech`; `ReplySpeechResult`, `VisemeFrame`, `AlignmentFrame`, `ReplySpeechOptions`, `synthesize_reply`, tolerant response normalization. |
| `realtime.rs` | Mints a short-lived signed WebSocket URL from the backend's `/voice-agent/get-signed-url` so the desktop client can open an ElevenLabs Agents session directly (#5399); the provider API key never leaves the server. |
| `realtime_harness.rs` (+ `realtime_harness/turn_handler.rs`, `realtime_harness/chat_delivery.rs`, `realtime_harness/agent.rs`, `realtime_harness/prompt.rs`) | `voice:harness` socket turn handler for realtime sessions: runs the local orchestrator agent (same brain as chat/meet) on each turn the backend relays from the ElevenLabs Custom-LLM proxy, streaming `voice:harness:delta` / `:done` / `:error` back. |
| `stub.rs` | Disabled-voice facade compiled when `voice` is OFF; mirrors the real public surface with no-op / error bodies. |
| `cli.rs` | `openhuman voice` / `openhuman dictate` subcommand adapter: runs a blocking standalone dictation server (domain-owned, since it blocks forever and doesn't fit the controller registry). |
-| `*_tests.rs` | Sibling test suites wired via `#[path = ...]` (no inline `#[cfg(test)] mod` blocks, since `pnpm rust:layout` rejects them): `always_on_tests.rs`, `bus_tests.rs`, `compile_status_tests.rs`, `dictation_listener_tests.rs`, `ops_tests.rs`, `realtime_harness_tests.rs`, `realtime_tests.rs`, `reply_speech_tests.rs`, `schemas_tests.rs` (wired from `schemas/mod.rs`), `server_tests.rs`, `text_input_tests.rs`, `types_tests.rs`, `factory/factory_tests.rs`, `factory/stt_providers_tests.rs`, `audio_toolkit/ops_tests.rs`. |
+| `*_tests.rs` | Sibling test suites wired via `#[path = ...]` (no inline `#[cfg(test)] mod` blocks, since `pnpm rust:layout` rejects them): `always_on_tests.rs`, `bus_tests.rs`, `compile_status_tests.rs`, `dictation_listener_tests.rs`, `ops_tests.rs`, `realtime_harness_tests.rs`, `realtime_tests.rs`, `reply_speech_tests.rs`, `schemas_tests.rs` (wired from `schemas/mod.rs`), `server_tests.rs`, `types_tests.rs`, `factory/factory_tests.rs`, `factory/stt_providers_tests.rs`, `audio_toolkit/ops_tests.rs`. |
## Public surface
@@ -65,7 +64,7 @@ Keeping the two surfaces in lockstep is enforced by the disabled-build check
- Events: `publish_ptt_transcript_committed` (from `bus`).
- Compile status: `VOICE_COMPILED_IN` (from `compile_status`, always available regardless of the feature gate).
- Re-exported inference submodules: `cloud_transcribe`, `local_speech`, `postprocess`, and `streaming` (only when `http-server` is also enabled).
-- Submodules `server`, `hotkey`, `dictation_listener`, `reply_speech`, `text_input`, `audio_capture`, `factory`, `always_on`, `bus`, `realtime`, `realtime_harness`, `audio_toolkit` are `pub`.
+- Submodules `server`, `hotkey`, `dictation_listener`, `reply_speech`, `audio_capture`, `factory`, `always_on`, `bus`, `realtime`, `realtime_harness`, `audio_toolkit` are `pub`.
## RPC / controllers
diff --git a/crates/openhuman-core/src/voice/mod.rs b/crates/openhuman-core/src/voice/mod.rs
index 607e591ae1..0d18f2cba4 100644
--- a/crates/openhuman-core/src/voice/mod.rs
+++ b/crates/openhuman-core/src/voice/mod.rs
@@ -61,8 +61,6 @@ mod schemas;
#[cfg(feature = "voice")]
pub mod server;
#[cfg(feature = "voice")]
-pub mod text_input;
-#[cfg(feature = "voice")]
mod types;
#[cfg(feature = "voice")]
diff --git a/crates/openhuman-core/src/voice/server/pipeline.rs b/crates/openhuman-core/src/voice/server/pipeline.rs
index ea6ae627f5..c435d12cd7 100644
--- a/crates/openhuman-core/src/voice/server/pipeline.rs
+++ b/crates/openhuman-core/src/voice/server/pipeline.rs
@@ -13,7 +13,7 @@ use tokio::sync::Mutex;
use crate::config::Config;
use crate::modules::voice::{is_hallucinated, HallucinationMode};
use crate::voice::audio_capture::RecordingHandle;
-use crate::voice::text_input;
+use tinycomputer_accessibility::paste as text_input;
#[cfg(target_os = "macos")]
use tinycomputer_accessibility as accessibility;
diff --git a/crates/openhuman-core/src/voice/text_input.rs b/crates/openhuman-core/src/voice/text_input.rs
deleted file mode 100644
index ce81369ca7..0000000000
--- a/crates/openhuman-core/src/voice/text_input.rs
+++ /dev/null
@@ -1,173 +0,0 @@
-//! Text insertion into the currently active text field.
-//!
-//! Uses the **clipboard-paste** strategy (like OpenWhispr): writes text
-//! to the system clipboard then simulates Cmd+V / Ctrl+V to paste it.
-//! This is atomic and instantaneous, unlike enigo's `text()` which types
-//! character-by-character and causes garbled/repeated output on macOS.
-//!
-//! The previous clipboard contents are saved and restored after a short
-//! delay so the user's clipboard is not permanently overwritten.
-
-use log::{debug, info, warn};
-use std::time::Duration;
-
-use arboard::Clipboard;
-use enigo::{Direction, Enigo, Key, Keyboard, Settings};
-#[cfg(target_os = "macos")]
-use tinycomputer_accessibility as accessibility;
-
-const LOG_PREFIX: &str = "[voice_input]";
-
-/// Delay before sending Cmd+V, letting the clipboard write settle.
-/// OpenWhispr uses 120ms on macOS.
-const PASTE_DELAY: Duration = Duration::from_millis(120);
-
-/// Delay after sending Cmd+V before restoring the clipboard, giving the
-/// target application time to read from the clipboard.
-/// OpenWhispr uses 450ms on macOS.
-const CLIPBOARD_RESTORE_DELAY: Duration = Duration::from_millis(450);
-#[cfg(target_os = "macos")]
-const FOCUS_RESTORE_DELAY: Duration = Duration::from_millis(100);
-
-/// Insert text into the currently active text field via clipboard-paste.
-///
-/// Strategy:
-/// 1. Save current clipboard contents
-/// 2. Write transcribed text to clipboard
-/// 3. Simulate Cmd+V (macOS) or Ctrl+V (Windows/Linux)
-/// 4. Wait briefly, then restore original clipboard
-///
-/// This avoids the character-by-character typing issues with enigo's
-/// `text()` method which causes garbled/repeated output.
-pub fn insert_text(text: &str, expected_app: Option<&str>) -> Result<(), String> {
- if text.trim().is_empty() {
- warn!("{LOG_PREFIX} transcription was empty/whitespace, skipping insertion");
- return Ok(());
- }
-
- #[cfg(not(target_os = "macos"))]
- let _ = expected_app;
-
- info!(
- "{LOG_PREFIX} inserting {} chars via clipboard-paste",
- text.len()
- );
-
- // Step 1: Save current clipboard.
- let mut clipboard = Clipboard::new().map_err(|e| format!("failed to access clipboard: {e}"))?;
- let saved_clipboard = clipboard.get_text().ok();
- debug!(
- "{LOG_PREFIX} saved clipboard ({} chars)",
- saved_clipboard.as_ref().map_or(0, |s| s.len())
- );
-
- // Step 2: Write transcription to clipboard.
- clipboard
- .set_text(text)
- .map_err(|e| format!("failed to write text to clipboard: {e}"))?;
- debug!("{LOG_PREFIX} transcription written to clipboard");
-
- // Step 3: Brief delay to let clipboard write settle, then simulate paste.
- std::thread::sleep(PASTE_DELAY);
-
- #[cfg(target_os = "macos")]
- if let Some(app_name) = expected_app {
- debug!("{LOG_PREFIX} validating focus before paste; expected_app='{app_name}'");
- if let Err(validation_err) =
- accessibility::validate_focused_target(Some(app_name), None, None)
- {
- warn!("{LOG_PREFIX} focus changed before paste: {validation_err}");
- // Always try to restore focus — even if the user hasn't clicked a
- // text field yet, activating the app brings it to front and most
- // apps will accept Cmd+V into their last-focused element.
- if let Err(restore_err) = restore_focus_to_app(app_name) {
- warn!(
- "{LOG_PREFIX} focus restore failed: {restore_err} — will attempt paste anyway"
- );
- } else {
- info!("{LOG_PREFIX} focus restored to '{app_name}' before paste");
- }
- }
- }
-
- let mut enigo = Enigo::new(&Settings::default())
- .map_err(|e| format!("failed to create enigo instance: {e}"))?;
-
- let modifier = paste_modifier_key();
- enigo
- .key(modifier, Direction::Press)
- .map_err(|e| format!("failed to press modifier: {e}"))?;
- enigo
- .key(Key::Unicode('v'), Direction::Click)
- .map_err(|e| format!("failed to press 'v': {e}"))?;
- enigo
- .key(modifier, Direction::Release)
- .map_err(|e| format!("failed to release modifier: {e}"))?;
-
- debug!("{LOG_PREFIX} paste keystroke sent");
-
- // Step 4: Restore clipboard after a delay (non-blocking).
- if let Some(original) = saved_clipboard {
- std::thread::spawn(move || {
- std::thread::sleep(CLIPBOARD_RESTORE_DELAY);
- match Clipboard::new() {
- Ok(mut cb) => {
- if let Err(e) = cb.set_text(&original) {
- warn!("{LOG_PREFIX} failed to restore clipboard: {e}");
- } else {
- debug!("{LOG_PREFIX} clipboard restored");
- }
- }
- Err(e) => warn!("{LOG_PREFIX} failed to re-open clipboard for restore: {e}"),
- }
- });
- }
-
- info!("{LOG_PREFIX} text inserted successfully via paste");
- Ok(())
-}
-
-#[cfg(target_os = "macos")]
-fn restore_focus_to_app(app_name: &str) -> Result<(), String> {
- let script = format!(
- r#"tell application "{}" to activate"#,
- escape_applescript_string(app_name)
- );
- let output = std::process::Command::new("osascript")
- .arg("-e")
- .arg(script)
- .output()
- .map_err(|e| format!("failed to run osascript for focus restore: {e}"))?;
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
- let detail = if stderr.is_empty() {
- "unknown osascript error".to_string()
- } else {
- stderr
- };
- return Err(format!(
- "failed to restore focus to '{}': {}",
- app_name, detail
- ));
- }
- std::thread::sleep(FOCUS_RESTORE_DELAY);
- Ok(())
-}
-
-#[cfg(target_os = "macos")]
-fn escape_applescript_string(value: &str) -> String {
- value.replace('\\', "\\\\").replace('"', "\\\"")
-}
-
-/// Returns the platform-appropriate paste modifier key.
-fn paste_modifier_key() -> Key {
- if cfg!(target_os = "macos") {
- Key::Meta
- } else {
- Key::Control
- }
-}
-
-#[cfg(test)]
-#[path = "text_input_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/voice/text_input_tests.rs b/crates/openhuman-core/src/voice/text_input_tests.rs
deleted file mode 100644
index de03b33f2b..0000000000
--- a/crates/openhuman-core/src/voice/text_input_tests.rs
+++ /dev/null
@@ -1,82 +0,0 @@
-use super::*;
-
-// ── Guard clause: empty / whitespace input short-circuits ────
-//
-// The post-guard code (clipboard / enigo / AppleScript) needs a
-// display and a real system event loop, so coverage of those paths
-// below `insert_text`'s trim-guard is only achievable in an
-// end-to-end integration environment. Units here pin the logic
-// that IS deterministic in a headless test process.
-
-#[test]
-fn empty_text_is_noop_and_succeeds() {
- assert!(insert_text("", None).is_ok());
-}
-
-#[test]
-fn whitespace_only_skips_insertion_and_succeeds() {
- assert!(insert_text(" ", None).is_ok());
-}
-
-#[test]
-fn newlines_and_tabs_only_also_treated_as_empty() {
- // `trim()` strips any Unicode whitespace — the skip branch must
- // fire for pure `\t` and `\n` buffers too, not just spaces.
- assert!(insert_text("\n\n", None).is_ok());
- assert!(insert_text("\t \n", Some("any-app")).is_ok());
-}
-
-#[test]
-fn paste_modifier_is_platform_correct() {
- let key = paste_modifier_key();
- if cfg!(target_os = "macos") {
- assert!(matches!(key, Key::Meta));
- } else {
- assert!(matches!(key, Key::Control));
- }
-}
-
-#[test]
-fn constants_match_openwhispr_timings() {
- // Lock in the OpenWhispr-derived delays so nobody silently
- // shortens them (would race the target app's paste handler).
- assert_eq!(PASTE_DELAY, Duration::from_millis(120));
- assert_eq!(CLIPBOARD_RESTORE_DELAY, Duration::from_millis(450));
-}
-
-// ── AppleScript string escaping (macOS-only) ─────────────────
-
-#[cfg(target_os = "macos")]
-#[test]
-fn escape_applescript_string_escapes_backslash_and_quote() {
- assert_eq!(escape_applescript_string("plain"), "plain");
- assert_eq!(escape_applescript_string(r#"a"b"#), r#"a\"b"#);
- assert_eq!(escape_applescript_string(r"a\b"), r"a\\b");
- // Backslash must be escaped BEFORE quotes so the order of
- // substitutions doesn't double-escape already-escaped quotes.
- assert_eq!(escape_applescript_string(r#"\"mix"#), r#"\\\"mix"#);
-}
-
-#[cfg(target_os = "macos")]
-#[test]
-fn escape_applescript_string_is_idempotent_on_benign_input() {
- for s in ["", "App Name", "Safari", "Sub-App 2", "123"] {
- assert_eq!(escape_applescript_string(s), s);
- }
-}
-
-// ── Focus-restore error path (macOS-only) ────────────────────
-
-#[cfg(target_os = "macos")]
-#[test]
-fn restore_focus_to_app_errors_on_bogus_app_name() {
- // `osascript` returns a non-zero exit when the target app
- // cannot be activated, so we expect the helper to surface
- // that as an Err. This exercises the error-formatting branch.
- let err = restore_focus_to_app("__definitely_no_such_app_abcxyz__")
- .expect_err("bogus app should not activate");
- assert!(
- err.contains("failed to restore focus"),
- "expected focus-restore prefix in error, got: {err}"
- );
-}