Skip to main content

cdp_driver/
agent.rs

1//! Running [`BrowserAction`]s against a tab and reporting how each one went.
2
3use serde_json::{Value, json};
4use tokio::sync::broadcast;
5
6use crate::action_parse::parse_action;
7use crate::client::CdpClient;
8use crate::config::Config;
9use crate::error::{CdpError, Result};
10use crate::keys::key_info;
11use crate::types::ConsoleMessage;
12
13// Re-exported so `crate::agent::{BrowserAction, ActionBuilder}` keeps resolving
14// now that these live in their own modules.
15pub use crate::action::BrowserAction;
16pub use crate::action_builder::ActionBuilder;
17
18/// How often `WaitForSelector` re-checks the page.
19const SELECTOR_POLL_MS: u64 = 100;
20
21/// How many console messages may queue before the oldest are dropped.
22const CONSOLE_BACKLOG: usize = 64;
23
24/// Render `s` as a JavaScript string literal, so a selector or value containing
25/// quotes cannot break out of the expression it is spliced into.
26fn quote(s: &str) -> String {
27    serde_json::to_string(s).unwrap_or_else(|_| format!("\"{}\"", s.replace('"', "\\\"")))
28}
29
30/// Outcome of [`BrowserAgent::execute`]. Errors are captured as strings rather than
31/// propagated so a batch of actions ([`BrowserAgent::execute_many`]) can run to
32/// completion and report per-action success/failure.
33#[derive(Debug, Clone)]
34pub struct ActionResult {
35    /// Whether the action completed without error.
36    pub success: bool,
37    /// The action's return value, when it produces one and succeeded.
38    pub value: Option<Value>,
39    /// The error message, when `success` is `false`.
40    pub error: Option<String>,
41}
42
43impl ActionResult {
44    /// Shorthand for `self.success`.
45    pub fn is_success(&self) -> bool {
46        self.success
47    }
48
49    /// The outcome of an action that raised `error`.
50    fn failed(error: impl std::fmt::Display) -> Self {
51        ActionResult {
52            success: false,
53            value: None,
54            error: Some(error.to_string()),
55        }
56    }
57}
58
59impl std::fmt::Display for ActionResult {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        if self.success {
62            write!(f, "Ok({:?})", self.value)
63        } else {
64            write!(f, "Err({})", self.error.as_deref().unwrap_or("unknown"))
65        }
66    }
67}
68
69/// Drives a single browser tab via [`BrowserAction`]s. Wraps a [`CdpClient`] with
70/// `Page`, `Runtime`, `DOM`, and `Network` already enabled.
71pub struct BrowserAgent {
72    client: CdpClient,
73}
74
75impl BrowserAgent {
76    /// Connect to the first available page target and enable the domains actions
77    /// depend on.
78    pub async fn connect(host: &str, port: u16) -> Result<Self> {
79        let client = CdpClient::connect_to_page(host, port).await?;
80        for domain in ["Page", "Runtime", "DOM", "Network"] {
81            client.enable_domain(domain).await?;
82        }
83        Ok(BrowserAgent { client })
84    }
85
86    /// [`connect`](Self::connect) using `config.host`/`config.port`, then apply
87    /// `config`'s viewport size.
88    pub async fn connect_with_config(config: &Config) -> Result<Self> {
89        let agent = Self::connect(&config.host, config.port).await?;
90        agent
91            .client
92            .set_viewport(config.viewport_width, config.viewport_height, false)
93            .await?;
94        Ok(agent)
95    }
96
97    /// Wrap an already-connected client (domains are the caller's responsibility).
98    pub fn from_client(client: CdpClient) -> Self {
99        BrowserAgent { client }
100    }
101
102    /// Close the underlying tab.
103    pub async fn close(&self) -> Result<()> {
104        self.client.close().await
105    }
106
107    /// Start capturing `console.*` calls from the page. Returns a receiver that
108    /// yields each call as a [`ConsoleMessage`]; capture continues until the agent
109    /// (and its underlying client) is dropped.
110    pub fn capture_console(&self) -> broadcast::Receiver<ConsoleMessage> {
111        let (tx, rx) = broadcast::channel(CONSOLE_BACKLOG);
112        let mut events = self.client.subscribe_events();
113        tokio::spawn(async move {
114            while let Ok((method, params)) = events.recv().await {
115                if method != "Runtime.consoleAPICalled" {
116                    continue;
117                }
118                let level = params["type"].as_str().unwrap_or("log").to_string();
119                let text = params["args"]
120                    .as_array()
121                    .and_then(|args| args.first())
122                    .and_then(|a| a["value"].as_str())
123                    .unwrap_or("")
124                    .to_string();
125                let url = params["stackTrace"]["callFrames"][0]["url"]
126                    .as_str()
127                    .map(str::to_owned);
128                let line = params["stackTrace"]["callFrames"][0]["lineNumber"].as_u64();
129                let _ = tx.send(ConsoleMessage {
130                    level,
131                    text,
132                    url,
133                    line,
134                });
135            }
136        });
137        rx
138    }
139
140    /// Run one action, capturing success/failure into an [`ActionResult`] instead of
141    /// returning `Result`.
142    pub async fn execute(&self, action: BrowserAction) -> ActionResult {
143        match self.dispatch(action).await {
144            Ok(value) => ActionResult {
145                success: true,
146                value: Some(value),
147                error: None,
148            },
149            Err(e) => ActionResult::failed(e),
150        }
151    }
152
153    /// Run each action in `actions` in order, continuing even if one fails.
154    pub async fn execute_many(&self, actions: Vec<BrowserAction>) -> Vec<ActionResult> {
155        let mut results = Vec::with_capacity(actions.len());
156        for action in actions {
157            results.push(self.execute(action).await);
158        }
159        results
160    }
161
162    /// Parse `json_str` as a [`BrowserAction`] (e.g. `{"action": "navigate", "url":
163    /// "..."}`) and run it. Suited for dispatching LLM tool calls directly.
164    pub async fn execute_json(&self, json_str: &str) -> ActionResult {
165        match parse_action(json_str) {
166            Ok(action) => self.execute(action).await,
167            Err(e) => ActionResult::failed(e),
168        }
169    }
170
171    async fn dispatch(&self, action: BrowserAction) -> Result<Value> {
172        match action {
173            BrowserAction::Navigate { url } => {
174                let nav = self.client.navigate(&url).await?;
175                Ok(json!({ "frameId": nav.frame_id }))
176            }
177            BrowserAction::GoBack => self.client.send_command("Page.goBack", json!({})).await,
178            BrowserAction::GoForward => self.client.send_command("Page.goForward", json!({})).await,
179            BrowserAction::Reload => self.client.send_command("Page.reload", json!({})).await,
180
181            BrowserAction::Click { selector, x, y } => {
182                if let Some(sel) = selector {
183                    self.client
184                        .eval(&format!("document.querySelector({})?.click()", quote(&sel)))
185                        .await?;
186                } else if let (Some(cx), Some(cy)) = (x, y) {
187                    for event_type in ["mousePressed", "mouseReleased"] {
188                        self.client
189                            .send_command(
190                                "Input.dispatchMouseEvent",
191                                json!({
192                                    "type": event_type, "x": cx, "y": cy,
193                                    "button": "left", "clickCount": 1,
194                                }),
195                            )
196                            .await?;
197                    }
198                } else {
199                    return Err(CdpError::Protocol("click: need selector or (x, y)".into()));
200                }
201                Ok(json!(null))
202            }
203
204            BrowserAction::Type { text, selector } => {
205                if let Some(sel) = selector {
206                    self.client
207                        .eval(&format!("document.querySelector({})?.focus()", quote(&sel)))
208                        .await?;
209                }
210                self.client
211                    .send_command("Input.insertText", json!({ "text": text }))
212                    .await?;
213                Ok(json!(null))
214            }
215
216            BrowserAction::Fill { selector, value } => {
217                self.client
218                    .eval(&format!(
219                        "(sel => {{ \
220                        let el = document.querySelector(sel); \
221                        if (!el) return; \
222                        el.focus(); \
223                        el.value = {}; \
224                        el.dispatchEvent(new Event('input', {{bubbles:true}})); \
225                        el.dispatchEvent(new Event('change', {{bubbles:true}})); \
226                    }})({})",
227                        quote(&value),
228                        quote(&selector),
229                    ))
230                    .await?;
231                Ok(json!(null))
232            }
233
234            BrowserAction::Submit { selector } => {
235                let sel = selector.as_deref().unwrap_or("form");
236                self.client
237                    .eval(&format!("document.querySelector({})?.submit()", quote(sel)))
238                    .await?;
239                Ok(json!(null))
240            }
241
242            BrowserAction::PressKey { key } => {
243                let (code, vk) = key_info(&key);
244                self.client
245                    .send_command(
246                        "Input.dispatchKeyEvent",
247                        json!({
248                            "type": "keyDown", "key": key, "code": code,
249                            "windowsVirtualKeyCode": vk,
250                        }),
251                    )
252                    .await?;
253                self.client
254                    .send_command(
255                        "Input.dispatchKeyEvent",
256                        json!({
257                            "type": "keyUp", "key": key, "code": code,
258                        }),
259                    )
260                    .await?;
261                Ok(json!(null))
262            }
263
264            BrowserAction::GetTitle => Ok(json!(self.client.eval("document.title").await?)),
265            BrowserAction::GetUrl => Ok(json!(self.client.eval("window.location.href").await?)),
266            BrowserAction::GetText => Ok(json!(self.client.eval("document.body.innerText").await?)),
267
268            BrowserAction::GetContent { selector } => {
269                let expr = match selector {
270                    Some(sel) => format!("document.querySelector({})?.innerHTML", quote(&sel)),
271                    None => "document.documentElement.outerHTML".into(),
272                };
273                Ok(json!(self.client.eval(&expr).await?))
274            }
275
276            BrowserAction::GetLinks => {
277                let ev = self
278                    .client
279                    .evaluate(
280                        "Array.from(document.querySelectorAll('a'))\
281                     .map(a => ({ href: a.href, text: a.innerText.trim() }))",
282                    )
283                    .await?;
284                Ok(ev.result.value.unwrap_or(json!([])))
285            }
286
287            BrowserAction::GetAttributes { selector } => {
288                let ev = self
289                    .client
290                    .evaluate(&format!(
291                        "(sel => {{ \
292                        let el = document.querySelector(sel); \
293                        if (!el) return null; \
294                        let attrs = {{}}; \
295                        for (let a of el.attributes) attrs[a.name] = a.value; \
296                        return attrs; \
297                    }})({})",
298                        quote(&selector)
299                    ))
300                    .await?;
301                Ok(ev.result.value.unwrap_or(json!(null)))
302            }
303
304            BrowserAction::Exists { selector } => {
305                let ev = self
306                    .client
307                    .evaluate(&format!("!!document.querySelector({})", quote(&selector)))
308                    .await?;
309                Ok(ev.result.value.unwrap_or(json!(false)))
310            }
311
312            BrowserAction::Screenshot { path } => match path {
313                Some(p) => {
314                    self.client.full_page_screenshot_to_file(&p).await?;
315                    Ok(json!(p))
316                }
317                None => Ok(json!(self.client.full_page_screenshot().await?.len())),
318            },
319
320            BrowserAction::Evaluate { expression } => {
321                let ev = self.client.evaluate(&expression).await?;
322                Ok(ev.result.value.unwrap_or(json!(null)))
323            }
324
325            BrowserAction::Wait { ms } => {
326                tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
327                Ok(json!(null))
328            }
329
330            BrowserAction::WaitForSelector {
331                selector,
332                timeout_ms,
333            } => {
334                let deadline =
335                    std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
336                let expr = format!("!!document.querySelector({})", quote(&selector));
337                loop {
338                    let ev = self.client.evaluate(&expr).await?;
339                    if ev.result.value == Some(json!(true)) {
340                        return Ok(json!(true));
341                    }
342                    if std::time::Instant::now() >= deadline {
343                        return Err(CdpError::Timeout);
344                    }
345                    tokio::time::sleep(std::time::Duration::from_millis(SELECTOR_POLL_MS)).await;
346                }
347            }
348
349            BrowserAction::Scroll { x, y } => {
350                self.client
351                    .eval(&format!("window.scrollTo({x}, {y})"))
352                    .await?;
353                Ok(json!(null))
354            }
355
356            BrowserAction::SetViewport {
357                width,
358                height,
359                mobile,
360            } => {
361                self.client.set_viewport(width, height, mobile).await?;
362                Ok(json!(null))
363            }
364
365            BrowserAction::GetMetrics => {
366                self.client
367                    .send_command("Performance.getMetrics", json!({}))
368                    .await
369            }
370        }
371    }
372}