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

refactor(owned-browser): child WebView, session access, and omnibox chrome

divanshu-go915de37f830f
diff --git a/apps/screenpipe-app-tauri/components/browser-sidebar.tsx b/apps/screenpipe-app-tauri/components/browser-sidebar.tsx
index c9da294c2..05afbd6a2 100644
--- a/apps/screenpipe-app-tauri/components/browser-sidebar.tsx
+++ b/apps/screenpipe-app-tauri/components/browser-sidebar.tsx
@@ -5,11 +5,11 @@
/**
* BrowserSidebar — a right-side panel inside the chat layout that hosts the
- * agent-controlled embedded browser. The actual page is rendered by a
- * Tauri *top-level* `WebviewWindow` (label: "owned-browser") created in
+ * agent-controlled embedded browser. The actual page is rendered by a Tauri
+ * child `Webview` (label: "owned-browser") created in
* `src-tauri/src/owned_browser.rs`. This component owns:
- * 1. Layout: measures its placeholder div and pushes those bounds to Tauri
- * so the native webview tracks the panel's position.
+ * 1. Layout: coalesces placeholder measurements and pushes parent-local
+ * bounds to Tauri so the native webview tracks the panel.
* 2. Width: a JS-clamped state — never relies on CSS flex/max-width, since
* Tailwind class changes via HMR are unreliable and flex-shrink behavior
* drifted in practice. We compute `effectiveWidth = clamp(width, MIN,
@@ -19,17 +19,16 @@
* 4. Collapse: hide/show toggle. The webview survives in the background
* (cookies + page state preserved) — only the panel is hidden.
*
- * The agent triggers navigation via
- * `POST /connections/browsers/owned-default/eval`. That emits a
- * `owned-browser:navigate` event the sidebar listens to.
+ * The agent triggers navigation via `POST /connections/browsers/owned-default`.
+ * Rust emits requested-navigation and native page-state events; the header
+ * always renders the native state when it is available.
*/
import React, { useCallback, useEffect, useRef, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window";
-import { motion, AnimatePresence } from "framer-motion";
-import { KeyRound, PanelRightClose, PanelRightOpen, RotateCw } from "lucide-react";
+import { KeyRound, RotateCw, PanelRightClose, PanelRightOpen } from "lucide-react";
import {
loadConversationFile,
updateConversationFlags,
@@ -38,6 +37,7 @@ import { Button } from "@/components/ui/button";
const NAVIGATE_EVENT = "owned-browser:navigate";
const SESSION_ACCESS_REQUEST_EVENT = "owned-browser:session-access-request";
+const STATE_EVENT = "owned-browser:state";
const DEFAULT_WIDTH = 480;
const MIN_WIDTH = 320;
const MIN_CHAT_WIDTH = 360;
@@ -59,6 +59,12 @@ interface ActiveSessionAccessRequest {
host: string;
}
+interface OwnedBrowserStateEvent {
+ url?: string | null;
+ title?: string | null;
+ loading?: boolean | null;
+}
+
/** Clamp the panel width so it can never push the chat below MIN_CHAT_WIDTH
* in the *available* horizontal area (the chat layout's split host, not
* the whole window — AppSidebar / history sidebar can eat into it).
@@ -74,6 +80,8 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
const [visible, setVisible] = useState(false);
const [collapsed, setCollapsed] = useState(false);
const [currentUrl, setCurrentUrl] = useState<string | null>(null);
+ const [currentTitle, setCurrentTitle] = useState<string | null>(null);
+ const [loading, setLoading] = useState(false);
const [sessionAccessRequest, setSessionAccessRequest] =
useState<ActiveSessionAccessRequest | null>(null);
const [sessionAccessAnswer, setSessionAccessAnswer] = useState<
@@ -91,6 +99,9 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
);
const placeholderRef = useRef<HTMLDivElement>(null);
const panelRef = useRef<HTMLDivElement>(null);
+ const boundsRafRef = useRef<number | null>(null);
+ /** True while the cookie-consent card is up — pushBounds must not re-show the native webview. */
+ const sessionAccessActiveRef = useRef(false);
const dragStateRef = useRef<{ startX: number; startWidth: number } | null>(
null,
);
@@ -136,12 +147,18 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
);
// ---------------------------------------------------------------------------
- // Bounds push (CSS rect → Rust → screen position)
+ // Bounds push (CSS rect → Rust → child webview bounds)
// ---------------------------------------------------------------------------
const pushBounds = useCallback(async () => {
const el = placeholderRef.current;
if (!el) return;
+ // Native child webviews sit above HTML — never position/show while the
+ // session-access card is visible (ResizeObserver races with hide()).
+ if (sessionAccessActiveRef.current) {
+ await invoke("owned_browser_hide").catch(() => {});
+ return;
+ }
// offsetParent === null when any ancestor is display:none. That's how
// the home page hides the always-mounted chat layer when the user
// switches to Memories / Settings / Timeline / etc. Without checking
@@ -168,6 +185,23 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
}
}, []);
+ const schedulePushBounds = useCallback(() => {
+ if (boundsRafRef.current !== null) return;
+ boundsRafRef.current = requestAnimationFrame(() => {
+ boundsRafRef.current = null;
+ void pushBounds();
+ });
+ }, [pushBounds]);
+
+ useEffect(() => {
+ return () => {
+ if (boundsRafRef.current !== null) {
+ cancelAnimationFrame(boundsRafRef.current);
+ boundsRafRef.current = null;
+ }
+ };
+ }, []);
+
// ---------------------------------------------------------------------------
// Viewport resize tracking — drives both the JS clamp and re-pushing bounds
// ---------------------------------------------------------------------------
@@ -186,9 +220,11 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
setAvailableW(window.innerWidth);
return;
}
- const measure = () => setAvailableW(host.getBoundingClientRect().width);
- measure();
- const ro = new ResizeObserver(measure);
+ setAvailableW(host.clientWidth);
+ const ro = new ResizeObserver((entries) => {
+ const width = entries[0]?.contentRect.width ?? host.clientWidth;
+ setAvailableW(width);
+ });
ro.observe(host);
return () => ro.disconnect();
}, [panelOpen]);
@@ -206,6 +242,8 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
setVisible(true);
setCollapsed(false);
setCurrentUrl(url);
+ setCurrentTitle(null);
+ setLoading(true);
persistState({ url, collapsed: false });
});
return () => {
@@ -230,6 +268,8 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
setVisible(true);
setCollapsed(false);
setCurrentUrl(request.url);
+ setCurrentTitle(null);
+ setLoading(true);
persistState({ url: request.url, collapsed: false });
invoke("owned_browser_hide").catch(() => {});
},
@@ -239,6 +279,40 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
};
}, [persistState]);
+ useEffect(() => {
+ sessionAccessActiveRef.current = sessionAccessRequest !== null;
+ if (sessionAccessRequest) {
+ invoke("owned_browser_hide").catch(() => {});
+ } else if (panelOpen) {
+ schedulePushBounds();
+ }
+ }, [sessionAccessRequest, panelOpen, schedulePushBounds]);
+
+ useEffect(() => {
+ const unlistenPromise = listen<OwnedBrowserStateEvent>(STATE_EVENT, (e) => {
+ const payload = e.payload;
+ if (!payload || typeof payload !== "object") return;
+
+ if (typeof payload.url === "string" && payload.url.length > 0) {
+ if (payload.url !== currentUrl) {
+ setCurrentTitle(null);
+ }
+ setCurrentUrl(payload.url);
+ persistState({ url: payload.url });
+ }
+ if (typeof payload.title === "string") {
+ const title = payload.title.trim();
+ setCurrentTitle(title.length > 0 ? title : null);
+ }
+ if (typeof payload.loading === "boolean") {
+ setLoading(payload.loading);
+ }
+ });
+ return () => {
+ unlistenPromise.then((fn) => fn()).catch(() => {});
+ };
+ }, [currentUrl, persistState]);
+
// ---------------------------------------------------------------------------
// Per-conversation restore
// ---------------------------------------------------------------------------
@@ -249,6 +323,8 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
setVisible(false);
setCollapsed(false);
setCurrentUrl(null);
+ setCurrentTitle(null);
+ setLoading(false);
setSessionAccessRequest(null);
setSessionAccessAnswer(null);
setRequestedWidth(DEFAULT_WIDTH);
@@ -270,6 +346,8 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
setVisible(true);
setCollapsed(wasCollapsed);
setCurrentUrl(url);
+ setCurrentTitle(null);
+ setLoading(!wasCollapsed);
// The webview install runs on a background task that retries
// until the app's Tauri runtime has booted. On cold start a chat
// with a saved `browserState.url` opens fast enough that this
@@ -295,6 +373,8 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
setVisible(false);
setCollapsed(false);
setCurrentUrl(null);
+ setCurrentTitle(null);
+ setLoading(false);
invoke("owned_browser_hide").catch(() => {});
}
})();
@@ -305,59 +385,19 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
}, [conversationId]);
// ---------------------------------------------------------------------------
- // Bounds tracking — covers slide-in, window resize, drag-resize,
- // chat-history toggle, window move (top-level webview lives in screen
- // coords, doesn't follow parent moves automatically).
+ // Bounds tracking — covers slide-in, window resize, drag-resize, and
+ // chat/app sidebar layout changes. The native browser is now a child
+ // Webview attached to the same Tauri window, so parent window movement no
+ // longer needs per-frame screen-coordinate chasing.
// ---------------------------------------------------------------------------
useEffect(() => {
if (!panelOpen) return;
const el = placeholderRef.current;
if (!el) return;
- pushBounds();
-
- // Burst-mode rect poll. ResizeObserver only fires on *size* changes —
- // position changes (sibling flex-basis growing, chat-history sidebar
- // collapsing, JSX restructure via HMR) leave the native webview at
- // stale screen coords. So we still poll via rAF, but only for a short
- // window after a known trigger (mount, ResizeObserver fire, window
- // move/resize). When the rect is stable for BURST_MS, the loop stops
- // and idle CPU drops to zero. Previously this rAF ran forever, which
- // pinned tauri://localhost at ~80% and cascaded into WindowServer +
- // replayd via the per-frame bind/setBounds path.
- const BURST_MS = 500;
- let raf = 0;
- let last = el.getBoundingClientRect();
- let lastChangeAt = performance.now();
-
- const tick = () => {
- const r = el.getBoundingClientRect();
- if (
- r.left !== last.left ||
- r.top !== last.top ||
- r.width !== last.width ||
- r.height !== last.height
- ) {
- last = r;
- lastChangeAt = performance.now();
- pushBounds();
- }
- if (performance.now() - lastChangeAt < BURST_MS) {
- raf = requestAnimationFrame(tick);
- } else {
- raf = 0;
- }
- };
-
- const scheduleBurst = () => {
- lastChangeAt = performance.now();
- if (!raf) {
- last = el.getBoundingClientRect();
- raf = requestAnimationFrame(tick);
- }
- };
+ schedulePushBounds();
- const ro = new ResizeObserver(scheduleBurst);
+ const ro = new ResizeObserver(schedulePushBounds);
ro.observe(el);
// Also observe the panel's flex parent — a sibling's flex-basis change
// (chat history sidebar collapse, app sidebar toggle) shifts our
@@ -366,21 +406,10 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
const host = panelRef.current?.parentElement;
if (host) ro.observe(host);
- const w = getCurrentWindow();
- const unlistenMovedP = w.listen("tauri://move", scheduleBurst);
- const unlistenResizedP = w.listen("tauri://resize", scheduleBurst);
-
- // Initial burst covers the slide-in animation (~200ms) and any
- // post-mount layout settling.
- scheduleBurst();
-
return () => {
ro.disconnect();
- if (raf) cancelAnimationFrame(raf);
- unlistenMovedP.then((fn) => fn()).catch(() => {});
- unlistenResizedP.then((fn) => fn()).catch(() => {});
};
- }, [panelOpen, pushBounds]);
+ }, [panelOpen, effectiveWidth, availableW, schedulePushBounds]);
// ---------------------------------------------------------------------------
// Drag-resize
@@ -434,6 +463,7 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
const reload = useCallback(async () => {
if (!currentUrl) return;
try {
+ setLoading(true);
await invoke("owned_browser_navigate", { url: currentUrl });
} catch (e) {
console.error("reload failed", e);
@@ -442,6 +472,7 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
const collapse = useCallback(() => {
setCollapsed(true);
+ setLoading(false);
persistState({ collapsed: true });
invoke("owned_browser_hide").catch(() => {});
}, [persistState]);
@@ -461,10 +492,11 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
requestId: request.requestId,
allow,
});
+ setSessionAccessRequest((current) =>
+ current?.requestId === request.requestId ? null : current,
+ );
if (!allow) {
- setSessionAccessRequest((current) =>
- current?.requestId === request.requestId ? null : current,
- );
+ setSessionAccessAnswer(null);
}
} catch (e) {
console.error("owned_browser_resolve_session_access failed", e);
@@ -472,8 +504,6 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
current?.requestId === request.requestId ? null : current,
);
setSessionAccessAnswer(null);
- } finally {
- if (!allow) setSessionAccessAnswer(null);
}
},
[sessionAccessRequest, sessionAccessAnswer],
@@ -483,116 +513,127 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
// Render
// ---------------------------------------------------------------------------
+ const headerTitle = currentTitle ?? currentUrl ?? "about:blank";
+
return (
<>
- <AnimatePresence>
- {panelOpen && (
- <motion.div
- ref={panelRef}
- initial={{ width: 0, opacity: 0 }}
- animate={{ width: effectiveWidth, opacity: 1 }}
- exit={{ width: 0, opacity: 0 }}
- transition={{ duration: 0.2 }}
- // Inline flex item — sits *beside* the chat, doesn't overlay
- // it. shrink-0 keeps us at effectiveWidth; the chat content
- // (flex-1 min-w-0) gives way. The JS clamp on effectiveWidth
- // guarantees viewport - chat ≥ 360px so the chat is never
- // crushed below readable width.
- style={{ width: effectiveWidth, flexBasis: effectiveWidth }}
- className="border-l border-border/50 bg-muted/30 flex flex-col overflow-hidden shrink-0 relative"
- >
- {/* Drag handle — 10px hot zone on the left edge with a thicker
+ {panelOpen && (
+ <div
+ ref={panelRef}
+ // Inline flex item — sits *beside* the chat, doesn't overlay
+ // it. shrink-0 keeps us at effectiveWidth; the chat content
+ // (flex-1 min-w-0) gives way. The JS clamp on effectiveWidth
+ // guarantees viewport - chat ≥ 360px so the chat is never
+ // crushed below readable width.
+ style={{ width: effectiveWidth, flexBasis: effectiveWidth }}
+ className="border-l border-border/50 bg-muted/30 flex flex-col overflow-hidden shrink-0 relative"
+ >
+ {/* Drag handle — 10px hot zone on the left edge with a thicker
visible grip in the vertical center. The 1px border
reads as the panel's edge; the 32px tall grip bar is the
discoverable affordance. */}
+ <div
+ onMouseDown={onDragStart}
+ className="absolute top-0 left-0 h-full w-2.5 cursor-ew-resize z-10 group/resize -translate-x-1/2"
+ title="Drag to resize"
+ >
+ <div className="absolute inset-y-0 left-1/2 -translate-x-1/2 w-px bg-border/60 group-hover/resize:bg-foreground/40 transition-colors" />
+ <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-10 w-1 rounded-full bg-border group-hover/resize:bg-foreground/60 group-hover/resize:w-1.5 transition-all" />
+ </div>
+
+ <div className="relative flex items-center gap-2 px-3 h-10 border-b border-border/50 bg-background/60 pl-4">
<div
- onMouseDown={onDragStart}
- className="absolute top-0 left-0 h-full w-2.5 cursor-ew-resize z-10 group/resize -translate-x-1/2"
- title="Drag to resize"
+ className="flex-1 min-w-0 text-muted-foreground"
+ title={currentUrl ?? headerTitle}
>
- <div className="absolute inset-y-0 left-1/2 -translate-x-1/2 w-px bg-border/60 group-hover/resize:bg-foreground/40 transition-colors" />
- <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-10 w-1 rounded-full bg-border group-hover/resize:bg-foreground/60 group-hover/resize:w-1.5 transition-all" />
- </div>
-
- <div className="flex items-center gap-2 px-3 h-10 border-b border-border/50 bg-background/60 pl-4">
- <div className="flex-1 min-w-0 text-xs text-muted-foreground truncate">
- {currentUrl ?? "about:blank"}
- </div>
- <button
- onClick={reload}
- title="Reload"
- className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground"
- >
- <RotateCw className="h-3.5 w-3.5" />
- </button>
- <button
- onClick={collapse}
- title="Hide panel"
- className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground"
- >
- <PanelRightClose className="h-3.5 w-3.5" />
- </button>
+ <div className="text-xs truncate">{headerTitle}</div>
+ {currentTitle && currentUrl && (
+ <div className="text-[10px] leading-3 truncate opacity-70">
+ {currentUrl}
+ </div>
+ )}
</div>
- {/* Placeholder — the native webview is positioned over this rect. */}
- <div
- ref={placeholderRef}
- className="flex-1 bg-background relative flex items-center justify-center text-xs text-muted-foreground"
+ <button
+ onClick={reload}
+ title="Reload"
+ className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground"
+ >
+ <RotateCw className="h-3.5 w-3.5" />
+ </button>
+ <button
+ onClick={collapse}
+ title="Hide panel"
+ className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground"
>
- {sessionAccessRequest ? (
- <div className="absolute inset-0 z-20 flex items-center justify-center bg-background p-4">
- <div className="w-full max-w-sm border border-border bg-card p-4 shadow-sm">
- <div className="mb-3 flex items-start gap-3">
- <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center border border-border bg-muted text-foreground">
- <KeyRound className="h-4 w-4" />
+ <PanelRightClose className="h-3.5 w-3.5" />
+ </button>
+ {loading && (
+ <div
+ className="pointer-events-none absolute inset-x-0 bottom-0 z-10 h-0.5 overflow-hidden bg-border/25"
+ role="progressbar"
+ aria-label="Page loading"
+ >
+ <div className="h-full w-1/3 min-w-20 bg-foreground/70 animate-owned-browser-load" />
+ </div>
+ )}
+ </div>
+ {/* Placeholder — native child webview is positioned over this rect only. */}
+ <div
+ ref={placeholderRef}
+ className="flex-1 bg-background relative"
+ aria-hidden={sessionAccessRequest ? true : undefined}
+ />
+ {sessionAccessRequest && (
+ <div className="absolute inset-0 z-40 flex items-center justify-center bg-background p-4">
+ <div className="w-full max-w-sm border border-border bg-card p-4 shadow-sm">
+ <div className="mb-3 flex items-start gap-3">
+ <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center border border-border bg-muted text-foreground">
+ <KeyRound className="h-4 w-4" />
+ </div>
+ <div className="min-w-0">
+ <div className="text-sm font-medium text-foreground">
+ Use your browser login?
</div>
- <div className="min-w-0">
- <div className="text-sm font-medium text-foreground">
- Use your browser login?
- </div>
- <div className="mt-1 break-all text-xs text-muted-foreground">
- {sessionAccessRequest.host}
- </div>
+ <div className="mt-1 break-all text-xs text-muted-foreground">
+ {sessionAccessRequest.host}
</div>
</div>
- <p className="text-xs leading-5 text-muted-foreground">
- ScreenPipe Browser can copy matching session cookies from
- your browser so the agent opens this site already signed
- in. It does not read saved passwords.
- </p>
- <p className="mt-2 text-xs leading-5 text-muted-foreground">
- If you allow it, macOS may ask for access to browser safe
- storage next.
- </p>
- <div className="mt-4 flex flex-col gap-2">
- <Button
- size="sm"
- disabled={sessionAccessAnswer !== null}
- onClick={() => answerSessionAccess(true)}
- className="w-full"
- >
- {sessionAccessAnswer === "allow"
- ? "Waiting for macOS"
- : "Use browser session"}
- </Button>
- <Button
- size="sm"
- variant="outline"
- disabled={sessionAccessAnswer !== null}
- onClick={() => answerSessionAccess(false)}
- className="w-full"
- >
- Continue logged out
- </Button>
- </div>
+ </div>
+ <p className="text-xs leading-5 text-muted-foreground">
+ ScreenPipe Browser can copy matching session cookies from
+ your browser so the agent opens this site already signed
+ in. It does not read saved passwords.
+ </p>
+ <p className="mt-2 text-xs leading-5 text-muted-foreground">
+ If you allow it, macOS may ask for access to browser safe
+ storage next.
+ </p>
+ <div className="mt-4 flex flex-col gap-2">
+ <Button
+ size="sm"
+ disabled={sessionAccessAnswer !== null}
+ onClick={() => answerSessionAccess(true)}
+ className="w-full"
+ >
+ {sessionAccessAnswer === "allow"
+ ? "Waiting for macOS"
+ : "Use browser session"}
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={sessionAccessAnswer !== null}
+ onClick={() => answerSessionAccess(false)}
+ className="w-full"
+ >
+ Continue logged out
+ </Button>
</div>
</div>
- ) : (
- "loading…"
- )}
</div>
- </motion.div>
- )}
- </AnimatePresence>
+ )}
+ </div>
+ )}
{/* Floating re-open affordance: shown when a URL is saved but the
panel is collapsed. Pinned to the viewport's top-right corner so
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs
index f4e63edf6..0519109d4 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs
@@ -4,27 +4,16 @@
//! Tauri-side glue for the owned-browser instance.
//!
-//! The owned browser is a **top-level** `WebviewWindow` (its own native
-//! window, decorations off, taskbar/dock skipped). The frontend
-//! `<BrowserSidebar />` measures a placeholder div in whichever app window
-//! it's mounted in, converts that rect into screen coordinates, and pushes
-//! it via `owned_browser_set_bounds`. The webview tracks the placeholder
-//! exactly as if it were embedded.
+//! The owned browser is primarily a native Tauri child `Webview` parented
+//! to whichever app window hosts `<BrowserSidebar />`. The frontend sends a
+//! coalesced placeholder rect in parent-local coordinates, and Rust uses
+//! `Window::add_child`/`Webview::set_bounds` so the OS follows parent
+//! window movement without a per-frame screen-coordinate loop.
//!
-//! Why a top-level window instead of a child `Webview`:
-//! - A child webview must be parented to one specific window. The chat
-//! UI can render in `home`, `main`, `main-window`, or `chat` depending
-//! on the user's session — and it can switch between them at runtime
-//! (overlay ↔ window mode, tray-only ↔ home). Whatever window we
-//! parented to could disappear or become inactive, leaving the browser
-//! either stuck in the wrong window or rendered off-screen because the
-//! sidebar's `getBoundingClientRect()` is in a *different* window's
-//! coordinate space than the parent.
-//! - A top-level window has no parent. The frontend computes screen
-//! coords from the active window's `innerPosition() + scaleFactor()`
-//! plus the placeholder's viewport rect, and the webview lands exactly
-//! where the placeholder is — regardless of which window is hosting
-//! the chat UI.
+//! Agent navigation requests can arrive before the sidebar has mounted. In
+//! that case we persist the pending URL, emit the sidebar-open event, and let
+//! the first `owned_browser_set_bounds` attach the native child and consume
+//! the pending navigation.
//!
//! [`OwnedWebviewHandle`] is implemented by translating the agent's `eval`
//! requests into `webview.eval()` + a `document.title` round-trip. We use
@@ -32,7 +21,7 @@
//! (e.g. wikipedia.org) do not have access to `window.__TAURI__` — the
//! Tauri IPC bridge is only injected on app-origin pages. Setting
//! `document.title` works on every origin and the title is observable from
-//! Rust via `WebviewWindow::title()`. We install the bridge via
+//! Rust via `on_document_title_changed`. We install the bridge via
//! `initialization_script`, which Tauri runs on every page load including
//! cross-origin navigations.
//!
@@ -43,19 +32,21 @@
use async_trait::async_trait;
use screenpipe_connect::connections::browser::{EvalResult, OwnedWebviewHandle};
-use std::collections::HashMap;
+use serde::Serialize;
+use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
-use std::sync::{Arc, OnceLock};
+use std::sync::{Arc, Mutex as StdMutex, OnceLock};
use std::time::{Duration, Instant};
+use tauri::webview::PageLoadEvent;
use tauri::{
- AppHandle, Emitter, LogicalPosition, LogicalSize, Manager, WebviewUrl, WebviewWindow,
- WebviewWindowBuilder,
+ AppHandle, Emitter, LogicalPosition, LogicalSize, Manager, Position, Rect, Size, Webview,
+ WebviewUrl, Window, Wry,
};
use tokio::sync::{oneshot, Mutex};
use tracing::{debug, info, warn};
use uuid::Uuid;
-/// WebviewWindow label — also used by the frontend Tauri commands.
+/// Embedded webview label — also used by the frontend Tauri commands.
pub const WEBVIEW_LABEL: &str = "owned-browser";
/// Event the Rust handle emits when the agent navigates the browser. The
@@ -63,10 +54,19 @@ pub const WEBVIEW_LABEL: &str = "owned-browser";
/// position the webview, and persist the URL to the active chat.
const NAVIGATE_EVENT: &str = "owned-browser:navigate";
+/// Native webview state updates for the sidebar header (omnibox model).
+///
+/// - [`NAVIGATE_EVENT`] + provisional `url` in state: top-level navigation we
+/// requested (agent/sidebar), shown while loading — like a browser omnibox
+/// during navigation.
+/// - Committed `url` in state: main-document URL from `webview.url()` only,
+/// never from `on_navigation` (subframes can fire that on macOS).
+const STATE_EVENT: &str = "owned-browser:state";
+
/// Emitted to the frontend exactly once when `spawn_install_when_ready`
-/// finishes building the top-level webview and attaching the handle to
-/// the registry. Lets `BrowserSidebar` retry a per-conversation
-/// `owned_browser_navigate` that lost the install race on cold start.
+/// attaches the handle to the registry. Lets `BrowserSidebar` retry a
+/// per-conversation `owned_browser_navigate` that lost the install race on
+/// cold start.
const READY_EVENT: &str = "owned-browser:ready";
/// Emitted when the owned browser is about to copy cookies from the
@@ -77,18 +77,18 @@ const SESSION_ACCESS_TIMEOUT: Duration = Duration::from_secs(60);
/// Marker prefix for `document.title`-based result delivery. The bridge JS
/// sets `document.title = "<MARKER>:<json>"`; the Rust eval polls
-/// `WebviewWindow::title()` until it sees this prefix and parses the
+/// the latest title observed from native title-change events until it sees
+/// this prefix and parses the
/// trailing JSON. Title is universally writable from JS on every origin,
/// which is why we use it instead of Tauri's IPC bridge (the latter is
/// only available on app-origin pages, and the agent navigates the
/// browser to arbitrary external sites).
const RESULT_TITLE_PREFIX: &str = "__SP_OWNED_BROWSER_RESULT__:";
-/// Bridge script — runs on every page load via
-/// `WebviewWindowBuilder::initialization_script`. Defines
-/// `window.__SP_RESULT__(payload)` which sets the page title to a
-/// recognisable marker. Idempotent — re-running on the same page is a
-/// no-op (the function is already there).
+/// Bridge script — runs on every page load via the child webview's
+/// initialization script. Defines `window.__SP_RESULT__(payload)` which sets
+/// the page title to a recognisable marker. Idempotent — re-running on the
+/// same page is a no-op (the function is already there).
const BRIDGE_INIT_SCRIPT: &str = r#"
(function () {
if (window.__SP_RESULT__) return;
@@ -106,12 +106,23 @@ const BRIDGE_INIT_SCRIPT: &str = r#"
})();
"#;
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct OwnedBrowserStateEvent {
+ url: Option<String>,
+ title: Option<String>,
+ loading: Option<bool>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
enum BrowserSessionDecision {
UseBrowserSession,
ContinueLoggedOut,
}
+const SESSION_ACCESS_STORE_KEY: &str = "owned_browser_session_access";
+
#[derive(serde::Serialize, Clone)]
struct BrowserSessionAccessRequestPayload {
request_id: String,
@@ -124,6 +135,8 @@ static SESSION_ACCESS_PENDING: OnceLock<
> = OnceLock::new();
static SESSION_ACCESS_DECISIONS: OnceLock<Mutex<HashMap<String, BrowserSessionDecision>>> =
OnceLock::new();
+static SESSION_ACCESS_IN_FLIGHT: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
+static SESSION_ACCESS_HYDRATED: OnceLock<()> = OnceLock::new();
fn pending_session_access(
) -> &'static Mutex<HashMap<String, oneshot::Sender<BrowserSessionDecision>>> {
@@ -134,11 +147,53 @@ fn remembered_session_access() -> &'static Mutex<HashMap<String, BrowserSessionD
SESSION_ACCESS_DECISIONS.get_or_init(|| Mutex::new(HashMap::new()))
}
-async fn remember_session_access_decision(host: &str, decision: BrowserSessionDecision) {
+fn session_access_in_flight() -> &'static Mutex<HashSet<String>> {
+ SESSION_ACCESS_IN_FLIGHT.get_or_init(|| Mutex::new(HashSet::new()))
+}
+
+/// Normalize host keys so `www.example.com` and `example.com` share one decision.
+fn session_host_key(host: &str) -> String {
+ let lower = host.to_ascii_lowercase();
+ lower
+ .strip_prefix("www.")
+ .map(|rest| rest.to_string())
+ .unwrap_or(lower)
+}
+
+async fn hydrate_remembered_session_access(app: &AppHandle) {
+ if SESSION_ACCESS_HYDRATED.get().is_some() {
+ return;
+ }
+ if let Ok(store) = crate::store::get_store(app, None) {
+ if let Some(raw) = store.get(SESSION_ACCESS_STORE_KEY) {
+ if let Ok(map) =
+ serde_json::from_value::<HashMap<String, BrowserSessionDecision>>(raw)
+ {
+ let mut remembered = remembered_session_access().lock().await;
+ for (host, decision) in map {
+ remembered.insert(session_host_key(&host), decision);
+ }
+ }
+ }
+ }
+ let _ = SESSION_ACCESS_HYDRATED.set(());
+}
+
+async fn remember_session_access_decision(
+ app: &AppHandle,
+ host: &str,
+ decision: BrowserSessionDecision,
+) {
+ let host_key = session_host_key(host);
remembered_session_access()
.lock()
.await
- .insert(host.to_ascii_lowercase(), decision);
+ .insert(host_key.clone(), decision);
+ if let Ok(store) = crate::store::get_store(app, None) {
+ let snapshot = remembered_session_access().lock().await.clone();
+ store.set(SESSION_ACCESS_STORE_KEY, serde_json::json!(snapshot));
+ let _ = store.save();
+ }
}
#[tauri::command]
@@ -160,12 +215,161 @@ pub async fn owned_browser_resolve_session_access(
.map_err(|_| "session access request was already closed".to_string())
}
+// ---------------------------------------------------------------------------
+// Native webview state
+// ---------------------------------------------------------------------------
+
+#[derive(Default)]
+struct OwnedBrowserInner {
+ child: Option<Webview<Wry>>,
+ child_parent: Option<String>,
+ pending_url: Option<url::Url>,
+ visible: bool,
+}
+
+struct OwnedBrowserState {
+ inner: Mutex<OwnedBrowserInner>,
+ last_title: StdMutex<String>,
+}
+
+impl OwnedBrowserState {
+ fn new() -> Self {
+ Self {
+ inner: Mutex::new(OwnedBrowserInner::default()),
+ last_title: StdMutex::new(String::new()),
+ }
+ }
+
+ fn record_title(&self, title: String) {
+ if let Ok(mut last_title) = self.last_title.lock() {
+ *last_title = title;
+ }
+ }
+
+ fn latest_title(&self) -> String {
+ self.last_title
+ .lock()
+ .map(|title| title.clone())
+ .unwrap_or_default()
+ }
+
+ async fn active(&self) -> Option<Webview<Wry>> {
+ let inner = self.inner.lock().await;
+ inner.child.as_ref().cloned()
+ }
+
+ async fn is_visible(&self) -> bool {
+ self.inner.lock().await.visible
+ }
+
+ async fn set_visible(&self, visible: bool) {
+ self.inner.lock().await.visible = visible;
+ }
+
+ async fn store_pending_url(&self, url: url::Url) {
+ self.inner.lock().await.pending_url = Some(url);
+ }
+
+ async fn clear_pending_url(&self) {
+ self.inner.lock().await.pending_url = None;
+ }
+}
+
+fn browser_state() -> Arc<OwnedBrowserState> {
+ static STATE: OnceLock<Arc<OwnedBrowserState>> = OnceLock::new();
+ STATE
+ .get_or_init(|| Arc::new(OwnedBrowserState::new()))
+ .clone()
+}
+
+fn emit_state_event(
+ app: &AppHandle,
+ url: Option<String>,
+ title: Option<String>,
+ loading: Option<bool>,
+) {
+ let payload = OwnedBrowserStateEvent {
+ url,
+ title,
+ loading,
+ };
+ if let Err(e) = app.emit(STATE_EVENT, payload) {
+ debug!("owned-browser: failed to emit state event: {e}");
+ }
+}
+
+/// Main-frame document URL (omnibox / address bar). Same as `WKWebView.URL` /
+/// WebView2 `Source` — not subframe navigation targets.
+fn webview_url(webview: &Webview<Wry>) -> Option<String> {
+ webview.url().ok().map(|url| url.to_string())
+}
+
+fn child_webview_builder(
+ app: &AppHandle,
+ label: &str,
+ url: WebviewUrl,
+) -> tauri::webview::WebviewBuilder<Wry> {
+ let app_for_title = app.clone();
+ let app_for_nav = app.clone();
+ let app_for_page_load = app.clone();
+ let mut builder = tauri::webview::WebviewBuilder::new(label.to_string(), url)
+ .initialization_script(BRIDGE_INIT_SCRIPT)
+ .on_navigation(move |_url| {
+ // Browsers do not put subframe navigations in the omnibox. Wry's
+ // `on_navigation` URL can be an iframe target on macOS (wry#1593),
+ // so never copy it into the sidebar — only reflect load activity.
+ emit_state_event(&app_for_nav, None, None, Some(true));
+ true
+ })
+ .on_page_load(move |webview, payload| {
+ let loading = matches!(payload.event(), PageLoadEvent::Started);
+ if loading {
+ emit_state_event(&app_for_page_load, None, None, Some(true));
+ return;
+ }
+ // Committed URL: native main-document URL, not `payload.url()` from
+ // the navigation that finished (may be a subframe on some sites).
+ let committed_url = webview_url(&webview);
+ emit_state_event(&app_for_page_load, committed_url, None, Some(false));
+ })
+ .on_document_title_changed(move |webview, title| {
+ let state = browser_state();
+ state.record_title(title.clone());
+ if title.starts_with(RESULT_TITLE_PREFIX) {
+ return;
+ }
+ let committed_url = webview_url(&webview);
+ emit_state_event(&app_for_title, committed_url, Some(title), None);
+ });
+
+ #[cfg(target_os = "macos")]
+ {
+ // Some sites gate the default WKWebView UA even though the underlying
+ // engine is Safari.
+ builder = builder.user_agent(
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_5) \
+ AppleWebKit/605.1.15 (KHTML, like Gecko) \
+ Version/17.5 Safari/605.1.15",
+ );
+ }
+
+ builder
+}
+
+fn logical_rect(x: f64, y: f64, width: f64, height: f64) -> Rect {
+ Rect {
+ position: Position::Logical(LogicalPosition::new(x, y)),
+ size: Size::Logical(LogicalSize::new(width, height)),
+ }
+}
+
// ---------------------------------------------------------------------------
// Handle implementation
// ---------------------------------------------------------------------------
struct TauriOwnedHandle {
app: AppHandle,
+ state: Arc<OwnedBrowserState>,
/// Serialise concurrent eval calls. The result transport
/// (`document.title`) is a single global slot, so we can only
/// reliably observe one outstanding eval at a time. Agents very rarely
@@ -184,19 +388,39 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
// Hold the mutex for the entire eval — see eval_lock comment.
let _guard = self.eval_lock.lock().await;
- let webview_window = self
- .app
- .get_webview_window(WEBVIEW_LABEL)
- .ok_or_else(|| "owned-browser webview window not found".to_string())?;
+ let target_url = if let Some(target) = url {
+ Some(
+ target
+ .parse::<url::Url>()
+ .map_err(|e: url::ParseError| format!("invalid url: {e}"))?,
+ )
+ } else {
+ None
+ };
+
+ if let Some(parsed) = &target_url {
+ prepare_navigation(&self.app, &self.state, parsed).await;
+ }
+
+ let active = match self.state.active().await {
+ Some(child) => child,
+ None if target_url.is_some() => {
+ wait_for_active_child(&self.state, timeout.min(Duration::from_secs(10)))
+ .await
+ .ok_or_else(|| "owned-browser child webview not attached".to_string())?
+ }
+ None => return Err("owned-browser child webview not attached".to_string()),
+ };
// A hidden WebView2 window can accept `eval()` without actually
// executing the script. Make sure the native webview is live before
// code-only evals. URL navigations defer showing until after the
// optional session-access prompt, so the sidebar can explain the
// request before any native webview covers it.
- let was_visible = webview_window.is_visible().unwrap_or(false);
- if !was_visible && url.is_none() {
- let _ = webview_window.show();
+ let was_visible = self.state.is_visible().await;
+ if !was_visible && target_url.is_none() {
+ let _ = active.show();
+ self.state.set_visible(true).await;
tokio::time::sleep(Duration::from_millis(100)).await;
}
@@ -205,25 +429,23 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
// the old eval-based navigation could no-op while the window was
// hidden/offscreen, leaving the request waiting forever for a title
// marker that would never be written.
- if let Some(target) = url {
- let parsed: url::Url = target
- .parse()
- .map_err(|e: url::ParseError| format!("invalid url: {e}"))?;
+ if let Some(parsed) = target_url {
inject_cookies_for_url(&self.app, &parsed).await;
- if !webview_window.is_visible().unwrap_or(false) {
- let _ = webview_window.show();
+ if !was_visible {
+ let _ = active.show();
+ self.state.set_visible(true).await;
tokio::time::sleep(Duration::from_millis(100)).await;
}
- let _ = self.app.emit(NAVIGATE_EVENT, parsed.as_str());
- webview_window
+ active
.navigate(parsed)
.map_err(|e| format!("webview.navigate failed: {e}"))?;
+ self.state.clear_pending_url().await;
tokio::time::sleep(Duration::from_millis(1_000)).await;
}
// Snapshot the current title so we can restore it after we read
// our marker. Best-effort — we don't fail the eval if this fails.
- let original_title = webview_window.title().unwrap_or_default();
+ let original_title = self.state.latest_title();
let id = Uuid::new_v4().to_string();
let id_lit = serde_json::to_string(&id).unwrap();
@@ -258,7 +480,7 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
id = id_lit
);
- webview_window
+ active
.eval(wrapped)
.map_err(|e| format!("webview.eval failed: {e}"))?;
@@ -269,18 +491,18 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
let result_json = loop {
if start.elapsed() >= timeout {
if !was_visible && url.is_none() {
- let _ = webview_window.hide();
+ let _ = active.hide();
+ self.state.set_visible(false).await;
}
return Err(format!(
"owned-browser eval timed out after {}s (last title: {:?})",
timeout.as_secs(),
- webview_window.title().unwrap_or_default()
+ self.state.latest_title()
));
}
- if let Ok(title) = webview_window.title() {
- if let Some(rest) = title.strip_prefix(RESULT_TITLE_PREFIX) {
- break rest.to_string();
- }
+ let title = self.state.latest_title();
+ if let Some(rest) = title.strip_prefix(RESULT_TITLE_PREFIX) {
+ break rest.to_string();
}
tokio::time::sleep(Duration::from_millis(50)).await;
};
@@ -288,9 +510,10 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
// Restore the page's prior title so user-facing chrome (history,
// tab labels in any embedding UI) doesn't keep our marker.
let restore_lit = serde_json::to_string(&original_title).unwrap_or_else(|_| "\"\"".into());
- let _ = webview_window.eval(format!("document.title = {restore_lit};"));
+ let _ = active.eval(format!("document.title = {restore_lit};"));
if !was_visible && url.is_none() {
- let _ = webview_window.hide();
+ let _ = active.hide();
+ self.state.set_visible(false).await;
}
// Parse the payload our wrapper emitted. We expect the same
@@ -332,11 +555,6 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
/// own titles. The frontend sidebar listens for `NAVIGATE_EVENT` and
/// reveals/positions the webview itself.
async fn navigate(&self, url: &str) -> Result<(), String> {
- let webview_window = self
- .app
- .get_webview_window(WEBVIEW_LABEL)
- .ok_or_else(|| "owned-browser webview window not found".to_string())?;
-
let parsed: url::Url = url
.parse()
.map_err(|e: url::ParseError| format!("invalid url: {e}"))?;
@@ -349,21 +567,22 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
// hook the agent always lands on the logged-out version of the
// site even though the Tauri-command-driven sidebar restore
// path was injecting correctly.
+ prepare_navigation(&self.app, &self.state, &parsed).await;
inject_cookies_for_url(&self.app, &parsed).await;
- // Make the webview live before navigating — a hidden WebView2
- // window can silently drop the navigate call. We do NOT hold the
- // eval_lock here; navigate is independent of in-flight evals so
- // a long-running snapshot can't queue behind it.
- if !webview_window.is_visible().unwrap_or(false) {
- let _ = webview_window.show();
+ if let Some(active) = self.state.active().await {
+ if !self.state.is_visible().await {
+ let _ = active.show();
+ self.state.set_visible(true).await;
+ }
+ active
+ .navigate(parsed)
+ .map_err(|e| format!("webview.navigate failed: {e}"))?;
+ self.state.clear_pending_url().await;
+ } else {
+ debug!("owned-browser navigate queued until sidebar attaches child webview");
}
- let _ = self.app.emit(NAVIGATE_EVENT, parsed.as_str());
- webview_window
- .navigate(parsed)
- .map_err(|e| format!("webview.navigate failed: {e}"))?;
-
// Brief wait so the navigation has time to *commit* before we
// return — `webview.navigate()` only schedules the load. If we
// return immediately and the agent calls `/snapshot` right after,
@@ -382,22 +601,20 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
}
// ---------------------------------------------------------------------------
-// Install — build the top-level webview window, return ready-to-attach handle
+// Install — return ready-to-attach handle
// ---------------------------------------------------------------------------
-/// Spawn the owned-browser install on a background task. Top-level
-/// windows don't need a parent so this is mostly just retry-on-error
-/// resilience for app cold-start races.
+/// Spawn the owned-browser handle install on a background task. The native
+/// child webview itself is attached lazily by `owned_browser_set_bounds`,
+/// because it needs the currently active chat window as its parent.
pub fn spawn_install_when_ready(
app: AppHandle,
screenpipe_dir: PathBuf,
owned_browser: std::sync::Arc<screenpipe_connect::connections::browser::OwnedBrowser>,
) {
tauri::async_runtime::spawn(async move {
- // Top-level windows can be created any time after the app's
- // Tauri runtime is ready. A short retry loop covers the cold-
- // start case where install() is called before the runtime is
- // fully up.
+ // A short retry loop covers the cold-start case where install() is
+ // called before the Tauri runtime is fully up.
const MAX_ATTEMPTS: u32 = 60;
const BACKOFF: Duration = Duration::from_millis(500);
let mut last_err = String::new();
@@ -429,107 +646,127 @@ pub fn spawn_install_when_ready(
});
}
-/// Create the owned-browser top-level window if it doesn't exist yet, and
-/// return a ready-to-attach handle. Idempotent.
-///
-/// The window starts at 1×1 off-screen and hidden; the frontend sidebar
-/// calls `owned_browser_set_bounds` to position and show it once a chat
-/// needs it.
+/// Return a ready-to-attach handle. Idempotent. The actual webview is created
+/// later when the frontend supplies a parent window and bounds.
pub async fn install(
app: &AppHandle,
screenpipe_dir: PathBuf,
) -> Result<Arc<dyn OwnedWebviewHandle>, String> {
let _ = screenpipe_dir;
- if app.get_webview_window(WEBVIEW_LABEL).is_none() {
- let blank: url::Url = "about:blank"
- .parse()
- .map_err(|e: url::ParseError| e.to_string())?;
-
- #[allow(unused_mut)]
- let mut builder =
- WebviewWindowBuilder::new(app, WEBVIEW_LABEL, WebviewUrl::External(blank))
- .title("owned-browser")
- .decorations(false)
- .resizable(false)
- .skip_taskbar(true)
- // NOT `always_on_top(true)` — that maps to NSFloatingWindowLevel
- // on macOS, which sits above every other app's normal-level
- // windows globally. Result: when screenpipe loses focus to
- // MT5 / Claude.ai / Discord / etc., the browser stayed on top
- // of whatever the user just switched to. The placeholder div
- // is in its own flex column in the chat layout, not stacked
- // under the chat content, so normal level is enough — host
- // app focus/hide/minimize now propagate to the browser via
- // the OS's standard cross-app window ordering.
- .shadow(false)
- .initialization_script(BRIDGE_INIT_SCRIPT);
-
- #[cfg(target_os = "macos")]
- {
- // Spoof a real Safari UA so anti-WebView gates (notably x.com,
- // which hangs forever on the splash with the default WKWebView UA)
- // serve us the normal site. Do not apply this to WebView2:
- // YouTube and other Google properties expect the Chromium/Edge
- // feature surface that WebView2 actually provides.
- builder = builder.user_agent(
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_5) \
- AppleWebKit/605.1.15 (KHTML, like Gecko) \
- Version/17.5 Safari/605.1.15",
- );
- }
-
- #[cfg(target_os = "windows")]
- {
- // WebView2 can fail controller creation with 0x8007139F when the
- // native window is born hidden at a 1x1 client size during app
- // startup. Create it as a tiny visible off-screen window and leave
- // it that way until the sidebar positions or hides it. Hiding
- // immediately after build can race WebView2's async controller
- // creation and leave the owned browser unable to open.
- builder = builder
- .visible(true)
- .focused(false)
- .inner_size(64.0, 64.0)
- .position(-32000.0, -32000.0);
- }
-
- #[cfg(not(target_os = "windows"))]
- {
- builder = builder
- .visible(false)
- .inner_size(1.0, 1.0)
- .position(0.0, 0.0);
- }
-
- builder
- .build()
- .map(crate::window::finalize_webview_window)
- .map_err(|e| format!("WebviewWindowBuilder::build failed: {e}"))?;
-
- info!("owned-browser: top-level webview window created");
- }
+ let state = browser_state();
let handle = Arc::new(TauriOwnedHandle {
app: app.clone(),
+ state,
eval_lock: Mutex::new(()),
});
Ok(handle as Arc<dyn OwnedWebviewHandle>)
}
+async fn ensure_child_bounds(
+ app: &AppHandle,
+ parent: &str,
+ x: f64,
+ y: f64,
+ width: f64,
+ height: f64,
+) -> Result<Webview<Wry>, String> {
+ let state = browser_state();
+ let parent_window: Option<Window<Wry>> = app.get_window(parent);
+
+ let Some(parent_window) = parent_window else {
+ return Err(format!("parent window {parent:?} not found"));
+ };
+
+ let mut pending_url = None;
+ let child = {
+ let mut inner = state.inner.lock().await;
+
+ if let Some(child) = inner.child.clone() {
+ if inner.child_parent.as_deref() != Some(parent) {
+ child
+ .reparent(&parent_window)
+ .map_err(|e| format!("owned-browser child reparent failed: {e}"))?;
+ inner.child_parent = Some(parent.to_string());
+ }
+ pending_url = inner.pending_url.take();
+ child
+ } else {
+ let blank: url::Url = "about:blank"
+ .parse()
+ .map_err(|e: url::ParseError| e.to_string())?;
+ let builder = child_webview_builder(app, WEBVIEW_LABEL, WebviewUrl::External(blank));
+ let child = parent_window
+ .add_child(
+ builder,
+ LogicalPosition::new(x, y),
+ LogicalSize::new(width, height),
+ )
+ .map_err(|e| format!("owned-browser child webview attach failed: {e}"))?;
+ pending_url = inner.pending_url.take();
+ inner.child = Some(child.clone());
+ inner.child_parent = Some(parent.to_string());
+ info!(parent, "owned-browser: child webview attached");
+ child
+ }
+ };
+
+ child
+ .set_bounds(logical_rect(x, y, width, height))
+ .map_err(|e| format!("owned-browser child set_bounds failed: {e}"))?;
+ child
+ .show()
+ .map_err(|e| format!("owned-browser child show failed: {e}"))?;
+ state.set_visible(true).await;
+
+ if let Some(url) = pending_url {
+ inject_cookies_for_url(app, &url).await;
+ let _ = child.navigate(url);
+ }
+
+ Ok(child)
+}
+
+async fn prepare_navigation(app: &AppHandle, state: &OwnedBrowserState, parsed: &url::Url) {
+ // Provisional omnibox URL while a top-level navigation is in flight
+ // (agent or sidebar initiated). Committed URL comes from `webview.url()`
+ // on main-document load finish / title change.
+ emit_state_event(
+ app,
+ Some(parsed.as_str().to_string()),
+ None,
+ Some(true),
+ );
+ let _ = app.emit(NAVIGATE_EVENT, parsed.as_str());
+ state.store_pending_url(parsed.clone()).await;
+}
+
+async fn wait_for_active_child(
+ state: &OwnedBrowserState,
+ timeout: Duration,
+) -> Option<Webview<Wry>> {
+ let start = Instant::now();
+ loop {
+ if let Some(child) = state.active().await {
+ return Some(child);
+ }
+ if start.elapsed() >= timeout {
+ return None;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+}
+
// ---------------------------------------------------------------------------
// Tauri commands — sidebar controls (frontend → child webview)
// ---------------------------------------------------------------------------
-/// Position and size the embedded webview window. The frontend sends
-/// viewport-relative coords (the placeholder's `getBoundingClientRect()`)
-/// plus the label of the parent window that hosts the placeholder. Rust
-/// resolves the parent's screen position and adds the rect offsets — this
-/// keeps the conversion logic on one side (Rust's `inner_position()` is
-/// the authoritative source) and avoids JS↔Rust unit-mismatch bugs that
-/// caused the webview to land off-screen on monitors where JS-side math
-/// disagreed with the OS. Call with width/height = 0 to hide.
+/// Position and size the embedded child webview. The frontend sends
+/// viewport-relative coords from the same window that hosts the child, so
+/// they can be applied as parent-local bounds. Call with width/height = 0
+/// to hide.
#[tauri::command]
pub async fn owned_browser_set_bounds(
app: AppHandle,
@@ -539,137 +776,28 @@ pub async fn owned_browser_set_bounds(
width: f64,
height: f64,
) -> Result<(), String> {
- let webview_window = app
- .get_webview_window(WEBVIEW_LABEL)
- .ok_or_else(|| "owned-browser not initialized".to_string())?;
+ let state = browser_state();
if width <= 0.0 || height <= 0.0 {
- webview_window.hide().map_err(|e| e.to_string())?;
+ if let Some(active) = state.active().await {
+ active.hide().map_err(|e| e.to_string())?;
+ }
+ state.set_visible(false).await;
return Ok(());
}
- let parent_w = app
- .get_webview_window(&parent)
- .ok_or_else(|| format!("parent window {parent:?} not found"))?;
- let scale = parent_w.scale_factor().map_err(|e| e.to_string())?;
- let inner_pos_phys = parent_w.inner_position().map_err(|e| e.to_string())?;
- let inner_pos = inner_pos_phys.to_logical::<f64>(scale);
-
- let screen_x = inner_pos.x + x;
- let screen_y = inner_pos.y + y;
-
- tracing::debug!(
- "owned-browser set_bounds: parent={parent} inner=({:.0},{:.0}) rect=({x:.0},{y:.0},{width:.0}x{height:.0}) -> screen=({screen_x:.0},{screen_y:.0})",
- inner_pos.x,
- inner_pos.y
- );
-
- // Bind owned-browser as a child of the host window. macOS then ties
- // the two together: parent miniaturize / orderOut / app-deactivate
- // propagate to the child automatically, and `addChildWindow:ordered:`
- // ensures the child stays *above* the parent in z-order without
- // floating-globally above other apps' windows. Replaces the old
- // `always_on_top: true` approach which caused the browser to sit on
- // top of MT5 / Claude.ai / etc. when the user switched apps.
- // Switching parents auto-removes from the old one (a window can have
- // at most one parent in Cocoa). Cache the bound label so we only
- // call addChildWindow on actual parent change — set_bounds runs on
- // every frame during slide-in / drag-resize, and re-binding 60×/s
- // wakes WindowServer + replayd into a feedback loop.
- #[cfg(target_os = "macos")]
- {
- let mut current = bound_parent().lock().await;
- if current.as_deref() != Some(parent.as_str()) {
- bind_owned_browser_to_parent(&app, &parent).await?;
- *current = Some(parent.clone());
+ // Frontend session-access card is HTML; keep the native layer hidden until
+ // the user resolves the prompt (pushBounds races would otherwise re-show).
+ if !pending_session_access().lock().await.is_empty() {
+ if let Some(active) = state.active().await {
+ let _ = active.hide();
}
+ state.set_visible(false).await;
+ return Ok(());
}
- webview_window
- .set_position(LogicalPosition::new(screen_x, screen_y))
- .map_err(|e| e.to_string())?;
- webview_window
- .set_size(LogicalSize::new(width, height))
- .map_err(|e| e.to_string())?;
- webview_window.show().map_err(|e| e.to_string())
-}
-
-/// macOS only: parent label currently bound via `addChildWindow:`. The
-/// owned-browser is a singleton, so a single global slot is sufficient.
-/// Read/written from `owned_browser_set_bounds` to skip redundant
-/// bind calls — `addChildWindow:` is documented idempotent but each
-/// call still walks NSWindow's child list and fires
-/// runningboard/WindowServer notifications, which under per-frame
-/// invocation drives the SCK audio-filter daemon (replayd) into a
-/// restart loop.
-#[cfg(target_os = "macos")]
-fn bound_parent() -> &'static Mutex<Option<String>> {
- static BOUND_PARENT: OnceLock<Mutex<Option<String>>> = OnceLock::new();
- BOUND_PARENT.get_or_init(|| Mutex::new(None))
-}
-
-/// macOS only: make the owned-browser a child of the named host window
-/// via `[NSWindow addChildWindow:ordered:NSWindowAbove]`. Once bound,
-/// the OS propagates parent visibility (orderOut / miniaturize / app
-/// deactivate) to the child for free, and the child stays above its
-/// parent in z-order — but only within the parent's app, not floating
-/// globally over other apps. Cocoa enforces single-parent semantics, so
-/// re-binding to a different parent automatically removes the old one.
-#[cfg(target_os = "macos")]
-async fn bind_owned_browser_to_parent(app: &AppHandle, parent_label: &str) -> Result<(), String> {
- use objc::runtime::Object;
- use objc::{msg_send, sel, sel_impl};
-
- let app_for_main = app.clone();
- let parent_label = parent_label.to_string();
- let (tx, rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
-
- app.run_on_main_thread(move || {
- let result: Result<(), String> = (|| {
- // Resolve parent NSWindow* — host can be either an NSPanel
- // (overlay/window timeline + chat) or a regular WebviewWindow
- // (settings / home in window mode), so try both lookups.
- let parent_ptr: *mut Object = if let Ok(panel) =
- <tauri::AppHandle as tauri_nspanel::ManagerExt<_>>::get_webview_panel(
- &app_for_main,
- &parent_label,
- ) {
- &*panel as *const _ as *mut Object
- } else if let Some(win) = app_for_main.get_webview_window(&parent_label) {
- let raw = win
- .ns_window()
- .map_err(|e| format!("ns_window for {parent_label}: {e}"))?;
- raw as *mut Object
- } else {
- return Err(format!("parent window {parent_label:?} not found"));
- };
-
- let child_win = app_for_main
- .get_webview_window(WEBVIEW_LABEL)
- .ok_or_else(|| "owned-browser not initialized".to_string())?;
- let child_ptr: *mut Object = child_win
- .ns_window()
- .map_err(|e| format!("ns_window for owned-browser: {e}"))?
- as *mut Object;
-
- if parent_ptr.is_null() || child_ptr.is_null() {
- return Err("null NSWindow pointer".to_string());
- }
- if std::ptr::eq(parent_ptr, child_ptr) {
- return Err("refusing to add window as child of itself".to_string());
- }
-
- // NSWindowOrderingMode::NSWindowAbove == 1
- unsafe {
- let _: () = msg_send![parent_ptr, addChildWindow: child_ptr ordered: 1i64];
- }
- Ok(())
- })();
- let _ = tx.send(result);
- })
- .map_err(|e| format!("run_on_main_thread: {e}"))?;
- rx.await
- .map_err(|_| "main thread channel closed".to_string())?
+ ensure_child_bounds(&app, &parent, x, y, width, height).await?;
+ Ok(())
}
/// Navigate the embedded webview to `url`. Used by the agent (via
@@ -677,27 +805,35 @@ async fn bind_owned_browser_to_parent(app: &AppHandle, parent_label: &str) -> Re
/// when restoring per-chat state.
#[tauri::command]
pub async fn owned_browser_navigate(app: AppHandle, url: String) -> Result<(), String> {
- let webview_window = app
- .get_webview_window(WEBVIEW_LABEL)
- .ok_or_else(|| "owned-browser not initialized".to_string())?;
+ let state = browser_state();
let parsed: url::Url = url
.parse()
.map_err(|e: url::ParseError| format!("invalid url: {e}"))?;
- // Inherit the user's logged-in sessions before navigating.
+ prepare_navigation(&app, &state, &parsed).await;
inject_cookies_for_url(&app, &parsed).await;
- let _ = app.emit(NAVIGATE_EVENT, parsed.as_str());
- webview_window.navigate(parsed).map_err(|e| e.to_string())
+ if let Some(active) = state.active().await {
+ if !state.is_visible().await {
+ active.show().map_err(|e| e.to_string())?;
+ state.set_visible(true).await;
+ }
+ active.navigate(parsed).map_err(|e| e.to_string())?;
+ state.clear_pending_url().await;
+ }
+ Ok(())
}
/// Hide the embedded webview without destroying it. Equivalent to calling
/// `set_bounds` with zero dimensions, but more explicit at the call site.
#[tauri::command]
pub async fn owned_browser_hide(app: AppHandle) -> Result<(), String> {
- let webview_window = app
- .get_webview_window(WEBVIEW_LABEL)
- .ok_or_else(|| "owned-browser not initialized".to_string())?;
- webview_window.hide().map_err(|e| e.to_string())
+ let _ = app;
+ let state = browser_state();
+ if let Some(active) = state.active().await {
+ active.hide().map_err(|e| e.to_string())?;
+ }
+ state.set_visible(false).await;
+ Ok(())
}
/// Cross-platform cookie pre-navigate hook. Resolves the URL's host,
@@ -731,7 +867,21 @@ async fn inject_cookies_for_url(app: &AppHandle, url: &url::Url) {
info!(host, "owned-browser cookies: pre-navigate inject starting");
let cookies = crate::owned_browser_cookies::cookies_for_host(host).await;
if cookies.is_empty() {
- remember_session_access_decision(host, BrowserSessionDecision::ContinueLoggedOut).await;
+ let host_key = session_host_key(host);
+ let prior = remembered_session_access()
+ .lock()
+ .await
+ .get(&host_key)
+ .copied();
+ // Never downgrade an explicit "allow" when Keychain/sqlite returns nothing.
+ if prior != Some(BrowserSessionDecision::UseBrowserSession) {
+ remember_session_access_decision(
+ app,
+ host,
+ BrowserSessionDecision::ContinueLoggedOut,
+ )
+ .await;
+ }
info!(
host,
"owned-browser cookies: 0 cookies available — navigating without inject \
@@ -763,10 +913,12 @@ async fn browser_session_decision_for_url(
app: &AppHandle,
url: &url::Url,
) -> BrowserSessionDecision {
+ hydrate_remembered_session_access(app).await;
+
let Some(host) = url.host_str() else {
return BrowserSessionDecision::ContinueLoggedOut;
};
- let host_key = host.to_ascii_lowercase();
+ let host_key = session_host_key(host);
if !crate::owned_browser_cookies::has_cookies_for_host(&host_key).await {
return BrowserSessionDecision::ContinueLoggedOut;
@@ -781,8 +933,39 @@ async fn browser_session_decision_for_url(
return decision;
}
- if let Some(webview_window) = app.get_webview_window(WEBVIEW_LABEL) {
- let _ = webview_window.hide();
+ // Agent may navigate the same host repeatedly while the first prompt is open.
+ let wait_deadline = Instant::now() + SESSION_ACCESS_TIMEOUT;
+ loop {
+ if let Some(decision) = remembered_session_access()
+ .lock()
+ .await
+ .get(&host_key)
+ .copied()
+ {
+ return decision;
+ }
+ let in_flight = session_access_in_flight().lock().await;
+ if !in_flight.contains(&host_key) {
+ drop(in_flight);
+ break;
+ }
+ drop(in_flight);
+ if Instant::now() >= wait_deadline {
+ warn!(
+ host = host_key.as_str(),
+ "owned-browser session access: timed out waiting for in-flight prompt"
+ );
+ return BrowserSessionDecision::ContinueLoggedOut;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+
+ session_access_in_flight().lock().await.insert(host_key.clone());
+
+ let state = browser_state();
+ if let Some(active) = state.active().await {
+ let _ = active.hide();
+ state.set_visible(false).await;
}
let request_id = Uuid::new_v4().to_string();
@@ -800,6 +983,7 @@ async fn browser_session_decision_for_url(
if let Err(e) = app.emit(SESSION_ACCESS_REQUEST_EVENT, payload) {
pending_session_access().lock().await.remove(&request_id);
+ session_access_in_flight().lock().await.remove(&host_key);
warn!("owned-browser session access: failed to emit request: {e}");
return BrowserSessionDecision::ContinueLoggedOut;
}
@@ -817,7 +1001,8 @@ async fn browser_session_decision_for_url(
}
};
- remember_session_access_decision(&host_key, decision).await;
+ session_access_in_flight().lock().await.remove(&host_key);
+ remember_session_access_decision(app, &host_key, decision).await;
decision
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser_cookies.rs b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser_cookies.rs
index 40824d138..a12a97524 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser_cookies.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser_cookies.rs
@@ -414,7 +414,7 @@ fn read_cookies(source: &KeychainEntry, host: &str) -> Result<Vec<Cookie>, Strin
//
// The is_secure / is_httponly columns are 0/1 ints; same_site is
// signed (-1..=2). expires_utc is microseconds since 1601 — convert
- // to seconds-since-1970 in [`row_to_cookie`].
+ // to seconds-since-1970 in [`chromium_micros_to_unix_secs`].
let host_filters = host_match_clauses(host);
let where_clause = host_where_clause(&host_filters);
let sql = format!(
diff --git a/apps/screenpipe-app-tauri/tailwind.config.ts b/apps/screenpipe-app-tauri/tailwind.config.ts
index 960e084e1..d347788b3 100644
--- a/apps/screenpipe-app-tauri/tailwind.config.ts
+++ b/apps/screenpipe-app-tauri/tailwind.config.ts
@@ -188,12 +188,18 @@ module.exports = {
"background-position": "200%",
},
},
+ "owned-browser-load": {
+ "0%": { transform: "translateX(-100%)" },
+ "100%": { transform: "translateX(400%)" },
+ },
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
pulse: "pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",
rainbow: "rainbow var(--speed, 2s) infinite linear",
+ "owned-browser-load":
+ "owned-browser-load 1.1s ease-in-out infinite",
},
}
diff --git a/crates/screenpipe-connect/src/connections/browser/owned.rs b/crates/screenpipe-connect/src/connections/browser/owned.rs
index 939e729f5..1825988e1 100644
--- a/crates/screenpipe-connect/src/connections/browser/owned.rs
+++ b/crates/screenpipe-connect/src/connections/browser/owned.rs
@@ -42,9 +42,8 @@ pub trait OwnedWebviewHandle: Send + Sync {
/// Fire-and-forget navigation. Default impl falls back to `eval` so
/// existing transports keep working unchanged; the Tauri impl
- /// overrides it with `WebviewWindow::navigate(...)` so we don't pay
- /// the eval round-trip (which polls `document.title` and races the
- /// page's own title setters — see incident notes in the parent crate).
+ /// overrides it with the native webview `navigate(...)` call so we
+ /// don't pay the eval round-trip.
async fn navigate(&self, url: &str) -> Result<(), String> {
let escaped = serde_json::to_string(url).map_err(|e| format!("encode url: {e}"))?;
self.eval(
@@ -162,6 +161,10 @@ mod tests {
last_code: Mutex<Option<String>>,
}
+ struct NativeNavigateHandle {
+ last_url: Mutex<Option<String>>,
+ }
+
#[async_trait]
impl OwnedWebviewHandle for StubHandle {
async fn eval(
@@ -179,6 +182,27 @@ mod tests {
}
}
+ #[async_trait]
+ impl OwnedWebviewHandle for NativeNavigateHandle {
+ async fn eval(
+ &self,
+ _code: &str,
+ _url: Option<&str>,
+ _timeout: Duration,
+ ) -> Result<EvalResult, String> {
+ Ok(EvalResult {
+ ok: true,
+ result: None,
+ error: None,
+ })
+ }
+
+ async fn navigate(&self, url: &str) -> Result<(), String> {
+ *self.last_url.lock().await = Some(url.to_string());
+ Ok(())
+ }
+ }
+
#[tokio::test]
async fn unattached_owned_returns_not_connected() {
let owned = OwnedBrowser::default_instance();
@@ -234,4 +258,20 @@ mod tests {
Some(r#"location.href = "https://example.com""#.into())
);
}
+
+ #[tokio::test]
+ async fn attached_owned_navigate_uses_native_handle_override() {
+ let owned = OwnedBrowser::default_instance();
+ let handle = Arc::new(NativeNavigateHandle {
+ last_url: Mutex::new(None),
+ });
+ owned.attach(handle.clone()).await;
+
+ owned.navigate("https://example.com/native").await.unwrap();
+
+ assert_eq!(
+ handle.last_url.lock().await.clone(),
+ Some("https://example.com/native".into())
+ );
+ }
}