Skip to main content

agent_hub_runtime/core/preview/
page_actions.rs

1use super::{
2    super::error::AppError,
3    browser::{validate_url, Action, Browsers},
4};
5use serde_json::{json, Value};
6
7impl Browsers {
8    pub fn action(&self, id: &str, action: Action) -> Result<Value, AppError> {
9        if matches!(&action, Action::Devtools) {
10            return self.devtools_url(id).map(Value::String);
11        }
12        if let Action::ImportCookies { cookies } = &action {
13            return self.import_cookie_values(id, cookies.clone());
14        }
15        let page = self.page(id)?;
16        let intent = if matches!(
17            &action,
18            Action::Navigate { .. }
19                | Action::Back
20                | Action::Forward
21                | Action::Reload { .. }
22                | Action::Stop
23        ) {
24            let mut current = page
25                .lock()
26                .map_err(|_| AppError::internal("Browser page unavailable"))?;
27            current.navigation_intent = current.navigation_intent.wrapping_add(1);
28            Some((current.navigation_intent, current.connection_generation))
29        } else {
30            None
31        };
32        let action = if let Action::Navigate { url } = action {
33            let profile = self
34                .state
35                .lock()
36                .map_err(|_| AppError::internal("Browser state unavailable"))?
37                .pages
38                .get(id)
39                .map(|page| page.profile.clone())
40                .ok_or_else(|| AppError::not_found("Browser page unavailable"))?;
41            Action::Navigate {
42                url: self.resolve_document_url(&profile, &url)?,
43            }
44        } else {
45            action
46        };
47        let mut page = page
48            .lock()
49            .map_err(|_| AppError::internal("Browser page unavailable"))?;
50        if intent
51            .is_some_and(|intent| intent != (page.navigation_intent, page.connection_generation))
52        {
53            return Err(AppError::cancelled(
54                "Navigation was superseded; inspect the current page",
55            ));
56        }
57        if intent.is_some() {
58            page.frame_info = None;
59        }
60        match action {
61            Action::Devtools => unreachable!("handled before page locking"),
62            Action::SetTheme { dark, .. } => page.cdp.call("Emulation.setEmulatedMedia", json!({ "features": [{ "name": "prefers-color-scheme", "value": if dark { "dark" } else { "light" } }] })),
63            Action::VerifyRevision {expected_revision} => {
64                if page.identity()?.0 != expected_revision { return Err(AppError::cancelled("PREVIEW_CONTEXT_CHANGED")); }
65                Ok(Value::Null)
66            }
67            Action::HandleDialog {accept,prompt} => {
68                let result = page.cdp.call("Page.handleJavaScriptDialog",json!({"accept":accept,"promptText":prompt.unwrap_or_default()}))?;
69                page.cdp.dialog = None;
70                Ok(result)
71            }
72            Action::CancelUpload {token} => {
73                if page.cdp.chooser.as_ref().is_some_and(|chooser|chooser["token"]==token) { page.cdp.chooser = None; }
74                Ok(Value::Null)
75            }
76
77            Action::InspectRef {reference} => {
78                page.validate_reference(&reference)?;
79                let (revision,url)=page.identity()?;
80                let value=page.cdp.evaluate(&super::scripts::reference(&reference,super::scripts::ReferenceAction::Inspect)?)?;
81                page.validate_reference(&reference)?;
82                super::capture::normalize(value,revision,url)
83            }
84            Action::ClickRef {reference} => {
85                page.validate_reference(&reference)?;
86                let encoded=serde_json::to_string(&reference).map_err(|error|AppError::invalid_input(error.to_string()))?;
87                let position=page.cdp.evaluate(&format!("(()=>{{const [token,index]={encoded}.split(':');const snapshot=window.__agentHubSnapshots?.get(token);if(snapshot?.url!==location.href)throw Error('Snapshot expired');const node=snapshot?.nodes[Number(index)];if(!node?.isConnected)throw Error('Snapshot expired');node.scrollIntoView({{block:'center',inline:'center'}});const box=node.getBoundingClientRect();const scale=visualViewport?.scale||1;return {{x:(box.x+box.width/2-(visualViewport?.offsetLeft||0))*scale,y:(box.y+box.height/2-(visualViewport?.offsetTop||0))*scale}}}})()"))?;
88                page.validate_reference(&reference)?;
89                for event in ["mousePressed","mouseReleased"] { page.cdp.call("Input.dispatchMouseEvent",json!({"type":event,"x":position["x"],"y":position["y"],"button":"left","clickCount":1}))?; }
90                Ok(Value::Null)
91            }
92            Action::FillRef {reference,value} => {
93                page.validate_reference(&reference)?;
94                if value.len()>64*1024{return Err(AppError::invalid_input("Input exceeds limit"));}
95                let reference=serde_json::to_string(&reference).map_err(|error|AppError::invalid_input(error.to_string()))?;
96                let value=serde_json::to_string(&value).map_err(|error|AppError::invalid_input(error.to_string()))?;
97                page.cdp.evaluate(&format!("(()=>{{const [token,index]={reference}.split(':');const snapshot=window.__agentHubSnapshots?.get(token);if(snapshot?.url!==location.href)throw Error('Snapshot expired');const node=snapshot?.nodes[Number(index)];if(!node?.isConnected||node.disabled||node.readOnly)throw Error('Input unavailable');node.focus();const setter=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(node),'value')?.set;if(setter)setter.call(node,{value});else if(node.isContentEditable)node.textContent={value};else throw Error('Element is not editable');node.dispatchEvent(new Event('input',{{bubbles:true}}));node.dispatchEvent(new Event('change',{{bubbles:true}}));return true}})()"))
98            }
99
100            Action::Navigate { url } => { validate_url(&url)?; page.cdp.call("Page.navigate", json!({ "url": url })) }
101            Action::Reload { hard } => page.cdp.call("Page.reload", json!({ "ignoreCache": hard })),
102            Action::Stop => page.cdp.call("Page.stopLoading", json!({})),
103            Action::Back | Action::Forward => {
104                let direction = if matches!(action, Action::Back) { -1 } else { 1 };
105                let history = page.cdp.call("Page.getNavigationHistory", json!({}))?;
106                let index = history["currentIndex"].as_i64().unwrap_or_default() + direction;
107                if index < 0 { return Ok(Value::Null); }
108                match history["entries"][index as usize]["id"].as_i64() {
109                    Some(entry) => page.cdp.call("Page.navigateToHistoryEntry", json!({ "entryId": entry })), None => Ok(Value::Null)
110                }
111            }
112            Action::Resize { width, height, mobile, device_scale_factor } => {
113                if !(240..=3840).contains(&width) || !(200..=2160).contains(&height) { return Err(AppError::invalid_input("Viewport dimensions are outside the supported range")); }
114                let density = device_scale_factor.unwrap_or(1.);
115                if !density.is_finite() || !(1. ..=2.).contains(&density) { return Err(AppError::invalid_input("Device scale factor must be between 1 and 2")); }
116                page.frame_info = None;
117                page.cdp.configure_frames(width, height, mobile, density)?;
118                page.width = width; page.height = height;page.mobile=mobile;page.device_scale_factor=density;page.cdp.frame=None;
119                Ok(Value::Null)
120            }
121            Action::Mouse { x, y, event, button, delta_x, delta_y } => {
122                if !x.is_finite() || !y.is_finite() || x < 0. || y < 0. || x > f64::from(page.width) || y > f64::from(page.height) { return Err(AppError::invalid_input("Pointer is outside the page")); }
123                if !["mousePressed", "mouseReleased", "mouseMoved", "mouseWheel"].contains(&event.as_str()) { return Err(AppError::invalid_input("Invalid pointer event")); }
124                let button = button.unwrap_or_else(|| "left".into());
125                if !["left", "right", "middle", "none"].contains(&button.as_str()) { return Err(AppError::invalid_input("Invalid pointer button")); }
126                let mut params = json!({ "type":event,"x":x,"y":y,"button":button,"clickCount":1 });
127                params["buttons"] = json!(if event == "mouseReleased" || event == "mouseWheel" {0} else {match button.as_str(){"left"=>1,"right"=>2,"middle"=>4,_=>0}});
128                if event == "mouseWheel" { params["deltaX"] = json!(delta_x.filter(|value| value.is_finite()).unwrap_or(0.).clamp(-2000., 2000.)); params["deltaY"] = json!(delta_y.filter(|value| value.is_finite()).unwrap_or(0.).clamp(-2000., 2000.)); }
129                page.cdp.call("Input.dispatchMouseEvent", params)
130            }
131            Action::Text { text } => {
132                if text.len() > 64 * 1024 { return Err(AppError::invalid_input("Input exceeds limit")); }
133                page.cdp.call("Input.insertText", json!({"text":text}))
134            }
135            Action::Key { key, code, modifiers } => {
136                if key.len() > 64 || code.len() > 64 || modifiers > 15 { return Err(AppError::invalid_input("Invalid key")); }
137                let key_code = match key.as_str() { "Backspace"=>8,"Tab"=>9,"Enter"=>13,"Escape"=>27,"ArrowLeft"=>37,"ArrowUp"=>38,"ArrowRight"=>39,"ArrowDown"=>40,"Delete"=>46,"Home"=>36,"End"=>35,_ if key.len()==1=>u32::from(key.as_bytes()[0].to_ascii_uppercase()),_=>0 };
138                let params = json!({"type":"keyDown","key":key,"code":code,"modifiers":modifiers,"windowsVirtualKeyCode":key_code});
139                page.cdp.call("Input.dispatchKeyEvent", params)?;
140                page.cdp.call("Input.dispatchKeyEvent", json!({"type":"keyUp","key":key,"code":code,"modifiers":modifiers,"windowsVirtualKeyCode":key_code}))
141            }
142            Action::Evaluate { expression } => page.cdp.evaluate(&expression),
143            Action::Pick { x, y } => {
144                if !x.is_finite() || !y.is_finite() { return Err(AppError::invalid_input("Invalid pick position")); }
145                let (revision,url)=page.identity()?;
146                let value=page.cdp.evaluate(&format!("({})({}, {})", super::scripts::picker(), x, y))?;
147                if !value.is_object(){return Ok(Value::Null);}
148                if page.identity()?.0 != revision { return Err(AppError::cancelled("Page changed during selection")); }
149                super::capture::normalize(value,revision,url)
150            }
151            Action::Snapshot => {
152                let (revision,url)=page.identity()?;
153                let token = uuid::Uuid::new_v4().simple().to_string();
154                let mut value = page.cdp.evaluate(&super::scripts::snapshot(&token))?;
155                if !value.is_object() || page.identity()?.0 != revision {return Err(AppError::cancelled("Page changed during snapshot"));}
156                if page.snapshots.len() >= 8 { page.snapshots.pop_front(); }
157                page.snapshots.push_back((token, revision.clone()));
158                value["revision"]=json!(revision);value["url"]=json!(url);Ok(value)
159            },
160            Action::Screenshot { full, clip, expected_revision } => {
161                let (revision,_)=page.identity()?;
162                if expected_revision.as_ref().is_some_and(|expected|expected!=&revision){return Err(AppError::cancelled("PREVIEW_CONTEXT_CHANGED"));}
163                let mut params = json!({ "format":"png", "captureBeyondViewport": full });
164                if full {
165                    let layout = page.cdp.call("Page.getLayoutMetrics", json!({}))?;
166                    let size = &layout["cssContentSize"];
167                    let w = size["width"].as_f64().unwrap_or(0.); let h = size["height"].as_f64().unwrap_or(0.);
168                    if w <= 0. || h <= 0. || w * h > 32_000_000. { return Err(AppError::invalid_input("Page exceeds the full-page screenshot limit")); }
169                    params["clip"] = json!({"x":0,"y":0,"width":w,"height":h,"scale":1});
170                } else if let Some(clip) = clip {
171                    for field in ["x", "y", "width", "height"] { let value = clip[field].as_f64().ok_or_else(|| AppError::invalid_input("Invalid capture bounds"))?; if !value.is_finite() || value < 0. { return Err(AppError::invalid_input("Invalid capture bounds")); } }
172                    if clip["width"].as_f64().unwrap_or(0.) * clip["height"].as_f64().unwrap_or(0.) > 32_000_000. { return Err(AppError::invalid_input("Capture exceeds limit")); }
173                    params["clip"] = clip; params["clip"]["scale"] = json!(1); params["captureBeyondViewport"] = json!(true);
174                }
175                let result = page.cdp.call("Page.captureScreenshot", params)?;
176                if page.identity()?.0 != revision { return Err(AppError::cancelled("Page changed during capture")); }
177                if result["data"].as_str().is_some_and(|data| data.len() <= 24 * 1024 * 1024) { Ok(result) } else { Err(AppError::invalid_input("Screenshot is unavailable or exceeds limit")) }
178            }
179            Action::Find { text, backwards } => page.cdp.evaluate(&super::scripts::find(&text, backwards)?),
180            Action::Cookies => page.cdp.call("Network.getAllCookies", json!({})),
181            Action::ImportCookies { .. } => Err(AppError::internal("Cookie import was not dispatched")),
182            Action::Storage => page.cdp.evaluate(super::scripts::STORAGE),
183        }
184    }
185}
186
187impl super::browser::Page {
188    fn validate_reference(&mut self, reference: &str) -> Result<(), AppError> {
189        let (token, index) = reference
190            .split_once(':')
191            .ok_or_else(|| AppError::invalid_input("Invalid snapshot reference"))?;
192        if reference.len() > 100 || index.parse::<usize>().map_or(true, |index| index >= 500) {
193            return Err(AppError::invalid_input("Invalid snapshot reference"));
194        }
195        let revision = self.identity()?.0;
196        if !self
197            .snapshots
198            .iter()
199            .any(|(stored, value)| stored == token && value == &revision)
200        {
201            return Err(AppError::cancelled("Snapshot expired; take a new snapshot"));
202        }
203        Ok(())
204    }
205}