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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix focus monitor identity matching (#3411)
Louis Beaumont59c7c15c4080
diff --git a/crates/screenpipe-engine/src/event_driven_capture.rs b/crates/screenpipe-engine/src/event_driven_capture.rsindex cbb438bf4..21e5c75bc 100644--- a/crates/screenpipe-engine/src/event_driven_capture.rs+++ b/crates/screenpipe-engine/src/event_driven_capture.rs@@ -393,7 +393,7 @@ pub async fn event_driven_capture_loop(let mut warm_trigger_override: Option<CaptureTrigger> = None;{use crate::focus_aware_controller::CaptureState;- let capture_state = focus_controller.state(monitor_id);+ let capture_state = focus_controller.state_for_monitor(&monitor);// Fires exactly once per focus-away transition, not every Cold// loop iteration, so the log line is meaningful and we don'tdiff --git a/crates/screenpipe-engine/src/focus_aware_controller.rs b/crates/screenpipe-engine/src/focus_aware_controller.rsindex a89a70763..8202ca627 100644--- a/crates/screenpipe-engine/src/focus_aware_controller.rs+++ b/crates/screenpipe-engine/src/focus_aware_controller.rs@@ -30,7 +30,7 @@//! back to "all Active" automatically via the Null tracker + Unknown event//! path — no opt-out needed.-use crate::focus_tracker::{FocusEvent, FocusTracker};+use crate::focus_tracker::{FocusEvent, FocusTracker, MonitorIdentity};use std::collections::HashMap;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};@@ -62,13 +62,30 @@ const WARM_CUTOFF: Duration = Duration::from_millis(2_000);/// Time in Warm before dropping to Cold.const COLD_CUTOFF: Duration = Duration::from_millis(60_000);+#[derive(Clone, Debug, PartialEq, Eq, Hash)]+enum MonitorKey {+ Stable(String),+ RuntimeId(u32),+}++impl MonitorKey {+ fn from_identity(identity: &MonitorIdentity) -> Self {+ identity+ .stable_id+ .as_ref()+ .filter(|stable_id| !stable_id.is_empty())+ .map(|stable_id| Self::Stable(stable_id.clone()))+ .unwrap_or(Self::RuntimeId(identity.id))+ }+}+pub struct FocusAwareController {tracker: Arc<dyn FocusTracker>,/// When each monitor last held focus. `Instant` = the moment it *lost*/// focus. A monitor that's never been focused is absent from the map.- last_focus_time: Mutex<HashMap<u32, Instant>>,- /// Currently focused monitor id, or `None` if unknown.- current_focus: Mutex<Option<u32>>,+ last_focus_time: Mutex<HashMap<MonitorKey, Instant>>,+ /// Currently focused monitor identity, or `None` if unknown.+ current_focus: Mutex<Option<MonitorIdentity>>,/// Wall-clock time the most recent focus/unknown event was received. If/// nothing arrives for `STALE_FOCUS_CUTOFF`, we treat the state as/// Unknown so all monitors stay Active (safe default).@@ -114,8 +131,8 @@ impl FocusAwareController {break;}match rx.recv().await {- Ok(FocusEvent::Focused(id)) => {- this.apply_focus(id);+ Ok(FocusEvent::Focused(identity)) => {+ this.apply_focus(identity);}Ok(FocusEvent::Unknown) => {this.apply_unknown();@@ -132,34 +149,34 @@ impl FocusAwareController {});}- fn apply_focus(&self, id: u32) {+ fn apply_focus(&self, identity: MonitorIdentity) {let prev = {let mut current = self.current_focus.lock().expect("focus-aware current_focus mutex poisoned");- let prev = *current;- *current = Some(id);+ let prev = current.clone();+ *current = Some(identity.clone());prev};// Record the previous monitor's loss-of-focus instant.- if let Some(prev_id) = prev {- if prev_id != id {+ if let Some(prev_identity) = prev {+ if !prev_identity.matches(&identity) {let mut times = self.last_focus_time.lock().expect("focus-aware last_focus_time mutex poisoned");- times.insert(prev_id, Instant::now());+ times.insert(MonitorKey::from_identity(&prev_identity), Instant::now());}}self.touch_last_event();- // Wake the notify for the newly focused monitor so any Cold capture- // loop sleeping on it reactivates immediately.- let notify = self.notify_for(id);- notify.notify_waiters();+ // A focused event may match a Cold loop by stable id even if the raw+ // runtime id differs, so wake all monitor loops and let state() decide+ // which one should become Active.+ self.wake_all_monitors();}fn apply_unknown(&self) {@@ -171,7 +188,7 @@ impl FocusAwareController {*current = None;}self.touch_last_event();- // No notify wake — all monitors fall back to Active anyway.+ self.wake_all_monitors();}fn touch_last_event(&self) {@@ -182,87 +199,73 @@ impl FocusAwareController {/// Query state for a monitor. Must be cheap — called on every capture/// loop iteration.- ///- /// **Currently short-circuited to always return `Active`.**- ///- /// Why: on fresh macOS installs (and likely other environments) the- /// classifier was keeping monitor 1 permanently in `Cold`, because the- /// Darwin focus tracker's reported monitor ids didn't always match the- /// `monitor_id` VisionManager uses. Result: the event-driven capture- /// loop blocked on the notify forever and no frames were ever written- /// to the DB — the UI sat on "building your memory…" indefinitely- /// (observed on v2.4.37 MBA fresh install: 3 frames in ~17 min of- /// runtime, zero after that session's restart).- ///- /// Disabling the pause-on-unfocused behavior via an early-return here- /// preserves all the focus-tracker scaffolding (subscribers, Darwin- /// observer, autorelease-pool fix in 8f8e1e819, etc.) without the- /// risk of a full revert touching multiple downstream commits. Once- /// the monitor-id mapping is properly reconciled between the focus- /// tracker and VisionManager, the body below can be reinstated.- ///- /// The rest of this function is kept intact (dead code) so the fix- /// can be reverted to "re-enable focus-aware" with a one-line diff.- pub fn state(&self, _monitor_id: u32) -> CaptureState {- return CaptureState::Active;-- #[allow(unreachable_code)]- {- let monitor_id = _monitor_id;- // Stale-focus safety: if no focus event has landed in 30s, assume- // the tracker stalled (native thread blocked, notifications dropped- // during sleep/wake, etc.) and treat everything as Active. Matches- // the Null-tracker all-Active fallback so a broken focus source- // never silently freezes capture on non-focused monitors.- let last_event_elapsed = self- .last_event_time- .lock()- .ok()- .map(|t| t.elapsed())- .unwrap_or_else(|| Duration::from_secs(0));- if last_event_elapsed >= STALE_FOCUS_CUTOFF {- return CaptureState::Active;- }+ pub fn state_for_monitor(+ &self,+ monitor: &screenpipe_screen::monitor::SafeMonitor,+ ) -> CaptureState {+ self.state_for_identity(&MonitorIdentity::from_monitor(monitor))+ }- // If focus is Unknown (no data yet), everything is Active — safest- // fallback. Preserves existing behaviour when the tracker can't- // resolve the cursor to a monitor.- let current = *self- .current_focus- .lock()- .expect("focus-aware current_focus mutex poisoned");- let Some(current_id) = current else {- return CaptureState::Active;- };+ #[cfg(test)]+ pub(crate) fn state(&self, monitor_id: u32) -> CaptureState {+ self.state_for_identity(&MonitorIdentity::runtime_id(monitor_id))+ }- if current_id == monitor_id {- return CaptureState::Active;- }+ fn state_for_identity(&self, identity: &MonitorIdentity) -> CaptureState {+ // Stale-focus safety: if no focus event has landed in 30s, assume+ // the tracker stalled (native thread blocked, notifications dropped+ // during sleep/wake, etc.) and treat everything as Active. Matches+ // the Null-tracker all-Active fallback so a broken focus source+ // never silently freezes capture on non-focused monitors.+ let last_event_elapsed = self+ .last_event_time+ .lock()+ .ok()+ .map(|t| t.elapsed())+ .unwrap_or_else(|| Duration::from_secs(0));+ if last_event_elapsed >= STALE_FOCUS_CUTOFF {+ return CaptureState::Active;+ }- let last = self- .last_focus_time- .lock()- .expect("focus-aware last_focus_time mutex poisoned")- .get(&monitor_id)- .copied();-- match last {- // Never focused since controller start → Cold. The loop will- // block on the notify; once the cursor lands on this monitor- // (or focus becomes Unknown), state flips back to Active.- None => CaptureState::Cold,- Some(t) => {- let elapsed = t.elapsed();- if elapsed < WARM_CUTOFF {- // Hysteresis: still feels "active" for a beat after- // focus change to avoid stuttering during normal- // window switching.- CaptureState::Active- } else if elapsed < COLD_CUTOFF {- CaptureState::Warm- } else {- CaptureState::Cold- }+ // If focus is Unknown (no data yet), everything is Active — safest+ // fallback. Preserves existing behaviour when the tracker can't+ // resolve the cursor to a monitor.+ let current = self+ .current_focus+ .lock()+ .expect("focus-aware current_focus mutex poisoned")+ .clone();+ let Some(current_identity) = current else {+ return CaptureState::Active;+ };++ if current_identity.matches(identity) {+ return CaptureState::Active;+ }++ let key = MonitorKey::from_identity(identity);+ let last = self+ .last_focus_time+ .lock()+ .expect("focus-aware last_focus_time mutex poisoned")+ .get(&key)+ .copied();++ match last {+ // Never focused since controller start → Cold. The loop will block+ // on the notify; once focus lands on this monitor (or becomes+ // Unknown), state flips back to Active.+ None => CaptureState::Cold,+ Some(t) => {+ let elapsed = t.elapsed();+ if elapsed < WARM_CUTOFF {+ // Hysteresis: still feels "active" for a beat after focus+ // change to avoid stuttering during normal window switching.+ CaptureState::Active+ } else if elapsed < COLD_CUTOFF {+ CaptureState::Warm+ } else {+ CaptureState::Cold}}}@@ -280,6 +283,14 @@ impl FocusAwareController {.clone()}+ fn wake_all_monitors(&self) {+ if let Ok(map) = self.monitor_notifies.lock() {+ for notify in map.values() {+ notify.notify_waiters();+ }+ }+ }+/// Shutdown. Stops the subscriber task and the underlying tracker./// Idempotent.pub fn shutdown(&self) {@@ -299,7 +310,12 @@ impl FocusAwareController {// ── Test helpers ──────────────────────────────────────────────────#[cfg(test)]pub(crate) fn set_focus_for_test(&self, id: u32) {- self.apply_focus(id);+ self.apply_focus(MonitorIdentity::runtime_id(id));+ }++ #[cfg(test)]+ pub(crate) fn set_focus_identity_for_test(&self, identity: MonitorIdentity) {+ self.apply_focus(identity);}#[cfg(test)]@@ -311,11 +327,20 @@ impl FocusAwareController {/// Lets tests backdate state without blocking on wall-clock sleeps.#[cfg(test)]pub(crate) fn backdate_focus_for_test(&self, monitor_id: u32, lost_at: Instant) {+ self.backdate_focus_identity_for_test(&MonitorIdentity::runtime_id(monitor_id), lost_at);+ }++ #[cfg(test)]+ pub(crate) fn backdate_focus_identity_for_test(+ &self,+ identity: &MonitorIdentity,+ lost_at: Instant,+ ) {let mut times = self.last_focus_time.lock().expect("focus-aware last_focus_time mutex poisoned");- times.insert(monitor_id, lost_at);+ times.insert(MonitorKey::from_identity(identity), lost_at);}/// Force the last-event timestamp to simulate a stalled tracker.@@ -336,10 +361,6 @@ impl Drop for FocusAwareController {}// Tests below exercise the Active/Warm/Cold classifier via state().-// Since state() is currently short-circuited to always return Active-// (see the function doc-comment for why), tests that expect Warm/Cold-// have `#[ignore = "..."]` applied. Re-enable them the moment-// state()'s early-return is removed.#[cfg(test)]mod tests {use super::*;@@ -358,7 +379,6 @@ mod tests {}#[tokio::test]- #[ignore = "state() short-circuited to Active — see focus_aware_controller::state doc"]async fn focused_monitor_is_active_and_never_focused_is_cold() {let ctrl = make_ctrl();ctrl.set_focus_for_test(1);@@ -379,7 +399,6 @@ mod tests {}#[tokio::test]- #[ignore = "state() short-circuited to Active — see focus_aware_controller::state doc"]async fn transitions_to_warm_after_warm_cutoff() {let ctrl = make_ctrl();ctrl.set_focus_for_test(1);@@ -391,7 +410,6 @@ mod tests {}#[tokio::test]- #[ignore = "state() short-circuited to Active — see focus_aware_controller::state doc"]async fn transitions_to_cold_after_cold_cutoff() {let ctrl = make_ctrl();ctrl.set_focus_for_test(1);@@ -403,7 +421,6 @@ mod tests {}#[tokio::test]- #[ignore = "state() short-circuited to Active — intermediate Cold assertions no longer hold"]async fn unknown_event_forces_all_active_fallback() {let ctrl = make_ctrl();ctrl.set_focus_for_test(1);@@ -425,7 +442,6 @@ mod tests {}#[tokio::test]- #[ignore = "state() short-circuited to Active — intermediate Cold assertions no longer hold"]async fn stale_focus_falls_back_to_active() {let ctrl = make_ctrl();ctrl.set_focus_for_test(1);@@ -444,6 +460,54 @@ mod tests {assert_eq!(ctrl.state(2), CaptureState::Cold);}+ #[tokio::test]+ async fn stable_identity_matches_when_runtime_ids_differ() {+ let ctrl = make_ctrl();+ let focused = MonitorIdentity::new(100, Some("Dell_3840x2160_0,0".to_string()));+ let same_display = MonitorIdentity::new(200, Some("Dell_3840x2160_0,0".to_string()));+ let other_display = MonitorIdentity::new(300, Some("LG_1920x1080_3840,0".to_string()));++ ctrl.set_focus_identity_for_test(focused);++ assert_eq!(ctrl.state_for_identity(&same_display), CaptureState::Active);+ assert_eq!(ctrl.state_for_identity(&other_display), CaptureState::Cold);+ }++ #[tokio::test]+ async fn stable_identity_mismatch_wins_over_runtime_id_match() {+ let ctrl = make_ctrl();+ let focused = MonitorIdentity::new(100, Some("Dell_3840x2160_0,0".to_string()));+ let different_display_with_same_runtime_id =+ MonitorIdentity::new(100, Some("LG_1920x1080_3840,0".to_string()));++ ctrl.set_focus_identity_for_test(focused);++ assert_eq!(+ ctrl.state_for_identity(&different_display_with_same_runtime_id),+ CaptureState::Cold+ );+ }++ #[tokio::test]+ async fn unknown_event_wakes_cold_notify() {+ let ctrl = make_ctrl();+ let notify = ctrl.notify_for(2);+ ctrl.set_focus_for_test(1);+ assert_eq!(ctrl.state(2), CaptureState::Cold);++ let join = tokio::spawn(async move {+ notify.notified().await;+ });+ tokio::task::yield_now().await;++ ctrl.set_unknown_for_test();++ tokio::time::timeout(Duration::from_millis(500), join)+ .await+ .expect("unknown fallback should wake cold monitors within 500ms")+ .expect("notified task finished");+ }+#[tokio::test]async fn apply_focus_wakes_cold_notify() {let ctrl = make_ctrl();diff --git a/crates/screenpipe-engine/src/focus_tracker/darwin.rs b/crates/screenpipe-engine/src/focus_tracker/darwin.rsindex f0ffafcba..5663b2034 100644--- a/crates/screenpipe-engine/src/focus_tracker/darwin.rs+++ b/crates/screenpipe-engine/src/focus_tracker/darwin.rs@@ -35,9 +35,9 @@//! practice because the controller is only torn down on settings change//! and the leak is a few KB).-use super::{FocusEvent, FocusTracker};+use super::{FocusEvent, FocusTracker, MonitorIdentity};use anyhow::Result;-use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;use tokio::sync::broadcast;@@ -84,9 +84,9 @@ fn cursor_location() -> Option<(f64, f64)> {/// Rectangular bounds of a monitor for point-in-rect testing. Plain struct/// so the pure pick logic can be exercised in tests without needing access/// to `SafeMonitor`'s private test constructor.-#[derive(Clone, Copy, Debug)]+#[derive(Clone, Debug)]struct MonitorRect {- id: u32,+ identity: MonitorIdentity,x: f64,y: f64,w: f64,@@ -97,10 +97,10 @@ struct MonitorRect {////// `[x, x+w)` / `[y, y+h)` is half-open so adjacent monitors don't overlap/// at the seam.-fn pick_monitor(rects: &[MonitorRect], x: f64, y: f64) -> Option<u32> {+fn pick_monitor(rects: &[MonitorRect], x: f64, y: f64) -> Option<MonitorIdentity> {rects.iter().find_map(|r| {if x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h {- Some(r.id)+ Some(r.identity.clone())} else {None}@@ -116,11 +116,11 @@ fn monitor_for_point(monitors: &[screenpipe_screen::monitor::SafeMonitor],x: f64,y: f64,-) -> Option<u32> {+) -> Option<MonitorIdentity> {let rects: Vec<MonitorRect> = monitors.iter().map(|m| MonitorRect {- id: m.id(),+ identity: MonitorIdentity::from_monitor(m),x: m.x() as f64,y: m.y() as f64,w: m.width() as f64,@@ -134,10 +134,8 @@ fn monitor_for_point(/// poll. Kept in an `Arc` so both can update it without reach-around.struct Inner {tx: broadcast::Sender<FocusEvent>,- /// Last known focused monitor id. `0` encodes "unknown" (monitor ids from- /// sck-rs / xcap are platform-assigned non-zero display ids, so 0 is a- /// safe sentinel).- current: AtomicU32,+ /// Last known focused monitor identity, or None when unknown.+ current: Mutex<Option<MonitorIdentity>>,stop_flag: AtomicBool,/// Latch: if we've already emitted `Unknown`, don't re-spam until we/// resolve a valid monitor again. Protected by a Mutex because it's@@ -155,13 +153,23 @@ impl Inner {let resolved = cursor_location().and_then(|(x, y)| monitor_for_point(monitors, x, y));match resolved {- Some(id) => {- let prev = self.current.load(Ordering::Relaxed);- if prev != id {- self.current.store(id, Ordering::Relaxed);+ Some(identity) => {+ let changed = self+ .current+ .lock()+ .map(|mut current| {+ if current.as_ref() == Some(&identity) {+ false+ } else {+ *current = Some(identity.clone());+ true+ }+ })+ .unwrap_or(false);+ if changed {// Ignore send errors — no subscribers is fine.- let _ = self.tx.send(FocusEvent::Focused(id));- debug!("focus tracker: focused monitor -> {}", id);+ let _ = self.tx.send(FocusEvent::Focused(identity.clone()));+ debug!("focus tracker: focused monitor -> {:?}", identity);}if let Ok(mut u) = self.unknown_emitted.lock() {*u = false;@@ -181,7 +189,9 @@ impl Inner {};if emit {let _ = self.tx.send(FocusEvent::Unknown);- self.current.store(0, Ordering::Relaxed);+ if let Ok(mut current) = self.current.lock() {+ *current = None;+ }debug!("focus tracker: cursor not on any known monitor");}}@@ -199,7 +209,7 @@ impl DarwinFocusTracker {let (tx, _) = broadcast::channel::<FocusEvent>(16);let inner = Arc::new(Inner {tx,- current: AtomicU32::new(0),+ current: Mutex::new(None),stop_flag: AtomicBool::new(false),unknown_emitted: Mutex::new(false),});@@ -326,13 +336,8 @@ fn run_workspace_observer(inner: Arc<Inner>) {}impl FocusTracker for DarwinFocusTracker {- fn current(&self) -> Option<u32> {- let v = self.inner.current.load(Ordering::Relaxed);- if v == 0 {- None- } else {- Some(v)- }+ fn current(&self) -> Option<MonitorIdentity> {+ self.inner.current.lock().ok()?.clone()}fn subscribe(&self) -> broadcast::Receiver<FocusEvent> {@@ -361,14 +366,14 @@ mod tests {fn pick_monitor_basic_bounds() {let monitors = vec![MonitorRect {- id: 1,+ identity: MonitorIdentity::runtime_id(1),x: 0.0,y: 0.0,w: 1920.0,h: 1080.0,},MonitorRect {- id: 2,+ identity: MonitorIdentity::runtime_id(2),x: 1920.0,y: 0.0,w: 1920.0,@@ -376,10 +381,19 @@ mod tests {},];- assert_eq!(pick_monitor(&monitors, 100.0, 100.0), Some(1));- assert_eq!(pick_monitor(&monitors, 2000.0, 100.0), Some(2));+ assert_eq!(+ pick_monitor(&monitors, 100.0, 100.0),+ Some(MonitorIdentity::runtime_id(1))+ );+ assert_eq!(+ pick_monitor(&monitors, 2000.0, 100.0),+ Some(MonitorIdentity::runtime_id(2))+ );// Left edge of m2 is inclusive; right edge of m1 is exclusive.- assert_eq!(pick_monitor(&monitors, 1920.0, 500.0), Some(2));+ assert_eq!(+ pick_monitor(&monitors, 1920.0, 500.0),+ Some(MonitorIdentity::runtime_id(2))+ );assert_eq!(pick_monitor(&monitors, 500.0, 5000.0), None);assert_eq!(pick_monitor(&monitors, -5.0, -5.0), None);}diff --git a/crates/screenpipe-engine/src/focus_tracker/linux.rs b/crates/screenpipe-engine/src/focus_tracker/linux.rsindex 38a2f1768..262fdbb7d 100644--- a/crates/screenpipe-engine/src/focus_tracker/linux.rs+++ b/crates/screenpipe-engine/src/focus_tracker/linux.rs@@ -24,7 +24,7 @@//! This slot is wired up via `focus_tracker::new_tracker()` so we can swap in//! a real X11 implementation in a follow-up without touching callers.-use super::{FocusEvent, FocusTracker};+use super::{FocusEvent, FocusTracker, MonitorIdentity};use anyhow::Result;use tokio::sync::broadcast;@@ -48,7 +48,7 @@ impl LinuxFocusTracker {}impl FocusTracker for LinuxFocusTracker {- fn current(&self) -> Option<u32> {+ fn current(&self) -> Option<MonitorIdentity> {None}diff --git a/crates/screenpipe-engine/src/focus_tracker/mod.rs b/crates/screenpipe-engine/src/focus_tracker/mod.rsindex a0f37e1cd..8a087594c 100644--- a/crates/screenpipe-engine/src/focus_tracker/mod.rs+++ b/crates/screenpipe-engine/src/focus_tracker/mod.rs@@ -20,11 +20,47 @@ mod windows;pub use null::NullFocusTracker;+/// Stable-enough monitor identity for focus/capture comparisons.+///+/// The runtime numeric id comes from the platform capture backend and is still+/// useful for logs and fallbacks, but it can drift across enumerations on some+/// macOS setups. The stable id is based on the monitor descriptor used by the+/// capture stack, so the focus tracker and capture loop can agree on the same+/// physical display even when the raw ids differ.+#[derive(Clone, Debug, PartialEq, Eq, Hash)]+pub struct MonitorIdentity {+ pub id: u32,+ pub stable_id: Option<String>,+}++impl MonitorIdentity {+ pub fn new(id: u32, stable_id: Option<String>) -> Self {+ Self { id, stable_id }+ }++ pub fn runtime_id(id: u32) -> Self {+ Self::new(id, None)+ }++ pub fn from_monitor(monitor: &screenpipe_screen::monitor::SafeMonitor) -> Self {+ Self::new(monitor.id(), Some(monitor.stable_id()))+ }++ pub fn matches(&self, other: &Self) -> bool {+ match (&self.stable_id, &other.stable_id) {+ (Some(a), Some(b)) if !a.is_empty() && a == b => true,+ (Some(a), Some(b)) if !a.is_empty() && !b.is_empty() => false,+ _ if self.id == other.id => true,+ _ => false,+ }+ }+}+/// Focus event — emitted whenever the tracker detects a change.#[derive(Clone, Debug, PartialEq, Eq)]pub enum FocusEvent {- /// User is now looking at this monitor (our internal u32 monitor id).- Focused(u32),+ /// User is now looking at this monitor.+ Focused(MonitorIdentity),/// Focus cannot be determined (API unavailable, permission denied, etc.)/// Controller should fall back to treating all monitors as Active.Unknown,@@ -32,7 +68,7 @@ pub enum FocusEvent {pub trait FocusTracker: Send + Sync {/// Current best-effort focused monitor. None if unknown.- fn current(&self) -> Option<u32>;+ fn current(&self) -> Option<MonitorIdentity>;/// Subscribe to focus-change events. Broadcast so multiple consumers OK.fn subscribe(&self) -> broadcast::Receiver<FocusEvent>;/// Stop the tracker (idempotent). Called on shutdown.diff --git a/crates/screenpipe-engine/src/focus_tracker/null.rs b/crates/screenpipe-engine/src/focus_tracker/null.rsindex e89fce5dc..382bcfd57 100644--- a/crates/screenpipe-engine/src/focus_tracker/null.rs+++ b/crates/screenpipe-engine/src/focus_tracker/null.rs@@ -5,7 +5,7 @@//! Null focus tracker: always reports Unknown, never emits events.//! Used on unsupported platforms or when the native impl fails to start.-use super::{FocusEvent, FocusTracker};+use super::{FocusEvent, FocusTracker, MonitorIdentity};use tokio::sync::broadcast;pub struct NullFocusTracker {@@ -26,7 +26,7 @@ impl Default for NullFocusTracker {}impl FocusTracker for NullFocusTracker {- fn current(&self) -> Option<u32> {+ fn current(&self) -> Option<MonitorIdentity> {None}fn subscribe(&self) -> broadcast::Receiver<FocusEvent> {diff --git a/crates/screenpipe-engine/src/focus_tracker/windows.rs b/crates/screenpipe-engine/src/focus_tracker/windows.rsindex 418e59859..6a993c952 100644--- a/crates/screenpipe-engine/src/focus_tracker/windows.rs+++ b/crates/screenpipe-engine/src/focus_tracker/windows.rs@@ -23,9 +23,9 @@//! thread-local `Arc` pointer in the WinEvent callback to reach back to it//! without crossing the ABI boundary with non-ABI-safe types.-use super::{FocusEvent, FocusTracker};+use super::{FocusEvent, FocusTracker, MonitorIdentity};use anyhow::Result;-use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;use tokio::sync::broadcast;@@ -34,9 +34,9 @@ use tracing::{debug, warn};/// Plain rect used for monitor resolution — the Win32 `RECT` type is not/// trivially shareable across Rust modules. We convert on the edge.-#[derive(Clone, Copy, Debug)]+#[derive(Clone, Debug)]struct MonitorRect {- id: u32,+ identity: MonitorIdentity,x: i32,y: i32,w: u32,@@ -45,10 +45,10 @@ struct MonitorRect {/// Find the monitor whose bounds contain the given point. Half-open on/// right/bottom so adjacent monitors don't overlap at the seam.-fn pick_monitor(rects: &[MonitorRect], x: i32, y: i32) -> Option<u32> {+fn pick_monitor(rects: &[MonitorRect], x: i32, y: i32) -> Option<MonitorIdentity> {rects.iter().find_map(|r| {if x >= r.x && x < r.x + r.w as i32 && y >= r.y && y < r.y + r.h as i32 {- Some(r.id)+ Some(r.identity.clone())} else {None}@@ -59,11 +59,11 @@ fn monitor_for_point(monitors: &[screenpipe_screen::monitor::SafeMonitor],x: i32,y: i32,-) -> Option<u32> {+) -> Option<MonitorIdentity> {let rects: Vec<MonitorRect> = monitors.iter().map(|m| MonitorRect {- id: m.id(),+ identity: MonitorIdentity::from_monitor(m),x: m.x(),y: m.y(),w: m.width(),@@ -126,7 +126,7 @@ fn foreground_window_anchor() -> Option<(i32, i32)> {struct Inner {tx: broadcast::Sender<FocusEvent>,- current: AtomicU32,+ current: Mutex<Option<MonitorIdentity>>,stop_flag: AtomicBool,unknown_emitted: Mutex<bool>,// Handle to the tokio runtime captured at start(). The WinEvent callback@@ -150,12 +150,22 @@ impl Inner {.or_else(|| cursor_position().and_then(|(x, y)| monitor_for_point(monitors, x, y)));match resolved {- Some(id) => {- let prev = self.current.load(Ordering::Relaxed);- if prev != id {- self.current.store(id, Ordering::Relaxed);- let _ = self.tx.send(FocusEvent::Focused(id));- debug!("win focus tracker: focused monitor -> {}", id);+ Some(identity) => {+ let changed = self+ .current+ .lock()+ .map(|mut current| {+ if current.as_ref() == Some(&identity) {+ false+ } else {+ *current = Some(identity.clone());+ true+ }+ })+ .unwrap_or(false);+ if changed {+ let _ = self.tx.send(FocusEvent::Focused(identity.clone()));+ debug!("win focus tracker: focused monitor -> {:?}", identity);}if let Ok(mut u) = self.unknown_emitted.lock() {*u = false;@@ -175,7 +185,9 @@ impl Inner {};if emit {let _ = self.tx.send(FocusEvent::Unknown);- self.current.store(0, Ordering::Relaxed);+ if let Ok(mut current) = self.current.lock() {+ *current = None;+ }debug!("win focus tracker: no monitor resolvable");}}@@ -222,7 +234,7 @@ impl WindowsFocusTracker {let (tx, _) = broadcast::channel::<FocusEvent>(16);let inner = Arc::new(Inner {tx,- current: AtomicU32::new(0),+ current: Mutex::new(None),stop_flag: AtomicBool::new(false),unknown_emitted: Mutex::new(false),runtime: handle.clone(),@@ -355,13 +367,8 @@ fn run_win_event_observer() {}impl FocusTracker for WindowsFocusTracker {- fn current(&self) -> Option<u32> {- let v = self.inner.current.load(Ordering::Relaxed);- if v == 0 {- None- } else {- Some(v)- }+ fn current(&self) -> Option<MonitorIdentity> {+ self.inner.current.lock().ok()?.clone()}fn subscribe(&self) -> broadcast::Receiver<FocusEvent> {@@ -389,14 +396,14 @@ mod tests {fn pick_monitor_basic_bounds() {let monitors = vec![MonitorRect {- id: 1,+ identity: MonitorIdentity::runtime_id(1),x: 0,y: 0,w: 1920,h: 1080,},MonitorRect {- id: 2,+ identity: MonitorIdentity::runtime_id(2),x: 1920,y: 0,w: 1920,@@ -404,9 +411,18 @@ mod tests {},];- assert_eq!(pick_monitor(&monitors, 100, 100), Some(1));- assert_eq!(pick_monitor(&monitors, 2000, 100), Some(2));- assert_eq!(pick_monitor(&monitors, 1920, 500), Some(2));+ assert_eq!(+ pick_monitor(&monitors, 100, 100),+ Some(MonitorIdentity::runtime_id(1))+ );+ assert_eq!(+ pick_monitor(&monitors, 2000, 100),+ Some(MonitorIdentity::runtime_id(2))+ );+ assert_eq!(+ pick_monitor(&monitors, 1920, 500),+ Some(MonitorIdentity::runtime_id(2))+ );assert_eq!(pick_monitor(&monitors, 500, 5000), None);assert_eq!(pick_monitor(&monitors, -5, -5), None);}