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(owned-browser): top-level WebviewWindow + cross-origin eval

Louis Beaumont0db2466d7ad3
diff --git a/apps/screenpipe-app-tauri/components/browser-sidebar.tsx b/apps/screenpipe-app-tauri/components/browser-sidebar.tsx
index 8816cc801..eef4aa390 100644
--- a/apps/screenpipe-app-tauri/components/browser-sidebar.tsx
+++ b/apps/screenpipe-app-tauri/components/browser-sidebar.tsx
@@ -23,6 +23,7 @@
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 { X, RotateCw } from "lucide-react";
import {
@@ -53,9 +54,16 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
[conversationId],
);
- // Push the current placeholder rect to Tauri so the child webview lines up.
- // Logical pixels (CSS pixels) — Tauri's LogicalPosition/LogicalSize match
- // getBoundingClientRect()'s units exactly.
+ // Push the current placeholder rect to Tauri so the top-level webview
+ // window lines up. The Rust side positions a *top-level* WebviewWindow,
+ // so the bounds must be in **screen coordinates** (origin = primary
+ // display top-left), not viewport-relative.
+ //
+ // Translation: screen = active-window-inner-position + placeholder
+ // viewport rect. `innerPosition()` returns physical pixels; divide by
+ // scaleFactor() to get logical CSS pixels (which is what
+ // `getBoundingClientRect()` returns and what Tauri's
+ // LogicalPosition/LogicalSize expects).
const pushBounds = useCallback(async () => {
const el = placeholderRef.current;
if (!el) return;
@@ -64,14 +72,23 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
await invoke("owned_browser_hide").catch(() => {});
return;
}
- await invoke("owned_browser_set_bounds", {
- x: r.left,
- y: r.top,
- width: r.width,
- height: r.height,
- }).catch((e) => {
+ try {
+ const w = getCurrentWindow();
+ const [innerPos, scale] = await Promise.all([
+ w.innerPosition(),
+ w.scaleFactor(),
+ ]);
+ const logicalInnerX = innerPos.x / scale;
+ const logicalInnerY = innerPos.y / scale;
+ await invoke("owned_browser_set_bounds", {
+ x: logicalInnerX + r.left,
+ y: logicalInnerY + r.top,
+ width: r.width,
+ height: r.height,
+ });
+ } catch (e) {
console.error("owned_browser_set_bounds failed", e);
- });
+ }
}, []);
// Close: hide the webview, clear chat state. The webview itself stays
@@ -134,8 +151,10 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
};
}, [conversationId]);
- // Track placeholder rect — covers panel slide-in, window resize, and
- // chat-history sidebar collapse/expand.
+ // Track placeholder rect — covers panel slide-in, window resize,
+ // window *move* (top-level webview windows live in screen coords so
+ // they don't follow parent moves automatically), and chat-history
+ // sidebar collapse/expand.
useEffect(() => {
if (!visible) return;
const el = placeholderRef.current;
@@ -145,9 +164,18 @@ export function BrowserSidebar({ conversationId }: BrowserSidebarProps) {
ro.observe(el);
const onResize = () => pushBounds();
window.addEventListener("resize", onResize);
+
+ // Window-moved + window-resized fire on the active Tauri window.
+ // Both translate to a re-push of bounds in screen coordinates.
+ const w = getCurrentWindow();
+ const unlistenMovedP = w.listen("tauri://move", () => pushBounds());
+ const unlistenResizedP = w.listen("tauri://resize", () => pushBounds());
+
return () => {
ro.disconnect();
window.removeEventListener("resize", onResize);
+ unlistenMovedP.then((fn) => fn()).catch(() => {});
+ unlistenResizedP.then((fn) => fn()).catch(() => {});
};
}, [visible, pushBounds]);
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index 0491d863c..a7c663243 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "2.4.113"
+version = "2.4.114"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
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 e215f588f..16d33692a 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/owned_browser.rs
@@ -4,97 +4,107 @@
//! Tauri-side glue for the owned-browser instance.
//!
-//! The owned browser is a child `Webview` attached to one of the app's
-//! existing windows. The parent is picked from `PARENT_WINDOW_CANDIDATES`
-//! at install time — main, main-window, or chat — whichever the user's
-//! current session has, with any other webview window as a final
-//! fallback. The frontend positions it (via `owned_browser_set_bounds`)
-//! in the parent's coordinate space; since the sidebar UI is rendered in
-//! the same window it's attached to, the bounds are always meaningful
-//! regardless of which parent was picked.
+//! 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.
+//!
+//! 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.
//!
//! [`OwnedWebviewHandle`] is implemented by translating the agent's `eval`
-//! requests into `webview.eval()` + a Tauri-event round-trip. The webview is
-//! created lazily on first install and persists for the app's lifetime; the
-//! sidebar UI hides it by collapsing its size to 0×0 when no chat is using
-//! it. Cookies/localStorage live in `~/.screenpipe/browsers/default`.
+//! requests into `webview.eval()` + a `document.title` round-trip. We use
+//! the title as a result transport because cross-origin pages
+//! (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
+//! `initialization_script`, which Tauri runs on every page load including
+//! cross-origin navigations.
+//!
+//! Cookies/localStorage live in `~/.screenpipe/browsers/default` on
+//! Windows (per-window data dir is supported via WebView2's
+//! `additional_browser_args`). On macOS/Linux the platform webviews share
+//! a single store with the main app webview — Tauri's public API doesn't
+//! expose per-window profiles for WKWebView/webkit2gtk yet.
use async_trait::async_trait;
use screenpipe_connect::connections::browser::{EvalResult, OwnedWebviewHandle};
-use serde::Deserialize;
-use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
-use std::time::Duration;
+use std::time::{Duration, Instant};
use tauri::{
- webview::WebviewBuilder, AppHandle, Emitter, Listener, LogicalPosition, LogicalSize, Manager,
- WebviewUrl, WebviewWindow,
+ AppHandle, Emitter, LogicalPosition, LogicalSize, Manager, WebviewUrl, WebviewWindow,
+ WebviewWindowBuilder,
};
-use tokio::sync::{oneshot, Mutex};
+use tokio::sync::Mutex;
use tracing::{info, warn};
use uuid::Uuid;
-/// Webview label — the same string is used by the frontend Tauri commands.
+/// WebviewWindow label — also used by the frontend Tauri commands.
pub const WEBVIEW_LABEL: &str = "owned-browser";
-/// Candidate parent windows, in preference order:
-/// - "home" — the standard app window (post-onboarding default;
-/// created at startup via `ShowRewindWindow::Home`).
-/// This is what the prod fallback caught on Louis's
-/// MBA — the most common parent in real sessions.
-/// - "main" — overlay-mode main window (NSPanel-based on macOS).
-/// - "main-window" — window-mode main window (traditional WebviewWindow).
-/// - "chat" — pre-created chat panel; exists in tray-only flows
-/// where the user only ever talks to Pi via the chat
-/// overlay and never opens the regular home window.
-///
-/// Why a list: the previous hardcoded "main" silently broke for everyone
-/// whose actual window label was something else — overwhelmingly "home"
-/// (post-onboarding default) and "chat" (tray-only). Trying each known
-/// label in order, with any other webview window as a final fallback,
-/// makes the install resilient to whatever window topology the user
-/// happens to be running. The fallback is what rescued the v2.4.113
-/// release in prod when "home" wasn't in the list yet — keeping it as a
-/// belt-and-suspenders for any future window label we forget to add.
-const PARENT_WINDOW_CANDIDATES: &[&str] = &["home", "main", "main-window", "chat"];
-
-/// Resolve a parent window for the child webview. Prefers the candidates
-/// above (in order). Falls back to any other webview window so future
-/// labels we don't know about still work without code changes.
-fn pick_parent_window(app: &AppHandle) -> Option<WebviewWindow> {
- for label in PARENT_WINDOW_CANDIDATES {
- if let Some(w) = app.get_webview_window(label) {
- return Some(w);
- }
- }
- app.webview_windows().into_values().next()
-}
-
-/// Event the injected JS emits when an eval finishes (or throws).
-const RESULT_EVENT: &str = "owned-browser:result";
-
/// Event the Rust handle emits when the agent navigates the browser. The
/// frontend's `<BrowserSidebar />` listens for this so it can slide in,
/// position the webview, and persist the URL to the active chat.
const NAVIGATE_EVENT: &str = "owned-browser:navigate";
+/// 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
+/// 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).
+const BRIDGE_INIT_SCRIPT: &str = r#"
+(function () {
+ if (window.__SP_RESULT__) return;
+ window.__SP_RESULT__ = function (payload) {
+ try {
+ var json = JSON.stringify(payload);
+ document.title = "__SP_OWNED_BROWSER_RESULT__:" + json;
+ } catch (e) {
+ document.title = "__SP_OWNED_BROWSER_RESULT__:" + JSON.stringify({
+ ok: false,
+ error: "serialize result failed: " + (e && e.message || e),
+ });
+ }
+ };
+})();
+"#;
+
// ---------------------------------------------------------------------------
// Handle implementation
// ---------------------------------------------------------------------------
struct TauriOwnedHandle {
app: AppHandle,
- pending: Mutex<HashMap<String, oneshot::Sender<EvalResult>>>,
-}
-
-#[derive(Debug, Deserialize)]
-struct ResultPayload {
- id: String,
- ok: bool,
- #[serde(default)]
- result: Option<serde_json::Value>,
- #[serde(default)]
- error: Option<String>,
+ /// 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
+ /// fire parallel evals at the same browser, so a mutex is fine.
+ eval_lock: Mutex<()>,
}
#[async_trait]
@@ -105,109 +115,149 @@ impl OwnedWebviewHandle for TauriOwnedHandle {
url: Option<&str>,
timeout: Duration,
) -> Result<EvalResult, String> {
- let webview = self
+ // 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(WEBVIEW_LABEL)
- .ok_or_else(|| "owned-browser webview not found".to_string())?;
+ .get_webview_window(WEBVIEW_LABEL)
+ .ok_or_else(|| "owned-browser webview window not found".to_string())?;
// If a target URL was supplied and the current location isn't on it,
- // navigate first. Tauri's `eval` is fire-and-forget so we just wait
- // a beat for the page to start loading. The frontend listens to
+ // navigate first. Tauri's `eval` is fire-and-forget so we wait a
+ // beat for the page to start loading. The frontend listens to
// NAVIGATE_EVENT so it can mount the sidebar before the page paints.
if let Some(target) = url {
let _ = self.app.emit(NAVIGATE_EVENT, target);
let target_lit = serde_json::to_string(target).unwrap_or_default();
- let _ = webview.eval(format!(
+ let _ = webview_window.eval(format!(
"if (!location.href.includes({lit})) location.href = {lit};",
lit = target_lit
));
tokio::time::sleep(Duration::from_millis(500)).await;
}
- let id = Uuid::new_v4().to_string();
- let (tx, rx) = oneshot::channel();
- self.pending.lock().await.insert(id.clone(), tx);
+ // 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();
- // Wrap user code so any outcome — success, throw, or rejected promise
- // — reports back via the result event. We JSON-encode the id so it
- // survives even if the user code crashes the surrounding scope.
+ let id = Uuid::new_v4().to_string();
let id_lit = serde_json::to_string(&id).unwrap();
+
+ // Wrap user code so any outcome — success, throw, or rejected
+ // promise — reports back via __SP_RESULT__. We JSON-encode the id
+ // so it survives even if the user code crashes the surrounding
+ // scope. Defensive check on __SP_RESULT__ in case the page
+ // navigated mid-flight before the bridge re-installed.
let wrapped = format!(
r#"(async () => {{
try {{
const __sp_result = await (async () => {{ {code} }})();
- window.__TAURI__.event.emit({event:?}, {{
- id: {id},
- ok: true,
- result: __sp_result === undefined ? null : __sp_result
- }});
+ if (window.__SP_RESULT__) {{
+ window.__SP_RESULT__({{
+ id: {id},
+ ok: true,
+ result: __sp_result === undefined ? null : __sp_result
+ }});
+ }}
}} catch (e) {{
- window.__TAURI__.event.emit({event:?}, {{
- id: {id},
- ok: false,
- error: String((e && e.message) || e)
- }});
+ if (window.__SP_RESULT__) {{
+ window.__SP_RESULT__({{
+ id: {id},
+ ok: false,
+ error: String((e && e.message) || e)
+ }});
+ }}
}}
}})()"#,
code = code,
- event = RESULT_EVENT,
id = id_lit
);
- if let Err(e) = webview.eval(wrapped) {
- self.pending.lock().await.remove(&id);
- return Err(format!("webview.eval failed: {e}"));
- }
-
- match tokio::time::timeout(timeout, rx).await {
- Ok(Ok(r)) => Ok(r),
- Ok(Err(_)) => Err("response channel dropped before eval reply".into()),
- Err(_) => {
- self.pending.lock().await.remove(&id);
- Err(format!(
- "owned-browser eval timed out after {}s",
- timeout.as_secs()
- ))
+ webview_window
+ .eval(wrapped)
+ .map_err(|e| format!("webview.eval failed: {e}"))?;
+
+ // Poll the title for our marker. 50ms cadence is fine — most
+ // evals complete in <500ms and the timeout cap keeps a stuck
+ // page from blocking forever.
+ let start = Instant::now();
+ let result_json = loop {
+ if start.elapsed() >= timeout {
+ return Err(format!(
+ "owned-browser eval timed out after {}s (last title: {:?})",
+ timeout.as_secs(),
+ webview_window.title().unwrap_or_default()
+ ));
+ }
+ if let Ok(title) = webview_window.title() {
+ if let Some(rest) = title.strip_prefix(RESULT_TITLE_PREFIX) {
+ break rest.to_string();
+ }
}
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ };
+
+ // 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};"));
+
+ // Parse the payload our wrapper emitted. We expect the same
+ // shape as before: { id, ok, result?, error? }.
+ #[derive(serde::Deserialize)]
+ struct Payload {
+ #[serde(default)]
+ id: String,
+ ok: bool,
+ #[serde(default)]
+ result: Option<serde_json::Value>,
+ #[serde(default)]
+ error: Option<String>,
+ }
+ let parsed: Payload = serde_json::from_str(&result_json)
+ .map_err(|e| format!("parse eval result: {e} (raw: {result_json})"))?;
+
+ // The id is informational — with eval_lock serialising calls,
+ // there's only ever one outstanding eval, so mismatches would
+ // indicate a stale title from a previous eval that didn't get
+ // restored. Log but accept.
+ if parsed.id != id {
+ warn!(
+ "owned-browser eval got stale result id (got {}, expected {})",
+ parsed.id, id
+ );
}
+
+ Ok(EvalResult {
+ ok: parsed.ok,
+ result: parsed.result,
+ error: parsed.error,
+ })
}
}
// ---------------------------------------------------------------------------
-// Install — build the child webview, wire up the result listener, return handle
+// Install — build the top-level webview window, return ready-to-attach handle
// ---------------------------------------------------------------------------
-/// Spawn the owned-browser install on a background task that survives
-/// every window topology — main visible, main hidden, tray-only with the
-/// chat panel, all of the above with mode switching mid-session.
-///
-/// Two phases:
-/// 1. Fast retry to absorb the normal window-creation race (`bun tauri
-/// dev` server thread vs WebviewWindow creation, app cold-start).
-/// 2. Event-driven retry — wakes up on every `window-focused` event
-/// (emitted whenever any window is shown or focused) and polls every
-/// 30s as a backstop. Tries every candidate parent in
-/// `PARENT_WINDOW_CANDIDATES`; as soon as one exists the install
-/// runs and attaches. There is no give-up timeout: the install task
-/// is cheap (one mpsc receiver + one tokio listener) and the only
-/// way it ever sees zero usable parents is if the user never
-/// interacts with the app at all, in which case the agent isn't
-/// asking for the browser anyway. Previous 30-minute deadline was
-/// the source of the user-visible "owned browser permanently broken"
-/// bug for chat-panel-only users.
+/// 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.
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 {
- // Phase 1 — fast retry. The chat panel is pre-created ~3s after
- // app setup (see main.rs `Pre-creating chat panel`), so 15s of
- // 500ms attempts is enough for the cold-start case to land here.
- const FAST_ATTEMPTS: u32 = 30;
- const FAST_BACKOFF: Duration = Duration::from_millis(500);
+ // 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.
+ const MAX_ATTEMPTS: u32 = 60;
+ const BACKOFF: Duration = Duration::from_millis(500);
let mut last_err = String::new();
- for attempt in 1..=FAST_ATTEMPTS {
+ for attempt in 1..=MAX_ATTEMPTS {
match install(&app, screenpipe_dir.clone()).await {
Ok(handle) => {
owned_browser.attach(handle).await;
@@ -217,71 +267,22 @@ pub fn spawn_install_when_ready(
Err(e) => {
last_err = e;
tracing::debug!(
- "owned-browser install attempt {attempt}/{FAST_ATTEMPTS}: {last_err}"
- );
- tokio::time::sleep(FAST_BACKOFF).await;
- }
- }
- }
-
- // Phase 2 — event-driven retry. No deadline; the install task is
- // cheap and we'd rather wait indefinitely than ever silently
- // surface ready=false to the agent.
- info!(
- "owned-browser: no candidate parent window after {FAST_ATTEMPTS} attempts \
- ({last_err}) — switching to event-driven retry, listening for window-focused"
- );
-
- let (tx, mut rx) = tokio::sync::mpsc::channel::<()>(8);
- let _listener_id = app.listen("window-focused", move |_event| {
- // Use try_send so we don't backpressure on the listener thread.
- let _ = tx.try_send(());
- });
-
- let mut last_log = std::time::Instant::now();
- loop {
- tokio::select! {
- _ = rx.recv() => {
- // window-focused fired — give the WebviewWindow a beat
- // to settle before trying to add_child to it.
- tokio::time::sleep(Duration::from_millis(100)).await;
- }
- _ = tokio::time::sleep(Duration::from_secs(30)) => {
- // Fallback poll. No log here — it would fire twice a
- // minute forever for a true tray-only session.
- }
- }
- if pick_parent_window(&app).is_none() {
- if last_log.elapsed() > Duration::from_secs(300) {
- tracing::debug!(
- "owned-browser: still waiting for any candidate parent window \
- (looked for: {PARENT_WINDOW_CANDIDATES:?})"
+ "owned-browser install attempt {attempt}/{MAX_ATTEMPTS}: {last_err}"
);
- last_log = std::time::Instant::now();
- }
- continue;
- }
- match install(&app, screenpipe_dir.clone()).await {
- Ok(handle) => {
- owned_browser.attach(handle).await;
- info!("owned-browser ready (after parent window appeared)");
- return;
- }
- Err(e) => {
- // pick_parent_window saw something, but install failed
- // — likely a closing race. Loop and try again.
- tracing::debug!("owned-browser delayed install: {e}");
+ tokio::time::sleep(BACKOFF).await;
}
}
}
+ warn!("owned-browser install never succeeded after {MAX_ATTEMPTS} attempts: {last_err}");
});
}
-/// Create the owned-browser child webview if it doesn't exist yet, register
-/// the result-event listener, and return a ready-to-attach handle. Idempotent.
+/// Create the owned-browser top-level window if it doesn't exist yet, and
+/// return a ready-to-attach handle. Idempotent.
///
-/// The webview starts at 0×0 (visually hidden); the frontend sidebar calls
-/// `owned_browser_set_bounds` to position it once a chat needs it.
+/// 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.
pub async fn install(
app: &AppHandle,
screenpipe_dir: PathBuf,
@@ -297,75 +298,48 @@ pub async fn install(
warn!("owned-browser: failed to create data dir {data_dir:?}: {e}");
}
- if app.get_webview(WEBVIEW_LABEL).is_none() {
- let parent_ww = pick_parent_window(app).ok_or_else(|| {
- format!("no candidate parent window found (looked for: {PARENT_WINDOW_CANDIDATES:?})")
- })?;
- let parent_label = parent_ww.label().to_string();
- // `add_child` lives on `Window`, not `WebviewWindow` — drop down to it.
- let parent_window = parent_ww.as_ref().window();
-
+ 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 = WebviewBuilder::new(WEBVIEW_LABEL, WebviewUrl::External(blank));
+ let mut builder =
+ WebviewWindowBuilder::new(app, WEBVIEW_LABEL, WebviewUrl::External(blank))
+ .title("owned-browser")
+ .decorations(false)
+ .resizable(false)
+ .skip_taskbar(true)
+ .visible(false)
+ // Always-on-top so the embedded browser stays above the
+ // sidebar's placeholder when both are visible. The frontend
+ // hides the webview (zero size) when it shouldn't be shown,
+ // so this doesn't trap the user.
+ .always_on_top(true)
+ .shadow(false)
+ .inner_size(1.0, 1.0)
+ .position(0.0, 0.0)
+ .initialization_script(BRIDGE_INIT_SCRIPT);
#[cfg(target_os = "windows")]
{
builder = builder
.additional_browser_args(&format!("--user-data-dir=\"{}\"", data_dir.display()));
}
- // Silence the unused-binding warning on non-Windows targets where the
- // data_dir is informational only.
+ // Silence the unused-binding warning on non-Windows targets where
+ // the data_dir is informational only.
let _ = &data_dir;
- // 1×1 placeholder; some platforms reject 0×0. The frontend will
- // resize as soon as the sidebar mounts.
- parent_window
- .add_child(
- builder,
- LogicalPosition::new(0.0, 0.0),
- LogicalSize::new(1.0, 1.0),
- )
- .map_err(|e| format!("add_child failed: {e}"))?;
-
- // Hide until the sidebar mounts and positions us — avoids a brief
- // flash of about:blank in the corner of the parent window.
- if let Some(wv) = app.get_webview(WEBVIEW_LABEL) {
- let _ = wv.hide();
- }
+ builder
+ .build()
+ .map_err(|e| format!("WebviewWindowBuilder::build failed: {e}"))?;
- info!("owned-browser: child webview created (parent: {parent_label})");
+ info!("owned-browser: top-level webview window created");
}
let handle = Arc::new(TauriOwnedHandle {
app: app.clone(),
- pending: Mutex::new(HashMap::new()),
- });
-
- // The injected JS emits results on the global event bus. Any frame in
- // the app could spoof this — that's acceptable because the engine only
- // matches by id and the worst case is a dropped reply.
- let listen_handle = handle.clone();
- app.listen(RESULT_EVENT, move |event| {
- let payload: ResultPayload = match serde_json::from_str(event.payload()) {
- Ok(p) => p,
- Err(e) => {
- warn!("owned-browser: unparseable result payload: {e}");
- return;
- }
- };
- let h = listen_handle.clone();
- tauri::async_runtime::spawn(async move {
- if let Some(tx) = h.pending.lock().await.remove(&payload.id) {
- let _ = tx.send(EvalResult {
- ok: payload.ok,
- result: payload.result,
- error: payload.error,
- });
- }
- });
+ eval_lock: Mutex::new(()),
});
Ok(handle as Arc<dyn OwnedWebviewHandle>)
@@ -375,11 +349,11 @@ pub async fn install(
// Tauri commands — sidebar controls (frontend → child webview)
// ---------------------------------------------------------------------------
-/// Position and size the embedded webview in its parent window's
-/// coordinate space (logical pixels, origin = top-left of the parent
-/// window's content area). The parent is whichever window the install
-/// picked — see `PARENT_WINDOW_CANDIDATES`. Call with width/height = 0
-/// to hide.
+/// Position and size the embedded webview window in **screen
+/// coordinates** (logical pixels, origin = top-left of the primary
+/// display). The frontend computes these from the active window's
+/// inner-position + the placeholder's viewport rect; see
+/// `<BrowserSidebar />`. Call with width/height = 0 to hide.
#[tauri::command]
pub async fn owned_browser_set_bounds(
app: AppHandle,
@@ -388,22 +362,22 @@ pub async fn owned_browser_set_bounds(
width: f64,
height: f64,
) -> Result<(), String> {
- let webview = app
- .get_webview(WEBVIEW_LABEL)
+ let webview_window = app
+ .get_webview_window(WEBVIEW_LABEL)
.ok_or_else(|| "owned-browser not initialized".to_string())?;
if width <= 0.0 || height <= 0.0 {
- webview.hide().map_err(|e| e.to_string())?;
+ webview_window.hide().map_err(|e| e.to_string())?;
return Ok(());
}
- webview
+ webview_window
.set_position(LogicalPosition::new(x, y))
.map_err(|e| e.to_string())?;
- webview
+ webview_window
.set_size(LogicalSize::new(width, height))
.map_err(|e| e.to_string())?;
- webview.show().map_err(|e| e.to_string())
+ webview_window.show().map_err(|e| e.to_string())
}
/// Navigate the embedded webview to `url`. Used by the agent (via
@@ -411,22 +385,22 @@ pub async fn owned_browser_set_bounds(
/// when restoring per-chat state.
#[tauri::command]
pub async fn owned_browser_navigate(app: AppHandle, url: String) -> Result<(), String> {
- let webview = app
- .get_webview(WEBVIEW_LABEL)
+ let webview_window = app
+ .get_webview_window(WEBVIEW_LABEL)
.ok_or_else(|| "owned-browser not initialized".to_string())?;
let parsed: url::Url = url
.parse()
.map_err(|e: url::ParseError| format!("invalid url: {e}"))?;
let _ = app.emit(NAVIGATE_EVENT, parsed.as_str());
- webview.navigate(parsed).map_err(|e| e.to_string())
+ webview_window.navigate(parsed).map_err(|e| e.to_string())
}
/// 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 = app
- .get_webview(WEBVIEW_LABEL)
+ let webview_window = app
+ .get_webview_window(WEBVIEW_LABEL)
.ok_or_else(|| "owned-browser not initialized".to_string())?;
- webview.hide().map_err(|e| e.to_string())
+ webview_window.hide().map_err(|e| e.to_string())
}