use std::path::PathBuf;
use serde_json::{json, Value};
use crate::instance_registry;
const PAIRED_SENTINEL: &str = ".nexo-paired";
fn ok(result: Value) -> Value {
json!({ "ok": true, "result": result })
}
fn err(msg: impl Into<String>) -> Value {
json!({ "ok": false, "error": msg.into() })
}
fn arg_instance(req: &Value) -> Result<String, Value> {
req.get("instance")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.ok_or_else(|| err("`instance` arg required"))
}
pub fn list_instances() -> Value {
let rows: Vec<Value> = instance_registry::entries()
.into_iter()
.map(|(label, plugin)| {
let dir = plugin.user_data_dir().to_string();
let paired = PathBuf::from(&dir).join(PAIRED_SENTINEL).exists();
json!({
"instance": label,
"user_data_dir": dir,
"paired": paired,
})
})
.collect();
ok(json!({ "instances": rows }))
}
pub async fn shutdown(req: &Value) -> Value {
let instance = match arg_instance(req) {
Ok(s) => s,
Err(e) => return e,
};
let Some(plugin) = instance_registry::lookup(&instance) else {
return err(format!("instance `{instance}` not declared"));
};
plugin.shutdown_chrome().await;
ok(json!({ "instance": instance, "shutdown": true }))
}
pub async fn restart(req: &Value) -> Value {
let instance = match arg_instance(req) {
Ok(s) => s,
Err(e) => return e,
};
let Some(plugin) = instance_registry::lookup(&instance) else {
return err(format!("instance `{instance}` not declared"));
};
plugin.shutdown_chrome().await;
ok(json!({ "instance": instance, "restart": true }))
}
pub fn mark_paired(req: &Value) -> Value {
let instance = match arg_instance(req) {
Ok(s) => s,
Err(e) => return e,
};
let Some(plugin) = instance_registry::lookup(&instance) else {
return err(format!("instance `{instance}` not declared"));
};
let dir = PathBuf::from(plugin.user_data_dir());
if let Err(e) = std::fs::create_dir_all(&dir) {
return err(format!("create user_data_dir failed: {e}"));
}
let path = dir.join(PAIRED_SENTINEL);
match std::fs::write(&path, b"paired\n") {
Ok(()) => ok(json!({
"instance": instance,
"sentinel": path.to_string_lossy(),
})),
Err(e) => err(format!("write sentinel failed: {e}")),
}
}
pub async fn launch_visible(req: &Value) -> Value {
let instance = match arg_instance(req) {
Ok(s) => s,
Err(e) => return e,
};
let Some(plugin) = instance_registry::lookup(&instance) else {
return err(format!("instance `{instance}` not declared"));
};
plugin.request_visible_next_boot();
plugin.shutdown_chrome().await;
ok(json!({
"instance": instance,
"launched": true,
"note": "Chrome will spawn visible on next tool.invoke targeting this instance",
}))
}
pub async fn dispatch(verb: &str, params: &Value) -> Value {
match verb {
"list_instances" => list_instances(),
"shutdown" => shutdown(params).await,
"restart" => restart(params).await,
"mark_paired" => mark_paired(params),
"launch_visible" => launch_visible(params).await,
other => err(format!("unknown admin verb: `{other}`")),
}
}