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

feat: per-device audio toggle from tray + security hardening

Louis Beaumont3ee3defcbf93
diff --git a/apps/screenpipe-app-tauri/app/home/page.tsx b/apps/screenpipe-app-tauri/app/home/page.tsx
index 4d868c27b..fe213bdff 100644
--- a/apps/screenpipe-app-tauri/app/home/page.tsx
+++ b/apps/screenpipe-app-tauri/app/home/page.tsx
@@ -347,45 +347,25 @@ function HomeContent() {
{/* Row 1: name + phone + collapse */}
<div className={cn("flex items-center", sidebarCollapsed ? "justify-center" : "justify-between")}>
{!sidebarCollapsed && <h1 className={cn("text-lg font-bold", isTranslucent ? "vibrant-heading" : "text-foreground")}>screenpipe</h1>}
- <div className="flex items-center gap-1.5">
- <NotificationBell />
- <button
- onClick={toggleMeeting}
- disabled={meetingLoading || (meetingState.active && !meetingState.manualActive)}
- className={cn("relative flex items-center justify-center h-5 w-5 transition-colors", isTranslucent ? "vibrant-nav-item" : "text-muted-foreground hover:text-foreground")}
- title={
- meetingState.manualActive
- ? "stop meeting"
- : meetingState.active
- ? "meeting detected"
- : "start meeting"
- }
- >
- {meetingState.active && (
- <span className="absolute -top-0.5 -right-0.5 h-1.5 w-1.5 rounded-full bg-foreground animate-pulse" />
- )}
- <Phone className="h-3.5 w-3.5" />
- </button>
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- onClick={toggleSidebar}
- className={cn("transition-colors", isTranslucent ? "vibrant-nav-item" : "text-muted-foreground hover:text-foreground")}
- >
- {sidebarCollapsed ? (
- <PanelLeftOpen className="h-4 w-4" />
- ) : (
- <PanelLeftClose className="h-4 w-4" />
- )}
- </button>
- </TooltipTrigger>
- <TooltipContent side="bottom" className="text-xs">
- {sidebarCollapsed ? "expand sidebar" : "collapse sidebar"} <kbd className="ml-1 px-1 py-0.5 bg-muted rounded text-[10px]">⌘B</kbd>
- </TooltipContent>
- </Tooltip>
- </div>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ onClick={toggleSidebar}
+ className={cn("transition-colors", isTranslucent ? "vibrant-nav-item" : "text-muted-foreground hover:text-foreground")}
+ >
+ {sidebarCollapsed ? (
+ <PanelLeftOpen className="h-4 w-4" />
+ ) : (
+ <PanelLeftClose className="h-4 w-4" />
+ )}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="text-xs">
+ {sidebarCollapsed ? "expand sidebar" : "collapse sidebar"} <kbd className="ml-1 px-1 py-0.5 bg-muted rounded text-[10px]">⌘B</kbd>
+ </TooltipContent>
+ </Tooltip>
</div>
- {/* Row 2: device icons */}
+ {/* Row 2: device status + action buttons */}
{!sidebarCollapsed && (() => {
const monitors = recordingDevices.filter((d) => d.kind === "monitor");
const inputs = recordingDevices.filter((d) => d.kind === "input");
@@ -393,25 +373,79 @@ function HomeContent() {
const screenOpacity = overlayData.screenActive ? 0.5 + Math.min(overlayData.captureFps / 2, 0.5) : 0.2;
const audioOpacity = overlayData.audioActive ? 0.5 + Math.min(overlayData.speechRatio, 0.5) : 0.2;
- const groups: { key: string; icon: typeof Monitor; count: number; title: string; opacity: number }[] = [];
- if (monitors.length > 0) groups.push({ key: "monitor", icon: Monitor, count: monitors.length, title: monitors.map((d) => d.name).join(", "), opacity: screenOpacity });
- if (inputs.length > 0) groups.push({ key: "mic", icon: Mic, count: inputs.length, title: inputs.map((d) => d.name).join(", "), opacity: audioOpacity });
- if (outputs.length > 0) groups.push({ key: "output", icon: Volume2, count: outputs.length, title: outputs.map((d) => d.name).join(", "), opacity: audioOpacity });
+ const groups: { key: string; icon: typeof Monitor; count: number; title: string; opacity: number; devices: RecordingDevice[] }[] = [];
+ if (monitors.length > 0) groups.push({ key: "monitor", icon: Monitor, count: monitors.length, title: monitors.map((d) => d.name).join(", "), opacity: screenOpacity, devices: monitors });
+ if (inputs.length > 0) groups.push({ key: "mic", icon: Mic, count: inputs.length, title: inputs.map((d) => d.name).join(", "), opacity: audioOpacity, devices: inputs });
+ if (outputs.length > 0) groups.push({ key: "output", icon: Volume2, count: outputs.length, title: outputs.map((d) => d.name).join(", "), opacity: audioOpacity, devices: outputs });
- if (groups.length === 0) return null;
return (
<div className="flex items-center gap-2 mt-1.5">
- {groups.map(({ key, icon: Icon, count, title, opacity }) => (
- <span key={key} className="flex items-center gap-0.5" title={title}>
- <Icon
- className={cn("h-3 w-3 transition-opacity duration-500", isTranslucent ? "vibrant-sidebar-fg" : "text-foreground")}
- style={{ opacity }}
- />
- {count > 1 && (
- <span className={cn("text-[9px] font-medium leading-none", isTranslucent ? "vibrant-sidebar-fg-muted" : "text-foreground/50")}>{count}</span>
- )}
- </span>
+ {groups.map(({ key, icon: Icon, count, title, opacity, devices: groupDevices }) => (
+ <Tooltip key={key}>
+ <TooltipTrigger asChild>
+ <button
+ className={cn(
+ "flex items-center gap-0.5 rounded px-0.5 transition-all",
+ key === "monitor"
+ ? "cursor-default"
+ : cn(
+ "cursor-pointer",
+ isTranslucent ? "hover:bg-white/10" : "hover:bg-muted"
+ )
+ )}
+ onClick={key === "monitor" ? undefined : async () => {
+ const allActive = groupDevices.every((d: RecordingDevice) => d.active);
+ const endpoint = allActive
+ ? "http://localhost:3030/audio/device/stop"
+ : "http://localhost:3030/audio/device/start";
+ for (const d of groupDevices) {
+ if (allActive || !d.active) {
+ const suffix = d.kind === "input" ? "input" : "output";
+ await fetch(endpoint, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ device_name: `${d.name} (${suffix})` }),
+ }).catch(() => {});
+ }
+ }
+ }}
+ >
+ <Icon
+ className={cn("h-3 w-3 transition-opacity duration-500", isTranslucent ? "vibrant-sidebar-fg" : "text-foreground")}
+ style={{ opacity }}
+ />
+ {count > 1 && (
+ <span className={cn("text-[9px] font-medium leading-none", isTranslucent ? "vibrant-sidebar-fg-muted" : "text-foreground/50")}>{count}</span>
+ )}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="text-xs">
+ {key === "monitor" ? title : `${title} — click to ${groupDevices.every((d: RecordingDevice) => d.active) ? "mute" : "unmute"}`}
+ </TooltipContent>
+ </Tooltip>
))}
+ <div className="w-px h-3 bg-border mx-0.5" />
+ <NotificationBell />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ onClick={toggleMeeting}
+ disabled={meetingLoading || (meetingState.active && !meetingState.manualActive)}
+ className={cn(
+ "relative flex items-center justify-center h-5 w-5 rounded transition-colors",
+ isTranslucent ? "vibrant-nav-item hover:bg-white/10" : "text-muted-foreground hover:text-foreground hover:bg-muted"
+ )}
+ >
+ {meetingState.active && (
+ <span className="absolute -top-0.5 -right-0.5 h-1.5 w-1.5 rounded-full bg-foreground animate-pulse" />
+ )}
+ <Phone className="h-3 w-3" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="text-xs">
+ {meetingState.manualActive ? "stop meeting" : meetingState.active ? "meeting detected" : "start meeting"}
+ </TooltipContent>
+ </Tooltip>
</div>
);
})()}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/health.rs b/apps/screenpipe-app-tauri/src-tauri/src/health.rs
index d4339a6f4..d07ed672f 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/health.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/health.rs
@@ -80,6 +80,31 @@ pub fn get_recording_info() -> RecordingInfo {
.clone()
}
+/// Cached audio device status from /audio/device/status API.
+/// Updated by the health polling loop so the tray can read it without blocking.
+#[derive(Clone, Debug)]
+pub struct AudioDeviceEntry {
+ pub name: String,
+ pub is_running: bool,
+}
+
+static AUDIO_DEVICE_STATUS: Lazy<RwLock<Vec<AudioDeviceEntry>>> =
+ Lazy::new(|| RwLock::new(Vec::new()));
+
+pub fn get_audio_device_status() -> Vec<AudioDeviceEntry> {
+ AUDIO_DEVICE_STATUS
+ .read()
+ .unwrap_or_else(|e| e.into_inner())
+ .clone()
+}
+
+pub fn set_audio_device_status(devices: Vec<AudioDeviceEntry>) {
+ let mut guard = AUDIO_DEVICE_STATUS
+ .write()
+ .unwrap_or_else(|e| e.into_inner());
+ *guard = devices;
+}
+
#[allow(dead_code)]
fn set_recording_status(status: RecordingStatus) {
RECORDING_INFO
@@ -395,6 +420,60 @@ pub async fn start_health_check(app: tauri::AppHandle) -> Result<()> {
}
}
+ // Fetch all audio devices (including user-disabled) for tray display
+ if let Ok(res) = reqwest::get("http://localhost:3030/audio/device/status").await {
+ if let Ok(devs) = res.json::<Vec<serde_json::Value>>().await {
+ let mut entries = Vec::new();
+ for d in &devs {
+ let name = d["name"].as_str().unwrap_or("").to_string();
+ let is_running = d["is_running"].as_bool().unwrap_or(false);
+ let is_user_disabled =
+ d["is_user_disabled"].as_bool().unwrap_or(false);
+ entries.push(AudioDeviceEntry {
+ name: name.clone(),
+ is_running,
+ });
+
+ // Add user-paused devices to the tray list so they
+ // stay visible with active=false (unchecked).
+ if is_user_disabled {
+ let already_listed = devices.iter().any(|dev| {
+ let full = format!(
+ "{} ({})",
+ dev.name,
+ if dev.kind == DeviceKind::AudioInput {
+ "input"
+ } else {
+ "output"
+ }
+ );
+ full == name
+ });
+ if !already_listed {
+ let kind = if name.contains("(input)") {
+ DeviceKind::AudioInput
+ } else if name.contains("(output)") {
+ DeviceKind::AudioOutput
+ } else {
+ continue;
+ };
+ let display_name = name
+ .replace(" (input)", "")
+ .replace(" (output)", "");
+ devices.push(DeviceInfo {
+ name: display_name,
+ kind,
+ active: false,
+ last_seen_secs_ago: 0,
+ });
+ }
+ }
+ }
+
+ set_audio_device_status(entries);
+ }
+ }
+
set_recording_info(status, devices);
let current_status = status_to_icon_key(status);
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/store.rs b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
index b9cd11eee..0d875b1f1 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/store.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
@@ -19,6 +19,13 @@ fn build_store(app: &AppHandle) -> anyhow::Result<Arc<tauri_plugin_store::Store<
let store_path = base_dir.join("store.bin");
let mut last_err = None;
+ // Ensure store.bin has restrictive permissions (contains API keys)
+ #[cfg(unix)]
+ if store_path.exists() {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&store_path, std::fs::Permissions::from_mode(0o600));
+ }
+
for attempt in 0..3u32 {
match StoreBuilder::new(app, store_path.clone()).build() {
Ok(s) => return Ok(s),
@@ -1016,16 +1023,19 @@ mod tests {
let mut corrupted = json!({
"aiPresets": ["corrupted_string_not_an_object"]
});
-
+
let sanitized = SettingsStore::sanitize_legacy_fields(corrupted);
-
+
// And let's test a valid object with missing/unknown provider to prove it works
let mut valid = json!({
"aiPresets": [{"provider": "unknown_provider"}]
});
let sanitized2 = SettingsStore::sanitize_legacy_fields(valid);
-
+
let presets = sanitized2.get("aiPresets").unwrap().as_array().unwrap();
- assert_eq!(presets[0].get("provider").unwrap().as_str().unwrap(), "custom");
+ assert_eq!(
+ presets[0].get("provider").unwrap().as_str().unwrap(),
+ "custom"
+ );
}
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
index 09a75edfb..f2b7c064b 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/tray.rs
@@ -4,7 +4,9 @@
use crate::commands::{hide_main_window, show_main_window};
use crate::enterprise_policy::is_tray_item_hidden;
-use crate::health::{get_recording_info, get_recording_status, DeviceKind, RecordingStatus};
+use crate::health::{
+ get_audio_device_status, get_recording_info, get_recording_status, DeviceKind, RecordingStatus,
+};
use crate::recording::RecordingState;
use crate::store::{get_store, OnboardingStore, SettingsStore};
use crate::updates::{is_enterprise_build, is_source_build};
@@ -415,24 +417,55 @@ fn create_dynamic_menu(
.build(app)?,
);
- if effective_status == RecordingStatus::Recording
- || effective_status == RecordingStatus::Starting
{
let info = get_recording_info();
- for (i, device) in info.devices.iter().enumerate() {
+
+ // Show monitors (non-clickable)
+ for device in info
+ .devices
+ .iter()
+ .filter(|d| d.kind == DeviceKind::Monitor)
+ {
let dot = if device.active { "●" } else { "○" };
- let icon = match device.kind {
- DeviceKind::Monitor => "▣",
- DeviceKind::AudioInput => "♪",
- DeviceKind::AudioOutput => "♫",
- };
- let label = format!(" {} {} {}", dot, icon, device.name);
+ let label = format!(" {} ▣ {}", dot, device.name);
menu_builder = menu_builder.item(
- &MenuItemBuilder::with_id(format!("device_{}", i), label)
+ &MenuItemBuilder::with_id(format!("monitor_{}", device.name), label)
.enabled(false)
.build(app)?,
);
}
+
+ // Show only the audio devices from get_recording_info (the ones
+ // the user configured in recording settings). User-disabled devices
+ // stay in the list but show as unchecked.
+ let device_status = get_audio_device_status();
+ for device in info
+ .devices
+ .iter()
+ .filter(|d| d.kind != DeviceKind::Monitor)
+ {
+ let suffix = if device.kind == DeviceKind::AudioInput {
+ "input"
+ } else {
+ "output"
+ };
+ let full_name = format!("{} ({})", device.name, suffix);
+ let icon = if device.kind == DeviceKind::AudioInput {
+ "♪"
+ } else {
+ "♫"
+ };
+ // Check if running from cached device status (reflects user-disable state)
+ let is_running = device_status
+ .iter()
+ .any(|d| d.name == full_name && d.is_running);
+ let label = format!(" {} {}", icon, device.name);
+ let toggle =
+ CheckMenuItemBuilder::with_id(format!("toggle_audio_device_{}", full_name), label)
+ .checked(is_running)
+ .build(app)?;
+ menu_builder = menu_builder.item(&toggle);
+ }
}
// Show "fix permissions" when recording is in error state
@@ -511,7 +544,11 @@ fn create_dynamic_menu(
menu_builder = menu_builder.item(&PredefinedMenuItem::separator(app)?);
let is_recording = effective_status == RecordingStatus::Recording;
- let label = if is_recording { "Recording" } else { "Record" };
+ let label = if is_recording {
+ "Recording"
+ } else {
+ "Stopped — click to record"
+ };
let toggle = CheckMenuItemBuilder::with_id("toggle_recording", label)
.checked(is_recording)
.build(app)?;
@@ -641,6 +678,41 @@ fn handle_menu_event(app_handle: &AppHandle, event: tauri::menu::MenuEvent) {
}
});
}
+ id if id.starts_with("toggle_audio_device_") => {
+ let device_name = id
+ .strip_prefix("toggle_audio_device_")
+ .unwrap()
+ .to_string();
+
+ // Check current state from cached device status.
+ // Default to "running" if device isn't in cache yet (it's shown
+ // checked in the tray, so first click should pause it).
+ let cached = get_audio_device_status();
+ let is_running = cached
+ .iter()
+ .find(|d| d.name == device_name)
+ .map(|d| d.is_running)
+ .unwrap_or(true);
+
+ // macOS CheckMenuItem already toggles the visual check on click.
+ // Just fire the API call — the health poll (every 1s) will sync state.
+ let endpoint = if is_running {
+ "http://localhost:3030/audio/device/stop"
+ } else {
+ "http://localhost:3030/audio/device/start"
+ };
+ tauri::async_runtime::spawn(async move {
+ let client = reqwest::Client::new();
+ let _ = client
+ .post(endpoint)
+ .header("Content-Type", "application/json")
+ .body(
+ serde_json::json!({"device_name": device_name}).to_string(),
+ )
+ .send()
+ .await;
+ });
+ }
"lock_vault" => {
let _ = app_handle.emit("vault-lock-requested", ());
}
diff --git a/crates/screenpipe-audio/src/audio_manager/device_monitor.rs b/crates/screenpipe-audio/src/audio_manager/device_monitor.rs
index 510e317cf..15113787c 100644
--- a/crates/screenpipe-audio/src/audio_manager/device_monitor.rs
+++ b/crates/screenpipe-audio/src/audio_manager/device_monitor.rs
@@ -359,40 +359,48 @@ pub async fn start_device_monitor(
// Check if system default input changed
if let Some(new_default_input) = default_tracker.check_input_changed() {
- info!("system default input changed to: {}", new_default_input);
+ if audio_manager
+ .user_disabled_devices()
+ .await
+ .contains(&new_default_input)
+ {
+ debug!("[DEVICE_RECOVERY] skipping default input change: {} is user-disabled", new_default_input);
+ } else {
+ info!("system default input changed to: {}", new_default_input);
- // Stop all current input devices
- for device_name in enabled_devices.iter() {
- if let Ok(device) = parse_audio_device(device_name) {
- if device.device_type == DeviceType::Input {
- let _ = audio_manager.stop_device(device_name).await;
+ // Stop all current input devices
+ for device_name in enabled_devices.iter() {
+ if let Ok(device) = parse_audio_device(device_name) {
+ if device.device_type == DeviceType::Input {
+ let _ = audio_manager.stop_device(device_name).await;
+ }
}
}
- }
- // Start the new default input device (reset cooldown on change)
- if let Ok(new_device) = parse_audio_device(&new_default_input) {
- failed_devices.remove(&new_default_input);
- match audio_manager.start_device(&new_device).await {
- Ok(()) => {
- info!(
- "switched to new system default input: {}",
- new_default_input
- );
- }
- Err(e) => {
- let count = failed_devices
- .entry(new_default_input.clone())
- .or_insert((0, Instant::now()));
- count.0 += 1;
- count.1 = Instant::now();
- error!(
+ // Start the new default input device (reset cooldown on change)
+ if let Ok(new_device) = parse_audio_device(&new_default_input) {
+ failed_devices.remove(&new_default_input);
+ match audio_manager.start_device(&new_device).await {
+ Ok(()) => {
+ info!(
+ "switched to new system default input: {}",
+ new_default_input
+ );
+ }
+ Err(e) => {
+ let count = failed_devices
+ .entry(new_default_input.clone())
+ .or_insert((0, Instant::now()));
+ count.0 += 1;
+ count.1 = Instant::now();
+ error!(
"failed to start new default input {}: {} (will back off)",
new_default_input, e
);
+ }
}
}
- }
+ } // else: skip user-disabled
}
// Check if system default output changed.
@@ -400,59 +408,68 @@ pub async fn start_device_monitor(
// This ensures continuous audio capture — if the new device
// fails to start, the old devices keep running as fallback.
if let Some(new_default_output) = default_tracker.check_output_changed().await {
- info!(
- "[DEVICE_RECOVERY] system default output changed to: {}",
- new_default_output
- );
-
- let new_started = if let Ok(new_device) =
- parse_audio_device(&new_default_output)
+ // Skip if new default is user-disabled
+ if audio_manager
+ .user_disabled_devices()
+ .await
+ .contains(&new_default_output)
{
- failed_devices.remove(&new_default_output);
- match audio_manager.start_device(&new_device).await {
- Ok(()) => {
- info!(
+ debug!("[DEVICE_RECOVERY] skipping default output change: {} is user-disabled", new_default_output);
+ } else {
+ info!(
+ "[DEVICE_RECOVERY] system default output changed to: {}",
+ new_default_output
+ );
+
+ let new_started = if let Ok(new_device) =
+ parse_audio_device(&new_default_output)
+ {
+ failed_devices.remove(&new_default_output);
+ match audio_manager.start_device(&new_device).await {
+ Ok(()) => {
+ info!(
"[DEVICE_RECOVERY] started new system default output: {}",
new_default_output
);
- true
- }
- Err(e) => {
- warn!(
+ true
+ }
+ Err(e) => {
+ warn!(
"[DEVICE_RECOVERY] failed to start new default output {}: {} — keeping old devices running",
new_default_output, e
);
- false
+ false
+ }
}
- }
- } else {
- false
- };
+ } else {
+ false
+ };
- // Only stop old output devices if the new one started successfully
- if new_started {
- // Don't stop the communications output device during swap
- #[cfg(target_os = "windows")]
- let comm_name = default_tracker.last_communications_output.clone();
- for device_name in audio_manager.enabled_devices().await.iter() {
- if *device_name == new_default_output {
- continue; // don't stop the one we just started
- }
+ // Only stop old output devices if the new one started successfully
+ if new_started {
+ // Don't stop the communications output device during swap
#[cfg(target_os = "windows")]
- if comm_name.as_deref() == Some(device_name.as_str()) {
- continue; // don't stop the communications device
- }
- if let Ok(device) = parse_audio_device(device_name) {
- if device.device_type == DeviceType::Output {
- info!(
- "[DEVICE_RECOVERY] stopping old output device: {}",
- device_name
- );
- let _ = audio_manager.stop_device(device_name).await;
+ let comm_name = default_tracker.last_communications_output.clone();
+ for device_name in audio_manager.enabled_devices().await.iter() {
+ if *device_name == new_default_output {
+ continue; // don't stop the one we just started
+ }
+ #[cfg(target_os = "windows")]
+ if comm_name.as_deref() == Some(device_name.as_str()) {
+ continue; // don't stop the communications device
+ }
+ if let Ok(device) = parse_audio_device(device_name) {
+ if device.device_type == DeviceType::Output {
+ info!(
+ "[DEVICE_RECOVERY] stopping old output device: {}",
+ device_name
+ );
+ let _ = audio_manager.stop_device(device_name).await;
+ }
}
}
}
- }
+ } // else: skip user-disabled
}
// Windows: check if the eCommunications output device changed.
@@ -504,13 +521,21 @@ pub async fn start_device_monitor(
// No backoff — missing input audio is critical.
{
let current_enabled = audio_manager.enabled_devices().await;
+ let user_disabled = audio_manager.user_disabled_devices().await;
let has_input = current_enabled.iter().any(|name| {
parse_audio_device(name)
.map(|d| d.device_type == DeviceType::Input)
.unwrap_or(false)
});
+ // Don't try to recover if user explicitly disabled all inputs
+ let all_inputs_user_disabled = !has_input && {
+ match default_input_device() {
+ Ok(d) => user_disabled.contains(&d.to_string()),
+ Err(_) => false,
+ }
+ };
- if !has_input {
+ if !has_input && !all_inputs_user_disabled {
no_input_retry_count += 1;
// Throttle logging after many retries to avoid spamming logs
@@ -575,13 +600,21 @@ pub async fn start_device_monitor(
// or output device was lost during a device change.
{
let current_enabled = audio_manager.enabled_devices().await;
+ let user_disabled = audio_manager.user_disabled_devices().await;
let has_output = current_enabled.iter().any(|name| {
parse_audio_device(name)
.map(|d| d.device_type == DeviceType::Output)
.unwrap_or(false)
});
+ // Don't try to recover if user explicitly disabled output
+ let output_user_disabled = !has_output && {
+ match default_output_device().await {
+ Ok(d) => user_disabled.contains(&d.to_string()),
+ Err(_) => false,
+ }
+ };
- if !has_output {
+ if !has_output && !output_user_disabled {
// Apply backoff: skip this cycle if we haven't waited long enough.
// Transient errors (SCK not ready) use short backoff (2-8s).
// Permanent errors (no display) use longer backoff (up to 120s).
@@ -644,7 +677,17 @@ pub async fn start_device_monitor(
// 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;
+ let user_disabled_for_stale = audio_manager.user_disabled_devices().await;
for device_name in stale_devices {
+ // Don't restart user-disabled devices — they're supposed to be stopped
+ if user_disabled_for_stale.contains(&device_name) {
+ debug!(
+ "[DEVICE_RECOVERY] stale handle for user-disabled device {}, cleaning up only",
+ device_name
+ );
+ let _ = audio_manager.cleanup_stale_device(&device_name).await;
+ continue;
+ }
warn!(
"[DEVICE_RECOVERY] detected stale recording handle for {}, cleaning up for restart",
device_name
@@ -792,7 +835,14 @@ pub async fn start_device_monitor(
}
}
+ let user_disabled_for_reconnect = audio_manager.user_disabled_devices().await;
for device_name in disconnected_devices.clone() {
+ // Skip user-disabled devices — they're intentionally stopped
+ if user_disabled_for_reconnect.contains(&device_name) {
+ disconnected_devices.remove(&device_name);
+ continue;
+ }
+
let device = match parse_audio_device(&device_name) {
Ok(device) => device,
Err(e) => {
@@ -863,6 +913,15 @@ pub async fn start_device_monitor(
continue;
}
+ // Skip user-disabled (paused) devices — don't restart them
+ if audio_manager
+ .user_disabled_devices()
+ .await
+ .contains(device_name)
+ {
+ continue;
+ }
+
match audio_manager.start_device(&device).await {
Ok(()) => {
//
diff --git a/crates/screenpipe-audio/src/audio_manager/manager.rs b/crates/screenpipe-audio/src/audio_manager/manager.rs
index da39e844c..1c905046f 100644
--- a/crates/screenpipe-audio/src/audio_manager/manager.rs
+++ b/crates/screenpipe-audio/src/audio_manager/manager.rs
@@ -100,6 +100,10 @@ pub struct AudioManager {
/// Output devices temporarily stopped due to DRM content detection.
/// Stored so they can be restarted when DRM clears.
drm_stopped_devices: Arc<RwLock<Vec<AudioDevice>>>,
+ /// Devices explicitly disabled by the user via the API/UI.
+ /// The device monitor must never auto-start devices in this set.
+ /// Cleared on global start/stop but preserved across reconnects.
+ user_disabled_devices: Arc<RwLock<HashSet<String>>>,
}
/// Result of checking / restarting the two central handler tasks.
@@ -162,6 +166,7 @@ impl AudioManager {
engine: Arc::new(RwLock::new(None)),
reconciliation_handle: Arc::new(RwLock::new(None)),
drm_stopped_devices: Arc::new(RwLock::new(Vec::new())),
+ user_disabled_devices: Arc::new(RwLock::new(HashSet::new())),
};
Ok(manager)
@@ -310,15 +315,32 @@ impl AudioManager {
.enabled_devices
.remove(device_name);
- self.device_manager.stop_device(&device).await?;
+ self.stop_device_recording(&device).await
+ }
- if let Some(pair) = self.recording_handles.get(&device) {
- let handle = pair.value();
+ /// Stop a device's recording without removing it from enabled_devices.
+ /// Idempotent — safe to call on already-stopped devices.
+ async fn stop_device_recording(&self, device: &AudioDevice) -> Result<()> {
+ // Signal the recording loop to stop BEFORE aborting the handle,
+ // so it exits cleanly without triggering "stream dead" warnings.
+ if let Some(is_running) = self.device_manager.is_running_mut(device) {
+ is_running.store(false, std::sync::atomic::Ordering::Relaxed);
+ }
+
+ // Ignore "already stopped" errors
+ if let Err(e) = self.device_manager.stop_device(device).await {
+ let msg = e.to_string();
+ if !msg.contains("already stopped") && !msg.contains("not running") {
+ return Err(e);
+ }
+ }
+ if let Some(pair) = self.recording_handles.get(device) {
+ let handle = pair.value();
handle.lock().await.abort();
}
- self.recording_handles.remove(&device);
+ self.recording_handles.remove(device);
Ok(())
}
@@ -327,6 +349,57 @@ impl AudioManager {
self.status.read().await.clone()
}
+ /// Temporarily pause a device without changing the configured device list.
+ /// Idempotent — safe to call if already paused. Never errors.
+ pub async fn pause_device(&self, device_name: &str) -> Result<()> {
+ // Mark as disabled FIRST so no monitor path can race and restart it
+ self.user_disabled_devices
+ .write()
+ .await
+ .insert(device_name.to_string());
+
+ // Best-effort stop — ignore all errors (already stopped, not found, etc.)
+ if let Ok(device) = parse_audio_device(device_name) {
+ let _ = self.stop_device_recording(&device).await;
+ }
+ info!("user paused audio device: {}", device_name);
+ Ok(())
+ }
+
+ /// Resume a previously paused device. Idempotent — safe to call if already running.
+ pub async fn resume_device(&self, device_name: &str) -> Result<()> {
+ // Remove from disabled FIRST so start_device gate allows it
+ self.user_disabled_devices.write().await.remove(device_name);
+
+ let device = match parse_audio_device(device_name) {
+ Ok(device) => device,
+ Err(_) => return Err(anyhow!("Device {} not found", device_name)),
+ };
+ self.start_device(&device).await?;
+ info!("user resumed audio device: {}", device_name);
+ Ok(())
+ }
+
+ /// Mark a device as user-disabled. The device monitor will not auto-start it.
+ pub async fn user_disable_device(&self, device_name: &str) {
+ self.user_disabled_devices
+ .write()
+ .await
+ .insert(device_name.to_string());
+ info!("user disabled audio device: {}", device_name);
+ }
+
+ /// Remove a device from the user-disabled set, allowing auto-start again.
+ pub async fn user_enable_device(&self, device_name: &str) {
+ self.user_disabled_devices.write().await.remove(device_name);
+ info!("user re-enabled audio device: {}", device_name);
+ }
+
+ /// Returns the set of devices the user has explicitly disabled.
+ pub async fn user_disabled_devices(&self) -> HashSet<String> {
+ self.user_disabled_devices.read().await.clone()
+ }
+
pub async fn start_device(&self, device: &AudioDevice) -> Result<()> {
// Don't restart devices that are paused due to DRM content detection.
// The monitor watcher will call start_output_devices() when DRM clears.
@@ -340,6 +413,17 @@ impl AudioManager {
return Ok(());
}
+ // Don't restart devices the user explicitly disabled via API/UI.
+ if self
+ .user_disabled_devices
+ .read()
+ .await
+ .contains(&device.to_string())
+ {
+ debug!("skipping auto-start of user-disabled device: {}", device);
+ return Ok(());
+ }
+
if let Err(e) = self.device_manager.start_device(device).await {
let err_str = e.to_string();
diff --git a/crates/screenpipe-connect/src/oauth.rs b/crates/screenpipe-connect/src/oauth.rs
index 7d32b2544..8ce9e3ebd 100644
--- a/crates/screenpipe-connect/src/oauth.rs
+++ b/crates/screenpipe-connect/src/oauth.rs
@@ -161,7 +161,13 @@ pub fn write_oauth_token_instance(
if let Some(expires_in) = data["expires_in"].as_u64() {
stored["expires_at"] = Value::from(unix_now() + expires_in);
}
- std::fs::write(path, serde_json::to_string_pretty(&stored)?)?;
+ std::fs::write(&path, serde_json::to_string_pretty(&stored)?)?;
+ // Restrict permissions — file contains OAuth credentials
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
+ }
Ok(())
}
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index 0feceff94..4027e77a1 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -698,7 +698,14 @@ fn resolve_preset(pipes_dir: &Path, preset_id: &str) -> Option<ResolvedPreset> {
}
});
if let Ok(json) = serde_json::to_string_pretty(&default_store) {
- let _ = std::fs::write(&store_path, json);
+ let _ = std::fs::write(&store_path, &json);
+ // Restrict permissions — file contains API keys and credentials
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ =
+ std::fs::set_permissions(&store_path, std::fs::Permissions::from_mode(0o600));
+ }
info!("created store.bin with default preset (screenpipe cloud)");
}
}
diff --git a/crates/screenpipe-engine/src/retention.rs b/crates/screenpipe-engine/src/retention.rs
index 913e62ade..01b804c82 100644
--- a/crates/screenpipe-engine/src/retention.rs
+++ b/crates/screenpipe-engine/src/retention.rs
@@ -387,6 +387,11 @@ async fn do_local_cleanup(db: &Arc<DatabaseManager>, cutoff: DateTime<Utc>) -> a
if let Err(e) = db.cleanup_orphaned_chunks().await {
warn!("retention: orphan chunk cleanup failed: {}", e);
}
+ // Reclaim disk space — without VACUUM, SQLite keeps deleted pages
+ info!("retention: running incremental vacuum to reclaim disk space");
+ if let Err(e) = db.execute_raw_sql("PRAGMA incremental_vacuum(1000)").await {
+ warn!("retention: incremental vacuum failed: {}", e);
+ }
}
Ok(total)
diff --git a/crates/screenpipe-engine/src/routes/audio.rs b/crates/screenpipe-engine/src/routes/audio.rs
index 1ca474c32..4629de6eb 100644
--- a/crates/screenpipe-engine/src/routes/audio.rs
+++ b/crates/screenpipe-engine/src/routes/audio.rs
@@ -11,7 +11,7 @@ use axum::{
use oasgen::{oasgen, OaSchema};
use screenpipe_audio::core::device::{
- default_input_device, default_output_device, list_audio_devices, AudioDevice,
+ default_input_device, default_output_device, list_audio_devices,
};
use serde::{Deserialize, Serialize};
@@ -90,26 +90,13 @@ pub(crate) async fn start_audio_device(
Json(payload): Json<AudioDeviceControlRequest>,
) -> Result<Json<AudioDeviceControlResponse>, (StatusCode, JsonResponse<Value>)> {
let device_name = payload.device_name.clone();
- let device: AudioDevice;
- // todo Better handling error
- match AudioDevice::from_name(&payload.device_name) {
- Ok(audio_device) => device = audio_device,
- Err(e) => {
- return Err((
- StatusCode::UNPROCESSABLE_ENTITY,
- JsonResponse(
- json!({"success": false, "message": format!("device {} not found: {}", device_name.clone(), e)}),
- ),
- ))
- }
- };
-
- if let Err(e) = state.audio_manager.start_device(&device).await {
+
+ if let Err(e) = state.audio_manager.resume_device(&device_name).await {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
JsonResponse(json!({
"success": false,
- "message": format!("Failed to start recording device {}: {}", device_name.clone(), e)
+ "message": format!("Failed to start recording device {}: {}", device_name, e)
})),
));
}
@@ -127,12 +114,12 @@ pub(crate) async fn stop_audio_device(
) -> Result<Json<AudioDeviceControlResponse>, (StatusCode, JsonResponse<Value>)> {
let device_name = payload.device_name.clone();
- if let Err(e) = state.audio_manager.stop_device(&device_name).await {
+ if let Err(e) = state.audio_manager.pause_device(&device_name).await {
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
JsonResponse(json!({
"success": false,
- "message": format!("Failed to stop recording device {}: {}", device_name.clone(), e)
+ "message": format!("Failed to stop recording device {}: {}", device_name, e)
})),
));
}
@@ -143,6 +130,43 @@ pub(crate) async fn stop_audio_device(
}))
}
+#[derive(OaSchema, Serialize)]
+pub(crate) struct DeviceStatusEntry {
+ pub name: String,
+ pub is_running: bool,
+ pub is_user_disabled: bool,
+}
+
+#[oasgen]
+pub(crate) async fn audio_device_status(
+ State(state): State<Arc<AppState>>,
+) -> Result<JsonResponse<Vec<DeviceStatusEntry>>, (StatusCode, JsonResponse<Value>)> {
+ let all_devices = list_audio_devices().await.map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": format!("Failed to list audio devices: {}", e)})),
+ )
+ })?;
+ let enabled = state.audio_manager.enabled_devices().await;
+ let user_disabled = state.audio_manager.user_disabled_devices().await;
+
+ let entries: Vec<DeviceStatusEntry> = all_devices
+ .into_iter()
+ .map(|d| {
+ let name = d.to_string();
+ let in_enabled = enabled.contains(&name);
+ let is_disabled = user_disabled.contains(&name);
+ DeviceStatusEntry {
+ is_running: in_enabled && !is_disabled,
+ is_user_disabled: is_disabled,
+ name,
+ }
+ })
+ .collect();
+
+ Ok(JsonResponse(entries))
+}
+
#[oasgen]
pub(crate) async fn start_audio(
State(state): State<Arc<AppState>>,
diff --git a/crates/screenpipe-engine/src/routes/content.rs b/crates/screenpipe-engine/src/routes/content.rs
index 4170dd546..4c4d93d2c 100644
--- a/crates/screenpipe-engine/src/routes/content.rs
+++ b/crates/screenpipe-engine/src/routes/content.rs
@@ -521,10 +521,17 @@ fn validate_raw_sql(query: &str) -> Result<(), String> {
.join(" ");
let upper = normalized.to_uppercase();
- // Only SELECT queries need limit validation
+ // Only allow read-only queries — block writes via /raw_sql
let trimmed = upper.trim_start();
- if !trimmed.starts_with("SELECT") {
- return Ok(());
+ if !trimmed.starts_with("SELECT")
+ && !trimmed.starts_with("WITH")
+ && !trimmed.starts_with("EXPLAIN")
+ {
+ return Err(
+ "Query rejected: /raw_sql only allows SELECT, WITH, and EXPLAIN queries. \
+ Use the dedicated API endpoints for writes."
+ .to_string(),
+ );
}
// Check for LIMIT clause
diff --git a/crates/screenpipe-engine/src/server.rs b/crates/screenpipe-engine/src/server.rs
index 01bb9b03a..72dfe8015 100644
--- a/crates/screenpipe-engine/src/server.rs
+++ b/crates/screenpipe-engine/src/server.rs
@@ -18,7 +18,8 @@ use crate::{
routes::{
activity_summary::get_activity_summary,
audio::{
- api_list_audio_devices, start_audio, start_audio_device, stop_audio, stop_audio_device,
+ api_list_audio_devices, audio_device_status, start_audio, start_audio_device,
+ stop_audio, stop_audio_device,
},
content::{
add_tags, add_to_database, execute_raw_sql, get_tags_batch, merge_frames_handler,
@@ -521,6 +522,7 @@ impl SCServer {
.get("/search/keyword", keyword_search_handler)
.post("/audio/device/start", start_audio_device)
.post("/audio/device/stop", stop_audio_device)
+ .get("/audio/device/status", audio_device_status)
.get("/elements", search_elements)
.get("/frames/:frame_id/elements", get_frame_elements)
.get("/activity-summary", get_activity_summary)