Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(audio): auto-recover microphone when hijacked by another app

Louis Beaumonta42a695d4547
diff --git a/screenpipe-audio/src/audio_manager/device_monitor.rs b/screenpipe-audio/src/audio_manager/device_monitor.rs
index 4a6ee0147..f0a138dc4 100644
--- a/screenpipe-audio/src/audio_manager/device_monitor.rs
+++ b/screenpipe-audio/src/audio_manager/device_monitor.rs
@@ -2,7 +2,7 @@ use std::{collections::HashSet, sync::Arc, time::Duration};
use anyhow::Result;
use tokio::{sync::Mutex, task::JoinHandle, time::sleep};
-use tracing::{error, info};
+use tracing::{error, info, warn};
use crate::{core::device::parse_audio_device, device::device_manager::DeviceManager};
@@ -24,6 +24,19 @@ pub async fn start_device_monitor(
if audio_manager.status().await == AudioManagerStatus::Running {
let currently_available_devices = device_manager.devices().await;
let enabled_devices = audio_manager.enabled_devices().await;
+
+ // Check for stale recording handles (tasks that have finished/crashed)
+ // This handles cases where audio stream was hijacked by another app
+ let stale_devices = audio_manager.check_stale_recording_handles().await;
+ for device_name in stale_devices {
+ warn!(
+ "detected stale recording handle for {}, cleaning up for restart",
+ device_name
+ );
+ let _ = audio_manager.cleanup_stale_device(&device_name).await;
+ disconnected_devices.insert(device_name);
+ }
+
for device_name in disconnected_devices.clone() {
let device = match parse_audio_device(&device_name) {
Ok(device) => device,
@@ -34,6 +47,7 @@ pub async fn start_device_monitor(
};
if audio_manager.start_device(&device).await.is_ok() {
+ info!("successfully restarted device {}", device_name);
disconnected_devices.remove(&device_name);
}
}
diff --git a/screenpipe-audio/src/audio_manager/manager.rs b/screenpipe-audio/src/audio_manager/manager.rs
index 9a3007f67..7b6cea6d7 100644
--- a/screenpipe-audio/src/audio_manager/manager.rs
+++ b/screenpipe-audio/src/audio_manager/manager.rs
@@ -386,6 +386,49 @@ impl AudioManager {
pub async fn enabled_devices(&self) -> HashSet<String> {
self.options.read().await.enabled_devices.clone()
}
+
+ /// Check for recording handles that have finished (crashed or timed out)
+ /// Returns device names that need to be cleaned up and restarted
+ pub async fn check_stale_recording_handles(&self) -> Vec<String> {
+ let mut stale_devices = Vec::new();
+
+ for pair in self.recording_handles.iter() {
+ let device = pair.key();
+ let handle = pair.value();
+
+ // Check if the JoinHandle has finished (task completed/crashed)
+ if handle.lock().await.is_finished() {
+ stale_devices.push(device.to_string());
+ }
+ }
+
+ stale_devices
+ }
+
+ /// Clean up a stale device that had its recording handle crash/timeout
+ /// This prepares the device for restart by the device monitor
+ pub async fn cleanup_stale_device(&self, device_name: &str) -> anyhow::Result<()> {
+ let device = match parse_audio_device(device_name) {
+ Ok(device) => device,
+ Err(_) => return Err(anyhow!("Device {} not found", device_name)),
+ };
+
+ // Remove from recording handles
+ if let Some((_, handle)) = self.recording_handles.remove(&device) {
+ // Abort the handle if somehow still running
+ handle.lock().await.abort();
+ }
+
+ // Stop the device in device manager (clears streams and states)
+ let _ = self.device_manager.stop_device(&device).await;
+
+ info!(
+ "cleaned up stale device {} for restart",
+ device_name
+ );
+
+ Ok(())
+ }
}
impl Drop for AudioManager {
diff --git a/screenpipe-audio/src/core/run_record_and_transcribe.rs b/screenpipe-audio/src/core/run_record_and_transcribe.rs
index 1f1f4bcbd..b00dc7649 100644
--- a/screenpipe-audio/src/core/run_record_and_transcribe.rs
+++ b/screenpipe-audio/src/core/run_record_and_transcribe.rs
@@ -14,6 +14,11 @@ use crate::{core::update_device_capture_time, AudioInput};
use super::AudioStream;
+/// Timeout for receiving audio data before considering the stream dead.
+/// If no audio is received for this duration, the stream is likely hijacked
+/// by another app (e.g., Wispr Flow taking over the microphone).
+const AUDIO_RECEIVE_TIMEOUT_SECS: u64 = 30;
+
pub async fn run_record_and_transcribe(
audio_stream: Arc<AudioStream>,
duration: Duration,
@@ -40,12 +45,20 @@ pub async fn run_record_and_transcribe(
&& !audio_stream.is_disconnected.load(Ordering::Relaxed)
{
while collected_audio.len() < max_samples && is_running.load(Ordering::Relaxed) {
- match receiver.recv().await {
- Ok(chunk) => {
+ // Use timeout to detect when audio stream stops sending data
+ // This happens when another app hijacks the audio device
+ let recv_result = tokio::time::timeout(
+ Duration::from_secs(AUDIO_RECEIVE_TIMEOUT_SECS),
+ receiver.recv(),
+ )
+ .await;
+
+ match recv_result {
+ Ok(Ok(chunk)) => {
collected_audio.extend(chunk);
update_device_capture_time(&device_name);
}
- Err(broadcast::error::RecvError::Lagged(n)) => {
+ Ok(Err(broadcast::error::RecvError::Lagged(n))) => {
// Channel buffer overflow - receiver fell behind producer
// This is expected under heavy load, continue instead of failing
warn!(
@@ -54,10 +67,24 @@ pub async fn run_record_and_transcribe(
);
continue;
}
- Err(e) => {
+ Ok(Err(e)) => {
error!("error receiving audio data: {}", e);
return Err(anyhow!("Audio stream error: {}", e));
}
+ Err(_timeout) => {
+ // No audio data received for AUDIO_RECEIVE_TIMEOUT_SECS seconds
+ // This likely means another app took over the audio device
+ warn!(
+ "no audio received from {} for {}s - stream may be hijacked by another app, triggering reconnect",
+ device_name, AUDIO_RECEIVE_TIMEOUT_SECS
+ );
+ // Mark stream as disconnected so device monitor can restart it
+ audio_stream.is_disconnected.store(true, Ordering::Relaxed);
+ return Err(anyhow!(
+ "Audio stream timeout - no data received for {}s (possible audio hijack)",
+ AUDIO_RECEIVE_TIMEOUT_SECS
+ ));
+ }
}
}