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(windows): route escape-pressed to Main overlay when Home has focus (#3084)

Ansh Groverc513a33456fc
diff --git a/apps/screenpipe-app-tauri/components/rewind/timeline.tsx b/apps/screenpipe-app-tauri/components/rewind/timeline.tsx
index 4ade20fd0..02805064b 100644
--- a/apps/screenpipe-app-tauri/components/rewind/timeline.tsx
+++ b/apps/screenpipe-app-tauri/components/rewind/timeline.tsx
@@ -28,6 +28,7 @@ import { useKeywordSearchStore } from "@/lib/hooks/use-keyword-search-store";
import { usePlatform } from "@/lib/hooks/use-platform";
import { useAudioPlayback } from "@/lib/hooks/use-audio-playback";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
+import { useSettings } from "@/lib/hooks/use-settings";
import { usePipes, type TemplatePipe } from "@/lib/hooks/use-pipes";
import posthog from "posthog-js";
@@ -90,6 +91,7 @@ const easeOutCubic = (x: number): number => {
export default function Timeline({ embedded = false }: { embedded?: boolean }) {
const { isMac } = usePlatform();
+ const { settings } = useSettings();
const { health } = useHealthCheck();
const [currentIndex, setCurrentIndex] = useState(0);
const [showAudioTranscript, setShowAudioTranscript] = useState(false);
@@ -395,6 +397,9 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {
// Hide timeline when mouse moves to a different screen (skip in embedded mode)
useEffect(() => {
if (embedded) return;
+ // Window mode is a small movable window; cursor is often "outside" vs fullscreen
+ // monitor bounds, which incorrectly fired closeWindow and unregistered Escape.
+ if (settings?.overlayMode === "window") return;
let initialScreenBounds: { x: number; y: number; width: number; height: number } | null = null;
let checkInterval: ReturnType<typeof setInterval> | null = null;
@@ -449,7 +454,7 @@ export default function Timeline({ embedded = false }: { embedded?: boolean }) {
clearInterval(checkInterval);
}
};
- }, []);
+ }, [embedded, settings?.overlayMode]);
// Helper to navigate to a timestamp
const navigateToTimestamp = useCallback(async (targetTimestamp: string) => {
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
index 7bbb9155d..8dfeecdeb 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
@@ -452,6 +452,7 @@ pub fn set_tray_health_icon(app_handle: tauri::AppHandle) {
#[specta::specta]
pub fn show_main_window(app_handle: &tauri::AppHandle, _overlay: bool) {
info!("show_main_window called");
+ set_main_close_in_progress(false);
let window_to_show = ShowRewindWindow::Main;
match window_to_show.show(app_handle) {
@@ -473,10 +474,13 @@ pub fn show_main_window(app_handle: &tauri::AppHandle, _overlay: bool) {
// already "focused" or never lost focus) wouldn't trigger a re-fetch.
let _ = app_handle.emit("window-focused", true);
- // NOTE: Window shortcuts (Escape) are registered by the focus-gain
- // handler in window/show.rs. Do NOT also register them here — doing
- // so races with the focus handler and causes duplicate
- // RegisterEventHotKey calls that fail on macOS.
+ // NOTE: On macOS, Escape is registered only from the focus-gain handler
+ // in window/show.rs (duplicate RegisterEventHotKey fails there).
+ // On Windows/Linux, set_focus can succeed without delivering a new
+ // Focused(true) event when Home already had focus — then Escape never
+ // re-registers until another focus cycle. Sync once after show.
+ #[cfg(not(target_os = "macos"))]
+ register_window_shortcuts_if_main_visible(app_handle.clone());
}
Err(e) => {
error!("ShowRewindWindow::Main.show failed: {}", e);
@@ -1073,10 +1077,22 @@ pub async fn close_window(
// If closing the main window, also unregister window-specific shortcuts
// (Escape, search shortcut) so they don't interfere with other apps
if matches!(window, ShowRewindWindow::Main) {
+ set_main_close_in_progress(true);
+ info!("shortcut-sync: scheduling unregister (reason=close_window_main)");
+ let expected_gen =
+ WINDOW_SHORTCUTS_GEN.load(std::sync::atomic::Ordering::SeqCst);
let app_clone = app_handle.clone();
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(10));
- let _ = unregister_window_shortcuts(app_clone);
+ info!("shortcut-sync: unregister execute (reason=close_window_main)");
+ let _ = unregister_window_shortcuts_if_generation_unchanged(
+ app_clone,
+ expected_gen,
+ "close_window_main",
+ );
+ // Allow register_if_visible on Home focus again; stale blur debounce paths
+ // still skip extra unregister while this was true (see show.rs guards).
+ set_main_close_in_progress(false);
});
}
@@ -1946,7 +1962,24 @@ pub fn register_window_shortcuts(app_handle: tauri::AppHandle) -> Result<(), Str
if matches!(event.state, ShortcutState::Pressed) {
if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
info!("Escape pressed, emitting escape-pressed event");
- let _ = app.emit("escape-pressed", ());
+ // Target the Main overlay webview explicitly. `app.emit` can be
+ // delivered only to the focused Tauri window; when Home stays
+ // focused while the fullscreen overlay is visible on top, the
+ // overlay never saw escape-pressed (and no keydown reaches it),
+ // so Esc looked broken until a focus change re-routed events.
+ let mut delivered = false;
+ for label in [RewindWindowId::Main.label(), "main-window"] {
+ if let Some(w) = app.get_webview_window(label) {
+ if w.is_visible().unwrap_or(false) {
+ let _ = app.emit_to(label, "escape-pressed", ());
+ delivered = true;
+ break;
+ }
+ }
+ }
+ if !delivered {
+ let _ = app.emit("escape-pressed", ());
+ }
})) {
tracing::error!("panic in escape handler: {:?}", e);
}
@@ -1970,6 +2003,11 @@ pub fn register_window_shortcuts(app_handle: tauri::AppHandle) -> Result<(), Str
Ok(())
}
+static WINDOW_SHORTCUTS_GEN: std::sync::atomic::AtomicU64 =
+ std::sync::atomic::AtomicU64::new(0);
+static MAIN_CLOSE_IN_PROGRESS: std::sync::atomic::AtomicBool =
+ std::sync::atomic::AtomicBool::new(false);
+
/// Unregister window-specific shortcuts when main window is hidden.
/// Only unregisters Escape and arrow keys. Global shortcuts (search, show, chat)
/// are NOT touched here — they must persist across window show/hide cycles.
@@ -1993,6 +2031,82 @@ pub fn unregister_window_shortcuts(app_handle: tauri::AppHandle) -> Result<(), S
Ok(())
}
+/// Register Escape and return the current generation token. Any delayed
+/// unregister should check this token before unregistering to avoid races.
+pub(crate) fn register_window_shortcuts_with_generation(
+ app_handle: tauri::AppHandle,
+) -> Result<u64, String> {
+ register_window_shortcuts(app_handle.clone())?;
+ let gen = WINDOW_SHORTCUTS_GEN
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
+ .saturating_add(1);
+ info!("shortcut-sync: register generation bumped to {}", gen);
+ Ok(gen)
+}
+
+pub(crate) fn current_window_shortcuts_generation() -> u64 {
+ WINDOW_SHORTCUTS_GEN.load(std::sync::atomic::Ordering::SeqCst)
+}
+
+pub(crate) fn set_main_close_in_progress(in_progress: bool) {
+ MAIN_CLOSE_IN_PROGRESS.store(in_progress, std::sync::atomic::Ordering::SeqCst);
+ info!("shortcut-sync: main_close_in_progress={}", in_progress);
+}
+
+pub(crate) fn is_main_close_in_progress() -> bool {
+ MAIN_CLOSE_IN_PROGRESS.load(std::sync::atomic::Ordering::SeqCst)
+}
+
+/// Unregister only if no newer register happened after `expected_gen`.
+pub(crate) fn unregister_window_shortcuts_if_generation_unchanged(
+ app_handle: tauri::AppHandle,
+ expected_gen: u64,
+ reason: &str,
+) -> Result<(), String> {
+ let current = WINDOW_SHORTCUTS_GEN.load(std::sync::atomic::Ordering::SeqCst);
+ if current != expected_gen {
+ info!(
+ "shortcut-sync: skip unregister (reason={}, expected_gen={}, current_gen={})",
+ reason, expected_gen, current
+ );
+ return Ok(());
+ }
+ unregister_window_shortcuts(app_handle)
+}
+
+/// True if any Tauri webview in this process currently holds keyboard focus.
+/// Used on Windows/Linux to tell "focus left Main for another app" from
+/// "focus moved to Home while overlay stays visible".
+pub(crate) fn any_screenpipe_webview_has_focus(app: &tauri::AppHandle) -> bool {
+ app.webview_windows()
+ .values()
+ .any(|w| w.is_focused().unwrap_or(false))
+}
+
+pub(crate) fn main_overlay_is_visible(app: &tauri::AppHandle) -> bool {
+ for label in [RewindWindowId::Main.label(), "main-window"] {
+ if let Some(w) = app.get_webview_window(label) {
+ if w.is_visible().unwrap_or(false) {
+ return true;
+ }
+ }
+ }
+ false
+}
+
+/// Re-register Escape when a non-Main window (e.g. Home) gains focus while the
+/// overlay is still shown — otherwise Main's blur path unregisters Escape and
+/// Esc stops working until Main is focused again.
+pub(crate) fn register_window_shortcuts_if_main_visible(app: tauri::AppHandle) {
+ if is_main_close_in_progress() {
+ info!("shortcut-sync: skip register_if_visible (reason=main_close_in_progress)");
+ return;
+ }
+ if main_overlay_is_visible(&app) {
+ let _ = register_window_shortcuts_with_generation(app);
+ }
+}
+
/// Install a specific older version from R2. Downloads and installs via Tauri updater,
/// then restarts the app.
#[tauri::command]
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/window/show.rs b/apps/screenpipe-app-tauri/src-tauri/src/window/show.rs
index a087ea53f..7a65569eb 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/window/show.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/window/show.rs
@@ -275,6 +275,12 @@ impl ShowRewindWindow {
}
window.unminimize().ok();
window.show().ok();
+ #[cfg(target_os = "windows")]
+ if let Err(e) =
+ crate::windows_overlay::center_window_mode_on_cursor_monitor(window, app)
+ {
+ tracing::warn!("Failed to center window-mode overlay: {}", e);
+ }
window.set_focus().ok();
let _ = app.emit("window-focused", true);
}
@@ -715,6 +721,18 @@ impl ShowRewindWindow {
tracing::error!("Failed to set display affinity: {}", e);
}
win.show().ok();
+ #[cfg(target_os = "windows")]
+ if let Err(e) =
+ crate::windows_overlay::center_window_mode_on_cursor_monitor(
+ &win,
+ &app_clone,
+ )
+ {
+ tracing::warn!(
+ "Failed to center new window-mode overlay: {}",
+ e
+ );
+ }
win.set_focus().ok();
let _ = app_clone.emit("window-focused", true);
}
@@ -817,10 +835,44 @@ impl ShowRewindWindow {
}
});
}
+ #[cfg(not(target_os = "macos"))]
+ {
+ // Only keep Escape when the overlay is still visible.
+ // Otherwise Home (or another app window) can hold focus while
+ // the overlay is already gone — returning here would skip
+ // blur unregister and leave the global Escape hook stuck on.
+ if crate::commands::any_screenpipe_webview_has_focus(&app)
+ && crate::commands::main_overlay_is_visible(&app)
+ {
+ info!(
+ "main-window blur: another screenpipe window has focus, keep Escape registered"
+ );
+ let _ = app.emit("window-focused", false);
+ return;
+ }
+ }
+ // Stale blur debounce: close_window already set MAIN_CLOSE_IN_PROGRESS
+ // and scheduled unregister — do not schedule a second unregister here.
+ if crate::commands::is_main_close_in_progress() {
+ let _ = app.emit("window-focused", false);
+ return;
+ }
// Unregister window shortcuts on focus loss (#2219)
+ info!(
+ "shortcut-sync: scheduling unregister (reason=main_window_blur_debounce)"
+ );
+ let expected_gen =
+ crate::commands::current_window_shortcuts_generation();
let app3 = app.clone();
std::thread::spawn(move || {
- let _ = crate::commands::unregister_window_shortcuts(app3);
+ info!(
+ "shortcut-sync: unregister execute (reason=main_window_blur_debounce)"
+ );
+ let _ = crate::commands::unregister_window_shortcuts_if_generation_unchanged(
+ app3,
+ expected_gen,
+ "main_window_blur_debounce",
+ );
});
let _ = app.emit("window-focused", false);
});
@@ -851,7 +903,7 @@ impl ShowRewindWindow {
// Re-register window shortcuts on focus gain
let app_reg = app_clone.clone();
std::thread::spawn(move || {
- let _ = crate::commands::register_window_shortcuts(app_reg);
+ let _ = crate::commands::register_window_shortcuts_with_generation(app_reg);
});
let _ = app_clone.emit("window-focused", true);
}
@@ -1192,11 +1244,40 @@ impl ShowRewindWindow {
}
});
}
+ #[cfg(target_os = "windows")]
+ {
+ if crate::commands::any_screenpipe_webview_has_focus(&app)
+ && crate::commands::main_overlay_is_visible(&app)
+ {
+ info!(
+ "Main overlay blur: another screenpipe window has focus, keep Escape registered"
+ );
+ let _ = app.emit("window-focused", false).ok();
+ return;
+ }
+ }
+ // Stale debounce after close_window: same as main-window path (#2219).
+ if crate::commands::is_main_close_in_progress() {
+ let _ = app.emit("window-focused", false).ok();
+ return;
+ }
// Unregister window-specific shortcuts (arrows, Escape)
// so they don't steal keys from other apps (#2219)
+ info!(
+ "shortcut-sync: scheduling unregister (reason=main_overlay_blur_debounce)"
+ );
+ let expected_gen =
+ crate::commands::current_window_shortcuts_generation();
let app3 = app.clone();
std::thread::spawn(move || {
- let _ = crate::commands::unregister_window_shortcuts(app3);
+ info!(
+ "shortcut-sync: unregister execute (reason=main_overlay_blur_debounce)"
+ );
+ let _ = crate::commands::unregister_window_shortcuts_if_generation_unchanged(
+ app3,
+ expected_gen,
+ "main_overlay_blur_debounce",
+ );
});
let _ = app.emit("window-focused", false).ok();
});
@@ -1225,7 +1306,7 @@ impl ShowRewindWindow {
// Re-register window-specific shortcuts on focus gain
let app_reg = app_clone.clone();
std::thread::spawn(move || {
- let _ = crate::commands::register_window_shortcuts(app_reg);
+ let _ = crate::commands::register_window_shortcuts_with_generation(app_reg);
});
let _ = app_clone.emit("window-focused", true).ok();
}
@@ -1275,6 +1356,63 @@ impl ShowRewindWindow {
};
let window = builder.build()?;
+ // When Main loses focus to Home, Main's debounce used to unregister Escape
+ // while the overlay stayed visible. Re-register on Home focus; unregister
+ // when Home blurs and no screenpipe window has focus (user left the app).
+ #[cfg(not(target_os = "macos"))]
+ {
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use std::sync::Arc;
+ use std::time::Duration;
+ let app_h = app.clone();
+ let home_blur_cancel = Arc::new(AtomicBool::new(false));
+ window.on_window_event(move |event| {
+ if let tauri::WindowEvent::Focused(focused) = event {
+ if !focused {
+ home_blur_cancel.store(false, Ordering::SeqCst);
+ let cancel = home_blur_cancel.clone();
+ let app_c = app_h.clone();
+ std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_millis(300));
+ if cancel.load(Ordering::SeqCst) {
+ return;
+ }
+ if crate::commands::any_screenpipe_webview_has_focus(&app_c) {
+ return;
+ }
+ if crate::commands::is_main_close_in_progress() {
+ return;
+ }
+ let expected_gen =
+ crate::commands::current_window_shortcuts_generation();
+ let app2 = app_c.clone();
+ std::thread::spawn(move || {
+ info!(
+ "shortcut-sync: unregister execute (reason=home_blur_no_screenpipe_focus)"
+ );
+ let _ = crate::commands::unregister_window_shortcuts_if_generation_unchanged(
+ app2,
+ expected_gen,
+ "home_blur_no_screenpipe_focus",
+ );
+ });
+ });
+ } else {
+ home_blur_cancel.store(true, Ordering::SeqCst);
+ let app_c = app_h.clone();
+ std::thread::spawn(move || {
+ info!(
+ "shortcut-sync: register_if_visible execute (reason=home_focus)"
+ );
+ crate::commands::register_window_shortcuts_if_main_visible(
+ app_c,
+ );
+ });
+ }
+ }
+ });
+ }
+
// Disable WKWebView's native scroll so wheel events reach JavaScript
// (needed for embedded timeline scroll gestures)
#[cfg(target_os = "macos")]
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/windows_overlay.rs b/apps/screenpipe-app-tauri/src-tauri/src/windows_overlay.rs
index 89b0f0df9..aff4e1ad7 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/windows_overlay.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/windows_overlay.rs
@@ -9,7 +9,7 @@
//! - Click-through mode: mouse events pass through to windows below
//! - Interactive mode: window receives mouse events normally
-use tauri::WebviewWindow;
+use tauri::{AppHandle, Manager, WebviewWindow};
use tracing::{error, info};
use windows::Win32::Foundation::{HWND, RECT};
use windows::Win32::Graphics::Gdi::{
@@ -224,6 +224,43 @@ pub fn is_click_through_enabled(window: &WebviewWindow) -> bool {
/// Repositions the overlay to exactly cover the monitor at the given physical point.
/// Used when re-showing the overlay so it appears on the monitor where the cursor is,
/// matching macOS behavior where the panel moves to the active screen.
+/// Centers window-mode overlay (fixed inner size) on the monitor that contains
+/// the cursor. Without this, Windows places the first webview near the prior
+/// window (often beside Home), which breaks cursor-vs-monitor bounds checks.
+pub fn center_window_mode_on_cursor_monitor(
+ window: &WebviewWindow,
+ app: &AppHandle,
+) -> Result<(), String> {
+ let cursor = app.cursor_position().map_err(|e| e.to_string())?;
+ let monitors = app.available_monitors().map_err(|e| e.to_string())?;
+ let monitor = monitors
+ .into_iter()
+ .find(|m| {
+ let p = m.position();
+ let s = m.size();
+ let cx = cursor.x as i32;
+ let cy = cursor.y as i32;
+ cx >= p.x
+ && cx < p.x + s.width as i32
+ && cy >= p.y
+ && cy < p.y + s.height as i32
+ })
+ .or_else(|| app.primary_monitor().ok().flatten())
+ .ok_or_else(|| "no monitor found for centering".to_string())?;
+
+ let mp = monitor.position();
+ let ms = monitor.size();
+ let ws = window.inner_size().map_err(|e| e.to_string())?;
+ let x = mp.x + (ms.width as i32 - ws.width as i32) / 2;
+ let y = mp.y + (ms.height as i32 - ws.height as i32) / 2;
+
+ window
+ .set_position(tauri::Position::Physical(tauri::PhysicalPosition::new(x, y)))
+ .map_err(|e| e.to_string())?;
+ info!("window-mode overlay centered at ({}, {})", x, y);
+ Ok(())
+}
+
pub fn reposition_to_cursor_monitor(
window: &WebviewWindow,
cursor_x: i32,