Skip to main content

agent_hub_runtime/commands/
preview_native.rs

1//! System WebView adapter. It owns no Chromium process, CDP transport, or Chrome profile.
2mod capture;
3pub mod control;
4pub mod cookies;
5pub mod downloads;
6pub mod export;
7mod platform;
8mod profile;
9use crate::core::error::AppError;
10pub use control::{
11    __cmd__preview_native_execute, __cmd__preview_native_frame, __cmd__preview_native_pick_mode,
12    preview_native_execute, preview_native_frame, preview_native_pick_mode,
13};
14use serde::{Deserialize, Serialize};
15use std::{
16    collections::HashMap,
17    sync::{Arc, Mutex},
18};
19use tauri::{Emitter, Manager};
20pub struct NativeViews {
21    pub downloads: downloads::Downloads,
22    gates: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
23    imports: Arc<crate::core::preview::cookies::Imports>,
24    import_uas: Mutex<HashMap<String, (std::time::Instant, Option<String>)>>,
25    cookie_gate: tokio::sync::Mutex<()>,
26    picking: Mutex<Option<String>>,
27    #[cfg(target_os = "linux")]
28    closing: Mutex<std::collections::HashSet<String>>,
29}
30impl Default for NativeViews {
31    fn default() -> Self {
32        Self {
33            downloads: downloads::Downloads::default(),
34            gates: Mutex::default(),
35            imports: crate::core::preview::cookies::Imports::shared(),
36            import_uas: Mutex::default(),
37            cookie_gate: tokio::sync::Mutex::new(()),
38            picking: Mutex::default(),
39            #[cfg(target_os = "linux")]
40            closing: Mutex::default(),
41        }
42    }
43}
44impl NativeViews {
45    fn is_picking(&self, id: &str) -> bool {
46        self.picking
47            .lock()
48            .unwrap_or_else(|error| error.into_inner())
49            .as_deref()
50            == Some(id)
51    }
52    fn set_picking(&self, id: &str, enabled: bool) {
53        let mut picking = self
54            .picking
55            .lock()
56            .unwrap_or_else(|error| error.into_inner());
57        if enabled {
58            *picking = Some(id.into());
59        } else if picking.as_deref() == Some(id) {
60            *picking = None;
61        }
62    }
63    #[cfg(target_os = "linux")]
64    fn last_view_closing(&self, id: &str, live: impl IntoIterator<Item = String>) -> bool {
65        let live: std::collections::HashSet<_> = live.into_iter().collect();
66        let mut closing = self
67            .closing
68            .lock()
69            .unwrap_or_else(|error| error.into_inner());
70        // Runtime removal is asynchronous; simultaneous close requests must count
71        // already-closing views without retaining stale identities indefinitely.
72        closing.retain(|view| live.contains(view));
73        closing.insert(id.into());
74        live.iter().all(|view| closing.contains(view))
75    }
76    async fn lock(&self, id: &str) -> Result<tokio::sync::OwnedMutexGuard<()>, AppError> {
77        let gate = self
78            .gates
79            .lock()
80            .map_err(|_| AppError::internal("Native page state unavailable"))?
81            .entry(id.into())
82            .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
83            .clone();
84        Ok(gate.lock_owned().await)
85    }
86}
87
88#[derive(Clone, Deserialize)]
89pub struct NativeBounds {
90    x: f64,
91    y: f64,
92    width: f64,
93    height: f64,
94    zoom: Option<f64>,
95}
96impl NativeBounds {
97    fn validate(&self) -> Result<(), AppError> {
98        if ![self.x, self.y, self.width, self.height]
99            .iter()
100            .all(|v| v.is_finite())
101            || self.x < 0.0
102            || self.y < 0.0
103            || self.width < 1.0
104            || self.height < 1.0
105            || self.x + self.width > 20000.0
106            || self.y + self.height > 20000.0
107            || self
108                .zoom
109                .is_some_and(|zoom| !zoom.is_finite() || !(0.01..=5.0).contains(&zoom))
110        {
111            return Err(AppError::invalid_input("Invalid native browser bounds"));
112        }
113        Ok(())
114    }
115}
116#[derive(Clone, Serialize)]
117struct Location {
118    id: String,
119    url: String,
120    loading: bool,
121}
122fn main_only(caller: &tauri::Webview) -> Result<(), AppError> {
123    if !crate::desktop::workspaces::is_workspace(caller) {
124        return Err(AppError::invalid_input(
125            "Native preview requires a trusted workspace",
126        ));
127    }
128    Ok(())
129}
130fn native_url(url: &str) -> Result<tauri::Url, AppError> {
131    crate::core::preview::navigation::validate_url(url)?;
132    tauri::Url::parse(url).map_err(|error| AppError::invalid_input(error.to_string()))
133}
134fn target(caller: &tauri::Webview, id: &str) -> Result<tauri::Webview, AppError> {
135    main_only(caller)?;
136    if !id
137        .strip_prefix("preview-native-")
138        .is_some_and(|value| uuid::Uuid::parse_str(value).is_ok())
139    {
140        return Err(AppError::invalid_input("Invalid native preview identity"));
141    }
142    caller
143        .app_handle()
144        .get_webview(id)
145        .filter(|view| view.window().label() == caller.window().label())
146        .ok_or_else(|| AppError::not_found("Native preview is closed"))
147}
148#[tauri::command]
149pub async fn preview_native_info(
150    webview: tauri::Webview,
151    id: Option<String>,
152) -> Result<serde_json::Value, AppError> {
153    main_only(&webview)?;
154    let engine = if cfg!(target_os = "macos") {
155        "WKWebView"
156    } else if cfg!(windows) {
157        "WebView2"
158    } else {
159        "WebKitGTK"
160    };
161    let ua = if let Some(id) = id {
162        let view = target(&webview, &id)?;
163        control::metadata(&view)
164            .await
165            .map(|metadata| metadata["userAgent"].clone())
166            .unwrap_or(serde_json::Value::Null)
167    } else {
168        serde_json::Value::Null
169    };
170    Ok(
171        serde_json::json!({"engine":engine,"version":tauri::webview_version().ok(),"userAgent":ua,"inspection":ua.is_string(),"cookies":cfg!(target_os="macos"),"persistent":profile::persistent()}),
172    )
173}
174#[tauri::command]
175pub async fn preview_native_open(
176    webview: tauri::Webview,
177    url: String,
178    bounds: NativeBounds,
179) -> Result<String, AppError> {
180    main_only(&webview)?;
181    bounds.validate()?;
182    let url = native_url(&url)?;
183    let window = webview.window();
184    if window
185        .webviews()
186        .iter()
187        .filter(|view| view.label().starts_with("preview-native-"))
188        .count()
189        >= 12
190    {
191        return Err(AppError::invalid_input("PREVIEW_TAB_LIMIT"));
192    }
193    tauri::async_runtime::spawn_blocking(move || {
194        let id = format!("preview-native-{}", uuid::Uuid::new_v4());
195        let event_id = id.clone();
196        let popup_id = id.clone();
197        let owner = webview.label().to_owned();
198        let popup_owner = owner.clone();
199        let popup_app = window.app_handle().clone();
200        let builder = tauri::webview::WebviewBuilder::new(&id, tauri::WebviewUrl::External(url))
201            .incognito(true)
202            .initialization_script(
203                include_str!("preview_native/bridge.js")
204                    .replace(
205                        "__PICK_FUNCTION__",
206                        &crate::core::preview::scripts::picker(),
207                    )
208                    .replace(
209                        "__ELEMENT_CONTEXT__",
210                        include_str!("../core/preview/scripts/elements.js"),
211                    ),
212            )
213            .focused(false)
214            .on_navigation(|url| native_url(url.as_str()).is_ok())
215            .on_download(downloads::handle)
216            .on_new_window(move |url, _| {
217                if native_url(url.as_str()).is_ok() && url.scheme() != "about" {
218                    let _ = popup_app.emit_to(
219                        popup_owner.as_str(),
220                        "preview-native-new-tab",
221                        serde_json::json!({"id":popup_id,"url":url.as_str()}),
222                    );
223                }
224                tauri::webview::NewWindowResponse::Deny
225            })
226            .on_page_load(move |view, payload| {
227                let _ = view.app_handle().emit_to(
228                    owner.as_str(),
229                    "preview-native-location",
230                    Location {
231                        id: event_id.clone(),
232                        url: payload.url().to_string(),
233                        loading: payload.event() == tauri::webview::PageLoadEvent::Started,
234                    },
235                );
236            });
237        let builder = profile::configure(builder)?;
238        let view = window
239            .add_child(
240                builder,
241                tauri::LogicalPosition::new(bounds.x, bounds.y),
242                tauri::LogicalSize::new(bounds.width, bounds.height),
243            )
244            .map_err(AppError::io)?;
245        if let Err(error) = view.set_zoom(bounds.zoom.unwrap_or(1.0)) {
246            let _ = view.close();
247            return Err(AppError::io(error));
248        }
249        Ok(id)
250    })
251    .await
252    .map_err(AppError::io)?
253}
254#[tauri::command]
255pub fn preview_native_update(
256    webview: tauri::Webview,
257    id: String,
258    visible: bool,
259    bounds: Option<NativeBounds>,
260    url: Option<String>,
261) -> Result<(), AppError> {
262    let view = target(&webview, &id)?;
263    if let Some(bounds) = bounds {
264        bounds.validate()?;
265        view.set_position(tauri::LogicalPosition::new(bounds.x, bounds.y))
266            .map_err(AppError::io)?;
267        view.set_size(tauri::LogicalSize::new(bounds.width, bounds.height))
268            .map_err(AppError::io)?;
269        view.set_zoom(bounds.zoom.unwrap_or(1.0))
270            .map_err(AppError::io)?;
271    }
272    if let Some(url) = url {
273        view.navigate(native_url(&url)?).map_err(AppError::io)?;
274    }
275    if visible {
276        view.show().map_err(AppError::io)?;
277    } else {
278        view.hide().map_err(AppError::io)?;
279    }
280    Ok(())
281}
282#[tauri::command]
283pub fn preview_native_action(
284    webview: tauri::Webview,
285    id: String,
286    action: String,
287) -> Result<(), AppError> {
288    let view = target(&webview, &id)?;
289    match action.as_str() {
290        "reload" => view.reload().map_err(AppError::io),
291        "back" => view.eval("history.back()").map_err(AppError::io),
292        "forward" => view.eval("history.forward()").map_err(AppError::io),
293        "close" => {
294            webview.state::<NativeViews>().set_picking(&id, false);
295            #[cfg(target_os = "linux")]
296            if webview.state::<NativeViews>().last_view_closing(
297                &id,
298                webview
299                    .window()
300                    .webviews()
301                    .iter()
302                    .filter(|view| view.label().starts_with("preview-native-"))
303                    .map(|view| view.label().to_owned()),
304            ) {
305                let _ = platform::linux_restore_theme(&view);
306            }
307            webview.state::<NativeViews>().downloads.close_view(&id);
308            if let Ok(mut gates) = webview.state::<NativeViews>().gates.lock() {
309                gates.remove(&id);
310            }
311            view.close().map_err(AppError::io)
312        }
313        _ => Err(AppError::invalid_input("Unsupported native browser action")),
314    }
315}
316
317#[cfg(test)]
318#[path = "preview_native/tests.rs"]
319mod tests;