Skip to main content

agent_hub_runtime/core/preview/
runtime.rs

1//! Chromium discovery and owned background runtime lifecycle.
2use super::{super::error::AppError, cdp::Cdp};
3use serde::{Deserialize, Serialize};
4use serde_json::{json, Value};
5use std::{
6    fs,
7    path::{Path, PathBuf},
8    process::{Child, Command, Stdio},
9    sync::{Arc, Mutex},
10    time::{Duration, Instant},
11};
12
13#[derive(Clone, Serialize, Deserialize)]
14pub struct BrowserProfile {
15    pub id: String,
16    pub name: String,
17    #[serde(default)]
18    pub executable: Option<String>,
19    #[serde(default)]
20    pub endpoint: Option<String>,
21    #[serde(default)]
22    pub proxy: Option<String>,
23    #[serde(default)]
24    pub remote_download_directory: Option<String>,
25    #[serde(default)]
26    pub remote_transfer_target: Option<String>,
27    #[serde(default)]
28    pub ephemeral: bool,
29    #[serde(default)]
30    pub deleting: bool,
31}
32impl BrowserProfile {
33    pub fn guest() -> Self {
34        Self {
35            id: "guest".into(),
36            name: "Guest".into(),
37            ephemeral: true,
38            ..Self::default()
39        }
40    }
41}
42impl Default for BrowserProfile {
43    fn default() -> Self {
44        Self {
45            id: "default".into(),
46            name: "Default".into(),
47            executable: None,
48            endpoint: None,
49            proxy: None,
50            remote_download_directory: None,
51            remote_transfer_target: None,
52            ephemeral: false,
53            deleting: false,
54        }
55    }
56}
57pub(super) struct OwnedChild {
58    pub process: Child,
59    pub _temporary_profile: Option<tempfile::TempDir>,
60}
61impl Drop for OwnedChild {
62    fn drop(&mut self) {
63        let _ = self.process.kill();
64        let _ = self.process.wait();
65    }
66}
67pub struct Runtime {
68    pub(super) execution: super::execution::Execution,
69    pub(super) instance_id: String,
70    pub(super) download_epoch: u64,
71    pub(super) download_frames: std::collections::VecDeque<String>,
72    pub(super) remote_download_dir: Option<String>,
73    context_proxy: Option<String>,
74    pub(super) documents: Option<Arc<super::documents::Documents>>,
75    pub(super) ssh_target: Option<String>,
76    pub(super) document_forward: Option<super::document_forward::Forward>,
77    pub(super) document_forward_gate: Arc<Mutex<()>>,
78    child: Option<Arc<Mutex<OwnedChild>>>,
79    pub cdp: Cdp,
80    pub endpoint: String,
81    pub context: Option<String>,
82    pub download_dir: Option<PathBuf>,
83}
84impl Runtime {
85    pub(super) fn start(
86        root: &Path,
87        profile: &BrowserProfile,
88        spawn: impl FnOnce(
89            &mut Command,
90            Option<tempfile::TempDir>,
91        ) -> Result<Arc<Mutex<OwnedChild>>, AppError>,
92    ) -> Result<Self, AppError> {
93        validate_profile(profile)?;
94        if profile.deleting {
95            return Err(AppError::invalid_input(
96                "Profile deletion is pending; retry it in browser settings",
97            ));
98        }
99        let (child, endpoint) = if let Some(endpoint) = &profile.endpoint {
100            (None, validate_endpoint(endpoint)?)
101        } else {
102            let executable = match &profile.executable {
103                Some(path) if !path.trim().is_empty() => {
104                    let path = PathBuf::from(path);
105                    if !path.is_file() {
106                        return Err(AppError::not_found(
107                            "Configured browser executable is unavailable",
108                        ));
109                    }
110                    path
111                }
112                _ => discover().ok_or_else(|| AppError::not_found("PREVIEW_BROWSER_NOT_FOUND"))?,
113            };
114            let temporary = if profile.ephemeral {
115                Some(
116                    tempfile::Builder::new()
117                        .prefix("agent-hub-guest-")
118                        .tempdir()?,
119                )
120            } else {
121                None
122            };
123            let directory = temporary
124                .as_ref()
125                .map(|directory| directory.path().to_path_buf())
126                .unwrap_or_else(|| root.join("profiles").join(&profile.id));
127            fs::create_dir_all(&directory)?;
128            #[cfg(unix)]
129            {
130                use std::os::unix::fs::PermissionsExt;
131                fs::set_permissions(&directory, fs::Permissions::from_mode(0o700))?;
132            }
133            let port_file = directory.join("DevToolsActivePort");
134            if port_file.exists() {
135                fs::remove_file(&port_file)?;
136            }
137            let mut command = Command::new(executable);
138            command
139                .args([
140                    "--headless=new",
141                    "--remote-debugging-address=127.0.0.1",
142                    "--remote-debugging-port=0",
143                    "--no-first-run",
144                    "--no-default-browser-check",
145                    "--disable-background-networking",
146                ])
147                .arg(format!("--user-data-dir={}", directory.display()))
148                .arg("about:blank")
149                .stdin(Stdio::null())
150                .stdout(Stdio::null())
151                .stderr(Stdio::null());
152            if let Some(proxy) = &profile.proxy {
153                command.arg(format!("--proxy-server={proxy}"));
154                command.arg("--proxy-bypass-list=<-loopback>;*.agent-hub.localhost");
155                command.arg("--dns-prefetch-disable");
156            }
157            #[cfg(windows)]
158            {
159                use std::os::windows::process::CommandExt;
160                command.creation_flags(0x08000000);
161            }
162            #[cfg(test)]
163            command.args(["--use-mock-keychain", "--password-store=basic"]);
164            let child = spawn(&mut command, temporary)?;
165            let started = Instant::now();
166            let port = loop {
167                if let Some(status) = child
168                    .lock()
169                    .map_err(|_| AppError::internal("Browser process unavailable"))?
170                    .process
171                    .try_wait()?
172                {
173                    return Err(AppError::network(if status.code() == Some(21) {
174                        "PREVIEW_PROFILE_IN_USE: Browser profile is already in use. Close the previous AgentHub instance and retry, or use a guest tab. Saved login data has not been removed."
175                    } else {
176                        "Browser exited during startup; check the executable and profile"
177                    }));
178                }
179                if let Ok(text) = fs::read_to_string(&port_file) {
180                    if let Some(port) = text
181                        .lines()
182                        .next()
183                        .and_then(|line| line.parse::<u16>().ok())
184                    {
185                        break port;
186                    }
187                }
188                if started.elapsed() > Duration::from_secs(15) {
189                    let _ = child.lock().map(|mut child| child.process.kill());
190                    let _ = child.lock().map(|mut child| child.process.wait());
191                    return Err(AppError::network("Browser startup timed out"));
192                }
193                std::thread::sleep(Duration::from_millis(50));
194            };
195            (Some(child), format!("http://127.0.0.1:{port}"))
196        };
197        let cdp = match connect_control(&endpoint) {
198            Ok(cdp) => cdp,
199            Err(error) => {
200                if let Some(child) = child {
201                    let _ = child.lock().map(|mut child| child.process.kill());
202                    let _ = child.lock().map(|mut child| child.process.wait());
203                }
204                return Err(error);
205            }
206        };
207        let instance_id = uuid::Uuid::new_v4().to_string();
208        let remote_download_dir = profile
209            .remote_download_directory
210            .as_ref()
211            .map(|base| super::remote_downloads::managed_directory(base, &instance_id))
212            .transpose()?;
213        let mut runtime = Self {
214            execution: super::execution::Execution::from_profile(profile),
215            instance_id,
216            download_epoch: 0,
217            download_frames: std::collections::VecDeque::new(),
218            remote_download_dir,
219            context_proxy: profile.proxy.clone(),
220            documents: None,
221            ssh_target: profile.remote_transfer_target.clone(),
222            document_forward: None,
223            document_forward_gate: Arc::new(Mutex::new(())),
224            child,
225            cdp,
226            endpoint,
227            context: None,
228            download_dir: None,
229        };
230        if profile.endpoint.is_none() {
231            let targets = runtime.cdp.call("Target.getTargets", json!({}))?;
232            if let Some(targets) = targets["targetInfos"].as_array() {
233                for target in targets {
234                    if target["type"] == "page" {
235                        let _ = runtime
236                            .cdp
237                            .call("Target.closeTarget", json!({"targetId":target["targetId"]}));
238                    }
239                }
240            }
241        }
242        if profile.endpoint.is_some() {
243            let context = create_context(&mut runtime.cdp, runtime.context_proxy.as_deref())?;
244            runtime.context = Some(
245                context["browserContextId"]
246                    .as_str()
247                    .filter(|id| !id.is_empty())
248                    .ok_or_else(|| AppError::network("Browser did not create an isolated context"))?
249                    .to_owned(),
250            );
251            runtime.configure_remote_downloads()?;
252        } else {
253            let directory = root.join("downloads").join(&profile.id);
254            fs::create_dir_all(&directory)?;
255            runtime.cdp.call(
256                "Browser.setDownloadBehavior",
257                json!({ "behavior": "allowAndName", "downloadPath": directory, "eventsEnabled": true }),
258            )?;
259            runtime.download_dir = Some(directory);
260        }
261        Ok(runtime)
262    }
263    pub(super) fn owned_process_exited(&self) -> Result<bool, AppError> {
264        match &self.child {
265            Some(child) => Ok(child
266                .lock()
267                .map_err(|_| AppError::internal("Browser process unavailable"))?
268                .process
269                .try_wait()?
270                .is_some()),
271            None => Ok(false),
272        }
273    }
274    fn ensure_context(&mut self) -> Result<(), AppError> {
275        if let Some(context) = &self.context {
276            let contexts = self.cdp.call("Target.getBrowserContexts", json!({}))?;
277            let contexts = contexts["browserContextIds"]
278                .as_array()
279                .ok_or_else(|| AppError::network("Browser contexts unavailable"))?;
280            if !contexts
281                .iter()
282                .any(|value| value.as_str() == Some(context.as_str()))
283            {
284                let created = create_context(&mut self.cdp, self.context_proxy.as_deref())?;
285                self.context = Some(
286                    created["browserContextId"]
287                        .as_str()
288                        .ok_or_else(|| {
289                            AppError::network("Browser did not create an isolated context")
290                        })?
291                        .into(),
292                );
293                self.download_frames.clear();
294            }
295        }
296        self.configure_remote_downloads()
297    }
298    pub fn create_page(
299        &mut self,
300        on_created: impl FnOnce(&str) -> Result<(), AppError>,
301    ) -> Result<(String, Cdp), AppError> {
302        self.ensure_context()?;
303        let mut params = json!({ "url": "about:blank" });
304        if let Some(context) = &self.context {
305            params["browserContextId"] = json!(context);
306        }
307        let result = self.cdp.call("Target.createTarget", params)?;
308        let id = result["targetId"]
309            .as_str()
310            .ok_or_else(|| AppError::network("Browser did not create a page"))?
311            .to_owned();
312        on_created(&id)?;
313        let cdp = self.attach_page(&id)?;
314        Ok((id, cdp))
315    }
316    pub fn attach_page(&mut self, id: &str) -> Result<Cdp, AppError> {
317        let target = json_endpoint(&self.endpoint, "/json/list")?
318            .as_array()
319            .and_then(|targets| targets.iter().find(|target| target["id"] == id))
320            .cloned()
321            .ok_or_else(|| AppError::network("Browser page is not ready"))?;
322        let address = target["webSocketDebuggerUrl"]
323            .as_str()
324            .ok_or_else(|| AppError::network("Browser page is unavailable"))?;
325        let address = control_address(&self.endpoint, address)?;
326        let mut cdp = Cdp::connect(&address)?;
327        if let Some(documents) = self.documents.as_ref().filter(|_| self.context.is_some()) {
328            cdp.enable_resources(&address, documents.clone())?;
329        }
330        cdp.call("Page.enable", json!({}))?;
331        cdp.call("Runtime.enable", json!({}))?;
332        cdp.call(
333            "Page.setInterceptFileChooserDialog",
334            json!({"enabled":true}),
335        )?;
336        cdp.call(
337            "Network.enable",
338            json!({ "maxTotalBufferSize": 1048576, "maxResourceBufferSize": 65536 }),
339        )?;
340        cdp.enable_frames(&address)?;
341        if self.context.is_some() && self.remote_download_dir.is_some() {
342            let tree = cdp.call("Page.getFrameTree", json!({}))?;
343            self.remember_download_frames(&tree["frameTree"]);
344        }
345        Ok(cdp)
346    }
347}
348impl Drop for Runtime {
349    fn drop(&mut self) {
350        if self.child.is_none() {
351            if let Some(context) = &self.context {
352                let _ = self.cdp.call(
353                    "Target.disposeBrowserContext",
354                    json!({ "browserContextId": context }),
355                );
356            }
357        }
358    }
359}
360pub fn json_endpoint(endpoint: &str, path: &str) -> Result<Value, AppError> {
361    use std::io::Read;
362    let response = reqwest::blocking::Client::builder()
363        .no_proxy()
364        .timeout(Duration::from_secs(5))
365        .build()
366        .map_err(AppError::network)?
367        .get(format!("{endpoint}{path}"))
368        .send()
369        .map_err(AppError::network)?
370        .error_for_status()
371        .map_err(AppError::network)?;
372    let mut bytes = Vec::new();
373    response.take(2 * 1024 * 1024 + 1).read_to_end(&mut bytes)?;
374    if bytes.len() > 2 * 1024 * 1024 {
375        return Err(AppError::network("Browser metadata exceeds limit"));
376    }
377    serde_json::from_slice(&bytes).map_err(AppError::network)
378}
379pub fn validate_endpoint(endpoint: &str) -> Result<String, AppError> {
380    let url = reqwest::Url::parse(endpoint)
381        .map_err(|error| AppError::invalid_input(error.to_string()))?;
382    if url.scheme() != "http"
383        || !matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "::1"))
384        || !url.username().is_empty()
385        || url.password().is_some()
386        || url.query().is_some()
387        || url.fragment().is_some()
388        || url.path() != "/"
389    {
390        return Err(AppError::invalid_input(
391            "Use a loopback HTTP browser endpoint; tunnel remote control through SSH",
392        ));
393    }
394    Ok(url.as_str().trim_end_matches('/').to_owned())
395}
396pub fn validate_profile(profile: &BrowserProfile) -> Result<(), AppError> {
397    if profile.id.is_empty()
398        || profile.id.len() > 64
399        || !profile
400            .id
401            .bytes()
402            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
403        || ["default", "guest"]
404            .iter()
405            .any(|reserved| profile.id.eq_ignore_ascii_case(reserved) && profile.id != *reserved)
406        || profile.name.trim().is_empty()
407        || profile.name.len() > 100
408        || profile
409            .executable
410            .as_ref()
411            .is_some_and(|path| path.len() > 8192)
412    {
413        return Err(AppError::invalid_input("Invalid browser profile"));
414    }
415    if let Some(proxy) = &profile.proxy {
416        let url = reqwest::Url::parse(proxy)
417            .map_err(|error| AppError::invalid_input(error.to_string()))?;
418        if !matches!(url.scheme(), "http" | "https" | "socks5")
419            || url.host_str().is_none()
420            || proxy.len() > 2048
421            || !url.username().is_empty()
422            || url.password().is_some()
423        {
424            return Err(AppError::invalid_input("Invalid browser proxy"));
425        }
426    }
427    if let Some(endpoint) = &profile.endpoint {
428        validate_endpoint(endpoint)?;
429    }
430    if let Some(directory) = &profile.remote_download_directory {
431        if profile.endpoint.is_none() {
432            return Err(AppError::invalid_input(
433                "Remote download directories require a remote endpoint",
434            ));
435        }
436        super::remote_downloads::managed_directory(directory, "validation")?;
437    }
438    if let Some(target) = &profile.remote_transfer_target {
439        super::remote_ssh::validate_target(target)?;
440        if profile.endpoint.is_none() {
441            return Err(AppError::invalid_input(
442                "Configure the remote endpoint first",
443            ));
444        }
445    }
446    Ok(())
447}
448pub fn discover() -> Option<PathBuf> {
449    #[cfg(target_os = "macos")]
450    let candidates = [
451        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
452        "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
453        "/Applications/Chromium.app/Contents/MacOS/Chromium",
454    ]
455    .map(PathBuf::from)
456    .to_vec();
457    #[cfg(windows)]
458    let candidates: Vec<PathBuf> = ["PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"]
459        .iter()
460        .filter_map(std::env::var_os)
461        .flat_map(|root| {
462            [
463                PathBuf::from(&root).join("Google/Chrome/Application/chrome.exe"),
464                PathBuf::from(&root).join("Microsoft/Edge/Application/msedge.exe"),
465            ]
466        })
467        .collect();
468    #[cfg(not(any(target_os = "macos", windows)))]
469    let candidates: Vec<PathBuf> =
470        std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
471            .flat_map(|directory| {
472                [
473                    directory.join("google-chrome"),
474                    directory.join("chromium"),
475                    directory.join("chromium-browser"),
476                    directory.join("microsoft-edge"),
477                ]
478            })
479            .collect();
480    candidates.into_iter().find(|path| path.is_file())
481}
482
483pub(super) fn control_address(endpoint: &str, advertised: &str) -> Result<String, AppError> {
484    let endpoint = reqwest::Url::parse(&validate_endpoint(endpoint)?).map_err(AppError::network)?;
485    let mut address = reqwest::Url::parse(advertised).map_err(AppError::network)?;
486    if address.scheme() != "ws" || !address.username().is_empty() || address.password().is_some() {
487        return Err(AppError::invalid_input("Invalid browser WebSocket address"));
488    }
489    address
490        .set_host(endpoint.host_str())
491        .map_err(AppError::network)?;
492    address
493        .set_port(endpoint.port())
494        .map_err(|_| AppError::invalid_input("Invalid browser control port"))?;
495    Ok(address.into())
496}
497
498/// Connect through the validated endpoint, including SSH-forwarded authorities.
499pub(super) fn connect_control(endpoint: &str) -> Result<Cdp, AppError> {
500    let version = json_endpoint(&validate_endpoint(endpoint)?, "/json/version")?;
501    let advertised = version["webSocketDebuggerUrl"]
502        .as_str()
503        .ok_or_else(|| AppError::network("Browser does not expose CDP"))?;
504    let mut cdp = Cdp::connect(&control_address(endpoint, advertised)?)?;
505    cdp.set_timeout(Duration::from_secs(2))?;
506    Ok(cdp)
507}
508
509// Keep initial creation and recovery on the same explicit network policy.
510fn create_context(cdp: &mut Cdp, proxy: Option<&str>) -> Result<Value, AppError> {
511    let mut params = json!({"disposeOnDetach": false});
512    if let Some(proxy) = proxy {
513        params["proxyServer"] = json!(proxy);
514        // Loopback means the network execution host; it must use an explicit proxy too.
515        params["proxyBypassList"] = json!("<-loopback>;*.agent-hub.localhost");
516    }
517    cdp.call("Target.createBrowserContext", params)
518}
519
520#[cfg(test)]
521mod tests;