Skip to main content

nexo_plugin_browser/
admin.rs

1//! Step 7 of browser-multi-instance — admin RPC handlers.
2//!
3//! Pure-fn handlers (one per verb) that operate on
4//! [`instance_registry`] + filesystem sentinel files. They take a
5//! `serde_json::Value` request payload and return the JSON reply.
6//!
7//! Wiring is split:
8//! - Handlers (this file) — testable in-process, no broker dep.
9//! - Broker subscriber loop — see `auto_discovery.rs` + main.rs
10//!   wire-up (deferred follow-up `browser.auto_discovery.subscriber`).
11//!
12//! Daemon-side admin RPC `nexo/admin/browser/<verb>` is forwarded
13//! via the broker pattern declared in `nexo-plugin.toml`
14//! `[plugin.admin]` (Step 8).
15
16use std::path::PathBuf;
17
18use serde_json::{json, Value};
19
20use crate::instance_registry;
21
22const PAIRED_SENTINEL: &str = ".nexo-paired";
23
24fn ok(result: Value) -> Value {
25    json!({ "ok": true, "result": result })
26}
27
28fn err(msg: impl Into<String>) -> Value {
29    json!({ "ok": false, "error": msg.into() })
30}
31
32fn arg_instance(req: &Value) -> Result<String, Value> {
33    req.get("instance")
34        .and_then(|v| v.as_str())
35        .map(|s| s.to_string())
36        .ok_or_else(|| err("`instance` arg required"))
37}
38
39/// `nexo/admin/browser/list_instances` — enumerate every declared
40/// instance with its current paired state.
41pub fn list_instances() -> Value {
42    let rows: Vec<Value> = instance_registry::entries()
43        .into_iter()
44        .map(|(label, plugin)| {
45            let dir = plugin.user_data_dir().to_string();
46            let paired = PathBuf::from(&dir).join(PAIRED_SENTINEL).exists();
47            json!({
48                "instance": label,
49                "user_data_dir": dir,
50                "paired": paired,
51            })
52        })
53        .collect();
54    ok(json!({ "instances": rows }))
55}
56
57/// `nexo/admin/browser/shutdown` — shut down the Chrome handle for
58/// a specific instance. Idempotent. The registry entry stays so
59/// the next `tool.invoke` lazy-reboots Chrome.
60pub async fn shutdown(req: &Value) -> Value {
61    let instance = match arg_instance(req) {
62        Ok(s) => s,
63        Err(e) => return e,
64    };
65    let Some(plugin) = instance_registry::lookup(&instance) else {
66        return err(format!("instance `{instance}` not declared"));
67    };
68    plugin.shutdown_chrome().await;
69    ok(json!({ "instance": instance, "shutdown": true }))
70}
71
72/// `nexo/admin/browser/restart` — shutdown + register intent to
73/// re-boot. The actual Chrome boot is lazy (next `tool.invoke`),
74/// so this verb is effectively `shutdown` from the runtime's
75/// perspective.
76pub async fn restart(req: &Value) -> Value {
77    let instance = match arg_instance(req) {
78        Ok(s) => s,
79        Err(e) => return e,
80    };
81    let Some(plugin) = instance_registry::lookup(&instance) else {
82        return err(format!("instance `{instance}` not declared"));
83    };
84    plugin.shutdown_chrome().await;
85    ok(json!({ "instance": instance, "restart": true }))
86}
87
88/// `nexo/admin/browser/mark_paired` — touches the `.nexo-paired`
89/// sentinel inside the instance's `user_data_dir` so the dashboard
90/// `auth_check` (Stage 6 wizard) flips green. Operator-confirmed
91/// signal; replaces fragile Chrome-internal SQLite probing.
92pub fn mark_paired(req: &Value) -> Value {
93    let instance = match arg_instance(req) {
94        Ok(s) => s,
95        Err(e) => return e,
96    };
97    let Some(plugin) = instance_registry::lookup(&instance) else {
98        return err(format!("instance `{instance}` not declared"));
99    };
100    let dir = PathBuf::from(plugin.user_data_dir());
101    if let Err(e) = std::fs::create_dir_all(&dir) {
102        return err(format!("create user_data_dir failed: {e}"));
103    }
104    let path = dir.join(PAIRED_SENTINEL);
105    match std::fs::write(&path, b"paired\n") {
106        Ok(()) => ok(json!({
107            "instance": instance,
108            "sentinel": path.to_string_lossy(),
109        })),
110        Err(e) => err(format!("write sentinel failed: {e}")),
111    }
112}
113
114/// `nexo/admin/browser/launch_visible` — request a non-headless
115/// Chrome boot for the instance so the operator can complete a
116/// manual pairing flow. Idempotent: shuts the current Chrome
117/// down (if any) so the next lazy-boot honours the one-shot
118/// `headless = false` override.
119///
120/// The actual Chrome (re-)boot is lazy: the next `tool.invoke`
121/// targeting this instance triggers `BrowserInner::ensure_session`
122/// which consumes the override and spawns Chrome with the visible
123/// flag.
124pub async fn launch_visible(req: &Value) -> Value {
125    let instance = match arg_instance(req) {
126        Ok(s) => s,
127        Err(e) => return e,
128    };
129    let Some(plugin) = instance_registry::lookup(&instance) else {
130        return err(format!("instance `{instance}` not declared"));
131    };
132    plugin.request_visible_next_boot();
133    plugin.shutdown_chrome().await;
134    ok(json!({
135        "instance": instance,
136        "launched": true,
137        "note": "Chrome will spawn visible on next tool.invoke targeting this instance",
138    }))
139}
140
141/// Generic dispatch entry point — matches the broker topic suffix
142/// to a handler. Unknown verb ⇒ structured error.
143pub async fn dispatch(verb: &str, params: &Value) -> Value {
144    match verb {
145        "list_instances" => list_instances(),
146        "shutdown" => shutdown(params).await,
147        "restart" => restart(params).await,
148        "mark_paired" => mark_paired(params),
149        "launch_visible" => launch_visible(params).await,
150        other => err(format!("unknown admin verb: `{other}`")),
151    }
152}