The management app reads the worker's history store (read only) and shows people's words, Jarvis's answers and the answer traces in time order, with filters for kind, place, person, channel, day and text, live follow, older items on demand and expandable traces (records given, tools offered, plan, model thinking, tool calls and results). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
860 lines
49 KiB
Rust
860 lines
49 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};
|
|
|
|
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}은(는) 글자여야 합니다"))
|
|
}
|
|
|
|
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())
|
|
}
|
|
|
|
/// 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> {
|
|
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)}))
|
|
}
|
|
"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);
|
|
}
|
|
let restart = changes.keys().any(|k| k != "voice.tts.speed");
|
|
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"): 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);
|
|
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: args.get("since").and_then(Value::as_f64), until: args.get("until").and_then(Value::as_f64),
|
|
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());
|
|
}
|
|
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 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), 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_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);
|
|
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");
|
|
}
|
|
|
|
#[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 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");
|
|
}
|
|
}
|