feat(app): M5 step 3, the management app's screens and their commands

- admin_api: the one entry point of the screens (app status, data folder,
  PC check, Discord token check and pickers, settings, service control and
  the dashboard, logs query, error report and zip export).
- discord_setup: token, Message Content and invite link checks over REST.
- app/ui: first-run wizard, dashboard, five settings screens and the log
  screen in plain HTML/CSS/JS (dark theme after DESIGN.md, Korean text).
- jarvis-admin-dev: a loopback, token-guarded development server so the
  screens run in a browser against the real commands.

Checked in a browser with the real test bot and voice worker: wizard
steps, start/restart/stop, settings save, chat channels, logs and export.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-12 14:15:58 +09:00
parent e8ddde5be6
commit 20300c017e
11 changed files with 1654 additions and 2 deletions

222
app/src/admin_api.rs Normal file
View File

@@ -0,0 +1,222 @@
//! 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};
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<Option<DataDir>>,
controller: Mutex<Option<Arc<Controller>>>,
hub: Arc<LogHub>,
}
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<LogHub>) -> Self {
let dir = DataDir::locate(location_file);
Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), hub }
}
fn dir(&self) -> Result<DataDir, String> {
self.dir.lock().unwrap().clone().ok_or_else(|| "데이터 폴더를 먼저 골라 주세요".into())
}
fn secrets(&self) -> Result<Secrets, String> {
Ok(Secrets::new(&self.dir()?.secrets_file()))
}
fn token(&self) -> Result<String, String> {
self.secrets()?.get(DISCORD_TOKEN).map_err(|e| e.to_string())?
.ok_or_else(|| "봇 토큰을 먼저 저장해 주세요".into())
}
fn controller(&self) -> Result<Arc<Controller>, String> {
let dir = self.dir()?;
let mut c = self.controller.lock().unwrap();
Ok(c.get_or_insert_with(|| Controller::new(ServicesHost { data_dir: dir.path().to_path_buf() })).clone())
}
pub async fn call(&self, command: &str, args: Value) -> Result<Value, String> {
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());
Ok(json!({"version": APP_VERSION, "dataDir": dir.as_ref().map(|d| d.path().to_string_lossy()),
"tokenSet": token.is_some(), "firstRun": dir.is_none() || token.is_none()}))
}
"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())?;
*self.dir.lock().unwrap() = Some(dir);
*self.controller.lock().unwrap() = None;
crate::info_log!("admin", "data folder chosen");
Ok(json!({"dataDir": path.to_string_lossy()}))
}
"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<String, Value> = arg(&args, "changes")?.as_object().cloned()
.ok_or("changes는 객체여야 합니다")?;
crate::settings_edit::apply(&self.dir()?.settings_file(), &changes).map_err(|e| e.0)?;
Ok(json!({"saved": changes.len(), "restartNeeded": self.controller()?.state() == crate::control::State::Running}))
}
"service_start" => self.controller()?.start().await.map(|_| json!({"ok": true})),
"service_stop" => self.controller()?.stop().await.map(|_| json!({"ok": true})),
"service_restart" => self.controller()?.restart().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, String> {
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), 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.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
assert!(data.join("config").is_dir());
assert_eq!(a.call("app_status", json!({})).await.unwrap()["firstRun"], json!(true), "no token yet");
let saved = a.call("token_save", json!({"token": "abc.def.ghijkl"})).await.unwrap();
assert_eq!(saved["masked"], json!("••••ijkl"));
let s = a.call("app_status", json!({})).await.unwrap();
assert_eq!((s["firstRun"].clone(), s["tokenSet"].clone()), (json!(false), json!(true)));
// 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());
}
}