Files
javis_bot/app/src/admin_api.rs
javis-bot 282f114e60 feat(weather): KMA current weather inside Korea with the app's stored key
The 기능 screen's 기상청 날씨 card stores the KMA API hub key encrypted
(kmaApiKey, masked in logs). On start the app passes it to the worker in
JARVIS_KMA_API_KEY; the worker takes it out of its environment before any
child process starts. Inside Korea getWeather reads 초단기실황 and the
coming hour's sky from 초단기예보, and falls back to open-meteo, then
met.no, on any KMA failure. The key is in KMA's URLs, so failures are
logged by their kind only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:05:31 +09:00

1052 lines
62 KiB
Rust

//! 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, KMA_KEY};
pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
pub struct AdminApi {
location_file: PathBuf,
dir: Mutex<Option<DataDir>>,
controller: Mutex<Option<Arc<Controller>>>,
installer: Mutex<Option<Arc<crate::install::Installer>>>,
syncer: Mutex<Option<Arc<crate::channel_sync::Syncer>>>,
hub: Arc<LogHub>,
/// The virtual monitor's driver is being installed or removed: no service start meanwhile.
driver_busy: Mutex<bool>,
updater: Mutex<Option<Arc<crate::update::Updater>>>,
/// Starts a downloaded installer (`update::launch_installer`; a fake in tests).
launcher: fn(&Path) -> Result<(), String>,
}
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}은(는) 글자여야 합니다"))
}
/// A `YYYY-MM-DD` day argument.
fn day_arg(args: &Value, key: &str) -> Result<chrono::NaiveDate, String> {
chrono::NaiveDate::parse_from_str(arg_str(args, key)?, "%Y-%m-%d").map_err(|_| format!("{key}는 YYYY-MM-DD 날짜여야 합니다"))
}
/// Unix seconds of a local day's start.
fn day_start(day: chrono::NaiveDate) -> f64 {
day.and_hms_opt(0, 0, 0).and_then(|t| t.and_local_timezone(chrono::Local).earliest())
.map_or(0.0, |t| t.timestamp() as f64)
}
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);
// Stored secrets are masked in every copy and export from the start, not only once saved again.
if let Some(d) = &dir {
hub.set_secrets(Secrets::new(&d.secrets_file()).values());
}
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, driver_busy: Mutex::new(false), updater: Mutex::new(None),
launcher: crate::update::launch_installer }
}
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())
}
/// 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::<Value>(&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<Arc<crate::install::Installer>, 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<Arc<crate::channel_sync::Syncer>, 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())
}
/// Start the services in the background, unless the virtual monitor's driver is being installed
/// or removed (its monitor would vanish under the bot browser, or appear half made).
fn start_services(&self, c: &Arc<Controller>) -> Result<Value, String> {
let busy = self.driver_busy.lock().unwrap();
if *busy {
return Err("가상 모니터 드라이버 작업이 끝난 뒤에 시작해 주세요".into());
}
c.start_in_background().map(|_| json!({"ok": true}))
}
/// Mark a driver install or removal as running; only while the services are stopped (a failed
/// run has stopped the bot browser already) and no other driver task runs.
fn begin_driver_task(&self) -> Result<(), String> {
let mut busy = self.driver_busy.lock().unwrap();
if *busy {
return Err("가상 모니터 드라이버 작업이 이미 진행 중입니다".into());
}
let controller = self.controller.lock().unwrap().clone();
if let Some(state) = controller.map(|c| c.state()) {
if !matches!(state, State::Stopped | State::Failed) {
return Err("서비스를 정지한 뒤에 가상 모니터 드라이버를 설치하거나 제거해 주세요".into());
}
}
*busy = true;
Ok(())
}
/// Updates for this data folder (installers go to its `cache/updates`).
fn updater(&self) -> Result<Arc<crate::update::Updater>, String> {
let dir = self.dir()?;
let mut u = self.updater.lock().unwrap();
Ok(u.get_or_insert_with(|| crate::update::Updater::new(crate::update::source(), APP_VERSION,
dir.path().join("cache").join("updates"))).clone())
}
/// Install the downloaded update: stop what runs (as when the window closes), then start the
/// installer, which waits for this app to close. `{"exit": true}`: the shell quits now.
async fn install_update(&self) -> Result<Value, String> {
let path = self.updater()?.ready_installer()?;
self.shutdown().await.map_err(|e| format!("실행 중인 것을 멈추지 못해 업데이트를 설치하지 않았습니다: {e}"))?;
(self.launcher)(&path).map_err(|e| format!("{e}. 서비스는 정지된 상태입니다"))?;
crate::info_log!("app", "update installer started: the app closes");
Ok(json!({"exit": true}))
}
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::new(dir.path().to_path_buf()))).clone())
}
/// Whether the window's close button hides it to the tray (`app.closeButton`) rather than
/// quitting. Without a data folder or with settings that do not parse, closing quits.
pub fn close_to_tray(&self) -> bool {
self.dir.lock().unwrap().as_ref()
.and_then(|d| crate::settings::load_settings(&d.settings_file()).ok())
.is_some_and(|s| s.close_to_tray)
}
/// 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<Value, String> {
// The 대화 screen asks for the stamp twice a second: a line each time would bury the log.
if command != "history_stamp" {
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.hub.set_secrets(Secrets::new(&dir.secrets_file()).values());
*self.dir.lock().unwrap() = Some(dir);
*self.controller.lock().unwrap() = None;
*self.installer.lock().unwrap() = None;
*self.updater.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)}))
}
"kma_key_status" => {
let k = self.secrets()?.get(KMA_KEY).map_err(|e| e.to_string())?;
Ok(json!({"set": k.is_some(), "masked": k.as_deref().map(masked)}))
}
"kma_key_set" => {
let value = arg_str(&args, "value")?.trim();
let secrets = self.secrets()?;
if value.is_empty() { secrets.remove(KMA_KEY) } else { secrets.set(KMA_KEY, value) }.map_err(|e| e.to_string())?;
self.hub.set_secrets(secrets.values());
crate::info_log!("admin", "kma key {}", if value.is_empty() { "removed" } else { "saved" });
Ok(json!({"set": !value.is_empty(), "masked": (!value.is_empty()).then(|| masked(value)),
"restartNeeded": self.controller()?.state() == crate::control::State::Running}))
}
"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는 객체여야 합니다")?;
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)?;
if changes.contains_key("mcpServers") {
// Values of removed servers and names go with them.
let servers = crate::settings::load_settings(&file).map_err(|e| e.0)?.mcp_servers;
crate::features::prune(&self.secrets()?, &servers).map_err(|e| e.to_string())?;
self.hub.set_secrets(self.secrets()?.values());
}
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);
}
}
}
// The speech speed reaches the running services at once; everything else waits for
// a restart.
if changes.contains_key("voice.tts.speed") {
let speed = crate::settings::load_settings(&file).map_err(|e| e.0)?.voice.tts_speed;
self.controller()?.set_tts_speed(speed);
}
// The close button's choice is read when it is pressed.
let restart = changes.keys().any(|k| k != "voice.tts.speed" && k != "app.closeButton");
Ok(json!({"saved": changes.len(),
"restartNeeded": restart && self.controller()?.state() == crate::control::State::Running,
"sync": sync}))
}
"mcp_env_status" => {
let servers = crate::settings::load_settings(&self.dir()?.settings_file()).map_err(|e| e.0)?.mcp_servers;
crate::features::env_status(&self.secrets()?, &servers).map_err(|e| e.to_string())
}
"mcp_env_set" => {
let (server, name) = (arg_str(&args, "server")?, arg_str(&args, "name")?);
let value = arg_str(&args, "value")?.trim();
let servers = crate::settings::load_settings(&self.dir()?.settings_file()).map_err(|e| e.0)?.mcp_servers;
if !servers.iter().any(|s| s.name == server && s.env.iter().any(|v| v == name)) {
return Err("저장된 MCP 서버의 환경 변수가 아닙니다. 서버 목록을 먼저 저장해 주세요".into());
}
let secrets = self.secrets()?;
let key = crate::features::secret_name(server, name);
if value.is_empty() { secrets.remove(&key) } else { secrets.set(&key, value) }.map_err(|e| e.to_string())?;
self.hub.set_secrets(secrets.values());
crate::info_log!("admin", "mcp value {} for {server}", if value.is_empty() { "removed" } else { "saved" });
Ok(json!({"set": !value.is_empty(),
"restartNeeded": self.controller()?.state() == crate::control::State::Running}))
}
// The virtual monitor's driver (admin.spec.md, "Virtual monitor"): installing or
// removing it runs this app elevated once; Windows asks the user.
"display_driver_status" => Ok(json!(crate::vdisplay::status())),
"display_driver_install" | "display_driver_uninstall" => {
let action = if command == "display_driver_install" { "install" } else { "uninstall" };
self.begin_driver_task()?;
let done = crate::vdisplay::run_elevated(action).await;
*self.driver_busy.lock().unwrap() = false;
if let Err(e) = done {
crate::warn_log!("admin", "Warning: display driver {action} failed: {e}");
return Err(e);
}
crate::info_log!("admin", "display driver {action} done");
Ok(json!(crate::vdisplay::status()))
}
"collect_results" => {
let target = args.get("target").and_then(Value::as_str).filter(|t| !t.is_empty());
let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(100).clamp(1, 500) as usize;
let dir = self.dir()?;
Ok(json!({"targets": crate::collect::result_targets(dir.path()),
"items": crate::collect::results(dir.path(), target, limit)?}))
}
// Schedules (admin.spec.md, "Schedules"): every person's, and deleting any of them.
"schedules_list" => {
let items = crate::schedule::Store::new(self.dir()?.path()).all()?;
Ok(json!({"items": items.iter().map(|i| {
let mut v = json!(i);
v["id"] = json!(i.id.to_string());
v["user"] = json!(i.user.to_string());
v["channel"] = json!(i.channel.map(|c| c.to_string()));
v
}).collect::<Vec<_>>()}))
}
// Personal notes (admin.spec.md, "Personal notes"): everyone's, editable on the screen.
"notes_list" => {
let items = crate::notes::Notes::new(self.dir()?.path()).all()?;
Ok(json!({"items": items.iter().map(|n| {
let mut v = json!(n);
v["id"] = json!(n.id.to_string());
v["user"] = json!(n.user.to_string());
v
}).collect::<Vec<_>>()}))
}
"note_update" => {
let id: u64 = arg_str(&args, "id")?.parse().map_err(|_| "지침 ID가 올바르지 않습니다")?;
crate::notes::Notes::new(self.dir()?.path()).update(id, arg_str(&args, "text")?)?;
crate::info_log!("admin", "note {id} changed");
Ok(json!({"updated": id.to_string()}))
}
"note_delete" => {
let id: u64 = arg_str(&args, "id")?.parse().map_err(|_| "지침 ID가 올바르지 않습니다")?;
crate::notes::Notes::new(self.dir()?.path()).delete(id, None)?;
crate::info_log!("admin", "note {id} deleted");
Ok(json!({"deleted": id.to_string()}))
}
// The 대화 screen (admin.spec.md, "Conversations"): whether what it shows changed.
"history_stamp" => {
let path = self.dir()?.path().join("memory").join("history.sqlite");
let stamp = tokio::task::spawn_blocking(move || crate::history_view::stamp(&path))
.await.map_err(|e| e.to_string())??;
Ok(json!({"stamp": stamp}))
}
// The 대화 screen (admin.spec.md, "Conversations"): records and answer traces.
"history_query" => {
let dir = self.dir()?;
let text = |k: &str| args.get(k).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(String::from);
let flag = |k: &str| args.get(k).and_then(Value::as_bool).unwrap_or(true);
// The current session: from when the latest start began (none yet: nothing to show).
let session = self.controller.lock().unwrap().as_ref().and_then(|c| c.session_start());
let only_session = args.get("session").and_then(Value::as_bool).unwrap_or(false);
let mut since = args.get("since").and_then(Value::as_f64);
if only_session {
since = Some(since.unwrap_or(f64::MIN).max(session.unwrap_or(f64::INFINITY)));
}
let q = crate::history_view::Query {
said: flag("said"), answered: flag("answered"), thought: flag("thought"),
via: text("via"), person: text("person"), channel: text("channel"), find: text("find"),
since, until: args.get("until").and_then(Value::as_f64),
before: args.get("before").and_then(crate::history_view::Cursor::of),
from: args.get("from").and_then(crate::history_view::Cursor::of),
limit: args.get("limit").and_then(Value::as_u64).map_or(crate::history_view::DEFAULT_LIMIT, |n| n as usize),
};
let bot = self.secrets()?.get(DISCORD_TOKEN).ok().flatten().and_then(|t| crate::history_view::bot_id_of_token(&t));
let path = dir.path().join("memory").join("history.sqlite");
let mut v = tokio::task::spawn_blocking(move || crate::history_view::query(&path, bot.as_deref(), &q))
.await.map_err(|e| e.to_string())??;
// Chat channels by the names given them in the settings.
let named = crate::settings::load_settings(&dir.settings_file()).map(|s| s.chat_channels).unwrap_or_default();
for ch in v["channels"].as_array_mut().into_iter().flatten() {
let name = named.iter().find(|c| Some(c.id.to_string().as_str()) == ch["id"].as_str()).map(|c| c.name.clone());
ch["name"] = json!(name.unwrap_or_default());
}
v["session"] = json!(session);
Ok(v)
}
"activity_list" => {
let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(200).clamp(1, 1000) as usize;
Ok(json!({"items": crate::activity::Activity::new(self.dir()?.path()).recent(limit)}))
}
"schedule_delete" => {
let id: u64 = arg_str(&args, "id")?.parse().map_err(|_| "예약 ID가 올바르지 않습니다")?;
crate::schedule::Store::new(self.dir()?.path()).delete(id, None)?;
crate::info_log!("admin", "schedule {id} deleted");
Ok(json!({"deleted": id.to_string()}))
}
"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.start_services(&self.controller()?),
"service_restart" => {
let c = self.controller()?;
if c.state() != State::Running {
return Err(format!("cannot restart while {:?}", c.state()).to_lowercase());
}
c.stop().await?;
self.start_services(&c)
}
"service_stop" => self.controller()?.stop().await.map(|_| json!({"ok": true})),
"dashboard" => Ok(self.controller()?.snapshot().await),
"update_status" => Ok(self.updater()?.status()),
"update_check" => self.updater()?.check().await,
"update_download" => {
let u = self.updater()?;
u.download()?;
Ok(u.status())
}
"update_install" => self.install_update().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 (from, to) = (day_arg(&args, "from")?, day_arg(&args, "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}))
}
// The 로그 view's lines as shown, masked again, in a text file in `logs/`.
"logs_save_text" => {
let text = arg_str(&args, "text")?;
let logs = self.dir()?.logs();
std::fs::create_dir_all(&logs).map_err(|e| e.to_string())?;
let out = logs.join(format!("jarvis-log-view-{}.txt", chrono::Local::now().format("%Y%m%d-%H%M%S")));
std::fs::write(&out, crate::logs::redact(text, &self.hub.masked_values())).map_err(|e| e.to_string())?;
Ok(json!({"path": out.to_string_lossy()}))
}
// The 로그 screen's 대화 view: the days' records and traces in full, as text in `logs/`.
"history_export" => {
let (from, to) = (day_arg(&args, "from")?, day_arg(&args, "to")?);
let dir = self.dir()?;
let names: std::collections::HashMap<String, String> = crate::settings::load_settings(&dir.settings_file())
.map(|s| s.chat_channels).unwrap_or_default().into_iter()
.map(|c| (c.id.to_string(), format!("{} (채팅)", c.name))).collect();
let bot = self.secrets()?.get(DISCORD_TOKEN).ok().flatten().and_then(|t| crate::history_view::bot_id_of_token(&t));
let path = dir.path().join("memory").join("history.sqlite");
let (since, until) = (day_start(from), day_start(to + chrono::Days::new(1)));
let (body, items) = tokio::task::spawn_blocking(move || {
crate::history_view::export_text(&path, bot.as_deref(), since, until, &names)
}).await.map_err(|e| e.to_string())??;
let text = format!("Jarvis 대화 기록 {from} ~ {to} · {items}개 · 내보낸 때 {}\n\n{body}",
chrono::Local::now().format("%Y-%m-%d %H:%M:%S"));
let out = dir.logs().join(format!("jarvis-talk-{from}-{to}.txt"));
std::fs::create_dir_all(dir.logs()).map_err(|e| e.to_string())?;
std::fs::write(&out, crate::logs::redact(&text, &self.hub.masked_values())).map_err(|e| e.to_string())?;
Ok(json!({"path": out.to_string_lossy(), "items": items}))
}
// The 로그 screen's 목소리 view: the days' recordings and their listing in a zip in `logs/`.
"voice_export" => {
let (from, to) = (day_arg(&args, "from")?, day_arg(&args, "to")?);
let dir = self.dir()?;
let out = dir.logs().join(format!("jarvis-voice-{from}-{to}.zip"));
std::fs::create_dir_all(dir.logs()).map_err(|e| e.to_string())?;
let root = dir.path().join("recordings");
let o2 = out.clone();
let files = tokio::task::spawn_blocking(move || crate::recordings::export_zip(&root, from, to, &o2))
.await.map_err(|e| e.to_string())?.map_err(|e| e.to_string())?;
let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
Ok(json!({"path": out.to_string_lossy(), "files": files, "bytes": bytes}))
}
_ => 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), driver_busy: Mutex::new(false), updater: Mutex::new(None), launcher: refused_launch },
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_close_button_follows_the_saved_choice() {
let (a, base) = api("api-close");
assert!(!a.close_to_tray(), "no data folder yet: closing quits");
let data = base.join("d");
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
assert!(!a.close_to_tray());
a.call("settings_apply", json!({"changes": {"app.closeButton": "tray"}})).await.unwrap();
assert!(a.close_to_tray());
// A settings file that does not parse never leaves the window unable to close.
std::fs::write(data.join("config").join("settings.json"), "{").unwrap();
assert!(!a.close_to_tray());
}
#[tokio::test]
async fn the_notes_screen_lists_edits_and_deletes_anyones_notes() {
let (a, base) = api("api-notes");
let data = base.join("d");
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
let store = crate::notes::Notes::new(&data);
let n = store.add(123456789012345678, "가", "반말로 해", 0).unwrap();
let items = a.call("notes_list", json!({})).await.unwrap()["items"].clone();
assert_eq!(items[0]["user"], "123456789012345678");
a.call("note_update", json!({"id": n.id.to_string(), "text": "존댓말로 해"})).await.unwrap();
assert_eq!(store.texts_of(123456789012345678), vec!["존댓말로 해".to_string()]);
assert!(a.call("note_update", json!({"id": n.id.to_string(), "text": " "})).await.is_err());
a.call("note_delete", json!({"id": n.id.to_string()})).await.unwrap();
assert!(store.all().unwrap().is_empty());
}
#[tokio::test]
async fn the_conversation_screen_reads_records_and_traces_with_channel_names() {
let (a, base) = api("api-history");
let data = base.join("d");
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
assert_eq!(a.call("history_query", json!({})).await.unwrap()["missing"], true);
let before = a.call("history_stamp", json!({})).await.unwrap();
std::fs::create_dir_all(data.join("memory")).unwrap();
let c = rusqlite::Connection::open(data.join("memory").join("history.sqlite")).unwrap();
c.execute_batch(crate::history_view::TEST_SCHEMA).unwrap();
c.execute_batch("INSERT INTO history(ts, kind, channel_id, author_id, author_name, text, norm)
VALUES (1, 'chat', '123456789012345678', '1', 'Alice', '안녕', '안녕');
INSERT INTO traces(ts, via, channel_id, user_id, question, answer, ms, steps)
VALUES (2, 'chat', '123456789012345678', '1', '안녕', '반가워요', 5, '[]');").unwrap();
a.call("settings_apply", json!({"changes": {"chatChannels": [{"id": "123456789012345678", "name": "잡담"}]}})).await.unwrap();
let v = a.call("history_query", json!({"thought": false})).await.unwrap();
assert_eq!(v["items"].as_array().unwrap().len(), 1);
assert_eq!(v["items"][0]["who"]["name"], "Alice");
assert_eq!(v["channels"][0]["name"], "잡담");
let v = a.call("history_query", json!({"said": false, "find": "반가"})).await.unwrap();
assert_eq!(v["items"][0]["type"], "thought");
// The screen polls the stamp and reads again only when it changed.
let now = a.call("history_stamp", json!({})).await.unwrap();
assert_ne!(now["stamp"], before["stamp"]);
assert_eq!(a.call("history_stamp", json!({})).await.unwrap(), now);
}
#[tokio::test]
async fn the_log_screen_saves_the_shown_lines_the_days_conversation_and_the_voice_recordings() {
let (a, base) = api("api-exports");
let data = base.join("d");
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
a.call("token_save", json!({"token": "abc.def.ghijkl"})).await.unwrap();
// The lines as shown, with a stored secret masked even if it was on screen.
let r = a.call("logs_save_text", json!({"text": "12:00:00 INFO [app] started abc.def.ghijkl"})).await.unwrap();
let saved = std::fs::read_to_string(r["path"].as_str().unwrap()).unwrap();
assert!(saved.contains("[app] started") && !saved.contains("abc.def.ghijkl"), "{saved}");
// The conversation of a day, in full.
std::fs::create_dir_all(data.join("memory")).unwrap();
let c = rusqlite::Connection::open(data.join("memory").join("history.sqlite")).unwrap();
c.execute_batch(crate::history_view::TEST_SCHEMA).unwrap();
let now = chrono::Local::now().timestamp() as f64;
c.execute("INSERT INTO history(ts, kind, channel_id, author_id, author_name, text, norm) VALUES (?, 'voice', 'vc', '1', 'Alice', '아이유 신곡 틀어 줘', '')",
[now]).unwrap();
c.execute("INSERT INTO traces(ts, via, channel_id, user_id, question, answer, ms, steps) VALUES (?, 'voice', 'vc', '1', '아이유 신곡 틀어 줘', '틀었습니다', 900, ?)",
rusqlite::params![now + 1.0, r#"[{"kind":"tool","name":"botBrowser","args":{"action":"open"},"ok":true,"result":"Media: paused"}]"#]).unwrap();
c.execute("INSERT INTO history(ts, kind, channel_id, author_id, author_name, text, norm) VALUES (?, 'voice', 'vc', '1', 'Alice', '어제 한 말', '')",
[now - 86400.0 * 2.0]).unwrap();
let today = chrono::Local::now().date_naive().to_string();
let r = a.call("history_export", json!({"from": today, "to": today})).await.unwrap();
assert_eq!(r["items"], 2);
let talk = std::fs::read_to_string(r["path"].as_str().unwrap()).unwrap();
for want in ["Alice(1) · 음성", "아이유 신곡 틀어 줘", "도구 호출: botBrowser (성공)", "Media: paused", "답: 틀었습니다"] {
assert!(talk.contains(want), "{want} in {talk}");
}
assert!(!talk.contains("어제 한 말"));
assert!(a.call("history_export", json!({"from": "어제", "to": today})).await.is_err());
// The voice recordings of the day (none kept yet: a zip that says so).
let r = a.call("voice_export", json!({"from": today, "to": today})).await.unwrap();
assert_eq!(r["files"], 0);
assert!(std::path::Path::new(r["path"].as_str().unwrap()).starts_with(data.join("logs")));
}
#[tokio::test]
async fn the_current_session_shows_only_what_came_since_the_latest_start() {
let (a, base) = api("api-history-session");
let data = base.join("d");
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
std::fs::create_dir_all(data.join("memory")).unwrap();
let c = rusqlite::Connection::open(data.join("memory").join("history.sqlite")).unwrap();
c.execute_batch(crate::history_view::TEST_SCHEMA).unwrap();
let rec = |ts: f64, text: &str| c.execute("INSERT INTO history(ts, kind, channel_id, author_id, author_name, text, norm) \
VALUES (?, 'voice', 'vc', '1', 'Alice', ?, ?)", rusqlite::params![ts, text, text]).unwrap();
rec(1.0, "지난번 말");
let texts = |v: &Value| v["items"].as_array().unwrap().iter().map(|i| i["text"].as_str().unwrap().to_string()).collect::<Vec<_>>();
// Not started yet in this app run: no session, so nothing in it.
let v = a.call("history_query", json!({"session": true})).await.unwrap();
assert_eq!((texts(&v), v["session"].clone()), (Vec::<String>::new(), Value::Null));
a.call("service_start", json!({})).await.unwrap();
let started = a.call("history_query", json!({})).await.unwrap()["session"].as_f64().unwrap();
rec(started + 1.0, "이번 말");
assert_eq!(texts(&a.call("history_query", json!({"session": true})).await.unwrap()), ["이번 말"]);
assert_eq!(texts(&a.call("history_query", json!({})).await.unwrap()), ["지난번 말", "이번 말"]);
a.shutdown().await.unwrap();
}
#[tokio::test]
async fn the_activity_screen_reads_the_newest_entries() {
let (a, base) = api("api-activity");
let data = base.join("d");
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
assert_eq!(a.call("activity_list", json!({})).await.unwrap()["items"], json!([]));
let log = crate::activity::Activity::new(&data);
log.record("chat.send", "채널 1", None, true, None);
log.record("chat.delete", "채널 1 메시지 2", Some("9 가".into()), false, Some("no".into()));
let items = a.call("activity_list", json!({"limit": 1})).await.unwrap()["items"].clone();
assert_eq!(items.as_array().unwrap().len(), 1);
assert_eq!(items[0]["kind"], "chat.delete");
}
#[tokio::test]
async fn the_schedule_screen_lists_everyones_schedules_and_deletes_any() {
let (a, base) = api("api-schedule");
let data = base.join("d");
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
assert_eq!(a.call("schedules_list", json!({})).await.unwrap()["items"], json!([]));
let store = crate::schedule::Store::new(&data);
let now = chrono::Utc::now().timestamp();
store.add(123456789012345678, "가", "remind", "회의", now + 600, "none", "voice", None, now).unwrap();
let b = store.add(9, "나", "task", "날씨", now + 60, "daily", "chat", Some(77), now).unwrap();
let items = a.call("schedules_list", json!({})).await.unwrap()["items"].as_array().unwrap().clone();
// Soonest first; IDs as strings (JSON numbers lose Discord IDs).
assert_eq!(items.iter().map(|i| i["text"].as_str().unwrap()).collect::<Vec<_>>(), ["날씨", "회의"]);
assert_eq!(items[1]["user"], "123456789012345678");
assert_eq!(items[0]["channel"], "77");
a.call("schedule_delete", json!({"id": b.id.to_string()})).await.unwrap();
assert_eq!(store.all().unwrap().len(), 1);
assert!(a.call("schedule_delete", json!({"id": b.id.to_string()})).await.is_err());
}
#[tokio::test]
async fn collection_targets_are_saved_and_their_results_read_from_the_data_folder() {
let (a, base) = api("api-collect");
let data = base.join("d");
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
let targets = json!([{"name": "뉴스", "kind": "rss", "value": "https://feed.example/rss", "everyMinutes": 30}]);
a.call("settings_apply", json!({"changes": {"collect.targets": targets, "collect.keepDays": 7}})).await.unwrap();
assert_eq!(a.call("settings_view", json!({})).await.unwrap()["collect.targets"], targets);
let day = data.join("collect").join("뉴스");
std::fs::create_dir_all(&day).unwrap();
std::fs::write(day.join("2026-11-13.jsonl"), "{\"at\": \"2026-11-13T09:00:00+09:00\", \"title\": \"t\"}\n").unwrap();
let r = a.call("collect_results", json!({"target": null})).await.unwrap();
assert_eq!(r, json!({"targets": ["뉴스"], "items": [{"at": "2026-11-13T09:00:00+09:00", "title": "t", "target": "뉴스"}]}));
assert!(a.call("collect_results", json!({"target": "../config"})).await.is_err());
}
#[tokio::test]
async fn the_kma_key_is_stored_encrypted_shown_masked_kept_by_mcp_saves_and_removed_when_empty() {
let (a, base) = api("api-kma");
let data = base.join("d");
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
assert_eq!(a.call("kma_key_status", json!({})).await.unwrap()["set"], json!(false));
let r = a.call("kma_key_set", json!({"value": " kma-key-5678 "})).await.unwrap();
assert_eq!((r["set"].clone(), r["masked"].clone()), (json!(true), json!("••••5678")));
assert_eq!(a.call("kma_key_status", json!({})).await.unwrap(), json!({"set": true, "masked": "••••5678"}));
if cfg!(windows) {
assert!(!String::from_utf8_lossy(&std::fs::read(data.join("config").join("secrets.dat")).unwrap()).contains("kma-key-5678"));
}
a.hub.push(Level::Error, "llm", "weather said kma-key-5678");
assert!(!a.call("logs_error_report", json!({})).await.unwrap()["report"].as_str().unwrap().contains("kma-key-5678"));
// Saving the MCP servers removes only their own values.
a.call("settings_apply", json!({"changes": {"mcpServers": []}})).await.unwrap();
assert_eq!(a.call("kma_key_status", json!({})).await.unwrap()["set"], json!(true));
assert!(!std::fs::read_to_string(data.join("config").join("settings.json")).unwrap_or_default().contains("kma-key-5678"));
a.call("kma_key_set", json!({"value": ""})).await.unwrap();
assert_eq!(a.call("kma_key_status", json!({})).await.unwrap(), json!({"set": false, "masked": null}));
}
#[tokio::test]
async fn mcp_values_are_stored_encrypted_shown_only_as_set_masked_in_logs_and_go_with_their_server() {
let (a, base) = api("api-mcp");
let data = base.join("d");
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
let server = json!([{"name": "brave", "command": "npx", "env": ["BRAVE_API_KEY"]}]);
// A value for a server that is not saved yet is refused.
assert!(a.call("mcp_env_set", json!({"server": "brave", "name": "BRAVE_API_KEY", "value": "k"})).await.is_err());
a.call("settings_apply", json!({"changes": {"mcpServers": server}})).await.unwrap();
a.call("mcp_env_set", json!({"server": "brave", "name": "BRAVE_API_KEY", "value": "brave-key-123"})).await.unwrap();
assert_eq!(a.call("mcp_env_status", json!({})).await.unwrap(), json!({"brave": {"BRAVE_API_KEY": true}}));
for f in ["settings.json", "secrets.dat"] {
let bytes = std::fs::read(data.join("config").join(f)).unwrap();
if cfg!(windows) || f == "settings.json" {
assert!(!String::from_utf8_lossy(&bytes).contains("brave-key-123"), "{f}");
}
}
a.hub.push(Level::Error, "llm", "server said brave-key-123");
let report = a.call("logs_error_report", json!({})).await.unwrap()["report"].as_str().unwrap().to_owned();
assert!(report.contains("server said") && !report.contains("brave-key-123"));
// A new app on the same folder masks it too, before anything is saved again.
let b = AdminApi::new(&a.location_file, LogHub::new(None));
b.hub.push(Level::Error, "llm", "again brave-key-123");
assert!(!b.call("logs_error_report", json!({})).await.unwrap()["report"].as_str().unwrap().contains("brave-key-123"));
// Removing the server removes its value.
a.call("settings_apply", json!({"changes": {"mcpServers": []}})).await.unwrap();
let secrets = Secrets::new(&data.join("config").join("secrets.dat"));
assert!(secrets.names().unwrap().iter().all(|n| !n.starts_with("mcp:")));
}
#[tokio::test]
async fn a_key_replaced_or_a_server_removed_while_running_stays_masked_in_late_worker_lines() {
let (a, base) = api("api-mcp-run");
let data = base.join("d");
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
let servers = json!([{"name": "brave", "command": "npx", "env": ["BRAVE_API_KEY"]},
{"name": "other", "command": "npx", "env": ["OTHER_KEY"]}]);
a.call("settings_apply", json!({"changes": {"mcpServers": servers}})).await.unwrap();
a.call("mcp_env_set", json!({"server": "brave", "name": "BRAVE_API_KEY", "value": "old-brave-key"})).await.unwrap();
a.call("mcp_env_set", json!({"server": "other", "name": "OTHER_KEY", "value": "old-other-key"})).await.unwrap();
// The services start with these values (services.rs does this on every start).
a.hub.set_secrets_in_use(vec!["old-brave-key".into(), "old-other-key".into()]);
// While they run, one key is replaced and the other server is removed.
a.call("mcp_env_set", json!({"server": "brave", "name": "BRAVE_API_KEY", "value": "new-brave-key"})).await.unwrap();
let brave = json!([{"name": "brave", "command": "npx", "env": ["BRAVE_API_KEY"]}]);
a.call("settings_apply", json!({"changes": {"mcpServers": brave}})).await.unwrap();
// The running worker still prints the old values afterwards.
a.hub.push_worker("[ llm ] Error: brave failed with old-brave-key, other with old-other-key");
let shown = a.call("logs_query", json!({})).await.unwrap().to_string();
let report = a.call("logs_error_report", json!({})).await.unwrap()["report"].as_str().unwrap().to_owned();
assert!(report.contains("brave failed with"), "{report}");
for old in ["old-brave-key", "old-other-key"] {
assert!(!shown.contains(old) && !report.contains(old), "{old}");
}
}
#[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());
}
static LAUNCHED: Mutex<Option<PathBuf>> = Mutex::new(None);
fn fake_launch(p: &Path) -> Result<(), String> {
*LAUNCHED.lock().unwrap() = Some(p.to_path_buf());
Ok(())
}
fn refused_launch(_: &Path) -> Result<(), String> {
Err("관리자 권한을 받지 못해 업데이트를 설치하지 않았습니다".into())
}
#[tokio::test]
async fn an_update_is_installed_only_once_downloaded_and_checked_after_stopping_what_runs() {
let (mut a, base) = api("apiupd");
a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap();
a.call("dashboard", json!({})).await.unwrap();
assert!(a.call("update_install", json!({})).await.unwrap_err().contains("먼저 받아"));
let installer = b"setup".to_vec();
let sum = format!("{:x}", <sha2::Sha256 as sha2::Digest>::digest(&installer));
let src = format!("{}/releases", crate::update::tests::gitea("9.0.0", installer, sum).await);
*a.updater.lock().unwrap() = Some(crate::update::Updater::new(src, APP_VERSION, base.join("d/cache/updates")));
assert_eq!(a.call("update_check", json!({})).await.unwrap()["latest"]["version"], json!("9.0.0"));
a.call("update_download", json!({})).await.unwrap();
for _ in 0..200 {
if a.call("update_status", json!({})).await.unwrap()["phase"] != json!("downloading") { break }
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
a.launcher = refused_launch;
assert!(a.call("update_install", json!({})).await.unwrap_err().contains("서비스는 정지된 상태"));
a.launcher = fake_launch;
assert_eq!(a.call("update_install", json!({})).await.unwrap(), json!({"exit": true}));
assert_eq!(LAUNCHED.lock().unwrap().clone(), Some(base.join("d/cache/updates/Jarvis-Setup-9.0.0.exe")));
assert_eq!(a.call("dashboard", json!({})).await.unwrap()["state"], json!("stopped"));
}
#[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<crate::channel_sync::ChannelInfo>);
#[async_trait::async_trait]
impl crate::channel_sync::ChannelApi for OneChannel {
async fn info(&self, _: u64) -> Result<crate::channel_sync::ChannelInfo, crate::channel_sync::ApiError> {
Ok(self.0.lock().unwrap().clone())
}
async fn edit(&self, _: u64, name: Option<&str>, topic: Option<&str>)
-> Result<crate::channel_sync::ChannelInfo, crate::channel_sync::ApiError> {
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 the_display_driver_and_the_services_never_change_at_the_same_time() {
let (a, base) = api("api5");
a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap();
// While the services start (or run), the driver is neither installed nor removed.
a.call("service_start", json!({})).await.unwrap();
for cmd in ["display_driver_install", "display_driver_uninstall"] {
assert!(a.call(cmd, json!({})).await.unwrap_err().contains("정지"), "{cmd}");
}
a.call("service_stop", json!({})).await.unwrap();
for _ in 0..200 {
if a.call("dashboard", json!({})).await.unwrap()["state"] == json!("stopped") { break; }
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
// While a driver task runs, the services do not start and no second task begins.
a.begin_driver_task().unwrap();
assert!(a.call("service_start", json!({})).await.unwrap_err().contains("드라이버"));
assert!(a.begin_driver_task().is_err());
assert_eq!(a.call("dashboard", json!({})).await.unwrap()["state"], json!("stopped"));
// A finished task (here off Windows it fails at once) frees both again.
*a.driver_busy.lock().unwrap() = false;
assert!(a.call("display_driver_install", json!({})).await.is_err());
assert!(!*a.driver_busy.lock().unwrap(), "a failed task does not stay running");
a.call("service_start", json!({})).await.unwrap();
a.call("service_stop", json!({})).await.unwrap();
}
#[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");
}
}