Skip to main content

nexo_plugin_browser/
plugin.rs

1//! Subprocess-side BrowserPlugin: launches Chrome, attaches a CDP
2//! session, dispatches [`BrowserCmd`] → [`BrowserResult`].
3//!
4//! Phase 81.17.c.crates-publish slim-down — the in-tree daemon
5//! integration (broker bridge, circuit breaker, `Plugin` /
6//! `NexoPlugin` trait impls, manifest parsing) was removed
7//! because the subprocess flow handles those concerns at the
8//! `nexo_microapp_sdk::plugin::PluginAdapter` layer:
9//!
10//! - **Broker bridge**: PluginAdapter publishes/consumes broker
11//!   events through the daemon-routed JSON-RPC stdio frames.
12//! - **Manifest**: `include_str!("../nexo-plugin.toml")` is
13//!   parsed once by PluginAdapter::new — no need for a second
14//!   `cached_manifest`.
15//! - **Plugin trait**: irrelevant for subprocess plugins; the
16//!   daemon's `SubprocessNexoPlugin` adapter speaks the wire
17//!   protocol on the host side.
18//! - **CircuitBreaker**: replaced by per-command timeouts;
19//!   subprocess crashes / supervisor logic live in
20//!   `nexo-core::nexo_plugin_registry` (Phase 81.21).
21//!
22//! What remains is the minimal CDP driver — enough for
23//! `dispatch.rs` to translate every `tool.invoke` into a
24//! `BrowserCmd` and call `execute`.
25
26use std::sync::Arc;
27use std::time::Duration;
28
29use base64::Engine;
30use tokio::sync::Mutex;
31
32use nexo_cdp::{CdpClient, CdpSession};
33use nexo_config::BrowserConfig;
34
35use crate::chrome::{ChromeLauncher, RunningChrome};
36use crate::command::{BrowserCmd, BrowserResult};
37
38/// Single-Chrome-instance state shared across the subprocess
39/// lifetime. `Arc<Mutex<...>>` so the caller can cheaply clone
40/// references into futures.
41pub struct BrowserPlugin {
42    inner: Arc<BrowserInner>,
43}
44
45struct BrowserInner {
46    config: BrowserConfig,
47    session: Mutex<Option<CdpSession>>,
48    chrome: Mutex<Option<RunningChrome>>,
49}
50
51impl BrowserPlugin {
52    pub fn new(config: BrowserConfig) -> Self {
53        Self {
54            inner: Arc::new(BrowserInner {
55                config,
56                session: Mutex::new(None),
57                chrome: Mutex::new(None),
58            }),
59        }
60    }
61
62    /// Execute one CDP command. Reuses the existing
63    /// session-or-launch flow; lazy-boots Chrome on the first
64    /// call. Per-command timeout from
65    /// `BrowserConfig.command_timeout_ms`.
66    pub async fn execute(&self, cmd: BrowserCmd) -> BrowserResult {
67        if let Err(e) = self.inner.ensure_session().await {
68            return BrowserResult::err(format!("session init failed: {e}"));
69        }
70        let mut lock = self.inner.session.lock().await;
71        let Some(session) = lock.as_mut() else {
72            return BrowserResult::err("no active session");
73        };
74        let timeout = Duration::from_millis(self.inner.config.command_timeout_ms);
75        match cmd {
76            BrowserCmd::Navigate { url } => {
77                match tokio::time::timeout(timeout, session.navigate(&url)).await {
78                    Ok(Ok(())) => BrowserResult::ok(),
79                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
80                    Err(_) => BrowserResult::err("navigate timed out"),
81                }
82            }
83            BrowserCmd::Click { target } => {
84                match tokio::time::timeout(timeout, session.click(&target)).await {
85                    Ok(Ok(())) => BrowserResult::ok(),
86                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
87                    Err(_) => BrowserResult::err("click timed out"),
88                }
89            }
90            BrowserCmd::Fill { target, value } => {
91                match tokio::time::timeout(timeout, session.fill(&target, &value)).await {
92                    Ok(Ok(())) => BrowserResult::ok(),
93                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
94                    Err(_) => BrowserResult::err("fill timed out"),
95                }
96            }
97            BrowserCmd::Screenshot => {
98                match tokio::time::timeout(timeout, session.screenshot()).await {
99                    Ok(Ok(bytes)) => {
100                        let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
101                        BrowserResult::ok_screenshot(b64)
102                    }
103                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
104                    Err(_) => BrowserResult::err("screenshot timed out"),
105                }
106            }
107            BrowserCmd::Evaluate { script } => {
108                match tokio::time::timeout(timeout, session.evaluate(&script)).await {
109                    Ok(Ok(v)) => BrowserResult::ok_value(v),
110                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
111                    Err(_) => BrowserResult::err("evaluate timed out"),
112                }
113            }
114            BrowserCmd::Snapshot => {
115                match tokio::time::timeout(timeout, session.snapshot()).await {
116                    Ok(Ok(text)) => BrowserResult::ok_snapshot(text),
117                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
118                    Err(_) => BrowserResult::err("snapshot timed out"),
119                }
120            }
121            BrowserCmd::ScrollTo { target } => {
122                match tokio::time::timeout(timeout, session.scroll_to(&target)).await {
123                    Ok(Ok(())) => BrowserResult::ok(),
124                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
125                    Err(_) => BrowserResult::err("scroll_to timed out"),
126                }
127            }
128        }
129    }
130}
131
132impl BrowserInner {
133    async fn ensure_session(self: &Arc<Self>) -> anyhow::Result<()> {
134        let mut session_lock = self.session.lock().await;
135        if session_lock.is_some() {
136            return Ok(());
137        }
138
139        let ws_url = if self.config.cdp_url.is_empty() {
140            let chrome = ChromeLauncher::launch(&self.config).await?;
141            let ws = chrome.ws_url.clone();
142            *self.chrome.lock().await = Some(chrome);
143            ws
144        } else {
145            ChromeLauncher::connect_existing(&self.config.cdp_url, self.config.connect_timeout_ms)
146                .await?
147        };
148
149        let client = Arc::new(CdpClient::connect(&ws_url).await?);
150
151        if let Err(e) = client.send("Page.enable", serde_json::json!({})).await {
152            tracing::warn!(error = %e, "Page.enable failed — navigation events may be missing");
153        }
154
155        let target_id = get_first_target_id(&ws_url, self.config.connect_timeout_ms).await?;
156        let session = CdpSession::new(
157            Arc::clone(&client),
158            &target_id,
159            self.config.command_timeout_ms,
160        )
161        .await?;
162        *session_lock = Some(session);
163        Ok(())
164    }
165}
166
167async fn get_first_target_id(ws_url: &str, timeout_ms: u64) -> anyhow::Result<String> {
168    let http_url = ws_url
169        .replace("ws://", "http://")
170        .replace("wss://", "https://");
171    let base = if let Some(idx) = http_url.find("/devtools/") {
172        http_url[..idx].to_string()
173    } else {
174        http_url
175    };
176
177    let client = reqwest::Client::builder()
178        .timeout(std::time::Duration::from_millis(timeout_ms))
179        .build()?;
180    let targets: Vec<serde_json::Value> = client
181        .get(format!("{base}/json/list"))
182        .header(reqwest::header::HOST, "localhost")
183        .send()
184        .await?
185        .json()
186        .await?;
187
188    targets
189        .iter()
190        .find(|t| t.get("type").and_then(|v| v.as_str()) == Some("page"))
191        .and_then(|t| t.get("id").and_then(|v| v.as_str()))
192        .map(|s| s.to_string())
193        .ok_or_else(|| anyhow::anyhow!("no page target found in Chrome"))
194}