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: retry UIA initialization with exponential backoff on Windows

Louis Beaumont25d784a9eb1f
diff --git a/crates/screenpipe-accessibility/src/platform/windows_uia.rs b/crates/screenpipe-accessibility/src/platform/windows_uia.rs
index b1a55cfe9..8c922f399 100644
--- a/crates/screenpipe-accessibility/src/platform/windows_uia.rs
+++ b/crates/screenpipe-accessibility/src/platform/windows_uia.rs
@@ -368,13 +368,40 @@ pub fn run_uia_thread(
}
}
- // Initialize UIA context
- let uia = match UiaContext::new() {
- Ok(ctx) => ctx,
- Err(e) => {
- error!("Failed to initialize UI Automation: {:?}", e);
- unsafe { CoUninitialize() };
- return;
+ // Initialize UIA context with retries — COM services may not be ready
+ // immediately after system boot or when resuming from sleep.
+ let uia = {
+ let mut last_err = None;
+ let mut ctx = None;
+ for attempt in 0..4 {
+ match UiaContext::new() {
+ Ok(c) => {
+ ctx = Some(c);
+ break;
+ }
+ Err(e) => {
+ let delay_secs = 1u64 << attempt.min(2); // 1, 2, 4, 4
+ warn!(
+ "UIA init attempt {} failed: {:?}, retrying in {}s",
+ attempt + 1,
+ e,
+ delay_secs
+ );
+ last_err = Some(e);
+ std::thread::sleep(std::time::Duration::from_secs(delay_secs));
+ }
+ }
+ }
+ match ctx {
+ Some(c) => c,
+ None => {
+ error!(
+ "Failed to initialize UI Automation after 4 attempts: {:?}",
+ last_err
+ );
+ unsafe { CoUninitialize() };
+ return;
+ }
}
};
diff --git a/crates/screenpipe-accessibility/src/tree/windows.rs b/crates/screenpipe-accessibility/src/tree/windows.rs
index 69d40105b..31b069b35 100644
--- a/crates/screenpipe-accessibility/src/tree/windows.rs
+++ b/crates/screenpipe-accessibility/src/tree/windows.rs
@@ -110,8 +110,32 @@ impl WindowsTreeWalker {
state.com_initialized = true;
}
if state.uia.is_none() {
- state.uia =
- Some(UiaContext::new().map_err(|e| anyhow::anyhow!("UIA init failed: {:?}", e))?);
+ let mut last_err = None;
+ for attempt in 0..4 {
+ match UiaContext::new() {
+ Ok(c) => {
+ state.uia = Some(c);
+ break;
+ }
+ Err(e) => {
+ let delay_secs = 1u64 << attempt.min(2);
+ tracing::warn!(
+ "UIA lazy-init attempt {} failed: {:?}, retrying in {}s",
+ attempt + 1,
+ e,
+ delay_secs
+ );
+ last_err = Some(e);
+ std::thread::sleep(std::time::Duration::from_secs(delay_secs));
+ }
+ }
+ }
+ if state.uia.is_none() {
+ return Err(anyhow::anyhow!(
+ "UIA init failed after 4 attempts: {:?}",
+ last_err
+ ));
+ }
}
Ok(state.uia.as_ref().unwrap())
}