Skip to main content

agent_hub_runtime/core/preview/
browser.rs

1//! Logical pages and isolated runtime ownership shared by GUI and CLI.
2use super::{
3    super::error::AppError,
4    cdp::Cdp,
5    runtime::{self, BrowserProfile, OwnedChild, Runtime},
6};
7use serde::Serialize;
8use serde_json::{json, Value};
9use sha2::{Digest, Sha256};
10use std::{
11    collections::{HashMap, HashSet, VecDeque},
12    path::PathBuf,
13    process::Command,
14    sync::{Arc, Mutex},
15    time::{Duration, Instant},
16};
17
18pub struct Page {
19    pub(super) frame_info: Option<(Instant, Value)>,
20    pub(super) connection_generation: u64,
21    pub(super) navigation_intent: u64,
22    pub(super) snapshots: VecDeque<(String, String)>,
23    pub cdp: Cdp,
24    pub width: u32,
25    pub height: u32,
26    pub(super) device_scale_factor: f64,
27    pub(super) mobile: bool,
28    pub(super) metadata: Arc<Mutex<BrowserPageInfo>>,
29}
30impl Page {
31    pub fn identity(&mut self) -> Result<(String, String), AppError> {
32        let result = self.cdp.call("Page.getFrameTree", json!({}))?;
33        let frame = &result["frameTree"]["frame"];
34        let revision = frame["loaderId"]
35            .as_str()
36            .filter(|value| !value.is_empty())
37            .ok_or_else(|| AppError::network("Browser document is not ready"))?
38            .to_owned();
39        let url = match frame["unreachableUrl"]
40            .as_str()
41            .filter(|url| validate_url(url).is_ok())
42        {
43            Some(url) => url.to_owned(),
44            None => format!(
45                "{}{}",
46                frame["url"].as_str().unwrap_or("about:blank"),
47                frame["urlFragment"].as_str().unwrap_or("")
48            ),
49        };
50        let revision = format!(
51            "{}:{}:{}:{:x}",
52            revision,
53            self.connection_generation,
54            self.cdp.navigation_version,
55            Sha256::digest(url.as_bytes())
56        );
57        self.snapshots.retain(|(_, value)| value == &revision);
58        Ok((revision, url))
59    }
60}
61#[derive(Clone)]
62pub(super) struct PageHandle {
63    pub profile: String,
64    pub target: String,
65    pub internal: bool,
66    pub page: Arc<Mutex<Page>>,
67    pub metadata: Arc<Mutex<BrowserPageInfo>>,
68}
69#[derive(Default)]
70pub(super) struct State {
71    pub reopening_profiles: HashMap<String, String>,
72    pub lost_pages: HashSet<String>,
73    pub cookie_gates: HashMap<String, Arc<Mutex<()>>>,
74    pub downloads: HashMap<String, super::downloads::Download>,
75    pub transfers: HashMap<String, Arc<super::download_transfer::Transfer>>,
76    pub document_builds: HashMap<String, Arc<std::sync::atomic::AtomicBool>>,
77    pub closing: bool,
78    pub runtimes: HashMap<String, Arc<Mutex<Runtime>>>,
79    pub processes: HashMap<String, Arc<Mutex<OwnedChild>>>,
80    pub starting: HashMap<String, Arc<Mutex<()>>>,
81    pub pending: HashMap<String, String>,
82    pub attaching: HashSet<(String, String)>,
83    pub pending_targets: HashMap<String, (String, String)>,
84    pub idle: HashMap<String, Instant>,
85    pub pages: HashMap<String, PageHandle>,
86}
87pub struct Browsers {
88    pub root: PathBuf,
89    pub documents: Arc<super::documents::Documents>,
90    pub(super) document_port: std::sync::atomic::AtomicU16,
91    pub(super) state: Mutex<State>,
92    pub(super) downloads_gate: Mutex<()>,
93}
94#[derive(Clone, Copy, Debug, Serialize, PartialEq)]
95#[serde(rename_all = "snake_case")]
96pub enum PageStatus {
97    Connected,
98    Unverified,
99    Gone,
100}
101#[derive(Clone, Serialize)]
102pub struct BrowserPageInfo {
103    pub execution: super::execution::Execution,
104    pub status: PageStatus,
105    pub id: String,
106    pub profile: String,
107    pub url: String,
108    pub title: String,
109    pub revision: String,
110    pub owner: Option<String>,
111}
112#[derive(Serialize)]
113pub struct BrowserInfo {
114    pub executable: Option<String>,
115    pub profiles: Vec<BrowserProfile>,
116}
117#[derive(Serialize)]
118pub struct Frame {
119    pub image: String,
120    pub image_mime: &'static str,
121    pub info: Value,
122    pub events: Vec<Value>,
123    pub version: u64,
124}
125pub(super) struct ProfileLease<'a> {
126    pub browsers: &'a Browsers,
127    pub profile: String,
128    pub id: String,
129}
130impl Drop for ProfileLease<'_> {
131    fn drop(&mut self) {
132        if let Ok(mut state) = self.browsers.state.lock() {
133            if state.reopening_profiles.get(&self.profile) == Some(&self.id) {
134                state.reopening_profiles.remove(&self.profile);
135            }
136        }
137    }
138}
139struct Reservation<'a> {
140    manager: &'a Browsers,
141    id: String,
142    profile: String,
143}
144impl Drop for Reservation<'_> {
145    fn drop(&mut self) {
146        if let Ok(mut state) = self.manager.state.lock() {
147            state.pending.remove(&self.id);
148            state.pending_targets.remove(&self.id);
149            if !state
150                .pages
151                .values()
152                .any(|page| page.profile == self.profile)
153                && !state
154                    .pending
155                    .values()
156                    .any(|profile| profile == &self.profile)
157            {
158                state
159                    .idle
160                    .entry(self.profile.clone())
161                    .or_insert_with(Instant::now);
162            }
163        }
164    }
165}
166pub use super::actions::Action;
167impl Browsers {
168    pub fn new(root: PathBuf) -> Self {
169        Self {
170            root,
171            documents: Arc::new(super::documents::Documents::default()),
172            document_port: std::sync::atomic::AtomicU16::new(0),
173            state: Mutex::new(State::default()),
174            downloads_gate: Mutex::new(()),
175        }
176    }
177    pub fn shared(root: PathBuf) -> Arc<Self> {
178        let manager = Arc::new(Self::new(root));
179        let weak = Arc::downgrade(&manager);
180        std::thread::spawn(move || loop {
181            let Some(manager) = weak.upgrade() else {
182                break;
183            };
184            let closed = manager.state.lock().map_or(true, |state| state.closing);
185            if closed {
186                break;
187            }
188            manager.reap_exited();
189            let _ = manager.downloads();
190            manager.retire_idle();
191            drop(manager);
192            std::thread::sleep(Duration::from_millis(700));
193        });
194        manager
195    }
196    pub fn info(&self) -> Result<BrowserInfo, AppError> {
197        Ok(BrowserInfo {
198            executable: runtime::discover().map(|path| path.to_string_lossy().into_owned()),
199            profiles: self.profiles()?,
200        })
201    }
202    pub fn create(&self, profile: &str, url: &str) -> Result<String, AppError> {
203        self.create_page(profile, url, false, None, None)
204    }
205    pub(super) fn create_internal(&self, profile: &str, url: &str) -> Result<String, AppError> {
206        self.create_page(profile, url, true, None, None)
207    }
208    pub fn create_owned(&self, profile: &str, url: &str, owner: &str) -> Result<String, AppError> {
209        if owner.len() > 100 {
210            return Err(AppError::invalid_input("Invalid preview owner"));
211        }
212        self.create_page(profile, url, false, Some(owner.into()), None)
213    }
214    pub(super) fn create_replacement(
215        &self,
216        profile: &str,
217        url: &str,
218        original: &str,
219    ) -> Result<String, AppError> {
220        self.create_page(profile, url, true, None, Some(original))
221    }
222    fn create_page(
223        &self,
224        profile: &str,
225        url: &str,
226        internal: bool,
227        owner: Option<String>,
228        recovery_id: Option<&str>,
229    ) -> Result<String, AppError> {
230        validate_url(url)?;
231        if !self.profiles()?.iter().any(|item| item.id == profile) {
232            return Err(AppError::not_found("Browser profile unavailable"));
233        }
234        let id = uuid::Uuid::new_v4().to_string();
235        let gate = {
236            let mut state = self
237                .state
238                .lock()
239                .map_err(|_| AppError::internal("Browser state unavailable"))?;
240            if state.closing {
241                return Err(AppError::cancelled("Preview is shutting down"));
242            }
243            if state.reopening_profiles.get(profile).map(String::as_str) != recovery_id {
244                return Err(AppError::cancelled("PREVIEW_REOPEN_BUSY"));
245            }
246            let limit = if recovery_id.is_some() { 13 } else { 12 };
247            if state.pages.len() + state.pending.len() + state.attaching.len() >= limit {
248                return Err(AppError::invalid_input("Browser page limit reached"));
249            }
250            state.pending.insert(id.clone(), profile.into());
251            state
252                .starting
253                .entry(profile.into())
254                .or_insert_with(|| Arc::new(Mutex::new(())))
255                .clone()
256        };
257        let _reservation = Reservation {
258            manager: self,
259            id: id.clone(),
260            profile: profile.into(),
261        };
262        let _gate = gate
263            .lock()
264            .map_err(|_| AppError::internal("Browser startup unavailable"))?;
265        let existing = {
266            let state = self
267                .state
268                .lock()
269                .map_err(|_| AppError::internal("Browser state unavailable"))?;
270            if state.closing {
271                return Err(AppError::cancelled("Preview is shutting down"));
272            }
273            state.runtimes.get(profile).cloned()
274        };
275        let runtime = if let Some(runtime) = existing {
276            runtime
277        } else {
278            let settings = self
279                .profiles()?
280                .into_iter()
281                .find(|item| item.id == profile)
282                .ok_or_else(|| AppError::not_found("Profile unavailable"))?;
283            let created =
284                Runtime::start(&self.root, &settings, |command: &mut Command, temporary| {
285                    let mut state = self
286                        .state
287                        .lock()
288                        .map_err(|_| AppError::internal("Browser state unavailable"))?;
289                    if state.closing {
290                        return Err(AppError::cancelled("Preview is shutting down"));
291                    }
292                    let child = Arc::new(Mutex::new(OwnedChild {
293                        process: command.spawn().map_err(AppError::io)?,
294                        _temporary_profile: temporary,
295                    }));
296                    state.processes.insert(profile.into(), child.clone());
297                    Ok(child)
298                });
299            let runtime = match created {
300                Ok(mut runtime) => {
301                    runtime.documents = Some(self.documents.clone());
302                    Arc::new(Mutex::new(runtime))
303                }
304                Err(error) => {
305                    let child = self
306                        .state
307                        .lock()
308                        .ok()
309                        .and_then(|mut state| state.processes.remove(profile));
310                    if let Some(child) = child {
311                        if let Ok(mut child) = child.lock() {
312                            let _ = child.process.kill();
313                            let _ = child.process.wait();
314                        }
315                    }
316                    return Err(error);
317                }
318            };
319            {
320                let mut state = self
321                    .state
322                    .lock()
323                    .map_err(|_| AppError::internal("Browser state unavailable"))?;
324                if state.closing {
325                    return Err(AppError::cancelled("Preview is shutting down"));
326                }
327                state.runtimes.insert(profile.into(), runtime.clone());
328            }
329            runtime
330        };
331        let (target, mut cdp) = {
332            let mut runtime = runtime
333                .lock()
334                .map_err(|_| AppError::internal("Browser runtime unavailable"))?;
335            let result = runtime.create_page(|target| {
336                self.state
337                    .lock()
338                    .map_err(|_| AppError::internal("Browser state unavailable"))?
339                    .pending_targets
340                    .insert(id.clone(), (profile.into(), target.into()));
341                Ok(())
342            });
343            match result {
344                Ok(result) => result,
345                Err(error) => {
346                    let target = self
347                        .state
348                        .lock()
349                        .map_err(|_| AppError::internal("Browser state unavailable"))?
350                        .pending_targets
351                        .get(&id)
352                        .map(|(_, target)| target.clone());
353                    if let Some(target) = target {
354                        let closed = runtime
355                            .cdp
356                            .call("Target.closeTarget", json!({"targetId":target}))
357                            .is_ok_and(|value| value["success"] == true);
358                        if !closed {
359                            if let Some(original) = recovery_id {
360                                self.keep_uncertain_replacement(original, profile, &target)?;
361                                return Err(AppError::network("PREVIEW_REOPEN_UNCERTAIN"));
362                            }
363                        }
364                    }
365                    return Err(error);
366                }
367            }
368        };
369        let mut opened_url = url.to_owned();
370        let setup = (|| {
371            opened_url = self.resolve_document_url(profile, url)?;
372            cdp.call(
373                "Emulation.setDeviceMetricsOverride",
374                json!({"width":1200,"height":800,"deviceScaleFactor":1,"mobile":false}),
375            )?;
376            let result = cdp.call("Page.navigate", json!({"url":opened_url}))?;
377            if result.get("errorText").is_some() {
378                return Err(AppError::network(
379                    result["errorText"].as_str().unwrap_or("Navigation failed"),
380                ));
381            }
382            Ok(())
383        })();
384        if let Err(error) = setup {
385            let closed = runtime.lock().ok().is_some_and(|mut runtime| {
386                runtime
387                    .cdp
388                    .call("Target.closeTarget", json!({"targetId":target}))
389                    .is_ok_and(|value| value["success"] == true)
390            });
391            if !closed {
392                if let Some(original) = recovery_id {
393                    self.keep_uncertain_replacement(original, profile, &target)?;
394                    return Err(AppError::network("PREVIEW_REOPEN_UNCERTAIN"));
395                }
396            }
397            return Err(error);
398        }
399        let execution = runtime
400            .lock()
401            .map_err(|_| AppError::internal("Browser runtime unavailable"))?
402            .execution;
403        let metadata = Arc::new(Mutex::new(BrowserPageInfo {
404            execution,
405            status: PageStatus::Connected,
406            id: id.clone(),
407            profile: profile.into(),
408            url: opened_url.clone(),
409            title: opened_url,
410            revision: String::new(),
411            owner,
412        }));
413        let page = Arc::new(Mutex::new(Page {
414            frame_info: None,
415            connection_generation: 0,
416            navigation_intent: 0,
417            snapshots: VecDeque::new(),
418            cdp,
419            width: 1200,
420            height: 800,
421            device_scale_factor: 1.,
422            mobile: false,
423            metadata: metadata.clone(),
424        }));
425        let mut state = self
426            .state
427            .lock()
428            .map_err(|_| AppError::internal("Browser state unavailable"))?;
429        if state.closing {
430            return Err(AppError::cancelled("Preview is shutting down"));
431        }
432        state.pages.insert(
433            id.clone(),
434            PageHandle {
435                profile: profile.into(),
436                target,
437                internal,
438                page,
439                metadata,
440            },
441        );
442        state.idle.remove(profile);
443        Ok(id)
444    }
445    fn keep_uncertain_replacement(
446        &self,
447        original: &str,
448        profile: &str,
449        target: &str,
450    ) -> Result<(), AppError> {
451        let mut state = self
452            .state
453            .lock()
454            .map_err(|_| AppError::internal("Browser state unavailable"))?;
455        if state.closing
456            || state.reopening_profiles.get(profile).map(String::as_str) != Some(original)
457        {
458            return Err(AppError::cancelled("PREVIEW_PAGE_GONE"));
459        }
460        let page = state
461            .pages
462            .get_mut(original)
463            .filter(|page| page.profile == profile)
464            .ok_or_else(|| AppError::not_found("PREVIEW_PAGE_GONE"))?;
465        page.target = target.into();
466        page.metadata
467            .lock()
468            .map_err(|_| AppError::internal("Browser metadata unavailable"))?
469            .status = PageStatus::Unverified;
470        state.lost_pages.remove(original);
471        Ok(())
472    }
473    pub fn page(&self, id: &str) -> Result<Arc<Mutex<Page>>, AppError> {
474        self.state
475            .lock()
476            .map_err(|_| AppError::internal("Browser state unavailable"))?
477            .pages
478            .get(id)
479            .map(|handle| handle.page.clone())
480            .ok_or_else(|| AppError::not_found("Browser page closed"))
481    }
482    pub fn close(&self, id: &str) -> Result<(), AppError> {
483        let _lease = {
484            let mut state = self
485                .state
486                .lock()
487                .map_err(|_| AppError::internal("Browser state unavailable"))?;
488            if let Some(page) = state.pages.get(id) {
489                if state.reopening_profiles.contains_key(&page.profile) && !page.internal {
490                    return Err(AppError::cancelled("PREVIEW_REOPEN_BUSY"));
491                }
492            }
493            if state.lost_pages.remove(id) {
494                if let Some(page) = state.pages.remove(id) {
495                    if !state
496                        .pages
497                        .values()
498                        .any(|item| item.profile == page.profile)
499                    {
500                        state.idle.insert(page.profile, Instant::now());
501                    }
502                }
503                return Ok(());
504            }
505            if let Some(page) = state.pages.get(id).cloned() {
506                if page.internal && state.reopening_profiles.contains_key(&page.profile) {
507                    None
508                } else {
509                    state
510                        .reopening_profiles
511                        .insert(page.profile.clone(), id.into());
512                    Some(ProfileLease {
513                        browsers: self,
514                        profile: page.profile,
515                        id: id.into(),
516                    })
517                }
518            } else {
519                return Ok(());
520            }
521        };
522        let (page, runtime) = {
523            let state = self
524                .state
525                .lock()
526                .map_err(|_| AppError::internal("Browser state unavailable"))?;
527            let Some(page) = state.pages.get(id).cloned() else {
528                return Ok(());
529            };
530            let runtime = state.runtimes.get(&page.profile).cloned().ok_or_else(|| {
531                AppError::network("Cannot verify page closure: runtime unavailable")
532            })?;
533            (page, runtime)
534        };
535        let result = runtime
536            .lock()
537            .map_err(|_| AppError::internal("Browser runtime unavailable"))?
538            .cdp
539            .call("Target.closeTarget", json!({"targetId":page.target}))?;
540        if result["success"] != true {
541            return Err(AppError::network("Browser did not confirm page closure"));
542        }
543        let mut state = self
544            .state
545            .lock()
546            .map_err(|_| AppError::internal("Browser state unavailable"))?;
547        if state
548            .pages
549            .get(id)
550            .is_some_and(|current| !Arc::ptr_eq(&current.page, &page.page))
551        {
552            return Err(AppError::cancelled("PREVIEW_REOPEN_BUSY"));
553        }
554        state.pages.remove(id);
555        if !state
556            .pages
557            .values()
558            .any(|item| item.profile == page.profile)
559        {
560            state.idle.insert(page.profile.clone(), Instant::now());
561        }
562        Ok(())
563    }
564    pub(super) fn runtime_handles(&self) -> Result<HashMap<String, Arc<Mutex<Runtime>>>, AppError> {
565        Ok(self
566            .state
567            .lock()
568            .map_err(|_| AppError::internal("Browser state unavailable"))?
569            .runtimes
570            .clone())
571    }
572    fn retire_idle(&self) {
573        let retired = {
574            let Ok(mut state) = self.state.lock() else {
575                return;
576            };
577            let profiles = state
578                .idle
579                .iter()
580                .filter(|(profile, time)| {
581                    time.elapsed() > Duration::from_secs(3)
582                        && !state.pending.values().any(|id| id == *profile)
583                        && !state
584                            .downloads
585                            .values()
586                            .any(|item| &item.profile == *profile && item.state == "inProgress")
587                })
588                .map(|(profile, _)| profile.clone())
589                .collect::<Vec<_>>();
590            let mut retired = Vec::new();
591            for profile in profiles {
592                if state.pages.values().any(|page| page.profile == profile) {
593                    state.idle.remove(&profile);
594                    continue;
595                }
596                retired.push((
597                    state.runtimes.remove(&profile),
598                    state.processes.remove(&profile),
599                ));
600                state.idle.remove(&profile);
601                state.starting.remove(&profile);
602            }
603            retired
604        };
605        for (runtime, process) in retired {
606            if let Some(process) = process {
607                if let Ok(mut process) = process.lock() {
608                    let _ = process.process.kill();
609                    let _ = process.process.wait();
610                }
611            }
612            drop(runtime);
613        }
614    }
615    pub fn clear(&self) {
616        let detached = {
617            let Ok(mut state) = self.state.lock() else {
618                return;
619            };
620            state.closing = true;
621            for cancel in state.document_builds.values() {
622                cancel.store(true, std::sync::atomic::Ordering::Release);
623            }
624            for job in state.transfers.values() {
625                job.cancel();
626            }
627            state.pages.clear();
628            (
629                std::mem::take(&mut state.runtimes),
630                std::mem::take(&mut state.processes),
631            )
632        };
633        for child in detached.1.values() {
634            if let Ok(mut child) = child.lock() {
635                let _ = child.process.kill();
636                let _ = child.process.wait();
637            }
638        }
639        drop(detached);
640        // Reap SSH descendants and remove staging files before shutdown returns.
641        let deadline = Instant::now() + Duration::from_secs(2);
642        while Instant::now() < deadline {
643            let active = self
644                .state
645                .lock()
646                .map(|state| state.transfers.values().any(|job| job.active()))
647                .unwrap_or(false);
648            if !active {
649                break;
650            }
651            std::thread::sleep(Duration::from_millis(30));
652        }
653    }
654}
655pub use super::navigation::validate_url;
656#[cfg(test)]
657#[path = "browser/tests.rs"]
658mod tests;