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(linux): bound wake-lock acquisition without blocking Tokio (#7106)

jualvarez1ab96568e268
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/power_awake.rs b/apps/screenpipe-app-tauri/src-tauri/src/power_awake.rs
index bffbd8001..503510a1b 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/power_awake.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/power_awake.rs
@@ -4,6 +4,6 @@
#[tauri::command]
#[specta::specta]
-pub fn set_keep_awake(enabled: bool) -> Result<(), String> {
- screenpipe_engine::power::set_keep_awake(enabled)
+pub async fn set_keep_awake(enabled: bool) -> Result<(), String> {
+ screenpipe_engine::power::set_keep_awake_async(enabled).await
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
index 2e9eb193e..1b6a0ca54 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs
@@ -605,7 +605,9 @@ impl ServerCore {
})
.unwrap_or_default();
let power_manager = start_power_manager_with_pref(initial_power_pref);
- if let Err(e) = screenpipe_engine::power::set_keep_awake(config.keep_computer_awake) {
+ if let Err(e) =
+ screenpipe_engine::power::set_keep_awake_async(config.keep_computer_awake).await
+ {
warn!("failed to apply keep-awake setting: {}", e);
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/storage_migration.rs b/apps/screenpipe-app-tauri/src-tauri/src/storage_migration.rs
index 6ba372e7c..5c64deaa2 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/storage_migration.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/storage_migration.rs
@@ -313,7 +313,7 @@ pub(crate) async fn resume_before_startup(
// large index: expose that work and keep retry unavailable until the
// server and saved capture preference have actually been restored.
let awake =
- screenpipe_engine::power::KeepAwakeGuard::acquire().map_err(|e| e.to_string())?;
+ screenpipe_engine::power::KeepAwakeGuard::acquire_async().await?;
update_operation(app, |operation| {
*operation = Operation {
root: Some(root.clone()),
@@ -353,7 +353,7 @@ pub(crate) async fn resume_before_startup(
{
return Ok(None);
}
- let awake = screenpipe_engine::power::KeepAwakeGuard::acquire().map_err(|e| e.to_string())?;
+ let awake = screenpipe_engine::power::KeepAwakeGuard::acquire_async().await?;
crate::health::set_boot_phase(
"migrating_database",
Some("Resuming saved storage migration"),
@@ -780,12 +780,14 @@ async fn start_storage_migration_inner(
}
// Independent of the recording preference, which startup reapplies during switchover.
// Acquire before pausing so a failed wake lock never strands recording.
- let awake = screenpipe_engine::power::KeepAwakeGuard::acquire().map_err(|error| {
- let error = format!("Could not prevent sleep. Migration has not started: {error}");
- report_migration_failure(&app, &root, &error);
- let _ = save_migration_error(&root, &error);
- error
- })?;
+ let awake = screenpipe_engine::power::KeepAwakeGuard::acquire_async()
+ .await
+ .map_err(|error| {
+ let error = format!("Could not prevent sleep. Migration has not started: {error}");
+ report_migration_failure(&app, &root, &error);
+ let _ = save_migration_error(&root, &error);
+ error
+ })?;
// Write BEFORE pausing recording. A crash, kill, or failed error write must
// never erase the block and let the next launch pause recording again.
save_migration_error(&root, INTERRUPTED_MIGRATION).map_err(|error| {
diff --git a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
index 25cc96ca3..7a2fa3328 100644
--- a/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
+++ b/crates/screenpipe-engine/src/bin/screenpipe-engine.rs
@@ -559,7 +559,9 @@ async fn main() -> anyhow::Result<()> {
!config.analytics_enabled,
)?);
- if let Err(e) = screenpipe_engine::power::set_keep_awake(config.keep_computer_awake) {
+ if let Err(e) =
+ screenpipe_engine::power::set_keep_awake_async(config.keep_computer_awake).await
+ {
warn!("failed to apply keep-awake setting: {}", e);
}
diff --git a/crates/screenpipe-engine/src/power/awake.rs b/crates/screenpipe-engine/src/power/awake.rs
index faaf8734d..455e4b171 100644
--- a/crates/screenpipe-engine/src/power/awake.rs
+++ b/crates/screenpipe-engine/src/power/awake.rs
@@ -13,6 +13,20 @@ impl KeepAwakeGuard {
pub fn acquire() -> Result<Self, String> {
Self::start()
}
+
+ /// Acquire on Tokio without blocking its executor on Linux D-Bus.
+ pub async fn acquire_async() -> Result<Self, String> {
+ #[cfg(target_os = "linux")]
+ {
+ tokio::time::timeout(std::time::Duration::from_secs(5), Self::start_async())
+ .await
+ .map_err(|_| "timed out acquiring logind wake lock after 5s".to_string())?
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ Self::start()
+ }
+ }
}
/// Enable or disable the process-wide keep-awake lock.
@@ -33,6 +47,21 @@ pub fn set_keep_awake(enabled: bool) -> Result<(), String> {
Ok(())
}
+/// Apply the setting without holding up the async executor on Linux.
+/// The synchronous setter serializes updates; its D-Bus acquisition is bounded.
+pub async fn set_keep_awake_async(enabled: bool) -> Result<(), String> {
+ #[cfg(target_os = "linux")]
+ {
+ tokio::task::spawn_blocking(move || set_keep_awake(enabled))
+ .await
+ .map_err(|e| format!("keep-awake setting task failed: {e}"))?
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ set_keep_awake(enabled)
+ }
+}
+
#[cfg(target_os = "macos")]
pub struct KeepAwakeGuard {
assertions: Vec<u32>,
@@ -230,14 +259,34 @@ pub struct KeepAwakeGuard {
#[cfg(target_os = "linux")]
impl KeepAwakeGuard {
fn start() -> Result<Self, String> {
- let connection =
- zbus::blocking::Connection::system().map_err(|e| format!("D-Bus system bus: {e}"))?;
- let proxy = zbus::blocking::Proxy::new(
+ // Keep the synchronous API usable even inside an existing runtime.
+ // Async callers use acquire_async directly; this worker also gets its
+ // timeout, including connection/authentication rather than just Inhibit.
+ std::thread::Builder::new()
+ .name("screenpipe-keep-awake".into())
+ .spawn(|| {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .map_err(|e| format!("failed to create keep-awake runtime: {e}"))?
+ .block_on(Self::acquire_async())
+ })
+ .map_err(|e| format!("failed to spawn keep-awake thread: {e}"))?
+ .join()
+ .map_err(|_| "keep-awake thread panicked".to_string())?
+ }
+
+ async fn start_async() -> Result<Self, String> {
+ let connection = zbus::Connection::system()
+ .await
+ .map_err(|e| format!("D-Bus system bus: {e}"))?;
+ let proxy = zbus::Proxy::new(
&connection,
"org.freedesktop.login1",
"/org/freedesktop/login1",
"org.freedesktop.login1.Manager",
)
+ .await
.map_err(|e| format!("logind D-Bus proxy: {e}"))?;
let fd: zbus::zvariant::OwnedFd = proxy
.call(
@@ -249,6 +298,7 @@ impl KeepAwakeGuard {
"block",
),
)
+ .await
.map_err(|e| format!("logind Inhibit call failed: {e}"))?;
Ok(Self { _fd: fd })
@@ -264,3 +314,7 @@ impl KeepAwakeGuard {
Err("keep-awake is not supported on this platform".to_string())
}
}
+
+#[cfg(all(test, target_os = "linux"))]
+#[path = "awake_tests.rs"]
+mod tests;
diff --git a/crates/screenpipe-engine/src/power/awake_tests.rs b/crates/screenpipe-engine/src/power/awake_tests.rs
new file mode 100644
index 000000000..dc69ec771
--- /dev/null
+++ b/crates/screenpipe-engine/src/power/awake_tests.rs
@@ -0,0 +1,397 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+// Live coverage: cargo test -p screenpipe-engine --lib power::awake::tests
+// --features zbus/tokio -- --include-ignored. Explicitly enable Tokio so
+// feature-unification changes cannot hide the original nested-runtime panic.
+// Live tests require logind; default tests use isolated child processes and
+// cover missing/stalled buses without privileges.
+
+use super::{set_keep_awake, set_keep_awake_async, KeepAwakeGuard};
+use std::sync::{Arc, Barrier, Mutex};
+use std::time::{Duration, Instant};
+
+// Live tests share the process-wide setting. Serialize them and always release
+// it, including on assertion failure. Other Screenpipe processes are excluded.
+static LIVE_TEST: Mutex<()> = Mutex::new(());
+
+fn with_logind(test: impl FnOnce()) {
+ let _serial = LIVE_TEST.lock().unwrap_or_else(|e| e.into_inner());
+ struct Reset;
+ impl Drop for Reset {
+ fn drop(&mut self) {
+ set_keep_awake(false).expect("release test setting");
+ }
+ }
+ let _reset = Reset;
+ expect_inhibitors(0);
+ test();
+ expect_inhibitors(0);
+}
+
+fn expect_inhibitors(expected: usize) {
+ // Also safe when called inside a Tokio test, without masking acquisition
+ // bugs in the production API under test.
+ std::thread::spawn(move || {
+ let connection = zbus::blocking::Connection::system().unwrap();
+ let proxy = zbus::blocking::Proxy::new(
+ &connection,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ )
+ .unwrap();
+ let deadline = Instant::now() + Duration::from_secs(2);
+ loop {
+ let locks: Vec<(String, String, String, String, u32, u32)> =
+ proxy.call("ListInhibitors", &()).unwrap();
+ let ours: Vec<_> = locks
+ .iter()
+ .filter(|lock| lock.1 == "screenpipe" && lock.5 == std::process::id())
+ .collect();
+ for lock in &ours {
+ assert_eq!(lock.0, "sleep:idle");
+ assert_eq!(lock.3, "block");
+ }
+ if ours.len() == expected {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "expected {expected} inhibitors, got {ours:?}"
+ );
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ })
+ .join()
+ .unwrap();
+}
+
+#[test]
+#[ignore = "requires a real system bus and permission to inhibit logind"]
+fn sync_lifetime_and_independent_setting() {
+ with_logind(|| {
+ let migration = KeepAwakeGuard::acquire().expect("acquire migration lock");
+ let recovery = KeepAwakeGuard::acquire().expect("acquire recovery lock");
+ expect_inhibitors(2);
+ for _ in 0..3 {
+ set_keep_awake(true).unwrap();
+ set_keep_awake(true).unwrap();
+ expect_inhibitors(3);
+ set_keep_awake(false).unwrap();
+ set_keep_awake(false).unwrap();
+ expect_inhibitors(2);
+ }
+ drop(migration);
+ expect_inhibitors(1);
+ drop(recovery);
+ });
+}
+
+fn runtime_lifetime(runtime: tokio::runtime::Runtime) {
+ with_logind(|| {
+ let guard = runtime.block_on(async {
+ set_keep_awake_async(true).await.unwrap();
+ let guard = KeepAwakeGuard::acquire_async()
+ .await
+ .expect("acquire from Tokio");
+ expect_inhibitors(2);
+ set_keep_awake_async(false).await.unwrap();
+ guard
+ });
+ drop(runtime);
+ // logind owns the lifetime through the FD, not the worker or runtime.
+ expect_inhibitors(1);
+ drop(guard);
+ });
+}
+
+#[test]
+#[ignore = "requires a real system bus and permission to inhibit logind"]
+fn current_thread_runtime_and_shutdown() {
+ runtime_lifetime(
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap(),
+ );
+}
+
+#[test]
+#[ignore = "requires a real system bus and permission to inhibit logind"]
+fn multi_thread_runtime_and_shutdown() {
+ runtime_lifetime(
+ tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .build()
+ .unwrap(),
+ );
+}
+
+#[test]
+#[ignore = "requires a real system bus and permission to inhibit logind"]
+fn concurrent_acquisitions_release_independently() {
+ with_logind(|| {
+ let ready = Arc::new(Barrier::new(5));
+ let release = Arc::new(Barrier::new(5));
+ let workers: Vec<_> = (0..4)
+ .map(|_| {
+ let ready = ready.clone();
+ let release = release.clone();
+ std::thread::spawn(move || {
+ let setting = set_keep_awake(true);
+ let guard = KeepAwakeGuard::acquire();
+ ready.wait();
+ release.wait();
+ setting.expect("concurrent setting");
+ drop(guard.expect("concurrent acquisition"));
+ })
+ })
+ .collect();
+ ready.wait();
+ // Release the workers even if the assertion fails.
+ let observed = std::panic::catch_unwind(|| expect_inhibitors(5));
+ release.wait();
+ for worker in workers {
+ worker.join().unwrap();
+ }
+ observed.unwrap();
+ expect_inhibitors(1);
+ set_keep_awake(false).unwrap();
+ });
+}
+
+#[test]
+#[ignore = "requires a real system bus and permission to inhibit logind"]
+fn cancelled_task_releases_only_its_lock() {
+ with_logind(|| {
+ let independent = KeepAwakeGuard::acquire().unwrap();
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ runtime.block_on(async {
+ let (ready, acquired) = tokio::sync::oneshot::channel();
+ let task = tokio::spawn(async move {
+ let _guard = KeepAwakeGuard::acquire_async().await.unwrap();
+ ready.send(()).unwrap();
+ std::future::pending::<()>().await;
+ });
+ acquired.await.unwrap();
+ expect_inhibitors(2);
+ task.abort();
+ assert!(task.await.unwrap_err().is_cancelled());
+ });
+ expect_inhibitors(1);
+ drop(independent);
+ });
+}
+
+#[test]
+#[ignore = "requires a real system bus and permission to inhibit logind"]
+fn unwinding_releases_only_its_lock() {
+ with_logind(|| {
+ let independent = KeepAwakeGuard::acquire().unwrap();
+ let result = std::panic::catch_unwind(|| {
+ let _guard = KeepAwakeGuard::acquire().unwrap();
+ expect_inhibitors(2);
+ panic!("simulated caller failure");
+ });
+ assert!(result.is_err());
+ expect_inhibitors(1);
+ drop(independent);
+ });
+}
+
+#[test]
+fn unavailable_bus_returns_errors_without_poisoning_state() {
+ // Change the bus address only in a child: process-global env mutation would
+ // race with the live tests and any other D-Bus users in the test process.
+ let module = module_path!().split_once("::").unwrap().1;
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ &format!("{module}::unavailable_bus_child"),
+ "--ignored",
+ "--nocapture",
+ ])
+ .env("SCREENPIPE_AWAKE_FAILURE_TEST", "1")
+ .env(
+ "DBUS_SYSTEM_BUS_ADDRESS",
+ "unix:path=/dev/null/screenpipe-no-bus",
+ )
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
+}
+
+#[test]
+#[ignore = "child process only; started by unavailable_bus_returns_errors_without_poisoning_state"]
+fn unavailable_bus_child() {
+ if std::env::var("SCREENPIPE_AWAKE_FAILURE_TEST").as_deref() != Ok("1") {
+ return;
+ }
+ fn exercise() {
+ for _ in 0..3 {
+ let error = KeepAwakeGuard::acquire()
+ .err()
+ .expect("bus must be unavailable");
+ assert!(error.starts_with("D-Bus system bus:"), "{error}");
+ let error = set_keep_awake(true).unwrap_err();
+ assert!(error.starts_with("D-Bus system bus:"), "{error}");
+ set_keep_awake(false).expect("failure must not poison the settings mutex");
+ }
+ }
+ exercise();
+ for runtime in [
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap(),
+ tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .build()
+ .unwrap(),
+ ] {
+ runtime.block_on(async {
+ exercise();
+ let error = KeepAwakeGuard::acquire_async()
+ .await
+ .err()
+ .expect("missing bus");
+ assert!(error.starts_with("D-Bus system bus:"), "{error}");
+ assert!(set_keep_awake_async(true).await.is_err());
+ set_keep_awake_async(false).await.unwrap();
+ });
+ }
+}
+
+#[test]
+fn stalled_bus_has_bounded_wait_and_allows_cancellation() {
+ use std::io::Read;
+ use std::os::unix::net::UnixListener;
+ use std::sync::atomic::{AtomicBool, Ordering};
+ let path = std::env::temp_dir().join(format!(
+ "screenpipe-stalled-bus-{}.sock",
+ std::process::id()
+ ));
+ let listener = UnixListener::bind(&path).unwrap();
+ listener.set_nonblocking(true).unwrap();
+ let stop = Arc::new(AtomicBool::new(false));
+ let stopped = stop.clone();
+ let server = std::thread::spawn(move || {
+ let mut connections = Vec::new();
+ while !stopped.load(Ordering::SeqCst) {
+ if let Ok((stream, _)) = listener.accept() {
+ stream.set_nonblocking(true).unwrap();
+ connections.push(stream);
+ }
+ // Accept authentication bytes but deliberately never answer.
+ connections.retain_mut(|stream| {
+ let mut bytes = [0; 256];
+ !matches!(stream.read(&mut bytes), Ok(0))
+ });
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ });
+ let module = module_path!().split_once("::").unwrap().1;
+ let mut child = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ &format!("{module}::stalled_bus_child"),
+ "--ignored",
+ "--nocapture",
+ ])
+ .env("SCREENPIPE_AWAKE_STALL_TEST", "1")
+ .env(
+ "DBUS_SYSTEM_BUS_ADDRESS",
+ format!("unix:path={}", path.display()),
+ )
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()
+ .unwrap();
+ let deadline = Instant::now() + Duration::from_secs(25);
+ while child.try_wait().unwrap().is_none() && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ let timed_out = child.try_wait().unwrap().is_none();
+ if timed_out {
+ child.kill().unwrap();
+ }
+ let output = child.wait_with_output().unwrap();
+ stop.store(true, Ordering::SeqCst);
+ server.join().unwrap();
+ std::fs::remove_file(path).unwrap();
+ assert!(
+ !timed_out,
+ "wake lock blocked the test process beyond its deadline"
+ );
+ assert!(
+ output.status.success(),
+ "{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
+}
+
+#[test]
+#[ignore = "child process only; started by stalled_bus_has_bounded_wait_and_allows_cancellation"]
+fn stalled_bus_child() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ if std::env::var("SCREENPIPE_AWAKE_STALL_TEST").as_deref() != Ok("1") {
+ return;
+ }
+ let start = Instant::now();
+ let error = KeepAwakeGuard::acquire()
+ .err()
+ .expect("stalled bus must time out");
+ assert!(error.contains("timed out"), "{error}");
+ assert!(start.elapsed() < Duration::from_secs(7));
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ runtime.block_on(async {
+ let beats = Arc::new(AtomicUsize::new(0));
+ let ticks = beats.clone();
+ let heartbeat = tokio::spawn(async move {
+ loop {
+ ticks.fetch_add(1, Ordering::SeqCst);
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ });
+ let error = KeepAwakeGuard::acquire_async()
+ .await
+ .err()
+ .expect("stalled bus must time out");
+ assert!(error.contains("timed out"), "{error}");
+ assert!(
+ beats.load(Ordering::SeqCst) > 10,
+ "acquisition blocked Tokio"
+ );
+ let pending = tokio::spawn(KeepAwakeGuard::acquire_async());
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ pending.abort();
+ let result = tokio::time::timeout(Duration::from_secs(1), pending)
+ .await
+ .expect("cancellation stalled");
+ assert!(matches!(result, Err(error) if error.is_cancelled()));
+ let before = beats.load(Ordering::SeqCst);
+ let error = set_keep_awake_async(true).await.unwrap_err();
+ assert!(error.contains("timed out"), "{error}");
+ assert!(
+ beats.load(Ordering::SeqCst) > before + 10,
+ "setting blocked Tokio"
+ );
+ set_keep_awake_async(false).await.unwrap();
+ heartbeat.abort();
+ });
+}
diff --git a/crates/screenpipe-engine/src/power/mod.rs b/crates/screenpipe-engine/src/power/mod.rs
index ad75f6fc6..5819f36cd 100644
--- a/crates/screenpipe-engine/src/power/mod.rs
+++ b/crates/screenpipe-engine/src/power/mod.rs
@@ -22,7 +22,7 @@ pub mod monitor;
pub mod profile;
// Re-export the public API at the module level
-pub use awake::{set_keep_awake, KeepAwakeGuard};
+pub use awake::{set_keep_awake, set_keep_awake_async, KeepAwakeGuard};
pub use manager::{
start_power_manager, start_power_manager_with_pref, PowerManagerHandle, PowerStatus,
};