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//! This is the minimal CDP driver only. Daemon-integration
5//! concerns are handled elsewhere:
6//!
7//! - **Broker bridge**: `nexo_microapp_sdk::plugin::PluginAdapter`
8//!   publishes/consumes broker events through the daemon-routed
9//!   JSON-RPC stdio frames.
10//! - **Manifest**: `include_str!("../nexo-plugin.toml")` is
11//!   parsed once by `PluginAdapter::new`.
12//! - **Plugin trait**: irrelevant for subprocess plugins; the
13//!   daemon's `SubprocessNexoPlugin` adapter speaks the wire
14//!   protocol on the host side.
15//! - **CircuitBreaker**: replaced by per-command timeouts;
16//!   subprocess crash / supervisor logic lives in
17//!   `nexo-core::nexo_plugin_registry`.
18//!
19//! `dispatch.rs` translates every `tool.invoke` into a
20//! `BrowserCmd` and calls `execute`.
21
22use std::sync::atomic::{AtomicBool, Ordering};
23use std::sync::Arc;
24use std::time::Duration;
25
26use base64::Engine;
27use tokio::sync::Mutex;
28
29use nexo_cdp::{CdpClient, CdpSession};
30use crate::config::BrowserConfig;
31
32use crate::chrome::{ChromeLauncher, RunningChrome};
33use crate::command::{BrowserCmd, BrowserResult};
34
35/// Single-Chrome-instance state shared across the subprocess
36/// lifetime. `Arc<Mutex<...>>` so the caller can cheaply clone
37/// references into futures.
38pub struct BrowserPlugin {
39    inner: Arc<BrowserInner>,
40}
41
42struct BrowserInner {
43    config: BrowserConfig,
44    session: Mutex<Option<CdpSession>>,
45    chrome: Mutex<Option<RunningChrome>>,
46    /// Follow-up `browser.launch_visible.runtime`. When `true`,
47    /// the next lazy-boot flips `headless = false` regardless of
48    /// the configured value, then clears the flag. Set by the
49    /// admin RPC `launch_visible` after it shuts the current
50    /// Chrome down.
51    headless_override_off: AtomicBool,
52}
53
54impl BrowserPlugin {
55    pub fn new(config: BrowserConfig) -> Self {
56        Self {
57            inner: Arc::new(BrowserInner {
58                config,
59                session: Mutex::new(None),
60                chrome: Mutex::new(None),
61                headless_override_off: AtomicBool::new(false),
62            }),
63        }
64    }
65
66    /// Follow-up `browser.launch_visible.runtime` — request the
67    /// next lazy-boot to spawn a non-headless Chrome regardless
68    /// of the configured `headless` flag. One-shot: the flag
69    /// resets to `false` after the override fires.
70    pub fn request_visible_next_boot(&self) {
71        self.inner.headless_override_off.store(true, Ordering::SeqCst);
72    }
73
74    fn instance_label_for_metrics(&self) -> String {
75        self.inner
76            .config
77            .instance
78            .clone()
79            .unwrap_or_else(|| "default".into())
80    }
81
82    /// Borrow this instance's `allow_agents` slice for routing
83    /// gates. Empty ⇒ accept any caller (back-compat).
84    pub fn allow_agents(&self) -> &[String] {
85        &self.inner.config.allow_agents
86    }
87
88    /// Borrow this instance's resolved `user_data_dir` — used by
89    /// admin RPC `mark_paired` (Step 7) to locate the sentinel file.
90    pub fn user_data_dir(&self) -> &str {
91        &self.inner.config.user_data_dir
92    }
93
94    /// Borrow the instance's owned config snapshot. Useful for the
95    /// admin RPC `list_instances` reply.
96    pub fn config_snapshot(&self) -> &BrowserConfig {
97        &self.inner.config
98    }
99
100    /// Execute one CDP command. Reuses the existing
101    /// session-or-launch flow; lazy-boots Chrome on the first
102    /// call. Per-command timeout from
103    /// `BrowserConfig.command_timeout_ms`.
104    pub async fn execute(&self, cmd: BrowserCmd) -> BrowserResult {
105        if let Err(e) = self.inner.ensure_session().await {
106            return BrowserResult::err(format!("session init failed: {e}"));
107        }
108        let mut lock = self.inner.session.lock().await;
109        let Some(session) = lock.as_mut() else {
110            return BrowserResult::err("no active session");
111        };
112        let timeout = Duration::from_millis(self.inner.config.command_timeout_ms);
113        match cmd {
114            BrowserCmd::Navigate { url } => {
115                match tokio::time::timeout(timeout, session.navigate(&url)).await {
116                    Ok(Ok(())) => BrowserResult::ok(),
117                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
118                    Err(_) => BrowserResult::err("navigate timed out"),
119                }
120            }
121            BrowserCmd::Click { target } => {
122                match tokio::time::timeout(timeout, session.click(&target)).await {
123                    Ok(Ok(())) => BrowserResult::ok(),
124                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
125                    Err(_) => BrowserResult::err("click timed out"),
126                }
127            }
128            BrowserCmd::Fill { target, value } => {
129                match tokio::time::timeout(timeout, session.fill(&target, &value)).await {
130                    Ok(Ok(())) => BrowserResult::ok(),
131                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
132                    Err(_) => BrowserResult::err("fill timed out"),
133                }
134            }
135            BrowserCmd::Screenshot => {
136                match tokio::time::timeout(timeout, session.screenshot()).await {
137                    Ok(Ok(bytes)) => {
138                        let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
139                        BrowserResult::ok_screenshot(b64)
140                    }
141                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
142                    Err(_) => BrowserResult::err("screenshot timed out"),
143                }
144            }
145            BrowserCmd::Evaluate { script } => {
146                match tokio::time::timeout(timeout, session.evaluate(&script)).await {
147                    Ok(Ok(v)) => BrowserResult::ok_value(v),
148                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
149                    Err(_) => BrowserResult::err("evaluate timed out"),
150                }
151            }
152            BrowserCmd::Snapshot => {
153                match tokio::time::timeout(timeout, session.snapshot()).await {
154                    Ok(Ok(text)) => BrowserResult::ok_snapshot(text),
155                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
156                    Err(_) => BrowserResult::err("snapshot timed out"),
157                }
158            }
159            BrowserCmd::ScrollTo { target } => {
160                match tokio::time::timeout(timeout, session.scroll_to(&target)).await {
161                    Ok(Ok(())) => BrowserResult::ok(),
162                    Ok(Err(e)) => BrowserResult::err(e.to_string()),
163                    Err(_) => BrowserResult::err("scroll_to timed out"),
164                }
165            }
166        }
167    }
168}
169
170impl BrowserPlugin {
171    /// Close the active Chrome session and kill the spawned Chrome
172    /// process. Idempotent: a second call after the inner state is
173    /// already empty is a no-op.
174    ///
175    /// Drop order matters: clear `session` first so any pending
176    /// CDP commands fail with the existing "no active session"
177    /// branch, then clear `chrome` (whose `RunningChrome::Drop`
178    /// kills the OS process). Both fields stay re-bootable —
179    /// the next [`Self::execute`] call will lazy-reboot a fresh
180    /// Chrome with the same `user_data_dir` so cookies / login
181    /// state persist across eviction cycles.
182    pub async fn shutdown_chrome(&self) {
183        let mut session = self.inner.session.lock().await;
184        *session = None;
185        drop(session);
186        let mut chrome = self.inner.chrome.lock().await;
187        *chrome = None;
188        crate::metrics::set_chrome_alive(&self.instance_label_for_metrics(), false);
189    }
190}
191
192impl BrowserInner {
193    fn instance_label(&self) -> String {
194        self.config
195            .instance
196            .clone()
197            .unwrap_or_else(|| "default".into())
198    }
199
200    async fn ensure_session(self: &Arc<Self>) -> anyhow::Result<()> {
201        let mut session_lock = self.session.lock().await;
202        if session_lock.is_some() {
203            return Ok(());
204        }
205
206        // Follow-up `browser.launch_visible.runtime` — consume the
207        // one-shot override here so the next boot honours it then
208        // the flag resets.
209        let mut cfg_for_launch = self.config.clone();
210        if self
211            .headless_override_off
212            .swap(false, Ordering::SeqCst)
213        {
214            cfg_for_launch.headless = false;
215        }
216        let ws_url = if cfg_for_launch.cdp_url.is_empty() {
217            let chrome = ChromeLauncher::launch(&cfg_for_launch).await?;
218            let ws = chrome.ws_url.clone();
219            *self.chrome.lock().await = Some(chrome);
220            ws
221        } else {
222            ChromeLauncher::connect_existing(
223                &cfg_for_launch.cdp_url,
224                cfg_for_launch.connect_timeout_ms,
225            )
226            .await?
227        };
228
229        let client = Arc::new(CdpClient::connect(&ws_url).await?);
230
231        if let Err(e) = client.send("Page.enable", serde_json::json!({})).await {
232            tracing::warn!(error = %e, "Page.enable failed — navigation events may be missing");
233        }
234
235        let target_id =
236            get_first_target_id(&ws_url, cfg_for_launch.connect_timeout_ms).await?;
237        let session = CdpSession::new(
238            Arc::clone(&client),
239            &target_id,
240            cfg_for_launch.command_timeout_ms,
241        )
242        .await?;
243        *session_lock = Some(session);
244
245        // Follow-up `browser.per-instance-supervisor` — bump
246        // per-instance metrics on every (re-)boot so dashboards
247        // can plot Chrome lifecycle.
248        let label = self.instance_label();
249        crate::metrics::set_chrome_alive(&label, true);
250        crate::metrics::inc_chrome_restart(&label);
251        Ok(())
252    }
253}
254
255async fn get_first_target_id(ws_url: &str, timeout_ms: u64) -> anyhow::Result<String> {
256    let http_url = ws_url
257        .replace("ws://", "http://")
258        .replace("wss://", "https://");
259    let base = if let Some(idx) = http_url.find("/devtools/") {
260        http_url[..idx].to_string()
261    } else {
262        http_url
263    };
264
265    let client = reqwest::Client::builder()
266        .timeout(std::time::Duration::from_millis(timeout_ms))
267        .build()?;
268    let targets: Vec<serde_json::Value> = client
269        .get(format!("{base}/json/list"))
270        .header(reqwest::header::HOST, "localhost")
271        .send()
272        .await?
273        .json()
274        .await?;
275
276    targets
277        .iter()
278        .find(|t| t.get("type").and_then(|v| v.as_str()) == Some("page"))
279        .and_then(|t| t.get("id").and_then(|v| v.as_str()))
280        .map(|s| s.to_string())
281        .ok_or_else(|| anyhow::anyhow!("no page target found in Chrome"))
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    fn test_config() -> BrowserConfig {
289        BrowserConfig {
290            instance: None,
291            headless: true,
292            executable: String::new(),
293            cdp_url: String::new(),
294            user_data_dir: "./.test-profile".into(),
295            window_width: 1280,
296            window_height: 800,
297            connect_timeout_ms: 8_000,
298            command_timeout_ms: 30_000,
299            args: Vec::new(),
300            allow_agents: Vec::new(),
301        }
302    }
303
304    #[tokio::test]
305    async fn shutdown_chrome_is_idempotent_on_fresh_plugin() {
306        // BrowserPlugin::new doesn't boot Chrome (lazy); session
307        // and chrome are both `None`. shutdown_chrome must be a
308        // no-op (no panic on locking-empty-Mutex, no error).
309        let plugin = BrowserPlugin::new(test_config());
310        plugin.shutdown_chrome().await;
311        plugin.shutdown_chrome().await; // second call must also no-op.
312    }
313}
314