//! The commands the management app's screens call (`app/src/admin.spec.md`, "Admin commands"). //! //! One entry point, `AdminApi::call(command, args)`, with JSON in and out: the Tauri shell passes //! the screen's `invoke` straight to it, and the development server does the same over loopback //! HTTP, so both run the same code. use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use serde_json::{json, Map, Value}; use crate::control::{Controller, ServicesHost, State}; use crate::datadir::{free_bytes, DataDir, RECOMMENDED_FREE_BYTES}; use crate::logs::{Level, LogHub}; use crate::secrets::{masked, Secrets, DISCORD_TOKEN}; pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION"); pub struct AdminApi { location_file: PathBuf, dir: Mutex>, controller: Mutex>>, installer: Mutex>>, syncer: Mutex>>, hub: Arc, } fn arg<'a>(args: &'a Value, key: &str) -> Result<&'a Value, String> { args.get(key).ok_or_else(|| format!("{key}이(가) 필요합니다")) } fn arg_str<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { arg(args, key)?.as_str().ok_or_else(|| format!("{key}은(는) 글자여야 합니다")) } fn level_of(s: &str) -> Level { match s { "error" => Level::Error, "warn" => Level::Warn, "info" => Level::Info, _ => Level::Debug, } } impl AdminApi { /// `location_file`: where the data folder is remembered; `hub`: the app's log hub. pub fn new(location_file: &Path, hub: Arc) -> Self { let dir = DataDir::locate(location_file); Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), installer: Mutex::new(None), syncer: Mutex::new(None), hub } } fn dir(&self) -> Result { self.dir.lock().unwrap().clone().ok_or_else(|| "데이터 폴더를 먼저 골라 주세요".into()) } fn secrets(&self) -> Result { Ok(Secrets::new(&self.dir()?.secrets_file())) } fn token(&self) -> Result { self.secrets()?.get(DISCORD_TOKEN).map_err(|e| e.to_string())? .ok_or_else(|| "봇 토큰을 먼저 저장해 주세요".into()) } /// The wizard's progress, `config/setup.json`: `{step, done}`. fn setup(&self, dir: &DataDir) -> Value { std::fs::read_to_string(dir.config().join("setup.json")).ok() .and_then(|t| serde_json::from_str::(&t).ok()) .filter(Value::is_object) .unwrap_or_else(|| json!({"step": 1, "done": false})) } fn save_setup(&self, dir: &DataDir, v: &Value) -> Result<(), String> { crate::datadir::write_atomic(&dir.config().join("setup.json"), v.to_string().as_bytes()) .map_err(|e| format!("설정 진행 상황을 저장하지 못했습니다: {e}")) } /// The installer for the data folder; the Python sources come from the settings' worker folder. fn installer(&self) -> Result, String> { let dir = self.dir()?; let mut i = self.installer.lock().unwrap(); if i.is_none() { let src = crate::settings::load_settings(&dir.settings_file()).map_err(|e| e.0)?.voice_worker.cwd; let layout = crate::install::Layout { data: dir.path().to_path_buf(), src }; *i = Some(crate::install::Installer::new(layout, crate::install::steps())); } Ok(i.clone().unwrap()) } /// Keeps chat channel names and topics in step with Discord, with the stored bot token. fn syncer(&self) -> Result, String> { let dir = self.dir()?; let mut s = self.syncer.lock().unwrap(); Ok(s.get_or_insert_with(|| crate::channel_sync::Syncer::new( Arc::new(crate::channel_sync::DiscordRest::new(dir.secrets_file())), dir.settings_file())).clone()) } fn controller(&self) -> Result, String> { let dir = self.dir()?; let mut c = self.controller.lock().unwrap(); Ok(c.get_or_insert_with(|| Controller::new(ServicesHost::new(dir.path().to_path_buf()))).clone()) } /// The app is closing: cancel an install in progress and wait for it (its commands and their /// children end), stop the services (a start in progress is cancelled and waited for) and clear /// what a failed run may have left (the LLM's server). An error means something may still run; /// the window then stays open (admin.spec.md, "Window and Windows build"). pub async fn shutdown(&self) -> Result<(), String> { let installer = self.installer.lock().unwrap().clone(); if let Some(i) = installer.filter(|i| i.running()) { i.cancel(); let until = std::time::Instant::now() + std::time::Duration::from_secs(60); while i.running() && std::time::Instant::now() < until { tokio::time::sleep(std::time::Duration::from_millis(100)).await; } if i.running() { return Err("설치를 멈추지 못했습니다".into()); } } let controller = self.controller.lock().unwrap().clone(); match controller { Some(c) => c.shutdown().await, None => Ok(()), } } pub async fn call(&self, command: &str, args: Value) -> Result { crate::debug_log!("admin", "command {command}"); match command { "app_status" => { let dir = self.dir.lock().unwrap().clone(); let token = dir.as_ref().and_then(|d| Secrets::new(&d.secrets_file()).get(DISCORD_TOKEN).ok().flatten()); // The wizard is done only when its last step was reached, not when a token exists. let setup = dir.as_ref().map(|d| self.setup(d)); let done = setup.as_ref().is_some_and(|s| s["done"] == json!(true)); Ok(json!({"version": APP_VERSION, "dataDir": dir.as_ref().map(|d| d.path().to_string_lossy()), "tokenSet": token.is_some(), "firstRun": !done, "wizardStep": setup.as_ref().and_then(|s| s["step"].as_u64()).unwrap_or(0)})) } "wizard_step" => { let dir = self.dir()?; let step = arg(&args, "step")?.as_u64().ok_or("step은 숫자여야 합니다")?; let mut s = self.setup(&dir); s["step"] = json!(step); self.save_setup(&dir, &s)?; Ok(s) } "wizard_finish" => { let dir = self.dir()?; if self.secrets()?.get(DISCORD_TOKEN).map_err(|e| e.to_string())?.is_none() { return Err("봇 토큰을 먼저 저장해 주세요".into()); } let mut s = self.setup(&dir); s["done"] = json!(true); self.save_setup(&dir, &s)?; crate::info_log!("admin", "first-run setup finished"); Ok(s) } "folder_check" => { let path = PathBuf::from(arg_str(&args, "path")?); if !path.is_absolute() { return Err("전체 경로를 적어 주세요 (예: D:\\JarvisBot)".into()); } let free = free_bytes(&path).map_err(|e| e.to_string())?; Ok(json!({"freeBytes": free, "recommendedBytes": RECOMMENDED_FREE_BYTES, "enough": free >= RECOMMENDED_FREE_BYTES, "exists": path.exists()})) } "folder_choose" => { let path = PathBuf::from(arg_str(&args, "path")?); let dir = DataDir::choose(&path, &self.location_file).map_err(|e| e.to_string())?; // Log files go to the chosen folder from now on, not only after a restart. self.hub.set_dir(&dir.logs()); *self.dir.lock().unwrap() = Some(dir); *self.controller.lock().unwrap() = None; *self.installer.lock().unwrap() = None; crate::info_log!("admin", "data folder chosen"); Ok(json!({"dataDir": path.to_string_lossy()})) } "install_status" => Ok(self.installer()?.status()), "install_start" => { if !self.installer()?.start() { return Err("설치가 이미 진행 중입니다".into()); } Ok(json!({"started": true})) } "install_cancel" => { self.installer()?.cancel(); Ok(json!({"cancelling": true})) } "pc_check" => { let usage = crate::system::usage().await; let driver = crate::system::driver_version().await; let disk = self.dir.lock().unwrap().as_ref().and_then(|d| free_bytes(d.path()).ok()); Ok(json!({"os": std::env::consts::OS, "cpuThreads": std::thread::available_parallelism().map(|n| n.get()).ok(), "ramTotalMb": usage.ram_total_mb, "gpus": usage.gpus, "driver": driver, "driverOk": driver.as_deref().is_some_and(crate::system::driver_ok), "minDriver": crate::system::MIN_DRIVER_MAJOR, "diskFreeBytes": disk})) } "token_check" => Ok(json!(crate::discord_setup::check_token(arg_str(&args, "token")?).await?)), "token_save" => { let token = arg_str(&args, "token")?.trim().to_owned(); if token.is_empty() { return Err("봇 토큰이 비어 있습니다".into()); } self.secrets()?.set(DISCORD_TOKEN, &token).map_err(|e| e.to_string())?; self.hub.set_secrets(self.secrets()?.values()); crate::info_log!("admin", "bot token saved"); Ok(json!({"masked": masked(&token)})) } "token_status" => { let t = self.secrets()?.get(DISCORD_TOKEN).map_err(|e| e.to_string())?; Ok(json!({"set": t.is_some(), "masked": t.as_deref().map(masked)})) } "discord_guilds" => Ok(json!(crate::discord_setup::guilds(&self.token()?).await?)), "discord_channels" => { let guild: u64 = arg_str(&args, "guildId")?.parse().map_err(|_| "서버 ID가 올바르지 않습니다")?; Ok(json!(crate::discord_setup::channels(&self.token()?, guild).await?)) } "settings_fields" => Ok(json!(crate::settings_edit::fields())), "settings_view" => crate::settings_edit::view(&self.dir()?.settings_file()) .map(Value::Object).map_err(|e| e.0), "settings_apply" => { let changes: Map = arg(&args, "changes")?.as_object().cloned() .ok_or("changes는 객체여야 합니다")?; let file = self.dir()?.settings_file(); // Chat channels: a topic Discord would refuse is caught before saving; after saving, // the edited channels go to Discord (admin.spec.md, "Chat channel names and topics"). let chats = changes.get("chatChannels"); let old = match chats { Some(list) => { let parsed = crate::settings::parse_settings(&json!({"chatChannels": list})).map_err(|e| e.0)?; crate::channel_sync::check_topics(&parsed.chat_channels)?; crate::settings::load_settings(&file).map_err(|e| e.0)?.chat_channels } None => vec![], }; crate::settings_edit::apply(&file, &changes).map_err(|e| e.0)?; let mut sync = vec![]; if chats.is_some() { let new = crate::settings::load_settings(&file).map_err(|e| e.0)?.chat_channels; let todo = crate::channel_sync::changed(&old, &new); if !todo.is_empty() { for (id, state) in self.syncer()?.sync(todo, &old).await { let mut v = json!(state); v["id"] = json!(id.to_string()); sync.push(v); } } } Ok(json!({"saved": changes.len(), "restartNeeded": self.controller()?.state() == crate::control::State::Running, "sync": sync})) } "channel_sync_status" => Ok(Value::Object(self.syncer()?.status().into_iter() .map(|(id, s)| (id.to_string(), json!(s))).collect())), "discord_channel_info" => { let id: u64 = arg_str(&args, "id")?.trim().parse().map_err(|_| "채널 ID가 올바르지 않습니다")?; Ok(json!(self.syncer()?.info(id).await?)) } // Starting can take long (the LLM's first start downloads the model), so it runs in the // background and the dashboard shows how it goes; stop also cancels a start. "service_start" => self.controller()?.start_in_background().map(|_| json!({"ok": true})), "service_restart" => { let c = self.controller()?; if c.state() != State::Running { return Err(format!("cannot restart while {:?}", c.state()).to_lowercase()); } c.stop().await?; c.start_in_background().map(|_| json!({"ok": true})) } "service_stop" => self.controller()?.stop().await.map(|_| json!({"ok": true})), "dashboard" => Ok(self.controller()?.snapshot().await), "logs_query" => { let tab = args.get("tab").and_then(Value::as_str).filter(|t| !t.is_empty() && *t != "all"); let level = level_of(args.get("level").and_then(Value::as_str).unwrap_or("debug")); let find = args.get("find").and_then(Value::as_str).filter(|f| !f.is_empty()); let after = args.get("after").and_then(Value::as_u64); let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(500).min(5000) as usize; Ok(json!(self.hub.query(tab, level, find, after, limit))) } "logs_error_report" => { let report = self.hub.recent_error_report(APP_VERSION); let too_long = report.as_ref().is_some_and(|r| r.chars().count() > crate::logs::DISCORD_MESSAGE_CHARS); Ok(json!({"report": report, "tooLongForDiscord": too_long})) } "logs_export" => { let day = |k: &str| -> Result { chrono::NaiveDate::parse_from_str(arg_str(&args, k)?, "%Y-%m-%d").map_err(|_| format!("{k}는 YYYY-MM-DD 날짜여야 합니다")) }; let (from, to) = (day("from")?, day("to")?); let out = self.dir()?.logs().join(format!("jarvis-logs-{from}-{to}.zip")); let dropped = self.hub.export_zip(from, to, &out).map_err(|e| e.to_string())?; Ok(json!({"path": out.to_string_lossy(), "droppedLines": dropped})) } _ => Err(format!("알 수 없는 명령: {command}")), } } } #[cfg(test)] mod tests { use super::*; use crate::datadir::temp_dir; fn api(tag: &str) -> (AdminApi, PathBuf) { let base = temp_dir(tag); let loc = base.join("cfg").join("location.json"); (AdminApi { location_file: loc, dir: Mutex::new(None), controller: Mutex::new(None), installer: Mutex::new(None), syncer: Mutex::new(None), hub: LogHub::new(None) }, base) } #[tokio::test] async fn the_first_run_chooses_a_folder_then_stores_the_token() { let (a, base) = api("api1"); assert_eq!(a.call("app_status", json!({})).await.unwrap()["firstRun"], json!(true)); assert!(a.call("settings_view", json!({})).await.unwrap_err().contains("데이터 폴더")); assert!(a.call("folder_check", json!({"path": "relative"})).await.is_err()); let data = base.join("data"); let check = a.call("folder_check", json!({"path": data.to_string_lossy()})).await.unwrap(); assert!(check["freeBytes"].as_u64().unwrap() > 0 && check["exists"] == json!(false)); a.hub.push(Level::Info, "app", "before the folder"); a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap(); assert!(data.join("config").is_dir()); // From the choice on, lines go to the folder's log files and the zip export works. a.hub.push(Level::Info, "app", "after the folder"); let today = chrono::Local::now().date_naive().to_string(); let logs = std::fs::read_to_string(data.join("logs").join(format!("app-{today}.log"))).unwrap(); assert!(logs.contains("after the folder")); let zip = a.call("logs_export", json!({"from": today, "to": today})).await.unwrap(); assert!(std::path::Path::new(zip["path"].as_str().unwrap()).exists()); assert_eq!(a.call("app_status", json!({})).await.unwrap()["firstRun"], json!(true), "no token yet"); assert!(a.call("wizard_finish", json!({})).await.is_err(), "not without a token"); let saved = a.call("token_save", json!({"token": "abc.def.ghijkl"})).await.unwrap(); assert_eq!(saved["masked"], json!("••••ijkl")); a.call("wizard_step", json!({"step": 4})).await.unwrap(); // A stored token does not finish the wizard: it resumes at the step it reached. let s = a.call("app_status", json!({})).await.unwrap(); assert_eq!((s["firstRun"].clone(), s["tokenSet"].clone(), s["wizardStep"].clone()), (json!(true), json!(true), json!(4))); a.call("wizard_finish", json!({})).await.unwrap(); assert_eq!(a.call("app_status", json!({})).await.unwrap()["firstRun"], json!(false)); // The token never comes back whole. assert_eq!(a.call("token_status", json!({})).await.unwrap(), json!({"set": true, "masked": "••••ijkl"})); } #[tokio::test] async fn settings_go_through_the_editor_and_logs_through_the_hub() { let (a, base) = api("api2"); a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap(); let fields = a.call("settings_fields", json!({})).await.unwrap(); assert_eq!(fields.as_array().unwrap().len(), crate::settings_edit::fields().len()); a.call("settings_apply", json!({"changes": {"call.mode": "everything"}})).await.unwrap(); assert_eq!(a.call("settings_view", json!({})).await.unwrap()["call.mode"], json!("everything")); assert!(a.call("settings_apply", json!({"changes": {"call.mode": "x"}})).await.unwrap_err().contains("call.mode")); a.hub.push(Level::Error, "discord", "login failed"); a.hub.push(Level::Debug, "chat", "ok"); let lines = a.call("logs_query", json!({"tab": "discord", "level": "error"})).await.unwrap(); assert_eq!(lines.as_array().unwrap().len(), 1); let r = a.call("logs_error_report", json!({})).await.unwrap(); assert!(r["report"].as_str().unwrap().contains("login failed")); assert!(a.call("nope", json!({})).await.is_err()); } #[tokio::test] async fn the_dashboard_answers_before_anything_runs() { let (a, base) = api("api3"); a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap(); let d = a.call("dashboard", json!({})).await.unwrap(); assert_eq!(d["state"], json!("stopped")); assert!(a.call("service_stop", json!({})).await.is_err()); } #[tokio::test] async fn closing_the_app_while_starting_waits_until_everything_is_stopped() { let (a, base) = api("api5"); a.shutdown().await.unwrap(); // nothing chosen or started yet a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap(); a.call("service_start", json!({})).await.unwrap(); a.shutdown().await.unwrap(); assert_eq!(a.call("dashboard", json!({})).await.unwrap()["state"], json!("stopped")); } /// A step that runs until it is cancelled (an install in progress when the window closes). struct Endless; #[async_trait::async_trait] impl crate::install::Step for Endless { fn id(&self) -> &'static str { "endless" } fn label(&self) -> &'static str { "endless" } fn size_hint(&self) -> &'static str { "" } fn version(&self, _: &crate::install::Layout) -> String { "1".into() } async fn run(&self, ctx: &crate::install::Ctx) -> Result<(), String> { while !ctx.cancel.load(std::sync::atomic::Ordering::SeqCst) { tokio::time::sleep(std::time::Duration::from_millis(20)).await; } Err("cancelled".into()) } } #[tokio::test] async fn closing_the_app_during_the_install_cancels_it_and_waits() { let (a, base) = api("api6"); a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap(); let layout = crate::install::Layout { data: base.join("d"), src: PathBuf::from("src") }; *a.installer.lock().unwrap() = Some(crate::install::Installer::new(layout, vec![Box::new(Endless)])); a.call("install_start", json!({})).await.unwrap(); tokio::time::sleep(std::time::Duration::from_millis(100)).await; assert_eq!(a.call("install_status", json!({})).await.unwrap()["running"], json!(true)); a.shutdown().await.unwrap(); let st = a.call("install_status", json!({})).await.unwrap(); assert_eq!((st["running"].clone(), st["steps"][0]["state"].clone()), (json!(false), json!("failed"))); } /// Discord for the chat channel screen: one channel whose names lose their spaces. struct OneChannel(Mutex); #[async_trait::async_trait] impl crate::channel_sync::ChannelApi for OneChannel { async fn info(&self, _: u64) -> Result { Ok(self.0.lock().unwrap().clone()) } async fn edit(&self, _: u64, name: Option<&str>, topic: Option<&str>) -> Result { let mut c = self.0.lock().unwrap(); if let Some(n) = name { c.name = n.replace(' ', "-"); } if let Some(t) = topic { c.topic = t.into(); } Ok(c.clone()) } } #[tokio::test] async fn saving_chat_channels_brings_their_names_and_topics_to_discord() { let (a, base) = api("api7"); a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap(); let discord = Arc::new(OneChannel(Mutex::new(crate::channel_sync::ChannelInfo { name: "memo".into(), topic: "".into() }))); let file = a.dir().unwrap().settings_file(); *a.syncer.lock().unwrap() = Some(crate::channel_sync::Syncer::new(discord.clone(), file.clone())); const ID: &str = "100000000000000001"; // Registering fills the fields from Discord. assert_eq!(a.call("discord_channel_info", json!({"id": ID})).await.unwrap()["name"], json!("memo")); let r = a.call("settings_apply", json!({"changes": {"chatChannels": [ {"id": ID, "name": "할 일 메모", "description": "오늘 할 일"}]}})).await.unwrap(); assert_eq!(r["sync"][0], json!({"id": ID, "state": "applied", "name": "할-일-메모"})); assert_eq!(discord.0.lock().unwrap().topic, "오늘 할 일"); assert_eq!(a.call("settings_view", json!({})).await.unwrap()["chatChannels"][0]["name"], json!("할-일-메모")); assert_eq!(a.call("channel_sync_status", json!({})).await.unwrap()[ID]["state"], json!("applied")); // A topic over Discord's limit is refused and nothing is saved. let before = std::fs::read_to_string(&file).unwrap(); let e = a.call("settings_apply", json!({"changes": {"chatChannels": [ {"id": ID, "name": "할-일-메모", "description": "가".repeat(1025)}]}})).await.unwrap_err(); assert!(e.contains("1024"), "{e}"); assert_eq!(std::fs::read_to_string(&file).unwrap(), before); } #[tokio::test] async fn a_start_is_starting_when_it_answers_so_a_stop_right_after_it_is_not_refused() { let (a, base) = api("api4"); a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap(); a.call("service_start", json!({})).await.unwrap(); assert!(a.call("service_start", json!({})).await.unwrap_err().contains("starting")); a.call("service_stop", json!({})).await.unwrap(); let mut state = Value::Null; for _ in 0..200 { state = a.call("dashboard", json!({})).await.unwrap()["state"].clone(); if state == json!("stopped") { break; } tokio::time::sleep(std::time::Duration::from_millis(10)).await; } assert_eq!(state, json!("stopped"), "the start was cancelled, not started late"); } }