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(search): eliminate ~10-20s first-open freeze (pre-warm window + kill 15k-file stat storm + defer cosmetic reads)

Louis Beaumont331c674f5785
diff --git a/apps/screenpipe-app-tauri/components/rewind/search-modal.tsx b/apps/screenpipe-app-tauri/components/rewind/search-modal.tsx
index f5a2bd6a4..fd1e2e2b3 100644
--- a/apps/screenpipe-app-tauri/components/rewind/search-modal.tsx
+++ b/apps/screenpipe-app-tauri/components/rewind/search-modal.tsx
@@ -148,7 +148,7 @@ function useSuggestions(isOpen: boolean) {
let cancelled = false;
setIsLoading(true);
- (async () => {
+ const run = async () => {
try {
const now = new Date();
const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
@@ -246,10 +246,31 @@ function useSuggestions(isOpen: boolean) {
} catch {
if (!cancelled) setIsLoading(false);
}
- })();
+ };
+
+ // Defer the 24h OCR scan off the open/first-paint path so this cosmetic
+ // suggestion query (empty-state chips) doesn't compete with the initial
+ // render + first keyword search for the engine's heavy-read slots when the
+ // modal opens. Runs when the main thread next goes idle (or after a short
+ // fallback delay where requestIdleCallback is unavailable).
+ const w = window as unknown as {
+ requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number;
+ cancelIdleCallback?: (handle: number) => void;
+ };
+ let idleHandle = 0;
+ let timeoutHandle = 0;
+ if (typeof w.requestIdleCallback === "function") {
+ idleHandle = w.requestIdleCallback(() => void run(), { timeout: 1500 });
+ } else {
+ timeoutHandle = window.setTimeout(() => void run(), 200);
+ }
return () => {
cancelled = true;
+ if (idleHandle && typeof w.cancelIdleCallback === "function") {
+ w.cancelIdleCallback(idleHandle);
+ }
+ if (timeoutHandle) window.clearTimeout(timeoutHandle);
};
}, [isOpen]);
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts
index ef441dc6f..110ff181d 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/chat-storage.test.ts
@@ -51,7 +51,20 @@ vi.mock("@tauri-apps/plugin-fs", () => ({
}),
}));
+vi.mock("@/lib/utils/tauri", () => ({
+ commands: {
+ // Default: pretend the native bulk command is unavailable so the existing
+ // tests exercise the stat() fallback (mirrors a non-Tauri test env).
+ // Individual tests override this with mockImplementation/mockRejectedValue.
+ listChatEntriesByMtime: vi.fn(async () => {
+ throw new Error("no tauri runtime");
+ }),
+ },
+}));
+
+import { commands } from "@/lib/utils/tauri";
import {
+ CHAT_CONTENT_SEARCH_SCAN_LIMIT,
CHAT_HISTORY_INITIAL_LIMIT,
CONVERSATION_DEDUP_WINDOW_MS,
__resetChatStorageCachesForTests,
@@ -460,3 +473,81 @@ describe("listConversations duplicate collapsing", () => {
expect(rows.map((r) => r.id).sort()).toEqual(["evening", "morning"]);
});
});
+
+describe("chat-storage native mtime listing + bounded search", () => {
+ // Returns all conversation files sorted newest-first, mirroring the Rust
+ // `list_chat_entries_by_mtime` command. The specta binding wraps the result in
+ // a `{ status: "ok"; data }` union, so the mock must too (catches the
+ // unwrap-the-Result contract that a bare-array mock would miss).
+ const nativeListing = async (dir: string) => ({
+ status: "ok" as const,
+ data: Array.from(fsMock.files.keys())
+ .filter((path) => path.startsWith(`${dir}/`) && path.endsWith(".json"))
+ .map((path) => ({
+ name: path.slice(dir.length + 1),
+ mtime_ms: fsMock.files.get(path)?.mtime ?? 0,
+ }))
+ .sort((a, b) => b.mtime_ms - a.mtime_ms || b.name.localeCompare(a.name)),
+ });
+
+ beforeEach(() => {
+ fsMock.files.clear();
+ fsMock.reads.length = 0;
+ fsMock.stats.length = 0;
+ __resetChatStorageCachesForTests();
+ vi.mocked(commands.listChatEntriesByMtime).mockReset();
+ });
+
+ it("uses the native bulk command (no per-file stat storm) when available", async () => {
+ for (let i = 0; i < 60; i += 1) putConversation(`chat-${i}`, { updatedAt: i + 1 });
+ vi.mocked(commands.listChatEntriesByMtime).mockImplementation(nativeListing);
+
+ const rows = await listConversations({ limit: CHAT_HISTORY_INITIAL_LIMIT });
+
+ expect(rows).toHaveLength(50);
+ expect(rows[0].id).toBe("chat-59");
+ expect(fsMock.stats).toHaveLength(0); // the 15k-file stat() storm is gone
+ expect(fsMock.reads).toHaveLength(50);
+ });
+
+ it("falls back to stat() when the native command errors", async () => {
+ for (let i = 0; i < 5; i += 1) putConversation(`chat-${i}`, { updatedAt: i + 1 });
+ vi.mocked(commands.listChatEntriesByMtime).mockRejectedValue(new Error("boom"));
+
+ const rows = await listConversations({ limit: CHAT_HISTORY_INITIAL_LIMIT });
+
+ expect(rows).toHaveLength(5);
+ expect(fsMock.stats.length).toBeGreaterThan(0); // used the fallback path
+ });
+
+ it("caps the content scan to the most-recent N conversations", async () => {
+ // Needle lives only in the OLDEST chat, beyond the recent-N scan window.
+ for (let i = 0; i < CHAT_CONTENT_SEARCH_SCAN_LIMIT + 100; i += 1) {
+ putConversation(`chat-${i}`, {
+ updatedAt: i + 1,
+ content: i === 0 ? "needle-in-old-chat" : "ordinary",
+ });
+ }
+ vi.mocked(commands.listChatEntriesByMtime).mockImplementation(nativeListing);
+
+ const rows = await searchConversations("needle-in-old-chat", { limit: 50 });
+
+ expect(rows).toHaveLength(0); // oldest is past the cap → not body-searched
+ expect(fsMock.reads.length).toBe(CHAT_CONTENT_SEARCH_SCAN_LIMIT);
+ });
+
+ it("finds matches within the most-recent N", async () => {
+ const newest = CHAT_CONTENT_SEARCH_SCAN_LIMIT + 99;
+ for (let i = 0; i <= newest; i += 1) {
+ putConversation(`chat-${i}`, {
+ updatedAt: i + 1,
+ content: i === newest ? "fresh-needle" : "ordinary",
+ });
+ }
+ vi.mocked(commands.listChatEntriesByMtime).mockImplementation(nativeListing);
+
+ const rows = await searchConversations("fresh-needle", { limit: 50 });
+
+ expect(rows.map((r) => r.id)).toEqual([`chat-${newest}`]);
+ });
+});
diff --git a/apps/screenpipe-app-tauri/lib/chat-storage.ts b/apps/screenpipe-app-tauri/lib/chat-storage.ts
index 1070a54b1..578755435 100644
--- a/apps/screenpipe-app-tauri/lib/chat-storage.ts
+++ b/apps/screenpipe-app-tauri/lib/chat-storage.ts
@@ -19,6 +19,7 @@ import type {
PipeContext,
} from "@/lib/hooks/use-settings";
import { deleteCachedBrowserState } from "@/lib/browser-state-cache";
+import { commands } from "@/lib/utils/tauri";
import {
CHAT_PROCESSING_PLACEHOLDER,
CONVERSATION_DEDUP_WINDOW_MS,
@@ -26,6 +27,12 @@ import {
messagesHaveCompletedReply,
} from "@/lib/chat-dedup";
+// Cap on how many (most-recent) conversation files a content search will open
+// and scan. Title matches are cheap over the full ordered list; only the
+// message-body scan is bounded so a rare/no-match query can't read all 15k+
+// files (each a Tauri IPC round-trip) and hang the search modal.
+export const CHAT_CONTENT_SEARCH_SCAN_LIMIT = 500;
+
let _chatsDir: string | null = null;
let _orderedEntriesCacheDir: string | null = null;
let _orderedEntriesCache: ConversationEntry[] | null = null;
@@ -280,7 +287,22 @@ async function orderedConversationEntries(dir: string): Promise<ConversationEntr
return _orderedEntriesCache;
}
- const ordered = await orderEntriesByMtime(await listConversationEntries(dir));
+ let ordered: ConversationEntry[];
+ try {
+ // One native readdir+metadata pass in Rust, already sorted newest-first.
+ // Replaces a `stat()` IPC round-trip per file (~15k on large histories),
+ // which froze the search modal on cold open. The specta binding wraps the
+ // Rust `Result` in a `{ status, data | error }` union — unwrap it here.
+ const res = await commands.listChatEntriesByMtime(dir);
+ if (res.status !== "ok") throw new Error(res.error);
+ ordered = res.data
+ .filter((r) => r.name.endsWith(".json"))
+ .map((r) => ({ name: r.name, path: `${dir}/${r.name}` }));
+ } catch {
+ // Fallback: enumerate + stat() per file (slow but correct) when the command
+ // is unavailable (older engine / bindings drift / non-Tauri test env).
+ ordered = await orderEntriesByMtime(await listConversationEntries(dir));
+ }
_orderedEntriesCacheDir = dir;
_orderedEntriesCache = ordered;
return ordered;
@@ -508,7 +530,12 @@ export async function searchConversations(
const limit = normalizeLimit(options.limit ?? CHAT_SEARCH_RESULT_LIMIT);
const offset = Math.max(0, Math.floor(options.offset ?? 0));
if (limit === 0) return [];
- const entries = await orderedConversationEntries(dir);
+ // Bound the body scan to the most-recent N conversations. Entries are sorted
+ // newest-first, so this searches recent chats and caps a rare/no-match query
+ // at N file reads instead of all 15k+ (each a Tauri IPC round-trip that froze
+ // the modal). Older conversations are intentionally not body-searched here.
+ const allEntries = await orderedConversationEntries(dir);
+ const entries = allEntries.slice(0, CHAT_CONTENT_SEARCH_SCAN_LIMIT);
const candidates: ConversationDedupCandidate[] = [];
let skipped = 0;
diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
index a48b24a43..eab26085b 100644
--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -843,6 +843,14 @@ async listCacheFiles() : Promise<Result<CacheFile[], string>> {
else return { status: "error", error: e as any };
}
},
+async listChatEntriesByMtime(dir: string) : Promise<Result<ChatDirEntry[], string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("list_chat_entries_by_mtime", { dir }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
/**
* List skills currently in the screenpipe store.
*/
@@ -2308,6 +2316,7 @@ endDisplay: string; attendees: string[]; location: string | null; meetingUrl: st
*/
source?: string }
export type CalendarStatus = { available: boolean; authorized: boolean; authorizationStatus: string; calendarCount: number }
+export type ChatDirEntry = { name: string; mtime_ms: number }
export type ChatGptOAuthStatus = { logged_in: boolean }
export type Credits = { amount: number }
/**
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index cc5c2a544..4a4798478 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -10927,7 +10927,7 @@ dependencies = [
[[package]]
name = "screenpipe-app"
-version = "2.5.62"
+version = "2.5.76"
dependencies = [
"aes 0.8.4",
"aes-gcm 0.10.3",
@@ -11048,7 +11048,7 @@ dependencies = [
[[package]]
name = "screenpipe-audio"
-version = "0.4.23"
+version = "0.4.24"
dependencies = [
"anyhow",
"audiopipe",
@@ -11123,7 +11123,7 @@ dependencies = [
[[package]]
name = "screenpipe-config"
-version = "0.4.23"
+version = "0.4.24"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -11135,7 +11135,7 @@ dependencies = [
[[package]]
name = "screenpipe-connect"
-version = "0.4.23"
+version = "0.4.24"
dependencies = [
"anyhow",
"async-trait",
@@ -11176,7 +11176,7 @@ dependencies = [
[[package]]
name = "screenpipe-core"
-version = "0.4.23"
+version = "0.4.24"
dependencies = [
"accessibility",
"accessibility-sys",
@@ -11227,7 +11227,7 @@ dependencies = [
[[package]]
name = "screenpipe-db"
-version = "0.4.23"
+version = "0.4.24"
dependencies = [
"anyhow",
"chrono",
@@ -11252,7 +11252,7 @@ dependencies = [
[[package]]
name = "screenpipe-engine"
-version = "0.4.23"
+version = "0.4.24"
dependencies = [
"anyhow",
"arc-swap",
@@ -11319,7 +11319,7 @@ dependencies = [
[[package]]
name = "screenpipe-events"
-version = "0.4.23"
+version = "0.4.24"
dependencies = [
"anyhow",
"chrono",
@@ -11335,7 +11335,7 @@ dependencies = [
[[package]]
name = "screenpipe-redact"
-version = "0.4.23"
+version = "0.4.24"
dependencies = [
"aho-corasick",
"anyhow",
@@ -11370,7 +11370,7 @@ dependencies = [
[[package]]
name = "screenpipe-rfdetr-mlx"
-version = "0.4.23"
+version = "0.4.24"
dependencies = [
"image 0.25.10",
"mlx-rs",
@@ -11381,7 +11381,7 @@ dependencies = [
[[package]]
name = "screenpipe-screen"
-version = "0.4.23"
+version = "0.4.24"
dependencies = [
"accessibility-sys",
"anyhow",
@@ -11435,7 +11435,7 @@ dependencies = [
[[package]]
name = "screenpipe-sync"
-version = "0.4.23"
+version = "0.4.24"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -11455,7 +11455,7 @@ dependencies = [
[[package]]
name = "screenpipe-vault"
-version = "0.4.23"
+version = "0.4.24"
dependencies = [
"argon2",
"chacha20poly1305",
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
index 609cb9674..cbc1705ca 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
@@ -375,10 +375,40 @@ fn emit_meeting_note_route_with_retries(app: &tauri::AppHandle, deeplink_url: &s
mod tests {
use super::{
fallback_local_api_config, is_login_callback_scheme, notification_copy_value,
- notification_source_url, parse_meeting_deeplink,
+ notification_source_url, parse_meeting_deeplink, scan_chat_entries_by_mtime,
};
use serde_json::json;
+ #[test]
+ fn chat_entries_missing_dir_is_empty() {
+ // First run (no chats dir yet) must be a clean empty list, not an error.
+ let res =
+ scan_chat_entries_by_mtime("/definitely/not/a/real/screenpipe/chats/path").unwrap();
+ assert!(res.is_empty());
+ }
+
+ #[test]
+ fn chat_entries_filters_non_json_and_orders_newest_first() {
+ use std::time::{Duration, SystemTime};
+ let dir = tempfile::tempdir().unwrap();
+ let p = dir.path();
+
+ let a = std::fs::File::create(p.join("a.json")).unwrap();
+ a.set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(1_000))
+ .unwrap();
+ let b = std::fs::File::create(p.join("b.json")).unwrap();
+ b.set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(2_000))
+ .unwrap();
+ // Non-.json must be ignored.
+ std::fs::File::create(p.join("notes.txt")).unwrap();
+
+ let res = scan_chat_entries_by_mtime(p.to_str().unwrap()).unwrap();
+ let names: Vec<&str> = res.iter().map(|e| e.name.as_str()).collect();
+ assert_eq!(names, vec!["b.json", "a.json"]); // newest first
+ assert!(res.iter().all(|e| e.name.ends_with(".json")));
+ assert!(res[0].mtime_ms >= res[1].mtime_ms);
+ }
+
#[test]
fn parses_meeting_deeplink_path_id() {
assert_eq!(
@@ -2465,6 +2495,67 @@ pub async fn get_keychain_status() -> Result<KeychainStatus, String> {
})
}
+/// One conversation file with its modified time (epoch millis). Returned by
+/// [`list_chat_entries_by_mtime`].
+#[derive(serde::Serialize, specta::Type)]
+pub struct ChatDirEntry {
+ pub name: String,
+ pub mtime_ms: f64,
+}
+
+/// List `*.json` conversation files in `dir`, newest-first by mtime, in a SINGLE
+/// native directory scan.
+///
+/// The chat list/search previously sorted by firing one `stat()` IPC call per
+/// file via `Promise.all` — with 15k+ conversations that's 15k Tauri round-trips
+/// on every cold open, which (alongside the webview cold-boot) froze the search
+/// modal for seconds before the input was usable. Doing the readdir + metadata
+/// pass in Rust collapses it to one call (~40ms for 15k files).
+///
+/// A missing dir (first run) returns an empty list, not an error.
+#[tauri::command]
+#[specta::specta]
+pub async fn list_chat_entries_by_mtime(dir: String) -> Result<Vec<ChatDirEntry>, String> {
+ scan_chat_entries_by_mtime(&dir)
+}
+
+/// Sync core of [`list_chat_entries_by_mtime`] (testable without a Tauri runtime).
+fn scan_chat_entries_by_mtime(dir: &str) -> Result<Vec<ChatDirEntry>, String> {
+ let read_dir = match std::fs::read_dir(dir) {
+ Ok(rd) => rd,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
+ Err(e) => return Err(format!("read_dir {dir}: {e}")),
+ };
+
+ let mut entries: Vec<ChatDirEntry> = Vec::new();
+ for entry in read_dir.flatten() {
+ let name = entry.file_name().to_string_lossy().into_owned();
+ if !name.ends_with(".json") {
+ continue;
+ }
+ // mtime is best-effort; fall back to 0 (sorted last) if unavailable.
+ let mtime_ms = entry
+ .metadata()
+ .ok()
+ .and_then(|m| m.modified().ok())
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|d| d.as_millis() as f64)
+ .unwrap_or(0.0);
+ entries.push(ChatDirEntry { name, mtime_ms });
+ }
+
+ // Newest first; tiebreak by name descending to match the TS ordering
+ // (`b.sortTime - a.sortTime || b.name.localeCompare(a.name)`).
+ entries.sort_by(|a, b| {
+ b.mtime_ms
+ .partial_cmp(&a.mtime_ms)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ .then_with(|| b.name.cmp(&a.name))
+ });
+
+ Ok(entries)
+}
+
#[tauri::command]
#[specta::specta]
pub async fn enable_keychain_encryption() -> Result<KeychainStatus, String> {
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 26acd0377..418b8fa89 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -1405,6 +1405,27 @@ async fn main() {
});
}
+ // Pre-warm the floating search window (hidden, unfocused) so the
+ // FIRST search-shortcut press reuses a warm webview instead of
+ // cold-booting Next.js for ~5s (the "search frozen ~10s before you
+ // can type" bug). Cross-platform: create_search_window builds it
+ // hidden and never shows/activates it when unfocused, so there's no
+ // blink or focus-steal. Guarded like the chat pre-create above.
+ if onboarding_store.is_completed && !app_ui_hidden {
+ let app_handle_search = app.handle().clone();
+ tauri::async_runtime::spawn(async move {
+ // Stagger after the chat pre-create (3s) so the two hidden
+ // webviews don't cold-boot at the same instant as the main
+ // window.
+ tokio::time::sleep(tokio::time::Duration::from_secs(4)).await;
+ if app_handle_search.get_webview_window("search").is_none() {
+ if let Err(e) = ShowRewindWindow::prewarm_search(&app_handle_search) {
+ warn!("failed to pre-warm search window: {}", e);
+ }
+ }
+ });
+ }
+
// Pi is NOT auto-started at boot — it starts lazily when the user opens
// the chat (standalone-chat.tsx calls pi_start). An idle watchdog in pi.rs
// auto-stops it after 5 minutes of inactivity to avoid stale processes.
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 164273e67..4847778da 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/window/show.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/window/show.rs
@@ -1467,104 +1467,11 @@ impl ShowRewindWindow {
window
}
ShowRewindWindow::Search { query } => {
- let mut url = "/search".to_string();
info!("query: {:?}", query);
- if let Some(q) = query {
- url.push_str(&format!("{}", q));
- }
-
- // Raycast-style floating search bar — compact, centered, no chrome
- // Start thin (just the input row), JS will resize as results appear
- let bar_w = 680.0_f64;
- let bar_h = 80.0; // input row + footer
- let (x, y) = if let Ok(Some(monitor)) = app.primary_monitor() {
- let logical: LogicalSize<f64> =
- monitor.size().to_logical(monitor.scale_factor());
- let pos = monitor.position();
- let scale = monitor.scale_factor();
- let origin_x = pos.x as f64 / scale;
- let origin_y = pos.y as f64 / scale;
- (
- origin_x + (logical.width - bar_w.min(logical.width - 40.0)) / 2.0,
- origin_y + logical.height * 0.22, // ~22% from top
- )
- } else {
- (200.0, 140.0)
- };
- let bar_w = if let Ok(Some(monitor)) = app.primary_monitor() {
- let logical: LogicalSize<f64> =
- monitor.size().to_logical(monitor.scale_factor());
- bar_w.min(logical.width - 40.0)
- } else {
- bar_w
- };
-
- let builder =
- WebviewWindow::builder(app, self.id().label(), WebviewUrl::App(url.into()))
- .title("")
- .visible(false) // show after panel conversion
- .accept_first_mouse(true)
- .shadow(true)
- .decorations(false)
- .transparent(true)
- .always_on_top(true)
- .visible_on_all_workspaces(true)
- .inner_size(bar_w, bar_h)
- .min_inner_size(400.0, 56.0)
- .position(x, y)
- .focused(true)
- .resizable(true);
-
- let window = super::finalize_webview_window(builder.build()?);
-
- // Skip NSPanel conversion for search — it causes SIGSEGV crashes
- // in objc_autoreleasePoolPop on macOS 26. Use raw NSWindow level
- // instead to float above fullscreen apps without NSPanel.
- #[cfg(target_os = "macos")]
- {
- let window_clone = window.clone();
- run_on_main_thread_safe(app, move || {
- use objc::{msg_send, sel, sel_impl};
- use tauri_nspanel::cocoa::base::id;
- use tauri_nspanel::objc_foundation::INSObject;
- use tauri_nspanel::raw_nspanel::object_setClass;
- if let Ok(ns_win) = window_clone.ns_window() {
- let ns_win = ns_win as id;
- unsafe {
- // Swizzle NSWindow → NSPanel class for non-activating behavior
- // Do NOT use to_panel() — its Id::from_retained_ptr causes
- // use-after-free on window.close() → SIGSEGV
- let nspanel_class: id = msg_send![
- tauri_nspanel::raw_nspanel::RawNSPanel::class(),
- class
- ];
- object_setClass(ns_win, nspanel_class);
-
- // Level 1002 — above fullscreen (CGShieldingWindowLevel+2)
- let _: () = msg_send![ns_win, setLevel: 1002_i64];
-
- // NSNonactivatingPanelMask (128) — appear over fullscreen
- // without triggering Space switch
- let current: i32 = msg_send![ns_win, styleMask];
- let _: () = msg_send![ns_win, setStyleMask: current | 128];
-
- // CanJoinAllSpaces (1) + FullScreenAuxiliary (256)
- let _: () = msg_send![ns_win, setCollectionBehavior: 257_u64];
-
- let _: () = msg_send![ns_win, setHidesOnDeactivate: false];
- let _: () = msg_send![ns_win, orderFrontRegardless];
- let _: () = msg_send![ns_win, makeKeyWindow];
- }
- }
- });
- }
- #[cfg(not(target_os = "macos"))]
- {
- let _ = window.show();
- window.set_focus().ok();
- }
-
- window
+ // Build the floating search bar and bring it to front (focus=true).
+ // The hidden pre-warm path (prewarm_search) reuses the same builder
+ // with focus=false so startup doesn't steal focus.
+ Self::create_search_window(app, query.as_deref(), true)?
}
ShowRewindWindow::Onboarding => {
if onboarding_store.is_completed {
@@ -1739,6 +1646,144 @@ impl ShowRewindWindow {
Ok(window)
}
+ /// Build the floating search bar (Raycast-style). When `focus` is true the
+ /// window is brought to front and made key (the normal open). When false it
+ /// is created hidden and NOT activated — used by `prewarm_search` so startup
+ /// doesn't steal focus, while the FIRST real open reuses this warm webview
+ /// (show()'s existing-window branch) instead of paying a multi-second
+ /// Next.js cold-boot during which the input is unresponsive.
+ fn create_search_window(
+ app: &AppHandle,
+ query: Option<&str>,
+ focus: bool,
+ ) -> tauri::Result<WebviewWindow> {
+ let mut url = "/search".to_string();
+ if let Some(q) = query {
+ url.push_str(q);
+ }
+
+ // Compact, centered, no chrome. Start thin (just the input row); JS
+ // resizes as results appear.
+ let default_bar_w = 680.0_f64;
+ let bar_h = 80.0; // input row + footer
+ let (x, y, bar_w) = if let Ok(Some(monitor)) = app.primary_monitor() {
+ let logical: LogicalSize<f64> = monitor.size().to_logical(monitor.scale_factor());
+ let pos = monitor.position();
+ let scale = monitor.scale_factor();
+ let origin_x = pos.x as f64 / scale;
+ let origin_y = pos.y as f64 / scale;
+ let w = default_bar_w.min(logical.width - 40.0);
+ (
+ origin_x + (logical.width - w) / 2.0,
+ origin_y + logical.height * 0.22, // ~22% from top
+ w,
+ )
+ } else {
+ (200.0, 140.0, default_bar_w)
+ };
+
+ let builder = WebviewWindow::builder(
+ app,
+ RewindWindowId::Search.label(),
+ WebviewUrl::App(url.into()),
+ )
+ .title("")
+ .visible(false) // shown after panel conversion (and only when `focus`)
+ .accept_first_mouse(true)
+ .shadow(true)
+ .decorations(false)
+ .transparent(true)
+ .always_on_top(true)
+ .visible_on_all_workspaces(true)
+ .inner_size(bar_w, bar_h)
+ .min_inner_size(400.0, 56.0)
+ .position(x, y)
+ .focused(focus)
+ .resizable(true);
+
+ let window = super::finalize_webview_window(builder.build()?);
+
+ // Skip tauri-nspanel to_panel() — it causes SIGSEGV in
+ // objc_autoreleasePoolPop on macOS 26. Swizzle the raw NSWindow class
+ // instead so it floats above fullscreen apps without NSPanel. The
+ // class/level/style/collection setup runs for BOTH paths so a pre-warmed
+ // (hidden) window is already a configured panel; only the
+ // order-front/make-key activation is gated on `focus`.
+ #[cfg(target_os = "macos")]
+ {
+ let window_clone = window.clone();
+ run_on_main_thread_safe(app, move || {
+ use objc::{msg_send, sel, sel_impl};
+ use tauri_nspanel::cocoa::base::id;
+ use tauri_nspanel::objc_foundation::INSObject;
+ use tauri_nspanel::raw_nspanel::object_setClass;
+ if let Ok(ns_win) = window_clone.ns_window() {
+ let ns_win = ns_win as id;
+ unsafe {
+ let nspanel_class: id =
+ msg_send![tauri_nspanel::raw_nspanel::RawNSPanel::class(), class];
+ object_setClass(ns_win, nspanel_class);
+
+ // Level 1002 — above fullscreen (CGShieldingWindowLevel+2)
+ let _: () = msg_send![ns_win, setLevel: 1002_i64];
+
+ // NSNonactivatingPanelMask (128) — appear over fullscreen
+ // without triggering a Space switch
+ let current: i32 = msg_send![ns_win, styleMask];
+ let _: () = msg_send![ns_win, setStyleMask: current | 128];
+
+ // CanJoinAllSpaces (1) + FullScreenAuxiliary (256)
+ let _: () = msg_send![ns_win, setCollectionBehavior: 257_u64];
+
+ let _: () = msg_send![ns_win, setHidesOnDeactivate: false];
+
+ // Only activate for a real open. Pre-warm leaves the
+ // window ordered-out so startup never steals focus.
+ if focus {
+ let _: () = msg_send![ns_win, orderFrontRegardless];
+ let _: () = msg_send![ns_win, makeKeyWindow];
+ }
+ }
+ }
+ });
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ if focus {
+ let _ = window.show();
+ window.set_focus().ok();
+ }
+ // Pre-warm (focus=false): leave hidden (visible(false)). The
+ // existing-window branch in show() shows()+focuses on first open.
+ }
+
+ Ok(window)
+ }
+
+ /// Pre-warm the floating search window at startup: create it hidden and
+ /// unfocused so the FIRST user-triggered open reuses this warm webview
+ /// (instant) instead of cold-booting Next.js for several seconds (the
+ /// "search bar frozen ~10s before you can type" bug). No-op if the window
+ /// already exists or the UI is suppressed (enterprise hidden mode).
+ pub fn prewarm_search(app: &AppHandle) -> tauri::Result<()> {
+ if crate::enterprise_policy::is_app_ui_hidden() {
+ return Ok(());
+ }
+ if app
+ .get_webview_window(RewindWindowId::Search.label())
+ .is_some()
+ {
+ return Ok(());
+ }
+ let window = Self::create_search_window(app, None, false)?;
+ #[cfg(target_os = "macos")]
+ setup_content_process_handler(&window);
+ #[cfg(not(target_os = "macos"))]
+ let _ = &window;
+ info!("search window pre-warmed (hidden, unfocused)");
+ Ok(())
+ }
+
/// Hide Main panel without restoring the previous frontmost app.
/// Used when transitioning from Main to another screenpipe window (e.g. Home/Settings)
/// so that focus stays with the app instead of bouncing to the previous app.