diff --git a/app/Cargo.toml b/app/Cargo.toml index e5332fd..8b03254 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -41,7 +41,7 @@ codegen-units = 4 strip = "symbols" [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Cryptography", "Win32_System_SystemInformation"] } +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security_Cryptography", "Win32_System_SystemInformation"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/app/shell/src/main.rs b/app/shell/src/main.rs index 2f20ff7..59289c7 100644 --- a/app/shell/src/main.rs +++ b/app/shell/src/main.rs @@ -1,23 +1,33 @@ -//! Jarvis management app: one Tauri 2 window over the app core (`app/src/admin.spec.md`, "Screens"). -//! The screens (`app/ui`) call `invoke("admin", {command, args})`, passed to the same `AdminApi` the -//! development server uses. Closing the window stops the services the app started. +//! Jarvis management app: one Tauri 2 window over the app core (`app/src/admin.spec.md`, "Window +//! and Windows build"). The screens (`app/ui`) call `invoke("admin", {command, args})`, passed to the +//! same `AdminApi` the development server uses. Closing the window first stops what the app started; +//! if that cannot be confirmed the window stays open and says so, and closing it again quits. //! //! jarvis [--location FILE] #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use std::path::PathBuf; +use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::Arc; use jarvis_app::admin_api::AdminApi; use serde_json::Value; -use tauri::{Manager, RunEvent, WebviewUrl, WebviewWindowBuilder}; +use tauri::{Emitter, Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent}; -struct Api(Arc); +/// Where closing stands: open, closing (stopping what runs), or the stop could not be confirmed. +const OPEN: u8 = 0; +const CLOSING: u8 = 1; +const CLOSE_FAILED: u8 = 2; + +struct Api { + api: Arc, + phase: AtomicU8, +} #[tauri::command] -async fn admin(api: tauri::State<'_, Api>, command: String, args: Option) -> Result { - api.0.call(&command, args.unwrap_or(Value::Null)).await +async fn admin(state: tauri::State<'_, Api>, command: String, args: Option) -> Result { + state.api.call(&command, args.unwrap_or(Value::Null)).await } fn arg(name: &str) -> Option { @@ -33,30 +43,62 @@ fn main() { let hub = jarvis_app::logs::LogHub::new(logs.as_deref()); jarvis_app::logs::install(hub.clone()); let api = Arc::new(AdminApi::new(&location, hub)); - // The window's own browser data sits next to the location file, not in a folder of its own. - let webview_data = location.parent().map(|p| p.join("webview")); + // The window's browser data: in the data folder, or a scratch folder in the system temp folder + // before there is one. WebView2 holds that folder until this process has ended, so scratch + // folders of earlier runs are removed here, at the next start. + jarvis_app::datadir::remove_scratch_webview(&std::env::temp_dir(), None); + let (webview_data, _) = jarvis_app::datadir::webview_data_dir(&location); let app = tauri::Builder::default() - .manage(Api(api.clone())) + .manage(Api { api, phase: AtomicU8::new(OPEN) }) .invoke_handler(tauri::generate_handler![admin]) - .setup(move |app| { - let mut w = WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into())) - .title("Jarvis 관리") - .inner_size(1200.0, 820.0) - .min_inner_size(900.0, 600.0); - if let Some(dir) = webview_data.clone() { - w = w.data_directory(dir); + .setup({ + move |app| { + WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into())) + .title("Jarvis 관리") + .inner_size(1200.0, 820.0) + .min_inner_size(900.0, 600.0) + .data_directory(webview_data) + .build()?; + Ok(()) + } + }) + .on_window_event(|window, event| { + let WindowEvent::CloseRequested { api: close, .. } = event else { return }; + let state = window.state::(); + match state.phase.load(Ordering::SeqCst) { + CLOSE_FAILED => { + jarvis_app::warn_log!("app", "window closed again: quitting although the stop was not confirmed"); + } + CLOSING => close.prevent_close(), + _ => { + close.prevent_close(); + state.phase.store(CLOSING, Ordering::SeqCst); + let _ = window.emit("closing", ()); + let (handle, api) = (window.app_handle().clone(), state.api.clone()); + tauri::async_runtime::spawn(async move { + jarvis_app::info_log!("app", "window closing: stopping what the app started"); + match api.shutdown().await { + Ok(()) => handle.exit(0), + Err(e) => { + handle.state::().phase.store(CLOSE_FAILED, Ordering::SeqCst); + let _ = handle.emit("close-failed", e); + } + } + }); + } } - w.build()?; - Ok(()) }) .build(tauri::generate_context!()) .expect("the window did not start"); app.run(move |handle, event| { - if let RunEvent::ExitRequested { .. } = event { - jarvis_app::info_log!("app", "window closed: stopping the services"); - let api = handle.state::().0.clone(); - tauri::async_runtime::block_on(api.shutdown()); + match event { + // Quitting another way (the system shutting down) still stops what runs. + RunEvent::ExitRequested { .. } if handle.state::().phase.load(Ordering::SeqCst) == OPEN => { + let api = handle.state::().api.clone(); + let _ = tauri::async_runtime::block_on(api.shutdown()); + } + _ => {} } }); } diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 4adc7a8..6ab0014 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -165,7 +165,9 @@ The LLM itself (Qwen3.6-35B-A3B, about 23 GB) is downloaded by Strata on its fir - Every command runs with the layout's environment: `uv`'s cache and Pythons, `HF_HOME` (`models/hf`), `NLTK_DATA` (`models/nltk`), temp files (`cache/tmp`) and Strata's folders (on Windows also `APPDATA` and `LOCALAPPDATA`, where Strata and the NVIDIA shader cache write - whatever `STRATA_*` says), all inside the data folder. Python comes from `uv` only. Output lines go to the `install` log tab. + whatever `STRATA_*` says), all inside the data folder. Python comes from `uv` only. Output lines go to the `install` log tab. A line that is not UTF-8 (a + Windows PC without the UTF-8 option prints in its code page, CP949 for Korean) is read in the + PC's OEM code page, never ending the reading. - Downloads go to `.part`, continue with an HTTP range after a break (a server without ranges starts over), and are checked against the pinned SHA-256; a wrong checksum deletes the part. - When every step is done, `uv`'s download cache is cleaned (the venvs hold copies). @@ -207,6 +209,28 @@ start it first, so nothing answers before the brain can, and stop it last. `memory/jarvis.db`; the worker gets it as `JARVIS_CONFIG_PATH`. Loading it writes nothing to the home folder. +## Chat channel names and topics (`app/src/channel_sync.rs`) + +`docs/v2/conversation.md`, "채널 이름·주제 반영". A chat channel with `syncDiscord` (on by default) +keeps its Discord name and topic in step with its `name` and `description`: + +- Registering a channel fills empty name and description with the channel's Discord name and topic + (`discord_channel_info`). +- `settings_apply` with `chatChannels` first refuses a description over Discord's topic limit + (1,024 characters) of a syncing channel, saving nothing. After saving, each syncing channel that + is new, or whose name or description changed, is compared with Discord and edited where they + differ (a new channel never clears a Discord name or topic with an empty field). Discord's form of + the name (spaces become `-`) is written back to the settings so the screen shows it. The results + come back in `sync` (`applied` with the name, `pending` with the wait, `failed` with the reason) + and stay readable with `channel_sync_status`. +- Discord allows about two name or topic edits per channel in ten minutes. A refused edit is + `pending` and tried again by itself after the wait Discord names, with what the settings hold + then; saving again while waiting adds no second retry. +- Without the Manage Channels permission (or any other refusal) the edit is `failed` with the + reason; the app keeps what the user wrote. +- The two calls go to Discord's REST API directly with the stored token (serenity's client would + wait out the rate limit itself, up to ten minutes). + ## Admin commands (`app/src/admin_api.rs`) `AdminApi::call(command, args)` is the one entry point of the screens, JSON in and out; errors come @@ -222,8 +246,9 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv | `token_check` `{token}` | the bot's tag and IDs, whether the Message Content intent is on, the invite link (REST only, nothing stored) | | `token_save` `{token}` / `token_status` | store it (masked from then on in logs) / `set` and the masked form, never the token | | `discord_guilds` / `discord_channels` `{guildId}` | the bot's servers / a server's voice and text channels, for the pickers | -| `settings_fields` / `settings_view` / `settings_apply` `{changes}` | the settings editor above; `restartNeeded` when the services run | +| `settings_fields` / `settings_view` / `settings_apply` `{changes}` | the settings editor above; `restartNeeded` when the services run; `sync` with the chat channels sent to Discord (below) | | `service_start` / `service_stop` / `service_restart` / `dashboard` | the controller and its snapshot; start and restart run in the background, stop also cancels a start | +| `discord_channel_info` `{id}` / `channel_sync_status` | a channel's Discord name and topic / each synced chat channel's last result (above) | | `install_status` / `install_start` / `install_cancel` | the install steps and their state, bytes and last line / run what is not done in the background / stop it | | `logs_query` `{tab, level, find, after, limit}` / `logs_error_report` / `logs_export` `{from, to}` | the log hub; the zip goes to `logs/` and its path comes back | @@ -263,9 +288,17 @@ URL), so other local programs cannot drive it. - `jarvis.exe` (crate `jarvis-shell`, Tauri 2 on the WebView2 Windows already has) opens one window with the screens (`app/ui`) and passes `invoke("admin", {command, args})` to `AdminApi::call`. `--location FILE` replaces the default location file (`%APPDATA%\JarvisBot\location.json`). - The window's own browser data goes next to the location file (`webview/`), nothing under - `%LOCALAPPDATA%`. Closing the window stops the services and waits until a start in progress is - cancelled (`AdminApi::shutdown`), so nothing the app started keeps running. + The window's own browser data (WebView2) goes in the data folder (`cache/webview`); before the + first-run wizard chose one it is a scratch folder in the system temp folder + (`JarvisBot-webview-`), which WebView2 holds until the process ends, so the next start + removes it. Nothing goes under `%LOCALAPPDATA%`, and `%APPDATA%\JarvisBot` holds only the + location file. +- Closing the window first runs `AdminApi::shutdown` and closes only when it succeeds: an install in + progress is cancelled and waited for (its commands and their children end), the services stop (a + start in progress is cancelled and waited for, up to 150 s), and after a failed run what may be + left is cleared (`Controller::shutdown`: the LLM's server stopped and confirmed gone). While that + runs the window says so; if it fails the window stays open with the reason, and closing it again + quits anyway. Quitting another way (the system shutting down) runs the same shutdown. - `app/shell/package.sh ` builds it on Linux (`x86_64-pc-windows-gnu`, mingw-w64) and lays out `Jarvis/`: `jarvis.exe`, `WebView2Loader.dll` and `python-src/` (the `voice_worker` and `jarvis` packages, no caches or specs). The worker's default sources are `python-src` next to the @@ -287,7 +320,15 @@ used without Strata, Strata missing, a fake Strata that reports progress, return stopped, is cancelled during its download and cleared, or fails with its last line, a stop that fails or hangs while the server still answers, holds connections silently or answers 503 (failed, not off, also through the controller) and one that fails while the port refuses connections (off); -a stop right after a background start running no launch at all, and the next start not cancelled; a background start that is starting at once, so a stop right after it cancels it +a stop right after a background start running no launch at all, and the next start not cancelled; +closing the app (the controller's shutdown after a failed stop: clean-up failing keeps it failed, +succeeding stops it; an install in progress cancelled and waited for); command output that is not +UTF-8 read on to the end; the window data folder (data folder, or a scratch folder removed later); +the TTS speed reaching the worker's arguments; chat channel names and topics (only new or edited +syncing channels sent, the topic limit refused before saving, Discord's form of the name written +back, a missing permission failing with the reason and the text kept, a rate-limited edit pending +and retried once with the latest text, a new channel never clearing Discord, unchanged ones not +edited; through `settings_apply` too); a background start that is starting at once, so a stop right after it cancels it and a second start is refused, also through the admin commands; a failed stop reported as failed; the brain's config loaded without writing to the home folder, `tests/test_config_db_path.py`); the dashboard from made-up events (captions replaced and cleared, latency stages and medians, an answer matched to its asker's final, missed requests without text); the admin diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs index 430c9be..c38f8ca 100644 --- a/app/src/admin_api.rs +++ b/app/src/admin_api.rs @@ -21,6 +21,7 @@ pub struct AdminApi { dir: Mutex>, controller: Mutex>>, installer: Mutex>>, + syncer: Mutex>>, hub: Arc, } @@ -45,7 +46,8 @@ impl AdminApi { /// `location_file`: where the data folder is remembered; `hub`: the app's log hub. pub fn new(location_file: &Path, hub: Arc) -> Self { let dir = DataDir::locate(location_file); - Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), installer: Mutex::new(None), hub } + Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), installer: Mutex::new(None), + syncer: Mutex::new(None), hub } } fn dir(&self) -> Result { @@ -86,26 +88,40 @@ impl AdminApi { Ok(i.clone().unwrap()) } + /// Keeps chat channel names and topics in step with Discord, with the stored bot token. + fn syncer(&self) -> Result, String> { + let dir = self.dir()?; + let mut s = self.syncer.lock().unwrap(); + Ok(s.get_or_insert_with(|| crate::channel_sync::Syncer::new( + Arc::new(crate::channel_sync::DiscordRest::new(dir.secrets_file())), dir.settings_file())).clone()) + } + fn controller(&self) -> Result, String> { let dir = self.dir()?; let mut c = self.controller.lock().unwrap(); Ok(c.get_or_insert_with(|| Controller::new(ServicesHost::new(dir.path().to_path_buf()))).clone()) } - /// Stop the services (and cancel a start) when the app closes, so nothing it started (the - /// worker, Strata) keeps running. - pub async fn shutdown(&self) { - let controller = self.controller.lock().unwrap().clone(); - if let Some(c) = controller { - if matches!(c.state(), State::Running | State::Starting) { - let _ = c.stop().await; - } - // A cancelled start finishes in the background: wait for it (Strata's stop takes up to - // two minutes) before the app exits. - let until = std::time::Instant::now() + std::time::Duration::from_secs(150); - while matches!(c.state(), State::Starting | State::Stopping) && std::time::Instant::now() < until { + /// 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(()), } } @@ -207,8 +223,39 @@ impl AdminApi { "settings_apply" => { let changes: Map = arg(&args, "changes")?.as_object().cloned() .ok_or("changes는 객체여야 합니다")?; - crate::settings_edit::apply(&self.dir()?.settings_file(), &changes).map_err(|e| e.0)?; - Ok(json!({"saved": changes.len(), "restartNeeded": self.controller()?.state() == crate::control::State::Running})) + let file = self.dir()?.settings_file(); + // Chat channels: a topic Discord would refuse is caught before saving; after saving, + // the edited channels go to Discord (admin.spec.md, "Chat channel names and topics"). + let chats = changes.get("chatChannels"); + let old = match chats { + Some(list) => { + let parsed = crate::settings::parse_settings(&json!({"chatChannels": list})).map_err(|e| e.0)?; + crate::channel_sync::check_topics(&parsed.chat_channels)?; + crate::settings::load_settings(&file).map_err(|e| e.0)?.chat_channels + } + None => vec![], + }; + crate::settings_edit::apply(&file, &changes).map_err(|e| e.0)?; + let mut sync = vec![]; + if chats.is_some() { + let new = crate::settings::load_settings(&file).map_err(|e| e.0)?.chat_channels; + let todo = crate::channel_sync::changed(&old, &new); + if !todo.is_empty() { + for (id, state) in self.syncer()?.sync(todo, &old).await { + let mut v = json!(state); + v["id"] = json!(id.to_string()); + sync.push(v); + } + } + } + Ok(json!({"saved": changes.len(), "restartNeeded": self.controller()?.state() == crate::control::State::Running, + "sync": sync})) + } + "channel_sync_status" => Ok(Value::Object(self.syncer()?.status().into_iter() + .map(|(id, s)| (id.to_string(), json!(s))).collect())), + "discord_channel_info" => { + let id: u64 = arg_str(&args, "id")?.trim().parse().map_err(|_| "채널 ID가 올바르지 않습니다")?; + Ok(json!(self.syncer()?.info(id).await?)) } // Starting can take long (the LLM's first start downloads the model), so it runs in the // background and the dashboard shows how it goes; stop also cancels a start. @@ -258,7 +305,8 @@ mod tests { 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), hub: LogHub::new(None) }, + (AdminApi { location_file: loc, dir: Mutex::new(None), controller: Mutex::new(None), installer: Mutex::new(None), syncer: Mutex::new(None), + hub: LogHub::new(None) }, base) } @@ -326,13 +374,83 @@ mod tests { #[tokio::test] async fn closing_the_app_while_starting_waits_until_everything_is_stopped() { let (a, base) = api("api5"); - a.shutdown().await; // nothing chosen or started yet + 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; + a.shutdown().await.unwrap(); assert_eq!(a.call("dashboard", json!({})).await.unwrap()["state"], json!("stopped")); } + /// A step that runs until it is cancelled (an install in progress when the window closes). + struct Endless; + #[async_trait::async_trait] + impl crate::install::Step for Endless { + fn id(&self) -> &'static str { "endless" } + fn label(&self) -> &'static str { "endless" } + fn size_hint(&self) -> &'static str { "" } + fn version(&self, _: &crate::install::Layout) -> String { "1".into() } + async fn run(&self, ctx: &crate::install::Ctx) -> Result<(), String> { + while !ctx.cancel.load(std::sync::atomic::Ordering::SeqCst) { + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + Err("cancelled".into()) + } + } + + #[tokio::test] + async fn closing_the_app_during_the_install_cancels_it_and_waits() { + let (a, base) = api("api6"); + a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap(); + let layout = crate::install::Layout { data: base.join("d"), src: PathBuf::from("src") }; + *a.installer.lock().unwrap() = Some(crate::install::Installer::new(layout, vec![Box::new(Endless)])); + a.call("install_start", json!({})).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + assert_eq!(a.call("install_status", json!({})).await.unwrap()["running"], json!(true)); + a.shutdown().await.unwrap(); + let st = a.call("install_status", json!({})).await.unwrap(); + assert_eq!((st["running"].clone(), st["steps"][0]["state"].clone()), (json!(false), json!("failed"))); + } + + /// Discord for the chat channel screen: one channel whose names lose their spaces. + struct OneChannel(Mutex); + #[async_trait::async_trait] + impl crate::channel_sync::ChannelApi for OneChannel { + async fn info(&self, _: u64) -> Result { + Ok(self.0.lock().unwrap().clone()) + } + async fn edit(&self, _: u64, name: Option<&str>, topic: Option<&str>) + -> Result { + let mut c = self.0.lock().unwrap(); + if let Some(n) = name { c.name = n.replace(' ', "-"); } + if let Some(t) = topic { c.topic = t.into(); } + Ok(c.clone()) + } + } + + #[tokio::test] + async fn saving_chat_channels_brings_their_names_and_topics_to_discord() { + let (a, base) = api("api7"); + a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap(); + let discord = Arc::new(OneChannel(Mutex::new(crate::channel_sync::ChannelInfo { name: "memo".into(), topic: "".into() }))); + let file = a.dir().unwrap().settings_file(); + *a.syncer.lock().unwrap() = Some(crate::channel_sync::Syncer::new(discord.clone(), file.clone())); + const ID: &str = "100000000000000001"; + // Registering fills the fields from Discord. + assert_eq!(a.call("discord_channel_info", json!({"id": ID})).await.unwrap()["name"], json!("memo")); + let r = a.call("settings_apply", json!({"changes": {"chatChannels": [ + {"id": ID, "name": "할 일 메모", "description": "오늘 할 일"}]}})).await.unwrap(); + assert_eq!(r["sync"][0], json!({"id": ID, "state": "applied", "name": "할-일-메모"})); + assert_eq!(discord.0.lock().unwrap().topic, "오늘 할 일"); + assert_eq!(a.call("settings_view", json!({})).await.unwrap()["chatChannels"][0]["name"], json!("할-일-메모")); + assert_eq!(a.call("channel_sync_status", json!({})).await.unwrap()[ID]["state"], json!("applied")); + // A topic over Discord's limit is refused and nothing is saved. + let before = std::fs::read_to_string(&file).unwrap(); + let e = a.call("settings_apply", json!({"changes": {"chatChannels": [ + {"id": ID, "name": "할-일-메모", "description": "가".repeat(1025)}]}})).await.unwrap_err(); + assert!(e.contains("1024"), "{e}"); + assert_eq!(std::fs::read_to_string(&file).unwrap(), before); + } + #[tokio::test] async fn a_start_is_starting_when_it_answers_so_a_stop_right_after_it_is_not_refused() { let (a, base) = api("api4"); diff --git a/app/src/channel_sync.rs b/app/src/channel_sync.rs new file mode 100644 index 0000000..6e7a411 --- /dev/null +++ b/app/src/channel_sync.rs @@ -0,0 +1,378 @@ +//! Chat channel names and topics kept in step with Discord (`app/src/admin.spec.md`, "Chat channel +//! names and topics"; `docs/v2/conversation.md`, "채널 이름·주제 반영"). When the chat channel +//! settings are saved, each channel with `syncDiscord` whose name or description changed gets them as +//! its Discord name and topic; Discord's own form of the name (spaces become `-`) is written back. +//! Discord allows only a few such edits per channel in ten minutes: a refused edit is "pending" and +//! tried again by itself after the wait Discord names. Without the permission (or any other refusal) +//! the edit is "failed" with the reason, and the app keeps what the user wrote. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use async_trait::async_trait; +use serde::Serialize; +use serde_json::{json, Value}; + +use crate::settings::ChatChannelSettings; + +/// Discord's limit for a channel topic. +pub const TOPIC_MAX: usize = 1024; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ChannelInfo { + pub name: String, + pub topic: String, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ApiError { + /// Too many edits: try again after this long. + RateLimited(Duration), + Failed(String), +} + +/// Discord's channel endpoints (a fake in tests). +#[async_trait] +pub trait ChannelApi: Send + Sync { + async fn info(&self, id: u64) -> Result; + /// Set what is given; returns the channel as Discord stored it. + async fn edit(&self, id: u64, name: Option<&str>, topic: Option<&str>) -> Result; +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "state", rename_all = "camelCase")] +pub enum SyncState { + Applied { name: String }, + #[serde(rename_all = "camelCase")] + Pending { retry_in_sec: u64 }, + Failed { reason: String }, +} + +/// Refuse (before anything is saved) a description Discord would not take as a topic. +pub fn check_topics(channels: &[ChatChannelSettings]) -> Result<(), String> { + match channels.iter().find(|c| c.sync_discord && c.description.chars().count() > TOPIC_MAX) { + Some(c) => Err(format!("채널 {}의 설명이 {}자를 넘어 디스코드 주제로 쓸 수 없습니다 ({}자)", c.id, TOPIC_MAX, + c.description.chars().count())), + None => Ok(()), + } +} + +/// The channels to bring to Discord after a save: `syncDiscord` on and new, or with another name or +/// description than before. +pub fn changed(old: &[ChatChannelSettings], new: &[ChatChannelSettings]) -> Vec { + new.iter().filter(|c| c.sync_discord) + .filter(|c| old.iter().find(|o| o.id == c.id) + .is_none_or(|o| o.name != c.name || o.description != c.description || !o.sync_discord)) + .cloned().collect() +} + +pub struct Syncer { + api: Arc, + settings_file: PathBuf, + status: Mutex>, + /// Channels with a retry already waiting (another save while waiting adds none). + retrying: Mutex>, +} + +impl Syncer { + pub fn new(api: Arc, settings_file: PathBuf) -> Arc { + Arc::new(Self { api, settings_file, status: Mutex::default(), retrying: Mutex::default() }) + } + + /// A channel's name and topic on Discord now (the screens fill a newly registered channel with them). + pub async fn info(&self, id: u64) -> Result { + self.api.info(id).await.map_err(|e| match e { + ApiError::RateLimited(w) => format!("디스코드가 {}초 뒤에 다시 물어 달라고 합니다", w.as_secs()), + ApiError::Failed(r) => r, + }) + } + + pub fn status(&self) -> HashMap { + self.status.lock().unwrap().clone() + } + + /// Bring these channels to Discord now; `old` tells which ones are new (a new one never clears a + /// Discord name or topic with an empty field). + pub async fn sync(self: &Arc, channels: Vec, old: &[ChatChannelSettings]) + -> Vec<(u64, SyncState)> { + let mut out = vec![]; + for c in channels { + let is_new = !old.iter().any(|o| o.id == c.id); + let state = self.sync_one(&c, is_new).await; + self.status.lock().unwrap().insert(c.id, state.clone()); + out.push((c.id, state)); + } + out + } + + async fn sync_one(self: &Arc, c: &ChatChannelSettings, is_new: bool) -> SyncState { + let current = match self.api.info(c.id).await { + Ok(i) => i, + Err(e) => return self.refused(c.id, e), + }; + let keep = |v: &str| !(is_new && v.trim().is_empty()); + let name = (keep(&c.name) && c.name != current.name).then_some(c.name.as_str()); + let topic = (keep(&c.description) && c.description != current.topic).then_some(c.description.as_str()); + if name.is_none() && topic.is_none() { + return SyncState::Applied { name: current.name }; + } + match self.api.edit(c.id, name, topic).await { + Ok(stored) => { + if keep(&c.name) && stored.name != c.name { + self.write_name(c.id, &stored.name); + } + crate::info_log!("chat", "channel {} name and topic updated on Discord", c.id); + SyncState::Applied { name: stored.name } + } + Err(e) => self.refused(c.id, e), + } + } + + fn refused(self: &Arc, id: u64, e: ApiError) -> SyncState { + match e { + ApiError::RateLimited(wait) => { + crate::info_log!("chat", "channel {id}: Discord asks to wait {}s before the next edit", wait.as_secs()); + if self.retrying.lock().unwrap().insert(id) { + let me = self.clone(); + tokio::spawn(async move { + tokio::time::sleep(wait).await; + me.retrying.lock().unwrap().remove(&id); + me.retry(id).await; + }); + } + SyncState::Pending { retry_in_sec: wait.as_secs().max(1) } + } + ApiError::Failed(reason) => { + crate::warn_log!("chat", "channel {id}: name and topic not updated on Discord: {reason}"); + SyncState::Failed { reason } + } + } + } + + /// Try a pending channel again with what the settings hold now. + async fn retry(self: &Arc, id: u64) { + let Ok(settings) = crate::settings::load_settings(&self.settings_file) else { return }; + match settings.chat_channels.into_iter().find(|c| c.id == id && c.sync_discord) { + Some(c) => { + let state = self.sync_one(&c, false).await; + self.status.lock().unwrap().insert(id, state); + } + None => { + self.status.lock().unwrap().remove(&id); + } + } + } + + /// Show Discord's form of the name (spaces become `-`) in the app too. + fn write_name(&self, id: u64, name: &str) { + let Ok(view) = crate::settings_edit::view(&self.settings_file) else { return }; + let Some(Value::Array(mut list)) = view.get("chatChannels").cloned() else { return }; + for c in &mut list { + if c["id"].as_str() == Some(id.to_string().as_str()) { + c["name"] = json!(name); + } + } + let mut changes = serde_json::Map::new(); + changes.insert("chatChannels".into(), Value::Array(list)); + if let Err(e) = crate::settings_edit::apply(&self.settings_file, &changes) { + crate::warn_log!("chat", "channel {id}: could not write Discord's name back: {}", e.0); + } + } +} + +/// Discord's REST API with the stored bot token. Serenity's client waits out rate limits by itself +/// (up to ten minutes for channel edits), so these two calls go out directly and report the wait. +pub struct DiscordRest { + pub secrets_file: PathBuf, + pub base: String, +} + +impl DiscordRest { + pub fn new(secrets_file: PathBuf) -> Self { + Self { secrets_file, base: "https://discord.com/api/v10".into() } + } + + async fn call(&self, req: impl FnOnce(&reqwest::Client, String) -> reqwest::RequestBuilder) -> Result { + let token = crate::secrets::Secrets::new(&self.secrets_file).get(crate::secrets::DISCORD_TOKEN) + .ok().flatten().ok_or_else(|| ApiError::Failed("봇 토큰이 저장되어 있지 않습니다".into()))?; + let client = reqwest::Client::builder().timeout(Duration::from_secs(15)).build() + .map_err(|e| ApiError::Failed(e.to_string()))?; + let r = req(&client, self.base.clone()).header("Authorization", format!("Bot {token}")) + .header("User-Agent", "DiscordBot (https://github.com/jarvis, 0.1)").send().await + .map_err(|e| ApiError::Failed(format!("디스코드에 연결하지 못했습니다: {e}")))?; + let status = r.status().as_u16(); + let body: Value = serde_json::from_str(&r.text().await.unwrap_or_default()).unwrap_or_default(); + match status { + 200..=299 => Ok(ChannelInfo { name: body["name"].as_str().unwrap_or_default().to_owned(), + topic: body["topic"].as_str().unwrap_or_default().to_owned() }), + 429 => Err(ApiError::RateLimited(Duration::from_secs_f64(body["retry_after"].as_f64().unwrap_or(60.0).ceil()))), + 403 => Err(ApiError::Failed("봇에 이 채널의 채널 관리 권한이 없습니다".into())), + 404 => Err(ApiError::Failed("디스코드에서 이 채널을 찾지 못했습니다".into())), + _ => Err(ApiError::Failed(format!("디스코드가 거절했습니다 ({status}): {}", + body["message"].as_str().unwrap_or_default()))), + } + } +} + +#[async_trait] +impl ChannelApi for DiscordRest { + async fn info(&self, id: u64) -> Result { + self.call(|c, base| c.get(format!("{base}/channels/{id}"))).await + } + + async fn edit(&self, id: u64, name: Option<&str>, topic: Option<&str>) -> Result { + let mut body = serde_json::Map::new(); + if let Some(n) = name { + body.insert("name".into(), json!(n)); + } + if let Some(t) = topic { + body.insert("topic".into(), json!(t)); + } + let body = Value::Object(body).to_string(); + self.call(move |c, base| c.patch(format!("{base}/channels/{id}")) + .header("Content-Type", "application/json").body(body)).await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::datadir::temp_dir; + + /// Discord as the tests need it: names lose their spaces, a channel may refuse, and the first + /// `limited` edits are rate limited. + #[derive(Default)] + struct FakeDiscord { + channels: Mutex>, + forbidden: Vec, + limited: Mutex, + edits: Mutex, Option)>>, + } + #[async_trait] + impl ChannelApi for FakeDiscord { + async fn info(&self, id: u64) -> Result { + self.channels.lock().unwrap().get(&id).cloned().ok_or_else(|| ApiError::Failed("없음".into())) + } + async fn edit(&self, id: u64, name: Option<&str>, topic: Option<&str>) -> Result { + if self.forbidden.contains(&id) { + return Err(ApiError::Failed("봇에 이 채널의 채널 관리 권한이 없습니다".into())); + } + { + let mut l = self.limited.lock().unwrap(); + if *l > 0 { + *l -= 1; + return Err(ApiError::RateLimited(Duration::from_millis(200))); + } + } + self.edits.lock().unwrap().push((id, name.map(String::from), topic.map(String::from))); + let mut chans = self.channels.lock().unwrap(); + let c = chans.get_mut(&id).unwrap(); + if let Some(n) = name { + c.name = n.replace(' ', "-"); + } + if let Some(t) = topic { + c.topic = t.into(); + } + Ok(c.clone()) + } + } + + const A: u64 = 100000000000000001; + const B: u64 = 100000000000000002; + + fn ch(id: u64, name: &str, description: &str) -> ChatChannelSettings { + ChatChannelSettings { id, name: name.into(), description: description.into(), read: true, send: true, edit: true, + react: true, delete: false, pin: false, answer_all: false, sync_discord: true } + } + + fn fake(forbidden: Vec, limited: u32) -> Arc { + let f = FakeDiscord { forbidden, limited: Mutex::new(limited), ..Default::default() }; + f.channels.lock().unwrap().insert(A, ChannelInfo { name: "일정".into(), topic: "".into() }); + f.channels.lock().unwrap().insert(B, ChannelInfo { name: "잡담".into(), topic: "아무 말".into() }); + Arc::new(f) + } + + fn settings_with(chans: &[ChatChannelSettings]) -> PathBuf { + let f = temp_dir("sync").join("settings.json"); + std::fs::create_dir_all(f.parent().unwrap()).unwrap(); + let list: Vec = chans.iter().map(|c| json!({"id": c.id.to_string(), "name": c.name, + "description": c.description})).collect(); + std::fs::write(&f, json!({"chatChannels": list}).to_string()).unwrap(); + f + } + + #[test] + fn only_new_or_edited_channels_that_keep_discord_in_step_are_sent() { + let old = vec![ch(A, "일정", ""), ch(B, "잡담", "아무 말")]; + let mut off = ch(B, "잡담2", "아무 말"); + off.sync_discord = false; + assert!(changed(&old, &old).is_empty()); + assert_eq!(changed(&old, &[ch(A, "일정 표", ""), off]).iter().map(|c| c.id).collect::>(), [A]); + assert_eq!(changed(&[], &[ch(B, "잡담", "아무 말")]).len(), 1, "a newly registered channel"); + } + + #[test] + fn a_topic_over_discord_s_limit_is_refused_before_saving() { + let long = "가".repeat(TOPIC_MAX + 1); + assert!(check_topics(&[ch(A, "일정", &long)]).unwrap_err().contains("1024")); + let mut off = ch(A, "일정", &long); + off.sync_discord = false; + assert!(check_topics(&[off]).is_ok(), "not sent to Discord: any length"); + } + + #[tokio::test] + async fn an_edit_reaches_discord_and_discord_s_form_of_the_name_comes_back() { + let d = fake(vec![], 0); + let file = settings_with(&[ch(A, "일정 표", "할 일")]); + let s = Syncer::new(d.clone(), file.clone()); + let out = s.sync(vec![ch(A, "일정 표", "할 일")], &[ch(A, "일정", "")]).await; + assert_eq!(out, [(A, SyncState::Applied { name: "일정-표".into() })]); + assert_eq!(d.channels.lock().unwrap()[&A], ChannelInfo { name: "일정-표".into(), topic: "할 일".into() }); + let saved = crate::settings::load_settings(&file).unwrap(); + assert_eq!(saved.chat_channels[0].name, "일정-표", "the app shows Discord's name"); + } + + #[tokio::test] + async fn without_permission_it_fails_with_the_reason_and_the_app_keeps_the_text() { + let d = fake(vec![A], 0); + let file = settings_with(&[ch(A, "일정 표", "할 일")]); + let s = Syncer::new(d.clone(), file.clone()); + let out = s.sync(vec![ch(A, "일정 표", "할 일")], &[]).await; + assert!(matches!(&out[0].1, SyncState::Failed { reason } if reason.contains("권한")), "{out:?}"); + assert_eq!(crate::settings::load_settings(&file).unwrap().chat_channels[0].name, "일정 표"); + assert_eq!(d.channels.lock().unwrap()[&A].name, "일정"); + } + + #[tokio::test] + async fn a_rate_limited_edit_is_pending_and_goes_through_by_itself_with_the_latest_text() { + let d = fake(vec![], 1); + let file = settings_with(&[ch(A, "일정 표", "할 일")]); + let s = Syncer::new(d.clone(), file.clone()); + let out = s.sync(vec![ch(A, "일정 표", "할 일")], &[ch(A, "일정", "")]).await; + assert!(matches!(out[0].1, SyncState::Pending { .. }), "{out:?}"); + // Edited again while waiting: the retry sends what the settings hold then. + std::fs::write(&file, json!({"chatChannels": [{"id": A.to_string(), "name": "일정 표 2", "description": "할 일"}]}) + .to_string()).unwrap(); + // A second save while waiting is pending too, but adds no second retry. + *d.limited.lock().unwrap() = 1; + let again = s.sync(vec![ch(A, "일정 표 2", "할 일")], &[ch(A, "일정 표", "할 일")]).await; + assert!(matches!(again[0].1, SyncState::Pending { .. }), "{again:?}"); + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!(s.status()[&A], SyncState::Applied { name: "일정-표-2".into() }); + assert_eq!(d.channels.lock().unwrap()[&A].name, "일정-표-2"); + assert_eq!(d.edits.lock().unwrap().len(), 1, "one retry, one edit"); + } + + #[tokio::test] + async fn a_new_channel_with_empty_fields_never_clears_discord_and_unchanged_ones_are_not_edited() { + let d = fake(vec![], 0); + let s = Syncer::new(d.clone(), settings_with(&[])); + let out = s.sync(vec![ch(B, "", "")], &[]).await; + assert_eq!(out, [(B, SyncState::Applied { name: "잡담".into() })]); + assert_eq!(d.channels.lock().unwrap()[&B].topic, "아무 말"); + s.sync(vec![ch(B, "잡담", "아무 말")], &[]).await; + assert!(d.edits.lock().unwrap().is_empty(), "nothing differs from Discord: no edit"); + } +} diff --git a/app/src/chat.rs b/app/src/chat.rs index a3e358b..6436ba9 100644 --- a/app/src/chat.rs +++ b/app/src/chat.rs @@ -178,7 +178,7 @@ mod tests { fn ch(id: u64, read: bool, send: bool) -> ChatChannelSettings { ChatChannelSettings { id, name: String::new(), description: String::new(), read, send, edit: true, - react: true, delete: false, pin: false, answer_all: false } + react: true, delete: false, pin: false, answer_all: false, sync_discord: true } } #[test] diff --git a/app/src/control.rs b/app/src/control.rs index aa57f74..b58a527 100644 --- a/app/src/control.rs +++ b/app/src/control.rs @@ -48,6 +48,10 @@ pub trait Host: Send + Sync + 'static { fn llm(&self) -> Value { Value::Null } + /// After a failed run (a start or a stop that could not clear everything): stop what may be left. + async fn cleanup(&self) -> Result<(), String> { + Ok(()) + } } struct Inner { @@ -211,6 +215,40 @@ impl Controller { } } + /// The app is closing: stop what runs (a start in progress is cancelled and waited for, up to + /// 150 s), then, if the state is failed, clear what may be left. Ok means nothing is left running. + pub async fn shutdown(&self) -> Result<(), String> { + if matches!(self.state(), State::Running | State::Starting) { + let _ = self.stop().await; + } + let until = Instant::now() + Duration::from_secs(150); + while matches!(self.state(), State::Starting | State::Stopping) { + if Instant::now() >= until { + return Err("서비스가 아직 멈추지 않았습니다".into()); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + if self.state() != State::Failed { + return Ok(()); + } + match self.host.cleanup().await { + Ok(()) => { + let mut i = self.inner.lock().unwrap(); + i.state = State::Stopped; + i.error = None; + drop(i); + crate::info_log!("app", "cleared what the failed run left"); + Ok(()) + } + Err(e) => { + let e = crate::logs::redact(&e, &self.host.secrets()); + crate::error_log!("app", "could not clear what the failed run left: {e}"); + self.inner.lock().unwrap().error = Some(e.clone()); + Err(e) + } + } + } + pub async fn restart(&self) -> Result<(), String> { if self.state() == State::Running { self.stop().await?; @@ -297,6 +335,14 @@ impl Host for ServicesHost { fn llm(&self) -> Value { json!(self.llm.status()) } + + async fn cleanup(&self) -> Result<(), String> { + if self.llm.status().state == crate::strata::LlmState::Failed { + self.llm.stop().await + } else { + Ok(()) + } + } } #[async_trait] @@ -328,6 +374,8 @@ mod tests { starts: AtomicU32, stops: AtomicU32, stop_fails: std::sync::atomic::AtomicBool, + cleanups: AtomicU32, + cleanup_fails: std::sync::atomic::AtomicBool, } struct FakeRunning(Arc); @@ -378,6 +426,10 @@ mod tests { fn secrets(&self) -> Vec { self.0.secrets() } + async fn cleanup(&self) -> Result<(), String> { + self.0.counts.cleanups.fetch_add(1, Ordering::SeqCst); + if self.0.counts.cleanup_fails.load(Ordering::SeqCst) { Err("Strata를 끄지 못했습니다".into()) } else { Ok(()) } + } } (Controller::new(Shared(host.clone())), counts, host) } @@ -464,6 +516,23 @@ mod tests { assert_eq!(c.state(), State::Running); } + #[tokio::test] + async fn closing_the_app_after_a_failed_stop_clears_what_is_left_or_says_it_could_not() { + let (c, counts, _) = controller(0); + c.shutdown().await.unwrap(); // nothing ran: nothing to do + assert_eq!(counts.cleanups.load(Ordering::SeqCst), 0); + c.start().await.unwrap(); + counts.stop_fails.store(true, Ordering::SeqCst); + counts.cleanup_fails.store(true, Ordering::SeqCst); + assert!(c.shutdown().await.is_err(), "the stop and the clean-up both failed"); + assert_eq!(c.state(), State::Failed); + counts.cleanup_fails.store(false, Ordering::SeqCst); + c.shutdown().await.unwrap(); + let s = c.snapshot().await; + assert_eq!((s["state"].clone(), s["error"].clone()), (json!("stopped"), Value::Null)); + assert_eq!(counts.cleanups.load(Ordering::SeqCst), 2); + } + #[tokio::test] async fn start_and_stop_follow_the_state_rules() { let (c, counts, _) = controller(0); diff --git a/app/src/datadir.rs b/app/src/datadir.rs index d0e55d9..7606f7d 100644 --- a/app/src/datadir.rs +++ b/app/src/datadir.rs @@ -99,6 +99,32 @@ pub fn default_location_file() -> Option { Some(base.join("jarvis-bot").join("location.json")) } +/// Where the window's own browser data (WebView2) goes: `cache/webview` in the data folder once +/// there is one. Before the first-run wizard chose a folder it is a scratch folder in the system +/// temp folder (`JarvisBot-webview-`, `true`); WebView2 holds it until the app's process +/// has ended, so the app removes it on its next start (`remove_scratch_webview`). +pub fn webview_data_dir(location_file: &Path) -> (PathBuf, bool) { + match DataDir::locate(location_file) { + Some(d) => (d.path().join("cache").join("webview"), false), + None => (std::env::temp_dir().join(format!("{WEBVIEW_SCRATCH}{}", std::process::id())), true), + } +} + +const WEBVIEW_SCRATCH: &str = "JarvisBot-webview-"; + +/// Remove the scratch browser data folders in `temp` (all of them, or only `only`); a folder still in +/// use stays and goes next time. +pub fn remove_scratch_webview(temp: &Path, only: Option<&Path>) { + let Ok(rd) = std::fs::read_dir(temp) else { return }; + for e in rd.flatten() { + let p = e.path(); + let ours = p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(WEBVIEW_SCRATCH)); + if ours && only.is_none_or(|o| o == p) { + let _ = std::fs::remove_dir_all(&p); + } + } +} + /// Free bytes on the disk that holds `path` (or its nearest existing parent). pub fn free_bytes(path: &Path) -> Result { let mut p = path; @@ -145,6 +171,27 @@ mod tests { assert_eq!(d.settings_file(), root.join("config").join("settings.json")); } + #[test] + fn the_window_data_goes_in_the_data_folder_or_a_scratch_folder_that_is_removed() { + let root = temp_dir("wv"); + let loc = root.join("cfg").join("location.json"); + let (dir, scratch) = webview_data_dir(&loc); + assert!(scratch && dir.starts_with(std::env::temp_dir()), "no folder chosen yet: scratch in temp"); + DataDir::choose(&root.join("data"), &loc).unwrap(); + if std::env::var("JARVIS_DATA_DIR").is_err() { + assert_eq!(webview_data_dir(&loc), (root.join("data").join("cache").join("webview"), false)); + } + // Scratch folders of earlier runs are removed; other folders stay. + let temp = root.join("tmp"); + for n in ["JarvisBot-webview-1", "JarvisBot-webview-2", "other"] { + std::fs::create_dir_all(temp.join(n).join("EBWebView")).unwrap(); + } + remove_scratch_webview(&temp, Some(&temp.join("JarvisBot-webview-2"))); + assert!(temp.join("JarvisBot-webview-1").exists() && !temp.join("JarvisBot-webview-2").exists()); + remove_scratch_webview(&temp, None); + assert!(!temp.join("JarvisBot-webview-1").exists() && temp.join("other").exists()); + } + #[test] fn a_relative_path_or_a_file_is_refused() { assert!(DataDir::create(Path::new("relative/data")).unwrap_err().0.contains("absolute")); diff --git a/app/src/discord_core.spec.md b/app/src/discord_core.spec.md index 599939a..db522e9 100644 --- a/app/src/discord_core.spec.md +++ b/app/src/discord_core.spec.md @@ -69,7 +69,8 @@ strings (numbers would lose precision). | `voice.joinNotice` | "자비스가 이 음성 채널에 들어왔습니다. 이 채널의 대화는 자비스가 받아 적습니다." | Posted in the voice channel's chat on every join. Must not be empty. | | `voice.wakeWords` | `["자비스"]` | Sent to the worker as STT `hotwords`, and the voice wake words of call detection. | | `voice.stt` | `{}` | Other worker STT settings (`partials`, `end_silence_ms`, `final_beam`, `language`, ...); the worker validates them. | -| `chatChannels` | `[]` | `{id, name, description, read (true), send (true), edit (true), react (true), delete (false), pin (false), answer ("wakeWord")}` per channel; `answer` is in `conversation.spec.md`. | +| `chatChannels` | `[]` | `{id, name, description, read (true), send (true), edit (true), react (true), delete (false), pin (false), answer ("wakeWord"), syncDiscord (true)}` per channel; `answer` is in `conversation.spec.md`, `syncDiscord` (the channel's Discord name and topic follow `name` and `description`) in `admin.spec.md`. | +| `voice.tts.speed` | `1.5` | How fast the voice speaks (MeloTTS `speed`, 0.5-2.0), passed to the worker as `--melo-speed` when it speaks (`--melo-python`) and its arguments set no speed. MeloTTS's Korean model has one voice, so there is no voice choice. | | `voiceWorker.python` | `python3` (`python.exe` on Windows) | Python of the worker venv. | | `voiceWorker.cwd` | `python-src` next to the app's executable when it is there (the Windows build), else the repo's `src/` | Folder holding the `voice_worker` package. | | `voiceWorker.args` | `[]` | Extra worker arguments, e.g. `["--melo-python", ""]`. | diff --git a/app/src/install.rs b/app/src/install.rs index 2464c7d..39d16ba 100644 --- a/app/src/install.rs +++ b/app/src/install.rs @@ -209,9 +209,15 @@ impl Ctx { let pump = |r: Box| { let (last, status, index, tab) = (last.clone(), self.status.clone(), self.index, self.tab); tokio::spawn(async move { - let mut lines = BufReader::new(r).lines(); - while let Ok(Some(l)) = lines.next_line().await { - let l = l.trim().to_owned(); + let mut reader = BufReader::new(r); + let mut buf = Vec::new(); + loop { + buf.clear(); + match reader.read_until(b'\n', &mut buf).await { + Ok(0) | Err(_) => break, + Ok(_) => {} + } + let l = decode_line(&buf).trim().to_owned(); if l.is_empty() { continue; } @@ -246,6 +252,31 @@ impl Ctx { } } +/// One output line as text: UTF-8 when it is, else (Windows without the UTF-8 option) the PC's OEM +/// code page, which console programs print in; never an error, so the reading goes on. +pub fn decode_line(bytes: &[u8]) -> String { + if let Ok(s) = std::str::from_utf8(bytes) { + return s.to_owned(); + } + #[cfg(windows)] + { + use windows_sys::Win32::Globalization::{MultiByteToWideChar, CP_OEMCP}; + let len = i32::try_from(bytes.len()).unwrap_or(i32::MAX); + // SAFETY: the input pointer and length describe `bytes`; the first call only measures, the + // second writes at most `n` UTF-16 units into a buffer of that size. + unsafe { + let n = MultiByteToWideChar(CP_OEMCP, 0, bytes.as_ptr(), len, std::ptr::null_mut(), 0); + if n > 0 { + let mut wide = vec![0u16; n as usize]; + if MultiByteToWideChar(CP_OEMCP, 0, bytes.as_ptr(), len, wide.as_mut_ptr(), n) == n { + return String::from_utf16_lossy(&wide); + } + } + } + } + String::from_utf8_lossy(bytes).into_owned() +} + /// End `child` and every process it started, and wait for it. async fn kill_tree(child: &mut tokio::process::Child) { if let Some(pid) = child.id() { @@ -385,6 +416,10 @@ impl Installer { pub fn cancel(&self) { self.cancel.store(true, Ordering::SeqCst); } + + pub fn running(&self) -> bool { + self.running.load(Ordering::SeqCst) + } } // ---- the real steps ------------------------------------------------------------------------------- @@ -693,6 +728,21 @@ mod tests { assert!(t.elapsed() < std::time::Duration::from_secs(5)); } + /// A Windows PC without the UTF-8 option prints in its code page (CP949 for Korean): such a line + /// must not end the reading, or every later line and the error are lost. + #[cfg(unix)] + #[tokio::test] + async fn output_that_is_not_utf8_does_not_stop_the_reading() { + let l = layout("inst9"); + let status = Arc::new(Mutex::new(vec![StepStatus { id: "x".into(), label: "".into(), size_hint: "".into(), + state: StepState::Running, bytes: None, note: None }])); + let ctx = Ctx { layout: l, status: status.clone(), index: 0, cancel: Arc::new(AtomicBool::new(false)), tab: "install" }; + // "설치 중" in CP949, then two plain lines and a failure. + let script = r"printf '\274\263\304\241 \301\337\\n'; echo 'step two'; echo 'last words'; exit 2"; + let err = ctx.run(Path::new("sh"), &["-c", script]).await.unwrap_err(); + assert!(err.contains("last words"), "{err}"); + } + #[cfg(unix)] #[tokio::test] async fn a_cancel_ends_the_command_and_everything_it_started() { diff --git a/app/src/lib.rs b/app/src/lib.rs index c199db3..354ad89 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -3,6 +3,7 @@ pub mod log; pub mod admin_api; pub mod calls; +pub mod channel_sync; pub mod chat; pub mod control; pub mod conversation; diff --git a/app/src/services.rs b/app/src/services.rs index ff7aab7..d569983 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -53,7 +53,7 @@ pub async fn start_services(data_dir: &Path, llm: Arc) -> Result, /// Voice worker STT settings (voice_worker.spec.md); the worker validates them. pub stt: Map, + /// How fast the voice speaks (MeloTTS `speed`, 0.5-2.0); the worker gets it at start. + pub tts_speed: f64, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -125,6 +130,7 @@ impl Default for Settings { join_notice: DEFAULT_JOIN_NOTICE.into(), wake_words: vec!["자비스".into()], stt: Map::new(), + tts_speed: 1.5, }, chat_channels: vec![], voice_worker: WorkerSettings { @@ -153,6 +159,18 @@ pub fn worker_cwd_for(exe: Option<&Path>) -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("src") } +impl Settings { + /// The voice worker's arguments: `voiceWorker.args`, plus the voice speed when it speaks + /// (`--melo-python`) and the arguments do not set one themselves. + pub fn worker_args(&self) -> Vec { + let mut a = self.voice_worker.args.clone(); + if a.iter().any(|x| x == "--melo-python") && !a.iter().any(|x| x == "--melo-speed") { + a.extend(["--melo-speed".to_string(), self.voice.tts_speed.to_string()]); + } + a + } +} + fn err(msg: impl Into) -> Result { Err(SettingsError(msg.into())) } @@ -352,6 +370,17 @@ pub fn parse_settings(raw: &Value) -> Result { if join_notice.encode_utf16().count() > 2000 { return err("voice.joinNotice must be at most 2000 characters"); } + let tts_speed = match voice.and_then(|m| m.get("tts")) { + None => d.voice.tts_speed, + Some(Value::Object(t)) => match t.get("speed") { + None => d.voice.tts_speed, + Some(v) => match v.as_f64() { + Some(x) if (0.5..=2.0).contains(&x) => x, + _ => return err("voice.tts.speed must be a number 0.5-2.0"), + }, + }, + Some(_) => return err("voice.tts must be an object"), + }; let stt = match voice.and_then(|m| m.get("stt")) { None => d.voice.stt.clone(), Some(Value::Object(m)) => m.clone(), @@ -386,6 +415,7 @@ pub fn parse_settings(raw: &Value) -> Result { "everything" => true, _ => return err(format!("{path}.answer must be wakeWord or everything")), }, + sync_discord: get_bool(Some(m), "syncDiscord", &path, true)?, }); } @@ -403,6 +433,7 @@ pub fn parse_settings(raw: &Value) -> Result { join_notice, wake_words, stt, + tts_speed, }, chat_channels, voice_worker: WorkerSettings { @@ -467,6 +498,21 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn the_tts_speed_reaches_the_worker_when_it_speaks() { + let melo = json!({"voiceWorker": {"args": ["--melo-python", "/m/python", "--brain"]}}); + let s = parse_settings(&melo).unwrap(); + let speed = |a: &[String]| a.iter().position(|x| x == "--melo-speed").map(|i| a[i + 1].clone()); + assert_eq!(speed(&s.worker_args()), Some(s.voice.tts_speed.to_string()), "the default speed"); + let mut fast = melo.clone(); + fast["voice"] = json!({"tts": {"speed": 1.8}}); + assert_eq!(speed(&parse_settings(&fast).unwrap().worker_args()).as_deref(), Some("1.8")); + assert!(speed(&Settings::default().worker_args()).is_none(), "no TTS, no speed"); + for bad in [json!(0.2), json!(3), json!("fast")] { + assert!(parse_settings(&json!({"voice": {"tts": {"speed": bad}}})).unwrap_err().0.contains("voice.tts.speed")); + } + } + #[test] fn the_python_sources_shipped_next_to_the_app_win_over_the_repository() { let dir = crate::datadir::temp_dir("pysrc"); @@ -512,7 +558,7 @@ mod tests { assert_eq!(s.voice.stt.get("end_silence_ms"), Some(&json!(250))); assert_eq!(s.chat_channels, vec![ChatChannelSettings { id: IDN, name: "일정".into(), description: "일정 올리는 곳".into(), read: true, send: false, edit: true, react: true, delete: false, - pin: false, answer_all: false }]); + pin: false, answer_all: false, sync_discord: true }]); assert_eq!(s.voice_worker.args, vec!["--melo-python", "/m/python"]); assert_eq!(s.voice_worker.cwd, PathBuf::from("/repo/src")); } diff --git a/app/src/settings_edit.rs b/app/src/settings_edit.rs index c068911..fca277b 100644 --- a/app/src/settings_edit.rs +++ b/app/src/settings_edit.rs @@ -107,6 +107,8 @@ pub fn fields() -> Vec { f("voice.stt.partial_interval_ms", Model, Int { min: 100, max: 5000 }, json!(400), "중간 전사 간격(ms)"), f("voice.stt.final_beam", Model, Int { min: 1, max: 5 }, json!(2), "최종 전사 정확도(빔)"), f("voice.stt.language", Model, LanguageCode, json!("ko"), "받아 적을 언어(비우면 자동)"), + // MeloTTS's Korean model has one voice (speaker "KR"), so only the speed is a choice. + f("voice.tts.speed", Model, Number { min: 0.5, max: 2.0 }, json!(1.5), "말하기 속도(MeloTTS, 기본 1.5)"), // The LLM (admin.spec.md, "LLM"); `llm.url` (a server the app does not start) is file-only. f("llm.context", Model, Int { min: 4096, max: 262144 }, json!(32768), "대화 모델이 한 번에 기억하는 양(토큰)"), f("llm.port", Model, Int { min: 1024, max: 65535 }, json!(8080), "대화 모델 포트"), diff --git a/app/src/strata.rs b/app/src/strata.rs index 430f43f..d9c1561 100644 --- a/app/src/strata.rs +++ b/app/src/strata.rs @@ -358,7 +358,7 @@ mod tests { let mut s = Settings::default(); assert_eq!(parallel(&s), 1); s.chat_channels.push(ChatChannelSettings { id: 1, name: String::new(), description: String::new(), read: true, - send: true, edit: true, react: true, delete: false, pin: false, answer_all: true }); + send: true, edit: true, react: true, delete: false, pin: false, answer_all: true, sync_discord: true }); assert_eq!(parallel(&s), 2); } diff --git a/app/tests/worker_client.rs b/app/tests/worker_client.rs index cb759f2..01ad2b8 100644 --- a/app/tests/worker_client.rs +++ b/app/tests/worker_client.rs @@ -300,7 +300,7 @@ async fn chat_channels_go_out_and_chat_actions_come_back_with_their_results() { c.start(); c.wait_ready(Duration::from_secs(2)).await.expect("ready"); c.chat_channels(Some(900), &[ChatChannelSettings { id: 5, name: "일정".into(), description: "약속".into(), - read: true, send: true, edit: true, react: true, delete: false, pin: false, answer_all: false }]); + read: true, send: true, edit: true, react: true, delete: false, pin: false, answer_all: false, sync_discord: true }]); w.send(Message::text(json!({"type": "chat_action", "id": "a1", "action": "react", "channel": "5", "message_id": "77", "emoji": "👍"}).to_string())); let ev = next_matching(&mut rx, |e| matches!(e, WorkerEvent::ChatAction(_))).await; diff --git a/app/ui/app.js b/app/ui/app.js index 22df4ae..50b555e 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -129,14 +129,27 @@ function editor(f, value) { } function chatChannelsEditor(f, value) { - const flags = [["read", "읽기", true], ["send", "보내기", true], ["edit", "수정", true], ["react", "반응", true], - ["delete", "삭제", false], ["pin", "고정", false]]; + const flags = [["syncDiscord", "디스코드 반영", true], ["read", "읽기", true], ["send", "보내기", true], ["edit", "수정", true], + ["react", "반응", true], ["delete", "삭제", false], ["pin", "고정", false]]; const body = h("tbody"); + const SYNC = { applied: "반영됨", pending: "잠시 뒤 반영", failed: "반영 못 함" }; + const statusCells = new Map(); const addRow = (c = {}) => { - const tr = h("tr", {}, - h("td", {}, h("input", { type: "text", value: c.id ?? "", placeholder: "채널 ID", "data-k": "id" })), - h("td", {}, h("input", { type: "text", value: c.name ?? "", placeholder: "이름", "data-k": "name" })), - h("td", {}, h("input", { type: "text", value: c.description ?? "", placeholder: "무엇에 쓰는 채널인지", "data-k": "description" })), + const id = h("input", { type: "text", value: c.id ?? "", placeholder: "채널 ID", "data-k": "id" }); + const name = h("input", { type: "text", value: c.name ?? "", placeholder: "이름", "data-k": "name" }); + const desc = h("input", { type: "text", value: c.description ?? "", placeholder: "무엇에 쓰는 채널인지", "data-k": "description" }); + // A newly registered channel starts with its Discord name and topic. + id.addEventListener("change", async () => { + if (!id.value.trim() || (name.value && desc.value)) return; + try { + const info = await api("discord_channel_info", { id: id.value.trim() }); + if (!name.value) name.value = info.name; + if (!desc.value) desc.value = info.topic; + } catch (e) { fail(e); } + }); + const status = h("td", { class: "small muted" }); + if (c.id) statusCells.set(c.id, status); + const tr = h("tr", {}, h("td", {}, id), h("td", {}, name), h("td", {}, desc), flags.map(([k, , d]) => { const box = h("input", { type: "checkbox", "data-k": k }); box.checked = c[k] ?? d; @@ -145,11 +158,18 @@ function chatChannelsEditor(f, value) { h("td", {}, h("select", { "data-k": "answer" }, h("option", { value: "wakeWord", selected: (c.answer ?? "wakeWord") === "wakeWord" }, "호출어"), h("option", { value: "everything", selected: c.answer === "everything" }, "모든 글"))), + status, h("td", {}, h("button", { class: "btn", onclick: () => tr.remove() }, "삭제"))); body.append(tr); }; (value || []).forEach(addRow); - const table = h("table", {}, h("thead", {}, h("tr", {}, ["ID", "이름", "설명", ...flags.map((x) => x[1]), "대답", ""] + api("channel_sync_status").then((st) => { + for (const [cid, s] of Object.entries(st)) { + const cell = statusCells.get(cid); + if (cell) { cell.textContent = SYNC[s.state] ?? s.state; cell.title = s.reason ?? ""; } + } + }).catch(() => {}); + const table = h("table", {}, h("thead", {}, h("tr", {}, ["ID", "이름", "설명", ...flags.map((x) => x[1]), "대답", "디스코드", ""] .map((t) => h("th", {}, t)))), body); const read = () => [...body.rows].map((tr) => { const c = {}; @@ -173,6 +193,15 @@ async function settingsScreen(screen, title, extra) { if (!Object.keys(changes).length) return toast("바뀐 것이 없습니다"); const r = await api("settings_apply", { changes }); Object.assign(view, changes); + const sync = r.sync || []; + if (sync.length) { + const n = (k) => sync.filter((x) => x.state === k).length; + const failed = sync.filter((x) => x.state === "failed").map((x) => x.reason); + toast(`저장했습니다. 디스코드 반영: ${n("applied")}개 반영${n("pending") ? `, ${n("pending")}개 잠시 뒤 반영` : ""}` + + (failed.length ? `, ${failed.length}개 못 함(${failed[0]})` : ""), failed.length > 0); + show(current); // Discord's form of the names, and the status column + return; + } toast(r.restartNeeded ? "저장했습니다. 다시 시작하면 적용됩니다." : "저장했습니다."); } catch (e) { fail(e); } }; @@ -558,4 +587,10 @@ async function start() { for (const b of document.querySelectorAll(".nav")) b.onclick = () => show(b.dataset.screen); show("dashboard"); } +// The window tells what closing does: stopping what runs first, or that it could not. +if (window.__TAURI__?.event) { + window.__TAURI__.event.listen("closing", () => toast("실행 중인 것을 정리하고 종료합니다…")); + window.__TAURI__.event.listen("close-failed", (e) => + toast(`정리를 끝내지 못해 창을 닫지 않았습니다: ${e.payload}. 한 번 더 닫으면 그대로 종료합니다.`, true)); +} start().catch(fail); diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index 23e82de..877a613 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -9,7 +9,7 @@ | M2 | 디스코드 음성 코어 이전 | v1 봇 기능을 새 앱 안으로 이전. 입장/퇴장, 화자별 수신, 재생, 정지 명령 동작. 채팅 채널 연결(읽기·보내기). 구현과 테스트 완료(2026-11-11): `app/`(Rust, serenity + songbird), 스펙은 [discord_core.spec.md](../../app/src/discord_core.spec.md). 처음 Electron + TypeScript로 만든 것을 사용자 요청으로 Rust로 다시 씀. 앱이 음성 워커를 띄우고(실행마다 새 토큰, 죽으면 다시 시작) 연결이 끊기면 다시 붙습니다. 음성 채널에 들어갈 때마다 전사 고지를 채널 채팅에 올립니다. songbird 0.6.1의 DAVE 수신 해독이 조각 3분의 1가량을 깨뜨려서(20ms마다 음이 바뀌는 시험 신호로 확인, 보내기는 정상) 받은 패킷의 순서 맞추기와 Opus 해독은 앱이 직접 합니다. 실제 디스코드에서 봇 두 개로 확인(이 서버의 RTX 5050): 다른 봇이 채널에 튼 녹음 문장 5개를 모두 받아 적었고(문자 오류율 3개 0%, "기록해"를 "비록해"로 적은 1개 5%, "일곱 시"를 "7시"로 적은 1개 12.5%), 말이 끝난 뒤 최종 전사까지 0.71~0.90초였습니다. 자비스가 말한 문장을 상대 봇이 받아 다시 전사하니 오류율 3.4%였고, 정지 명령 뒤 0.08초 만에 소리가 끊겼습니다. 채팅 채널은 새 글 받기, 최근 글 읽기, 보내기(2,000자 넘으면 나눔, 아무도 호출하지 않음)가 됩니다. 사람이 직접 말한 소리와 게임PC(Windows) 빌드는 아직 확인하지 않았고, 음성으로 "자비스, 멈춰"는 호출 판정이 필요해 M4에서 합니다 | | M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과. 1단계 완료(2026-11-11): LLM 주소가 `/v1`로 끝나면 OpenAI 호환 방식(`/chat/completions`, `/embeddings`)으로 부름. 형식 변환은 `src/jarvis/llm.py` 한곳에서 하고 두뇌의 나머지 코드는 그대로 씀. 대화, 도구 호출, 스트리밍, 의도 판정, 받아쓰기 정리, 미리 불러오기가 모두 이 방식으로 감. 이 서버 Ollama의 `/v1` 주소와 qwen2.5:7b로 실제 두뇌 한 턴을 돌려 "서울 날씨 어때?"에 날씨 도구를 부르고 그 결과로 답하는 것을 확인함. Strata에는 임베딩 모델이 없어 지난 기록 검색은 낱말 검색으로 함. 2단계 완료(2026-11-11): 대화 기록 저장소 `src/jarvis/memory/history.py`(스펙 [history.spec.md](../../src/jarvis/memory/history.spec.md)). 음성 전사, 자비스의 답, 채팅 채널 글, 음성 채널 출입 시간을 저장하고, 묻는 사람이 볼 수 있는 기록(본인 기록, 채팅 채널, 함께 있던 동안의 다른 사람 말)만 찾음. 전체 기간에서 관련도 순으로 찾고, 기록 10만 개에서 검색 48~143ms. 두뇌는 찾은 기록을 받아 지시문에 참고 자료로 넣음(평가 `evals/test_history_context_recall.py`, qwen2.5:7b에서 3번 모두 통과). 3단계 완료(2026-11-11): 앱이 음성 워커에 음성 채널 입장·퇴장, 사람 출입, 등록한 채팅 채널의 글·수정·삭제를 알리고, 워커가 최종 전사를 저장함. 워커는 `--history`로 저장소를, `--brain`으로 두뇌를 켜고, `reply` 요청에 묻는 사람의 범위로 찾은 기록을 넣어 답하고(`reply_text`) 음성이면 바로 말함. 실제 디스코드 시험(봇 두 개)에서 전사 8개가 이름과 함께 저장되고, 채팅 수정은 반영, 삭제한 글은 빠지고, 자비스가 나간 뒤 출입 기록이 모두 닫힘. 워커와 실제 두뇌(이 서버 Ollama `/v1`, qwen2.5:7b, 맥락 8천 토큰)로 다른 사람이 채팅에 남긴 약속을 4번 물어 4번 모두 맞게 답함. Ollama의 `/v1`은 맥락을 2,048토큰으로 고정해 지시문을 자르므로, Ollama로 시험할 때는 `num_ctx`를 넣은 모델 이름을 씀(Strata는 시작할 때 맥락을 정해 해당 없음). v2 두뇌는 한 사람용인 v1 장기 기억(프로필·일기·그래프)을 넣지 않고, 답하는 동안 원문이 로그에 찍히지 않게 함. 언제 `reply`를 보낼지(호출 판정)와 음성 답 재생 연결은 M4. 4단계 완료(2026-11-11): 채팅 채널 도구 `chatChannels`(목록·읽기·검색·보내기·수정·반응·삭제·고정, 스펙 [chat_channels.spec.md](../../src/jarvis/tools/builtin/chat_channels.spec.md)). 읽기·검색은 대화 기록 저장소에서, 나머지는 앱이 채널별 허용 설정을 확인하고 디스코드에서 실행. 삭제는 다음 메시지에서 사용자가 동의해야 실행하고, 채널 글은 명령이 아닌 자료로 표시. 실제 디스코드에서 수정(자기 글만)·반응·삭제·고정을 확인(음성 채널의 채팅은 디스코드가 고정을 막아 오류로 돌아옴). 평가(qwen2.5:7b) 3번에 12번 중 10번 통과, 글 속 명령을 따르지 않기와 같은 턴에 지우지 않기는 12번 모두 지킴. 식단 기록은 사람별로 나눔(v1 데이터는 그대로). 기존 테스트·평가 확인(2026-11-11): 단위 테스트는 2,215개 통과, 10개 실패이고, 실패 10개는 이 서버에 PortAudio가 없어 마이크 코드(음성 듣기·받아쓰기)가 꺼진 탓임. 갱신되지 않았던 테스트 4개(한국어 한 문장 날씨 3, 잡담 빠른 경로를 지나는 캐시 1)와 설치된 PyQt6를 가짜로 바꿔 다른 화면 테스트를 깨뜨리던 테스트 1곳을 고침. 평가(evals, qwen2.5:7b)는 145개 통과, 56개 실패, 60개 건너뜀. 실패 중 54개는 M3 이전 커밋(beaacb3)에서도 실패하거나, 3번씩 다시 돌린 통과 횟수가 양쪽이 같아 M3 때문에 생긴 실패는 없음. 나머지 2개는 새 채팅 도구 평가의 알려진 실패(12번 중 2번). 원래 실패하는 평가는 이 서버에 없는 모델(gpt-oss:20b, nomic-embed-text)을 쓰거나 qwen2.5:7b가 웹 검색·날씨 도구를 부르지 않는 경우가 대부분임. 실제로 쓸 모델로 평가 확인(2026-11-11): 게임PC의 Strata(Qwen3.6-35B-A3B UD-Q4_K_XL, 맥락 32K, 평소 배치)에 SSH 터널로 붙어 이 서버에서 평가 전체를 돌림. 193개 통과, 12개 실패, 60개 건너뜀(의도 판정·도구 선택 평가는 gemma4 단계에서만 돌고, gemma4는 이 서버 Ollama에 없음), 8분 13초. 실패 12개를 3번씩 다시 돌리니 5개는 3번 모두 실패(알려진 위치를 날씨 도구 인자로 넣지 않음 2, 파리·런던 비교에서 날씨 도구를 한 번만 부름 1, 지식 그래프 갈래 분류 1, 맥락에 있는 위치를 기억 검색 질문에 다시 넣음 1)했고, 날씨 한 번 부르기 평가는 엔진의 정해진 날씨 경로(`_maybe_deterministic_weather`)가 평가가 바꿔 둔 도구 실행기를 거치지 않고 실제 날씨를 받아 한국어로 바로 답해 3번 모두 실패함(모델과 상관없음). 나머지 6개는 3번 중 1~3번 통과함. qwen2.5:7b에서 없던 실패는 기억 검색 질문 1개(3번 모두)와 날씨 다시 시도 2개(다시 돌리면 6번 중 4번 통과)임 실패 고침(2026-11-11): 엔진의 정해진 한국어 날씨 경로를 뺌(평가의 도구 실행기를 거치지 않았고, 사용자가 말한 위치를 쓰지 못함, 큰 모델은 도구 결과를 한국어 한 문장으로 그대로 답함). 날씨 도구와 대화 지시문은 사용자가 대화나 기억에서 말한 위치를 넣고, 자동으로 잡힌 위치는 옮겨 적지 않게 함. "구, 시, 나라" 이름이 안 찾아지면 넓은 지역으로 다시 찾음. 계획 단계에 현재 시간·위치 줄을 주어, 위치를 모를 때만 기억에서 사용자 위치를 먼저 찾게 함. 같은 도구 반복 제한이 이전 답변의 호출까지 세어 사용자가 다시 해 달라고 해도 막던 버그를 고침. 기억 검색어 지시문에서 평가와 같은 문장의 예시를 바꾸고 현재 맥락 블록을 예시 뒤로 옮김(위치를 모를 때는 여전히 묻는지 보는 평가 추가, qwen2.5:7b는 바꾸기 전에도 묻지 않음). 평가 전체 202개 통과, 4개 실패, 9분 3초. 이 전체 실행의 날씨 실패 1개는 장소를 말하지 않은 "what's the weather this week"에 자동으로 잡힌 위치(`Hackney, England, UK`)를 인자로 옮겨 적은 것으로, 그 뒤 날씨 도구와 지시문을 사용자가 말한 위치만 넣도록 좁혀 고침. 고친 뒤 날씨 평가 12개를 따로 3번 돌려 36번 중 34번 통과(이 평가는 3번 모두 통과, 실패 2번은 날씨 한 번 부르기 평가가 파리 날씨 답에 도시 이름을 다시 말하지 않은 것). 전체 실행의 나머지 실패는 지식 그래프 갈래 분류 1개(모델이 "사용자가 물었다"를 사용자 사실로 하나 더 남김, 지시문을 두 번 고쳐도 같아 되돌림, v2는 v1 장기 기억을 쓰지 않음)와 다시 돌리면 통과하는 2개(유명인 두 턴 대화, 최근 일기 반영) | | M4 | 왕복 완성과 지연 튜닝 | 호출어·호출 방식·지정한 사람 설정, 동시 대화 응답 정책 4가지(기본 "처음 대화만")와 정책별 끼어들기 규칙. 말 끝부터 첫 소리까지 실측 1.5초 이내, 10명 채널 부하 테스트. 1단계 완료(2026-11-11): 앱의 호출 판정 `app/src/calls.rs`와 응답 정책 `app/src/policy.rs`(스펙 [conversation.spec.md](../../app/src/conversation.spec.md)), 설정 `call`·`response`. 비슷한 발음은 유니코드 NFKD로 한글을 자모로 나눠 편집 거리로 판단(기본 0.2: "자비즈"는 호출, "서비스"는 아님). 정책은 말이 끝난 시각 순서, 먼저 끝난 말의 전사 대기(최대 0.8초), 끼어들기, 놓친 요청 사유를 가짜 시각으로 시험함. 2단계 완료(2026-11-11): 대화 루프 `app/src/conversation.rs`가 최종 전사를 호출 판정과 응답 정책에 넣고, 정책의 결정대로 두뇌에 답을 요청해(`reply`, 답은 워커가 같은 id로 읽음) 앱의 재생 대기열에서 재생, 끼어들 때는 그 답만 멈춤, "자비스 멈춰"는 모든 말을 멈춤, 놓친 요청은 글 없이 최근 100개를 남김. 두뇌의 두 판정 `src/voice_worker/judges.py`(봇에게 하는 말인지, 중요도 순위)는 답과 따로 돌아 기다리지 않음. 평가 `evals/test_voice_judges.py` 12개를 qwen2.5:7b에서 모두 통과. 답을 만드는 중에 멈춘 요청은 말하지 않음. 실제 Python 워커(가짜 두뇌)와 앱의 통합 시험 통과. 3단계 완료(2026-11-11): 채팅 채널 호출. 채널마다 `answer`(호출어로 부를 때만 / 모든 메시지에 대답), 채팅 호출어(`call.chatWakeWords`, 없으면 음성과 같음)와 지정한 사람 설정은 음성과 같이 씀. 답은 같은 채널에 원래 메시지의 답글로 올리고 아무도 부르지 않음. 다른 봇의 글과 보내기가 꺼진 채널에는 답하지 않음. 음성 대화 순서와는 따로 감(워커가 음성 답과 채팅 답을 따로 써서 다른 사람의 채팅 답 때문에 음성 답이 기다리지 않음. 한 사람의 답은 물은 순서대로 하나씩 씀. 두 답의 LLM 호출이 동시에 돌려면 Strata를 `--parallel 2`로 띄움, 앱이 Strata를 띄우는 M5 전까지). 5분 넘게 늦은 채팅 답은 올리지 않음. 실제 디스코드 시험과 지연 측정은 4단계. 4단계 첫 측정(2026-11-12): 앱의 실제 서비스(`start_services`: 대화 루프, 응답 정책, 워커, 두뇌)를 게임PC Strata(`--parallel 2`)에 붙이고, 봇 두 개로 질문 5개를 2번씩 말해 잼(`app/tests/live_round_trip.rs`). 10개 모두 소리로 답했고, 말 끝부터 첫 소리까지 중앙값 3.5초(최소 2.8초, 날씨 도구 8.6초). 9명이 동시에 말하는 부하(워커의 두 번째 연결로 녹음 문장 9개를 실시간으로 넣음, 그동안 최종 전사 259개)에서는 중앙값 4.4초, 최종 전사가 0.6~0.9초에서 0.8~1.8초로 늦어졌고 1번은 "기분"을 "딥"으로 잘못 들어 날씨 도구를 불러 18.8초가 걸림. 짧은 답의 시간은 최종 전사 0.65~0.85초, 두뇌 2.0~2.9초(도구 고르기 0.42초, 계획 0.5초, 답 호출의 지시문 약 4,300토큰 읽기 1.1초와 생성), 재생 시작과 전달 약 0.4초. Strata의 Qwen3.6 엔진은 지시문 앞부분 재사용을 하지 않아(`--prompt-cache-every`는 "이 엔진의 옵션이 아님"으로 무시됨, 같은 대화를 그대로 이어 갈 때만 재사용) 매 호출을 처음부터 읽음. 생성은 0.2~0.5초라 문장 단위로 흘려도 짧은 답은 거의 빨라지지 않음. 1.5초 기준은 아직 못 맞춤. 같은 시험에서 찾아 고친 것: v1 TTS 설정(영어 전용 Piper) 때문에 한국어 질문에 영어로 답하던 것(v2 두뇌는 묻는 사람의 언어로 답함), 호출어 뒤에 쉬면 "자비스"만 따로 끊겨 그 이름에만 답하고 이어진 질문은 무시하던 것(이제 같은 사람이 이어서 하는 말과 합침, `call.followUpMs`). 4단계 지연 줄이기(사용자 결정, 2026-11-12): 부름을 받으면 "띠링" 효과음(앱이 만든 0.3초 소리, `call.earcon`, 이름만 부르고 쉬면 그때 바로), 답은 한국어 기본(영어 등은 따로 부탁할 때만), v2 두뇌의 짧은 지시문(성격 설명 7.4천 자를 1.3천 자로, 답은 최대한 짧게, 화면공유 도구는 v2에 없어 뺌: 인사의 답 지시문 4,500토큰이 1,400토큰), 답 전에 판단 한 번(도구 고르기로 도구가 필요한지 정하고, 필요할 때만 계획. 계획 하나로 합치거나 계획을 아예 빼 보니 날씨나 여러 단계 질문이 틀려 이 방식으로 정함), 말하는 중의 중간 전사가 호출로 읽히면 도구 고르기를 미리 해 둠(워커 `prepare`). 평가 전체(v2 설정, 마지막 지시문 수정 전) 219개 통과, 6개 실패: 파리·런던 비교와 지식 그래프 갈래 분류는 전부터 실패, 3개는 v2가 쓰지 않는 v1 개인 기억(그래프·일기) 평가, 1개는 새 답 길이 평가("하늘은 왜 파래"의 답이 72자로 기준 70자를 넘음). 그 뒤 "왜·어떻게" 질문은 핵심 이유만 말하도록 지시문을 고치고 답 길이 평가를 따로 3번 돌려 3번 모두 통과(v2 답 합계 185~205자, 예전 315~356자), 한국어 기본·지난 대화·채팅 채널·건너뛴 도구 평가 22개도 모두 통과(전체 평가는 이 수정 뒤 다시 돌리지 않음). 실제 디스코드 재측정(2026-11-12, `app/tests/live_round_trip.rs`, 질문 5개 2번): 첫 소리(효과음)는 이름 뒤에 쉬면 질문이 끝나기 전에, 쉬지 않으면 0.94~1.10초. 답의 첫 소리는 중앙값 1.9초(1.56~2.30초, 날씨 도구 5.75~5.85초), 9명이 동시에 말할 때 2.8초(2.13~3.41초, "기분"을 "딥"으로 잘못 들은 1번은 웹 검색으로 13.3초). 혼자일 때는 미리 해 둔 판단이 5번 모두 쓰여 말 끝 뒤 두뇌 시간이 0.6~0.74초였고, 9명 부하에서는 중간 전사가 밀려 미리 판단이 한 번도 되지 않음(두뇌 1.4초). 같은 시험에서 찾아 고친 것: 모델이 "10시 37분"을 오후로 읽음(시간 줄에 12시간 표기 추가), 없는 타이머 도구 호출 글자(``)를 답으로 내 TTS가 읽을 뻔함(도구 호출로 읽음) | -| M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드). 단계: 1 관리 기능(화면 없음), 2 서비스 제어와 대시보드 자료, 3 Tauri 화면, 4 런타임·모델 자동 설치, 5 Windows 빌드와 확인. 1단계 완료(2026-11-12): `app/src/datadir.rs`(데이터 폴더와 위치 기억 파일, 남은 용량), `settings_edit.rs`(화면 5개의 항목 36개, 기본값과 다른 값만 저장, 모르는 키 보존, 앱 검사를 통과해야만 저장), `secrets.rs`(봇 토큰, Windows는 사용자 계정 DPAPI 암호화), `logs.rs`(서비스별 탭, 날짜별 파일 14일 보관, 최근 오류 복사, 10MB 이하 zip, 비밀값·토큰 모양 가림), 앱 설정에 대화 기억(`memory`) 칸을 넣어 워커에 넘김. 스펙 [admin.spec.md](../../app/src/admin.spec.md). Windows용 코드는 Windows 대상으로 컴파일만 확인(실행 확인은 5단계). 2단계 완료(2026-11-12): `control.rs`(서비스 시작·정지·재시작 규칙, 실패는 비밀값을 가린 오류로 남기고 아무것도 켜 두지 않음, 앱 실행 파일도 같은 제어기를 씀), `dashboard.rs`(디스코드 이벤트만으로 만드는 대시보드 자료: 연결 상태, 음성 채널과 참가자, 실시간 자막 30줄(화면에만, 기록하지 않음, 나가거나 정지하면 지움), 답 20개의 단계별 지연(말 끝→최종 전사, 두뇌, 목소리, 전체)과 중앙값, 놓친 요청 20개(글 없이)), `system.rs`(RAM, `nvidia-smi`로 GPU 사용률·VRAM). 성능 단계(평소/게임 중/일시정지)는 게임 감지와 함께 M7. 3단계 완료(2026-11-12): 화면 `app/ui/`(빌드 도구 없는 HTML/CSS/JS, 어두운 테마, 한국어)와 화면이 부르는 명령 `admin_api.rs`(설정, 대시보드, 시작·정지, 로그 조회·복사·zip, PC 점검, 디스코드 토큰 확인·초대 링크·서버/채널 목록 `discord_setup.rs`). 첫 실행 마법사(데이터 폴더, PC 점검, 모델 안내, 봇 연결, 서버·음성 채널, 호출어, 시작), 대시보드, 설정 5개, 로그. 개발용 서버 `jarvis-admin-dev`로 이 서버의 브라우저에서 실제 테스트 봇과 음성 워커를 켜고 확인: 마법사 각 단계, 시작 뒤 "실행 중 · 테스트봇#9029 · 워커 연결됨", 다시 시작·정지, 설정 저장(바뀐 값만, 모르는 키 보존), 채팅 채널 추가, 로그 실시간 보기와 zip 내보내기. Tauri 창(셸)은 이 서버에서 빌드할 수 없어(webkit2gtk 없음) Windows 빌드 단계에서 붙임. 디스코드 채널 이름·주제 반영은 아직. 4단계 첫 부분 완료(2026-11-12): 설치 `install.rs`·`download.rs`(이어받기, SHA-256 확인), M0 키트와 같은 방식으로 uv 0.11.20 → 워커·두뇌 Python 3.12 환경(v2 전용 패키지 목록 `requirements-brain.txt`) → MeloTTS Python 3.11 환경 → Whisper large-v3-turbo → MeloTTS 한국어 음성 → Strata를 모두 데이터 폴더 안에 설치하고, 끝나면 다운로드 캐시를 비우고 워커 설정을 설치된 Python으로 바꿈. 마법사 "모델" 단계에서 진행·취소·다시 시도. 이 서버(Linux)에서 빈 폴더부터 전부 설치해 보고 그 런타임으로 서비스를 켜 워커 연결, 받아 적기·음성 준비까지 확인했고, 설치 중 데이터 폴더 밖에는 아무것도 쓰지 않음. 대화 모델(약 23GB)은 앱이 Strata를 직접 띄우는 다음 부분에서 받음. 4단계 뒷부분 완료(2026-11-12): 서비스를 켜면 앱이 먼저 데이터 폴더의 Strata를 띄움(`app/src/strata.rs`, M0와 같은 모델과 평소 배치, 처음 켤 때 대화 모델 약 23GB를 받음, 대시보드에 진행률과 Strata의 마지막 줄, 켜는 중에도 정지 가능, 서비스를 끄면 Strata도 끔). 동시 요청은 1개(모든 메시지에 답하는 채팅 채널이 있으면 2개), 그림 읽기는 v2에서 아직 쓰지 않아 끔. 시작할 때마다 두뇌 설정 `config/brain.json`(Strata 주소, Strata가 알려 준 모델 이름, 데이터 폴더 안의 기억 DB)을 써서 워커에 넘김. 이미 떠 있는 서버를 쓰려면 설정 파일의 `llm.url`. 확인: 가짜 Strata로 진행률·준비·정지·다운로드 중 취소·실패를 단위 시험, 게임PC의 Strata 0.1.59가 앱의 실행 옵션을 그대로 받아들임(`--plan`), 앱 서비스를 `llm.url`로 게임PC Strata에 붙여 실제 디스코드 왕복 10개 모두 소리로 답함. 앱이 Strata를 직접 띄워 모델을 받는 실제 확인은 이 서버에서 할 수 없어(메모리) Windows 빌드 단계에서 게임PC로 함. 5단계 완료(2026-11-12): Tauri 2 창 `app/shell`(`jarvis.exe`, 화면의 명령을 같은 `AdminApi`로 넘김, 창을 닫으면 서비스와 Strata를 끄고 끝날 때까지 기다림, 창의 브라우저 자료는 위치 기억 파일 옆)과 Windows 빌드 `app/shell/package.sh`(이 서버에서 `x86_64-pc-windows-gnu`로 빌드, `Jarvis/` 폴더에 실행 파일·WebView2Loader.dll·Python 소스 `python-src`, zip 11MB). 시험용 Windows VM에서: 창과 마법사, PC 점검, uv·워커 환경 설치, 설치 취소 뒤 남은 프로세스 없음, 봇 토큰 DPAPI 암호화 저장, 시작 실패 이유 표시, 로그 화면·오류 복사·zip, 창 닫기로 종료, %APPDATA%·%LOCALAPPDATA%에 아무것도 안 남김, 앱 핵심 단위 테스트(Windows 빌드) 통과. 게임PC(RTX 5070 Ti, C:\JarvisM0 안에서만)에서 같은 관리 명령으로: 전체 설치 7단계 6분 40초, 앱이 직접 띄운 Strata가 엔진과 대화 모델 22.9GB를 약 6분에 받고 준비, 워커(GPU 받아 적기·음성) 연결, 디스코드 음성 채널 입장, 시험 봇이 말한 질문 5개에 모두 소리로 답함(앱이 잰 전체 중앙값 3.36초, 처음 질문 6.4초, 날씨 11.6초), 정지 8초에 GPU 메모리 반환. 같은 시험에서 찾아 고친 것: Windows는 닫힌 로컬 포트의 연결 거부가 약 2초 늦어 정지 확인이 실패로 나오던 것, Strata가 모델 크기(`X of Y GB`)로만 진행을 알려 진행률이 앞 단계의 80%에 멈춰 있던 것, Strata와 NVIDIA 셰이더 캐시가 %APPDATA%에 쓰던 것(데이터 폴더로). 남은 것: 설치 파일(NSIS), Strata가 VRAM을 거의 다 써서(15.8/16.3GB) 받아 적기와 GPU를 나누는 문제(M0의 STT 자리 남기기 배치, M7 성능 단계와 함께), 디스코드 채널 이름·주제 반영 | +| M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드). 단계: 1 관리 기능(화면 없음), 2 서비스 제어와 대시보드 자료, 3 Tauri 화면, 4 런타임·모델 자동 설치, 5 Windows 빌드와 확인. 1단계 완료(2026-11-12): `app/src/datadir.rs`(데이터 폴더와 위치 기억 파일, 남은 용량), `settings_edit.rs`(화면 5개의 항목 36개, 기본값과 다른 값만 저장, 모르는 키 보존, 앱 검사를 통과해야만 저장), `secrets.rs`(봇 토큰, Windows는 사용자 계정 DPAPI 암호화), `logs.rs`(서비스별 탭, 날짜별 파일 14일 보관, 최근 오류 복사, 10MB 이하 zip, 비밀값·토큰 모양 가림), 앱 설정에 대화 기억(`memory`) 칸을 넣어 워커에 넘김. 스펙 [admin.spec.md](../../app/src/admin.spec.md). Windows용 코드는 Windows 대상으로 컴파일만 확인(실행 확인은 5단계). 2단계 완료(2026-11-12): `control.rs`(서비스 시작·정지·재시작 규칙, 실패는 비밀값을 가린 오류로 남기고 아무것도 켜 두지 않음, 앱 실행 파일도 같은 제어기를 씀), `dashboard.rs`(디스코드 이벤트만으로 만드는 대시보드 자료: 연결 상태, 음성 채널과 참가자, 실시간 자막 30줄(화면에만, 기록하지 않음, 나가거나 정지하면 지움), 답 20개의 단계별 지연(말 끝→최종 전사, 두뇌, 목소리, 전체)과 중앙값, 놓친 요청 20개(글 없이)), `system.rs`(RAM, `nvidia-smi`로 GPU 사용률·VRAM). 성능 단계(평소/게임 중/일시정지)는 게임 감지와 함께 M7. 3단계 완료(2026-11-12): 화면 `app/ui/`(빌드 도구 없는 HTML/CSS/JS, 어두운 테마, 한국어)와 화면이 부르는 명령 `admin_api.rs`(설정, 대시보드, 시작·정지, 로그 조회·복사·zip, PC 점검, 디스코드 토큰 확인·초대 링크·서버/채널 목록 `discord_setup.rs`). 첫 실행 마법사(데이터 폴더, PC 점검, 모델 안내, 봇 연결, 서버·음성 채널, 호출어, 시작), 대시보드, 설정 5개, 로그. 개발용 서버 `jarvis-admin-dev`로 이 서버의 브라우저에서 실제 테스트 봇과 음성 워커를 켜고 확인: 마법사 각 단계, 시작 뒤 "실행 중 · 테스트봇#9029 · 워커 연결됨", 다시 시작·정지, 설정 저장(바뀐 값만, 모르는 키 보존), 채팅 채널 추가, 로그 실시간 보기와 zip 내보내기. Tauri 창(셸)은 이 서버에서 빌드할 수 없어(webkit2gtk 없음) Windows 빌드 단계에서 붙임. 디스코드 채널 이름·주제 반영은 아직. 4단계 첫 부분 완료(2026-11-12): 설치 `install.rs`·`download.rs`(이어받기, SHA-256 확인), M0 키트와 같은 방식으로 uv 0.11.20 → 워커·두뇌 Python 3.12 환경(v2 전용 패키지 목록 `requirements-brain.txt`) → MeloTTS Python 3.11 환경 → Whisper large-v3-turbo → MeloTTS 한국어 음성 → Strata를 모두 데이터 폴더 안에 설치하고, 끝나면 다운로드 캐시를 비우고 워커 설정을 설치된 Python으로 바꿈. 마법사 "모델" 단계에서 진행·취소·다시 시도. 이 서버(Linux)에서 빈 폴더부터 전부 설치해 보고 그 런타임으로 서비스를 켜 워커 연결, 받아 적기·음성 준비까지 확인했고, 설치 중 데이터 폴더 밖에는 아무것도 쓰지 않음. 대화 모델(약 23GB)은 앱이 Strata를 직접 띄우는 다음 부분에서 받음. 4단계 뒷부분 완료(2026-11-12): 서비스를 켜면 앱이 먼저 데이터 폴더의 Strata를 띄움(`app/src/strata.rs`, M0와 같은 모델과 평소 배치, 처음 켤 때 대화 모델 약 23GB를 받음, 대시보드에 진행률과 Strata의 마지막 줄, 켜는 중에도 정지 가능, 서비스를 끄면 Strata도 끔). 동시 요청은 1개(모든 메시지에 답하는 채팅 채널이 있으면 2개), 그림 읽기는 v2에서 아직 쓰지 않아 끔. 시작할 때마다 두뇌 설정 `config/brain.json`(Strata 주소, Strata가 알려 준 모델 이름, 데이터 폴더 안의 기억 DB)을 써서 워커에 넘김. 이미 떠 있는 서버를 쓰려면 설정 파일의 `llm.url`. 확인: 가짜 Strata로 진행률·준비·정지·다운로드 중 취소·실패를 단위 시험, 게임PC의 Strata 0.1.59가 앱의 실행 옵션을 그대로 받아들임(`--plan`), 앱 서비스를 `llm.url`로 게임PC Strata에 붙여 실제 디스코드 왕복 10개 모두 소리로 답함. 앱이 Strata를 직접 띄워 모델을 받는 실제 확인은 이 서버에서 할 수 없어(메모리) Windows 빌드 단계에서 게임PC로 함. 5단계 완료(2026-11-12): Tauri 2 창 `app/shell`(`jarvis.exe`, 화면의 명령을 같은 `AdminApi`로 넘김, 창을 닫으면 서비스와 Strata를 끄고 끝날 때까지 기다림, 창의 브라우저 자료는 위치 기억 파일 옆)과 Windows 빌드 `app/shell/package.sh`(이 서버에서 `x86_64-pc-windows-gnu`로 빌드, `Jarvis/` 폴더에 실행 파일·WebView2Loader.dll·Python 소스 `python-src`, zip 11MB). 시험용 Windows VM에서: 창과 마법사, PC 점검, uv·워커 환경 설치, 설치 취소 뒤 남은 프로세스 없음, 봇 토큰 DPAPI 암호화 저장, 시작 실패 이유 표시, 로그 화면·오류 복사·zip, 창 닫기로 종료, %APPDATA%·%LOCALAPPDATA%에 아무것도 안 남김, 앱 핵심 단위 테스트(Windows 빌드) 통과. 게임PC(RTX 5070 Ti, C:\JarvisM0 안에서만)에서 같은 관리 명령으로: 전체 설치 7단계 6분 40초, 앱이 직접 띄운 Strata가 엔진과 대화 모델 22.9GB를 약 6분에 받고 준비, 워커(GPU 받아 적기·음성) 연결, 디스코드 음성 채널 입장, 시험 봇이 말한 질문 5개에 모두 소리로 답함(앱이 잰 전체 중앙값 3.36초, 처음 질문 6.4초, 날씨 11.6초), 정지 8초에 GPU 메모리 반환. 같은 시험에서 찾아 고친 것: Windows는 닫힌 로컬 포트의 연결 거부가 약 2초 늦어 정지 확인이 실패로 나오던 것, Strata가 모델 크기(`X of Y GB`)로만 진행을 알려 진행률이 앞 단계의 80%에 멈춰 있던 것, Strata와 NVIDIA 셰이더 캐시가 %APPDATA%에 쓰던 것(데이터 폴더로). 마무리(2026-11-12): 채팅 채널 이름·주제 반영 `app/src/channel_sync.rs`(채널마다 "디스코드에도 반영", 기본 켜짐; 등록하면 디스코드의 이름·주제로 채움, 저장하면 바뀐 채널만 디스코드에 반영하고 디스코드가 바꾼 이름(공백은 `-`)을 화면에 다시 보여 줌, 주제 1,024자 초과는 저장 전에 거절, 10분에 2번 제한에 걸리면 "잠시 뒤 반영" 후 디스코드가 알려 준 시간 뒤 마지막 저장값으로 저절로 다시 시도, 권한이 없으면 이유를 보여 주고 앱에만 저장). 실제 디스코드 시험 채널에서 채움·반영·제한(587초 대기)·자동 재시도까지 확인 후 채널 삭제. 모델 화면에 TTS 말하기 속도(MeloTTS, 0.5~2.0, 기본 1.5; 한국어 모델은 목소리가 KR 하나뿐이라 목소리 선택은 없음). 창을 닫을 때 설치 중이면 취소하고 끝날 때까지 기다림, 정리를 확인하지 못하면 창을 닫지 않고 이유를 보여 줌(한 번 더 닫으면 종료), 실패한 실행이 남긴 Strata도 정리. 창의 WebView 자료는 데이터 폴더(`cache/webview`), 폴더를 고르기 전에는 임시 폴더에 두었다가 다음 시작 때 지움(`%APPDATA%\JarvisBot`에는 위치 파일 하나만). Windows의 UTF-8 옵션이 꺼진 PC의 CP949 출력도 끝까지 읽음. VM에서 다시 확인: 설치 중 창 닫기 뒤 남은 프로세스 없음, `--location` 없이 실행 시 위치 파일 하나만, Windows용 단위 테스트 168개 통과. 남은 것: 설치 파일(NSIS), Strata가 VRAM을 거의 다 써서(15.8/16.3GB) 받아 적기와 GPU를 나누는 문제(M0의 STT 자리 남기기 배치, M7 성능 단계와 함께) | | M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인 | | M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 |